text
stringlengths
10
2.72M
package com.test.BikeRentalApp.restcontrollers; import com.test.BikeRentalApp.beans.Product; import com.test.BikeRentalApp.repository.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; //@Controller @RestController public class ProductsRestController { @Autowired private ProductRepository productRepository; /* @GetMapping("/BikeRentalApp/rest/products") @ResponseBody public List<Product> getProducts() { //calll product repo List<Product> products = new ArrayList<>(); productRepository.findAll().forEach(product -> products.add(product)); return products; }*/ @GetMapping("/BikeRentalApp/rest/products") public ResponseEntity getProductsByRequestParam(@RequestParam("name") String name){ List<Product> products = productRepository.searchByName(name); return new ResponseEntity<>(products, HttpStatus.OK); } @GetMapping("/BikeRentalApp/rest/products/{name}") public ResponseEntity getProductsByPathVariable(@PathVariable("name") String name){ List<Product> products = productRepository.searchByName(name); return new ResponseEntity<>(products, HttpStatus.OK); } }
package com.tencent.weui.base.preference; import android.content.SharedPreferences; import android.os.Bundle; import android.view.MenuItem; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.tencent.mm.bw.a.f; import com.tencent.mm.ui.BaseActivity; public abstract class WeUIPreference extends BaseActivity { private SharedPreferences duR; private boolean iWf = false; private ListView kww; private boolean oyq = false; protected RelativeLayout tCM; protected TextView tCN; protected ImageView tCO; private b vzz; public abstract int Ys(); protected void onResume() { this.vzz.notifyDataSetChanged(); super.onResume(); } public void onCreate(Bundle bundle) { super.onCreate(bundle); this.duR = getSharedPreferences(getPackageName() + "_preferences", 0); this.vzz = new b(this, this.duR); this.kww = (ListView) findViewById(16908298); this.tCM = (RelativeLayout) findViewById(f.preference_tips_banner_view); this.tCN = (TextView) findViewById(f.preference_tips_banner_tv); this.tCO = (ImageView) findViewById(f.preference_tips_banner_close); b bVar = this.vzz; bVar.vzC = new 1(this); bVar.notifyDataSetChanged(); int Ys = Ys(); if (Ys != -1) { b bVar2 = this.vzz; bVar2.tDb = true; bVar2.vzB.a(Ys, bVar2); bVar2.tDb = false; bVar2.notifyDataSetChanged(); } this.kww.setAdapter(this.vzz); this.kww.setOnItemClickListener(new 2(this)); this.kww.setOnItemLongClickListener(new 3(this)); this.kww.setOnScrollListener(new 4(this)); } public boolean onContextItemSelected(MenuItem menuItem) { return super.onContextItemSelected(menuItem); } }
package com.gft.playground.action; 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.gft.playground.form.HelloWorldForm; public class HelloWorldAction extends BasicAction { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ((HelloWorldForm) form).setMessage("Hello World! Struts"); return mapping.findForward(SUCCESS); } }
package com.jk.jkproject.ui.entity; import java.util.List; public class LiveHomeNearBeanInfo extends BaseInfo { private List<DataBean> data; public List<DataBean> getData() { return this.data; } public void setData(List<DataBean> paramList) { this.data = paramList; } public static class DataBean { private String cover; private String distance; private int live_type; private int peopleNumber; private String r_name; private int r_state; private String roomId; private String u_id; private String u_name; private String r_cover; private String u_picture; public String getR_cover() { return r_cover; } public void setR_cover(String r_cover) { this.r_cover = r_cover; } public String getU_picture() { return u_picture; } public void setU_picture(String u_picture) { this.u_picture = u_picture; } public String getCover() { return this.cover; } public String getDistance() { return this.distance; } public int getLive_type() { return this.live_type; } public int getPeopleNumber() { return this.peopleNumber; } public String getR_name() { return this.r_name; } public int getR_state() { return this.r_state; } public String getRoomId() { return this.roomId; } public String getU_id() { return this.u_id; } public String getU_name() { return this.u_name; } public void setCover(String param1String) { this.cover = param1String; } public void setDistance(String param1String) { this.distance = param1String; } public void setLive_type(int param1Int) { this.live_type = param1Int; } public void setPeopleNumber(int param1Int) { this.peopleNumber = param1Int; } public void setR_name(String param1String) { this.r_name = param1String; } public void setR_state(int param1Int) { this.r_state = param1Int; } public void setRoomId(String param1String) { this.roomId = param1String; } public void setU_id(String param1String) { this.u_id = param1String; } public void setU_name(String param1String) { this.u_name = param1String; } } }
package org.nishkarma.common.paging.model; import javax.xml.bind.annotation.XmlRootElement; import java.util.Collection; @XmlRootElement public class Paginator<T> { private int page; private int pageSize; private long total; private Collection<T> rows; public Paginator() { } public Collection<T> getRows() { return rows; } public void setRows(Collection<T> rows) { this.rows = rows; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } }
package org.christophe.marchal.redis.client.jedis.examples.thread; import java.math.BigDecimal; import org.christophe.marchal.redis.client.jedis.utils.JedisCallback; import org.christophe.marchal.redis.client.jedis.utils.JedisExecutor; import org.christophe.marchal.redis.client.jedis.utils.RedisOperation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; /** * <p>This class compute sum from 1 to N of 1/(n*n) * In theory this sum tend to Pi*Pi/6 * It creates POOL_SIZE threads computing BUCKET_SIZE sum value and store it in redis. * Once everything is computed, it get values from redis and sum them to get </p> * * * * @author Christophe Marchal * @since Apr 9, 2011 */ public class ThreadExample { private static ApplicationContext ac; public static final double N = 10000000; public static final int POOL_SIZE = 150; public static final int BUCKET_SIZE = 100; public static void main(String[] args) throws InterruptedException { ac = new GenericXmlApplicationContext("classpath:META-INF/spring-jedis-failover-beans.xml"); JedisExecutor je = ac.getBean(JedisExecutor.class); Engine engine = ac.getBean(Engine.class); Chronometer chronometer = ac.getBean(Chronometer.class); try{ je.flushAll(); Long start = chronometer.start(); BigDecimal d = engine.compute(); Long time = chronometer.stop(start); System.out.println("Computing Pi thanks to the 2-serie: Sum of 1/(n*n) = Pi * Pi /6 when n tend to infinity"); System.out.println("Computing with " + POOL_SIZE + " threads buckets of " + BUCKET_SIZE); engine.displayResult(d); System.out.println("\n Time spent computing: " + time/1000 + " sec"); }catch (Exception e){ e.printStackTrace(); }finally{ je.close(); } } }
package com.example.demo.controller; import com.example.demo.dao.StudentDao; import com.example.demo.dao.detailrespontory; import com.example.demo.dao.studentrespontory; import com.example.demo.dto.allrequest; import com.example.demo.dto.studetailresponse; import com.example.demo.model.detail; import com.example.demo.model.student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.web.PageableDefault; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping("/student") public class StudentController { @Autowired private detailrespontory detailres; @Autowired private StudentDao dao; @Autowired private studentrespontory studentres; @PostMapping("/register") public String registerstudent(@RequestBody List<student> obj) { dao.saveAll(obj); return "Successfull : " + obj.size(); } @PostMapping("/placeorder") public student placeorder(@RequestBody allrequest obj) { return studentres.save(obj.getStudents()); } @GetMapping("/display") public List<student> getStudents() { return (List<student>) dao.findAll(); } @GetMapping("/displaydetails") public List<detail> getallDetails() { return detailres.findAll(); } @GetMapping("/displayall") public List<student> getalltable() { return studentres.findAll(); } @PutMapping("/update") public String updatestudent(@RequestBody List<student> obj1) { dao.saveAll(obj1); return "Succesfful"+obj1.size(); } @GetMapping("/join") public List<studetailresponse>getjoin() { return studentres.getjoinstudetail(); } @DeleteMapping("/delete/{id}") public String deletestudent(@PathVariable int id) { Optional<student> obj=dao.findById(id); if(obj.isPresent()) { dao.delete(obj.get()); return "student is deleted with id"+id; } else { throw new RuntimeException("student not found or fail"); } } }
/** * */ package alg.code123; /** * 题目:写一个函数返回两个数中的较大者,不能使用if-else及任何比较操作符 * <a href="http://www.code123.cc/949.html" ></a> * @title GetMaxWithoutIf */ public class GetMaxWithoutIf { // 利用减法 public int getMax(int a, int b) { int c = a - b; int k = (c >> 31) & 1; return a - k * c; } }
package com.pg.whatsstatussaver.Fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.pg.whatsstatussaver.R; /** * A simple {@link Fragment} subclass. */ public class Fav_Video_Frgament extends Fragment { public Fav_Video_Frgament() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_fav__video__frgament, container, false); } }
package hr.unipu.java; import java.util.Scanner; // import the Scanner class import java.util.ArrayList; // import the ArrayList class public class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); //stringovi koje korisnik unosi String inputString; int samoglasnici1 = 0; int suglasnici1 = 0; int samoglasnici2 = 0; int suglasnici2 = 0; ArrayList<String> inputStringArray = new ArrayList<>(); ArrayList<String> rezultatniStringovi = new ArrayList<>(); do { // Ovo je poruka korisniku da unese string System.out.println("Unesi string: "); inputString = myObj.nextLine(); inputString = inputString.toLowerCase(); inputStringArray.add(inputString); } while (!inputString.equals("kraj")); for (int i = 0; i < inputStringArray.size(); i++) { for(int j = i + 1; j < inputStringArray.size(); j++) { for(int z = 0; z < inputStringArray.get(j).length(); z++) { char ch = inputStringArray.get(j).charAt(z); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++samoglasnici1; } else if((ch >= 'a'&& ch <= 'z')) { ++suglasnici1; } } for(int k = 0; k < inputStringArray.get(i).length(); k++) { char ch = inputStringArray.get(i).charAt(k); if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++samoglasnici2; } else if((ch >= 'a'&& ch <= 'z')) { ++suglasnici2; } } if((samoglasnici1 == samoglasnici2) && (suglasnici2 == suglasnici1)) { if (!rezultatniStringovi.contains(inputStringArray.get(i))) { rezultatniStringovi.add(inputStringArray.get(i)); } if(!rezultatniStringovi.contains(inputStringArray.get(j))) { rezultatniStringovi.add(inputStringArray.get(j)); } } samoglasnici1 = 0; suglasnici1 = 0; samoglasnici2 = 0; suglasnici2 = 0; } } System.out.println("Stringovi s jednakim brojem samoglasnika i suglasnika: " + rezultatniStringovi); } } // Domaca zadaca 2A // Marijela Milicevic // FIPU - nastavni smjer
package com.ds.weatherapp.control; public interface IWeatherControl { void getWeather(String cityNo); }
package net.minecraft.network.play.server; import com.google.common.collect.Maps; import java.io.IOException; import java.util.Map; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; public class SPacketStatistics implements Packet<INetHandlerPlayClient> { private Map<StatBase, Integer> statisticMap; public SPacketStatistics() {} public SPacketStatistics(Map<StatBase, Integer> statisticMapIn) { this.statisticMap = statisticMapIn; } public void processPacket(INetHandlerPlayClient handler) { handler.handleStatistics(this); } public void readPacketData(PacketBuffer buf) throws IOException { int i = buf.readVarIntFromBuffer(); this.statisticMap = Maps.newHashMap(); for (int j = 0; j < i; j++) { StatBase statbase = StatList.getOneShotStat(buf.readStringFromBuffer(32767)); int k = buf.readVarIntFromBuffer(); if (statbase != null) this.statisticMap.put(statbase, Integer.valueOf(k)); } } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeVarIntToBuffer(this.statisticMap.size()); for (Map.Entry<StatBase, Integer> entry : this.statisticMap.entrySet()) { buf.writeString(((StatBase)entry.getKey()).statId); buf.writeVarIntToBuffer(((Integer)entry.getValue()).intValue()); } } public Map<StatBase, Integer> getStatisticMap() { return this.statisticMap; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketStatistics.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package LeetCode.BloombergPractice; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class LRUCache { class DNode { int key; int val; DNode prev; DNode next; DNode(){} DNode(int key, int val) { this.key = key; this.val = val; } } public void removeNode(DNode node){ DNode nx = node.next; DNode pr = node.prev; pr.next = nx; nx.prev = pr; } // always add node to head public void addNode(DNode node){ node.next = head.next; node.prev = head; head.next.prev = node; head.next = node; } public void moveToHead(DNode node){ removeNode(node); addNode(node); } public DNode popTail(){ DNode pr = tail.prev; removeNode(pr); return pr; } HashMap<Integer, DNode> map = new HashMap<>(); DNode head, tail; int size, capacity; public LRUCache(int capacity) { head = new DNode(); tail = new DNode(); head.next = tail; tail.prev = head; this.capacity = capacity; this.size = 0; } public int get(int key) { DNode node = map.get(key); if(node == null) return -1; moveToHead(node); return node.val; } public void put(int key, int value) { DNode node = map.get(key); if(node == null) { DNode n = new DNode(key, value); map.put(key, n); addNode(n); ++size; if(size > capacity) { DNode del = popTail(); map.remove(del.key); --size; } } else { node.val = value; moveToHead(node); } } }
package frc.robot.subsystems; import frc.robot.Constants; import com.revrobotics.CANSparkMax; import com.revrobotics.CANSparkMax.IdleMode; import com.revrobotics.CANSparkMaxLowLevel.MotorType; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.command.Subsystem; public class Intake extends Subsystem { private final CANSparkMax intakeMotor = new CANSparkMax(Constants.Intake.motor, MotorType.kBrushless); private final DoubleSolenoid intakeSolenoid = new DoubleSolenoid(0, 1); private boolean extended = false; private double speedIn; private double speedOut; public Intake() { super(); intakeMotor.restoreFactoryDefaults(); intakeMotor.setIdleMode(IdleMode.kBrake); intakeMotor.enableVoltageCompensation(11); intakeMotor.setSmartCurrentLimit(20); intakeMotor.burnFlash(); } public void extend(Joystick joystick) { intakeSolenoid.set(Value.kForward); setExtended(true); double speedIn = joystick.getRawAxis(2); double speedOut = joystick.getRawAxis(3); if (speedIn > 0.1) intakeMotor.set(speedIn / 3.5); else if (speedOut > 0.1) intakeMotor.set(-speedOut); else intakeMotor.set(0); } public void retract() { intakeSolenoid.set(Value.kReverse); setExtended(false); } public void runWheels(Joystick joystick) { double speedOut = joystick.getRawAxis(2); double speedIn = joystick.getRawAxis(3); if (getExtended()) { if (speedIn > 0.1) intakeMotor.set(speedIn / 3.5); else if (speedOut > 0.1) intakeMotor.set(-speedOut); else intakeMotor.set(0); } } //auto intakes public void runWheelsAuto() { intakeMotor.set(.5); } public void extendAuto() { intakeSolenoid.set(Value.kForward); setExtended(true); intakeMotor.set(.5); } public boolean getExtended() { return extended; } public void setExtended(boolean extended) { this.extended = extended; } @Override protected void initDefaultCommand() { // TODO Auto-generated method stub } }
package programmers.lv1; public class Day_Test { //이런식으로 swith문 이용해서 풀었는데 나도 하면서 좀 지저분한 느낌을 받았다.. public String solution(int a, int b) { String answer = ""; int sum = 0; for (int i = 1; i < a; i++) { switch (i) { case 2: sum += 29; break; case 4: case 6: case 9: case 11: sum += 30; break; default: sum += 31; break; } } sum += b - 1; switch (sum % 7) { case 1: answer = "SAT"; break; case 2: answer = "SUN"; break; case 3: answer = "MON"; break; case 4: answer = "TUE"; break; case 5: answer = "WED"; break; case 6: answer = "THU"; break; default: answer = "FRI"; break; } return answer; } //그래서 다른 사람걸 보니까 이런식으로 배열로 깔끔하게 정리해놓았다 //코드가 길어지면 배열로 정리하는 생각.. 해야겠다 public String anotherSolution(int a, int b) { String answer = ""; int[] c = {31,29,31,30,31,30,31,31,30,31,30,31}; String[] MM ={"FRI","SAT","SUN","MON","TUE","WED","THU"}; int Adate = 0; for(int i = 0 ; i< a-1; i++){ Adate += c[i]; } Adate += b-1; answer = MM[Adate %7]; return answer; } }
package at.fhj.swd.selenium.pageobjects; import org.openqa.selenium.WebDriver; public class TopicPage extends PageObjectBase{ public TopicPage(WebDriver driver) { super(driver); } }
package test; import szallitas.*; public class Test2 extends Test { @Override public boolean test() { //Doboz tesztje Doboz d1 = new Doboz(100); Doboz d2 = new Doboz(150); if (d1.getErtek() != 100) hiba("A Doboz getErtek metodusa hibas"); d2.setErtek(200); if (d2.getErtek() != 200) hiba("A Doboz getErtek v. setErtek metodusa hibas"); if (d1.getRaktar() != 1) hiba("A Doboz getRaktar metodusa hibas"); if (d2.getRaktar() != 1) hiba("A Doboz getRaktar metodusa hibas"); if (! d1.toString().equals("[100,1]")) hiba("A Doboz(1) toString metodusa hibas"); if (! d2.toString().equals("[200,1]")) hiba("A Doboz(2) toString metodusa hibas"); //IranyitottDoboz tesztje IranyitottDoboz d3 = new IranyitottDoboz(300,(byte) 3); Doboz d4 = new IranyitottDoboz(400,(byte) 4); if (d3.getErtek() != (360)) hiba("Az IranyitottDoboz getErtek metodusa hibas"); if (d4.getErtek() != (480)) hiba("Az IranyitottDoboz getErtek metodusa hibas"); if (d3.getRaktar() != 3) hiba("Az IranyitottDoboz getRaktar metodusa hibas"); if (d4.getRaktar() != 4) hiba("Az IranyitottDoboz getRaktar metodusa hibas"); if (! d3.toString().equals("[360,3]")) hiba("Az IranyitottDoboz toString metodusa hibas"); if (! d4.toString().equals("[480,4]")) hiba("Az IranyitottDoboz toString metodusa hibas"); //Gyar tesztje if (Gyar.kozpontiRaktar != 1) hiba("A Gyar kozpontiRaktar nevu osztályszintu valtozojanak nem megfelelo a kezdoerteke"); Gyar gy = new Gyar(); gy.legyart(d1); gy.legyart(d2); gy.legyart(d3); gy.legyart(d4); if (gy.dobozokSzama() != 4) hiba("Nem megfelelo szamu doboz van a futoszalagon 4 doboz legyartasa utan a Gyarban."); return ok; } }
package com.taikang.healthcare.cust.service; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.taikang.healthcare.cust.PrincipalService; import com.taikang.healthcare.cust.dao.PrincipalMapper; import com.taikang.healthcare.cust.model.Principal; import com.taikang.healthcare.sdk.BeanUtil; /** * 〈功能简述〉 * @author zhanghb22 * @version [版本号,默认V1.0.0] * @Credited 2016年3月3日 下午1:03:40 * @see [相关类/方法] * @since [产品/模块版本] */ @Service("principalService") public class PrincipalServiceImpl implements PrincipalService{ @Resource private PrincipalMapper principalMapper; @Override public Map<String,Object> bind(Map<String,Object> principal) { try{ principalMapper.insert(principal); return principal; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<Map<String,Object>> search(Map<String,Object> map) { try { List<Map<String,Object>> resultMapList =new ArrayList<Map<String,Object>>(); List<Principal> principals=new ArrayList<Principal>(); principals=principalMapper.selectByuserId(map); for(Principal principal:principals){ resultMapList.add(BeanUtil.beanToMap(principal)); } return resultMapList; } catch (Exception e) { e.printStackTrace(); return null; } } @Override public List<Map<String,Object>> getCustomerId(long user_id) { List<Map<String,Object>> resultMapList =new ArrayList<Map<String,Object>>(); List<Principal> principals=new ArrayList<Principal>(); principals= principalMapper.selectCustomerIdByUserId(user_id); for(Principal principal:principals){ resultMapList.add(BeanUtil.beanToMap(principal)); } return resultMapList; } @Override public int unbind(long id) { try{ int result= principalMapper.deleteByPrimaryKey(id); return result; } catch (Exception e) { e.printStackTrace(); return 0; } } }
/** * <p> * This package contains the interface * {@link org.opentosca.planengine.service.IPlanEngineService}. * </p> * * <p> * The interface provides the only access point of openTOSCA to PlanEngine * functions. * </p> */ package org.opentosca.planengine.service;
package com.test.admin.dao; import com.fight.job.admin.config.ApplicationInitializer; import com.fight.job.admin.config.SpringConfig; import com.fight.job.admin.config.SpringWebConfig; import com.fight.job.admin.dao.ExecutorInfoDao; import com.fight.job.core.enums.ExecutorStateEnum; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.AnnotationConfigWebContextLoader; import org.springframework.test.context.web.WebAppConfiguration; /** * ExecutorInfo表测试类 * @author luo */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = {ApplicationInitializer.class, SpringConfig.class, SpringWebConfig.class}, loader=AnnotationConfigWebContextLoader.class) public class ExecutorInfoTest { @Autowired private ExecutorInfoDao executorDao; @Test public void testExecutor() { System.out.println(executorDao.selectAll()); System.out.println(executorDao.selectByGroupId("executor-group")); System.out.println(executorDao.selectByGroupIdState("executor-group", ExecutorStateEnum.OFFLINE.name())); // ExecutorInfoEntity executorEntity = new ExecutorInfoEntity("1232", 8080, "executor-group"); // executorEntity.setName("appname"); // System.out.println(executorDao.insert(executorEntity)); executorDao.updateExecutorState("1232", 8080, "executor-group", ExecutorStateEnum.ONLINE.name()); } }
package com.tencent.mm.plugin.account.a.a; import android.app.Activity; import android.content.Context; import com.tencent.mm.kernel.b.d; import com.tencent.mm.sdk.e.j; import com.tencent.mm.sdk.e.m; import java.util.LinkedList; public interface a extends d { void clearFriendData(); m getAddrUploadStg(); j getFacebookFrdStg(); j getFrdExtStg(); LinkedList getFriendData(); j getGoogleFriendStorage(); j getInviteFriendOpenStg(); String getPhoneNum(Context context, String str); j getQQGroupStg(); m getQQListStg(); void removeSelfAccount(Context context); void setFriendData(LinkedList linkedList); void showAddrBookUploadConfirm(Activity activity, Runnable runnable, boolean z, int i); boolean syncAddrBook(b bVar); void syncAddrBookAndUpload(); void syncUploadMContactStatus(boolean z, boolean z2); void updateAllContact(); }
/* * Copyright © 2014 YAOCHEN Corporation, All Rights Reserved. */ package com.yaochen.address.data.mapper.address; import java.util.List; import com.easyooo.framework.sharding.annotation.Table; import com.yaochen.address.data.domain.address.AdOaCountyRef; import com.yaochen.address.support.Repository; @Repository @Table("AD_OA_COUNTY_REF") public interface AdOaCountyRefMapper { int deleteByPrimaryKey(Integer companyId); int insert(AdOaCountyRef record); int insertSelective(AdOaCountyRef record); AdOaCountyRef selectByPrimaryKey(String companyId); int updateByPrimaryKeySelective(AdOaCountyRef record); int updateByPrimaryKey(AdOaCountyRef record); List<AdOaCountyRef> selectAll(); }
// Tests that references from a superclass to a subclass succeed (includes field accesses and method calls). int main() { ImplicitCastsClass2 a; a = new ImplicitCastsClass2(); a.f(); a.y.f(); a.y = a; a.y.y = a; return 0; } class ImplicitCastsClass1 { ImplicitCastsClass2 y; int f() { return 0; } } class ImplicitCastsClass2 extends ImplicitCastsClass1 { }
package RestAssuredStore; import io.restassured.builder.ResponseSpecBuilder; import io.restassured.filter.log.LogDetail; import io.restassured.specification.ResponseSpecification; public class LogResponseBodyResponseSpecBuilder { public static ResponseSpecification build() { return new ResponseSpecBuilder(). log(LogDetail.BODY). build(); } }
package LeetCode.LinkedList; import java.util.Deque; import java.util.LinkedList; class BNode { String val; BNode next; BNode prev; BNode(String val){ this.val = val; } } public class BrowserHistory { BNode cur; BNode head; public BrowserHistory(String homepage){ head = new BNode(homepage); cur = head; } public void visit(String url){ BNode temp = cur != null ? cur.next : null; if(temp != null) temp.prev = null; BNode newNode = new BNode(url); newNode.prev = cur; cur.next = newNode; cur = newNode; } public String back(int steps){ int count = 0; while (cur.prev != null && count < steps){ cur = cur.prev; count++; } return cur.val; } public String forward(int steps){ int count = 0; while (cur.next != null && count < steps){ cur = cur.next; count++; } return cur.val; } public static void main(String[] args){ BrowserHistory browserHistory = new BrowserHistory("leetcode.com"); browserHistory.visit("google.com"); browserHistory.visit("facebook.com"); browserHistory.visit("youtube.com"); System.out.println(browserHistory.back(1)); System.out.println(browserHistory.back(1)); System.out.println(browserHistory.forward(1)); browserHistory.visit("linkedin.com"); System.out.println(browserHistory.forward(2)); System.out.println(browserHistory.back(2)); System.out.println(browserHistory.back(7)); } }
package lesson29.Ex1; public class Fish extends Animal { private String color; private String food; public Fish() { } public Fish(String color, String food) { this.color = color; this.food = food; } public Fish(String name, String species, float height, float weight) { super(name, species, height, weight); } public final String getColor() { return color; } public final void setColor(String color) { this.color = color; } public final String getFood() { return food; } public final void setFood(String food) { this.food = food; } @Override public void eat(String food) { System.out.println("Cá ăn " + food); } @Override void sleep() { System.out.println("Cá ngủ bằng cách bơi đứng im"); } @Override void move() { System.out.println("Cá di chuyển ở dưới nước"); } @Override void relax() { System.out.println("Mấy con cá nhỏ đuổi nhau"); } }
import java.lang.reflect.Array; import java.util.*; public class ListOfWords { private String[] words = {"Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота","Воскресенье", "Среда", "Вторник", "Среда", "Пятница", "Воскресенье", "Среда", "Пятница", "Понедельник"}; public Set<String> createUniqueArray() { Set<String> uniqueWords = new HashSet<String>(Arrays.asList(words)); return uniqueWords; } public void countWords() { Set<String> uniqueWords = createUniqueArray(); List<String> tempWords = new ArrayList<>(Arrays.asList(words)); int counter = 0; for (String uniqueWord : uniqueWords) { for (int i = 0; i < tempWords.size(); i++) { if (uniqueWord.equals(tempWords.get(i))) { counter++; } } System.out.println(uniqueWord + ": " + counter); counter = 0; } } }
/**** Copyright (c) 2015, Skyley Networks, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Skyley Networks, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Skyley Networks, Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****/ package com.skyley.skstack_ip.api.skevents; import com.skyley.skstack_ip.api.skenums.SKDeviceModel; /** * EPANDESCイベントに対応したクラス、SKEventを実装 * @author Skyley Networks, Inc. * @version 0.1 */ public class SKEPanDesc implements SKEvent { /** 受信文字列のパーサー */ private SKEPanDescParser parser; /** 受信文字列("EPANDESC"に続く行を","で結合)*/ private String raw; /** 発見したPANの論理チャンネル番号 */ private byte channel; /** 発見したPANのチャンネルページ */ private byte channelPage; /** 発見したPANのPAN ID */ private int panID; /** アクティブスキャン応答元のアドレス(16進表現) */ private String address; /** 受信したビーコンの受信RSSI */ private short lqi; /** Side */ private String side; /** 相手から受信したParing ID */ private String pairID; /** HEMS 64bitアドレス(16進表現) */ private String hemsAddress; /** リレーデバイスモード */ private boolean isRelayDevice; /** リレーデバイスエンドポイント */ private boolean isRelayEndPoint; /** * コンストラクタ * @param raw 受信文字列("EPANDESC"に続く行を","で結合) * @param model デバイス機種 */ public SKEPanDesc(String raw, SKDeviceModel model) { this.raw = raw; switch (model) { case GENERAL: parser = new SKEPanDescGeneralParser(); break; case HAN_EXTENSION: parser = new SKEPanDescHanParser(); break; default: parser = new SKEPanDescGeneralParser(); break; } } /** * 受信文字列("EPANDESC"に続く行を","で結合)を取得 * @return 受信文字列("EPANDESC"に続く行を","で結合) */ public String getRaw() { return raw; } /** * チャンネル番号を取得 * @return チャンネル番号 */ public byte getChannel() { return channel; } /** * チャンネル番号をセット * @param channel チャンネル番号 */ public void setChannel(byte channel) { this.channel = channel; } /** * チャンネルページを取得 * @return チャンネルページ */ public byte getChannelPage() { return channelPage; } /** * チャンネルページをセット * @param channelPage チャンネルページ */ public void setChannelPage(byte channelPage) { this.channelPage = channelPage; } /** * PAN IDを取得 * @return PAN ID */ public int getPanID() { return panID; } /** * PAN IDをセット * @param panID PAN ID */ public void setPanID(int panID) { this.panID = panID; } /** * 応答元アドレスを取得 * @return 応答元アドレス(16進表現) */ public String getAddress() { return address; } /** * 応答元アドレスをセット * @param address 応答元アドレス */ public void setAddress(String address) { this.address = address; } /** * ビーコン受信RSSIを取得 * @return ビーコン受信RSSI */ public short getLQI() { return lqi; } /** * ビーコン受信RSSIをセット * @param lqi ビーコン受信RSSI */ public void setLQI(short lqi) { this.lqi = lqi; } public String getSide() { return side; } public void setSide(String side) { this.side = side; } /** * Paring IDを取得 * @return Paring ID */ public String getPairID() { return pairID; } /** * Paring IDをセット * @param pairID Paring ID */ public void setPairID(String pairID) { this.pairID = pairID; } /** * HEMS 64bitアドレスを取得 * @return HEMS 64bitアドレス */ public String getHemsAddress() { return hemsAddress; } /** * HEMS 64bitアドレスをセット * @param address HEMS 64bitアドレス */ public void setHemsAddress(String address) { hemsAddress = address; } /** * リレーデバイスモードを取得 * @return リレーデバイスモード */ public boolean isRelayDevice() { return isRelayDevice; } /** * リレーデバイスモードをセット * @param flag リレーデバイスモード */ public void setRelayDevice(boolean flag) { isRelayDevice = flag; } /** * リレーデバイスエンドポイントを取得 * @return リレーデバイスエンドポイント */ public boolean isRelayEndPoint() { return isRelayEndPoint; } /** * リレーデバイスエンドポイントをセット * @param flag リレーデバイスエンドポイント */ public void setRelayEndPoint(boolean flag) { isRelayEndPoint = flag; } /** * 受信文字列を解析、パラメータを格納 */ @Override public boolean parse(String raw) { // TODO 自動生成されたメソッド・スタブ return parser.parsePanDesc(this); } } 
package gov.smart.health.activity.find.model; import com.google.gson.annotations.SerializedName; import java.io.Serializable; /** * Created by laoniu on 11/5/17. */ public class FindEssayListDataModel implements Serializable { @SerializedName("memo") public String memo; @SerializedName("def1") public String def1; @SerializedName("def2") public String def2; @SerializedName("def3") public String def3; @SerializedName("def4") public String def4; @SerializedName("def5") public String def5; @SerializedName("be_std") public String be_std; @SerializedName("ts") public String ts; @SerializedName("dr") public String dr; @SerializedName("start") public String start; @SerializedName("length") public String length; @SerializedName("orderColumnName") public String orderColumnName; @SerializedName("orderDir") public String orderDir; @SerializedName("pk_essay") public String pk_essay; @SerializedName("essay_code") public String essay_code; @SerializedName("essay_name") public String essay_name; @SerializedName("essay_subname") public String essay_subname; @SerializedName("essay_content") public String essay_content; @SerializedName("is_publish") public String is_publish; @SerializedName("ts_start") public String ts_start; @SerializedName("ts_end") public String ts_end; @SerializedName("pk_person") public String pk_person; @SerializedName("person_name") public String person_name; @SerializedName("path_thumbnail") public String path_thumbnail; @SerializedName("pkvalue") public String pkvalue; @SerializedName("tableName") public String tableName; @SerializedName("pkfield") public String pkfield; }
package org.jboss.wise.demo; import static org.junit.Assert.assertEquals; import org.jboss.wise.core.client.InvocationResult; import org.jboss.wise.core.client.WSDynamicClient; import org.jboss.wise.core.client.WSMethod; import org.jboss.wise.core.mapper.SmooksMapper; import org.junit.Test; import demo.Cliente; import demo.ElementoOrdine; import demo.Ordine; import demo.StatoOrdine; public class WiseProjectB2Test extends AbstractTest { @Test public void testUsingSmooks() throws Exception { System.out.println("Creating client..."); WSDynamicClient client = getClient(WSDL_ADDRESS); WSMethod method = client.getWSMethod("OrderMgmtService", "OrderMgmtBeanPort", "prepareOrder"); System.out.println("\nPreparing parameters..."); Ordine ordine = new Ordine(); Cliente cliente = new Cliente(); cliente.setNome("Mario"); cliente.setCognome("Rossi"); cliente.setDettagliCartaCredito("1234-4567-890-333"); ordine.setCliente(cliente); ordine.setNumeroOrdine(1234); ElementoOrdine[] elems = new ElementoOrdine[1]; elems[0] = new ElementoOrdine(); elems[0].setNome("first-order"); elems[0].setPrezzo(10.45); ordine.setElementiOrdine(elems); System.out.println("Invoking..."); InvocationResult invRes = method.invoke(ordine, new SmooksMapper("smooks-request.xml", client)); StatoOrdine statoOrdine = (StatoOrdine)invRes.getMappedResult(new SmooksMapper("smooks-response.xml", client)).get("StatoOrdine"); System.out.println("\nInvocation result:"); System.out.println("order number : " + statoOrdine.getNumeroOrdine()); System.out.println("order status : " + statoOrdine.getStato()); System.out.println("order discount : " + statoOrdine.getSconto()); assertEquals(1234, statoOrdine.getNumeroOrdine()); assertEquals("Prepared", statoOrdine.getStato()); } }
package planning.actor.strategy; import domain.Estimation; import domain.Story; public class LazyEstimationStrategy implements EstimationStrategy<Story> { @Override public Estimation estimate(Story story) { return Estimation.XL; } }
package uk.ac.ed.inf.aqmaps.unitTests.simulation.collection; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anySet; import static org.mockito.ArgumentMatchers.booleanThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; import uk.ac.ed.inf.aqmaps.simulation.Sensor; import uk.ac.ed.inf.aqmaps.simulation.collection.Drone; import uk.ac.ed.inf.aqmaps.simulation.planning.ConstrainedTreeGraph; import uk.ac.ed.inf.aqmaps.simulation.planning.collectionOrder.BaseCollectionOrderPlanner; import uk.ac.ed.inf.aqmaps.simulation.planning.path.PathPlanner; import uk.ac.ed.inf.aqmaps.simulation.planning.path.PathSegment; // import uk.ac.ed.inf.aqmaps.client.Sensor; // import uk.ac.ed.inf.aqmaps.client.W3WAddress; @SuppressWarnings({"unchecked"}) public class DroneTest { PathPlanner mockPathPlanner = mock(PathPlanner.class); BaseCollectionOrderPlanner collectionOrderPlanner = mock(BaseCollectionOrderPlanner.class); Drone testUnit = new Drone(mockPathPlanner,collectionOrderPlanner); ConstrainedTreeGraph mockGraph = mock(ConstrainedTreeGraph.class); Sensor mockSensor1 = mock(Sensor.class); Sensor mockSensor2 = mock(Sensor.class); Sensor mockSensor3 = mock(Sensor.class); Deque<Sensor> sensorList = new LinkedList<Sensor>(Arrays.asList( mockSensor1,mockSensor2,mockSensor3 )); @BeforeEach public void reset(){ when(mockSensor1.getCoordinates()).thenReturn(new Coordinate()); when(mockSensor2.getCoordinates()).thenReturn(new Coordinate()); when(mockSensor3.getCoordinates()).thenReturn(new Coordinate()); when(collectionOrderPlanner.planRoute(any(Sensor.class), (Set<Sensor>)any(Set.class), anyBoolean())).thenReturn(sensorList); when(mockPathPlanner.planPath(any(Coordinate.class),(Deque<Sensor>)any(Deque.class), any(ConstrainedTreeGraph.class), anyBoolean())) .thenReturn(new LinkedList<PathSegment>(Arrays.asList( new PathSegment(new Coordinate(), 0, new Coordinate(), mockSensor1), new PathSegment(new Coordinate(), 0, new Coordinate(), null), new PathSegment(new Coordinate(), 0, new Coordinate(), mockSensor3) ))); } @Test public void planCollectionTest(){ var collection = testUnit.planCollection( new Coordinate(0,0), new HashSet<Sensor>(Arrays.asList(mockSensor1,mockSensor2,mockSensor3)), mockGraph, false, 0); verify(mockSensor1,times(1)).setHaveBeenRead(true); verify(mockSensor2,times(0)).setHaveBeenRead(true); verify(mockSensor3,times(1)).setHaveBeenRead(true); // should only affect the parameters of the flight and route planners // not the path itself assertEquals(3,collection.size()); verify(collectionOrderPlanner,times(1)).planRoute(any(Sensor.class), anySet(), booleanThat((b)->b == false)); verify(mockPathPlanner,times(1)).planPath(any(Coordinate.class),(Deque<Sensor>)any(Deque.class), any(ConstrainedTreeGraph.class), booleanThat((b)->b == false)); } @Test public void planCollectionLoopTest(){ var collection = testUnit.planCollection( new Coordinate(0,0), new HashSet<Sensor>(Arrays.asList(mockSensor1,mockSensor2,mockSensor3)), mockGraph, true, 0); verify(mockSensor1,times(1)).setHaveBeenRead(true); verify(mockSensor2,times(0)).setHaveBeenRead(true); verify(mockSensor3,times(1)).setHaveBeenRead(true); // should only affect the parameters of the flight and route planners // not the path itself assertEquals(3,collection.size()); verify(collectionOrderPlanner,times(1)).planRoute(any(Sensor.class), anySet(), booleanThat((b)->b == true)); verify(mockPathPlanner,times(1)).planPath(any(Coordinate.class),(Deque<Sensor>)any(Deque.class), any(ConstrainedTreeGraph.class), booleanThat((b)->b == true)); } }
package com.hly.o2o.service; import java.util.List; import com.hly.o2o.dto.ProductCategoryExecution; import com.hly.o2o.entity.ProductCategory; import com.hly.o2o.exceptions.ProductCategoryOperationException; public interface ProductCategoryService { /** * 通过shopId查找该店铺的所有商品类别 * * @param shopId * @return */ List<ProductCategory> getProductCategoryList(long shopId); /** * 批量插入商品类别 * @param productCategoryList * @return * @throws ProductCategoryOperationException */ ProductCategoryExecution batchAddProductCategory(List<ProductCategory> productCategoryList) throws ProductCategoryOperationException; /** * * 将该类别下的商品ID置为空,在删除该商品类别 * @param productCategoryId * @param shopId * @return * @throws ProductCategoryOperationException */ ProductCategoryExecution deleteProductCategory(long productCategoryId,long shopId) throws ProductCategoryOperationException; }
package com.uinsk.mobileppkapps.ui.mahasiswa.presensi; import androidx.lifecycle.ViewModel; public class PresensiMahasiswaViewModel extends ViewModel { // TODO: Implement the ViewModel }
/** * Copyright by www.codejava.net */ package net.codejava; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener public class UserSessionListener implements HttpSessionListener { static final String ONLINE_USERS = "OnlineUsers"; @Override public void sessionCreated(HttpSessionEvent se) { ServletContext context = se.getSession().getServletContext(); Integer onlineUsersCount = 0; Object attributeValue = context.getAttribute(ONLINE_USERS); if (attributeValue != null) { onlineUsersCount = (Integer) attributeValue; } context.setAttribute(ONLINE_USERS, ++onlineUsersCount); } @Override public void sessionDestroyed(HttpSessionEvent se) { ServletContext context = se.getSession().getServletContext(); Integer onlineUsersCount = (Integer) context.getAttribute(ONLINE_USERS); context.setAttribute(ONLINE_USERS, --onlineUsersCount); } }
/* * (c) tolina GmbH, 2014 */ package samples.guava; import jp.co.worksap.oss.findbugs.guava.UnexpectedAccessDetector; import junit.framework.TestCase; import org.junit.Ignore; /** * Class used only for {@link UnexpectedAccessDetector}-tests * @author Juan Martin Sotuyo Dodero * */ @Ignore("Not a real test, but used as test sample") public class JUnit3Test extends TestCase { void testCallVisibleForTestingMethod() { new MethodWithVisibleForTesting().method(); } }
import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; import jcuda.*; import jcuda.runtime.*; import jcuda.driver.*; import static jcuda.driver.JCudaDriver.*; public class GPLevenshtein { public static void main(String [] args) { if(args.length < 2) { System.err.println("Needs two arguments: <file a> <file b>"); System.exit(0); } String filea = args[0]; String fileb = args[1]; char[] a = null; char[] b = null; try { FileReader fra = new FileReader(filea); BufferedReader bra = new BufferedReader(fra); a = bra.readLine().toCharArray(); FileReader frb = new FileReader(fileb); BufferedReader brb = new BufferedReader(frb); b = brb.readLine().toCharArray(); } catch (IOException e) { e.printStackTrace(); System.exit(0); } // Initialize the costs array int[] costs = new int[a.length+1]; // Enable exception JCudaDriver.setExceptionsEnabled(true); // Initialize the driver and create a context for the first device cuInit(0); CUdevice device = new CUdevice(); cuDeviceGet(device, 0); CUcontext context = new CUcontext(); cuCtxCreate(context, 0, device); // Load the CUDA kernel ptx file CUmodule module = new CUmodule(); cuModuleLoad(module, "../JCudaLevenstein.ptx"); // Obtain a function pointer to the kernel function CUfunction function = new CUfunction(); cuModuleGetFunction(function, module, "leven"); // Allocate the device input data, and copy the host input data // to the device int ptrSize = a.length * Sizeof.CHAR; CUdeviceptr deviceInputA = new CUdeviceptr(); cuMemAlloc(deviceInputA, ptrSize); cuMemcpyHtoD(deviceInputA, Pointer.to(a), ptrSize); CUdeviceptr deviceInputB = new CUdeviceptr(); cuMemAlloc(deviceInputB, ptrSize); cuMemcpyHtoD(deviceInputB, Pointer.to(b), ptrSize); CUdeviceptr deviceInputCosts = new CUdeviceptr(); cuMemAlloc(deviceInputCosts, a.length * Sizeof.INT + 1); cuMemcpyHtoD(deviceInputCosts, Pointer.to(costs), a.length * Sizeof.INT + 1); // Set up the kernel parameters: A pointer to an array // of pointers which points to the actual values Pointer kernelParameters = Pointer.to( Pointer.to(deviceInputA), Pointer.to(deviceInputB), Pointer.to(deviceInputCosts), Pointer.to(new int[]{a.length}) ); // Kernel call parameters int blockSizeX = 256; int gridSizeX = (int)Math.ceil((double)a.length / blockSizeX); // -------------------------------- long startTime = System.currentTimeMillis(); // --- Start of benchmark zone ---> for(int i = 0; i < costs.length; i++) costs[i] = i; cuLaunchKernel(function, gridSizeX, 1, 1, // Grid dimension blockSizeX, 1, 1, // Block dimension 0, null, // Shared memory size and stream kernelParameters, null // Kernel and extra parameters ); cuCtxSynchronize(); // <--- End of benchmark zone ----- long stopTime = System.currentTimeMillis(); // -------------------------------- // Benchmark time elapsed computation long elapsedTime = stopTime - startTime; // Output System.out.println(elapsedTime/1000); // System.out.println("distance: " + dist); } // Compute the distance between a and b public static int distance(String a, String b) { int [] costs = new int [b.length() + 1]; for (int j = 0; j < costs.length; j++) costs[j] = j; for (int i = 1; i <= a.length(); i++) { costs[0] = i; computeRow(costs, i, a, b); } return costs[b.length()]; } // Compute a single row in the distance process public static void computeRow(int[] costs, int i, String a, String b) { int nw = i - 1; for (int j = 1; j <= b.length(); j++) { int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1); nw = costs[j]; costs[j] = cj; } } }
package com.tencent.mm.plugin.report; import java.util.HashMap; import java.util.Map.Entry; public final class b { private long mDv; private HashMap<Integer, Long> mDw = new HashMap(); private int mID = 463; private long mInterval = 300000; public final void g(int i, int i2, long j) { synchronized (this) { E(i, j); E(i2, 1); long currentTimeMillis = System.currentTimeMillis(); if (currentTimeMillis - this.mDv > this.mInterval) { for (Entry entry : this.mDw.entrySet()) { f.mDy.a((long) this.mID, (long) ((Integer) entry.getKey()).intValue(), ((Long) entry.getValue()).longValue(), false); } this.mDv = currentTimeMillis; } } } private void E(int i, long j) { Long l = (Long) this.mDw.get(Integer.valueOf(i)); if (l != null) { j += l.longValue(); } this.mDw.put(Integer.valueOf(i), Long.valueOf(j)); } }
package Raghu1; public class dec11 { public static void main(String[] args) { int rag[]=new int [4]; rag[0]=10; rag[1]=20; rag[2]=30; rag[3]=45; System.out.println(rag[3]); System.out.println(rag.length); for(int i=0;i<rag.length;i++) { System.out.println(rag[i]); } System.out.println("<-------->"); } }
package com.test.embedded.one2many; import java.util.List; import com.gigaspaces.annotation.pojo.SpaceId; import com.gigaspaces.annotation.pojo.SpaceIndex; import com.gigaspaces.annotation.pojo.SpaceIndexes; public class Author { Integer id; String lastName; List<Book> books; @SpaceId public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @SpaceIndex public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return "Author [id=" + id + ", lastName=" + lastName + "]"; } @SpaceIndex(path = "[*].title") public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } }
package VRPTW; import Model.Graph; import org.uma.jmetal.problem.impl.AbstractIntegerProblem; import org.uma.jmetal.solution.IntegerSolution; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class VRPTW extends AbstractIntegerProblem { private Graph graph; private List<Double> customerDemands; private int dispatchListLength; private int depotDispatchListLength; private int numOfVehicles; private int maxSteps; private double capacity; private FileWriter fw; private List<Double> readyTimes; private List<Double> dueTimes; private List<Double> serviceTimes; private long startTime; public int getDispatchListLength() { return dispatchListLength; } public int getDepotDispatchListLength() { return depotDispatchListLength; } public int getNumOfVehicles() { return numOfVehicles; } public double getCapacity() { return capacity; } public VRPTW(Graph graph, List<Double> customerDemands, int dispatchListLength, int depotDispatchListLength, int numOfVehicles, double capacity, FileWriter fw, List<Double> readyTimes, List<Double> dueTimes, List<Double> serviceTimes, int maxSteps){ this.graph = graph; this.customerDemands = customerDemands; this.dispatchListLength = dispatchListLength; this.depotDispatchListLength = depotDispatchListLength; this.numOfVehicles = numOfVehicles; this.capacity = capacity; this.readyTimes = readyTimes; this.dueTimes = dueTimes; this.serviceTimes = serviceTimes; this.maxSteps = maxSteps; this.setNumberOfVariables(this.depotDispatchListLength + (this.graph.getVertexNum()-1)*this.dispatchListLength); this.setNumberOfObjectives(1); this.setName("VRPSD"); List<Integer> lowerLimit = new ArrayList<>(getNumberOfVariables()) ; List<Integer> upperLimit = new ArrayList<>(getNumberOfVariables()) ; for (int i = 0; i < getNumberOfVariables(); i++) { lowerLimit.add(1); upperLimit.add(this.graph.getVertexNum()-1); } setLowerLimit(lowerLimit); setUpperLimit(upperLimit); this.fw = fw; startTime = System.nanoTime(); } @Override public void evaluate(IntegerSolution integerSolution) { int fitness = 0; VRPTWLuckyStarEvaluator evaluator = new VRPTWLuckyStarEvaluator(); //VRPTWEvaluator evaluator = new VRPTWEvaluator(); fitness = evaluator.evaluate(this, integerSolution, graph, customerDemands); try { fw.write((System.nanoTime() - startTime) + " " + fitness + "\n"); } catch (IOException e) { e.printStackTrace(); } integerSolution.setObjective(0, fitness); } public List<Double> getReadyTimes() { return readyTimes; } public List<Double> getDueTimes() { return dueTimes; } public List<Double> getServiceTimes() { return serviceTimes; } public int getMaxSteps() { return maxSteps; } }
package detail; import worker.Worker; import worker.Workerinterface; public class Teacher extends Worker implements Workerinterface{ public float calcSalary(){ return this.getSalaryIndex() * 730 + this.getAllowance() + this.getWorkingCount() *45; } }
package at.fhj.swd.presentation.viewHelper; import java.io.IOException; import java.io.Serializable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.inject.Inject; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.DefaultStreamedContent; import at.fhj.swd.data.entity.Document; import at.fhj.swd.data.entity.User; import at.fhj.swd.presentation.helper.CookieHelper; import at.fhj.swd.service.DocumentService; /** * Document-ViewHelper. * * @author Group1 * */ @ManagedBean(name="dtDocumentView") @ViewScoped public class DocumentView implements Serializable { private static final long serialVersionUID = 6219023243007670413L; @Inject protected transient Logger logger; protected String selectedDocument; private String selectedUserDocument; @EJB(beanName="DocumentServiceImpl") protected transient DocumentService service; @PostConstruct public void init() { logger.log(Level.INFO, "Initiliazing " + this.getClass().getName() + " in @PostConstruct!"); } // Global ------------------------ public List<Document> getDocuments() { logger.log(Level.INFO, "Retrieving Document List."); return this.service.getGlobalDocuments(); } public void handleFileUpload(FileUploadEvent event) throws IOException { logger.log(Level.INFO, "Uploading Global-Doc " + event.getFile().getFileName() + " into Documents."); this.service.uploadGlobalDocument(event.getFile().getInputstream(), event.getFile().getFileName()); } public void setSelectedDocument(String name) { this.selectedDocument = name; } public String getSelectedDocument() { return this.selectedDocument; } public void setDeleteDocument(String name) { logger.log(Level.INFO, "Deleting Global-Doc " + name + " from Documents."); this.service.deleteGlobalDocument(name); } public DefaultStreamedContent getDownload() throws IOException { String name = this.getSelectedDocument(); logger.log(Level.INFO, "Downloading Global-Doc " + name + " from Documents."); return new DefaultStreamedContent(this.service.downloadGlobalDocument(name), null, name); } // ----------------------------- // User ------------------------ public List<Document> getUserDocuments() { String username = getLoggedInUsername(); if (username != null) { logger.log(Level.INFO, "Retrieving Document List for User " + username + "."); return this.service.getUserDocuments(username); } else { return null; } } public void handleUserFileUpload(FileUploadEvent event) throws IOException { String username = getLoggedInUsername(); if (username != null) { logger.log(Level.INFO, "Uploading User-Doc " + event.getFile().getFileName() + " into Documents for User " + username + "."); this.service.uploadUserDocument(username, event.getFile().getInputstream(), event.getFile().getFileName()); } } public void setSelectedUserDocument(String name) { this.selectedUserDocument = name; } public String getSelectedUserDocument() { return this.selectedUserDocument; } public void setDeleteUserDocument(String name) { String username = getLoggedInUsername(); if (username != null) { logger.log(Level.INFO, "Deleting User-Doc " + name + " from " + username + "'s Documents."); this.service.deleteUserDocument(username, name); } } public DefaultStreamedContent getUserDownload() throws IOException { String username = getLoggedInUsername(); if (username != null) { String name = this.getSelectedUserDocument(); if (name != null) { logger.log(Level.INFO, "Downloading User-Doc " + name + " from " + username + "'s Documents."); return new DefaultStreamedContent(this.service.downloadUserDocument(username, name), null, name); } else { return null; } } else { return null; } } // ----------------------------- public boolean getAdministrationAllowed() { return service.getAdministrationAllowed(CookieHelper.getAuthTokenValue()); } // User related things ------------------------ public boolean getUserAdministrationAllowed() { return service.getUserAdministrationAllowed(CookieHelper.getAuthTokenValue()); } public void setService(DocumentService service) { this.service = service; } private String getLoggedInUsername() { User user = service.getUserByToken(CookieHelper.getAuthTokenValue()); if (user != null) { String username = user.getUsername(); if (username != null) { return username; } else { return null; } } else { return null; } } // -------------------------------------------- }
package com.scf.skyware.notice.dao; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.scf.skyware.mobile.domain.NoticeM; import com.scf.skyware.notice.domain.Notice; @Repository public class NoticeDAOImpl implements NoticeDAO { @Autowired private SqlSessionTemplate sqlSession; // 리스트 불러오기 @Override public List<Notice> getNoticeList() { return sqlSession.selectList("getNoticeList"); } // 페이지 상세 보기 @Override public Notice getNoticeView(int noticeNo){ return (Notice) sqlSession.selectOne("getNoticeView", noticeNo); } // 페이지 정보 구하기 @Override public int getPageInfo() { return (int) sqlSession.selectOne("getPageInfo"); } // 공지사항 등록 @Override public void noticeWriteProc(Notice notice){ sqlSession.insert("noticeWriteProc", notice); } // 공지사항 수정 @Override public void noticeUpdate(Notice notice){ sqlSession.update("noticeUpdate", notice); } @Override public void noticeDel(int noticeNo) { sqlSession.update("noticeDel", noticeNo); } @Override public List<NoticeM> getNoticeListM(NoticeM notice) { return sqlSession.selectList("Notice_getNoticeList_M", notice); } @Override public NoticeM getNoticeViewM(NoticeM notice) { return sqlSession.selectOne("Notice_getNoticeView_M", notice); } @Override public int noticeWriteProcM(NoticeM notice) { return sqlSession.insert("Notice_noticeWriteProc_M", notice); } @Override public int noticeUpdateM(NoticeM notice) { return sqlSession.update("Notice_noticeUpdate_M", notice); } @Override public int noticeDelM(NoticeM notice) { return sqlSession.update("Notice_noticeDel_M", notice); } @Override public int getMaxNotice() { return sqlSession.selectOne(""); } @Override public int getNoticeCount() { return sqlSession.selectOne("Notice_getNoticeCount_M"); } }
package servlet; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.sql.Date; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import data.riskLogic; import model.risk; import model.riskNum; public class RiskAction extends ActionSupport{ private ArrayList<risk> risklist; private String rname; private String rcontent; private String rpos; private String reff; private String risk_trigger; private String risk_committer; private String risk_tracker; //private int selectedprojectid; private int selectedriskid; private Date startTime; private Date endTime; private Date hidStart; private Date hidEnd; ArrayList<riskNum> recognized; ArrayList<riskNum> toProblem; public ArrayList<risk> getRisklist() { return risklist; } public void setRisklist(ArrayList<risk> risklist) { this.risklist = risklist; } public String getRname() { return rname; } public void setRname(String rname) { this.rname = rname; } public String getRcontent() { return rcontent; } public void setRcontent(String rcontent) { this.rcontent = rcontent; } public String getRpos() { return rpos; } public void setRpos(String rpos) { this.rpos = rpos; } public String getReff() { return reff; } public void setReff(String reff) { this.reff = reff; } public String getRisk_trigger() { return risk_trigger; } public void setRisk_trigger(String risk_trigger) { this.risk_trigger = risk_trigger; } public String getRisk_committer() { return risk_committer; } public void setRisk_committer(String risk_committer) { this.risk_committer = risk_committer; } public String getRisk_tracker() { return risk_tracker; } public void setRisk_tracker(String risk_tracker) { this.risk_tracker = risk_tracker; } public int getSelectedriskid() { return selectedriskid; } public void setSelectedriskid(int selectedriskid) { this.selectedriskid = selectedriskid; } // // public int getSelectedprojectid() { // return selectedprojectid; // } // // public void setSelectedprojectid(int selectedprojectid) { // this.selectedprojectid = selectedprojectid; // } public Date getHidStart() { return hidStart; } public void setHidStart(Date hidStart) { this.hidStart = hidStart; } public Date getHidEnd() { return hidEnd; } public void setHidEnd(Date hidEnd) { this.hidEnd = hidEnd; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public ArrayList<riskNum> getRecognized() { return recognized; } public void setRecognized(ArrayList<riskNum> recognized) { this.recognized = recognized; } public ArrayList<riskNum> getToProblem() { return toProblem; } public void setToProblem(ArrayList<riskNum> toProblem) { this.toProblem = toProblem; } public String getAllRisk(){ ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); String name=(String)session.get("username"); riskLogic r=new riskLogic(); risklist=r.getAllRisk(); setRiskList(); return "success"; } private void setRiskList(){ for(int i=0;i<risklist.size();i++){ switch(risklist.get(i).getRiskPossibility()){ case 1: risklist.get(i).setRiskPossibilityStr("µÍ"); break; case 2: risklist.get(i).setRiskPossibilityStr("ÖÐ"); break; case 3: risklist.get(i).setRiskPossibilityStr("¸ß"); break; default: System.out.println("riskPossibility false"); break; } switch(risklist.get(i).getRiskEfficiency()){ case 1: risklist.get(i).setRiskEfficiencyStr("µÍ"); break; case 2: risklist.get(i).setRiskEfficiencyStr("ÖÐ"); break; case 3: risklist.get(i).setRiskEfficiencyStr("¸ß"); break; default: System.out.println("riskEfficiencyStr false"); break; } } } public String addProjectRisk(){ System.out.println("addrisk!"); int rposvalue=3; int reffvalue=3; riskLogic rl=new riskLogic(); if(rpos.equals("low")){ rposvalue=1; }else if(rpos.equals("medium")){ rposvalue=2; }else if(rpos.equals("high")){ rposvalue=3; } if(reff.equals("low")){ reffvalue=1; }else if(reff.equals("medium")){ reffvalue=2; }else if(reff.equals("high")){ reffvalue=3; } ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); String userName=(String)session.get("username"); risk r=new risk(1,rname,rcontent,rposvalue,reffvalue,risk_trigger,userName,risk_tracker); java.sql.Date currentDate = new java.sql.Date(System.currentTimeMillis()); r.setCreateTime(currentDate); int projectid=(Integer)session.get("projectid"); int res=rl.addProjectRisk(r,projectid); risklist=rl.getExistRisk(projectid); setRiskList(); return "success"; } public String delProjectRisk(){ ActionContext actionContext = ActionContext.getContext(); Map session = actionContext.getSession(); int projectid=(Integer)session.get("projectid"); riskLogic r=new riskLogic(); int result=r.removeProjectRisk(selectedriskid, projectid); return "success"; } public String riskSearch(){ riskLogic r=new riskLogic(); risklist=r.getAllRisk(startTime, endTime); setRiskList(); return "success"; } public String forChart(){ riskLogic r=new riskLogic(); recognized=r.getSelectedRisk(hidStart, hidEnd, 1); toProblem=r.getSelectedRisk(hidStart, hidEnd, 2); System.out.println(recognized.size()); System.out.println(toProblem.size()); return "success"; } }
package com.tencent.mm.boot.svg.a.a; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import android.os.Looper; import com.tencent.mm.svg.WeChatSVGRenderC2Java; import com.tencent.mm.svg.c; public final class ab extends c { private final int height = 72; private final int width = 72; protected final int b(int i, Object... objArr) { switch (i) { case 0: return 72; case 1: return 72; case 2: Canvas canvas = (Canvas) objArr[0]; Looper looper = (Looper) objArr[1]; c.f(looper); c.e(looper); Paint i2 = c.i(looper); i2.setFlags(385); i2.setStyle(Style.FILL); Paint i3 = c.i(looper); i3.setFlags(385); i3.setStyle(Style.STROKE); i2.setColor(-16777216); i3.setStrokeWidth(1.0f); i3.setStrokeCap(Cap.BUTT); i3.setStrokeJoin(Join.MITER); i3.setStrokeMiter(4.0f); i3.setPathEffect(null); c.a(i3, looper).setStrokeWidth(1.0f); i2 = c.a(i2, looper); i2.setColor(-1); canvas.save(); Paint a = c.a(i2, looper); Path j = c.j(looper); j.moveTo(18.0f, 37.5f); j.cubicTo(18.0f, 39.9849f, 15.9849f, 42.0f, 13.5f, 42.0f); j.cubicTo(11.0151f, 42.0f, 9.0f, 39.9849f, 9.0f, 37.5f); j.cubicTo(9.0f, 35.0142f, 11.0151f, 33.0f, 13.5f, 33.0f); j.cubicTo(15.9849f, 33.0f, 18.0f, 35.0142f, 18.0f, 37.5f); j.close(); j.moveTo(34.5f, 33.0f); j.cubicTo(36.9849f, 33.0f, 39.0f, 35.0142f, 39.0f, 37.5f); j.cubicTo(39.0f, 39.9849f, 36.9849f, 42.0f, 34.5f, 42.0f); j.cubicTo(32.0151f, 42.0f, 30.0f, 39.9849f, 30.0f, 37.5f); j.cubicTo(30.0f, 35.0142f, 32.0151f, 33.0f, 34.5f, 33.0f); j.close(); j.moveTo(55.5f, 33.0f); j.cubicTo(57.9849f, 33.0f, 60.0f, 35.0142f, 60.0f, 37.5f); j.cubicTo(60.0f, 39.9849f, 57.9849f, 42.0f, 55.5f, 42.0f); j.cubicTo(53.0151f, 42.0f, 51.0f, 39.9849f, 51.0f, 37.5f); j.cubicTo(51.0f, 35.0142f, 53.0151f, 33.0f, 55.5f, 33.0f); j.close(); WeChatSVGRenderC2Java.setFillType(j, 2); canvas.drawPath(j, a); canvas.restore(); c.h(looper); break; } return 0; } }
package com.xtw.msrd; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.text.SimpleDateFormat; import java.util.Date; import util.CommonMethod; import android.annotation.TargetApi; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.StatFs; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.crearo.config.StorageOptions; import com.crearo.mpu.sdk.Common; import com.crearo.mpu.sdk.MPUHandler; import com.crearo.mpu.sdk.client.PUInfo; public class G extends Application implements OnSharedPreferenceChangeListener { private static final String DEFAULT_PORT = "8958"; private static final String DEFAULT_ADDRESS = "58.211.11.100"; public static final int STT_PRELOGIN = -1; public static final int STT_LOGINING = 0; public static final int STT_LOGINED = 1; /** * true l,false f */ public static boolean USE_APN = false; private volatile static int mLoginStatus = STT_PRELOGIN; public static final String KEY_SERVER_ADDRESS = "KEY_SERVER_ADDRESS"; public static final String KEY_SERVER_PORT = "KEY_SERVER_PORT"; public static final String KEY_SERVER_FIXADDR = "key_fixAddr"; public static final String KEY_AUTO_ANSWER_ENABLE = "KEY_AUTO_ANSWER_ENABLE"; public static final String KEY_AUTO_ANSWER_WHITE_LIST = "KEY_AUTO_ANSWER_WHITE_LIST"; public static final String KEY_DIALING_TRIGER_MODE = "KEY_DIALING_TRIGER_MODE"; public static final String KEY_DIALING_USE_3G_CARD = "KEY_DIALING_USE_3G_CARD"; public static String mAddres; public static int mPort; public static boolean mFixAddr, mPreviewVideo; /** * 0表示手动上线,1表示主动上线 */ public static int sTriggerMode = 0; // public static final Executor sExecutor = // Executors.newFixedThreadPool(10); public static final Handler sUIHandler = new Handler(); static MyMPUEntity sEntity = null; private static final String TAG = "G"; public static final CharSequence KEY_SERVER_MORE = "KEY_SERVER_MORE"; private static final String KEY_SERVER_PREVIEW_VIDEO = "key_preivew_video"; public static final String KEY_HIGH_QUALITY = "key_high_quality"; public static final String KEY_WHITE_LIST = "key_white_list"; public static final String KEY_AUDIO_FREQ = "key_audio_freq"; // public static final String DEFAULT_SSID = USE_APN ? "123456" : // "LiYinConfigure-WiFi007"; // public static final String DEFAULT_SSID_PWD = USE_APN ? "12344321" : // "admin123"; public static final String DEFAULT_SSID = "123_zxcvbnm"; public static final String DEFAULT_SSID_PWD = "12344321"; public static PUInfo sPUInfo; static { sPUInfo = new PUInfo(); } /** * 正在登录的线程,不等于null表示需要循环登录 */ public volatile static String sRootPath; /** * 该值表示是否在mount了之后启动录像 */ public static boolean sIsAbortToRecordAfterMounted = true; public static String sVersionCode = null; /* * (non-Javadoc) * * @see android.app.Application#onCreate() */ @Override public void onCreate() { super.onCreate(); try { sVersionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (NameNotFoundException e1) { sVersionCode = "0"; e1.printStackTrace(); } USE_APN = sVersionCode.contains(".apn"); Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { ex.printStackTrace(); try { FileOutputStream os = new FileOutputStream(new File(String.format("%s/%s.log", sRootPath, sVersionCode)), true); SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH.mm.ss"); String dateStr = sdf.format(new Date()); os.write(dateStr.getBytes()); PrintStream err = new PrintStream(os); ex.printStackTrace(err); err.close(); os.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(-1); } }; Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); sPUInfo.name = pref.getString(MPUHandler.KEY_PUNAME.toString(), "丽音模块"); sPUInfo.puid = pref.getString("key_puid", null); if (sPUInfo.puid == null) { sPUInfo.puid = Common.getPuid(this); pref.edit().putString("key_puid", sPUInfo.puid).commit(); } sPUInfo.cameraName = pref.getString(MPUHandler.KEY_CAMNAME.toString(), "camera"); sPUInfo.mMicName = pref.getString(MPUHandler.KEY_IA_NAME.toString(), "audio"); sPUInfo.mSpeakerName = null; sPUInfo.mGPSName = null;// 暂时不支持GPS,在这里设置为null final SharedPreferences prf = PreferenceManager.getDefaultSharedPreferences(this); mAddres = prf.getString(KEY_SERVER_ADDRESS, DEFAULT_ADDRESS); try { mPort = -1; mPort = Integer.parseInt(prf.getString(KEY_SERVER_PORT, DEFAULT_PORT)); } catch (Exception e) { e.printStackTrace(); } mFixAddr = prf.getBoolean(KEY_SERVER_FIXADDR, true); mPreviewVideo = prf.getBoolean(KEY_SERVER_PREVIEW_VIDEO, false); prf.registerOnSharedPreferenceChangeListener(this); sEntity = new MyMPUEntity(this); // wifi 配置 ConfigServer.start(this, null, 8080); // 直连 Intent i = new Intent(this, PUServerService.class); this.startService(i); initRoot(); if (!TextUtils.isEmpty(sRootPath)) { log("start record by G!"); RecordService.start(this); } File dir = getFilesDir(); File[] files = dir.listFiles(); if (files != null) { for (File f : files) { if (f.getName().endsWith(".wav")) { String path = PreferenceManager.getDefaultSharedPreferences(this).getString( f.getName(), null); if (path == null) { String dirPath = String.valueOf(1); File dirFile = new File(G.sRootPath, dirPath); dirFile.mkdirs(); path = dirFile.getPath(); } String dst = path + "/" + f.getName().replace(".wav", ".zip"); try { // 为了防止录音线程与加密线程冲突 new File(dst).createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } EncryptIntentService.startActionFoo(this, f.getName(), dst); } } } } public static void initRoot() { // log(StorageOptions.MNT_SDCARD); // StorageOptions.readMountsFile(); // String storager1 = "/storage/sdcard1"; // boolean contain = false; // for (String mount : StorageOptions.mMounts) { // log("MOUNT1: " + mount); // if (mount.equals(storager1)) { // contain = true; // } // } // StorageOptions.readVoldFile(); // for (String vold : StorageOptions.mVold) { // log("mVold: " + vold); // } // StorageOptions.compareMountsWithVold(); // for (String mount : StorageOptions.mMounts) { // log("MOUNT2: " + mount); // } // if (!contain) { // StorageOptions.mMounts.add(storager1); // } // File root = new File(storager1); // log("storage exists " + root.exists()); // log("storage isDirectory " + root.isDirectory()); // log("storage canWrite " + root.canWrite()); // log(storager1 + "/11111", "ceshi是否写入成功"); // StorageOptions.testAndCleanMountsList(); // for (String mount : StorageOptions.mMounts) { // log("MOUNT3: " + mount); // } // StorageOptions.setProperties(); StorageOptions.determineStorageOptions(); String[] paths = StorageOptions.paths; if (paths == null || paths.length == 0) { log("no path found !!!"); return; } for (String path : paths) { log("PATH: " + path); } // 使用版本号作为设备的名称 sRootPath = String.format("%s/%s", paths[0], "audio"); } @Override public void onSharedPreferenceChanged(SharedPreferences prf, String key) { if (key.equals(KEY_SERVER_ADDRESS) || key.equals(KEY_SERVER_PORT)) { mAddres = prf.getString(KEY_SERVER_ADDRESS, null); try { mPort = -1; mPort = Integer.parseInt(prf.getString(KEY_SERVER_PORT, DEFAULT_PORT)); } catch (Exception e) { e.printStackTrace(); } NCIntentService.stopNC(this); if (checkParam(false)) { NCIntentService.startNC(this, mAddres, mPort); } } else if (key.equals(KEY_SERVER_FIXADDR)) { mFixAddr = prf.getBoolean(KEY_SERVER_FIXADDR, true); NCIntentService.stopNC(this); if (checkParam(false)) { NCIntentService.startNC(this, mAddres, mPort); } } else if (key.equals(KEY_SERVER_PREVIEW_VIDEO)) { mPreviewVideo = prf.getBoolean(key, false); } } public boolean checkParam(boolean toast) { if (TextUtils.isEmpty(G.mAddres)) { if (toast) { Toast.makeText(getApplicationContext(), "平台地址不合法", Toast.LENGTH_SHORT).show(); } return false; } if (G.mPort == -1) { if (toast) { Toast.makeText(getApplicationContext(), "平台端口不合法", Toast.LENGTH_SHORT).show(); } return false; } return true; } public static int getLoginStatus() { return mLoginStatus; } public static void setLoginStatus(final int newStatus) { mLoginStatus = newStatus; } public void login() throws InterruptedException { if (sEntity == null) { return; } long loginBegin = System.currentTimeMillis(); int r = sEntity.loginBlock(G.mAddres, G.mPort, G.mFixAddr, "", sPUInfo); if (r != 0) { long timeSpend = System.currentTimeMillis() - loginBegin; if (timeSpend < 1000) { try { Thread.sleep(1000 - timeSpend); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { } } public void logout() { sEntity.logout(); } public static boolean networkAvailable(Context c) { ConnectivityManager connMgr = (ConnectivityManager) c .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } public static void stopCameraPreview() { } /** * 获取可用空间百分比 */ public static int getAvailableStore() { int result = 0; try { // 取得sdcard文件路径 StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); // 获取BLOCK数量 float totalBlocks = statFs.getBlockCount(); // 可使用的Block的数量 float availaBlock = statFs.getAvailableBlocks(); float s = availaBlock / totalBlocks; s *= 100; result = (int) s; } catch (Exception e) { // TODO: handle exception } return result; } public static void log(String message) { log(null, message); } public static synchronized void log(String path, String message) { Log.e(TAG, message); if (path == null) { if (TextUtils.isEmpty(G.sRootPath)) { return; } path = new File(String.format("%s/%s.log", G.sRootPath, sVersionCode)).getPath(); } CommonMethod.save2File(message, path, true); } @TargetApi(Build.VERSION_CODES.KITKAT) public static String getStorageState() { String state = null; if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { state = Environment.getStorageState(new File(G.sRootPath)); } else { state = Environment.getExternalStorageState(); } return state; } }
package com.komaxx.komaxx_gl.scenegraph.analysis; import java.util.ArrayList; /** * Represents a priced traversal from one Analysis node to another * * @author Matthias Schicker */ public class Path { public int price; public AnalysisNode startNode; public AnalysisNode endNode; /** * the complete path to the shared node including start and shared node. */ public ArrayList<AnalysisNode> pathUp = new ArrayList<AnalysisNode>(8); /** * the complete path from the shared node including shared and end node. */ public ArrayList<AnalysisNode> pathDown = new ArrayList<AnalysisNode>(8); public Path(AnalysisNode start, AnalysisNode end) { startNode = start; endNode = end; } // profiling info public long maxRenderNanos = 0; public long renderTimeCumulator = 0; public int renderFrames = 0; /** * returns false when there is no shared parent node. */ public boolean compute() { pathUp.clear(); pathDown.clear(); AnalysisNode currentNode = startNode; // got to first shared parent boolean found = false; while(!found){ pathUp.add(currentNode); if (endNode.pathToRoot.contains(currentNode)){ found = true; } else { currentNode = currentNode.pathToRoot.get(1); } } if (!found) return false; AnalysisNode sharedParent = currentNode; pathDown.add(sharedParent); // now, for the other half, go down the tree again currentNode = endNode; while (currentNode != sharedParent && !(currentNode.isCluster() && ((ClusterNode)currentNode).contains(sharedParent)) ){ pathDown.add(1, currentNode); currentNode = currentNode.pathToRoot.get(1); } return true; } @Override public String toString() { return startNode.node.getName() + " --" + (pathUp.size()+pathDown.size()-2) + "-> " + endNode.node.getName() + ": " + price; } public void clearProfilingData() { maxRenderNanos = 0; renderTimeCumulator = 0; renderFrames = 0; } public void updateRenderTime(long pathTimeNs) { renderFrames++; renderTimeCumulator += pathTimeNs; if (pathTimeNs > maxRenderNanos) maxRenderNanos = pathTimeNs; } }
package com.service.impl; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dao.RecordMapper; import com.model.Record; import com.service.RecordService; @Service public class RecordServiceImpl implements RecordService { @Autowired private RecordMapper recordMapper; public Map<String,Integer> selectRecord(Map<String, Object> map) { // TODO Auto-generated method stub SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cd = Calendar.getInstance(); String time=(String) map.get("time"); Map<String,Integer> record=new LinkedHashMap<>(); for (int i = 0; i < 6; i++) { if(time!=null && time!=""){ try { cd.setTime(sdf.parse(time)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ cd.setTime(new Date()); } cd.add(Calendar.DATE, -(Integer)map.get("interval")*i+1); Date startTime=cd.getTime(); cd.add(Calendar.DATE, -(Integer)map.get("interval")); Date endTime=cd.getTime(); map.put("startTime", sdf.format(startTime)); map.put("endTime", sdf.format(endTime)); SimpleDateFormat sdf1 = new SimpleDateFormat("MM.dd"); record.put(sdf1.format(endTime)+"至"+sdf1.format(startTime), recordMapper.selectRecord(map)); } return record; } @Override public int insertSelective(Record record) { // TODO Auto-generated method stub return recordMapper.insertSelective(record); } @Override public int updateByPrimaryKeySelective(Record record) { // TODO Auto-generated method stub return recordMapper.updateByPrimaryKeySelective(record); } @Override public Record selectByPrimaryKey(Record record) { // TODO Auto-generated method stub return recordMapper.selectByPrimaryKey(record.getId()); } }
package com.tutorial.inheritance.employee; public abstract class Employee { private String name; private int id; private String empType; public String getEmpType() { return empType; } public void setEmpType(String empType) { this.empType = empType; } public Employee(String name, int id, String empType) { this.name = name; this.id = id; this.empType = empType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void tieColor() { System.out.println("Default Tie Color of " + empType + " Employee with name " + name + " is Purple"); } public abstract void meetingAgenda(); public abstract void vehicleInfo(); }
package com.skh.hkhr.util; import android.content.Context; import android.graphics.drawable.Drawable; import androidx.core.content.ContextCompat; /*** * @DEV #SamiranKumar11 * @Created by Samiran on 1/02/2017. */ public class AppRes { public static Drawable getDrawable(int resId, Context context) { return ContextCompat.getDrawable(context, resId); } public static int getColor(int resId, Context context) { return ContextCompat.getColor(context, resId); } public static String getString(int resId, Context context) { return context.getResources().getString(resId); } }
public class ScoreEntry { private String name; private int score; public ScoreEntry(String n, int s) { name = n; score = s; } public ScoreEntry() { name = "<NOBODY>"; score = 0; } public String getName() { return name; } public int getScore() { return score; } public String toString() { return name + ": " + score; } }
package leecode.string; public class 最长回文串_409 { public int longestPalindrome(String s) { return 0; } }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; import f.a.a.b; import java.util.LinkedList; public final class tc extends a { public int hcE; public String jTu; public String rco; public int rdV; public int rdW; public String rwt; public bhy rwu; public String rwv; public String rww; public String rwx; public int rwy; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rwu == null) { throw new b("Not all required fields were included: EmojiBuffer"); } if (this.rwt != null) { aVar.g(1, this.rwt); } aVar.fT(2, this.rdW); aVar.fT(3, this.rdV); if (this.rwu != null) { aVar.fV(4, this.rwu.boi()); this.rwu.a(aVar); } aVar.fT(5, this.hcE); if (this.jTu != null) { aVar.g(6, this.jTu); } if (this.rwv != null) { aVar.g(7, this.rwv); } if (this.rww != null) { aVar.g(8, this.rww); } if (this.rwx != null) { aVar.g(9, this.rwx); } if (this.rco != null) { aVar.g(10, this.rco); } aVar.fT(11, this.rwy); return 0; } else if (i == 1) { if (this.rwt != null) { h = f.a.a.b.b.a.h(1, this.rwt) + 0; } else { h = 0; } h = (h + f.a.a.a.fQ(2, this.rdW)) + f.a.a.a.fQ(3, this.rdV); if (this.rwu != null) { h += f.a.a.a.fS(4, this.rwu.boi()); } h += f.a.a.a.fQ(5, this.hcE); if (this.jTu != null) { h += f.a.a.b.b.a.h(6, this.jTu); } if (this.rwv != null) { h += f.a.a.b.b.a.h(7, this.rwv); } if (this.rww != null) { h += f.a.a.b.b.a.h(8, this.rww); } if (this.rwx != null) { h += f.a.a.b.b.a.h(9, this.rwx); } if (this.rco != null) { h += f.a.a.b.b.a.h(10, this.rco); } return h + f.a.a.a.fQ(11, this.rwy); } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } if (this.rwu != null) { return 0; } throw new b("Not all required fields were included: EmojiBuffer"); } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; tc tcVar = (tc) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); switch (intValue) { case 1: tcVar.rwt = aVar3.vHC.readString(); return 0; case 2: tcVar.rdW = aVar3.vHC.rY(); return 0; case 3: tcVar.rdV = aVar3.vHC.rY(); return 0; case 4: LinkedList IC = aVar3.IC(intValue); int size = IC.size(); for (intValue = 0; intValue < size; intValue++) { byte[] bArr = (byte[]) IC.get(intValue); a bhy = new bhy(); f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (boolean z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) { } tcVar.rwu = bhy; } return 0; case 5: tcVar.hcE = aVar3.vHC.rY(); return 0; case 6: tcVar.jTu = aVar3.vHC.readString(); return 0; case 7: tcVar.rwv = aVar3.vHC.readString(); return 0; case 8: tcVar.rww = aVar3.vHC.readString(); return 0; case 9: tcVar.rwx = aVar3.vHC.readString(); return 0; case 10: tcVar.rco = aVar3.vHC.readString(); return 0; case 11: tcVar.rwy = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.cqrcb.service.impl; import java.util.ArrayList; import java.util.List; import com.cqrcb.dao.StaffDao; import com.cqrcb.model.Staff; import org.appfuse.service.impl.BaseManagerMockTestCase; import org.mockito.InjectMocks; import org.mockito.Mock; import org.junit.Before; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; public class StaffManagerImplTest extends BaseManagerMockTestCase { @InjectMocks private StaffManagerImpl manager; @Mock private StaffDao dao; @Test public void testGetStaff() { log.debug("testing get..."); //given final String staffId = 7L; final Staff staff = new Staff(); given(dao.get(staffId)).willReturn(staff); //when Staff result = manager.get(staffId); //then assertSame(staff, result); } @Test public void testGetStaffs() { log.debug("testing getAll..."); //given final List<Staff> staffs = new ArrayList<>(); given(dao.getAll()).willReturn(staffs); //when List result = manager.getAll(); //then assertSame(staffs, result); } @Test public void testSaveStaff() { log.debug("testing save..."); //given final Staff staff = new Staff(); // enter all required fields staff.setStaffName("WlKcXySvNfJ"); staff.setStaffstatus(5.901258083429002E8L); given(dao.save(staff)).willReturn(staff); //when manager.save(staff); //then verify(dao).save(staff); } @Test public void testRemoveStaff() { log.debug("testing remove..."); //given final String staffId = -11L; willDoNothing().given(dao).remove(staffId); //when manager.remove(staffId); //then verify(dao).remove(staffId); } }
package studentapp.c_learning.kit.studentapp; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.ArrayMap; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; public class PostActivity extends AppCompatActivity { Toolbar threadToolBar; private RecyclerView recyclerView; private Context mContext; private List<ThreadComment> threadComments; private ThreadCommentAdapter adapter; static String threadNo, threadID; ImageView postOwnerDisplayImageView, postDisplayImageVIew, postDisplayImageVIew2,postDisplayImageVIew3, more_option; TextView postOwnerUsernameTextView, postTimeCreatedTextView , postTextTextView , postBodyTextView, postNumReadsTextView, postNumCommentsTextView ; // LinearLayout postLikeLayout, postCommentLayout, commentLayout; CardView threadCardView, commentCardView, importFileCardView; static EditText comment; ImageView send; String fid1, fid2,fid3, userCommentInput; static String[] cNO,cRoot,cBranch,cParent,cText, cDate,ttName,stName, fID1,fID2,fID3, cAlreadyNum, cID = null; SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); threadToolBar = findViewById(R.id.toolbar); setSupportActionBar(threadToolBar); getSupportActionBar().setTitle(getIntent().getExtras().getString("cTitle")); getSupportActionBar().setDisplayHomeAsUpEnabled(true); preferences = PreferenceManager.getDefaultSharedPreferences(this); setupRecyclerView(); initPost(); getAllCommentAPI(); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } private void setupRecyclerView() { recyclerView = findViewById(R.id.comment_recyclerview); threadComments = new ArrayList<>(); adapter = new ThreadCommentAdapter(this,threadComments); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(adapter); } private void initPost(){ threadID = getIntent().getExtras().getString("ccID"); threadNo = getIntent().getExtras().getString("cNO"); more_option = findViewById(R.id.more_option); more_option.setVisibility(View.GONE); postTextTextView = findViewById(R.id.tv_post_text); postTextTextView.setText(getIntent().getExtras().getString("cTitle")); postOwnerUsernameTextView = findViewById(R.id.tv_post_username); postOwnerUsernameTextView.setText(getIntent().getExtras().getString("stName")); if(Make_Thread.bbAnonymous.equals("0") || Make_Thread.bbAnonymous.equals("1")){ if (!postOwnerUsernameTextView.getText().toString().equals(preferences.getString("stName", null))){ postOwnerUsernameTextView.setText("Anonymous"); } else { postOwnerUsernameTextView.setText(preferences.getString("stName", null)); } } else if(Make_Thread.bbAnonymous.equals("2")){ if (postOwnerUsernameTextView.getText().toString().equals("null")){ postOwnerUsernameTextView.setText(getIntent().getExtras().getString("ttName")); } else if(postOwnerUsernameTextView.getText().toString().equals(getIntent().getExtras().getString("stName"))){ postOwnerUsernameTextView.setText(getIntent().getExtras().getString("stName")); } } postBodyTextView = findViewById(R.id.tv_post_body); postBodyTextView.setText(getIntent().getExtras().getString("cText")); postTimeCreatedTextView = findViewById(R.id.tv_time); postTimeCreatedTextView.setText(getIntent().getExtras().getString("cDate")); postOwnerDisplayImageView = findViewById(R.id.iv_post_owner_display); if(postOwnerUsernameTextView.getText().toString().equals(getIntent().getExtras().getString("ttName"))){ Picasso.with(mContext).load(getIntent().getExtras().getString("userProfileComment")) .into(postOwnerDisplayImageView, new com.squareup.picasso.Callback() { @Override public void onSuccess() { } @Override public void onError() { } }); } else if(postOwnerUsernameTextView.getText().toString().equals(MyCourses.name.getText().toString()) || !postOwnerUsernameTextView.getText().toString().equals(MyCourses.name.getText().toString())){ postOwnerDisplayImageView.setImageResource(R.drawable.facebook_avatar); } comment = findViewById(R.id.et_comment); comment.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus){ importFileCardView.setVisibility(View.VISIBLE); }else { importFileCardView.setVisibility(View.GONE); } } }); importFileCardView = findViewById(R.id.importFileCardView); commentCardView = findViewById(R.id.commentCardView); send = findViewById(R.id.iv_send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { userCommentInput = comment.getText().toString(); System.out.println(";;;;;;;;;;;;;;;;" + userCommentInput); PostActivity.BackgroundTask task = new PostActivity.BackgroundTask(PostActivity.this); task.execute(); } }); } public void getAllCommentAPI(){ ArrayMap<String, String> header = new ArrayMap<>(); ArrayMap<String, String> data = new ArrayMap<>(); data.put("ccID", getIntent().getExtras().getString("ccID")); data.put("ttID", "id1"); HttpRequestAsync myHttp = new HttpRequestAsync(header,data); try{ String myUrl = myHttp.execute("http://kit.c-learning.jp/t/ajax/coop/list", "POST").get(); JSONObject object = new JSONObject(myUrl); JSONArray jsonArray = object.getJSONArray("data"); cNO = new String[jsonArray.length()]; cRoot = new String[jsonArray.length()]; cBranch = new String[jsonArray.length()]; cParent= new String[jsonArray.length()]; cText= new String[jsonArray.length()]; cDate = new String[jsonArray.length()]; ttName = new String[jsonArray.length()]; stName = new String[jsonArray.length()]; fID1 = new String[jsonArray.length()]; fID2 = new String[jsonArray.length()]; fID3 = new String[jsonArray.length()]; cAlreadyNum = new String[jsonArray.length()]; cID = new String[jsonArray.length()]; for (int i = 0; i< jsonArray.length(); i++){ JSONObject row = jsonArray.getJSONObject(i); cNO[i] = row.getString("cNO"); cRoot[i] = row.getString("cRoot"); cBranch[i] = row.getString("cBranch"); cParent[i] = row.getString("cParent"); cText[i] = row.getString("cText"); cDate[i] = row.getString("cDate"); stName[i] = row.getString("stName"); ttName[i] = row.getString("ttName"); fID1[i] = row.getString("fID1"); fID2[i] = row.getString("fID2"); fID3[i] = row.getString("fID3"); cAlreadyNum[i] = row.getString("cAlreadyNum"); if(threadNo.equals(cParent[i])){ prepareDisplayComment(ttName[i],cText[i], cDate[i]); for (int j = 0; j< adapter.getItemCount(); j++){ cID[j] = cNO[i]; System.out.println("-----Post-----" + cID[j]); System.out.println(adapter.getItemCount() + "getItemCount"); } } else {} if(threadNo.equals(cRoot[i]) && !cBranch[i].equals("0")){ prepareDisplayReply(ttName[i],cText[i], cDate[i]); for (int k = 0; k < threadComments.size(); k++){ cID[k] = cNO[i]; System.out.println("======POST========" + cID[k]); System.out.println(threadComments.size()+ "Lenght:"); } } else {} } } catch (InterruptedException | ExecutionException | JSONException e) { e.printStackTrace(); } } private void commentThreadAPI(){ ArrayMap<String,String> header = new ArrayMap<>(); ArrayMap<String,String> data = new ArrayMap<>(); data.put("m","input"); data.put("ct",Function.courseID); data.put("cc", getIntent().getExtras().getString("ccID")); data.put("cn",getIntent().getExtras().getString("cNO")); data.put("c_text",userCommentInput); data.put("stName", preferences.getString("stName", null)); data.put("stID", preferences.getString("stID", null)); /* threadID = getIntent().getExtras().getString("ccID"); threadNo = getIntent().getExtras().getString("cNO");*/ HttpRequestAsync myHttp = new HttpRequestAsync(header,data); if (isNetworkAvailable()){ try { String myURL = myHttp.execute("https://kit.c-learning.jp/s/ajax/coop/CoopRes","POST").get(); prepareComment(MyCourses.name.getText().toString(),userCommentInput); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }else Toast.makeText(getApplication(),"No Internet Connection!", Toast.LENGTH_LONG).show(); } private void prepareComment(String username, String text){ if (comment.getHint().toString().equals("Write a reply...")){ ThreadComment reply = new ThreadComment(username,text, "2h30", ThreadComment.ItemType.TWO_ITEM); // threadComments.add(reply); int position = ThreadCommentAdapter.index; System.out.println(position + "=++++"); // position = position +1; threadComments.add(ThreadCommentAdapter.index + 1,reply); adapter.notifyItemChanged(ThreadCommentAdapter.index + 1); adapter.notifyItemRangeChanged(ThreadCommentAdapter.index, adapter.getItemCount()); } else if(comment.getHint().toString().equals("Write a comment...")){ ThreadComment comment = new ThreadComment(username,text, "2h30", ThreadComment.ItemType.ONE_ITEM); threadComments.add(comment); } adapter.notifyDataSetChanged(); } public void prepareDisplayReply(String username, String text, String date){ // int position = ThreadCommentAdapter.index; ThreadComment reply = new ThreadComment(username,text, date, ThreadComment.ItemType.TWO_ITEM); threadComments.add(ThreadCommentAdapter.index + 1,reply); adapter.notifyItemChanged(ThreadCommentAdapter.index + 1); adapter.notifyItemRangeChanged(ThreadCommentAdapter.index, adapter.getItemCount()); } public void prepareDisplayComment(String username, String text, String date){ ThreadComment comment = new ThreadComment(username,text, date, ThreadComment.ItemType.ONE_ITEM); threadComments.add(comment); adapter.notifyDataSetChanged(); } private class BackgroundTask extends AsyncTask<Void, Void, Void> { private ProgressDialog dialog; public BackgroundTask(PostActivity activity) { dialog = new ProgressDialog(activity); } @Override protected void onPreExecute() { dialog.setMessage("Sending comment.."); dialog.show(); } @Override protected void onPostExecute(Void result) { if (dialog.isShowing()) { commentThreadAPI(); dialog.dismiss(); } } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } } }
package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; /** * Takes an input stream and an output stream. * Writes the input stream into the output stream. * @author Jack Galilee * @version 1.0 */ public class StreamSwapper extends Thread { // Stream we are going to read into the output stream. private InputStream inputStream; // Stream we are going to write the input stream into. private OutputStream outputStream; /** * Constructs the stream swapper. * @param input Stream to get data from. * @param output Stream to send data to. * @throws IOException */ public StreamSwapper(InputStream input, OutputStream output) throws IOException { this.inputStream = input; this.outputStream = output; } /** * Buffers the input stream and writes it to the output stream. */ public void run() { // Create a reader for the input stream. BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream)); // Create a writer for the output stream. PrintWriter outputWriter = new PrintWriter(outputStream, true); // Buffer each new line from the reader and write it to the output stream. try { String lineBuffer; while ((lineBuffer = inputReader.readLine()) != null) { outputWriter.println(lineBuffer); } // Close the input reader and output writer when we're finished. inputReader.close(); outputWriter.close(); // Handle any exceptions with the IO data streams. } catch (IOException e) { e.printStackTrace(); } } }
package com.farm.tables; import org.json.JSONObject; /* * Represents farm table in database */ public class Farm { public int farmId; public String farmName; public int perimeterId; public String addressLine1; public String addressLine2; public String landMark; public int visitorsCount; public double area, perimeter; public Farm(int farmId, String farmName, int perimeterId, String addressLine1, String addressLine2, String landMark, int visitorsCount){ this.farmId = farmId; this.farmName = farmName; this.perimeterId = perimeterId; this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.landMark = landMark; this.visitorsCount = visitorsCount; } /* * This constructor is called from farmreport */ public Farm(int farmId, String farmName, int perimeterId, String addressLine1, String addressLine2, String landMark, int visitorsCount, double area, double perimeter){ this.farmId = farmId; this.farmName = farmName; this.perimeterId = perimeterId; this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.landMark = landMark; this.visitorsCount = visitorsCount; this.area = area; this.perimeter = perimeter; } /* * Generates Json string corresponding to farm data */ public JSONObject getFarmJson(){ JSONObject obj = null; try { obj = new JSONObject(); obj.put("farmid", ""+farmId); obj.put("farmname", farmName); obj.put("perimeterid", ""+perimeterId); obj.put("addressline1", addressLine1); obj.put("addressline2", addressLine2); obj.put("landmark", landMark); obj.put("visitorscount", ""+visitorsCount); } catch (Exception e) { } return obj; } }
package amlsim.model; import java.io.*; import java.util.Random; import java.util.Properties; import amlsim.AMLSim; import amlsim.Account; /** * Adjust transaction parameters for fine-tuning of the transaction network */ public class ModelParameters { // private static Random rand = new Random(AMLSim.getSeed()); private static Random rand = AMLSim.getRandom(); private static Properties prop = null; private static float SAR2SAR_EDGE_THRESHOLD = 0.0F; private static float SAR2NORMAL_EDGE_THRESHOLD = 0.0F; private static float NORMAL2SAR_EDGE_THRESHOLD = 0.0F; private static float NORMAL2NORMAL_EDGE_THRESHOLD = 0.0F; private static float SAR2SAR_TX_PROB = 1.0F; private static float SAR2NORMAL_TX_PROB = 1.0F; private static float NORMAL2SAR_TX_PROB = 1.0F; private static float NORMAL2NORMAL_TX_PROB = 1.0F; private static float SAR2SAR_AMOUNT_RATIO = 1.0F; private static float SAR2NORMAL_AMOUNT_RATIO = 1.0F; private static float NORMAL2SAR_AMOUNT_RATIO = 1.0F; private static float NORMAL2NORMAL_AMOUNT_RATIO = 1.0F; private static float NORMAL_HIGH_RATIO = 1.0F; // High transaction amount ratio from normal accounts private static float NORMAL_LOW_RATIO = 1.0F; // Low transaction amount ratio from normal accounts private static float NORMAL_HIGH_PROB = 0.0F; // Probability of transactions with high amount private static float NORMAL_LOW_PROB = 0.0F; // Probability of transactions with low amount private static float NORMAL_SKIP_PROB = 0.0F; // Probability of skipping transactions /** * Whether it adjusts parameters of normal transactions * @return If true, it affects to normal transaction models * If false, it does not any effects to all normal transactions */ public static boolean isValid(){ return prop != null; } private static float getRatio(String key, float defaultValue){ String value = System.getProperty(key); if(value == null){ value = prop.getProperty(key, String.valueOf(defaultValue)); } return Float.parseFloat(value); } private static float getRatio(String key){ return getRatio(key, 1.0F); } public static void loadProperties(String propFile){ if(propFile == null){ return; } System.out.println("Model parameter file: " + propFile); try{ prop = new Properties(); prop.load(new FileInputStream(propFile)); }catch (IOException e){ System.err.println("Cannot load model parameter file: " + propFile); e.printStackTrace(); prop = null; return; } SAR2SAR_EDGE_THRESHOLD = getRatio("sar2sar.edge.threshold"); SAR2NORMAL_EDGE_THRESHOLD = getRatio("sar2normal.edge.threshold"); NORMAL2SAR_EDGE_THRESHOLD = getRatio("normal2sar.edge.threshold"); NORMAL2NORMAL_EDGE_THRESHOLD = getRatio("normal2normal.edge.threshold"); SAR2SAR_TX_PROB = getRatio("sar2sar.tx.prob"); SAR2NORMAL_TX_PROB = getRatio("sar2normal.tx.prob"); NORMAL2SAR_TX_PROB = getRatio("normal2sar.tx.prob"); NORMAL2NORMAL_TX_PROB = getRatio("normal2normal.tx.prob"); SAR2SAR_AMOUNT_RATIO = getRatio("sar2sar.amount.ratio"); SAR2NORMAL_AMOUNT_RATIO = getRatio("sar2normal.amount.ratio"); NORMAL2SAR_AMOUNT_RATIO = getRatio("normal2sar.amount.ratio"); NORMAL2NORMAL_AMOUNT_RATIO = getRatio("normal2normal.amount.ratio"); NORMAL_HIGH_RATIO = getRatio("normal.high.ratio", 1.0F); NORMAL_LOW_RATIO = getRatio("normal.low.ratio", 1.0F); NORMAL_HIGH_PROB = getRatio("normal.high.prob", 1.0F); NORMAL_LOW_PROB = getRatio("normal.low.prob", 1.0F); NORMAL_SKIP_PROB = getRatio("normal.skip.prob", 1.0F); if(NORMAL_HIGH_RATIO < 1.0){ throw new IllegalArgumentException("The high transaction amount ratio must be 1.0 or more"); } if(NORMAL_LOW_RATIO <= 0.0 || 1.0 < NORMAL_LOW_RATIO){ throw new IllegalArgumentException("The low transaction amount ratio must be positive and 1.0 or less"); } if(1.0 < NORMAL_HIGH_PROB + NORMAL_LOW_PROB + NORMAL_SKIP_PROB){ throw new IllegalArgumentException("The sum of high, low and skip transaction probabilities" + " must be 1.0 or less"); } System.out.println("Transaction Probability:"); System.out.println("\tSAR -> SAR: " + SAR2SAR_TX_PROB); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_TX_PROB); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_TX_PROB); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_TX_PROB); System.out.println("Transaction edge addition threshold (proportion of SAR accounts):"); System.out.println("\tSAR -> SAR: " + SAR2SAR_EDGE_THRESHOLD); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_EDGE_THRESHOLD); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_EDGE_THRESHOLD); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_EDGE_THRESHOLD); System.out.println("Transaction amount ratio:"); System.out.println("\tSAR -> SAR: " + SAR2SAR_AMOUNT_RATIO); System.out.println("\tSAR -> Normal: " + SAR2NORMAL_AMOUNT_RATIO); System.out.println("\tNormal -> SAR: " + NORMAL2SAR_AMOUNT_RATIO); System.out.println("\tNormal -> Normal: " + NORMAL2NORMAL_AMOUNT_RATIO); } /** * Generate an up to 10% ratio noise for the base transaction amount * @return Amount ratio [0.9, 1.1] */ public static float generateAmountRatio(){ // [0.9, 1.1] return rand.nextFloat() * 0.2F + 0.9F; } /** * Adjust transaction amount from the given accounts and the base amount * @param orig Originator account * @param bene Beneficiary account * @param baseAmount Base amount * @return Adjusted amount (If it should not make this transaction, return non-positive value) */ public static float adjustAmount(Account orig, Account bene, float baseAmount){ // Generate decentralized amount with up to 10% noise float amount = baseAmount * generateAmountRatio(); if(!isValid()){ return amount; } float ratio; float prob = rand.nextFloat(); if(orig.isSAR()){ // SAR originator if(bene.isSAR()){ // SAR -> SAR if(SAR2SAR_TX_PROB <= prob){ return 0.0F; } ratio = SAR2SAR_AMOUNT_RATIO; }else{ // SAR -> Normal if(SAR2NORMAL_TX_PROB <= prob){ return 0.0F; } ratio = SAR2NORMAL_AMOUNT_RATIO; } }else{ // Normal originator if(bene.isSAR()){ // Normal -> SAR if(NORMAL2SAR_TX_PROB <= prob){ return 0.0F; } ratio = NORMAL2SAR_AMOUNT_RATIO; }else{ // Normal -> Normal if(NORMAL2NORMAL_TX_PROB <= prob){ return 0.0F; } ratio = NORMAL2NORMAL_AMOUNT_RATIO; } prob = rand.nextFloat(); if(prob < NORMAL_HIGH_PROB){ // High-amount payment transaction (near to the upper limit) ratio *= NORMAL_HIGH_RATIO; }else if(prob < NORMAL_HIGH_PROB + NORMAL_LOW_PROB){ // Low-amount transaction ratio *= NORMAL_LOW_RATIO; }else if(prob < NORMAL_HIGH_PROB + NORMAL_LOW_PROB + NORMAL_SKIP_PROB){ return 0.0F; // Skip this transaction } } return amount * ratio; } /** * Determine whether the transaction edge should be actually added between the given accounts * @param orig Originator account * @param bene Beneficiary account * @return If the transaction should be actually added, return true. */ public static boolean shouldAddEdge(Account orig, Account bene){ if(!isValid()){ // It always adds this edge return true; } // Proportion of SAR beneficiary accounts of the originator account // float benePropThreshold = SAR2NORMAL_EDGE_THRESHOLD; // int beneNumThreshold = (int) Math.floor(1 / NORMAL2SAR_EDGE_THRESHOLD); int numNeighbors = orig.getBeneList().size(); float propSARBene = orig.getPropSARBene(); if(orig.isSAR()){ // SAR originator if(bene.isSAR()){ // SAR -> SAR return propSARBene >= SAR2SAR_EDGE_THRESHOLD; }else{ // SAR -> Normal // Allow edge creations if the ratio of SAR beneficiary accounts is enough large return propSARBene >= SAR2NORMAL_EDGE_THRESHOLD; } }else{ // Normal originator if(bene.isSAR()){ // Normal -> SAR // Create a transaction edge if the ratio of SAR beneficiary accounts is still large if(NORMAL2SAR_EDGE_THRESHOLD <= 0.0F){ return true; } return numNeighbors > (int) Math.floor(1 / NORMAL2SAR_EDGE_THRESHOLD) && propSARBene >= NORMAL2SAR_EDGE_THRESHOLD; }else{ // Normal -> Normal return propSARBene >= NORMAL2NORMAL_EDGE_THRESHOLD; } } } }
package Client.Services.Enums.Help; public class Expenselmpl extends RecurringExpenses implements ExpensesInterface { public double getRecurringExpenses() { double a = totalRecurringExpenses(); return a; } }
package com.tfxk.framework.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /** * Created by Chenchunpeng on 2015/9/16. */ public class ReflectUtils { public static Field generatorField(Class clazz, String fieldName) throws NoSuchFieldException { Field field = null; try { field = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { e.printStackTrace(); if (field == null) clazz = clazz.getSuperclass(); field = clazz.getDeclaredField(fieldName); } return field; } public static String generateSetMethod(Field field) { String fieldName = field.getName(); field.setAccessible(true); return "set" + fieldName.toUpperCase().charAt(0) + fieldName.substring(1); } public static String generateGetMethod(Field field) { String name = field.getName(); String methodName = name.toUpperCase().charAt(0) + name.substring(1); methodName = "get" + methodName; return methodName; } public static void handleSetMethod(Class clazz, Field field, Object value, Object out) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String methodName = generateSetMethod(field); Class fieldType = field.getType(); if (fieldType.equals(String.class)) { value = String.valueOf(value); } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { value = Integer.valueOf(String.valueOf(value)); } else if (fieldType.equals(float.class) || Float.class.equals(fieldType)) { value = Float.valueOf(String.valueOf(value)); } else if (Double.class.equals(fieldType) || double.class.equals(fieldType)) { value = Double.valueOf(String.valueOf(value)); } try { clazz.getDeclaredMethod(methodName, field.getType()).invoke(out, value); } catch (Exception e) { clazz = clazz.getSuperclass(); clazz.getDeclaredMethod(methodName, field.getType()).invoke(out, value); } } /** * @param clazz the class of the field which want to reflect * @param field the field which the object want to reflect * @param out the object which need call the getXXX() method * @return the object which after call getXXX() * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static Object handleGetMethod(Class clazz, Field field, Object out) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String methodName = generateGetMethod(field); Object object; try { object = clazz.getDeclaredMethod(methodName, new Class[]{}).invoke(out, new Object[]{}); } catch (Exception e) { clazz = clazz.getSuperclass(); object = clazz.getDeclaredMethod(methodName, new Class[]{}).invoke(out, new Object[]{}); } return object; } }
package graphics; import javafx.scene.canvas.GraphicsContext; public class Text_Sprite { private String text; private double positionX; private double positionY; public Text_Sprite() { positionX = 0; positionY = 0; } public void setPosition(double x, double y) { positionX = x; positionY = y; } public void setText(String new_text) { text = new_text; } public double getXPosition() { return positionX; } public double getYPosition() { return positionY; } public String getText() { return text; } public void render(GraphicsContext gc) { gc.fillText( text, positionX, positionY ); //gc.strokeText( text, positionX, positionY ); } }
package com.ifood.demo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertNotNull; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.http.MockHttpOutputMessage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.ifood.demo.client.Client; import com.ifood.demo.client.ClientRepository; @RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration(classes = ClientApplication.class) public class ClientRestDataIntegrationTests { private MockMvc mockMvc; private HttpMessageConverter mappingJackson2HttpMessageConverter; private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8")); @Autowired private WebApplicationContext context; @Autowired private ClientRepository clientRepository; @Autowired void setConverters(HttpMessageConverter<?>[] converters) { this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream() .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().orElse(null); assertNotNull("the JSON message converter must not be null", this.mappingJackson2HttpMessageConverter); } @Before public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .alwaysDo(MockMvcResultHandlers.print()) .build(); } @After public void truncateTable() { clientRepository.deleteAll(); } private String json(Object o) throws IOException { MockHttpOutputMessage mockHttpOutputMessage = new MockHttpOutputMessage(); this.mappingJackson2HttpMessageConverter.write(o, MediaType.APPLICATION_JSON, mockHttpOutputMessage); return mockHttpOutputMessage.getBodyAsString(); } public static <T> Object jsonToObject(String json, Class<T> objectClass) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(json, objectClass); } public static String jsonPathValue(String json, String fieldPath) throws IOException { JsonNode treeNode = new ObjectMapper().readTree(json); for (String field : fieldPath.split("\\.")) { if (treeNode.has(field)) { treeNode = treeNode.get(field); } else { return ""; } } return treeNode.textValue(); } private String buildSearchUrl(String searchContent, String jsonPath ) throws IOException { String jsonValue = jsonPathValue(searchContent, jsonPath); String searchUrl = jsonValue.replace("http://localhost", "").split("\\?")[0].replace("{", "?"); String[] searchParams = jsonValue.split("\\?")[1].split(",|}"); for (String param : searchParams) { searchUrl += param + "={" + param + "}&"; } return searchUrl; } @Test public void contextLoadsTest() {} @Test public void hateoasApiTest() throws Exception { String apiContent = this.mockMvc.perform(get("/v1").contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_links", hasKey("clients"))) .andExpect(jsonPath("_links.clients.href", is("http://localhost/v1/clients{?page,size,sort}"))) .andReturn().getResponse().getContentAsString(); String clientsUrl = jsonPathValue(apiContent, "_links.clients.href") .replace("http://localhost","") .split("\\{")[0]; String clientsContent = this.mockMvc.perform(get(clientsUrl).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_links", hasKey("self"))) .andExpect(jsonPath("_links", hasKey("search"))) .andExpect(jsonPath("_links.self.href", is("http://localhost/v1/clients{?page,size,sort}"))) .andExpect(jsonPath("_links.search.href", is("http://localhost/v1/clients/search"))) .andReturn().getResponse().getContentAsString(); String searchUrl = jsonPathValue(clientsContent, "_links.search.href") .replace("http://localhost",""); this.mockMvc.perform(get(searchUrl).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_links", hasKey("byName"))) .andExpect(jsonPath("_links", hasKey("byPhone"))) .andExpect(jsonPath("_links", hasKey("byEmail"))) .andExpect(jsonPath("_links", hasKey("byNameAndPhone"))) .andExpect(jsonPath("_links.self.href", is("http://localhost/v1/clients/search"))) .andExpect(jsonPath("_links.byName.href", is("http://localhost/v1/clients/search/byName{?name}"))) .andExpect(jsonPath("_links.byPhone.href", is("http://localhost/v1/clients/search/byPhone{?phone}"))) .andExpect(jsonPath("_links.byEmail.href", is("http://localhost/v1/clients/search/byEmail{?email}"))) .andExpect(jsonPath("_links.byNameAndPhone.href", is("http://localhost/v1/clients/search/byNameAndPhone{?name,phone}"))) .andReturn().getResponse().getContentAsString(); } @Test public void createClientTest() throws Exception { Client newClient = new Client("João da Silva", "joao@silva.com", "12345678"); String apiContent = this.mockMvc.perform(get("/v1").contextPath("/v1")) .andReturn().getResponse().getContentAsString(); String clientsUrl = jsonPathValue(apiContent, "_links.clients.href") .replace("http://localhost","") .split("\\{")[0]; String clientId = this.mockMvc.perform(post(clientsUrl).contextPath("/v1") .contentType(contentType).content(json(newClient))) .andExpect(status().isCreated()) .andReturn().getResponse().getHeader("Location").split("/clients/")[1]; this.mockMvc.perform(get(clientsUrl + "/{clientId}", clientId).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("name", is(newClient.getName()))) .andExpect(jsonPath("email", is(newClient.getEmail()))) .andExpect(jsonPath("phone", is(newClient.getPhone()))) .andExpect(jsonPath("_links", hasKey("self"))) .andExpect(jsonPath("_links.self.href", is("http://localhost/v1/clients/" + clientId))); } @Test public void updateClientTest() throws Exception { Client newClient = new Client("Maria da Silva", "maria@silva.com", "12348765"); String apiContent = this.mockMvc.perform(get("/v1/").contextPath("/v1")) .andReturn().getResponse().getContentAsString(); String clientsUrl = jsonPathValue(apiContent, "_links.clients.href") .replace("http://localhost","") .split("\\{")[0]; String clientId = this.mockMvc.perform(post(clientsUrl).contextPath("/v1") .contentType(contentType).content(json(newClient))) .andExpect(status().isCreated()) .andReturn().getResponse().getHeader("Location").split("/clients/")[1]; String createdClientJson = this.mockMvc.perform(get(clientsUrl + "/{clientId}", clientId).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("name", is(newClient.getName()))) .andExpect(jsonPath("email", is(newClient.getEmail()))) .andExpect(jsonPath("phone", is(newClient.getPhone()))) .andExpect(jsonPath("_links", hasKey("self"))) .andExpect(jsonPath("_links.self.href", is("http://localhost/v1/clients/" + clientId))) .andReturn().getResponse().getContentAsString(); Client createdClient = (Client) jsonToObject(createdClientJson, Client.class); Client clientForUpdate = new Client(createdClient.getName(), createdClient.getEmail(), "99998888"); clientForUpdate.setId(UUID.fromString(clientId)); this.mockMvc.perform(put(clientsUrl + "/{clientId}", clientId).contextPath("/v1") .contentType(contentType).content(json(clientForUpdate))) .andExpect(status().isNoContent()); this.mockMvc.perform(get(clientsUrl + "/{clientId}", clientId).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("name", is(clientForUpdate.getName()))) .andExpect(jsonPath("email", is(clientForUpdate.getEmail()))) .andExpect(jsonPath("phone", is(clientForUpdate.getPhone()))) .andExpect(jsonPath("_links", hasKey("self"))) .andExpect(jsonPath("_links.self.href", is("http://localhost/v1/clients/" + clientId))) .andReturn().getResponse().getContentAsString(); } @Test public void searchClientTest() throws Exception { Client client1 = new Client("João da Silva", "joao@silva.com", "12345678"); Client client2 = new Client("José da Silva", "jose@silva.com", "987654321"); Client client3 = new Client("Maria da Silva", "maria@silva.com", "12348765"); String apiContent = this.mockMvc.perform(get("/v1/").contextPath("/v1")) .andReturn().getResponse().getContentAsString(); String clientsUrl = jsonPathValue(apiContent, "_links.clients.href") .replace("http://localhost","") .split("\\{")[0]; String clientsContent = this.mockMvc.perform(get(clientsUrl).contextPath("/v1")) .andReturn().getResponse().getContentAsString(); String searchUrl = jsonPathValue(clientsContent, "_links.search.href") .replace("http://localhost",""); String searchContent = this.mockMvc.perform(get(searchUrl).contextPath("/v1")) .andReturn().getResponse().getContentAsString(); String searchByNameUrl = buildSearchUrl(searchContent, "_links.byName.href"); String searchByEmailUrl = buildSearchUrl(searchContent, "_links.byEmail.href"); String searchByPhoneUrl = buildSearchUrl(searchContent, "_links.byPhone.href"); String searchByNameAndPhoneUrl = buildSearchUrl(searchContent, "_links.byNameAndPhone.href"); this.mockMvc.perform(post(clientsUrl).contextPath("/v1").contentType(contentType).content(json(client1))).andExpect(status().isCreated()); this.mockMvc.perform(post(clientsUrl).contextPath("/v1").contentType(contentType).content(json(client2))).andExpect(status().isCreated()); this.mockMvc.perform(post(clientsUrl).contextPath("/v1").contentType(contentType).content(json(client3))).andExpect(status().isCreated()); this.mockMvc.perform(get(searchByNameUrl, "Silva").contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.clients", hasSize(3))); this.mockMvc.perform(get(searchByNameUrl, client1.getName()).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.clients", hasSize(1))) .andExpect(jsonPath("_embedded.clients[0].name", is(client1.getName()))) .andExpect(jsonPath("_embedded.clients[0].email", is(client1.getEmail()))) .andExpect(jsonPath("_embedded.clients[0].phone", is(client1.getPhone()))); this.mockMvc.perform(get(searchByEmailUrl, client2.getEmail()).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.clients", hasSize(1))) .andExpect(jsonPath("_embedded.clients[0].name", is(client2.getName()))) .andExpect(jsonPath("_embedded.clients[0].email", is(client2.getEmail()))) .andExpect(jsonPath("_embedded.clients[0].phone", is(client2.getPhone()))); this.mockMvc.perform(get(searchByPhoneUrl, client3.getPhone()).contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.clients", hasSize(1))) .andExpect(jsonPath("_embedded.clients[0].name", is(client3.getName()))) .andExpect(jsonPath("_embedded.clients[0].email", is(client3.getEmail()))) .andExpect(jsonPath("_embedded.clients[0].phone", is(client3.getPhone()))); this.mockMvc.perform(get(searchByNameAndPhoneUrl, "Silva", "4321").contextPath("/v1")) .andExpect(status().isOk()) .andExpect(jsonPath("_embedded.clients", hasSize(1))) .andExpect(jsonPath("_embedded.clients[0].name", is(client2.getName()))) .andExpect(jsonPath("_embedded.clients[0].email", is(client2.getEmail()))) .andExpect(jsonPath("_embedded.clients[0].phone", is(client2.getPhone()))); } }
package traning; public class Classdemo2 { public static void main(String[] args) { Calculator obj1= new Calculator(); obj1.sub(); obj1.sum(); System.out.println("Name is "+obj1.Name); System.out.println("Name is"+obj1.Hobby); } }
package com.android.demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; public class LoginAct extends Activity { private EditText name; private EditText pwd; private ImageButton login; private ImageButton register; private ImageButton forget; private String questStr = ""; private String postStr = ""; private String host="registerandlogin.duapp.com"; String requestUrl = "http://registerandlogin.duapp.com/RegisterAndLogin/Login"; private Intent intent; private SharedPreferences sharedPreferences; private Editor editor; /** Called when the activity is first created. */ @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏 setContentView(R.layout.login); name = (EditText) findViewById(R.id.UserName); pwd = (EditText) findViewById(R.id.pwd); login = (ImageButton) findViewById(R.id.login); register = (ImageButton) findViewById(R.id.register); forget = (ImageButton) findViewById(R.id.forget); forget.getBackground().setAlpha(0); intent = new Intent(LoginAct.this, RegisterAct.class); login.setOnTouchListener(new View.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ //重新设置按下时的背景图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.go_pressed)); }else if(event.getAction() == MotionEvent.ACTION_UP){ //再修改为抬起时的正常图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.go)); } return false; } }); forget.setOnTouchListener(new View.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ //重新设置按下时的背景图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.forget_pressed)); }else if(event.getAction() == MotionEvent.ACTION_UP){ //再修改为抬起时的正常图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.forget)); } return false; } }); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (LoginAct.this.loginIsSuccsee()) { // 用户输入正确 login(); } } }); register.setOnTouchListener(new View.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ //重新设置按下时的背景图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.creatcount_pressed)); }else if(event.getAction() == MotionEvent.ACTION_UP){ //再修改为抬起时的正常图片 ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.creatcount)); } return false; } }); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // name.setText(""); // pwd.setText(""); startActivity(intent); } }); sharedPreferences = getSharedPreferences("info",MODE_PRIVATE); editor = sharedPreferences.edit(); name.setText(sharedPreferences.getString("username", "")); pwd.setText(sharedPreferences.getString("password", "")); } /* * * 取得用户信息处理登录 */ @Override protected void onDestroy() { super.onDestroy(); unbindDrawables(findViewById(R.id.RootView)); System.gc(); } private void unbindDrawables(View view) { if (view.getBackground() != null) { view.getBackground().setCallback(null); } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { unbindDrawables(((ViewGroup) view).getChildAt(i)); } ((ViewGroup) view).removeAllViews(); } } /* * 判断用户输入是否规范 录入信息验证 验证是否通过 */ private boolean loginIsSuccsee() { EditText name = (EditText) findViewById(R.id.UserName); EditText pwd = (EditText) findViewById(R.id.pwd); // 获取用户输入的信息 String userName = name.getText().toString(); String password = pwd.getText().toString(); if ("".equals(userName)) { // 用户输入用户名为空 Toast.makeText(LoginAct.this, "用户名不能为空!", Toast.LENGTH_SHORT) .show(); return false; } else if ("".equals(password)) { // 密码不能为空 Toast.makeText(LoginAct.this, "密码不能为空!", Toast.LENGTH_SHORT).show(); return false; } return true; } private void login() { // 获取用户输入的用户名,密码 EditText name = (EditText) findViewById(R.id.UserName); EditText pwd = (EditText) findViewById(R.id.pwd); String username = name.getText().toString(); String password = pwd.getText().toString(); String httpstr = "http://"; postStr = httpstr + host + "/RegisterAndLogin/login"; // questStr = "{LOGIN:{username:'}" + username + "',password:'" // + password + "'}}"; questStr = "{LOGIN:{username:'" + username + "',password:'" + password + "'}}"; System.out.println("====questStr====" + questStr); System.out.println("====postStr====" + postStr); try { // 设置连接超时 HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(postStr); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", username)); nvps.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String isUser = ConvertStreamToString(is); System.out.println("asdfsdf" + isUser); String tb=isUser.substring(isUser.length()-4); System.out.println(tb); if ("true".equals(tb)) { // 登录成功 // 获取所有用户的数量 editor.putString("password", pwd.getText() .toString().trim()); editor.putString("username", name.getText() .toString().trim()); editor.commit(); Intent intent =new Intent(LoginAct.this,MainActivity.class); startActivity(intent); this.finish(); onDestroy(); } else if ("false".equals(isUser)) { AlertDialog.Builder builder = new Builder(LoginAct.this); builder.setMessage("用户名或密码输入错误!请重新登录"); builder.setTitle("提示"); builder.setPositiveButton("确认", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Intent i=new // Intent(LoginActivity.this,LoginAct.class); // LoginActivity.this.finish(); // startActivity(i); // EditText name = (EditText) findViewById(R.id.UserName); // EditText pwd = (EditText) findViewById(R.id.pwd); // name.setText(""); // pwd.setText(""); dialog.dismiss(); } }).show(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // 读取字符流 public String ConvertStreamToString(InputStream is) { StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String returnStr = ""; try { while ((returnStr = br.readLine()) != null) { sb.append(returnStr); } } catch (IOException e) { e.printStackTrace(); } final String result = sb.toString(); // System.out.println(result); return result; } }
this is sample for test
package com.qihoo.finance.chronus.master.bo; import lombok.Getter; import lombok.Setter; /** * 互斥节点 */ @Getter @Setter public class MutexNode { /** * 左节点 */ private String leftKey; /** * 关联key */ private String relationKey; /** * 右节点 */ private String rightKey; }
package com.fnsvalue.skillshare.controller; import java.util.ArrayList; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.fnsvalue.skillshare.bo.NoticeBO; import com.fnsvalue.skillshare.bo.NoticeDetailBO; import com.fnsvalue.skillshare.dto.Board; import com.fnsvalue.skillshare.dto.Notice; import com.fnsvalue.skillshare.dto.User; @Controller public class NoticeDetailsController { @Autowired private NoticeDetailBO noticedetailBO; @RequestMapping(value="noticedetails", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView noticeDetailView(Board board,HttpSession session) { ArrayList<HashMap> NoticeDetails=noticedetailBO.NoticeDetailsView(board); session.setAttribute("NoticeDetails",NoticeDetails); ModelAndView mav = new ModelAndView("noticedetails"); //mav.setViewName("redirect:usermanagerCri"); //model.addAttribute("list",rootmanagerBO.listCriteria(cri)); return mav; } @RequestMapping(value="noticedelete", method = {RequestMethod.GET, RequestMethod.POST}) public ModelAndView delete(Board board) { ModelAndView mav = new ModelAndView(); int result = noticedetailBO.NoticeDelete(board.getBoard_no_pk()); System.out.println("result = "+result); if(result > 0){ mav.setViewName("redirect:notice"); } else{ System.out.println("실패"); } return mav; } }
package com.commercetools.pspadapter.payone.util; import com.commercetools.pspadapter.payone.config.PropertyProvider; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.BeanProperty; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.ContextualSerializer; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import static com.commercetools.pspadapter.payone.config.PropertyProvider.HIDE_CUSTOMER_PERSONAL_DATA; /** * Bean fields marked with this annotation should be serialized with value {@code <HIDDEN>}. * {@code Apply} accepts 1 boolean parameter. If the parameter is {@code true} then the value will be hidden. * If the parameter is {@code false} or was not provided then the code will check environment variable * {@code HIDE_CUSTOMER_PERSONAL_DATA}. If the value of the environment variable is {@code true} then the * field will be hidden. If the value of environment variable is not provided then it will be counted as {@code true} * * @author fhaertig * @since 19.04.16 */ public class ClearSecuredValuesSerializer extends JsonSerializer<String> implements ContextualSerializer { public static final String PLACEHOLDER = "<HIDDEN>"; private final BeanProperty property; public ClearSecuredValuesSerializer() { this(null); } private ClearSecuredValuesSerializer(final BeanProperty property) { this.property = property; } @Override public void serialize(final String value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { final PropertyProvider propertyProvider = new PropertyProvider(); final boolean hideCustomerPersonalData = propertyProvider.getProperty(HIDE_CUSTOMER_PERSONAL_DATA) .map(dataString -> !dataString.equals("false")) .orElse(true); if (property != null && property.getAnnotation(Apply.class) != null && (property.getAnnotation(Apply.class).value() || hideCustomerPersonalData)) { gen.writeString(PLACEHOLDER); } else { gen.writeString(value); } } @Override public JsonSerializer<?> createContextual(final SerializerProvider prov, final BeanProperty property) { return new ClearSecuredValuesSerializer(property); } @Retention(RetentionPolicy.RUNTIME) public @interface Apply { boolean value() default false; } }
package dailyPractice.jianzhi; public class StarQ13 { public int movingCount(int m, int n, int k) { boolean[][] visited = new boolean[m][n]; return dfs(m, n, 0, 0, k, visited); } public int dfs(int m, int n, int i, int j, int k, boolean[][] visited) { if (sumDigit(i, j) > k || i < 0 || i >= m || j < 0 || j >= n || visited[i][j]) return 0; visited[i][j] = true; return 1 + dfs(m, n, i + 1, j, k, visited) + dfs(m, n, i, j + 1, k, visited) + dfs(m, n, i - 1, j, k, visited) + dfs(m, n, i, j - 1, k, visited); } // 数位之和计算: int sumDigit(int x, int y) { int s = 0; while (x != 0) { s += x % 10; x = x / 10; } while (y != 0) { s += y % 10; y = y / 10; } return s; } }
package temp001; public class ArrayListQuiz { // 콜렉션 (ArrayList) 사용하기 // 1. 선언하기 // 콜렉션<객체 타입> 변수명 = new 콜렉션<객체 타입>(); // 2. 사용법 // 콜렉션은 배열과 유사한 기능을 제공하는 객체들을 말한다. // -List 계열은 자료를 순서대로 저장해 index를 부여한다. 대표적으로 ArrayList를 사용한다. // -Set 계열은 자료를 순서 없이 저장하고, 중복을 자동으로 제거한다.(같은 것을 여러 번 저장해도 1번만 저장됨) 대표적으로 HashSet을 사용한다. // -Map 계열은 key, value의 쌍으로 자료를 저장한다. key는 특정 객체를 찾기 위한 값(index와 유사한 기능), value는 실질적으로 저장하려는 값이다. 대표적으로 HashMap을 사용한다. // ** Map은 콜렉션과 조금 사용법이 다르고 복잡하다. 그냥 이런 것이 있구나 참고만 하고 넘어가자. // 3. 콜렉션의 장점 // - 배열과 달리 자동으로 크기가 조절된다. // - 용도에 따라 적절한 콜렉션을 사용하면, 콜렉션에 이미 생성되어 있는 메소드들을 활용하여 더 많은 기능을 편하게 사용할 수 있다. // 4. 콜렉션 기본 메소드 // * 모든 콜렉션은 기본적인 사용법이 동일하다. // (1) 특정 index의 값을 꺼내기 (배열에서 변수명[i] 했던 것과 동일) : 변수명.get(index); // (2) 값을 콜렉션에 넣기 : 변수명.add(저장할 객체의 변수명); // (3) 다른 콜렉션에 있는 모든 값을 불러와 저장하기 : 변수명.addAll(다른 콜렉션객체 변수명); // (4) 콜렉션의 크기 구하기(배열에서 변수명.length()와 동일) : 변수명.size(); // * 더 자세한 사용법은 변수명. 해서 나오는 메소드들을 읽어보거나 구글에서 검색해볼 것(너무 다양함) // ObjectQuiz의 2번째 단계까지 다시 실행한다. // ArrayList<Student> studentList = new ArrayList<Student>(); 로 ArrayList를 선언한다. // studentList에 생성된 학생 정보 객체들을 담는다. // ArrayList를 대상으로 enhanced-for문을 사용해 3번 단계를 실행한다. // 아까의 studentList에 똑같은 학생 정보 객체들을 한번 더 담는다. // enhanced-for문을 사용해 3번 단계를 다시 실행한다. // HashSet을 만들어 학생 객체들을 두 번씩 담는다. // enhanced-for문을 사용해 3번 단계를 실행한다. }
package org.study.design_patterns.singleton; public class Singleton { private Singleton singleton; private Singleton() { } public synchronized Singleton getInstance() { if (singleton != null) { singleton = new Singleton(); } return singleton; } }
package com.zihui.cwoa.system.shiro; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager){ System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 必须设置 SecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 shiroFilterFactoryBean.setLoginUrl("login"); // 登录成功后要跳转的链接 shiroFilterFactoryBean.setSuccessUrl("index"); //捕获错误页面; shiroFilterFactoryBean.setUnauthorizedUrl("error"); //拦截器. Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>(); //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 //filterChainDefinitionMap.put("/static/js/**", "anon"); filterChainDefinitionMap.put("/**", "anon"); /*filterChainDefinitionMap.put("/logoutuser", "anon"); filterChainDefinitionMap.put("/css/**", "anon"); filterChainDefinitionMap.put("/image/**", "anon"); filterChainDefinitionMap.put("/img/**", "anon"); filterChainDefinitionMap.put("js/**", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/userlogin", "anon");*/ /*filterChainDefinitionMap.put("/**", "authc");*/ shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } //异常统一处理 @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //设置realm. securityManager.setRealm(myShiroRealm()); return securityManager; } /** * 身份认证realm; * (这个需要自己写,账号密码校验;权限等) * @return */ @Bean public MyShiroRealm myShiroRealm(){ MyShiroRealm myShiroRealm = new MyShiroRealm(); // myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());; return myShiroRealm; } /** * lifecycleBeanPostProcessor是负责生命周期的 , 初始化和销毁的类 * (可选) */ @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor(){ return new LifecycleBeanPostProcessor(); } @Bean @DependsOn({"lifecycleBeanPostProcessor"}) public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){ DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); advisorAutoProxyCreator.setProxyTargetClass(true); return advisorAutoProxyCreator; } /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){ System.out.println("shiro开启AOP注解"); AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } }
package com.thread.runnable; /** * @author zhangbingquan * @version 2019年09月11日 * @since 2019年09月11日} **/ public class DefaultRunnableTest { public static void main(String[] args) throws InterruptedException { ThreadImplRunnable threadImplRunnable = new ThreadImplRunnable("Thread1"); new Thread(threadImplRunnable).start(); threadImplRunnable = new ThreadImplRunnable("Thread2"); new Thread(threadImplRunnable).start(); Thread.sleep(100); System.out.println("end"); } }
package com.cngl.bilet.service.impl; import java.util.List; import com.cngl.bilet.dto.KoltukRequestDto; import com.cngl.bilet.dto.KoltukResponseDto; import com.cngl.bilet.entity.Koltuk; import com.cngl.bilet.repository.KoltukRepository; import com.cngl.bilet.repository.SeferRepository; import com.cngl.bilet.service.KoltukService; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.springframework.stereotype.Service; @Service public class KoltukServiceImpl implements KoltukService { private final KoltukRepository koltukRepository; private final SeferRepository seferRepository; private final ModelMapper modelMapper; public KoltukServiceImpl( KoltukRepository koltukRepository, SeferRepository seferRepository, ModelMapper modelMapper) { this.koltukRepository=koltukRepository; this.seferRepository=seferRepository; this.modelMapper = modelMapper; } public List<KoltukResponseDto> tumunuGetir(){ return modelMapper.map(koltukRepository.findAll(), new TypeToken<List<KoltukResponseDto>>() {}.getType()); } public KoltukResponseDto idYeGoreGetir(Long id) throws Exception { return modelMapper. map(koltukRepository.findById(id).orElseThrow(()-> new Exception("ff")), KoltukResponseDto.class); } public KoltukResponseDto kaydet(KoltukRequestDto kullaniciRequestDto) throws Exception { Koltuk koltuk= modelMapper.map(kullaniciRequestDto,Koltuk.class); koltuk=koltugaSeferAta(koltuk,kullaniciRequestDto); return modelMapper.map(koltukRepository. save(modelMapper.map(kullaniciRequestDto,Koltuk.class)),KoltukResponseDto.class); } public KoltukResponseDto guncelle(KoltukRequestDto kullaniciRequestDto) throws Exception { Koltuk koltuk= koltukRepository.findById(kullaniciRequestDto.getId()) .orElseThrow(()->new Exception("")); koltuk=koltugaSeferAta(koltuk,kullaniciRequestDto); return modelMapper.map(koltukRepository. save(modelMapper.map(kullaniciRequestDto,Koltuk.class)),KoltukResponseDto.class); } private Koltuk koltugaSeferAta(Koltuk koltuk,KoltukRequestDto kullaniciRequestDto)throws Exception{ koltuk.setSefer(seferRepository.findById(kullaniciRequestDto.getSeferId()). orElseThrow(()->new Exception("sefer atanamadı"))); return koltuk; } public void sil(Long id) throws Exception { koltukRepository.delete( koltukRepository.findById(id).orElseThrow(()->new Exception("koltuk bulunamadı")) ); } }
package com.example.xxxxxx.androidcourse; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class SecondActivity extends AppCompatActivity { private EditText txtSecondName; private TextView txtSecondResult; private Button btnSecondClick; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); txtSecondName = findViewById(R.id.txtSecondName); txtSecondResult = findViewById(R.id.txtSecondResult); btnSecondClick = findViewById(R.id.btnSecondClick); GetIntent(); ClickSecondIntent(); } private void GetIntent() { Bundle bundle = getIntent().getExtras(); if(bundle != null){ String data = bundle.getString("data"); txtSecondResult.setText(data); txtSecondName.setText(data); } } private void ClickSecondIntent() { btnSecondClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String data = txtSecondName.getText().toString().trim(); Intent intent = new Intent(getApplicationContext(),MainActivity.class); intent.putExtra("data",data); startActivity(intent); } }); } }
package com.chaisync.AppTrojanDetector; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import android.graphics.Color; import android.view.Window; import java.lang.Runnable; import android.Manifest; import android.support.v4.content.ContextCompat; import android.support.v4.app.ActivityCompat; import android.content.pm.ApplicationInfo; import java.util.List; import java.util.zip.*; import java.io.InputStream; import java.io.IOException; import java.util.Scanner; public class MainActivity extends AppCompatActivity { private TextView appName_display; private TextView permission_display; private TextView appName2_display; private TextView permission2_display; private ImageButton appButton1; private ImageButton appButton2; private ImageButton appButton3; private ImageButton appButton4; private ImageButton appButton5; private ImageButton appButton6; private ImageButton appButton7; private ImageButton appButton8; private ImageButton appButton9; private ImageButton appButton10; private TextView detectResult_display; SharedPreferences sharedPref; Context sync_context = this; PackageManager pm0; List<ApplicationInfo> apps; int appPermissionListSize1; int appPermissionListSize2; public MainActivity(){ super(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //remove title bar //this.requestWindowFeature(Window.FEATURE_NO_TITLE); //this.setContentView(R.layout.activity_main); sharedPref = this.getSharedPreferences("com.Chaisync.sharedPref", Context.MODE_PRIVATE); appName_display = (TextView) findViewById(R.id.appname_textview); permission_display = (TextView) findViewById(R.id.permission_textview); appName2_display = (TextView) findViewById(R.id.appname2_textview); permission2_display = (TextView) findViewById(R.id.permission2_textview); detectResult_display = (TextView) findViewById(R.id.detectresult_text); // generate app manifext text pm0 = this.getPackageManager(); apps = pm0.getInstalledApplications( PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES ); /* //search tool for finding installed apps. Commented out in final build for (int i = 0; i < apps.size(); i++) { Log.d("ManifestGetter", i + ", " +apps.get(i).publicSourceDir); } */ // apps[30] = minecraft, /data/app/cynthiaJGrenier.craftingtable.minecraftguide-1/base.apk // apps[36], /data/app/com.mauriciotogneri.fileexplorer-1/base.apk // apps[141], /data/app/com.youmi.filemasterlocal-1/base.apk // whale camera = 61 // Listen for button click to fire message from client to server appButton1 = (ImageButton) findViewById(R.id.app1); appButton1.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 30; // minecraft ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box1(tempApp.className, tempApp.publicSourceDir); //Toast.makeText(sync_context, "App1", Toast.LENGTH_LONG).show(); } }); appButton6 = (ImageButton) findViewById(R.id.app6); appButton6.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ ContextCompat.checkSelfPermission(sync_context, Manifest.permission.WRITE_EXTERNAL_STORAGE); ActivityCompat.requestPermissions((Activity) sync_context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0); updateTextInfo_box2("Minecraft Crafting Guide", "/storage/emulated/0/Download/crafting-guide-for-minecraft.apk"); //Toast.makeText(sync_context, "App6", Toast.LENGTH_LONG).show(); } }); appButton2 = (ImageButton) findViewById(R.id.app2); appButton2.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 0; // 0, 30, 113 ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box1(tempApp.className, tempApp.publicSourceDir); //Toast.makeText(sync_context, "App2", Toast.LENGTH_LONG).show(); } }); appButton7 = (ImageButton) findViewById(R.id.app7); appButton7.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 0; // 0, 30, 113 ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box2("YouTube", tempApp.publicSourceDir); //Toast.makeText(sync_context, "App7", Toast.LENGTH_LONG).show(); } }); appButton3 = (ImageButton) findViewById(R.id.app3); appButton3.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 36; // File Explorer ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box1(tempApp.className, tempApp.publicSourceDir); //Toast.makeText(sync_context, "App3", Toast.LENGTH_LONG).show(); } }); appButton8 = (ImageButton) findViewById(R.id.app8); appButton8.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ ContextCompat.checkSelfPermission(sync_context, Manifest.permission.WRITE_EXTERNAL_STORAGE); ActivityCompat.requestPermissions((Activity) sync_context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0); updateTextInfo_box2("File Explorer ApkMonk", "/storage/emulated/0/Download/global.fm.filesexplorer_2016-10-08.apk"); //Toast.makeText(sync_context, "App8", Toast.LENGTH_LONG).show(); } }); appButton4 = (ImageButton) findViewById(R.id.app4); appButton4.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 141; // 61 = whale camera ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box1(tempApp.className, tempApp.publicSourceDir); //Toast.makeText(sync_context, "App4", Toast.LENGTH_LONG).show(); } }); appButton9 = (ImageButton) findViewById(R.id.app9); appButton9.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ ContextCompat.checkSelfPermission(sync_context, Manifest.permission.WRITE_EXTERNAL_STORAGE); ActivityCompat.requestPermissions((Activity) sync_context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0); updateTextInfo_box2("FileMaster ApkSum", "/storage/emulated/0/Download/com.tec.file.master-5.3.1-free-www.apksum.com.apk"); //Toast.makeText(sync_context, "App9", Toast.LENGTH_LONG).show(); } }); appButton5 = (ImageButton) findViewById(R.id.app5); appButton5.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ int currentapp = 61; // 61 = whale camera ApplicationInfo tempApp = apps.get(currentapp); updateTextInfo_box1("Whale Camera", tempApp.publicSourceDir); //Toast.makeText(sync_context, "App5", Toast.LENGTH_LONG).show(); } }); appButton10 = (ImageButton) findViewById(R.id.app10); appButton10.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ /* new Thread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { detectResult_display.setText("~~Scanning~~"); detectResult_display.setTextColor(Color.BLUE); }}); }}).start(); */ ContextCompat.checkSelfPermission(sync_context, Manifest.permission.WRITE_EXTERNAL_STORAGE); ActivityCompat.requestPermissions((Activity) sync_context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0); updateTextInfo_box2("Whale Camera ApkPure", "/storage/emulated/0/Download/Whale Camera_v3.4.3_apkpure.com.apk"); //Toast.makeText(sync_context, "App10", Toast.LENGTH_LONG).show(); } }); }; private void updateTextInfo_box1(String appName, String appDirectory){ String classname = appName; String permission_text = ""; String manifest_text = classname + "\n " + appDirectory; appName_display.setText("" + manifest_text); permission_text = getManifestData(appDirectory,1 ); permission_display.setText("" + permission_text); cleanResult(); } private void updateTextInfo_box2(String appName, String appDirectory){ String classname2 = appName; String permission_text2 = ""; String manifest_text2 = classname2 + "\n " + appDirectory; appName2_display.setText("" + manifest_text2); permission_text2 = getManifestData(appDirectory, 2); permission2_display.setText("" + permission_text2); printResult(); } //1. extract AndroidManifest.xml from app apk String getManifestData(String appDirectory, int appNumber) { String permission_text2 = ""; String[] permissionList = new String[0]; try { ZipFile apk = new ZipFile(appDirectory); ZipEntry manifest = apk.getEntry("AndroidManifest.xml"); if (manifest != null){ //2. manifest data is now stored in inputstream InputStream stream = apk.getInputStream(manifest); //3. manifest data is now stored inputstream --> scanner text Scanner s = new Scanner(stream); String result = ""; while (s.hasNext()) { result += s.next(); } //4. in scanner text, filter to remove all char except letters result = result.replaceAll("[^a-zA-Z]", ""); //Log.d("Mani0festGetter", result); //5. in filter text, look for all "andriodpermission" to find // permission requests within AndroidManifest.xml permissionList = result.split("androidpermission"); if (permissionList.length > 0) for (int i = 1; i < permissionList.length; i++){ permissionList[i] = permissionList[i].split("(?=[a-z])")[0]; //Log.d("ManifestGetter", "permisson = " + permissionList[i]); permission_text2 = permission_text2 + permissionList[i] + "\n"; } Log.d("ManifestGetter", "Manifest size = " + manifest.getSize() + ", " + result); stream.close(); } apk.close(); } catch (IOException e) { e.printStackTrace(); } if ( appNumber == 1 ) appPermissionListSize1 = permissionList.length; else appPermissionListSize2 = permissionList.length ; return permission_text2; } private void printResult(){ if (appPermissionListSize1 == appPermissionListSize2 ) { detectResult_display.setText("Clean!"); detectResult_display.setTextColor(Color.GREEN); permission2_display.setTextColor(Color.GREEN); } else { detectResult_display.setText("=!=Virus Found=!="); detectResult_display.setTextColor(Color.RED); permission2_display.setTextColor(Color.RED); } } private void cleanResult(){ detectResult_display.setText(""); appName2_display.setText(""); permission2_display.setText(""); } }
package rockPaperScissors; import java.util.Scanner; import java.util.Random; public class rockPaperScissors { public static void main(String[] args) { System.out.println("What's your hand? (rock paper scissor)"); Scanner scan = new Scanner(System.in); String userInput = scan.nextLine(); scan.close(); String computer = shoot(); System.out.println("Computer's hand is: " + computer); // debugging.... shoot correctly returns a value String winner = returnWinner(userInput, computer); // System.out.println(winner); if (winner == "tie") { System.out.println("It's a tie!"); } else System.out.println("The winner is " + winner ); } // method randomly chooses a number between 1 and 3 // method returns a String of a corresponding output public static String shoot() { Random randNumberGenerator = new Random(); int randNum = randNumberGenerator.nextInt(3); String output = null; if (randNum == 0) { output = "rock"; } if (randNum == 1) { output = "paper"; } if (randNum == 2) { output = "scissor"; } return output; } public static String returnWinner(String user, String computer) { String output = null; if (user.equals(computer)) output = "tie"; else if (user.equals("rock")) { if (computer.equals("paper")) { output = "computer"; } else output = "user"; } else if (user.equals("paper")) { if (computer.equals("rock")) { output = "computer"; } else output = "user"; } else if (user.equals("scissor")){ if (computer.equals("rock")) { output = "computer"; } else output = "user"; } System.out.println(output); return output; } }
package graph.mst; /** * 加权无向连通图的最小生成树 */ public interface MinimumSpanningTree { Iterable<Edge> edges(); double weight(); }
/* * Copyright (c) 2014 Anthony Benavente * * 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.ambenavente.origins.gameplay.world.level; /** * A layer in the map. This is where the tiles are held that are drawn * to the screen * * @author Anthony Benavente * @version 2/10/14 */ public class TiledLayer { /** * The id of the TiledMap that houses this layer */ private int parentId; /** * The width of this layer in pixels */ private int width; /** * The height of this layer in pixels */ private int height; /** * The width of an individual tile in this layer (gotten from TiledMap) */ private int tileWidth; /** * The height of an individual tile in this layer (gotten from TiledMap) */ private int tileHeight; /** * The opacity of this layer used when drawing it to the screen */ private float opacity; /** * If the layer should be drawn */ private boolean isVisible; /** * A 2D array containing each tile in the layer */ private Tile[][] tiles; /** * Creates a default layer using its parent's values and a completely * null tiles array * * @param parent The TiledMap object that owns this layer */ public TiledLayer(TiledMap parent) { this(parent, new Tile[parent.getHeight()][parent.getHeight()]); } /** * Creates a layer with a given map * * @param parent The TiledMap object that owns this layer * @param map The array of tiles to set to this layer's tiles */ public TiledLayer(TiledMap parent, Tile[][] map) { this.parentId = parent.getId(); this.width = parent.getWidth(); this.height = parent.getHeight(); this.tileWidth = parent.getTileWidth(); this.tileHeight = parent.getTileHeight(); this.tiles = map.clone(); } /** * @return All the tiles in this layer */ public Tile[][] getTiles() { return tiles; } /** * @return The width of this layer in tiles (gotten from TiledMap) * @see TiledMap */ public int getWidth() { return width; } /** * @return The height of this layer in tiles (gotten from TiledMap) * @see TiledMap */ public int getHeight() { return height; } /** * @return The width of an individual tile in this layer * (gotten from TiledMap) * @see TiledMap */ public int getTileWidth() { return tileWidth; } /** * @return The height of an individual tile in this layer * (gotten from TiledMap) * @see TiledMap */ public int getTileHeight() { return tileHeight; } /** * Gets a specific tile at a given point * * @param x The x coordinate position to get the tile from * @param y The y coordinate position to get the tile from * @return The tile at the given coordinates. If the x or y is out of * bounds, the function throws an IndexOutOfBoundsException * @throws java.lang.IndexOutOfBoundsException */ public Tile getTile(int x, int y) { if (x >= 0 && x < width && y >= 0 && y < height) { return tiles[y][x]; } else { throw new IndexOutOfBoundsException(); } } /** * @return If the graphics object should draw this layer */ public boolean isVisible() { return isVisible; } /** * Sets if the graphics object can draw this layer aka if the layer is * visible * * @param isVisible True if the layer should be drawn, false otherwise */ public void setVisible(boolean isVisible) { this.isVisible = isVisible; } /** * @return The opacity of the layer, used when drawing it. The scale goes * from 0.0 being invisible to 1.0 being completely visible */ public float getOpacity() { return opacity; } /** * Sets the opacity of this layer * * @param opacity The opacity used when drawing this layer. This function * clamps this parameter between 0.0 and 1.0 */ public void setOpacity(float opacity) { this.opacity = (float) Math.min(1.0, Math.max(0.0, opacity)); } }
package controllers; import java.sql.Connection; import java.sql.SQLException; import play.db.DB; import play.mvc.*; import org.libvirt.*; import model.Host; import com.fasterxml.jackson.databind.JsonNode; public class VMOperation extends Controller{ public static Result start(String vmName, String hostName) { try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } if(vm.create()==0){ return ok("started"); } else { return ok("Failed to start"); } } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to start"); } } public static Result shutdown(String vmName, String hostName) { try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } if(vm.isActive()==1){ vm.shutdown(); return ok("shutdown signal sent"); } else return badRequest("vm is not running."); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to shutdown"); } } //for following op check for the flags public static Result reboot(String vmName,String hostName) { try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } if(vm.isActive()==1){ vm.reboot(0); return ok("rebooted"); } else return badRequest("vm is not running."); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to reboot"); } } public static Result destroy(String vmName, String hostName) { try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } vm.destroy(); return ok("destroyed"); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to destroy"); } } public static Result suspend(String vmName, String hostName){ try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null) return notFound("No vm "+vmName+" found on host"+hostName+"."); if(vm.isActive()==1){ vm.suspend(); return ok("suspended"); } else return badRequest("vm is not running."); } catch (LibvirtException e) { return internalServerError(e.getMessage()); } } public static Result resume(String vmName, String hostName){ try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } vm.resume(); return ok("resumed"); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Opps unable to resume"); } } public static Result delete(String vmName, String hostName) { try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); if(vm==null){ return notFound("No vm "+vmName+" found on host"+hostName+"."); } vm.undefine(3); return ok("deleted"); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to Delete"); } } public static Result save(String vmName, String hostName) { try { String to=new String(); Host tempHost=new Host(hostName); tempHost.conn.domainLookupByName(vmName).save(to); Connection dbConn=DB.getConnection(); dbConn.close(); return ok("saved"); } catch (LibvirtException e) { e.printStackTrace(); return internalServerError("Oops unable to save domain"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return internalServerError("Oops database server connectivity error"); } } public static Result snapshot(String vmName, String hostName){ try { String xmlDesc=new String("<domainsnapshot>"); JsonNode json=request().body().asJson(); String name = json.findPath("Name").textValue(); if(name != null) { xmlDesc=xmlDesc.concat("<name>"+name+"</name>"); } String description = json.findPath("Description").textValue(); if(description != null) { xmlDesc=xmlDesc.concat("<name>"+description+"</name>"); } xmlDesc=xmlDesc.concat("</domainsnapshot>"); Host tempHost=new Host(hostName); DomainSnapshot domSnap=tempHost.conn.domainLookupByName(vmName).snapshotCreateXML(xmlDesc); if(domSnap!=null){ return ok("snapshot created"); } else { return ok("Opps unable to create snapshot"); } } catch (LibvirtException e) { // TODO Auto-generated catch block e.printStackTrace(); return internalServerError("Opps connection error"); } } public static Result revert(String vmName, String hostName, String snapshot){ try { Host tempHost=new Host(hostName); Domain vm=tempHost.conn.domainLookupByName(vmName); DomainSnapshot vmSnap=vm.snapshotLookupByName(snapshot); if(vmSnap==null) return notFound("Sanpshot "+snapshot+"not found."); if(vm.revertToSnapshot(vmSnap)==0){ return ok("Successful revert"); }else { return ok("Unsuccessful revert"); } } catch (LibvirtException e) { // TODO Auto-generated catch block e.printStackTrace(); return internalServerError("Opps unable to revert"); } } }
package enthu_f; public class e_1321 { public static void main( String[] args){ try{ int i = 0; i = Integer.parseInt( args[0] ); } catch(NumberFormatException e){ System.out.println("Problem in " + i ); } } }
package org.fuserleer.crypto; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MerkleTree { private MerkleNode root; private List<MerkleNode> nodes; private List<MerkleNode> leaves; public MerkleTree() { this.nodes = new ArrayList<>(); this.leaves = new ArrayList<>(); } public List<MerkleNode> getLeaves() { return this.leaves; } public List<MerkleNode> getNodes() { return this.nodes; } public MerkleNode getRoot() { return this.root; } public MerkleNode appendLeaf(MerkleNode node) { this.nodes.add(node); this.leaves.add(node); return node; } public void appendLeaves(MerkleNode[] nodes) { for (MerkleNode node : nodes) this.appendLeaf(node); } public MerkleNode appendLeaf(Hash hash) { return this.appendLeaf(new MerkleNode(hash)); } public List<MerkleNode> appendLeaves(Hash[] hashes) { List<MerkleNode> nodes = new ArrayList<>(); for (Hash hash : hashes) nodes.add(this.appendLeaf(hash)); return nodes; } public List<MerkleNode> appendLeaves(Collection<Hash> hashes) { List<MerkleNode> nodes = new ArrayList<>(); for (Hash hash : hashes) nodes.add(this.appendLeaf(hash)); return nodes; } public Hash addTree(MerkleTree tree) { if (this.leaves.size() <= 0) throw new IllegalStateException("Cannot add to a tree with no leaves!"); tree.leaves.forEach(this::appendLeaf); return this.buildTree(); } public Hash buildTree() { if (this.leaves.size() <= 0) throw new IllegalStateException("Cannot add to a tree with no leaves!"); buildTree(this.leaves); return this.root.getHash(); } public void buildTree(List<MerkleNode> nodes) { if (nodes.size() <= 0) throw new IllegalStateException("Node list not expected to be empty!"); if (nodes.size() == 1) { this.root = nodes.get(0); } else { List<MerkleNode> parents = new ArrayList<>(); for (int i = 0; i < nodes.size(); i += 2) { MerkleNode right = (i + 1 < nodes.size()) ? nodes.get(i + 1) : null; MerkleNode parent = new MerkleNode(nodes.get(i), right); parents.add(parent); } buildTree(parents); } } public List<MerkleProof> auditProof(Hash leafHash) { List<MerkleProof> auditTrail = new ArrayList<>(); MerkleNode leafNode = findLeaf(leafHash); if (leafNode != null) { if (leafNode.getParent() == null) throw new IllegalStateException("Expected leaf to have a parent!"); MerkleNode parent = leafNode.getParent(); buildAuditTrail(auditTrail, parent, leafNode); } return auditTrail; } public static boolean verifyAudit(Hash rootHash, Hash leafHash, List<MerkleProof> auditTrail) { if (auditTrail.size() <= 0) throw new IllegalStateException("Audit trail cannot be empty!"); Hash testHash = leafHash; for (MerkleProof auditHash : auditTrail) testHash = auditHash.direction.equals(MerkleProof.Branch.RIGHT) ? new Hash(testHash, auditHash.hash, Hash.Mode.STANDARD) : new Hash(auditHash.hash, testHash, Hash.Mode.STANDARD); return testHash.equals(rootHash); } private MerkleNode findLeaf(Hash hash) { return this.leaves.stream().filter((leaf) -> leaf.getHash().equals(hash)).findFirst().orElse(null); } private void buildAuditTrail(List<MerkleProof> auditTrail, MerkleNode parent, MerkleNode child) { if (parent != null) { if (child.getParent() != parent) throw new IllegalStateException("Parent of child is not expected parent!"); MerkleNode nextChild = parent.getLeftNode().equals(child) ? parent.getRightNode() : parent.getLeftNode(); MerkleProof.Branch direction = parent.getLeftNode().equals(child) ? MerkleProof.Branch.RIGHT : MerkleProof.Branch.LEFT; if (nextChild != null) auditTrail.add(new MerkleProof(nextChild.getHash(), direction)); buildAuditTrail(auditTrail, parent.getParent(), child.getParent()); } } }
package com.springrest.springrest.controller; import com.springrest.springrest.entities.Course; import com.springrest.springrest.services.CourseService; import com.springrest.springrest.services.CourseServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class MyController { @Autowired public CourseService CourseService; /*@GetMapping("/home") public String home(){ this is for test return "this is my home page"; }*/ //get the courses @GetMapping("/courses") public List<Course> getCourses() { return this.CourseService.getCourses(); } @GetMapping("/courses/{courseId}") public Course getCourse(@PathVariable String courseId) { return this.CourseService.getCourse(Long.parseLong(courseId)); } @PostMapping("/course") public Course addCourse(@RequestBody Course course) { return this.CourseService.addCourse(course); } }
package com.simon.common.sorts; /** * Created by semen on 27.09.2015. */ public class Sort { //public abstract static int[] sort(int[] a); public static void print(int[] a){ System.out.print("[ "); for(int x: a){ System.out.print(x+" "); } System.out.print("]"); } static void swap(int[]a, int i, int j){ if (a[i]!=a[j]){ int c = a[i]; a[i] = a[j]; a[j] = c; } } }
package ru.rost; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; /** * @author rost. */ @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationMainTest { @Test @Ignore public void contextLoads() { } }
package com.Exercises_12032021.Task2.Services; import com.Exercises_12032021.Task2.Domain.PerfectNumber; import java.util.ArrayList; import java.util.List; public class PerfectNumberService { private CustomRandomService customRandomService; private List<Integer> seriesOfNumbersToProceed; private List<PerfectNumber> perfectNumbers; private float percentOfPn; public PerfectNumberService() { this.customRandomService = new CustomRandomService(); this.seriesOfNumbersToProceed = new ArrayList<>(); this.percentOfPn = 0; this.perfectNumbers = new ArrayList<>(); } public void start() { startMessage(); this.seriesOfNumbersToProceed = this.customRandomService.generateRandomNumbersSeries(); startInfoMessage(); generatingInfoMessage(); checkForPerfectNumbers(); calculatePercent(); summaryInfoMessage(); } private void checkForPerfectNumbers() { for(Integer i : this.seriesOfNumbersToProceed) { PerfectNumber pn = new PerfectNumber(i); if(pn.isPerfect()) { this.perfectNumbers.add(pn); } } } private void calculatePercent() { int totalPn = this.perfectNumbers.size(); if (totalPn > 0 & this.seriesOfNumbersToProceed.size() > 0) { this.percentOfPn = ((float)totalPn * 100) / this.seriesOfNumbersToProceed.size(); } } private void startMessage() { System.out.println("Starting perfect number calculator."); } private void startInfoMessage() { System.out.println("Total numbers to proceed: " + seriesOfNumbersToProceed.toString()); } private void generatingInfoMessage() { System.out.println("Generating..."); } private void summaryInfoMessage() { String summaryMessage = """ There are (%d) perfect numbers and they are (%.2f %%) of total numbers. """; System.out.println(String.format(summaryMessage, this.perfectNumbers.size(), this.percentOfPn)); } }
package com.avantir.qrcode.scheme; public class EMV { public static void main(String[] args){ try{ } catch(Exception ex){ ex.printStackTrace(); } } /* @Override public Schema parseSchema(String code) { if (code == null || !code.startsWith(PAYLOAD_FORMAT_INDICATOR)) { throw new IllegalArgumentException("this is not a valid EMV QR code: " + code); } Map<String, String> parameters = getParameters(code); if (parameters.containsKey(NAME)) { setName(parameters.get(NAME)); } if (parameters.containsKey(TITLE)) { setTitle(parameters.get(TITLE)); } if (parameters.containsKey(COMPANY)) { setCompany(parameters.get(COMPANY)); } if (parameters.containsKey(ADDRESS)) { setAddress(parameters.get(ADDRESS)); } if (parameters.containsKey(EMAIL)) { setEmail(parameters.get(EMAIL)); } if (parameters.containsKey(WEB)) { setWebsite(parameters.get(WEB)); } if (parameters.containsKey(PHONE)) { setPhoneNumber(parameters.get(PHONE)); } if (parameters.containsKey(NOTE)) { setNote(parameters.get(NOTE)); } return this; } @Override public String generateString() { StringBuilder sb = new StringBuilder(); sb.append(BEGIN_VCARD).append(LINE_FEED); sb.append("VERSION:3.0").append(LINE_FEED); if (name != null) { sb.append(NAME).append(":").append(name); } if (company != null) { sb.append(LINE_FEED).append(COMPANY).append(":").append(company); } if (title != null) { sb.append(LINE_FEED).append(TITLE).append(":").append(title); } if (phoneNumber != null) { sb.append(LINE_FEED).append(PHONE).append(":").append(phoneNumber); } if (website != null) { sb.append(LINE_FEED).append(WEB).append(":").append(website); } if (email != null) { sb.append(LINE_FEED).append(EMAIL).append(":").append(email); } if (address != null) { sb.append(LINE_FEED).append(ADDRESS).append(":").append(address); } if (note != null) { sb.append(LINE_FEED).append(NOTE).append(":").append(note); } sb.append(LINE_FEED).append("END:VCARD"); return sb.toString(); } public static Map<String, String> getParameters(final String qrCode) { Map<String, String> result = new LinkedHashMap<>(); BerTag TAG_E0 = new BerTag(0xe0); String[] parts = qrCode.split(paramSeparator); for (int i = 0; i < parts.length; i++) { String[] param = parts[i].split(keyValueSeparator); if (param.length > 1) { result.put(param[0], param[1]); } } return result; } */ /** * Returns the textual representation of this vcard of the form * <p> * BEGIN:VCARD N:John Doe ORG:Company TITLE:Title TEL:1234 URL:www.example.org * EMAIL:john.doe@example.org ADR:Street END:VCARD * </p> */ /* public String toString() { return generateString(); } public EMV parse(final String code) { parseSchema(code); return this; } */ public class additionalData{ } public class merchantInformationLanguage{ } }
package com.app.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.app.pojos.EmailData; import com.app.util.Email; import com.fasterxml.jackson.databind.ObjectMapper; @RestController @RequestMapping("/email") public class EmailController { Logger logger = LoggerFactory.getLogger(TeacherController.class); public EmailController() { System.out.println("Email Controller const"); } @PostMapping(value="/sendEmail") @CrossOrigin(origins = "http://localhost:4200") public ResponseEntity<?> sendEmail(@RequestParam String emailData){ String recipient = "kparanav@gmail.com"; logger.info("sending email...."+emailData); try { ObjectMapper mapper = new ObjectMapper(); EmailData emailData1 = mapper.readValue(emailData, EmailData.class); Email.sendMail(emailData1, recipient); logger.info("emailSent"); }catch (Exception e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } return new ResponseEntity<>(HttpStatus.OK); } }
package com.tb24.fn.model; public class Affiliate { public String id; public String slug; public String displayName; public String status; public Boolean verified; }
package com.tencent.mm.ui.conversation.a; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.tencent.mm.R; import com.tencent.mm.pluginsdk.h.a.a; import com.tencent.mm.ui.r; import java.util.ArrayList; public final class b extends r<c> { private ArrayList<c> eWc = new ArrayList(); a urM = null; public final /* bridge */ /* synthetic */ Object a(Object obj, Cursor cursor) { return null; } public b(Context context) { super(context, null); WS(); } protected final void WS() { WT(); } public final void WT() { this.eWc.clear(); if (this.urM != null) { this.eWc.add(new c(this.urM)); notifyDataSetChanged(); } } public final int getCount() { return this.eWc.size(); } /* renamed from: FV */ public final c getItem(int i) { return (c) this.eWc.get(i); } public final View getView(int i, View view, ViewGroup viewGroup) { d dVar; c cVar = (c) this.eWc.get(i); if (view == null) { view = View.inflate(this.context, R.i.adlist_item, null); d dVar2 = new d(); dVar2.urO = view; dVar2.urP = (Button) view.findViewById(R.h.ad_close); view.setTag(dVar2); dVar = dVar2; } else { dVar = (d) view.getTag(); } if (cVar.a(dVar) != 0) { return null; } return view; } }
package gxc.web.filter; import gxc.utils.HibernateUtil; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.hibernate.Session; public class TransactionFilter implements Filter{ @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //获取当前线程的session Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); try{ chain.doFilter(request, response); if(session!=null && session.isOpen()){ session.getTransaction().commit(); } }catch(Exception e){ e.printStackTrace(); if(session!=null && session.isOpen()){ session.getTransaction().rollback(); } } } @Override public void init(FilterConfig arg0) throws ServletException { } }
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static int[] S; public static void main (String [] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int len = Integer.parseInt(br.readLine()); S = new int [len + 1]; StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 1; i <= len; i++) { S[i] = Integer.parseInt(st.nextToken()); } int human = Integer.parseInt(br.readLine()); for (int i = 0; i < human; i++) { st = new StringTokenizer(br.readLine()); int gender = Integer.parseInt(st.nextToken()); int number = Integer.parseInt(st.nextToken()); // 남자의 경우 if (gender == 1) { for (int j = number; j <= len; j += number) { S[j] = S[j] == 1 ? 0 : 1; } } // 여자의경우 else { if ((number == 1 || number == len) || S[number - 1] != S[number + 1]) { S[number] = S[number] == 1 ? 0 : 1; } else { int left = number - 1; int right = number + 1; S[number] = S[number] == 1 ? 0 : 1; while (left > 0 && right <= len) { if (S[left] == S[right]) { S[left] = S[left] == 1 ? 0 : 1; S[right] = S[right] == 1 ? 0 : 1; --left; ++right; } else { break; } } } } } for (int i = 1; i <= len; i++) { System.out.print(S[i] + " "); if (i % 20 == 0) { System.out.println(); } } } }
package com.mediacom.tools; import javax.net.ssl.X509TrustManager; import java.security.cert.X509Certificate; public class DummyTrustmanager implements X509TrustManager { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0,String arg1) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0,String arg1) throws java.security.cert.CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } }
import java.util.ArrayList; import java.util.List; import com.leetcode.listnode.ListNode; import com.leetcode.listnode.ListNodeUtil; public class App { public static void main(String[] args) throws Exception { System.out.println("Hello, World!"); } }
import java.util.*; public class Example // All operands function between two numbers { public static void main(String[] args) { //prompt the user to enter names of all operands System.out.print("* Addition \n" ); System.out.print("* Subtraction\n"); System.out.print("* Multiplication\n"); System.out.print("* Division\n"); System.out.print("* modula\n"); System.out.print("* Squared\n"); System.out.print("* cubed\n"); // Create a scanner object Scanner input = new Scanner(System.in); System.out.println("Please enter in a calculation option:\n"); int number1 = input.nextInt(); int number2 = input.nextInt(); //Compute sum int sum = number1 + number2 ; //Compute difference int difference = number1 - number2 ; //Compute product int product = number1 * number2 ; //Compute quotient int quotient = number1 / number2 ; // Compute remainder int remainder = number1 % number2 ; // Compute square root double root = (Math.sqrt(number1)); // compute cube root double croot = (number2 )* 0.333 ; // Display result System.out.println("\n The sum of firstnumber " +number1 + " and second number " +number2 + " is " + sum ); System.out.println(" \n The difference of firstnumber " +number1 +" and second number " +number2 + " is " + difference); System.out.println(" \n The product of firstnumber " +number1 +" and secondnumber " +number2 + " is "+ product ); System.out.println("\n The quotient of firstnumber " +number1 + " and secondnumber " +number2 + " is " + quotient); System.out.println("\n The remainder of firstnumber " +number1 + " and secondnumber " +number2 + " is " + remainder); System.out.println("\n The square root of firstnumber " +number1+ " is : " +root); System.out.println("\n The cube root of secondnumber " +number2+ " is :" +croot); } }
package shapes.line; import java.awt.*; public class Segment extends base.Shape { private Point endPoint; public Segment() { } public Segment(Point theCenter, Point endPoint, int frameWidth, Color frameColor) { super(theCenter, frameWidth, frameColor); this.endPoint = endPoint; } @Override public void draw(Graphics2D g) { Point startPoint = getLocation(); g.setStroke(new BasicStroke(getFrameWidth())); g.setColor(getFrameColor()); g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y); } @Override public boolean contains(Point pt) { Point theCenter = getLocation(); int a = endPoint.y - theCenter.y; int b = endPoint.x - theCenter.x; double d = (a * pt.x - b * pt.y + b * theCenter.y - a * theCenter.x) / (Math.sqrt(a * a + b * b)); return Math.abs(d) < getFrameWidth() / 2; } @Override public void move(Point pt) { Point theCenter = getLocation(); setEndPoint(new Point(getEndPoint().x + pt.x - theCenter.x, getEndPoint().y + pt.y - theCenter.y)); super.move(pt); } public Point getEndPoint() { return endPoint; } public void setEndPoint(Point endPoint) { setEndPoint(endPoint, false); } public void setEndPoint(Point endPoint, boolean smooth) { if (!smooth) this.endPoint = endPoint; else { Point theCenter = getLocation(); if (Math.abs(theCenter.x - endPoint.x) < Math.abs(theCenter.y - endPoint.y)) this.endPoint = new Point(theCenter.x, endPoint.y); else this.endPoint = new Point(endPoint.x, theCenter.y); } } }
package com.zhouyi.business.dto; import java.io.Serializable; /** * @author 李秸康 * @ClassNmae: LedenBbsAttachmentDto * @Description: TODO * @date 2019/6/25 14:06 * @Version 1.0 **/ public class LedenBbsAttachmentDto extends BaseDto implements Serializable { private String pkId; private String bbsId; private String filename; private String fileurl; private String filesize; private String filetype; private String deletag; public String getPkId() { return pkId; } public void setPkId(String pkId) { this.pkId = pkId; } public String getBbsId() { return bbsId; } public void setBbsId(String bbsId) { this.bbsId = bbsId; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String getFileurl() { return fileurl; } public void setFileurl(String fileurl) { this.fileurl = fileurl; } public String getFilesize() { return filesize; } public void setFilesize(String filesize) { this.filesize = filesize; } public String getFiletype() { return filetype; } public void setFiletype(String filetype) { this.filetype = filetype; } public String getDeletag() { return deletag; } public void setDeletag(String deletag) { this.deletag = deletag; } }
package cn.amarone.model.user.service; import org.springframework.data.domain.Page; import cn.amarone.model.sys.common.exception.BizException; import cn.amarone.model.article.entity.Article; import cn.amarone.model.user.entity.SysUser; /** * @Description: * @Author: Amarone * @Created Date: 2019年03月26日 * @LastModifyDate: * @LastModifyBy: * @Version: */ public interface ISysUserService { /** * 校验用户信息 * * @param userInfo 用户信息 * @return Returns true if it exists * @description loginName must be not null<br/> passwd 必须得是密文 */ SysUser verifyAcc(SysUser userInfo) throws BizException; /** * 根据用户id获取用户信息 */ SysUser getAccInfo(Long userId) throws BizException; void getAccInfo(Article articleInfo) throws BizException; void getAccInfo(Page<Article> pageInfo) throws BizException; }
package com.elepy.handlers; import com.elepy.dao.Crud; import com.elepy.exceptions.ElepyException; import com.elepy.exceptions.Message; import com.elepy.http.HttpContext; import com.elepy.http.Request; import com.elepy.models.ModelContext; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.Serializable; /** * A helper class for developers to easily handle the update of objects. * * @param <T> the model you're updating * @see com.elepy.annotations.Update * @see DefaultUpdate * @see UpdateHandler */ public abstract class SimpleUpdate<T> extends DefaultUpdate<T> { @Override public void handleUpdatePut(HttpContext context, Crud<T> dao, ModelContext<T> modelContext, ObjectMapper objectMapper) throws Exception { final Serializable id = context.modelId(); final T before = dao.getById(id).orElseThrow(() -> new ElepyException("This item doesn't exist and therefor can't be updated")); T updatedObjectFromRequest = updatedObjectFromRequest(before, context.request(), objectMapper, modelContext.getModel()); beforeUpdate(before, updatedObjectFromRequest, context.request(), dao); final T updated = update( updatedObjectFromRequest, modelContext, modelContext.getObjectEvaluators(), modelContext.getModel()); afterUpdate(before, updated, dao); context.response().status(200); context.response().result(Message.of("Successfully updated item", 200)); } @Override public void handleUpdatePatch(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) throws Exception { super.handleUpdatePut(context, crud, modelContext, objectMapper); } /** * What happens before you update a model. Throw an exception to cancel the update. * * @param beforeVersion The object before the update * @param crud The crud implementation * @throws Exception you can throw any exception and Elepy handles them nicely. * @see ElepyException * @see com.elepy.exceptions.ElepyErrorMessage */ public abstract void beforeUpdate(T beforeVersion, T updatedVersion, Request httpRequest, Crud<T> crud) throws Exception; /** * What happens after you update a model. * * @param beforeVersion The object before the update * @param updatedVersion The object after the update * @param crud The crud implementation */ public abstract void afterUpdate(T beforeVersion, T updatedVersion, Crud<T> crud); }