text stringlengths 10 2.72M |
|---|
/**
*
*/
package com.wonders.task.todoItem.model.vo;
/**
* @ClassName: UserIndo
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2013-1-22 下午02:15:01
*
*/
public class UserInfo {
private String userId;
private String loginName;
private String userName;
private String deptId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDeptId() {
return deptId;
}
public void setDeptId(String deptId) {
this.deptId = deptId;
}
}
|
/* */ package com.ketonix.ketonixpro;
/* */
/* */ import java.io.PrintStream;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ class CalibrationThread
/* */ implements Runnable
/* */ {
/* */ KSync ksync;
/* */ CalibrateDialog gui;
/* */
/* */ public CalibrationThread(CalibrateDialog cd, KSync ks)
/* */ {
/* 21 */ this.ksync = ks;
/* 22 */ this.gui = cd;
/* */ }
/* */
/* */ public void run()
/* */ {
/* 27 */ int value = 0;int old_value = -1;int diff = 0;int hits = 0;int progress = 0;int precision = 3;int calibrationHits = 60;
/* 28 */ precision = this.ksync.precision();
/* 29 */ calibrationHits = this.ksync.calibrationHits();
/* 30 */ while (!this.gui.stopCalibrating)
/* */ {
/* */ try {
/* 33 */ Thread.sleep(700L);
/* */ } catch (Exception ex) {
/* 35 */ System.err.println(ex.toString());
/* */ }
/* 37 */ value = this.ksync.current_raw;
/* 38 */ if (old_value == -1) {
/* 39 */ old_value = value;
/* 40 */ System.out.println(old_value);
/* */ }
/* */ else
/* */ {
/* 44 */ diff = value - old_value;
/* 45 */ if (diff < 0) { diff *= -1;
/* */ }
/* 47 */ if (diff <= precision) {
/* 48 */ System.out.println("hits++ = " + hits);
/* */
/* 50 */ hits++;
/* */ } else {
/* 52 */ hits = 0;
/* 53 */ old_value = value;
/* 54 */ System.out.println("diff = " + diff + " => hits = " + hits);
/* */ }
/* 56 */ if (hits == 100) {
/* 57 */ System.out.println("hits = " + hits + " => calibration finished, set to " + value);
/* 58 */ this.gui.setProgress(100, 100);
/* */
/* 60 */ this.gui.setCalibration(value);
/* 61 */ this.gui.finishedCalibrating();
/* 62 */ this.gui.stopCalibrating = true;
/* 63 */ return;
/* */ }
/* */
/* 66 */ progress = progress < hits ? hits : progress;
/* 67 */ if (!this.gui.stopCalibrating)
/* 68 */ this.gui.setProgress(progress, 100);
/* */ }
/* */ }
/* 71 */ System.out.println("calibrateThread exit");
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/com/ketonix/ketonixpro/CalibrationThread.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ |
package ch14.ex14_03;
public class Test implements Runnable {
private Main obj;
Test(Main obj) {
this.obj = obj;
}
public void run() {
try {
for (;;) {
obj.add(5);
Thread.sleep(10);
}
} catch (InterruptedException e) {
return;
}
}
}
|
package exhaustiveSearch;
import java.util.ArrayList;
import java.util.Arrays;
public class PermutaionsII2 {
public static ArrayList<ArrayList<Integer>> permuteUnique2list(int[] nums) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (nums == null || nums.length == 0) {
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
// the default value for a boolean (primitive) is false.
permuteUnique2Helper(result, list, nums, visited);
return result;
}
public static void permuteUnique2Helper(
ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list,
int[] nums, boolean[] visited) {
if (list.size() == nums.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i]
|| (i > 0 && nums[i] == nums[i - 1] && !visited[i - 1])) {
// visited[i]: if nums[i] was visited already, skip
// i>0 && nums[i]==nums[i-1] && !visited[i-1]):
continue;
}
list.add(nums[i]);
visited[i] = true;
permuteUnique2Helper(result, list, nums, visited);
visited[i] = false;
list.remove(list.size() - 1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] source = { 1, 2, 2 };
System.out
.println("the final result is: " + permuteUnique2list(source));
}
}
|
package com.frankinz.disablewheel;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.MouseEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.event.RegistryEvent;
@Mod(
modid = DisableWheel.MOD_ID,
name = DisableWheel.MOD_NAME,
version = DisableWheel.VERSION
)
public class DisableWheel {
public static final String MOD_ID = "disablewheel";
public static final String MOD_NAME = "DisableWheel";
public static final String VERSION = "1.12";
/**
* This is the instance of your mod as created by Forge. It will never be null.
*/
@Mod.Instance(MOD_ID)
public static DisableWheel INSTANCE;
/**
* This is the second initialization event. Register custom recipes
*/
@Mod.EventHandler
public void init(FMLInitializationEvent event) {
// Register the event handler
MinecraftForge.EVENT_BUS.register(new MyMouseEventHandler());
}
/**
* The mouse event handler
*/
class MyMouseEventHandler{
@SubscribeEvent
public void mouseClickd(MouseEvent event){
if (event.getButton() == -1){
event.setCanceled(true);
}
}
}
}
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting.plotobject;
import javax.swing.ImageIcon;
/**
* Created by dodge1 Date: Mar 31, 2010
*/
public class MarginButtonIconGroup {
private final ImageIcon[] images;
public MarginButtonIconGroup(ImageIcon image0, ImageIcon image1, ImageIcon image2, ImageIcon image3) {
images = new ImageIcon[4];
images[0] = image0;
images[1] = image1;
images[2] = image2;
images[3] = image3;
}
public ImageIcon getIcon(int idx) {
return images[idx];
}
}
|
package test.main;
/*
* 1. 산술 연산자 테스트
*
* +, -, *, /, %
*/
public class MainClass01 {
public static void main(String[] args) {
int num1=5;
int num2=2;
// + 연산하기
int sum=10+1;
int sum2=num1+num2;
int sum3=10+num2;
//정수끼리 연산하면 결과는 정수만 나온다.
int result1=5/3;
int result2=num1/num2;
//연산의 결과로 실수 값을 얻어내고 싶으면 적어도 하나는 실수여야 한다.
double result3=5/3.0;
double result4=num1/(double)num2;
//앞에 있는 수를 뒤에 있는 수로 나눈 나머지 값을 얻어낸다.
int result5=num1%num2;
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class PROG_더맵게 {
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int[] scoville = {1, 2, 3, 9, 10, 12};
int K =7;
System.out.println(solution(scoville, K));
}
public static int solution(int[] scoville, int K) {
int answer = 0;
Arrays.sort(scoville);
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int i = 0; i < scoville.length; i++) {
pq.offer(scoville[i]);
}
while(true) {
if(pq.size() == 1) {
answer = -1;
break;
}
int s1 = pq.poll();
int s2 = pq.poll();
pq.offer(s1+(s2*2));
answer++;
if(pq.peek() >= K) break;
}
return answer;
}
}
|
/**
* Fragment and UI related classes.
*/
package eu.tivian.musico.ui; |
package com.jim.multipos.ui.start_configuration.payment_type;
import android.support.v4.app.Fragment;
import com.jim.multipos.config.scope.PerFragment;
import dagger.Binds;
import dagger.Module;
@Module(includes = PaymentTypePresenterModule.class)
public abstract class PaymentTypeFragmentModule {
@Binds
@PerFragment
abstract Fragment provideFragment(PaymentTypeFragment fragment);
@Binds
@PerFragment
abstract PaymentTypeView providePaymentTypeView(PaymentTypeFragment fragment);
}
|
package Index.Action;
import Base.Date.DateBase;
import Index.Date.*;
import Index.Model.*;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.catalina.connector.Request;
import org.apache.catalina.deploy.LoginConfig;
import com.sun.crypto.provider.RSACipher;
public class LoginAction extends HttpServlet {
private static final long serialVersionUID = 1L;
PreparedStatement sql;
HttpSession session;
StudentDate stuDate;
ResultSet result;
String user;
String pass;
String id;
Connection con;
String name;
int power;
StudentModel student=new StudentModel();
public LoginAction() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
session=request.getSession(true);
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
stuDate=new StudentDate();
user=request.getParameter("user");
pass=request.getParameter("pass");
String jiaose=request.getParameter("jiaose");
DateBase date=new DateBase();
date.connect();
if(jiaose.equals("2")){
String str="SELECT * FROM user WHERE user='"+user+"'AND password='"
+pass+"'";
result=date.find(str);
boolean m=false;
try{
m=result.next();
if(m==true){
power=result.getInt("power");
session.setAttribute("adminName", result.getString("name"));
session.setAttribute("user", user);
session.setAttribute("power", power);
if(power==3)
response.sendRedirect("./admin/index.jsp");
else if(power==2){
response.sendRedirect("./teacher/index.jsp");
}
}else{
session.setAttribute("user",null);
session.setAttribute("info","用户不存在或密码错误");
response.sendRedirect("index.jsp");
}
}catch(Exception e){
}
}else if(jiaose.equals("1")){
StudentDate stuDate=new StudentDate();
session.setAttribute("student", student);
try{
//学生登录验证
boolean m=login(user,pass);
if(m==true){
response.sendRedirect("./student/index.jsp");
}else{
response.sendRedirect("index.jsp");
}
}catch(Exception e)
{
}
}
}
public boolean login(String user,String pass){
boolean m=false;
try{
result=stuDate.cheak(user, pass);
student.setResult(result);
student.setNumber(user);
m=result.next();
if(m==true){
String class_id=result.getString(6);
id=result.getString(1);
session.setAttribute("user", user);
session.setAttribute("power", "1");
session.setAttribute("class_id", class_id);
session.setAttribute("state", "-1");
}else{
session.setAttribute("user",null);
session.setAttribute("info","用户不存在或密码错误");
}
}catch(Exception e){
}
return m;
}
}
|
package model;
public final class TC {
public static final String TABLE="user1.tc";
public static final String AYEAR="Ayear";
public static final String SEMESTER="Semester";
public static final String T_ID="T_id";
public static final String C_ID="C_id";
public static final String RATING="Rating";
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package builder;
import bridge.AlgoritamDodavanjaEmisija1;
import bridge.AlgoritamDodavanjaEmisija2;
import bridge.AlgoritamDodavanjaEmisija3;
import bridge.DodavanjeEmisijaSucelje;
import prototype.Emisija;
import anikolic_zadaca_2.Osoba;
import composite.RasporedTvKuce;
import anikolic_zadaca_2.Uloga;
import anikolic_zadaca_2.Vrsta;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* @author Ana
*/
public class DirektorGraditeljaRasporeda {
private Map<Integer, Osoba> osobe;
private Map<Integer, Uloga> uloge;
private Map<Integer, Vrsta> vrste;
private Map<Integer, Emisija> sveEmisije;
private List<List<String>> podaciPrograma;
private GradiRaspored gradiRaspored;
public DirektorGraditeljaRasporeda() {
}
public DirektorGraditeljaRasporeda(Map<Integer, Osoba> osobe, Map<Integer, Uloga> uloge,
Map<Integer, Vrsta> vrste, Map<Integer, Emisija> sveEmisije, List<List<String>> podaciPrograma) {
this.osobe = osobe;
this.uloge = uloge;
this.vrste = vrste;
this.sveEmisije = sveEmisije;
this.podaciPrograma = podaciPrograma;
}
public RasporedTvKuce izgradiRaspored(){
if (gradiRaspored == null){
gradiRaspored = new GradiRaspored();
}
List<DodavanjeEmisijaSucelje> redosljedDodavanja = new ArrayList<>();
redosljedDodavanja.add(new AlgoritamDodavanjaEmisija1());
redosljedDodavanja.add(new AlgoritamDodavanjaEmisija2());
redosljedDodavanja.add(new AlgoritamDodavanjaEmisija3());
RasporedTvKuce rasporedTvKuce = gradiRaspored
.dodajPodatkeTvKuce(osobe, uloge, vrste, sveEmisije)
.postaviPodatkePrograma(podaciPrograma)
.postaviAlgoritme(redosljedDodavanja)
.build();
return rasporedTvKuce;
}
}
|
package la.opi.verificacionciudadana.tabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
import la.opi.verificacionciudadana.R;
public class HomePagerAdapter extends FragmentPagerAdapter {
private static int[] ICONS = new int[]{
R.drawable.ic_events_custom,
R.drawable.ic_perfil_custom,
R.drawable.ic_location_custom
};
private List<Fragment> fragments;
public HomePagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
@Override
public int getCount() {
return ICONS.length;
}
public int getDrawableId(int position) {
return ICONS[position];
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
} |
package be.spring.app.service;
import be.spring.app.model.Season;
import java.util.List;
/**
* Created by u0090265 on 5/11/14.
*/
public interface SeasonService {
List<Season> getSeasons();
Season getLatestSeason();
}
|
package zuoshen.DP;
import java.util.HashSet;
public class 打印一个字符串的非重复排列 {
public void print_all(char[]chars,int index){
if(index==chars.length){
String res=String.valueOf(chars);
System.out.println(res);
return;
}
HashSet<Character>hashSet=new HashSet<>();
for (int j=index;j<chars.length;j++){
if(!hashSet.contains(chars[j])) {
hashSet.add(chars[j]);
swap(index, j, chars);
print_all(chars, index + 1);
swap(index, j, chars);
}
}
}
public void swap(int i,int j,char[]chars){
char temp=chars[i];
chars[i]=chars[j];
chars[j]=temp;
}
}
|
package game;
import game.net.Framework;
import game.util.Spring;
public class GameClient {
public static void main(String[] args) {
// Thread t = new Thread(new Runnable(){
// @Override
// public void run() {
// Framework framework = new Framework();
// try {
// framework.connect(8081, "127.0.0.1");
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// });
// t.start();
Spring.uiService.start(Spring.uiLogin);
Spring.input.start();
}
}
|
package com.tencent.map.lib;
import android.graphics.Rect;
import com.tencent.map.lib.basemap.data.GeoPoint;
import com.tencent.map.lib.gl.JNICallback$c;
import com.tencent.map.lib.gl.JNICallback.b;
import com.tencent.map.lib.gl.JNICallback.d;
import com.tencent.map.lib.gl.JNICallback.e;
import com.tencent.map.lib.gl.JNICallback.j;
import com.tencent.map.lib.gl.JNICallback.k;
import com.tencent.map.lib.mapstructure.MapRouteSectionWithName;
import com.tencent.map.lib.mapstructure.Polygon2D;
import com.tencent.map.lib.mapstructure.TappedElement;
import com.tencent.tencentmap.mapsdk.a.gv;
import com.tencent.tencentmap.mapsdk.a.gw;
import com.tencent.tencentmap.mapsdk.a.hb;
import com.tencent.tencentmap.mapsdk.a.hc;
import com.tencent.tencentmap.mapsdk.a.he;
import com.tencent.tencentmap.mapsdk.a.hg;
import com.tencent.tencentmap.mapsdk.a.hh;
import com.tencent.tencentmap.mapsdk.a.hi;
import com.tencent.tencentmap.mapsdk.a.hs;
import com.tencent.tencentmap.mapsdk.a.ht;
import com.tencent.tencentmap.mapsdk.a.hv;
import com.tencent.tencentmap.mapsdk.a.ic;
import com.tencent.tencentmap.mapsdk.a.ic.a;
import com.tencent.tencentmap.mapsdk.a.id;
import com.tencent.tencentmap.mapsdk.a.if;
import com.tencent.tencentmap.mapsdk.a.iw;
import java.util.List;
public class f {
private hv a;
private int b = a.a;
private int c = a.d;
private GeoPoint d = new GeoPoint();
private int e = 0;
public f(hv hvVar) {
this.a = hvVar;
}
public void a() {
this.a.x();
}
public int b() {
return this.c;
}
public int c() {
return this.b;
}
public int d() {
return this.a.e().n();
}
public int e() {
return this.a.a().u();
}
public void a(int i) {
this.a.a().b(i);
}
public GeoPoint f() {
return this.a.a().n();
}
public String a(GeoPoint geoPoint) {
return this.a.a(geoPoint);
}
public void b(int i) {
this.a.a().a(i);
}
public void a(iw iwVar) {
this.a.c().a(iwVar);
this.a.r();
}
public void b(iw iwVar) {
this.a.c().b(iwVar);
this.a.r();
}
public void a(hb hbVar) {
this.a.a().a(hbVar);
}
public void b(hb hbVar) {
this.a.a().b(hbVar);
}
public void a(hg hgVar) {
this.a.a().a(hgVar);
}
public void b(hg hgVar) {
this.a.a().b(hgVar);
}
public void b(GeoPoint geoPoint) {
this.a.a().a(geoPoint.getLatitudeE6(), geoPoint.getLongitudeE6());
}
public void a(int i, int i2) {
this.a.a().a(i, i2);
}
public void a(float f) {
this.a.a().c(f);
}
public void b(float f) {
this.a.a().b(f);
}
public boolean g() {
return this.a.v();
}
public void a(boolean z) {
this.a.b(z);
}
public int h() {
return this.a.a().m();
}
public float i() {
return this.a.a().l();
}
public float j() {
return this.a.a().q();
}
public void a(double d) {
this.a.a().j(d);
}
public void a(Runnable runnable) {
this.a.a().a(runnable);
}
public void b(Runnable runnable) {
this.a.a().b(runnable);
}
public void k() {
this.a.a().s();
}
public void l() {
this.a.t();
}
public void m() {
this.a.u();
}
public void n() {
try {
gv.a().a(this.a.s());
gv.a().a(this.a.e());
} catch (Exception e) {
}
}
public boolean a(String str, byte[] bArr) {
if p = this.a.p();
if (p == null) {
return false;
}
return p.a(str, bArr);
}
public boolean b(String str, byte[] bArr) {
if p = this.a.p();
if (p == null) {
return false;
}
return p.b(str, bArr);
}
public void o() {
if p = this.a.p();
if (p != null) {
p.c();
}
}
public void a(hc hcVar) {
this.a.a().a(hcVar);
}
public void a(he heVar) {
this.a.a().a(heVar);
}
public void b(he heVar) {
this.a.a().b(heVar);
}
public void a(com.tencent.map.lib.listener.a aVar) {
this.a.c().a(aVar);
}
public boolean a(float f, float f2) {
return this.a.c().a(f, f2);
}
public float p() {
return this.a.a().o();
}
public float q() {
return this.a.a().p();
}
public int a(Polygon2D polygon2D) {
return this.a.a(polygon2D);
}
public void b(Polygon2D polygon2D) {
this.a.b(polygon2D);
}
public void c(int i) {
this.a.b(i);
}
public int a(int i, int i2, int i3, int i4, int i5, float f) {
return this.a.a(i, i2, i3, i4, i5, f);
}
public void b(int i, int i2) {
this.a.c(i, i2);
}
public void d(int i) {
this.a.a(i);
}
public void a(List<MapRouteSectionWithName> list, List<GeoPoint> list2) {
this.a.a(list, list2);
}
public void r() {
this.a.w();
}
public void b(boolean z) {
if (this.a != null) {
this.a.e(z);
}
}
public void c(boolean z) {
if (this.a != null) {
this.a.f(z);
}
}
public hh s() {
return this.a.d();
}
@Deprecated
public hh t() {
return new gw(this.a);
}
public void a(hi hiVar) {
this.a.a().c(hiVar);
}
public void u() {
this.a.a().A();
}
public int a(int i, int i2, int i3, int i4) {
return this.a.a().a(i, i2, i3, i4);
}
public Rect v() {
return this.a.a().b();
}
public void a(e eVar) {
this.a.a().a(eVar);
}
public void d(boolean z) {
this.a.g(z);
}
public int w() {
return this.a.i().o();
}
public String[] x() {
return this.a.y();
}
public String c(GeoPoint geoPoint) {
return this.a.b(geoPoint);
}
public void e(int i) {
this.b = i;
this.a.i().b(i);
}
public void f(int i) {
this.c = i;
this.a.i().c(i);
}
public void a(e eVar) {
this.a.a(eVar);
}
public void a(ht.a aVar) {
this.a.a().a(aVar);
}
public void c(int i, int i2) {
this.a.a().b(i, i2);
}
public void c(float f) {
this.a.a().a(f);
}
public void a(float f, float f2, int i, boolean z) {
this.a.a().a(f, f2, z);
}
public void b(double d) {
this.a.a().h(d);
}
public void a(double d, double d2, double d3, double d4, double d5, Runnable runnable) {
this.a.a().a(d, d2, d3, d4, d5, runnable);
}
public void a(id idVar) {
this.a.a().a(idVar);
}
public hs y() {
return this.a.A();
}
public ic z() {
return this.a.e();
}
public int A() {
return this.a.a(3, true);
}
public int B() {
return this.a.a(2, false);
}
public int e(boolean z) {
return this.a.a(1, z);
}
public void g(int i) {
this.a.c(i);
}
public void h(int i) {
this.a.d(i);
}
public void a(d dVar) {
this.a.a(dVar);
}
public void a(j jVar) {
this.a.a(jVar);
}
public void a(b bVar) {
this.a.a(bVar);
}
public void a(JNICallback$c jNICallback$c) {
this.a.a(jNICallback$c);
}
public void a(k kVar) {
this.a.a(kVar);
}
public void d(int i, int i2) {
this.a.d(i, i2);
}
public void f(boolean z) {
this.a.h(z);
}
public void e(int i, int i2) {
this.a.e(i, i2);
}
public void a(String str) {
this.a.b(str);
}
public MapLanguage C() {
return this.a.z();
}
public void b(String str) {
this.a.a(str);
}
public TappedElement b(float f, float f2) {
return this.a.a(f, f2);
}
public void g(boolean z) {
this.a.j(z);
}
public void h(boolean z) {
this.a.k(z);
}
public void c(String str) {
this.a.c(str);
}
public void i(boolean z) {
this.a.i(z);
}
public boolean D() {
return this.a.C();
}
public void E() {
this.a.D();
}
public void j(boolean z) {
if (this.a != null) {
this.a.l(z);
}
}
}
|
package InterfaceDemo;
/**
* "One Interface multiple implementations". Interfaces cannot be used to create
* objects. All methods, variables static, and final (constant) by default. All
* methods in interface usually have empty methods. The subclass should
* implement all methods from the interface, but each subclass can implement
* these methods in a different way. To access the different method
* implementation through interface (Ex: MyInterface obj = new Class()).
* Interfaces can be nested in the class then they can be public\private.
*
* @author Bohdan Skrypnyk
*/
// class contain nested interface
class A {
// nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// class implement a nested interface
class B implements A.NestedIF {
@Override
public boolean isNotNegative(int x) {
return (x > 0) ? true : false;
}
}
public class NestedIfDemo {
public static void main(String args[]) {
// use reference on the nested interface
A.NestedIF nestedif = new B();
if (nestedif.isNotNegative(15)) {
System.out.println("Number is not negative");
}
if (nestedif.isNotNegative(-12)) {
System.out.println("will not be printed");
}
}
}
|
package com.tencent.mm.plugin.freewifi.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class FreeWifiPcUI$1 implements OnMenuItemClickListener {
final /* synthetic */ FreeWifiPcUI jnS;
FreeWifiPcUI$1(FreeWifiPcUI freeWifiPcUI) {
this.jnS = freeWifiPcUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
FreeWifiPcUI.a(this.jnS);
return true;
}
}
|
package com.dao.operateRecord.Impl;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.dao.operateRecord.OperateRecordDao;
import com.dao.operateRecord.mapper.OperateRecordMapper;
import com.dao.proxy.mapper.ProxyMapper;
import com.pojo.OperateRecord;
import com.pojo.Proxy;
import com.utils.SqlSessionUtil;
@Repository
public class OperateRecordDaoImpl implements OperateRecordDao{
@Override
public int addOperateRecord(OperateRecord opeRec) {
try {
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
OperateRecordMapper opeRecMapper = sqlSession.getMapper(OperateRecordMapper.class);
int result=opeRecMapper.addOperateRecord(opeRec);
sqlSession.commit();
sqlSession.close();
return result;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
|
package com.takshine.wxcrm.domain;
import java.util.List;
public class CalendarRss {
private String openid;
private String rssObjectId;
private String rssObjectName;
private String type;
private String rssObjectHeadImage;
private String currDate;
public String getCurrDate() {
return currDate;
}
public void setCurrDate(String currDate) {
this.currDate = currDate;
}
private List<CalendarInfo> list;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getRssObjectId() {
return rssObjectId;
}
public void setRssObjectId(String rssObjectId) {
this.rssObjectId = rssObjectId;
}
public String getRssObjectName() {
return rssObjectName;
}
public void setRssObjectName(String rssObjectName) {
this.rssObjectName = rssObjectName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRssObjectHeadImage() {
return rssObjectHeadImage;
}
public void setRssObjectHeadImage(String rssObjectHeadImage) {
this.rssObjectHeadImage = rssObjectHeadImage;
}
public List<CalendarInfo> getList() {
return list;
}
public void setList(List<CalendarInfo> list) {
this.list = list;
}
}
|
package com.kodilla.testing2.facebook;
import com.kodilla.testing2.config.WebDriverConfig;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class FacebookTestingApp {
public static final String XPATH_FIRSTNAME_INPUT = "//input[contains(@class, \"inputtext _58mg _5dba _2ph-\")" +
"and (@name=\"firstname\")]";
public static final String XPATH_LASTNAME_INPUT = "//input[contains(@class, \"inputtext _58mg _5dba _2ph-\")" +
"and (@name=\"lastname\")]";
public static final String XPATH_EMAIL_INPUT = "//input[contains(@class, \"inputtext _58mg _5dba _2ph-\")" +
"and (@name=\"reg_email__\")]";
public static final String XPATH_WAIT_FOR = "//span[contains(@class, \"_5k_4\")]";
public static final String SELECT_DAY_INPUT = "//select[contains(@id, \"day\")]";
public static final String SELECT_MONTH_INPUT = "//select[contains(@id, \"month\")]";
public static final String SELECT_YEAR_INPUT = "//select[contains(@id, \"year\")]";
public static void main(String[] args) {
WebDriver driver = WebDriverConfig.getDriver(WebDriverConfig.FIREFOX);
driver.get("https://pl-pl.facebook.com/");
WebElement firstnameField = driver.findElement(By.xpath(XPATH_FIRSTNAME_INPUT));
firstnameField.sendKeys("Przemek");
WebElement lastnameField = driver.findElement(By.xpath(XPATH_LASTNAME_INPUT));
lastnameField.sendKeys("Serbeński");
WebElement emailField = driver.findElement(By.xpath(XPATH_EMAIL_INPUT));
emailField.sendKeys("email@mail.com.pl");
while (!driver.findElement(By.xpath(XPATH_WAIT_FOR)).isDisplayed());
WebElement selectDayField = driver.findElement(By.xpath(SELECT_DAY_INPUT));
Select selectDay = new Select(selectDayField);
selectDay.selectByValue("12");
WebElement selectMonthField = driver.findElement(By.xpath(SELECT_MONTH_INPUT));
Select selectMonth = new Select(selectMonthField);
selectMonth.selectByValue("2");
WebElement selectYearField = driver.findElement(By.xpath(SELECT_YEAR_INPUT));
Select selectYear = new Select(selectYearField);
selectYear.selectByValue("1984");
}
}
|
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class py extends b {
public a caE;
public py() {
this((byte) 0);
}
private py(byte b) {
this.caE = new a();
this.sFm = false;
this.bJX = null;
}
}
|
package com.kunsoftware.bean;
import java.util.HashMap;
@SuppressWarnings({ "serial", "rawtypes","unchecked" })
public class JsonBean extends HashMap {
private String success = "1";
private String message;
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
put("success", success);
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
put("message", message);
this.message = message;
}
public void put(String key,Object value) {
super.put(key, value);
}
}
|
package com.xiaoxiao.tiny.frontline.mapper;
import com.xiaoxiao.pojo.XiaoxiaoLeaveMessage;
import com.xiaoxiao.pojo.vo.XiaoxiaoLeaveMessageVo;
import com.xiaoxiao.tiny.frontline.provider.XiaoxiaoLeaveMessageProvider;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.List;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/19:14:57
* @author:shinelon
* @Describe:
*/
@Repository
public interface FrontlineTinyLeaveMessageMapper
{
/**
* 插入
* @param leaveMessage
* @return
*/
@InsertProvider(type = XiaoxiaoLeaveMessageProvider.class,method = "insert")
int insert(@Param("leaveMessage") XiaoxiaoLeaveMessage leaveMessage);
/**
* 分页查询
* @return
*/
@Select("SELECT * FROM xiaoxiao_leave_message WHERE message_parent_id = '-1' ORDER BY message_date DESC")
List<XiaoxiaoLeaveMessage> findAllLeaveMessage();
/**
* 获取的
* @return
*/
@Select("select count(a.message_id) sum from xiaoxiao_leave_message as a")
XiaoxiaoLeaveMessageVo getLeaveMessageSum();
/**
* 获取子评论
* @return
*/
@Select("select * from xiaoxiao_leave_message as a where a.message_parent_id = #{messageId}")
List<XiaoxiaoLeaveMessage> getSon(@Param("messageId") String messageId);
}
|
package com.pgssoft.httpclient.internal.action;
import com.pgssoft.httpclient.Action;
import com.pgssoft.httpclient.MockedServerResponse;
public final class SetHeaderAction implements Action {
private final String key, value;
public SetHeaderAction(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public void enrichResponse(MockedServerResponse.Builder responseBuilder) {
responseBuilder.addHeader(key, value);
}
}
|
package com.spring.querybuilder;
public class CassandraTest {/*
public static void main(String[] args) {
Cluster cluster = Cluster.builder().addContactPoint("localhost").build();
Session session = cluster.connect("shopping");
MappingManager mappingManager = new MappingManager(session);
ResultSet resultSet = session.execute("select * from products");
Result<Products> mapper = mappingManager.mapper(Products.class).map(resultSet);
// mapper.all().stream().forEach(product ->
// System.out.println(product.getName()));
// System.out.println(mappingManager.mapper(Products.class).get(3));
Where query = QueryBuilder.select().all().from("products").where(QueryBuilder.eq("id", 3));
ResultSet result = session.execute(query);
mapper = mappingManager.mapper(Products.class).map(result);
// mappingManager.mapper(Products.class).getQuery(objects)
// MappingSession mappingSession = new MappingSession("shopping",
// session);
//
}
*/}
|
package fr.lteconsulting.commandes;
import java.util.Random;
import java.util.UUID;
import fr.lteconsulting.ApplicationContext;
import fr.lteconsulting.Chanson;
import fr.lteconsulting.Disque;
import fr.lteconsulting.DisqueDejaPresentException;
import fr.lteconsulting.Mots;
import fr.lteconsulting.Saisie;
public class CreerDisquesCommande extends CommandeBase
{
public CreerDisquesCommande()
{
super( "Créer des disques au hasard" );
}
@Override
public void executer( ApplicationContext contexte )
{
int nbDisques = Saisie.saisieInt( "Combien de disques voulez-vous créer ?" );
while( nbDisques-- > 0 )
{
try
{
contexte.getBibliotheque().ajouterDisque( creerDisque() );
}
catch( DisqueDejaPresentException e )
{
System.out.println( "Duplication de code barre ! C'est pas grave va..." );
}
}
}
private Disque creerDisque()
{
Disque disque = new Disque( Mots.phrase(), UUID.randomUUID().toString() );
int nbChansons = 3 + new Random().nextInt( 10 );
while( nbChansons-- > 0 )
disque.addChanson( creerChanson() );
return disque;
}
private Chanson creerChanson()
{
return new Chanson( Mots.phrase(), 30 + new Random().nextInt( 60 ) );
}
}
|
/**
* Javassonne
* http://code.google.com/p/javassonne/
*
* @author Ben Gotow
* @date Jan 28, 2009
*
* Copyright 2009 Javassonne Team
* 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 org.javassonne.messaging;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class NotificationCallback {
private Object target_ = null;
private Method method_ = null;
NotificationCallback(Object target, Method method) {
target_ = target;
method_ = method;
}
public void fire(Notification n) {
try {
if (method_.getParameterTypes().length == 0)
method_.invoke(target_);
else
method_.invoke(target_, n);
} catch (IllegalArgumentException e) {
String err = String.format("An exception occurred while sending "
+ "the notification %s to an observer of %s", n
.identifier(), target_.getClass().toString());
err += "\nThe callback function called does not take a Notification parameter";
NotificationManager.getInstance().sendNotification(
Notification.LOG_ERROR, err);
} catch (IllegalAccessException e) {
String err = String.format("An exception occurred while sending "
+ "the notification %s to an observer of %s", n
.identifier(), target_.getClass().toString());
err += "\nNotificationCallback cannot access that function";
NotificationManager.getInstance().sendNotification(
Notification.LOG_ERROR, err);
} catch (InvocationTargetException e) {
String err = String.format("An exception occurred while sending "
+ "the notification %s to an observer of %s", n
.identifier(), target_.getClass().toString());
err += "\nAn exception of type '" + e.getTargetException()
+ "' was thrown in the callback function.\n"
+ "Stack Trace: \n";
for (int i = 0; i < e.getTargetException().getStackTrace().length; i++) {
err += e.getTargetException().getStackTrace()[i] + "\n";
}
NotificationManager.getInstance().sendNotification(
Notification.LOG_ERROR, err);
}
}
public boolean equals(Object obj) {
if (obj.getClass() != NotificationCallback.class)
return false;
NotificationCallback other = (NotificationCallback) obj;
return ((other.target_.equals(target_)) && (other.method_
.equals(method_)));
}
public Object target() {
return target_;
}
public Method method() {
return method_;
}
} |
package OOD1;
public class ParkingLot {
private final Level[] levels;
public ParkingLot(int numLevels, int numSpotsPerLevel) {
levels = new Level[numLevels];
for (int i = 0; i < numLevels; i++) {
levels[i] = new Level(numSpotsPerLevel);
}
}
public boolean hasSpots(Vehicle v) {
for (Level l: levels) {
if(l.hasSpot(v)){
return true;
}
}
return false;
}
}
|
package com.example.project_redbus;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class My_BookingL extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mybooking1);
TextView txt2=findViewById(R.id.text2);
txt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(My_BookingL.this,MainActivity.class);
startActivity(intent);
}
});
}
} |
package com.epam.restaurant.controller.command.impl;
import com.epam.restaurant.controller.command.Command;
import com.epam.restaurant.controller.command.exception.CommandException;
import com.epam.restaurant.controller.name.JspPageName;
import com.epam.restaurant.entity.News;
import com.epam.restaurant.service.NewsService;
import com.epam.restaurant.service.exception.ServiceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import static com.epam.restaurant.controller.name.RequestParameterName.*;
/**
* Show page with all news.
*/
public class NewsCommand implements Command {
/**
* Service provides work with database (news table)
*/
private static final NewsService newsService = NewsService.getInstance();
/**
* Set all news to request.
* If everything is fine, return news page value.
*
* @return page to forward to
* @throws CommandException if can't get all news
*/
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws CommandException {
String result = JspPageName.NEWS_JSP;
try {
List<News> newsList = newsService.getAllNews();
request.setAttribute(NEWS_LIST, newsList);
} catch (ServiceException e) {
throw new CommandException("NewsCommand Exception", e);
}
return result;
}
}
|
package com.tt.miniapp;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.f.a;
import android.webkit.WebView;
import com.storage.async.Action;
import com.storage.async.Scheduler;
import com.tt.frontendapiinterface.e;
import com.tt.frontendapiinterface.j;
import com.tt.miniapp.audio.AudioManager;
import com.tt.miniapp.audio.background.BgAudioManagerClient;
import com.tt.miniapp.autotest.AutoTestManager;
import com.tt.miniapp.badcase.BlockPageManager;
import com.tt.miniapp.base.IActivityFetcher;
import com.tt.miniapp.base.MiniAppContextWrapper;
import com.tt.miniapp.call.PhoneCallImpl;
import com.tt.miniapp.component.nativeview.NativeViewManager;
import com.tt.miniapp.component.nativeview.NativeWebView;
import com.tt.miniapp.debug.PerformanceService;
import com.tt.miniapp.debug.SwitchManager;
import com.tt.miniapp.dialog.ActionSheetImpl;
import com.tt.miniapp.dialog.DialogImpl;
import com.tt.miniapp.favorite.FavoriteGuideWidget;
import com.tt.miniapp.jsbridge.ApiPermissionManager;
import com.tt.miniapp.jsbridge.JsRuntimeManager;
import com.tt.miniapp.launch.MiniAppLaunchConfig;
import com.tt.miniapp.launchcache.meta.MetaService;
import com.tt.miniapp.launchcache.pkg.PkgService;
import com.tt.miniapp.launchschedule.LaunchScheduler;
import com.tt.miniapp.manager.AppConfigManager;
import com.tt.miniapp.manager.AppbrandBroadcastService;
import com.tt.miniapp.manager.ForeBackgroundManager;
import com.tt.miniapp.manager.HostSnapShotManager;
import com.tt.miniapp.manager.MainMessageLoggerManager;
import com.tt.miniapp.manager.StorageManager;
import com.tt.miniapp.preload.PreloadManager;
import com.tt.miniapp.process.AppProcessManager;
import com.tt.miniapp.process.bridge.InnerHostProcessBridge;
import com.tt.miniapp.route.PageRouter;
import com.tt.miniapp.route.RouteEventCtrl;
import com.tt.miniapp.shortcut.ShortcutService;
import com.tt.miniapp.streamloader.FileAccessLogger;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapp.titlemenu.item.FavoriteMiniAppMenuItem;
import com.tt.miniapp.toast.HideToastImpl;
import com.tt.miniapp.toast.ToastImpl;
import com.tt.miniapp.toast.ToastManager;
import com.tt.miniapp.util.RenderSnapShotManager;
import com.tt.miniapp.util.TimeLineReporter;
import com.tt.miniapp.util.TimeLogger;
import com.tt.miniapp.util.timeline.MpTimeLineReporter;
import com.tt.miniapp.view.webcore.LoadPathInterceptor;
import com.tt.miniapp.webapp.WebAppPreloadManager;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.IAppbrandApplication;
import com.tt.miniapphost.LaunchThreadPool;
import com.tt.miniapphost.ModeManager;
import com.tt.miniapphost.NativeModule;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.game.GameModuleController;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.preload.IPreload;
import com.tt.miniapphost.process.HostProcessBridge;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class AppbrandApplicationImpl implements IAppbrandApplication {
private static AppbrandApplicationImpl sInstance;
private boolean isOpenedSchema = false;
private boolean jumpToApp = false;
private e mActivityLife;
private AppInfoEntity mAppInfo;
private a<String, Boolean> mCurrentPageHideShareMenuArrayMap = new a();
private String mCurrentPagePath;
private String mCurrentPageType;
private String mCurrentPageUrl;
private int mCurrentWebViewId;
private final ForeBackgroundManager mForeBackgroundManager;
private MiniAppLaunchConfig mMiniAppLaunchConfig = MiniAppLaunchConfig.DEFAULT;
private boolean mNeedNotifyPreloadEmptyProcess = false;
protected List<ILifecycleObserver> mObservers = new CopyOnWriteArrayList<ILifecycleObserver>();
private RouteEventCtrl mRouteEventCtrl;
private String mSchema;
private AppbrandServiceManager mServiceManager = new AppbrandServiceManager(this);
private String mStopReason = "";
private Handler mainHandler = new Handler(Looper.getMainLooper());
private MiniAppContextWrapper miniAppContextWrapper;
private AppInfoEntity updateAppInfo;
private AppbrandApplicationImpl() {
GameModuleController.inst().registerService(this.mServiceManager);
this.mServiceManager.register(WebViewManager.class);
this.mServiceManager.register(TimeLineReporter.class);
this.mServiceManager.register(JsRuntimeManager.class);
this.mServiceManager.register(PerformanceService.class);
this.mServiceManager.register(PreloadManager.class);
this.mServiceManager.register(SwitchManager.class);
this.mServiceManager.register(MpTimeLineReporter.class);
this.mServiceManager.register(FileAccessLogger.class);
this.mServiceManager.register(AppConfigManager.class);
this.mServiceManager.register(ShortcutService.class);
this.mServiceManager.register(LaunchScheduler.class);
this.mServiceManager.register(LoadPathInterceptor.class);
this.mServiceManager.register(TimeLogger.class);
this.mServiceManager.register(AppbrandBroadcastService.class);
this.mServiceManager.register(PageRouter.class);
this.mServiceManager.register(HostSnapShotManager.class);
this.mServiceManager.register(RenderSnapShotManager.class);
this.mServiceManager.register(BlockPageManager.class);
this.mServiceManager.register(FavoriteGuideWidget.class);
this.mServiceManager.register(WebAppPreloadManager.class);
this.mServiceManager.register(AutoTestManager.class);
this.mServiceManager.register(MetaService.class);
this.mServiceManager.register(PkgService.class);
this.mServiceManager.register(MainMessageLoggerManager.class);
this.mForeBackgroundManager = new ForeBackgroundManager();
}
public static AppbrandApplicationImpl getInst() {
// Byte code:
// 0: ldc com/tt/miniapp/AppbrandApplicationImpl
// 2: monitorenter
// 3: invokestatic isBdpProcess : ()Z
// 6: ifne -> 23
// 9: ldc 'tma_AppbrandApplicationImpl'
// 11: iconst_1
// 12: anewarray java/lang/Object
// 15: dup
// 16: iconst_0
// 17: ldc '这个类只应该在小程序、小游戏、UC进程里被使用'
// 19: aastore
// 20: invokestatic logOrThrow : (Ljava/lang/String;[Ljava/lang/Object;)V
// 23: getstatic com/tt/miniapp/AppbrandApplicationImpl.sInstance : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 26: ifnonnull -> 60
// 29: ldc com/tt/miniapp/AppbrandApplicationImpl
// 31: monitorenter
// 32: getstatic com/tt/miniapp/AppbrandApplicationImpl.sInstance : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 35: ifnonnull -> 48
// 38: new com/tt/miniapp/AppbrandApplicationImpl
// 41: dup
// 42: invokespecial <init> : ()V
// 45: putstatic com/tt/miniapp/AppbrandApplicationImpl.sInstance : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 48: ldc com/tt/miniapp/AppbrandApplicationImpl
// 50: monitorexit
// 51: goto -> 60
// 54: astore_0
// 55: ldc com/tt/miniapp/AppbrandApplicationImpl
// 57: monitorexit
// 58: aload_0
// 59: athrow
// 60: getstatic com/tt/miniapp/AppbrandApplicationImpl.sInstance : Lcom/tt/miniapp/AppbrandApplicationImpl;
// 63: astore_0
// 64: ldc com/tt/miniapp/AppbrandApplicationImpl
// 66: monitorexit
// 67: aload_0
// 68: areturn
// 69: astore_0
// 70: ldc com/tt/miniapp/AppbrandApplicationImpl
// 72: monitorexit
// 73: aload_0
// 74: athrow
// Exception table:
// from to target type
// 3 23 69 finally
// 23 32 69 finally
// 32 48 54 finally
// 48 51 54 finally
// 55 58 54 finally
// 58 60 69 finally
// 60 64 69 finally
}
public void finish() {
this.mForeBackgroundManager.clear();
}
public e getActivityLife() {
return this.mActivityLife;
}
public AppConfig getAppConfig() {
return ((AppConfigManager)getService(AppConfigManager.class)).getAppConfig();
}
public AppInfoEntity getAppInfo() {
return this.mAppInfo;
}
public a<String, Boolean> getCurrentPageHideShareMenuArrayMap() {
return this.mCurrentPageHideShareMenuArrayMap;
}
public String getCurrentPagePath() {
return this.mCurrentPagePath;
}
public String getCurrentPageType() {
return this.mCurrentPageType;
}
public String getCurrentPageUrl() {
return this.mCurrentPageUrl;
}
public int getCurrentWebViewId() {
return this.mCurrentWebViewId;
}
public String getCurrentWebViewUrl() {
WebViewManager webViewManager = getWebViewManager();
if (webViewManager != null) {
WebViewManager.IRender iRender = webViewManager.getCurrentIRender();
if (iRender != null) {
NativeViewManager nativeViewManager = iRender.getNativeViewManager();
if (nativeViewManager != null) {
NativeWebView nativeWebView = nativeViewManager.getCurrentNativeWebView();
if (nativeWebView != null) {
WebView webView = nativeWebView.getWebView();
if (webView != null)
return webView.getUrl();
}
}
}
}
return null;
}
public ForeBackgroundManager getForeBackgroundManager() {
return this.mForeBackgroundManager;
}
public j getJsBridge() {
return ((JsRuntimeManager)getService(JsRuntimeManager.class)).getJsBridge();
}
public boolean getJumToApp() {
return this.jumpToApp;
}
public LifeCycleManager getLifeCycleManager() {
return this.mServiceManager.<LifeCycleManager>get(LifeCycleManager.class);
}
public Handler getMainHandler() {
return this.mainHandler;
}
public MiniAppContextWrapper getMiniAppContext() {
// Byte code:
// 0: aload_0
// 1: getfield miniAppContextWrapper : Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 4: ifnonnull -> 50
// 7: aload_0
// 8: monitorenter
// 9: aload_0
// 10: getfield miniAppContextWrapper : Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 13: ifnonnull -> 40
// 16: aload_0
// 17: new com/tt/miniapp/AppbrandApplicationImpl$1
// 20: dup
// 21: aload_0
// 22: invokespecial <init> : (Lcom/tt/miniapp/AppbrandApplicationImpl;)V
// 25: invokestatic getInst : ()Lcom/tt/miniapphost/AppbrandContext;
// 28: invokevirtual getApplicationContext : ()Landroid/app/Application;
// 31: invokestatic create : (Lcom/tt/miniapp/base/IActivityFetcher;Landroid/content/Context;)Lcom/tt/miniapp/base/MiniAppContextWrapper$Builder;
// 34: invokevirtual build : ()Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 37: putfield miniAppContextWrapper : Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 40: aload_0
// 41: monitorexit
// 42: goto -> 50
// 45: astore_1
// 46: aload_0
// 47: monitorexit
// 48: aload_1
// 49: athrow
// 50: aload_0
// 51: getfield miniAppContextWrapper : Lcom/tt/miniapp/base/MiniAppContextWrapper;
// 54: areturn
// Exception table:
// from to target type
// 9 40 45 finally
// 40 42 45 finally
// 46 48 45 finally
}
public MiniAppLaunchConfig getMiniAppLaunchConfig() {
return this.mMiniAppLaunchConfig;
}
public IPreload getPreloadManager() {
return (IPreload)getService(PreloadManager.class);
}
public String getRequestRefer() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("https://tmaservice.developer.toutiao.com");
AppInfoEntity appInfoEntity = this.mAppInfo;
if (appInfoEntity != null && appInfoEntity.appId != null && this.mAppInfo.version != null) {
stringBuffer.append("?appid=");
stringBuffer.append(this.mAppInfo.appId);
stringBuffer.append("&version=");
stringBuffer.append(this.mAppInfo.version);
}
return stringBuffer.toString();
}
public RouteEventCtrl getRouteEventCtrl() {
return this.mRouteEventCtrl;
}
public String getSchema() {
return this.mSchema;
}
public <T extends AppbrandServiceManager.ServiceBase> T getService(Class<T> paramClass) {
return this.mServiceManager.get(paramClass);
}
public String getStopReason() {
return this.mStopReason;
}
public AppInfoEntity getUpdateAppInfo() {
return this.updateAppInfo;
}
public WebViewManager getWebViewManager() {
return getService(WebViewManager.class);
}
public AppConfig initAppConfig() {
return ((AppConfigManager)getService(AppConfigManager.class)).initAppConfig();
}
public void invokeHandler(int paramInt1, int paramInt2, String paramString) {
WebViewManager webViewManager = getWebViewManager();
if (webViewManager != null)
webViewManager.invokeHandler(paramInt1, paramInt2, paramString);
}
public void markNeedPreload() {
this.mNeedNotifyPreloadEmptyProcess = true;
}
public void notifyPreloadEmptyProcess() {
if (this.mNeedNotifyPreloadEmptyProcess) {
ThreadUtil.runOnWorkThread(new Action() {
public void act() {
InnerHostProcessBridge.notifyPreloadEmptyProcess();
}
}, (Scheduler)LaunchThreadPool.getInst());
this.mNeedNotifyPreloadEmptyProcess = false;
}
}
public void onCreate() {
getLifeCycleManager().notifyAppCreate();
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "--------onCreate---- " });
this.mRouteEventCtrl = new RouteEventCtrl();
AppbrandContext.getInst().getApplicationContext().registerActivityLifecycleCallbacks(new AppbrandActivityLifeCycleCallback(this));
ArrayList<ActionSheetImpl> arrayList = new ArrayList();
arrayList.add(new ActionSheetImpl(AppbrandContext.getInst()));
arrayList.add(new DialogImpl(AppbrandContext.getInst()));
arrayList.add(new ToastImpl(AppbrandContext.getInst()));
arrayList.add(new HideToastImpl(AppbrandContext.getInst()));
arrayList.add(new PhoneCallImpl(AppbrandContext.getInst()));
arrayList.add(new FavoriteMiniAppMenuItem.FavoriteModule(AppbrandContext.getInst()));
for (NativeModule nativeModule : arrayList)
ModeManager.getInst().register(nativeModule.getName(), nativeModule);
List list = HostDependManager.getInst().createNativeModules(AppbrandContext.getInst());
if (list != null)
for (NativeModule nativeModule : list)
ModeManager.getInst().register(nativeModule.getName(), nativeModule);
}
public void onError(String paramString) {}
public void onHide() {
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onHide" });
HostDependManager.getInst().getMiniAppLifeCycleInstance();
this.mForeBackgroundManager.onBackground();
ToastManager.clearToast();
AudioManager.getInst().onEnterBackground();
GameModuleController.inst().onHide();
getLifeCycleManager().notifyAppHide();
j j = getJsBridge();
if (j != null) {
j.onHide();
} else {
RouteEventCtrl routeEventCtrl = getRouteEventCtrl();
if (routeEventCtrl != null)
routeEventCtrl.onAppHide();
}
if (!this.isOpenedSchema && !InnerHostProcessBridge.isInJumpList((getAppInfo()).appId) && !BgAudioManagerClient.getInst().needKeepAlive()) {
AppBrandLogger.i("tma_AppbrandApplicationImpl", new Object[] { "小程序进入后台等待 5 分钟后被 SDK 逻辑杀死" });
AppProcessManager.getProcessHandler().sendEmptyMessageDelayed(1, 300000L);
} else {
AppBrandLogger.i("tma_AppbrandApplicationImpl", new Object[] { "小程序进入后台时保活,不会被 SDK 逻辑自动杀死" });
}
Iterator<ILifecycleObserver> iterator = this.mObservers.iterator();
while (iterator.hasNext())
((ILifecycleObserver)iterator.next()).onHide();
StorageManager.reportDiskOccupy();
}
public void onShow() {
HostDependManager.getInst().getMiniAppLifeCycleInstance();
this.mForeBackgroundManager.onForeground();
AudioManager.getInst().onEnterForeground();
GameModuleController.inst().onShow();
getLifeCycleManager().notifyAppShow();
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onShow" });
this.isOpenedSchema = false;
j j = getJsBridge();
if (j != null) {
j.onShow();
} else {
RouteEventCtrl routeEventCtrl = getRouteEventCtrl();
if (routeEventCtrl != null)
routeEventCtrl.onAppShow();
}
InnerHostProcessBridge.setTmaLaunchFlag();
AppProcessManager.getProcessHandler().removeMessages(1);
Iterator<ILifecycleObserver> iterator = this.mObservers.iterator();
while (iterator.hasNext())
((ILifecycleObserver)iterator.next()).onShow();
}
public void publish(int paramInt, String paramString1, String paramString2) {
WebViewManager webViewManager = getWebViewManager();
if (webViewManager != null)
webViewManager.publish(paramInt, paramString1, paramString2);
}
public void registerLifecycleObserver(ILifecycleObserver paramILifecycleObserver) {
this.mObservers.add(paramILifecycleObserver);
}
public void setActivityLife(e parame) {
this.mActivityLife = parame;
}
public void setAppInfo(final AppInfoEntity appInfo) {
this.mAppInfo = appInfo;
ThreadUtil.runOnWorkThread(new Action() {
public void act() {
ApiPermissionManager.initApiWhiteList(appInfo.ttSafeCode);
ApiPermissionManager.initApiBlackList(appInfo.ttBlackCode);
ApiPermissionManager.initHostMethodWhiteList(appInfo.encryptextra);
appInfo.parseDomain();
}
}, (Scheduler)LaunchThreadPool.getInst());
}
public void setCurrentPageHideShareMenuArrayMap(a<String, Boolean> parama) {
this.mCurrentPageHideShareMenuArrayMap = parama;
}
public void setCurrentPagePath(String paramString) {
this.mCurrentPagePath = paramString;
}
public void setCurrentPageType(String paramString) {
this.mCurrentPageType = paramString;
}
public void setCurrentPageUrl(String paramString) {
this.mCurrentPageUrl = paramString;
}
public void setCurrentWebViewId(int paramInt) {
this.mCurrentWebViewId = paramInt;
}
public void setJumpToApp(boolean paramBoolean) {
this.jumpToApp = paramBoolean;
}
public void setMiniAppLaunchConfig(MiniAppLaunchConfig paramMiniAppLaunchConfig) {
this.mMiniAppLaunchConfig = paramMiniAppLaunchConfig;
}
public void setOpenedSchema(boolean paramBoolean) {
this.isOpenedSchema = paramBoolean;
}
public void setSchema(String paramString) {
this.mSchema = paramString;
}
public void setStopReason(String paramString) {
this.mStopReason = paramString;
}
public void setUpdateAppInfo(AppInfoEntity paramAppInfoEntity) {
this.updateAppInfo = paramAppInfoEntity;
}
public void ungisterLifecycleObserver(ILifecycleObserver paramILifecycleObserver) {
this.mObservers.remove(paramILifecycleObserver);
}
static class AppbrandActivityLifeCycleCallback implements Application.ActivityLifecycleCallbacks {
AppbrandActivityLifeCycleCallback(AppbrandApplicationImpl param1AppbrandApplicationImpl) {}
public void onActivityCreated(Activity param1Activity, Bundle param1Bundle) {
HostProcessBridge.callHostLifecycleAction(param1Activity, "onCreate");
}
public void onActivityDestroyed(Activity param1Activity) {}
public void onActivityPaused(Activity param1Activity) {
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onActivityPaused" });
HostProcessBridge.callHostLifecycleAction(param1Activity, "onPause");
}
public void onActivityResumed(Activity param1Activity) {
HostProcessBridge.callHostLifecycleAction(param1Activity, "onResume");
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onActivityResumed" });
}
public void onActivitySaveInstanceState(Activity param1Activity, Bundle param1Bundle) {
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onActivitySaveInstanceState" });
}
public void onActivityStarted(Activity param1Activity) {}
public void onActivityStopped(Activity param1Activity) {
AppBrandLogger.d("tma_AppbrandApplicationImpl", new Object[] { "onActivityStopped" });
}
}
public static interface ILifecycleObserver {
void onHide();
void onShow();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\AppbrandApplicationImpl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package controller;
import model.*;
import x4fit.Utilities;
import java.io.IOException;
import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.Document;
@WebServlet("/forgot")
public class forgotPassword extends HttpServlet {
private static final long serialVersionUID = 1L;
public forgotPassword() {
super();
}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "";
// get email
String email = request.getParameter("email");
///send email to user
// thêm hàm kiểm tra email đã đăng kí rồi hay không ?
if(Account.checkExitEmail(email))
{
// sau đó lấy user dùng email đó
String from = "ngocyen174308@gmail.com";
String pass = "18110402yen";
String username = ""; //userDoc.getString("username");
String subject = "Change you password to X4FIT";
String newPass = "123456@"; // Viết hàm tạo pass mới
String body = "Dear " + username + ",\n\n"
+ "new password for you: " + newPass + "\n\n\n login: " + "https://x4fit.herokuapp.com/login/login.jsp" ;
boolean isBodyHTML = false;
try {
Utilities.sendMail(from,pass, email, subject, body, isBodyHTML);
String hashedPassword = DigestUtils.sha256Hex(newPass);
Account.updateNewPassword(hashedPassword, username);
System.out.println("sSend ddc mail");
url = "/login/success.jsp";
}catch(MessagingException e)
{
System.out.println("Khong send ddc mail");
System.out.println(e);
}
}
else
{url = "/login/forgot.jsp";
response.sendRedirect(url);
}
RequestDispatcher d = request.getRequestDispatcher(url);
d.forward(request, response);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
process(request, response);
}
}
|
package com.lcz.register.web;
/**
* 激活邮件
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lcz.register.entity.User;
import com.lcz.register.service.UserService;
import com.lcz.register.service.UserServiceImpl;
@WebServlet("/ActiveServlet")
public class ActiveServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接受激活码
String code=req.getParameter("code");
//根据激活码查询用户
UserService userService= new UserServiceImpl();
User user = userService.findByCode(code);
//已经查询到,修改用户的状态
if(user!=null) {
//已经查询到了,修改用户的状态
user.setState(1);
// user.setCode(null);
userService.update(user);
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}else {
//根据激活码没有查询到该用户
req.setAttribute("msg", "你的激活码有误,请重新激活");
req.getRequestDispatcher("/msg.jsp").forward(req, resp);
}
}
}
|
package com.jikexueyuan.getphonenum;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
public class MyNumber {
public static List<PhoneInfo> lists = new ArrayList<PhoneInfo>();
public static String GetNumber(Context context){
Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, null, null, null, null);
String phoneNumber;
String phoneName;
while (cursor.moveToNext()) {
phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
phoneName = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
PhoneInfo phoneInfo = new PhoneInfo(phoneName, phoneNumber);
lists.add(phoneInfo);
System.out.println(phoneName+phoneNumber);
}
return null;
}
}
|
package com.beiyelin.common.document;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
/**
* Created by xinsh on 2017/9/11.
*/
@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes = DocumentApplication.class)
//@WebAppConfiguration
public class testMsofficeCharacterizationUtils {
@Test
public void testRun() throws IOException {
try {
String result = MsofficeCharacterizationUtils.run("D:\\temp\\施耐德电气C-Bus智能灯光控制系统介绍.ppt");
System.out.println(result);
result = MsofficeCharacterizationUtils.run("D:\\temp\\Adidis Transition Plan.pptx");
System.out.println(result);
}catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
|
package com.jim.multipos.utils;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.jim.multipos.R;
import com.jim.multipos.data.DatabaseManager;
import com.jim.multipos.data.db.model.inventory.OutcomeProduct;
import com.jim.multipos.data.db.model.inventory.StockQueue;
import com.jim.multipos.data.db.model.products.Product;
import com.jim.multipos.ui.consignment.dialogs.StockPositionsDialog;
import com.jim.multipos.ui.inventory.model.InventoryItem;
import java.text.DecimalFormat;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by developer on 16.11.2017.
*/
public class WriteOffProductDialog extends Dialog {
private WriteOffCallback writeOffCallback;
private Product product;
private View dialogView;
@BindView(R.id.tvStockType)
TextView tvStockType;
@BindView(R.id.flPosition)
FrameLayout flPosition;
@BindView(R.id.tvDialogTitle)
TextView tvDialogTitle;
@BindView(R.id.tvStockRecord)
TextView tvStockRecord;
@BindView(R.id.etShortage)
TextView etShortage;
@BindView(R.id.tvActual)
TextView tvActual;
@BindView(R.id.tvUnit)
TextView tvUnit;
@BindView(R.id.etReason)
TextView etReason;
@BindView(R.id.btnCancel)
TextView btnCancel;
@BindView(R.id.btnNext)
TextView btnNext;
OutcomeProduct outcomeProduct;
double aDouble = 0;
double v1 = 0;
TextWatcherOnTextChange stock_out;
public WriteOffProductDialog(@NonNull Context context, WriteOffCallback writeOffCallback, InventoryItem inventoryItem, DecimalFormat decimalFormat, DatabaseManager databaseManager, StockQueue stockQueue) {
super(context);
this.writeOffCallback = writeOffCallback;
this.product = product;
outcomeProduct = new OutcomeProduct();
if (stockQueue != null) {
outcomeProduct.setCustomPickSock(true);
outcomeProduct.setPickedStockQueueId(stockQueue.getId());
outcomeProduct.setSumCountValue(stockQueue.getAvailable());
} else {
outcomeProduct.setCustomPickSock(false);
outcomeProduct.setSumCountValue(0d);
}
dialogView = getLayoutInflater().inflate(R.layout.write_off_dialog, null);
requestWindowFeature(Window.FEATURE_NO_TITLE);
ButterKnife.bind(this, dialogView);
setContentView(dialogView);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
tvDialogTitle.setText("Write-off: " + inventoryItem.getProduct().getName());
if (!outcomeProduct.getCustomPickSock())
switch (inventoryItem.getProduct().getStockKeepType()) {
case Product.FIFO:
tvStockType.setText("FIFO");
break;
case Product.LIFO:
tvStockType.setText("LIFO");
break;
case Product.FEFO:
tvStockType.setText("FEFO");
break;
}
else tvStockType.setText("CUSTOM");
outcomeProduct.setProduct(inventoryItem.getProduct());
tvStockRecord.setText(decimalFormat.format(inventoryItem.getInventory()));
tvUnit.setText(inventoryItem.getProduct().getMainUnit().getAbbr());
if (inventoryItem.getProduct().getMainUnit().getAbbr().equals("pcs"))
etShortage.setInputType(InputType.TYPE_CLASS_NUMBER);
else etShortage.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL);
flPosition.setOnClickListener(view -> {
StockPositionsDialog stockPositionsDialog = new StockPositionsDialog(getContext(), outcomeProduct, new ArrayList<>(), null, databaseManager);
stockPositionsDialog.setListener(new StockPositionsDialog.OnStockPositionsChanged() {
@Override
public void onConfirm(OutcomeProduct outcomeProduct) {
if (outcomeProduct.getCustomPickSock()) {
tvStockType.setText("Custom");
} else {
switch (inventoryItem.getProduct().getStockKeepType()) {
case Product.FIFO:
tvStockType.setText("FIFO");
break;
case Product.LIFO:
tvStockType.setText("LIFO");
break;
case Product.FEFO:
tvStockType.setText("FEFO");
break;
}
}
WriteOffProductDialog.this.outcomeProduct = outcomeProduct;
etShortage.removeTextChangedListener(stock_out);
etShortage.setText(decimalFormat.format(outcomeProduct.getSumCountValue()));
etShortage.addTextChangedListener(stock_out);
}
});
stockPositionsDialog.show();
});
stock_out = new TextWatcherOnTextChange() {
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
databaseManager.getAvailableCountForProduct(inventoryItem.getProduct().getId()).subscribe(available -> {
if (!etShortage.getText().toString().isEmpty()) {
try {
v1 = decimalFormat.parse(etShortage.getText().toString()).doubleValue();
} catch (Exception e) {
etShortage.setError(context.getString(R.string.invalid));
outcomeProduct.setSumCountValue(-1d);
return;
}
} else {
v1 = 0;
}
outcomeProduct.setCustomPickSock(false);
outcomeProduct.setPickedStockQueueId(0l);
switch (inventoryItem.getProduct().getStockKeepType()) {
case Product.FIFO:
tvStockType.setText("FIFO");
break;
case Product.LIFO:
tvStockType.setText("LIFO");
break;
case Product.FEFO:
tvStockType.setText("FEFO");
break;
}
if (available < v1) {
etShortage.setError("Stock out");
outcomeProduct.setSumCountValue(-1d);
} else {
outcomeProduct.setSumCountValue(v1);
etShortage.setError(null);
}
aDouble = inventoryItem.getInventory() - v1;
tvActual.setText(decimalFormat.format(aDouble));
});
}
};
etShortage.setText(decimalFormat.format(outcomeProduct.getSumCountValue()));
tvActual.setText(decimalFormat.format(inventoryItem.getInventory() - outcomeProduct.getSumCountValue()));
etShortage.addTextChangedListener(stock_out);
btnNext.setOnClickListener(view -> {
if (outcomeProduct.getSumCountValue() == 0 || outcomeProduct.getSumCountValue() < 0 || etShortage.getText().toString().isEmpty()) {
etShortage.setError("Invalid value");
return;
}
if (etReason.getText().toString().isEmpty()) {
etReason.setError(context.getString(R.string.please_enter_write_off_reason));
return;
}
outcomeProduct.setOutcomeType(OutcomeProduct.WASTE);
outcomeProduct.setDiscription(etReason.getText().toString());
UIUtils.closeKeyboard(etShortage, context);
Handler handler = new Handler();
handler.postDelayed(() -> {
outcomeProduct.setOutcomeDate(System.currentTimeMillis());
writeOffCallback.writeOff(inventoryItem, outcomeProduct);
dismiss();
}, 300);
});
btnCancel.setOnClickListener(view -> {
dismiss();
});
}
public interface WriteOffCallback {
void writeOff(InventoryItem inventoryItem, OutcomeProduct outcomeProduct);
}
}
|
package com.jscherrer.personal.deployment;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.io.IOException;
import java.util.regex.Pattern;
public class StartUpScriptTest {
@Test
public void defaultScriptHasAllPropertiesReplaced() throws IOException {
String defaultScript = StartUpScript.getDefaultStartUpScriptForS3File("S3Path", "AppName");
Pattern dollarBraceWrappedCharacters = Pattern.compile("\\$\\{.+\\}");
Assertions.assertThat(defaultScript).doesNotContainPattern(dollarBraceWrappedCharacters);
}
@Test
public void replacePropertyInScript() {
String scriptString = "My replaced variable is now ${replaceMe}";
String expectedString = "My replaced variable is now here";
Assertions.assertThat(StartUpScript.replacePropertyInScript(scriptString, "replaceMe", "here"))
.isEqualTo(expectedString);
}
} |
package javalab3;
import java.util.Scanner;
public class Sumofrows_19BDS0127 {
public static void main(String[] args) {
System.out.println(" Solved by Reg No. : 19BDS0127");
System.out.println(" ---------");
int i,j;
Scanner test=new Scanner(System.in);
System.out.println("Enter the number of rows in the matrix:");
int m=test.nextInt();
System.out.println("Enter the number of columns in the matrix:");
int n=test.nextInt();
int [][] A= new int[n][m];
System.out.println("Enter the Matrix A:");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
A[i][j]=test.nextInt( );
}
}
System.out.println("Sum of rows of the given matrix :");
for(i=0;i<m;i++)
{
int sum=0;
for(j=0;j<n;j++)
{
sum=sum+A[i][j];
}
System.out.println(sum);
System.out.println(" ");
}
}
}
|
package net.sf.ardengine.rpg.multiplayer.udplib;
import com.gmail.lepeska.martin.udplib.files.IFileShareListener;
import net.sf.ardengine.rpg.multiplayer.network.INetworkFileListener;
import java.io.File;
/**
* Layer between ArdEngine INetworkFileListener and UDPLib IFileShareListener implementation.
*/
class UDPLibFileListener implements IFileShareListener {
protected final INetworkFileListener gameListener;
/**
* @param gameListener ArdEngine INetworkListener to be mapped as IGroupListener
*/
UDPLibFileListener(INetworkFileListener gameListener) {
this.gameListener = gameListener;
}
@Override
public void onFinished(File file) {
gameListener.onFinished(file);
}
@Override
public void onFail(File file, Exception e) {
gameListener.onFail(file, e);
}
}
|
package bricks;
public class MediumBrick extends BaseBrick {
private int lives = 3;
public MediumBrick(int x, int y) {
super(x, y);
super.setLives(lives);
super.setBrickType(lives);
}
}
|
package shapes.polygon;
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Polygon extends base.ClosedShape {
private int nPoints;
private int[] xPoints;
private int[] yPoints;
protected static final int MIN_LENGTH = 4;
public Polygon() {
}
public Polygon(Point theCenter, int frameWidth, Color frameColor, Color fillColor) {
super(theCenter, frameWidth, frameColor, fillColor);
}
public Polygon(Point theCenter, List<Point> points, int frameWidth, Color frameColor, Color fillColor) {
super(theCenter, frameWidth, frameColor, fillColor);
setPoints(points);
}
public void setPoints(List<Point> points) {
setnPoints(points.size());
setxPoints(new int[getnPoints()]);
setyPoints(new int[getnPoints()]);
int i = 0;
for (Point p : points) {
getxPoints()[i] = p.x;
getyPoints()[i++] = p.y;
}
}
public List<Point> getPoints() {
List<Point> points = new ArrayList<>(getnPoints());
for (int i = 0; i < getnPoints(); ++i)
points.add(new Point(getxPoints()[i], getyPoints()[i]));
return points;
}
public int getPointsSize() {
return getnPoints();
}
public void addPoint(Point pt) {
if (getnPoints() >= getxPoints().length || getnPoints() >= getyPoints().length) {
int newLength = getnPoints() * 2;
if (newLength < MIN_LENGTH) {
newLength = MIN_LENGTH;
} else if ((newLength & (newLength - 1)) != 0) {
newLength = Integer.highestOneBit(newLength);
}
setxPoints(Arrays.copyOf(getxPoints(), newLength));
setyPoints(Arrays.copyOf(getyPoints(), newLength));
}
getxPoints()[getnPoints()] = pt.x;
getyPoints()[getnPoints()] = pt.y;
setnPoints(getnPoints() + 1);
setLocation(computeCenter());
}
public void setLastPoint(Point pt) {
getxPoints()[getnPoints() - 1] = pt.x;
getyPoints()[getnPoints() - 1] = pt.y;
setLocation(computeCenter());
}
private Point computeCenter() {
Point centroid = new Point(0, 0);
double signedArea = 0.0;
double x0; // Current vertex X
double y0; // Current vertex Y
double x1; // Next vertex X
double y1; // Next vertex Y
double a; // Partial signed area
for (int i = 0; i < getnPoints() - 1; ++i) {
x0 = getxPoints()[i];
y0 = getyPoints()[i];
x1 = getxPoints()[i + 1];
y1 = getyPoints()[i + 1];
a = x0 * y1 - x1 * y0;
signedArea += a;
centroid.x += (x0 + x1) * a;
centroid.y += (y0 + y1) * a;
}
x0 = getxPoints()[getnPoints() - 1];
y0 = getyPoints()[getnPoints() - 1];
x1 = getxPoints()[0];
y1 = getyPoints()[0];
a = x0 * y1 - x1 * y0;
signedArea += a;
centroid.x += (x0 + x1) * a;
centroid.y += (y0 + y1) * a;
signedArea *= 0.5;
centroid.x /= (6.0 * signedArea);
centroid.y /= (6.0 * signedArea);
return centroid;
}
@Override
public void draw(Graphics2D g) {
g.setStroke(new BasicStroke(getFrameWidth()));
g.setColor(getFillColor());
g.fillPolygon(getxPoints(), getyPoints(), getnPoints());
g.setColor(getFrameColor());
g.drawPolygon(getxPoints(), getyPoints(), getnPoints());
}
@Override
public boolean contains(Point pt) {
int hits = 0;
int lastx = getxPoints()[getnPoints() - 1];
int lasty = getyPoints()[getnPoints() - 1];
int curx, cury;
// Walk the edges of the polygon
for (int i = 0; i < getnPoints(); lastx = curx, lasty = cury, i++) {
curx = getxPoints()[i];
cury = getyPoints()[i];
if (cury == lasty) {
continue;
}
int leftx;
if (curx < lastx) {
if (pt.x >= lastx) {
continue;
}
leftx = curx;
} else {
if (pt.x >= curx) {
continue;
}
leftx = lastx;
}
double test1, test2;
if (cury < lasty) {
if (pt.y < cury || pt.y >= lasty) {
continue;
}
if (pt.x < leftx) {
hits++;
continue;
}
test1 = pt.x - curx;
test2 = pt.y - cury;
} else {
if (pt.y < lasty || pt.y >= cury) {
continue;
}
if (pt.x < leftx) {
hits++;
continue;
}
test1 = pt.x - lastx;
test2 = pt.y - lasty;
}
if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
hits++;
}
}
return ((hits & 1) != 0);
}
@Override
public void move(Point pt) {
Point theCenter = getLocation();
int deltaX = pt.x - theCenter.x;
int deltaY = pt.y - theCenter.y;
for (int i = 0; i < getnPoints(); i++) {
getxPoints()[i] += deltaX;
getyPoints()[i] += deltaY;
}
super.move(pt);
}
public int[] getxPoints() {
return xPoints;
}
public void setxPoints(int[] xPoints) {
this.xPoints = xPoints;
}
public int[] getyPoints() {
return yPoints;
}
public void setyPoints(int[] yPoints) {
this.yPoints = yPoints;
}
public int getnPoints() {
return nPoints;
}
public void setnPoints(int nPoints) {
this.nPoints = nPoints;
}
} |
package ksichenko.oop_task;
public class FixedSalaryEmploy extends Employ {
public FixedSalaryEmploy(String name, String sex, String salary, int id) {
super(name, sex, salary, id);
}
void calculateSalary() {
int salary = 10000;
System.out.println("Employ salary amount: " + salary);
}
}
|
/*
* Copyright 2015 Michal Harish, michal.harish@gmail.com
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.amient.kafka.metrics;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
public class InfluxDbSinkTask extends SinkTask {
private InfluxDbPublisher publisher = null;
private MeasurementConverter converter = null;
@Override
public String version() {
return new InfluxDbSinkConnector().version();
}
@Override
public void start(Map<String, String> props) {
Properties publisherConfig = new Properties();
publisherConfig.putAll(props);
publisher = new InfluxDbPublisher(publisherConfig);
converter = new MeasurementConverter();
}
@Override
public void put(Collection<SinkRecord> sinkRecords) {
for (SinkRecord record : sinkRecords) {
MeasurementV1 measurement = converter.fromConnectData(record.valueSchema(), record.value());
publisher.publish(measurement);
}
}
@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) {
//nothing to flush
}
@Override
public void stop() {
if (publisher != null) publisher.close();
}
}
|
/*
* EntityUtil.java
* This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin.
* $Id$
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
*/
package ru.otus.models;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
public class EntityUtil
{
public static <T> String convertToJson(T entity)
{
Jsonb jsonb = JsonbBuilder.create();
return jsonb.toJson(entity);
}
public static <T> T convertFromJson(String json, Class<T> clazz)
{
Jsonb jsonb = JsonbBuilder.create();
return jsonb.fromJson(json, clazz);
}
public static boolean isOdd(EmpEntity e)
{
return ! (e.getId() % 2 == 0);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package edu.kis.powp.command;
import java.util.List;
public class ComplexCommand implements DriverCommand{
public List<DriverCommand> list;
public ComplexCommand(List<DriverCommand> list){
this.list = list;
}
@Override public void execute() {
for (DriverCommand command:list){
command.execute();
}
}
} |
package com.dubbo.dubbo_service.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.dubbo_common.dubbo_common.service.UserService;
import org.springframework.stereotype.Component;
@Service(interfaceClass = UserService.class,weight = 100)
@Component
public class UserServiceImpl implements UserService {
@Override
public String hello() {
return "你在使用dubbo1.";
}
}
|
package testFunction;
public class Tower {
public static void main(String[] args)
{
int nDisks = 3;
doTowers(nDisks,'A','B','C');
}
public static void doTowers(int topN, char from, char inter, char to)
{
if(topN == 1){
System.out.println("Disk 1 from " + from + " to " + to);
} else {
doTowers(topN - 1,from,to,inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
doTowers(topN - 1,inter,from,to);
}
}
}
|
package utiles;
import java.rmi.Naming;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import javafx.util.Duration;
import jpaModel.Patient;
import services.IPatient;
public class Bar extends Application {
final static String itemA = "A";
final static String itemB = "B";
final static String itemC = "C";
@Override
public void start(Stage stage) {
final NumberAxis xAxis = new NumberAxis();
final CategoryAxis yAxis = new CategoryAxis();
final BarChart<Number, String> bc = new BarChart<Number, String>(xAxis, yAxis);
XYChart.Series series1=new XYChart.Series();
XYChart.Series series2=new XYChart.Series();
XYChart.Series series3 =new XYChart.Series();
bc.setTitle("TYPES DE VISITE LORS DES 3 PRECEDENTS MOIS");
xAxis.setLabel("VALEUR");
xAxis.setTickLabelRotation(90);
yAxis.setLabel("VISITES");
try {
IPatient stub = (IPatient) Naming.lookup("rmi://localhost:1099/patient");
List< Patient> l = stub.listePatient();
int mois=LocalDateTime.now().getMonth().getValue();
int value3=0;
int value2=0;
int value1=0;
String nom="";
String nomb="";String nomc="";
for (Patient marque : l) {
if(marque.getMatricule().charAt(0)=='C' )
{
value3++;
}
if(marque.getMatricule().charAt(0)=='V' )
{
value2++;
}
if(marque.getMatricule().charAt(0)=='H' )
{
value1++;
}
}
series1.setName("I YA 3 MOIS"+" "+value1+value2+value3+" FCFA");
series1.getData().add(new XYChart.Data(value1,"Consultation"));
series1.getData().add(new XYChart.Data(value2, "Vaccination"));
series1.getData().add(new XYChart.Data(value3, "Hospiatlisation"));
value3=0;
value2=0;
value1=0;
nom="";
nomb="";
nomc="";
for (Patient marque : l) {
if(marque.getMatricule().charAt(0)=='C' )
{
value3++;
}
if(marque.getMatricule().charAt(0)=='V' )
{
value2++;
}
if(marque.getMatricule().charAt(0)=='H' )
{
value1++;
}
}
series2.setName(nom+" "+value1+value2+value3+" FCFA");
series2.getData().add(new XYChart.Data(value1, "Consultation"));
series2.getData().add(new XYChart.Data(value2, "Vaccination"));
series2.getData().add(new XYChart.Data(value3, "Hospiatlisation"));
value3=0;
value2=0;
value1=0;
nom="";
nomb="";
nomc="";
for (Patient marque : l) {
if(marque.getMatricule().charAt(0)=='C' )
{
value3++;
}
if(marque.getMatricule().charAt(0)=='V' )
{
value2++;
}
if(marque.getMatricule().charAt(0)=='H' )
{
value1++;
}
}
series3 = new XYChart.Series();
series3.setName("Consultation"+" "+ value1+value2+value3 +" FCFA");
series3.getData().add(new XYChart.Data(value1, "Consultation"));
series3.getData().add(new XYChart.Data(value2, "Vaccination"));
series3.getData().add(new XYChart.Data(value3, "Hospiatlisation"));
} catch (Exception e) {
}
// XYChart.Series series2 = new XYChart.Series();
// series2.setName("MINERALE");
// series2.getData().add(new XYChart.Data(50, itemA));
// series2.getData().add(new XYChart.Data(41, itemB));
// series2.getData().add(new XYChart.Data(45, itemC));
//
// XYChart.Series series3 = new XYChart.Series();
// series3.setName("JUS LOCAUX");
//
// series3.getData().add(new XYChart.Data(45, itemA));
// series3.getData().add(new XYChart.Data(44, itemB));
// series3.getData().add(new XYChart.Data(18, itemC));
Timeline tl = new Timeline();
tl.getKeyFrames().add(new KeyFrame(Duration.seconds(3),
new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent actionEvent) {
for (XYChart.Series<Number, String> series : bc.getData()) {
for (XYChart.Data<Number, String> data : series.getData()) {
data.setXValue(1);
}
}
}
}));
tl.setCycleCount(Animation.INDEFINITE);
tl.play();
Scene scene = new Scene(bc, 900, 800);
bc.getData().addAll(series1, series2, series3);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.yunhe.billmanagement.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunhe.billmanagement.entity.RunningAccounts;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* <p>
* 资金流水表(ymy) Mapper 接口
* </p>
*
* @author 杨明月
* @since 2019-01-02
*/
@Repository
public interface RunningAccountsMapper extends BaseMapper<RunningAccounts> {
/**
* <P>
* 资金流水表
* </P>
* @param page 分页的参数存在一个对象里
* @param runningAccounts 资金流水
* @return 供应商应付欠款表:分页的结果集
*/
List<RunningAccounts> selectRaPage(Page page, RunningAccounts runningAccounts);
/**
* <p>
* 资金流水表(ymy) 服务类
* </p>
* @return 查询总收入和总支出
*/
@Select("select SUM(ra_income) as incomes,SUM(ra_outcome) AS outcomes from running_accounts")
Map<String,Object> selectCountMap();
/**
* @author 史江浩
* @since 2019-01-24 12:18
* 查询最大id值的所剩金额
* @return 最大id值的所剩金额
*/
RunningAccounts selectRunningMaxIdMoney();
}
|
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
Swingclient swing = new Swingclient();
swing.setVisible(true);
}
}
|
package com.pxene;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
/**
* Created by young on 2014/12/29.
*/
public class Constant {
public static final Logger logger = LogManager.getLogger(Constant.class);
public static final String HDFSColunms = "";
public static String getProperties(Properties properties, String key) {
if (null == key) {
//返回key的集合,用"|"分割
Set<Object> keys = properties.keySet();
StringBuilder sb = new StringBuilder();
for (Object obj : keys) {
sb.append(obj).append("|");
}
sb.substring(0, sb.length()-2);
return sb.toString();
} else {
//返回指定key的值
return (String)properties.get(key);
}
}
public static Object[] getProperties(Properties properties) {
Object[] objects = new Object[65];
Set<Object> keys = properties.keySet();
for (Object obj : keys) {
String keyStr = (String)obj;
int key = Integer.valueOf(keyStr) - 1;
Map<String, Object> map = new HashMap<>();
map.put(String.valueOf(properties.get(obj)), null);
objects[key] = map;
}
return objects;
}
public static Object[] getProperties(File file) {
Properties p = new Properties();
try {
FileInputStream in = new FileInputStream(file);
p.load(in);
return getProperties(p);
} catch (IOException e) {
logger.error(e.toString());
}
return null;
}
// public static String getProperties(File file) {
//
// Properties p = new Properties();
// try {
// FileInputStream in = new FileInputStream(file);
// p.load(in);
// return getProperties(p, null);
// } catch (IOException e) {
// logger.error(e.toString());
// }
// return "";
//
// }
public static File getFileFromSystem(String fileName) {
String filePath = Class.class.getResource("/").getPath() + "/" + fileName;
return new File(filePath);
}
}
|
package com.sdk4.boot.service;
import com.sdk4.boot.common.BaseResponse;
import com.sdk4.boot.domain.AdminUser;
/**
* 管理用户接口
*
* @author sh
*/
public interface AdminUserService {
/**
* 登录
*
* @param mobile
* @param password
* @return
*/
BaseResponse<AdminUser> loginByMobile(String mobile, String password);
/**
* 根据 id 获取用户
*
* @param id
* @return
*/
AdminUser getAdminUser(String id);
}
|
package leti.asd.db;
import leti.asd.db.db_list.DBrecord;
import leti.asd.db.db_list.ListDB;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
/**
* Project transportDB
* Created by nikolaikobyzev on 07.11.16.
*/
class FileController {
public static void saveToFile(ListDB listDB) throws IOException {
FileOutputStream fileOut = new FileOutputStream("transportDB");
DataOutputStream out = new DataOutputStream(fileOut);
out.writeInt(listDB.size());
for(DBrecord rec : listDB) {
out.writeUTF(rec.getFullName());
out.writeInt(rec.getLevel());
out.writeInt(rec.getYears_work());
out.writeInt(rec.getSalary());
}
out.close();
}
public static void loadFromFile(ListDB listDB) throws IOException {
FileInputStream fileIn = new FileInputStream("transportDB");
DataInputStream in = new DataInputStream(fileIn);
int i = in.readInt();
while (i > 0) {
DBrecord rec = new DBrecord();
rec.setFullName(in.readUTF());
rec.setLevel(in.readInt());
rec.setYears_work(in.readInt());
rec.setSalary(in.readInt());
listDB.add(rec);
--i;
}
in.close();
}
public static void loadFromTextFile(ListDB listDB, String name) throws IOException {
List<String> lines = Files.readAllLines(new File(name).toPath());
for(String line : lines) {
String[] data = line.split("\\|");
if(data.length<1) continue;
DBrecord rec = new DBrecord();
rec.setFullName(data[0]);
if(data.length < 2) {
listDB.add(rec);
continue;
}
int level = 0;
try {
level = Integer.parseInt(data[1]);
} catch (NumberFormatException e) {
System.out.println("Ошибка чтения разряда!");
}
rec.setLevel(level);
int years_work = 0;
try {
years_work = Integer.parseInt(data[2]);
} catch (NumberFormatException e) {
System.out.println("Ошибка чтения стажа!");
}
rec.setYears_work(years_work);
int salary = 0;
try {
salary = Integer.parseInt(data[3]);
} catch (NumberFormatException e) {
System.out.println("Ошибка чтения зарплаты!");
}
rec.setSalary(salary);
listDB.add(rec);
}
}
}
|
package baekjoon.greedy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Test_13305 {
public static void main(String[] args) throws IOException {
//나름 아이디어도 잘 떠올라서 쉽게 풀 수 있겠다고 생각했는데 틀렸다고 떴다.
//나는 먼저 현재 가격보다 낮은 가격이 나오기 전까지 반복문을 통해 인덱스를 하나씩 더해주고 그 차이만큼 for 문을 돌려
//답을 구했는데 어딘가 잘못된 곳이 있는거 같다. 발견하지는 못했다...
//검색해서 풀이를 보니 초기값을 구해주고 현재 인덱스와 다음 인덱스를 먼저 나누고 비교한 뒤 더했더라.
//이게 훨씬 더 깔끔한 풀이인 거 같아서 참고하여 해결했다.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
long[] lengths = new long[n-1];
long[] prices = new long[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < lengths.length; i++) {
lengths[i] = Long.parseLong(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (int i = 0; i < prices.length; i++) {
prices[i] = Long.parseLong(st.nextToken());
}
long answer = prices[0] * lengths[0];
int nowIndex = 0;
int nextIndex = nowIndex + 1;
while (nextIndex < n - 1) {
if (prices[nowIndex] < prices[nextIndex]) {
answer += prices[nowIndex] * lengths[nextIndex];
}else {
answer += prices[nextIndex] * lengths[nextIndex];
nowIndex = nextIndex;
}
nextIndex++;
}
System.out.println(answer);
// while (true) {
// int tmpIndex = cityIndex;
// while (true) {
// if (cityIndex == n-1) {
// break;
// }
// cityIndex++;
// if (prices[cityIndex-1] > prices[cityIndex]) {
// break;
// }
// }
// for (int i = tmpIndex; i < cityIndex; i++) {
// answer += prices[tmpIndex] * lengths[i];
// }
// if (cityIndex == n-1) {
// break;
// }
// }
}
}
|
package com.fleet.graphql.resolver;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
import com.fleet.graphql.entity.Author;
import com.fleet.graphql.entity.AuthorInput;
import com.fleet.graphql.entity.Book;
import com.fleet.graphql.entity.BookInput;
import org.springframework.stereotype.Component;
/**
* @author April Han
*/
@Component
public class BookMutationResolver implements GraphQLMutationResolver {
public Book insertBook(BookInput bookInput) {
Book book = new Book();
book.setId(3);
book.setTitle(bookInput.getTitle());
book.setPublisher(bookInput.getPublisher());
AuthorInput authorInput = bookInput.getAuthorInput();
if (authorInput != null) {
Author author = new Author();
author.setId(3);
author.setName(authorInput.getName());
author.setAge(authorInput.getAge());
book.setAuthor(author);
}
return book;
}
}
|
package gov.samhsa.c2s.pcm.service.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class ConsentExportException extends RuntimeException {
/**
* Instantiates a new DocumentSegmentation exception.
*/
public ConsentExportException() {
super();
}
/**
* Instantiates a new DocumentSegmentation exception.
*
* @param arg0 the arg0
* @param arg1 the arg1
*/
public ConsentExportException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
/**
* Instantiates a new DocumentSegmentation exception.
*
* @param arg0 the arg0
*/
public ConsentExportException(String arg0) {
super(arg0);
}
/**
* Instantiates a new DocumentSegmentation exception.
*
* @param arg0 the arg0
*/
public ConsentExportException(Throwable arg0) {
super(arg0);
}
}
|
package inheritance4.service;
public class Employee {
String name;
String address;
int age;
String gender;
public Employee(String name, String address, int age, String gender) {
super();
this.name = name;
this.address = address;
this.age = age;
this.gender = gender;
}
public void display() {
System.out.println("Name of Employee : "+name);
System.out.println("Address : "+address);
System.out.println("Age : "+age);
System.out.println("Gender : "+gender);
}
}
|
package com.yinghai.a24divine_user.module.divine.index;
import android.content.Context;
import android.view.View;
import com.example.fansonlib.base.BaseDataAdapter;
import com.example.fansonlib.base.BaseHolder;
import com.yinghai.a24divine_user.R;
import com.yinghai.a24divine_user.bean.BusinessBean;
import com.yinghai.a24divine_user.callback.OnAdapterListener;
import com.yinghai.a24divine_user.constant.ConstAdapter;
/**
* @author Created by:fanson
* Created Time: 2017/11/15 17:06
* Describe:大师业务的适配器
*/
public class BusinessAdapter extends BaseDataAdapter<BusinessBean.DataBean.TfBusinessListBean>{
private OnAdapterListener mOnAdapterListener;
public void setmOnAdapterListener(OnAdapterListener listener){
mOnAdapterListener = listener;
}
public BusinessAdapter(Context context) {
super(context);
}
@Override
public int getLayoutRes(int i) {
return R.layout.master_divine_detail_bottom;
}
@Override
public void bindCustomViewHolder(BaseHolder holder, final int position) {
holder.setText(R.id.tv_divine_type,getItem(position).getBName());
holder.setText(R.id.tv_divine_price,getItem(position).getBPrice()/100+context.getString(R.string.price_every));
holder.setText(R.id.tv_divine_descripe,getItem(position).getBIntroduction());
holder.setText(R.id.tv_divine_has_num,context.getString(R.string.have_benn)+getItem(position).getBDeals()+context.getString(R.string.consult));
holder.setOnClickListener(R.id.rootView, new View.OnClickListener() {
@Override
public void onClick(View view) {
mOnAdapterListener.clickItem(ConstAdapter.CLICK_MASTER_BUSINESS,getItem(position));
}
});
}
}
|
package sevenkyu.paintletterboxes;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class PaintLetterBoxesTest {
PaintLetterBoxes paintLetterBoxes;
@BeforeEach
public void init() {
paintLetterBoxes = new PaintLetterBoxes();
}
@Test
public void paintLetterboxes_shouldReturnWithDigitOccurrence() {
// Given
// When
int[] letters = paintLetterBoxes.paintLetterboxes(125, 132);
// Then
assertThat(letters).isEqualTo(new int[]{1, 9, 6, 3, 0, 1, 1, 1, 1, 1});
}
} |
package pl.cwanix.opensun.model.character;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class InventoryModel {
private int id;
private int money;
private int inventoryLock;
private byte[] inventoryItem;
private byte[] tmpInventoryItem;
private byte[] equipItem;
}
|
package Kata4final;
import Kata4final.Histogram;
import Kata4final.HistogramDisplay;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class Kata4 {
public static void main(String[] args) throws FileNotFoundException, IOException {
String pathname="/Users/iraidacorvo/NetBeansProjects/kata4vfinal-master/emails.txt";
ArrayList <String> mailList = MailReader.read(pathname);
Histogram<String> histogram= MailHistogramBuilder.build(mailList);
HistogramDisplay histoDisplay = new HistogramDisplay(histogram);
histoDisplay.execute();
}
}
|
package org.leandropadua.knockknock.controllers;
import org.leandropadua.knockknock.models.StringReverser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReverseWordsController {
@RequestMapping("/api/ReverseWords")
public String reverseWordsInSentence(@RequestParam(name="sentence",required=false, defaultValue="") String sentence) {
return StringReverser.reverse(sentence);
}
}
|
package com.jdk11.ssl.jdk11Client;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
public class Jdk11LoadTest {
//client is share to test connection reuse
Jdk11Client httpClient = new Jdk11Client();
public static String url = "https://localhost:8443/100kText";
Integer threads = 40;
Integer cycles = 100;
public void http2LoadTest() throws InterruptedException, ExecutionException, TimeoutException {
ExecutorService executor = Executors.newFixedThreadPool(threads);
List<HttpClientThread> actors = new ArrayList<>();
for (int i = 0; i < cycles; i++) {
actors.add(new HttpClientThread(httpClient,url));
}
List<Future<Long>> results = submitAll(executor, actors);
executor.shutdown();
for (Future<Long> result : results) {
try {
result.get(3, TimeUnit.SECONDS);
}catch(Exception all){}
}
}
private static <T> List<Future<T>> submitAll(ExecutorService executor, Collection<? extends Callable<T>> tasks) {
List<Future<T>> result = new ArrayList<Future<T>>(tasks.size());
for (Callable<T> task : tasks)
result.add(executor.submit(task));
return result;
}
public class HttpClientThread implements Callable<Long> {
Jdk11Client httpClient;
String url;
public HttpClientThread(Jdk11Client httpClient, String url) {
this.httpClient = httpClient;
this.url = url;
}
public Long call() throws Exception {
httpClient.call(url);
return 0l;
}
}
}
|
package com.tencent.mm.plugin.qqmail.ui;
import android.view.View;
import android.view.View.OnFocusChangeListener;
class MailAddrsViewControl$7 implements OnFocusChangeListener {
final /* synthetic */ MailAddrsViewControl mhb;
MailAddrsViewControl$7(MailAddrsViewControl mailAddrsViewControl) {
this.mhb = mailAddrsViewControl;
}
public final void onFocusChange(View view, boolean z) {
if (MailAddrsViewControl.g(this.mhb) != null) {
MailAddrsViewControl.g(this.mhb).hg(z);
}
String obj = this.mhb.mgU.getEditableText().toString();
if (!z && obj.trim().length() > 0) {
MailAddrsViewControl.a(this.mhb, obj, false);
}
if (MailAddrsViewControl.c(this.mhb) != null && MailAddrsViewControl.c(this.mhb).isSelected()) {
MailAddrsViewControl.c(this.mhb).setSelected(z);
MailAddrsViewControl.a(this.mhb, null);
}
this.mhb.bpb();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.ntp;
import java.io.IOException;
import java.net.InetAddress;
import java.time.Duration;
import org.apache.commons.net.examples.ntp.SimpleNTPServer;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* JUnit test class for NtpClient using SimpleNTPServer
*/
public class TestNtpClient {
private static SimpleNTPServer server;
@BeforeClass
public static void oneTimeSetUp() throws IOException {
// one-time initialization code
server = new SimpleNTPServer(0);
server.connect();
try {
server.start();
} catch (final IOException e) {
Assert.fail("failed to start NTP server: " + e);
}
Assert.assertTrue(server.isStarted());
// System.out.println("XXX: time server started");
boolean running = false;
for (int retries = 0; retries < 5; retries++) {
running = server.isRunning();
if (running) {
break;
}
// if not running then sleep 2 seconds and try again
try {
Thread.sleep(2000);
} catch (final InterruptedException e) {
// ignore
}
}
Assert.assertTrue(running);
}
@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
if (server != null) {
server.stop();
server = null;
}
}
@Test
public void testGetTime() throws IOException {
final long currentTimeMillis = System.currentTimeMillis();
final NTPUDPClient client = new NTPUDPClient();
// timeout if response takes longer than 2 seconds
client.setDefaultTimeout(Duration.ofSeconds(2));
try {
// Java 1.7: use InetAddress.getLoopbackAddress() instead
final InetAddress addr = InetAddress.getByAddress("loopback", new byte[] { 127, 0, 0, 1 });
final TimeInfo timeInfo = client.getTime(addr, server.getPort());
Assert.assertNotNull(timeInfo);
Assert.assertTrue(timeInfo.getReturnTime() >= currentTimeMillis);
final NtpV3Packet message = timeInfo.getMessage();
Assert.assertNotNull(message);
final TimeStamp rcvTimeStamp = message.getReceiveTimeStamp();
final TimeStamp xmitTimeStamp = message.getTransmitTimeStamp();
Assert.assertTrue(xmitTimeStamp.compareTo(rcvTimeStamp) >= 0);
final TimeStamp originateTimeStamp = message.getOriginateTimeStamp();
Assert.assertNotNull(originateTimeStamp);
Assert.assertTrue(originateTimeStamp.getTime() >= currentTimeMillis);
Assert.assertEquals(NtpV3Packet.MODE_SERVER, message.getMode());
// following assertions are specific to the SimpleNTPServer
final TimeStamp referenceTimeStamp = message.getReferenceTimeStamp();
Assert.assertNotNull(referenceTimeStamp);
Assert.assertTrue(referenceTimeStamp.getTime() >= currentTimeMillis);
Assert.assertEquals(NtpV3Packet.VERSION_3, message.getVersion());
Assert.assertEquals(1, message.getStratum());
Assert.assertEquals("LCL", NtpUtils.getReferenceClock(message));
} finally {
client.close();
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.b2b.facades.dropdownlist.impl;
import java.util.ArrayList;
import java.util.List;
import com.cnk.travelogix.b2b.facades.dropdownlist.DropDownListFacade;
/**
*
*/
public class CityDropDownListFacade implements DropDownListFacade
{
@Override
public List<String> getDropDownListContents()
{
final List<String> cities = new ArrayList<String>();
cities.add("New Delhi");
cities.add("Mumbai");
cities.add("Kolkata");
cities.add("Chennai");
cities.add("Bangalore");
return cities;
}
}
|
package com.example.interface_alfatest;
import android.app.Activity;
public class ActivityInfo extends Activity {
}
|
/**
* Rate.java
*
* Skarpetis Dimitris 2016, all rights reserved.
*/
package dskarpetis.elibrary.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* Rate domain object
*
* @author dskarpetis
*/
@Entity
@Table(name = "rate", schema = "public")
public class Rate implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name = "seq_gen_rate", sequenceName = "auto_increment_rate", initialValue = 1, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "seq_gen_rate")
@Column(name = "rate_id")
private int rateID;
@ManyToOne
@JoinColumn(name = "user_login_id")
private UserLogin userLogin;
@ManyToOne
@JoinColumn(name = "book_id")
private Book book;
@Column(name = "rate_number")
private Double rateNumber;
/**
* @return the rateID
*/
public int getRateID() {
return rateID;
}
/**
* @param rateID
* the rateID to set
*/
public void setRateID(int rateID) {
this.rateID = rateID;
}
/**
* @return the userLogin
*/
public UserLogin getUserLogin() {
return userLogin;
}
/**
* @param userLogin
* the userLogin to set
*/
public void setUserLogin(UserLogin userLogin) {
this.userLogin = userLogin;
}
/**
* @return the book
*/
public Book getBook() {
return book;
}
/**
* @param book
* the book to set
*/
public void setBook(Book book) {
this.book = book;
}
/**
* @return the rateNumber
*/
public Double getRateNumber() {
return rateNumber;
}
/**
* @param rateNumber
* the rateNumber to set
*/
public void setRateNumber(Double rateNumber) {
this.rateNumber = rateNumber;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((book == null) ? 0 : book.hashCode());
result = prime * result + rateID;
result = prime * result + ((rateNumber == null) ? 0 : rateNumber.hashCode());
result = prime * result + ((userLogin == null) ? 0 : userLogin.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rate other = (Rate) obj;
if (book == null) {
if (other.book != null)
return false;
} else if (!book.equals(other.book))
return false;
if (rateID != other.rateID)
return false;
if (rateNumber == null) {
if (other.rateNumber != null)
return false;
} else if (!rateNumber.equals(other.rateNumber))
return false;
if (userLogin == null) {
if (other.userLogin != null)
return false;
} else if (!userLogin.equals(other.userLogin))
return false;
return true;
}
}
|
package se.jaitco.queueticketapi.service;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import se.jaitco.queueticketapi.model.Ticket;
import se.jaitco.queueticketapi.model.TicketStatus;
import se.jaitco.queueticketapi.model.TicketTime;
import se.jaitco.queueticketapi.model.WebSocketEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static org.hamcrest.CoreMatchers.is;
import static se.jaitco.queueticketapi.service.TicketService.*;
public class TicketServiceTest {
@InjectMocks
private final TicketService classUnderTest = new TicketService();
@Mock
private RedissonClient redissonClient;
@Mock
private RLock rLock;
@Mock
private RDeque<Object> tickets;
@Mock
private RDeque<Object> ticketTimes;
@Mock
private RAtomicLong ticketNumber;
@Mock
private RAtomicLong ticketVersion;
@Mock
private SimpMessagingTemplate simpMessagingTemplate;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
Mockito.when(redissonClient.getLock(TICKET_LOCK))
.thenReturn(rLock);
Mockito.when(redissonClient.getDeque(TICKETS))
.thenReturn(tickets);
Mockito.when(redissonClient.getDeque(TICKET_TIMES))
.thenReturn(ticketTimes);
Mockito.when(redissonClient.getAtomicLong(TICKET_NUMBER))
.thenReturn(ticketNumber);
Mockito.when(redissonClient.getAtomicLong(TICKETS_VERSION))
.thenReturn(ticketVersion);
Mockito.when(tickets.poll())
.thenReturn(ticket());
Mockito.when(tickets.peek())
.thenReturn(ticket());
Mockito.when(tickets.peekLast())
.thenReturn(ticket());
Mockito.when(tickets.stream())
.thenReturn(Stream.of(tickets().toArray()));
Mockito.when(tickets.size())
.thenReturn(2);
Mockito.when(ticketTimes.stream())
.thenReturn(Stream.of(ticketTime()));
Mockito.when(ticketTimes.size())
.thenReturn(1);
Mockito.when(ticketNumber.incrementAndGet())
.thenReturn(2L);
Mockito.when(ticketVersion.incrementAndGet())
.thenReturn(3L);
}
@Test
public void testNewTicket() {
Ticket ticket = classUnderTest.newTicket();
verifyLock();
verifyWebSocketCall();
Assert.assertThat(ticket.getNumber(), is(2L));
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(redissonClient, Mockito.times(1)).getAtomicLong(TICKET_NUMBER);
Mockito.verify(redissonClient, Mockito.times(1)).getAtomicLong(TICKETS_VERSION);
Mockito.verify(tickets, Mockito.times(1)).add(Matchers.any(Ticket.class));
Mockito.verify(ticketNumber, Mockito.times(1)).incrementAndGet();
Mockito.verify(ticketVersion, Mockito.times(1)).get();
}
@Test
public void testResetTickets() {
classUnderTest.resetTickets();
verifyLock();
verifyWebSocketCall();
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKET_TIMES);
Mockito.verify(redissonClient, Mockito.times(1)).getAtomicLong(TICKET_NUMBER);
Mockito.verify(redissonClient, Mockito.times(1)).getAtomicLong(TICKETS_VERSION);
Mockito.verify(tickets, Mockito.times(1)).delete();
Mockito.verify(ticketTimes, Mockito.times(1)).delete();
Mockito.verify(ticketNumber, Mockito.times(1)).set(0L);
Mockito.verify(ticketVersion, Mockito.times(1)).incrementAndGet();
}
@Test
public void testNextTicket() {
classUnderTest.nextTicket();
verifyLock();
verifyWebSocketCall();
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKET_TIMES);
Mockito.verify(ticketTimes, Mockito.times(1)).add(Matchers.any(TicketTime.class));
}
@Test
public void testCurrentTicket() {
classUnderTest.currentTicket();
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(tickets, Mockito.times(1)).peek();
}
@Test
public void testTicketStatus() {
final long ticketNumber = 10L;
Optional<TicketStatus> ticketStatus = classUnderTest.ticketStatus(ticketNumber);
verifyLock();
Assert.assertThat(ticketStatus.get().getNumbersBefore(), is(9L));
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKET_TIMES);
}
@Test
public void testTicketStatusLowNumber() {
final long ticketNumber = 0L;
Optional<TicketStatus> ticketStatus = classUnderTest.ticketStatus(ticketNumber);
Assert.assertThat(ticketStatus, is(Optional.empty()));
}
@Test
public void testDropTicket() {
final long ticketNumber = 1L;
classUnderTest.dropTicket(ticketNumber);
verifyLock();
verifyWebSocketCall();
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(tickets, Mockito.times(1)).stream();
Mockito.verify(tickets, Mockito.times(1)).remove(Matchers.any(Ticket.class));
}
@Test
public void testSize() {
classUnderTest.size();
Mockito.verify(redissonClient, Mockito.times(1)).getDeque(TICKETS);
Mockito.verify(tickets, Mockito.times(1)).size();
}
@Test
public void testVersion() {
classUnderTest.version();
Mockito.verify(redissonClient, Mockito.times(1)).getAtomicLong(TICKETS_VERSION);
}
private void verifyLock() {
Mockito.verify(redissonClient, Mockito.times(1)).getLock(TICKET_LOCK);
Mockito.verify(rLock, Mockito.times(1)).lock();
Mockito.verify(rLock, Mockito.times(1)).unlock();
}
private void verifyWebSocketCall() {
Mockito.verify(simpMessagingTemplate, Mockito.times(1))
.convertAndSend(ArgumentMatchers.anyString(), ArgumentMatchers.any(WebSocketEvent.class));
}
private List<Ticket> tickets() {
List<Ticket> tickets = new ArrayList<>();
tickets.add(createTicket(1, 1));
tickets.add(createTicket(2, 1));
tickets.add(createTicket(3, 1));
tickets.add(createTicket(4, 1));
tickets.add(createTicket(5, 1));
tickets.add(createTicket(6, 1));
tickets.add(createTicket(7, 1));
tickets.add(createTicket(8, 1));
tickets.add(createTicket(9, 1));
tickets.add(createTicket(10, 1));
return tickets;
}
private Ticket ticket() {
return createTicket(1, System.nanoTime());
}
private Ticket createTicket(long number, long time) {
Ticket ticket = new Ticket();
ticket.setNumber(number);
ticket.setTime(time);
return ticket;
}
private TicketTime ticketTime() {
TicketTime ticketTime = new TicketTime();
ticketTime.setDuration(1);
return ticketTime;
}
} |
package net.liuzd.spring.boot.v2.domain;
import java.io.Serializable;
public class City implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String state;
private String country;
private String map;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getMap() {
return map;
}
public void setMap(String map) {
this.map = map;
}
@Override
public String toString() {
return "City [id=" + id + ", name=" + name + ", state=" + state + ", country=" + country + ", map=" + map + "]";
}
} |
package com.ssm.wechatpro.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.ssm.wechatpro.dao.WechatAppMapper;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatAppService;
import com.ssm.wechatpro.util.Constants;
import com.ssm.wechatpro.util.DateUtil;
import com.ssm.wechatpro.util.JudgeUtil;
import com.ssm.wechatpro.util.ToolUtil;
@Service
public class WechatAppServiceImpl implements WechatAppService {
@Resource
WechatAppMapper wechatAppMapper;
/***
* 添加一个app用户信息
* @amparam inputObject
* @par outputObject
* @throws ExceptionS
*/
@Override
public void addWechatApp(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
if(!ToolUtil.contains(params,Constants.WECHATAPP_KEY,Constants.WECHATAPP_RETURNMESSAGE, inputObject, outputObject)){
return ;
}
// 判断该用户是否存在
List<Map<String, Object>> app = wechatAppMapper.getApp();
if (!app.isEmpty()) {
outputObject.setreturnMessage("该公众号信息已经存在");
} else {
if (JudgeUtil.isNull(params.get("appId").toString()))
outputObject.setreturnMessage("appId的值不能为空");
else if (JudgeUtil.isNull(params.get("appSecret").toString()))
outputObject.setreturnMessage("appSecret的值不能为空");
else {
params.put("createId", inputObject.getLogParams().get("id"));
params.put("createTime", DateUtil.getTimeAndToString());
wechatAppMapper.addApp(params);
outputObject.setBean(params);
}
}
}
/***
* 修改app用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void updateApp(InputObject inputObject, OutputObject outputObject) throws Exception {
Map<String, Object> params = inputObject.getParams();
if(!ToolUtil.contains(params,Constants.WECHATAPP_KEY,Constants.WECHATAPP_RETURNMESSAGE, inputObject, outputObject)){
return ;
}
if (JudgeUtil.isNull(params.get("appId").toString()))
outputObject.setreturnMessage("appId的值不能为空");
else if (JudgeUtil.isNull(params.get("appSecret").toString()))
outputObject.setreturnMessage("appSecret的值不能为空");
else
wechatAppMapper.updateApp(params);
}
/***
* 查询app用户信息
* @amparam inputObject
* @par outputObject
* @throws Exception
*/
@Override
public void selectApp(InputObject inputObject, OutputObject outputObject) throws Exception {
List<Map<String, Object>> app = wechatAppMapper.getApp();
if (!app.isEmpty()) {
outputObject.setBean(app.get(0));
} else {
outputObject.setBean(null);
}
}
}
|
public class BoolTest {
public static void main(String args[]) {
boolean y;
y = false;
System.out.println("y is" + y);
y = true;
if (y) {
System.out.println("y is true");
}
System.out.println("10>9?" + (10 > 9));
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
import com.tencent.mm.plugin.exdevice.ui.ExdeviceProfileUI.1;
class ExdeviceProfileUI$1$3 implements Runnable {
final /* synthetic */ 1 iEz;
ExdeviceProfileUI$1$3(1 1) {
this.iEz = 1;
}
public final void run() {
ExdeviceProfileUI.k(this.iEz.iEx);
ExdeviceProfileUI.l(this.iEz.iEx).notifyDataSetChanged();
}
}
|
package Exceptions;
public class PhoneFormatException extends NameFormatException {
private static final String message = "Неверный формат телефона - ";
String additionalMessage;
public PhoneFormatException(String additionalMessage) {
super(message);
this.additionalMessage = additionalMessage;
}
@Override
public String getAdditionalMessage() {
return message + additionalMessage;
}
}
|
package ADD;
import Domain.Order;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
public class ADD
{
public static final int TIMES = 0;
public static final int SUM = 1;
public static final int MAX = 2;
public static final int MINUS = 3;
public static final int COST_SETTING = 4;
public static final int PRIME = 5;
// private Map<Integer, Node> nodes;
private Node root;
public ADD()
{
//nodes = new HashMap<Integer, Node>();
}
public ADD(Node root)
{
//nodes = new HashMap<Integer, Node>();
this.root = root;
//nodes.put(n.hashCode(), n);
}
public void setRoot(Node root)
{
this.root = root;
}
public Node getRoot()
{
return root;
}
public void putNode(Node parent, Node child, int side)
{
//nodes.put(child.hashCode(), child);
parent.addChild(child, side);
}
public ADD op(double value, int op)
{
Node aux = getRoot();
Node aux2 = new NodeTerminal(value);
ADD resultTree = new ADD();
Node root = recursivelyDoOp(resultTree, aux, aux2, op);
resultTree.setRoot(root);
return resultTree;
}
public ADD op(ADD tree2, int op)
{
Node aux = getRoot();
Node aux2 = tree2.getRoot();
ADD resultTree = new ADD();
Node root = recursivelyDoOp(resultTree, aux, aux2, op);
resultTree.setRoot(root);
return resultTree;
}
public ADD setCostDiagram(int threshold, ADD[] diagrams)
{
ADD resultTree = new ADD();
Node listNode = new ListNode(threshold, diagrams);
Node root = recursivelyDoOp(resultTree, getRoot(), listNode, COST_SETTING);
resultTree.setRoot(root);
return resultTree;
}
// Fazer recursivo para maior eficiencia
public ADD sumOut(int key)
{
List<Node> list = new ArrayList<Node>();
List<Node> listP = new ArrayList<Node>();
List<Integer> sides = new ArrayList<Integer>();
list.add(getRoot());
listP.add(null);
sides.add(0);
int indexVar = Order.getIndex(key);
while(!list.isEmpty())
{
Node aux = list.remove(0);
Node parent = listP.remove(0);
Integer side = sides.remove(0);
int indexAux = Order.getIndex(aux);
if(indexAux > indexVar) continue;
if(indexAux == indexVar)
{
ADD resultTree = new ADD();
Node root = recursivelyDoOp(resultTree, aux.getChild(0), aux.getChild(1), SUM);
if(parent != null) parent.addChild(root, side);
else setRoot(root);
}
else
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
{
sides.add(i);
list.add(aux.getChild(i));
listP.add(aux);
}
}
}
return this;
}
private Node lookUp(Node aux, Node aux2, int op)
{
Node result = null;
// if(!aux.isTerminal() || aux.isTerminal() && aux2.isTerminal()) result = doOp(aux, aux2, op);
if(!aux2.isTerminal()) result = doOp(aux2, aux, op);
else result = doOp(aux, aux2, op);
return result;
}
private Node doOp(Node aux, Node aux2, int op)
{
// Returns the node aux times aux2
if(op == TIMES) return aux.times(aux2);
else if(op == SUM) return aux.sum(aux2);
else if(op == MAX) return aux.max(aux2);
else if(op == MINUS) return aux.minus(aux2);
return null;
}
private Node recursivelyDoOp(ADD resultTree, Node aux, Node aux2, int op)
{
// if one of the sides is zero
if(op == TIMES)
{
if(aux.isTerminal() && ((NodeTerminal)aux).getValue() == 0) return aux;
else if(aux2.isTerminal() && ((NodeTerminal)aux2).getValue() == 0) return aux2;
}
Node result = lookUp(aux, aux2, op);
if(result != null) return result;
if(aux.isTerminal() && aux2.isTerminal() && op == COST_SETTING) return ((ListNode)aux2).setCost(aux);
Node parent = null;
// Aux2 preceds aux
if(Order.getIndex(aux2) < Order.getIndex(aux))
{
Node trade = aux;
aux = aux2;
aux2 = trade;
}
parent = aux.copy();
// If both variables are equal then goes to child nodes of both trees
if(aux.equals(aux2))
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
{
Node child = recursivelyDoOp(resultTree, aux.getChild(i), aux2.getChild(i), op);
resultTree.putNode(parent, child, i);
}
}
else
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
{
Node child = recursivelyDoOp(resultTree, aux.getChild(i), aux2, op);
resultTree.putNode(parent, child, i);
}
}
Dictionary.putItem(aux, aux2, parent, op);
return parent;
}
// Max(abs(ADD_1-ADD_2))
public double getMaxDifference(ADD tree2)
{
return recursivelyDoMaxDifference(getRoot(), tree2.getRoot());
}
// Add a dictonary to speed up operations
private double recursivelyDoMaxDifference(Node aux, Node aux2)
{
double maxValue = -1;
if(aux.isTerminal() && aux2.isTerminal()) maxValue = Math.max(maxValue, aux.absMinus(aux2));
else
{
// Aux2 preceds aux
if(Order.getIndex(aux2) < Order.getIndex(aux))
{
Node trade = aux;
aux = aux2;
aux2 = trade;
}
// If both variables are equal then goes to child nodes of both trees
if(aux.equals(aux2))
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
maxValue = Math.max(maxValue, recursivelyDoMaxDifference(aux.getChild(i), aux2.getChild(i)));
}
else
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
maxValue = Math.max(maxValue, recursivelyDoMaxDifference(aux.getChild(i), aux2));
}
}
return maxValue;
}
public List<Integer> getList()
{
Node root = getRoot();
List<Integer> list = new ArrayList<Integer>();
recursivelyGetList(root, list);
return list;
}
private void recursivelyGetList(Node aux, List<Integer> list)
{
if(aux.isTerminal())
list.add((int)Math.round(((NodeTerminal)aux).getValue()));
else
for(int i = 0; i < Node.NUMBER_CHILDS; i++) recursivelyGetList(aux.getChild(i), list);
}
public void prime()
{
recursivelyDoUnaryOp(getRoot(), PRIME);
}
private void recursivelyDoUnaryOp(Node aux, int op)
{
if(aux.isTerminal()) return;
if(op == PRIME) aux.prime();
for(int i = 0; i < Node.NUMBER_CHILDS; i++) recursivelyDoUnaryOp(aux.getChild(i), op);
}
// Ordering
public ADD order()
{
ADD resultTree = new ADD();
Node[] list = new Node[Order.size()+1];
int[] listB = new int[Order.size()+1];
recursivelyDoOrdering(resultTree, list, listB, getRoot());
return resultTree;
}
private void recursivelyDoOrdering(ADD resultTree, Node[] list, int[] listB, Node aux)
{
list[Order.getIndex(aux)] = aux;
if(aux.isTerminal())
{
int count = 0;
while(list[count] == null) count++;
putNodes(resultTree, list, listB, count, null, 0, resultTree.getRoot());
return;
}
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
{
listB[Order.getIndex(aux.hashCode())] = i;
recursivelyDoOrdering(resultTree, list, listB, aux.getChild(i));
}
list[Order.getIndex(aux)] = null;
listB[Order.getIndex(aux)] = 0;
}
private void putNodes(ADD resultTree, Node[] list, int[] listB, int listIt, Node parent, int parentSide, Node aux)
{
if(listIt >= list.length) return;
if(aux == null)
{
if(!list[listIt].isTerminal()) aux = list[listIt].copy();
else aux = list[listIt];
if(parent != null) parent.addChild(aux, parentSide);
else resultTree.setRoot(aux);
}
if(Order.getIndex(aux) < listIt)
{
for(int i = 0; i < Node.NUMBER_CHILDS; i++) putNodes(resultTree, list, listB, listIt, aux, i, aux.getChild(i));
}
else if(Order.getIndex(aux) == listIt)
{
// Get next node
listIt++;
while(listIt < list.length && list[listIt] == null) listIt++;
putNodes(resultTree, list, listB, listIt, aux, listB[Order.getIndex(aux)], aux.getChild(listB[Order.getIndex(aux)]));
}
else if(Order.getIndex(aux) > listIt)
{
Node copy = list[listIt].copy();
if(parent != null) parent.addChild(copy, parentSide);
else resultTree.setRoot(copy);
copy.addChild(aux, 1-listB[listIt]);
aux = copyTree(aux);
copy.addChild(aux, listB[listIt]);
// Get next node
listIt++;
while(listIt < list.length && list[listIt] == null) listIt++;
for(int i = 0; i < Node.NUMBER_CHILDS; i++) putNodes(resultTree, list, listB, listIt, copy, i, copy.getChild(i));
}
}
// Copy a tree
public Node copyTree(Node root)
{
Node newNode = root.copy();
List<Node> list = new ArrayList<Node>();
List<Node> listP = new ArrayList<Node>();
listP.add(newNode);
list.add(root);
while(!list.isEmpty())
{
Node aux = list.remove(0);
Node parent = listP.remove(0);
for(int i = 0; i < Node.NUMBER_CHILDS; i++)
{
Node child = aux.getChild(i);
if(child != null)
{
if(!child.isTerminal())
{
Node childCopy = child.copy();
parent.addChild(childCopy, i);
list.add(child);
listP.add(childCopy);
}
else parent.addChild(child, i);
}
}
}
return newNode;
}
// Print
public void print()
{
recursivelyDoPrint(getRoot(), "", 1);
}
public void recursivelyDoPrint(Node aux, String prefix, int side)
{
System.out.println(prefix + (side==0 ? "|-- " : "|++ ") + aux.print());
if(aux.isTerminal()) return;
for (int i = 0; i < Node.NUMBER_CHILDS; i++)
recursivelyDoPrint(aux.getChild(i), prefix + (side==1 ? " " : "| "), i);
}
public String printDistance(int distance)
{
String space = "";
for(int i = 0; i < distance; i++) space += " ";
return space;
}
}
|
/* */ package datechooser.autorun;
/* */
/* */ import datechooser.beans.DateChooserCombo;
/* */ import datechooser.beans.DateChooserComboCustomizer;
/* */ import java.awt.FlowLayout;
/* */ import java.awt.GridLayout;
/* */ import java.beans.IntrospectionException;
/* */ import javax.swing.BorderFactory;
/* */ import javax.swing.JComponent;
/* */ import javax.swing.JPanel;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class ConfigCombo
/* */ extends ConfigBean
/* */ {
/* */ public ConfigCombo()
/* */ throws IntrospectionException
/* */ {
/* 25 */ super(new DateChooserCombo(), new DateChooserComboCustomizer());
/* 26 */ initializeInterface();
/* */ }
/* */
/* */ private void initializeInterface() {
/* 30 */ setLayout(new GridLayout(1, 2, 2, 2));
/* 31 */ JPanel beanCell = new JPanel(new FlowLayout(1));
/* 32 */ beanCell.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(20, 2, 2, 2)));
/* */
/* */
/* 35 */ beanCell.add((JComponent)getBean());
/* 36 */ add(beanCell);
/* 37 */ add(getCustomizer());
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ public String getFileExt()
/* */ {
/* 46 */ return "dchc";
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/autorun/ConfigCombo.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/ |
package fr.tenebrae.MMOCore.Utils.Serializers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
public class ItemStackSerializer {
public static String toBase64(ItemStack inventory) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeObject(inventory);
dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) {
throw new IllegalStateException("Unable to save item stack.", e);
}
}
public static ItemStack fromBase64(String data) {
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack returned = (ItemStack) dataInput.readObject();
dataInput.close();
return returned;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
package org.fhcrc.honeycomb.metapop.fitness;
/**
* Returns the value it was initialized with regardless of the resource.
*
* Created on 24 Apr, 2013
* @author Adam Waite
* @version $Id: SpecifiedCalculator.java 2028 2013-05-09 03:03:14Z ajwaite $
*/
public class SpecifiedCalculator extends FitnessCalculator {
private double growth_rate;
private double death_rate;
public SpecifiedCalculator(double growth_rate, double death_rate) {
this.growth_rate = growth_rate;
this.death_rate = death_rate;
}
@Override
public double calculateGrowthRate(double param) { return growth_rate; }
@Override
public double calculateDeathRate(double param) { return death_rate; }
}
|
package src;
import src.Enums.ECharacterType;
import src.Enums.EGameKey;
import src.Enums.EWatchMode;
import src.Frame.KeyConstants;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashSet;
/**
* Created with IntelliJ IDEA.
* User: B. Seelbinder
* UID: ga25wul
* Date: 13.07.2014
* Time: 00:52
* *
*/
public class TGameSession implements ActionListener {
// << Container data >>
private final KeyConstants KEY_CONSTANTS = new KeyConstants();
private final TMap MAP;
private final TPlayer[] PLAYERS;
private final FileLoader LOADER = new FileLoader();
// << Game Timer >>
private TPlayer controlledPlayer;
private int gameStepTime = 50;
private final Timer GameClock = new Timer( gameStepTime, this );
// << View Modes >>
private EWatchMode watchMode = EWatchMode.CONTROLLED_PLAYER;
private int customPlayerID = 0; // only needed if watchMode == CUSTOM_PLAYER
//////////////////////////
///////--- CONSTRUCTORS ---///////
//////////////////////////
public TGameSession( Dimension mapSize, int initialPlayers ) {
if ( mapSize == null )
throw new NullPointerException( "Cannot create TGameSession: mapSize ist NULL!" );
if ( initialPlayers <= 0 )
throw new NullPointerException( "Cannot create TGameSession: negative or zero players!" );
// load some stuff
FileLoader loader = new FileLoader();
loader.loadAnimations();
// game stuff
this.MAP = new TMap( mapSize.width, mapSize.height );
this.PLAYERS = new TPlayer[initialPlayers];
for ( int i=0; i<initialPlayers; i++ )
PLAYERS[i] = new TPlayer( ECharacterType.DEFAULT, LOADER );
controlledPlayer = PLAYERS[0];
testSettings( controlledPlayer );
}
public void testSettings( TPlayer conPlayer ) {
conPlayer.setAbsolutePosition( MAP.getInitialStartupPosition() );
conPlayer.setRelative( MAP.getInitialStartupPosition() );
}
/////////////////////
///////--- METHODS ---///////
/////////////////////
public void start() {
this.GameClock.start();
}
public void pauseInput() {
this.GameClock.stop();
}
private Point[] getPlayerCoords() {
Point[] relCoords = new Point[PLAYERS.length];
int i = 0;
for ( TPlayer p : PLAYERS )
relCoords[i++] = p.getRel();
return relCoords;
}
private BufferedImage[] getPlayerImages() {
BufferedImage[] images = new BufferedImage[PLAYERS.length];
int i = 0;
for ( TPlayer p : PLAYERS )
images[i++] = p.getImage();
return images;
}
@Override
public void actionPerformed( ActionEvent e ) {
if ( e.getSource() == GameClock ) {
runKeyInput();
for ( TPlayer p : this.PLAYERS )
p.tick();
MAP.setPlayerCoords( getPlayerCoords() );
MAP.setPlayerImages( getPlayerImages() );
}
}
///////////////////////
///////--- KEY-INPUT ---///////
///////////////////////
private final HashSet<EGameKey> pressedGameKeys = new HashSet<EGameKey>();
public void runKeyInput() {
// movement attributes
int cpx = 0; // controlled player should move by cpx along x-axis
int cpy = 0; // controlled player should move by cpy along y-axis
int mpx = 0;
int mpy = 0;
for ( EGameKey e : pressedGameKeys ) {
switch ( e ) {
case PLAYER_UP:
cpy -= 1;
break;
case PLAYER_DOWN:
cpy += 1;
break;
case PLAYER_LEFT:
cpx -= 1;
break;
case PLAYER_RIGHT:
cpx += 1;
break;
case MAP_UP:
mpy -= 1;
break;
case MAP_DOWN:
mpy += 1;
break;
case MAP_LEFT:
mpx -= 1;
break;
case MAP_RIGHT:
mpx += 1;
break;
}
}
if ( cpx != 0 || cpy != 0 ) {
switch ( MAP.canMoveTo( controlledPlayer.getRelX() + cpx, controlledPlayer.getRelY() + cpy, cpx, cpy, controlledPlayer.getMoveState() ) ) {
case XY_WISE:
controlledPlayer.moveBy( cpx, cpy );
break;
case X_WISE:
controlledPlayer.moveBy( cpx, 0 );
break;
case Y_WISE:
controlledPlayer.moveBy( 0, cpy );
break;
case NONE:
// nothing to do
}
}
switch ( this.watchMode ) {
case OBSERVER:
if ( mpx != 0 || mpy != 0 )
MAP.moveMapCenterBy( mpx, mpy );
break;
case CONTROLLED_PLAYER:
MAP.setMapCenterTo( controlledPlayer.getRelX(), controlledPlayer.getRelY() );
break;
case CUSTOM_PLAYER:
MAP.setMapCenterTo( PLAYERS[this.customPlayerID].getRelX(), PLAYERS[this.customPlayerID].getRelY() );
break;
}
}
/**
* - this will get called from a window-listener component ( most certainly the game frame )
* @param KEY
*/
public void setKeyPressed( final char KEY ) {
// getkeyasenum will always return an enum value. NONE, if the key was not game relevant
pressedGameKeys.add( KEY_CONSTANTS.getKeyAsEnum( KEY ) );
}
/**
* - this will get called from a window-listener component ( most certainly the game frame )
* @param KEY
*/
public void setKeyReleased( final char KEY ) {
pressedGameKeys.remove( KEY_CONSTANTS.getKeyAsEnum( KEY ) );
}
///////////////////////////////
///////--- GETTER AND SETTER ---///////
///////////////////////////////
public TMap getMap() {
return this.MAP;
}
public TPlayer getPlayer( int index ) {
return ( index >= 0 && index < PLAYERS.length ) ? PLAYERS[index] : null;
}
protected void setGameStepTime( int t ) {
if ( t <= 0 ) {
System.err.println("Invalid game step time: cannot be zero or lower!");
return;
}
this.gameStepTime = t;
this.GameClock.setDelay( t );
this.GameClock.setInitialDelay( t );
}
public FileLoader getFileLoader() {
return LOADER;
}
}
|
/* Написать "сервер", который умеет многопоточно выполнять задачи:
а) Считывать информацию с консоли.
Он считывает строку и номер клиента.
После считывания, строка отправляется на соответствующий клиент
b) Умеет "ждать" подключения нового клиента, при новом подключении клиента,
сокет соединения помещается в новый поток для "общения сокета клиента и сокета сервера".
с) Класс потока для общения с клиентом
(для каждого клиента сервер выделяет новый сокет дял общения)
Также написать класс "клиент", который соединяется с сервером.
Задача клиента принять строку и вывести ее в формате "Client 1:"+stroka или "Client 2:"+stroka.
Кузменюк Максим: В Main запуск потока server, client1 и client2.*/
package myServer;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyServer {
// int port=0;
public static void main(String[] args) {
MyServer cl = new MyServer(3845,"124.0.0");
}
public MyServer(int port , String localegost){
//this.port = port;
new Server(port).start();
new Client(localegost, port).connect();
}
}
class Server extends Thread {
private ServerSocket server;
public ServerSocket getServer() {
return server;
}
private final int port;
public Server(int p) {
port = p;
}
public void run() {
try {
server = new ServerSocket(port);
System.out.println("Server is started!");
while (true) {
Socket socket = server.accept();
new ServerForClients(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class Client {
private String url;
private int port;
private Socket socket;
public Client(String url, int port) {
this.url = url;
this.port = port;
}
public void connect() {
try {
socket = new Socket(url, port);
//InputStream is = socket.getInputStream();
//DataInputStream dis = new DataInputStream(is);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
while(true)dos.writeUTF("Hello server");
//String str = dis.readUTF();
//System.out.println("Client receive from srever:" + str);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerForClients extends Thread {
private Socket socket;
public ServerForClients(Socket s) {
socket = s;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
//OutputStream os = socket.getOutputStream();
//DataOutputStream dos = new DataOutputStream(os);
while (true) {
System.out.println("server: "+dis.readUTF());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.zdzimi.blog.exception;
public class ArticleException extends RuntimeException {
public ArticleException(String title) {
super("Not found: " + title);
}
}
|
package config;
/**
* 一个spring配置类
* 它的作用相当于bean.xml文件
*/
//@ComponentScan("com.gzh" )
public class SpringConfiguration {
}
|
package com.spiderio;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
/**
* @author Pin HU
*
* 21 Oct 2011, 13:39:10
*/
public class BlockingListParser
{
private Set<String> blocks;
private File inputFile;
public BlockingListParser(File inputFile)
{
this.inputFile = inputFile;
blocks = new HashSet<String>();
}
public void setInputFile(File inputFile)
{
this.inputFile = inputFile;
}
public void parse()
{
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try
{
fis = new FileInputStream(inputFile);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
String line = br.readLine();
String[] parts = line.split("href=\"");
for(int i = parts.length - 1; i >= 0; i--)
{
String link = parts[i].substring(0, parts[i].indexOf("\""));
blocks.add(link);
}
}
catch(FileNotFoundException fnfe)
{
fnfe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
} catch (IOException e){}
}
if(isr != null)
{
try
{
isr.close();
} catch (IOException e){}
}
if(fis != null)
{
try
{
fis.close();
} catch (IOException e){}
}
}
}
public String[] getBlocks()
{
String[] ret = new String[blocks.size()];
blocks.toArray(ret);
return ret;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Forms;
import Clases.Cl_Conectar;
import Clases.Cl_Varios;
import Vistas.frm_ver_ventas;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Objects;
import javax.swing.table.DefaultTableModel;
/**
*
* @author loyanguren
*/
public final class frm_asiento_venta extends javax.swing.JInternalFrame {
Cl_Varios ven = new Cl_Varios();
Cl_Conectar con = new Cl_Conectar();
DefaultTableModel mostrar;
int item = 1;
/**
* Creates new form frm_asiento_venta
*/
public frm_asiento_venta() {
initComponents();
modelo_asiento();
}
public void modelo_asiento() {
mostrar = new DefaultTableModel() {
@Override
public boolean isCellEditable(int fila, int columna) {
if (columna == 3 || columna == 4) {
return true;
} else {
return false;
}
}
};
mostrar.addColumn("Item");
mostrar.addColumn("Cuenta");
mostrar.addColumn("Nombre");
mostrar.addColumn("Debe");
mostrar.addColumn("Haber");
mostrar.addColumn("T.C.");
mostrar.addColumn("Debe MN");
mostrar.addColumn("Haber MN");
t_asiento.setModel(mostrar);
t_asiento.getColumnModel().getColumn(0).setPreferredWidth(30);
t_asiento.getColumnModel().getColumn(1).setPreferredWidth(70);
t_asiento.getColumnModel().getColumn(2).setPreferredWidth(220);
t_asiento.getColumnModel().getColumn(3).setPreferredWidth(80);
t_asiento.getColumnModel().getColumn(4).setPreferredWidth(80);
t_asiento.getColumnModel().getColumn(5).setPreferredWidth(50);
t_asiento.getColumnModel().getColumn(6).setPreferredWidth(90);
t_asiento.getColumnModel().getColumn(7).setPreferredWidth(90);
ven.centrar_celda(t_asiento, 1);
ven.derecha_celda(t_asiento, 3);
ven.derecha_celda(t_asiento, 4);
ven.derecha_celda(t_asiento, 5);
ven.derecha_celda(t_asiento, 6);
ven.derecha_celda(t_asiento, 7);
}
private void bus_cuenta(String cuenta) {
DefaultTableModel mostrar_cc = new DefaultTableModel() {
@Override
public boolean isCellEditable(int fila, int columna) {
return false;
}
};
mostrar_cc.addColumn("Cuenta");
mostrar_cc.addColumn("Descripcion");
try {
Statement st = con.conexion();
String bus_c = "select * from cuentas_contables where idcuenta like '" + cuenta + "%' order by idcuenta asc";
ResultSet rs = con.consulta(st, bus_c);
Object fila_cc[] = new Object[2];
while (rs.next()) {
fila_cc[0] = rs.getString("idcuenta");
fila_cc[1] = rs.getString("nombre");
mostrar_cc.addRow(fila_cc);
}
t_cc.setModel(mostrar_cc);
con.cerrar(rs);
con.cerrar(st);
t_cc.getColumnModel().getColumn(0).setPreferredWidth(70);
t_cc.getColumnModel().getColumn(1).setPreferredWidth(380);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
bus_cc = new javax.swing.JDialog();
jLabel19 = new javax.swing.JLabel();
txt_buscar = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
t_cc = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
txt_ruc = new javax.swing.JTextField();
txt_raz = new javax.swing.JTextField();
txt_cod_venta = new javax.swing.JTextField();
txt_periodo = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txt_tipodoc = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txt_serie = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txt_nrodoc = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
txt_fec = new javax.swing.JFormattedTextField();
jLabel8 = new javax.swing.JLabel();
txt_tc = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txt_sub = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txt_moneda = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
jLabel14 = new javax.swing.JLabel();
txt_nom_cc = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
btn_cer = new javax.swing.JButton();
btn_registrar = new javax.swing.JButton();
txt_cc = new javax.swing.JTextField();
txt_monto = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
t_asiento = new javax.swing.JTable();
txt_haber = new javax.swing.JTextField();
cbx_destino = new javax.swing.JComboBox();
txt_debe = new javax.swing.JTextField();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jLabel19.setText("Buscar");
txt_buscar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_buscarKeyPressed(evt);
}
});
t_cc.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
t_cc.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
t_ccMouseClicked(evt);
}
});
jScrollPane2.setViewportView(t_cc);
javax.swing.GroupLayout bus_ccLayout = new javax.swing.GroupLayout(bus_cc.getContentPane());
bus_cc.getContentPane().setLayout(bus_ccLayout);
bus_ccLayout.setHorizontalGroup(
bus_ccLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bus_ccLayout.createSequentialGroup()
.addContainerGap()
.addGroup(bus_ccLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
.addGroup(bus_ccLayout.createSequentialGroup()
.addComponent(jLabel19)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
bus_ccLayout.setVerticalGroup(
bus_ccLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(bus_ccLayout.createSequentialGroup()
.addContainerGap()
.addGroup(bus_ccLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel19)
.addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE)
.addContainerGap())
);
setTitle("Registro de Asiento de Ventas");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Generales"));
txt_ruc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_ruc.setEnabled(false);
txt_raz.setEnabled(false);
txt_cod_venta.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_cod_venta.setEnabled(false);
txt_periodo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_periodo.setEnabled(false);
jLabel2.setText("Periodo:");
jLabel1.setText("Codigo.");
jLabel3.setText("RUC:");
jLabel4.setText("Tipo Doc.");
txt_tipodoc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_tipodoc.setEnabled(false);
jLabel5.setText("Serie:");
txt_serie.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_serie.setEnabled(false);
jLabel6.setText("Numero:");
txt_nrodoc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_nrodoc.setEnabled(false);
jLabel7.setText("Fecha");
try {
txt_fec.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
txt_fec.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_fec.setEnabled(false);
jLabel8.setText("TC");
txt_tc.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_tc.setEnabled(false);
jLabel10.setText("Sub Total");
txt_sub.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_sub.setEnabled(false);
jLabel11.setText("Moneda");
txt_moneda.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_moneda.setEnabled(false);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_serie)
.addComponent(txt_nrodoc)
.addComponent(txt_tipodoc)
.addComponent(txt_ruc, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(100, 100, 100)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel7))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_cod_venta, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_periodo, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(41, 41, 41)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel11)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txt_fec, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel8)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_tc)
.addComponent(txt_moneda)
.addComponent(txt_sub)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_raz)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_ruc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_raz, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_tipodoc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_serie, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_cod_venta, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(txt_sub, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_periodo, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(txt_moneda, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_nrodoc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_fec, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txt_tc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de Cuentas"));
jLabel14.setText("Nombre:");
txt_nom_cc.setHorizontalAlignment(javax.swing.JTextField.LEFT);
txt_nom_cc.setEnabled(false);
jLabel13.setText("Destino");
btn_cer.setText("Cerrar");
btn_cer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_cerActionPerformed(evt);
}
});
btn_registrar.setText("Registrar");
btn_registrar.setEnabled(false);
btn_registrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_registrarActionPerformed(evt);
}
});
txt_cc.setHorizontalAlignment(javax.swing.JTextField.CENTER);
txt_cc.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_ccKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txt_ccKeyTyped(evt);
}
});
txt_monto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_monto.setEnabled(false);
txt_monto.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_montoKeyPressed(evt);
}
});
jLabel12.setText("Monto:");
jLabel9.setText("Cuenta Contable:");
t_asiento.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
t_asiento.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
t_asientoKeyPressed(evt);
}
});
jScrollPane1.setViewportView(t_asiento);
txt_haber.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_haber.setEnabled(false);
cbx_destino.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "DEBE", "HABER" }));
cbx_destino.setEnabled(false);
cbx_destino.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
cbx_destinoKeyPressed(evt);
}
});
txt_debe.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
txt_debe.setEnabled(false);
jLabel17.setText("Debe");
jLabel18.setText("Haber");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel17)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_debe, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_haber, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_registrar)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_cer))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(txt_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cbx_destino, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_nom_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_monto, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel9)))
.addGap(0, 3, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_monto, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_nom_cc, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cbx_destino, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_cer, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_registrar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17)
.addComponent(txt_debe, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18)
.addComponent(txt_haber, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cbx_destinoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbx_destinoKeyPressed
txt_monto.setEnabled(true);
txt_monto.requestFocus();
}//GEN-LAST:event_cbx_destinoKeyPressed
private void t_asientoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_t_asientoKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
txt_debe.setText(ven.formato_numero(suma_debe()));
txt_haber.setText(ven.formato_numero(suma_haber()));
if (Objects.equals(ven.formato_numero(suma_debe()), ven.formato_numero(suma_haber()))) {
btn_registrar.setEnabled(true);
} else {
btn_registrar.setEnabled(false);
}
}
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
int fila = t_asiento.getSelectedRow();
DefaultTableModel modelo = (DefaultTableModel) t_asiento.getModel();
modelo.removeRow(fila);
txt_debe.setText(ven.formato_numero(suma_debe()));
txt_haber.setText(ven.formato_numero(suma_haber()));
}
}//GEN-LAST:event_t_asientoKeyPressed
private void txt_ccKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_ccKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
bus_cc.setSize(500, 500);
txt_buscar.setText(txt_cc.getText());
txt_cc.requestFocus();
bus_cuenta(txt_cc.getText());
bus_cc.setLocationRelativeTo(null);
bus_cc.setModal(true);
bus_cc.setVisible(true);
}
}//GEN-LAST:event_txt_ccKeyPressed
private void txt_ccKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_ccKeyTyped
if (txt_cc.getText().length() == 6) {
evt.consume();
}
char car = evt.getKeyChar();
if ((car < '0' || car > '9')) {
evt.consume();
}
}//GEN-LAST:event_txt_ccKeyTyped
private void txt_montoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_montoKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
if (txt_monto.getText().length() > 1) {
Object fila[] = new Object[8];
fila[0] = item;
item++;
fila[1] = txt_cc.getText();
fila[2] = txt_nom_cc.getText();
if (cbx_destino.getSelectedItem().equals("DEBE")) {
fila[3] = ven.formato_numero(Double.parseDouble(txt_monto.getText()));
fila[4] = 0.0;
} else {
fila[3] = 0.0;
fila[4] = ven.formato_numero(Double.parseDouble(txt_monto.getText()));
}
fila[5] = Double.parseDouble(txt_tc.getText());
fila[6] = "";
fila[7] = "";
mostrar.addRow(fila);
t_asiento.setModel(mostrar);
txt_cc.setText("");
txt_nom_cc.setText("");
txt_monto.setText("");
cbx_destino.setEnabled(false);
txt_monto.setEnabled(false);
txt_cc.requestFocus();
txt_debe.setText(ven.formato_numero(suma_debe()));
txt_haber.setText(ven.formato_numero(suma_haber()));
if (Objects.equals(ven.formato_numero(suma_debe()), ven.formato_numero(suma_haber()))) {
btn_registrar.setEnabled(true);
} else {
btn_registrar.setEnabled(false);
}
}
}
}//GEN-LAST:event_txt_montoKeyPressed
private Double suma_debe() {
Double debe = 0.0;
int filas = t_asiento.getRowCount();
if (filas > 0) {
for (int i = 0; i < filas; i++) {
Double debe_monto = Double.parseDouble(t_asiento.getValueAt(i, 3).toString());
debe = debe + debe_monto;
}
} else {
debe = debe + 0.0;
}
return debe;
}
private Double suma_haber() {
Double haber = 0.0;
int filas = t_asiento.getRowCount();
if (filas > 0) {
for (int i = 0; i < filas; i++) {
Double haber_monto = Double.parseDouble(t_asiento.getValueAt(i, 4).toString());
haber = haber + haber_monto;
}
} else {
haber = haber + 0.0;
}
return haber;
}
private void btn_registrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_registrarActionPerformed
int filas_asiento = t_asiento.getRowCount();
String periodo = txt_periodo.getText();
int idasiento = ver_id(periodo, "M");
String fecha = ven.fechabase(txt_fec.getText());
String glosa = "VENTA CON " + txt_tipodoc.getText() + " : " + txt_serie.getText() + " - " + txt_nrodoc.getText() + " CLIENTE: " + txt_raz.getText();
if (filas_asiento > 0) {
for (int i = 0; i < filas_asiento; i++) {
String cuenta = t_asiento.getValueAt(i, 1).toString();
String plan_cuenta = cuenta.charAt(0) + "" + cuenta.charAt(1);
Double debe = Double.parseDouble(t_asiento.getValueAt(i, 3).toString());
Double haber = Double.parseDouble(t_asiento.getValueAt(i, 4).toString());
try {
Statement st = con.conexion();
String ins_asiento = "insert into asiento_contable Values ('" + periodo + "', '" + idasiento + "', 'M', '" + plan_cuenta + "',"
+ "'" + cuenta + "', '" + fecha + "', '" + glosa + "', '" + debe + "', '" + haber + "', '1', 'V')";
System.out.println(ins_asiento);
con.actualiza(st, ins_asiento);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
try {
String idventa = txt_cod_venta.getText();
Statement st = con.conexion();
String ins_asto_vta = "insert into asiento_venta Values ('" + idventa + "', '" + periodo + "', '" + idasiento + "')";
System.out.println(ins_asto_vta);
con.actualiza(st, ins_asto_vta);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
frm_ver_ventas ventas = new frm_ver_ventas();
ven.llamar_ventana(ventas);
this.dispose();
}//GEN-LAST:event_btn_registrarActionPerformed
private Integer ver_id(String periodo, String identifacion) {
Integer idasiento = 0;
try {
Statement st = con.conexion();
String ver_cod_per = "select id_asiento from asiento_contable where periodo = '" + periodo + "' and identificacion = '" + identifacion + "' order by id_asiento desc";
ResultSet rs = con.consulta(st, ver_cod_per);
if (rs.next()) {
idasiento = rs.getInt("id_asiento");
} else {
idasiento = 0;
}
con.cerrar(rs);
con.cerrar(st);
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
idasiento = idasiento + 1;
return idasiento;
}
private void btn_cerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cerActionPerformed
frm_ver_ventas ventas = new frm_ver_ventas();
ven.llamar_ventana(ventas);
this.dispose();
}//GEN-LAST:event_btn_cerActionPerformed
private void txt_buscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_buscarKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
String buscar = txt_buscar.getText();
bus_cuenta(buscar);
}
}//GEN-LAST:event_txt_buscarKeyPressed
private void t_ccMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t_ccMouseClicked
if (evt.getClickCount() == 2) {
int icc = t_cc.getSelectedRow();
String cuenta = t_cc.getValueAt(icc, 0).toString();
String nombre = t_cc.getValueAt(icc, 1).toString();
txt_cc.setText("");
txt_cc.setText(cuenta);
txt_nom_cc.setText(nombre);
cbx_destino.setEnabled(true);
cbx_destino.requestFocus();
bus_cc.setVisible(false);
}
}//GEN-LAST:event_t_ccMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_cer;
public static javax.swing.JButton btn_registrar;
private javax.swing.JDialog bus_cc;
private javax.swing.JComboBox cbx_destino;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
public static javax.swing.JTable t_asiento;
private javax.swing.JTable t_cc;
private javax.swing.JTextField txt_buscar;
public static javax.swing.JTextField txt_cc;
public static javax.swing.JTextField txt_cod_venta;
public static javax.swing.JTextField txt_debe;
public static javax.swing.JFormattedTextField txt_fec;
public static javax.swing.JTextField txt_haber;
public static javax.swing.JTextField txt_moneda;
private javax.swing.JTextField txt_monto;
private javax.swing.JTextField txt_nom_cc;
public static javax.swing.JTextField txt_nrodoc;
public static javax.swing.JTextField txt_periodo;
public static javax.swing.JTextField txt_raz;
public static javax.swing.JTextField txt_ruc;
public static javax.swing.JTextField txt_serie;
public static javax.swing.JTextField txt_sub;
public static javax.swing.JTextField txt_tc;
public static javax.swing.JTextField txt_tipodoc;
// End of variables declaration//GEN-END:variables
}
|
package com.expedia.beans;
/**
* Represents offers. For now, only hotel offers are supported
*
* @author Alaa Fandi waked75@gmail.com
* @since 2018/02/21
*/
public class Offers {
private Hotel[] hotels;
public Hotel[] getHotels() {
return hotels;
}
public void setHotels(Hotel[] hotels) {
this.hotels = hotels;
}
}
|
package de.adesso.gitstalker.core.requests;
import de.adesso.gitstalker.core.enums.RequestType;
import de.adesso.gitstalker.core.objects.Query;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class RequestManagerTest {
@Test
public void checkIfOrganizationValidationRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.ORGANIZATION_VALIDATION);
assertEquals(RequestType.ORGANIZATION_VALIDATION, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfOrganizationDetailRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.ORGANIZATION_DETAIL);
assertEquals(RequestType.ORGANIZATION_DETAIL, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfMemberIDRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setEndCursor("testEndCursor");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.MEMBER_ID);
assertEquals(RequestType.MEMBER_ID, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfMemberPRRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setEndCursor("testEndCursor");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.MEMBER_PR);
assertEquals(RequestType.MEMBER_PR, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfMemberRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setMemberID("testMemberID");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.MEMBER);
assertEquals(RequestType.MEMBER, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfRepositoryRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setEndCursor("testEndCursor");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.REPOSITORY);
assertEquals(RequestType.REPOSITORY, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfTeamRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setEndCursor("testEndCursor");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.TEAM);
assertEquals(RequestType.TEAM, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfExternalRepoRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setRepoIDs(Arrays.asList("testRepoID"))
.setOrganizationName("adessoAG");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.EXTERNAL_REPO);
assertEquals(RequestType.EXTERNAL_REPO, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfCreatedRepoByMemberRequestIsGeneratedCorrectly() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG")
.setMemberID("testMemberID")
.setEndCursor("testEndCursor");
Query generatedTeamQuery = requestManager.generateRequest(RequestType.CREATED_REPOS_BY_MEMBERS);
assertEquals(RequestType.CREATED_REPOS_BY_MEMBERS, generatedTeamQuery.getQueryRequestType());
}
@Test
public void checkIfAllRequestAreGeneratedAfterValidation() {
RequestManager requestManager = new RequestManager()
.setOrganizationName("adessoAG");
ArrayList<Query> generatedRequestsAfterValidation = requestManager.generateAllRequests();
assertEquals(5, generatedRequestsAfterValidation.size());
}
@Test
public void checkIfInputIsFormattedCorrectly() {
RequestManager requestManager = new RequestManager();
String formattedInput = requestManager.formatInput("adesso AG");
assertEquals("adessoag", formattedInput);
}
} |
package com.example.shared.constants;
public class Constant {
Constant() {
throw new IllegalStateException("Constant class");
}
//HTTP header values
public static final String X_VSOLV_KEY = "x-vsolv-key";
public static final String CONTENT_TYPE = "application/json;charset=UTF-8";
}
|
package java_code.server.handlers;
import com.google.gson.JsonObject;
import com.pubnub.api.PubNub;
import com.pubnub.api.PubNubException;
import java_code.database.DBManager;
import java_code.server.MessageHandler;
import java_code.server.Server;
public class UpdateWaitPerPatronHandler implements MessageHandler {
Server server;
public UpdateWaitPerPatronHandler(Server server){this.server = server;}
@Override
public void handleMessage(JsonObject data, PubNub pubnub, String clientId) {
int venueID = data.get("venueID").getAsInt();
int waitPerPatronValue = data.get("wppValue").getAsInt();
if(DBManager.updateVenueWaitPerPatron(venueID, waitPerPatronValue)){
server.updateManagerPage(data);
server.updateCurrentVenueData();
server.sendUpdateWaitlistData();
server.updateVenueListData();
}else{//WaitPerPatron not updated
JsonObject msg = new JsonObject();
msg.addProperty("type", "badWaitPerPatronUpdate");
JsonObject data1 = new JsonObject();
data.addProperty("venueID", venueID);
msg.add("data", data1);
try {
pubnub.publish()
.channel("main")
.message(msg)
.sync();
} catch (PubNubException e) {
e.printStackTrace();
}
}
}
}
|
package sokrisztian.todo.admin.logic.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import sokrisztian.todo.admin.api.model.TodoView;
import sokrisztian.todo.admin.persistance.domain.TodoEntity;
@Component
public class TodoEntityToTodoViewConverter implements Converter<TodoEntity, TodoView> {
@Override
public TodoView convert(TodoEntity todoEntity) {
TodoView todoView = new TodoView();
todoView.setId(todoEntity.getId());
todoView.setUserId(todoEntity.getUserId());
todoView.setDescription(todoEntity.getDescription());
todoView.setDeadline(todoEntity.getDeadline());
return todoView;
}
}
|
package com.jbgames.sandsim.particles;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
public class Sand extends Powder{
public Sand(String type, Vector2 pos, float temperature, Vector2 velocity, float density, boolean solid) {
super(type, pos, temperature, velocity, density, solid);
}
@Override
public void render(ShapeRenderer sr) {
sr.setColor(147 / 255.0f, 80 / 255.0f, 27 / 255.0f, 1);
sr.rect(posToGrid().x, posToGrid().y, 1, 1);
}
}
|
package com.easyArch.client.manager;
import com.cxl.rpc.util.ProxyPush;
import com.cxl.rpc.util.Push;
import com.easeArch.common.entry.User;
public class Friend implements Push {
@Override
public void exec(Object o) {
Object response = ProxyPush.getInstance().getResponse();
if (null!=response&&!"".equals(response)){
User user= (User) response;
FriendManager.getInstance().onFriendLogin(user.getAccount());
}
}
}
|
package lista4;
import java.util.Scanner;
public class Exe15 {
public static void main(String[] args) {
// Declaração de variáveis
Scanner entrada = new Scanner(System.in);
int idade = 1;
char sexo = '\u0000';
char exp = '\u0000';
int contM = 0;
int contMs = 0;
int contF = 0;
double idadeMedia = 0;
int menorIdade = 999;
int cont45 = 0;
int cont21S = 0;
// Entradas
while (idade != 0){
System.out.println("Idade: ");
idade = entrada.nextInt();
if(idade!=0){
System.out.println("Sexo: ");
System.out.println("M - Masculino");
System.out.println("F - Feminino");
sexo = entrada.next().charAt(0);
sexo = Character.toUpperCase(sexo);
System.out.println("Experiência: ");
System.out.println("S - Sim");
System.out.println("N - Não");
exp = entrada.next().charAt(0);
exp = Character.toUpperCase(exp);
if(sexo=='M'){
contM++;
if(exp=='S'){
idadeMedia=idadeMedia+idade;
contMs++;
}
if(idade>45){
cont45++;
}
}else{
contF++;
if(idade<21 && exp=='S'){
cont21S++;
}
}
if(sexo=='F' && exp=='S'){
if(idade<menorIdade){
menorIdade=idade;
}
}
}
}
System.out.println("Candidatos Femininos: " + contF);
System.out.println("Candidatos Masculinos: " + contM);
System.out.println("Idade Média de Homens com experiência: " + (double)idadeMedia/contMs);
System.out.println("Porcentagem de homens com mais de 45 Anos: " + (double)cont45/contM*100 + "%");
System.out.println("Porcentagem de mulheres com menos de 21 Anos com experiência: " + (double)cont21S/contF*100 + "%");
System.out.println("Menor idade entre as mulheres com experiência: " + menorIdade);
entrada.close();
}
}
|
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.graphics.glutils;
import java.nio.FloatBuffer;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.BufferUtils;
import com.badlogic.gdx.utils.GdxRuntimeException;
/** An ImmediateModeRenderer allows you to perform immediate mode rendering as you were accustomed to in your desktop OpenGL
* environment. In order to draw something you first have to call {@link ImmediateModeRenderer10#begin(int)} with the primitive
* type you want to render. Next you specify as many vertices as you want by first defining the vertex color, normal and texture
* coordinates followed by the vertex position which finalizes the definition of a single vertex. When you are done specifying the
* geometry you have to call {@link ImmediateModeRenderer10#end()} to make the renderer render the geometry. Internally the
* renderer uses vertex arrays to render the provided geometry. This is not the best performing way to do this so use this class
* only for non performance critical low vertex count geometries while debugging.
*
* Note that this class of course only works with OpenGL ES 1.x.
*
* @author mzechner */
public class ImmediateModeRenderer10 implements ImmediateModeRenderer {
/** the primitive type **/
private int primitiveType;
/** the vertex position array and buffer **/
private float[] positions;
private FloatBuffer positionsBuffer;
/** the vertex color array and buffer **/
private float[] colors;
private FloatBuffer colorsBuffer;
/** the vertex normal array and buffer **/
private float[] normals;
private FloatBuffer normalsBuffer;
/** the texture coordinate array and buffer **/
private float[] texCoords;
private FloatBuffer texCoordsBuffer;
/** the current vertex attribute indices **/
private int idxPos = 0;
private int idxCols = 0;
private int idxNors = 0;
private int idxTexCoords = 0;
private boolean hasCols;
private boolean hasNors;
private boolean hasTexCoords;
private final int maxVertices;
private int numVertices;
/** Constructs a new ImmediateModeRenderer */
public ImmediateModeRenderer10 () {
this(2000);
}
/** Constructs a new ImmediateModeRenderer */
public ImmediateModeRenderer10 (int maxVertices) {
this.maxVertices = maxVertices;
if (Gdx.graphics.isGL20Available())
throw new GdxRuntimeException("ImmediateModeRenderer can only be used with OpenGL ES 1.0/1.1");
this.positions = new float[3 * maxVertices];
this.positionsBuffer = BufferUtils.newFloatBuffer(3 * maxVertices);
this.colors = new float[4 * maxVertices];
this.colorsBuffer = BufferUtils.newFloatBuffer(4 * maxVertices);
this.normals = new float[3 * maxVertices];
this.normalsBuffer = BufferUtils.newFloatBuffer(3 * maxVertices);
this.texCoords = new float[2 * maxVertices];
this.texCoordsBuffer = BufferUtils.newFloatBuffer(2 * maxVertices);
}
public void begin (Matrix4 projModelView, int primitiveType) {
GL10 gl = Gdx.gl10;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadMatrixf(projModelView.val, 0);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
begin(primitiveType);
}
/** Starts a new list of primitives. The primitiveType specifies which primitives to draw. Can be any of GL10.GL_TRIANGLES,
* GL10.GL_LINES and so on. A maximum of 6000 vertices can be drawn at once.
*
* @param primitiveType the primitive type. */
public void begin (int primitiveType) {
this.primitiveType = primitiveType;
numVertices = 0;
idxPos = 0;
idxCols = 0;
idxNors = 0;
idxTexCoords = 0;
hasCols = false;
hasNors = false;
hasTexCoords = false;
}
/** Specifies the color of the current vertex
* @param r the red component
* @param g the green component
* @param b the blue component
* @param a the alpha component */
public void color (float r, float g, float b, float a) {
colors[idxCols] = r;
colors[idxCols + 1] = g;
colors[idxCols + 2] = b;
colors[idxCols + 3] = a;
hasCols = true;
}
/** Specifies the normal of the current vertex
* @param x the x component
* @param y the y component
* @param z the z component */
public void normal (float x, float y, float z) {
normals[idxNors] = x;
normals[idxNors + 1] = y;
normals[idxNors + 2] = z;
hasNors = true;
}
/** Specifies the texture coordinates of the current vertex
* @param u the u coordinate
* @param v the v coordinate */
public void texCoord (float u, float v) {
texCoords[idxTexCoords] = u;
texCoords[idxTexCoords + 1] = v;
hasTexCoords = true;
}
/** Specifies the position of the current vertex and finalizes it. After a call to this method you will effectively define a new
* vertex afterwards.
*
* @param x the x component
* @param y the y component
* @param z the z component */
public void vertex (float x, float y, float z) {
positions[idxPos++] = x;
positions[idxPos++] = y;
positions[idxPos++] = z;
if (hasCols) idxCols += 4;
if (hasNors) idxNors += 3;
if (hasTexCoords) idxTexCoords += 2;
numVertices++;
}
public int getNumVertices () {
return numVertices;
}
public int getMaxVertices () {
return maxVertices;
}
/** Renders the primitives just defined. */
public void end () {
if (idxPos == 0) return;
GL10 gl = Gdx.gl10;
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
positionsBuffer.clear();
BufferUtils.copy(positions, positionsBuffer, idxPos, 0);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, positionsBuffer);
if (hasCols) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
colorsBuffer.clear();
BufferUtils.copy(colors, colorsBuffer, idxCols, 0);
gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorsBuffer);
}
if (hasNors) {
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
normalsBuffer.clear();
BufferUtils.copy(normals, normalsBuffer, idxNors, 0);
gl.glNormalPointer(GL10.GL_FLOAT, 0, normalsBuffer);
}
if (hasTexCoords) {
gl.glClientActiveTexture(GL10.GL_TEXTURE0);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
texCoordsBuffer.clear();
BufferUtils.copy(texCoords, texCoordsBuffer, idxTexCoords, 0);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoordsBuffer);
}
gl.glDrawArrays(primitiveType, 0, idxPos / 3);
if (hasCols) gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
if (hasNors) gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
if (hasTexCoords) gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
}
public void vertex (Vector3 point) {
vertex(point.x, point.y, point.z);
}
@Override
public void dispose () {
}
}
|
package Questao01;
import java.util.Random;
/**
* 17/03/2020
* @author thais
*/
public class Main {
public static void main(String[] args) {
Random gerador = new Random(); // Criando gerador de inteiro
// ############### Criando threads ###############
// Thread 01
new Thread( () -> {
int num = gerador.nextInt(15) * 1000; // Gerando tempo de execução eleatório
System.out.println("Thread 01 iniciando... time -> " + num);
try {
Thread.sleep(num); // Dormindo
} catch (InterruptedException ex) {
System.out.println("Erro sleep thread 01");
}
System.out.println("Thread 01 finalizando...");
}).start();
// Thread 02
new Thread( () -> {
int num = gerador.nextInt(15) * 1000; // Gerando tempo de execução eleatório
System.out.println("Thread 02 iniciando... time -> " + num);
try {
Thread.sleep(num); // Dormindo
} catch (InterruptedException ex) {
System.out.println("Erro sleep thread 01");
}
System.out.println("Thread 02 finalizando...");
}).start();
// Thread 03
new Thread( () -> {
int num = gerador.nextInt(15) * 1000; // Gerando tempo de execução eleatório
System.out.println("Thread 03 iniciando... time -> " + num);
try {
Thread.sleep(num); // Dormindo
} catch (InterruptedException ex) {
System.out.println("Erro sleep thread 01");
}
System.out.println("Thread 03 finalizando...");
}).start();
}
}
|
/*
* Filename: SearchResults.java
*
* Programmer: Ekta Dosad
* Date: 11/19/2015
*/
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import test.MainTest;
/**
* @author Ekta
*
*/
public class SearchResults {
/**
* Declaring Page Factory variables
*/
@FindBy(how = How.XPATH, using = ".//*[@id='tile-container']/div[1]/a")
static WebElement tv;
@FindBy(how = How.XPATH, using = ".//*[@id='tile-container']/ul/li[3]/div/a[1]")
static WebElement socks;
@FindBy(how = How.XPATH, using = ".//*[@id='tile-container']/div[2]/div/div/h4/a")
static WebElement dvd;
@FindBy(how = How.XPATH, using = ".//*[@id='sponsored-container-middle-2']/div/div[2]/ol/div/div/li[1]/div/div[2]/a/span")
static WebElement toys;
@FindBy(how = How.XPATH, using = ".//*[@id='tile-container']/div[1]/div/div/h4/a")
static WebElement iPhone;
/**
* Declaring variables
*/
static String title;
/**
*
* Constructor
*/
public SearchResults(WebDriver driver) {
PageFactory.initElements(driver, this);
}
/*
* return selected item
*/
public WebElement selectItemToAdd(){
title = MainTest.driver.getTitle();
switch(title){
case "tv - Walmart.com":
return tv;
case"socks - Walmart.com":
return socks;
case "dvd - Walmart.com":
return dvd;
case "Toys - Walmart.com":
return toys;
case "iphone - Walmart.com":
return iPhone;
}
return null;
}
/*
* return ItemDescriptionPage
*/
public ItemDescriptionPage clickOnItem() throws InterruptedException{
WebElement item = selectItemToAdd();
//scroll until the element is in view
((JavascriptExecutor) MainTest.driver).executeScript("arguments[0].scrollIntoView(true);", item);
Thread.sleep(500);
item.click();
WebElement myDynamicElement = (new WebDriverWait(MainTest.driver, 35)).
until(ExpectedConditions.presenceOfElementLocated((By.xpath("//*[contains(text(), 'Add to Cart')]"))));
return new ItemDescriptionPage(MainTest.driver);
}
}
|
package com.example.demo.api.transaction;
import com.example.demo.api.transaction.request.TransactionDetailRequest;
import com.example.demo.api.transaction.request.TransactionListRequest;
import com.example.demo.api.transaction.result.TransactionDetailResult;
import com.example.demo.api.transaction.result.TransactionListResult;
public interface TransactionApi {
TransactionDetailResult queryTransactionDetail(TransactionDetailRequest request);
TransactionListResult queryTransactionList(TransactionListRequest request);
} |
package esir.dom11.nsoc.model;
import java.util.Date;
public class AgendaEvent {
private final Date start;
private final Date end;
public AgendaEvent() {
start = new Date();
end = new Date();
}
public AgendaEvent(Date start, Date end) {
this.start = start;
this.end = end;
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.