text
stringlengths
10
2.72M
package geometry; // @author Raphaël public class StraightCenteredEllipse extends Shape2D { protected double halfWidth, squaredHalfWidth, halfHeight, squaredHalfHeight; public StraightCenteredEllipse(double halfWidth, double halfHeight) { this.halfWidth = halfWidth; squaredHalfWidth = halfWidth*halfWidth; this.halfHeight = halfHeight; squaredHalfHeight = halfHeight*halfHeight; } @Override public double getxMin() { return -halfWidth; } @Override public double getxMax() { return halfWidth; } @Override public double getyMin() { return -halfHeight; } @Override public double getyMax() { return halfHeight; } @Override public Shape2D getTranslatedInstance(double Dx, double Dy) { return null; } @Override public Shape2D getRelativelyRotatedInstance(double Dtheta) { return null; } @Override public Shape2D getAbsolutelyRotatedInstance(double theta) { return null; } @Override public Shape2D getSimplifiedInstance() { return null; } @Override public boolean strictlyContains(double x, double y) { return x*x/squaredHalfWidth + y*y/squaredHalfHeight < 1; } @Override public boolean contains(double x, double y) { return x*x/squaredHalfWidth + y*y/squaredHalfHeight <= 1; } }
package hu.mentlerd.hybrid; import java.util.Vector; public class Coroutine { public static final int INITIAL_STACK_SIZE = 32; public static final int INITIAL_FRAME_SIZE = 10; public static final int MAX_STACK_SIZE = 1024; public static final int MAX_FRAME_SIZE = 100; public static void yield( CallFrame frame, CallFrame argFrame, int argCount ){ if ( !frame.canYield ) throw new LuaException( "Cannot yield outside of a coroutine" ); Coroutine coroutine = frame.coroutine; Coroutine parent = coroutine.parent; LuaThread thread = coroutine.thread; if ( parent == null ) throw new LuaException( "Yielded a root thread. Something went horribly wrong!" ); coroutine.detach(); //Kill the current coroutine, and return values CallFrame nextFrame = parent.getCurrentFrame(); if ( nextFrame == null ){ //Parent is dead, push to the stack directly parent.setTop( argCount +1 ); parent.stack[0] = Boolean.TRUE; for ( int index = 0; index < argCount; index++ ) parent.stack[index +1] = argFrame.get(index); } else { nextFrame.push( Boolean.TRUE ); for ( int index = 0; index < argCount; index++ ) nextFrame.push( argFrame.get(index) ); } thread.coroutine = parent; } private final Vector<UpValue> upvalues = new Vector<UpValue>(); protected final Platform platform; protected LuaThread thread; protected Coroutine parent; protected LuaTable env; protected Object[] stack; protected int top; private CallFrame[] frameStack; private int frameStackTop; private StringBuilder stackTrace = new StringBuilder(); private int stackTraceLevel = 0; public Coroutine( Platform platform, LuaTable env ){ this.stack = new Object[INITIAL_STACK_SIZE]; this.frameStack = new CallFrame[INITIAL_FRAME_SIZE]; this.platform = platform; this.env = env; } //Used to setup root function public Coroutine( Platform platform, LuaTable env, LuaClosure root ){ this(platform, env); CallFrame frame = pushCallFrame(root, 0, 0, -1); frame.fromLua = true; frame.canYield = true; } /* * Stack management */ public final void setTop( int newTop ){ if ( top < newTop ){ //Ensure stack size int size = stack.length; if ( size < newTop ){ //Realloc if ( newTop > MAX_STACK_SIZE ) throw new LuaException("Stack overflow"); while( size < newTop ) size <<= 1; Object[] realloc = new Object[size]; System.arraycopy(stack, 0, realloc, 0, stack.length); stack = realloc; } } else { stackClear(newTop, top -1); } top = newTop; } public final int getTop(){ return top; } public final void stackClear( int index, int end ){ for(; index <= end; index++) stack[index] = null; } public final void stackCopy( int index, int dest, int len ){ if (len > 0 && index != dest) System.arraycopy(stack, index, stack, dest, len); } /* * Callframe Stack */ public CallFrame getCurrentFrame(){ if ( isDead() ) return null; CallFrame frame = frameStack[frameStackTop -1]; if ( frame == null ) frameStack[frameStackTop -1] = (frame = new CallFrame(this)); return frame; } public CallFrame pushCallFrame( LuaClosure closure, int localBase, int returnBase, int argCount ){ pullNewFrame(); CallFrame frame = getCurrentFrame(); frame.setup(closure, localBase, returnBase, argCount); return frame; } public CallFrame pushJavaFrame( Callable func, int localBase, int returnBase, int argCount ){ pullNewFrame(); CallFrame frame = getCurrentFrame(); frame.setup(null, localBase, returnBase, argCount); frame.function = func; frame.canYield = false; return frame; } public void popCallFrame(){ if ( frameStackTop == 0 ) throw new LuaException("Frame stack undeflow"); CallFrame popped = getCurrentFrame(); popped.closure = null; popped.function = null; frameStackTop--; } protected void pullNewFrame(){ int newTop = frameStackTop +1; int size = frameStack.length; if ( newTop > MAX_FRAME_SIZE ) throw new LuaException("Frame stack overflow"); if ( size < newTop ){ //Realloc size <<= 1; CallFrame[] realloc = new CallFrame[size]; System.arraycopy(frameStack, 0, realloc, 0, frameStack.length); frameStack = realloc; } frameStackTop = newTop; } public int getFrameTop(){ return frameStackTop; } public CallFrame getCallFrame(int index) { if (index < 0) index += frameStackTop; return frameStack[index]; } public boolean isAtBottom(){ return frameStackTop == 1; } public boolean isDead(){ return frameStackTop == 0; } /* * Upvalues */ public void closeUpvalues( int index ){ int loopIndex = upvalues.size(); while( --loopIndex >= 0 ){ UpValue upvalue = upvalues.elementAt(loopIndex); if ( upvalue.getIndex() < index ) return; upvalue.close(); upvalues.removeElementAt(loopIndex); } } public UpValue findUpvalue( int index ){ int loopIndex = upvalues.size(); while( --loopIndex >= 0 ){ UpValue upvalue = upvalues.elementAt(loopIndex); int currIndex = upvalue.getIndex(); if ( currIndex == index ) return upvalue; if ( currIndex < index ) break; //Not found, create! } UpValue upvalue = new UpValue(this, index); upvalues.insertElementAt(upvalue, loopIndex +1); return upvalue; } /* * Misc */ protected void beginStackTrace( CallFrame frame, Throwable err ){ stackTrace.append(frame.getSourceLocation()); stackTrace.append(": "); if ( err instanceof LuaException ){ LuaException error = (LuaException) err; stackTrace.append( error.getLuaCause() ); } else { stackTrace.append( err.toString() ); err.printStackTrace(); } stackTrace.append('\n'); stackTraceLevel = -1; } protected void addStackTrace( CallFrame frame ){ //Skip the first frame, as it was already added in beginStackTrace if ( ++stackTraceLevel == 0 ) return; //Build the prefix for ( int index = 0; index < stackTraceLevel; index++ ) stackTrace.append( ' ' ); stackTrace.append(stackTraceLevel); stackTrace.append(". "); //Trace back the source of the function on the stack if ( frame.isLua() ){ int lastOp = frame.closure.proto.code[ frame.pc -1 ]; String origin = LuaUtil.findSlotOrigin(frame, LuaOpcodes.getA8(lastOp)); if ( origin == null ) origin = "unknown"; stackTrace.append(origin); } else { stackTrace.append("java call"); } //Add location stackTrace.append(" - "); stackTrace.append(frame.getSourceLocation()); stackTrace.append('\n'); } public String getStackTrace(){ return stackTrace.toString(); } public void resetStackTrace(){ stackTrace = new StringBuilder(); stackTraceLevel = 0; } public Coroutine getParent(){ return parent; } public LuaTable getEnv(){ return env; } public String getStatus(){ if ( parent == null ){ return isDead() ? "dead" : "suspended"; } return "normal"; } public void resume( Coroutine parent ){ this.parent = parent; this.thread = parent.thread; } public void detach() { this.parent = null; this.thread = null; } }
import org.joda.time.*; import java.util.*; /** * Created by Ali on 5/18/2017 AD. */ public class Main { // public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // String input; // while (true){ // System.out.println("Hi, please enter your student number: "); // input = sc.nextLine(); // // StudentRepository studentRepository = StudentRepository.getInstance(); // Student currentStudent = studentRepository.getStudentByStudentNumber(Integer.parseInt(input)); //// Student currentStudent = studentRepository.getStudentByStudentNumber(810192456); // // //// System.out.println(Integer.parseInt(input)); // // // } // } // public static void main(String[] args) { Scanner sc = new Scanner(System.in); String input; while (true){ System.out.println("Which scenario you want to execute?"); System.out.println("entekhab vahed : e"); System.out.println("graduation : g"); input = sc.nextLine(); StudentRepository studentRepository; Student currentStudent; boolean quit = false; switch (input.charAt(0)){ case 'e': System.out.println("Please enter you student number : "); input = sc.nextLine(); studentRepository = StudentRepository.getInstance(); currentStudent = studentRepository.getStudentByStudentNumber(Integer.parseInt(input)); if (currentStudent != null) { while (!quit){ System.out.println("Hi " + currentStudent.getName() + " " + currentStudent.getLastName() + " :)"); VahedProcess vahedProcess = new VahedProcess(currentStudent); while (!quit) { vahedProcess.printOptions(); System.out.println(); System.out.println("Your current barnameh : "); vahedProcess.printCurrentBarnameh(); System.out.println("Please enter your action :"); System.out.println("r : Remove option"); System.out.println("a : Add option"); System.out.println("v : Validate barnameh"); System.out.println("c : Confirm barnameh"); System.out.println("q : Quit"); System.out.println(); input = sc.nextLine(); switch (input.charAt(0)) { case 'v': if (vahedProcess.validateBarnameh()){ System.out.println("Your barnameh is OK!!"); } else { System .out.println("Your barnameh is not ok :("); } System.out.println(); break; case 'c': if (vahedProcess.validateBarnameh()){ vahedProcess.confirmBarnameh(); System.out.println("Your barnameh is confirmed!!"); } else { System.out.println("Your barnameh is not ok :("); } System.out.println(); break; case 'a': System.out.println("Please enter the course index for add:"); input = sc.nextLine(); vahedProcess.addOption(Integer.parseInt(input)); break; case 'r': System.out.println("Please enter the course index for remove:"); input = sc.nextLine(); vahedProcess.removeOption(Integer.parseInt(input)); break; case 'q': vahedProcess.reverseCapacity(); quit = true; break; } } System.out.println(); System.out.println(); break; } } else { System.out.println("ID is not correct! please try again!"); continue; } break; case 'g': System.out.println("Please enter you student number : "); input = sc.nextLine(); studentRepository = StudentRepository.getInstance(); currentStudent = studentRepository.getStudentByStudentNumber(Integer.parseInt(input)); if (currentStudent != null) { while (!quit){ GraduationProcess graduationProcess = new GraduationProcess(currentStudent); System.out.println("Hi " + currentStudent.getName() + " " + currentStudent.getLastName() + " :)"); System.out.println(); graduationProcess.isGraduate(); break; } } else { System.out.println("ID is not correct! please try again!"); continue; } break; } } } }
package com.smyc.kaftanis.lookingfortable; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; public class Settings extends AppCompatActivity { ListView listView; ArrayAdapter<String> adapter; String[] items; ArrayList<String> listItems; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); setTitle("Ρυθμίσεις"); listView = (ListView) findViewById(R.id.listView3); listView.setEnabled(true); items = new String[]{"Καθορίστε την ακτίνα αναζήτησης (για το ροζ κουμπί)", "Εμφάνιση εικόνων", "Αλλαγή ονόματος", "Αλλαγή εικόνας"}; listItems=new ArrayList<>(Arrays.asList(items)); adapter=new ArrayAdapter<String>(this,R.layout.listitem, R.id.txtitem, listItems); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (listItems.get(position).equals("Καθορίστε την ακτίνα αναζήτησης (για το ροζ κουμπί)")) { SetRadius setRadius = new SetRadius(); setRadius.show(getFragmentManager(), "radius"); } else if (listItems.get(position).equals("Εμφάνιση εικόνων")) { VisiblePhotos visiblePhotos = new VisiblePhotos(); visiblePhotos.show(getFragmentManager(),"details"); } else if (listItems.get(position).equals("Αλλαγή ονόματος")) { if (MainActivity.isLoged) { ChangeNickName changeNickName = new ChangeNickName(); changeNickName.show(getFragmentManager(),"nickname"); } else Toast.makeText( Settings.this , "Δεν μπορείτε να το κάνετε αυτό ως επισκέπτης" , Toast.LENGTH_SHORT).show(); } else if (listItems.get(position).equals("Αλλαγή εικόνας")) { if (MainActivity.isLoged) { Intent intent = new Intent( Settings.this, AccountSettings.class); startActivity(intent); } else Toast.makeText( Settings.this , "Δεν μπορείτε να το κάνετε αυτό ως επισκέπτης" , Toast.LENGTH_SHORT).show(); } } } ); } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.util; import xyz.noark.core.exception.ServerBootstrapException; import java.lang.reflect.Method; /** * Class工具类. * * @author 小流氓[176543888@qq.com] * @since 3.0 */ public class ClassUtils { /** * 使用当前线程的ClassLoader加载给定的类 * * @param className 类的全称 * @return 给定的类 */ public static Class<?> loadClass(String className) { // ClassLoader#loadClass(String):将.class文件加载到JVM中,不会执行static块,只有在创建实例时才会去执行static块 try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException ignored) { } // Class#forName(String):将.class文件加载到JVM中,还会对类进行解释,并执行类中的static块 try { return Class.forName(className); } catch (ClassNotFoundException ignored) { } throw new ServerBootstrapException("无法加载指定类名的Class=" + className); } /** * 创建一个指定类的对象,调用默认的构造函数. * * @param <T> Class * @param klass 类 * @return 指定类的对象 */ public static <T> T newInstance(final Class<T> klass) { try { return klass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new ServerBootstrapException("无法创建实例. Class=" + klass.getName(), e); } } /** * 根据ClassName和构造方法的参数列表来创建一个对象 * * @param <T> Class * @param className 指定类全名(包含包名称的那种) * @param parameters 参数列表 * @return 指定ClassName的对象 */ @SuppressWarnings("unchecked") public static <T> T newInstance(String className, Object... parameters) { Class<?> klass = loadClass(className); try { Class<?>[] parameterTypes = new Class<?>[parameters.length]; for (int i = 0, len = parameters.length; i < len; i++) { parameterTypes[i] = parameters[i].getClass(); } return (T) klass.getConstructor(parameterTypes).newInstance(parameters); } catch (Exception e) { throw new ServerBootstrapException("无法创建实例. Class=" + klass.getName(), e); } } /** * 尝试运行一个带有Main方法的类. * * @param mainClass 带有Main方法类的名称 * @param args 启动参数数组 */ public static void invokeMain(String mainClass, String[] args) { final Class<?> klass = ClassUtils.loadClass(mainClass); Method mainMethod = MethodUtils.getMethod(klass, "main", String[].class); MethodUtils.invoke(null, mainMethod, new Object[]{args}); } }
/* * 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 poo.consultorio.ui; import java.text.SimpleDateFormat; import javax.swing.table.AbstractTableModel; import poo.consultorio.Agenda; import poo.consultorio.Turno; /** * * @author joaquinleonelrobles */ public class TablaAgendaModel extends AbstractTableModel { private static final String[] COLUMNAS = { "Fecha", "Hora", "Estado", "Consulta", "Paciente" }; private final SimpleDateFormat sdfHora; private final SimpleDateFormat sdfDia; private Agenda agenda; public TablaAgendaModel(Agenda agenda) { super(); this.agenda = agenda; this.sdfHora = new SimpleDateFormat("HH:mm"); this.sdfDia = new SimpleDateFormat("dd/MM/yyyy"); } @Override public int getRowCount() { return this.agenda.getTurnos().size(); } @Override public int getColumnCount() { return COLUMNAS.length; } @Override public String getColumnName(int column) { return COLUMNAS[column]; } @Override public Object getValueAt(int fila, int columna) { Object retorno = null; Turno turno = agenda.getTurnos().get(fila); // según la columna deseada obtenemos el valor a mostrar switch (columna) { case 0: retorno = sdfDia.format(turno.getFechaHora()); break; case 1: retorno = sdfHora.format(turno.getFechaHora()); break; case 2: retorno = turno.getEstado(); break; case 3: retorno = turno.getConsulta(); break; case 4: retorno = turno.getPaciente(); break; } return retorno; } public void setAgenda(Agenda agenda) { this.agenda = agenda; } }
package Object; import Object.Enum.GiornoEnum; import java.util.ArrayList; /** * La classe GiornoAlimProgObject mappa la tabella "giorno_alim_prog" del database */ public class GiornoAlimProgObject extends GiornoAlimObject { private int id_giorno; protected int fabbisogno; public GiornoAlimProgObject() { id_giorno=0; fabbisogno=0; tipo= GiornoEnum.programmato; pasti = new ArrayList<PastoObject>(); for (int i=0; i<4; i++) pasti.add(i, new PastoObject(i)); } public GiornoAlimProgObject(ArrayList<PastoObject> listapasti){ id_giorno=0; fabbisogno=0; tipo= GiornoEnum.programmato; pasti = listapasti; } public GiornoAlimProgObject(ArrayList<PastoObject> listapasti, int fabbisogno){ id_giorno=0; this.fabbisogno=fabbisogno; tipo= GiornoEnum.programmato; pasti = listapasti; } public int getId_giorno() { return id_giorno; } public void setId_giorno(int id_giorno) { this.id_giorno = id_giorno; } public int getCalorie() { return fabbisogno; } public void setCalorie(int fabbisogno) { this.fabbisogno = fabbisogno; } }
package ru.job4j.array; /** * classic brute force search. * @author Aliaksandr Kuzura (vorota-24@bk.ru) * @version $Id$ * @since 0.1 */ public class FindLoop { /** * Find element of array. * @param data array * @param el search value * @return array's index */ public int indexOf(int[] data, int el) { int rst = -1; for (int index = 0; index != data.length; index++) { if (data[index] == el) { rst = index; break; } } return rst; } }
package web.id.azammukhtar.subico.Adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; import web.id.azammukhtar.subico.Model.Product.Datum; import web.id.azammukhtar.subico.Network.ApiNetwork; import web.id.azammukhtar.subico.R; import static web.id.azammukhtar.subico.Utils.Constant.IMG_URL; public class SearchFragmentAdapter extends RecyclerView.Adapter<SearchFragmentAdapter.ViewHolder> implements Filterable { private static final String TAG = "HomeFragmentAdapter"; private List<Datum> productModels = new ArrayList<>(); private List<Datum> productModelsFull = new ArrayList<>(); private OnItemClick listener; private Context context; public SearchFragmentAdapter(Context context) { this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_main, parent, false)); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Datum productModel = productModels.get(position); holder.productName.setText(productModel.getName()); String price = "Rp " + productModel.getPrice(); String urlLast = null; // Uri uri = Uri.fromFile(new File(productModel.getImages())); holder.productPrice.setText(price); if (productModel.getImages() != null) { String url = productModel.getImages(); String urlFirst = url.replace("[", ""); String urlSecond = urlFirst.replace("\\", ""); String urlEnd = urlSecond.replace("\"", ""); urlLast = urlEnd.substring(0, urlEnd.length() - 1); } if (!ApiNetwork.isNetworkConnected(context)) { Glide.with(context).load(IMG_URL + urlLast).placeholder(R.drawable.ic_broken_image).into(holder.productImage); Log.d(TAG, "onBindViewHolder: gg " + productModel.getImages()); } Log.d(TAG, "onBindViewHolder: yy " + productModel.getImages()); Glide.with(context) .load(IMG_URL + urlLast) .placeholder(R.drawable.ic_broken_image) .into(holder.productImage); } @Override public int getItemCount() { return productModels == null ? 0 : productModels.size(); } public void setProductModels(List<Datum> productModels1) { this.productModels = productModels1; notifyDataSetChanged(); } public void clearList(List<Datum> productModels) { this.productModels = productModels; productModels.clear(); } class ViewHolder extends RecyclerView.ViewHolder { TextView productName, productPrice; ImageView productImage; ViewHolder(@NonNull View itemView) { super(itemView); productName = itemView.findViewById(R.id.textListMainName); productPrice = itemView.findViewById(R.id.textListMainPrice); productImage = itemView.findViewById(R.id.imageListMain); itemView.setOnClickListener(view -> listener.onItemClick(getAdapterPosition())); } } // public int getLastVisibleItemId() { // if (productModels.isEmpty()) { // return 0; // } // return productModels.get(productModels.size() - 1).getId(); // } public interface OnItemClick { void onItemClick(int position); } public void setOnItemClickListener(OnItemClick listener) { this.listener = listener; } @Override public Filter getFilter() { return productFilter; } private Filter productFilter = new Filter() { @Override protected FilterResults performFiltering(CharSequence charSequence) { List<Datum> filteredList = new ArrayList<>(); Log.d(TAG, "performFiltering: init " + charSequence); if (charSequence == null || charSequence.length() == 0) { filteredList.addAll(productModelsFull); Log.d(TAG, "performFiltering: null "); } else { String filterPattern = charSequence.toString().toLowerCase().trim(); Log.d(TAG, "performFiltering: not null "); for (Datum item : productModelsFull) { String key = filterPattern.substring(0, 3); String filter = filterPattern.replace(key, ""); Log.d(TAG, "performFiltering: " + key + " filtered " + filter); switch (key) { case "sub": for (int i = 0; i < item.getSubCategory().size(); i++) { if (item.getSubCategory().get(i).getName().toLowerCase().contains(filter)) { Log.d(TAG, "performFiltering: " + item.getSubCategory().get(i).getName().toLowerCase()); filteredList.add(item); } } break; case "cat": for (int i = 0; i < item.getSubCategory().size(); i++) { if (item.getSubCategory().get(i).getCategory().getName().toLowerCase().contains(filter)) { Log.d(TAG, "performFiltering: " + item.getSubCategory().get(i).getCategory().getName().toLowerCase()); filteredList.add(item); } } break; } } } FilterResults results = new FilterResults(); results.values = filteredList; return results; } @Override protected void publishResults(CharSequence charSequence, FilterResults filterResults) { productModels.clear(); // productModelsFull.clear(); productModels.addAll((List) filterResults.values); Log.d(TAG, "publishResults: " + filterResults.values); notifyDataSetChanged(); // int count = getItemCount(); // notifyItemRangeInserted(count, filterResults.count); } }; public List<Datum> getProductModels() { return productModels; } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { return position; } }
package cn.jaychang.scstudy.scmsgreceiver.mq; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.cloud.stream.messaging.Source; /** * * <p> * 用于接受订单创建成功的消息 注意注意!这里用的收 Source哦 * </p> * * @author zhangjie * @since 2018-11-05 */ @EnableBinding(Source.class) public class OrderCreateResultMessageListener { @StreamListener(Source.OUTPUT) public void receive2(String msg) { System.out.println("msg:"+msg); } }
package com.infoworks.lab.jjwt; import com.it.soul.lab.sql.entity.Entity; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class JWTPayload extends Entity { private long iat; private long nbf; private long exp; private String iss; private String sub; private Map<String, String> data; public JWTPayload() {} public long getIat() { return iat; } public JWTPayload setIat(long iat) { this.iat = iat;return this; } public long getNbf() { return nbf; } public JWTPayload setNbf(long nbf) { this.nbf = nbf; return this; } public long getExp() { return exp; } public JWTPayload setExp(long exp) { this.exp = exp; return this; } public Map<String, String> getData() { return data; } public JWTPayload setData(Map<String, String> data) { this.data = data; return this; } public String getIss() { return iss; } public JWTPayload setIss(String iss) { this.iss = iss; return this; } public String getSub() { return sub; } public JWTPayload setSub(String sub) { this.sub = sub; return this; } public JWTPayload addData(String key, String value){ if (data == null) data = new ConcurrentHashMap<>(); data.put(key, value); return this; } public JWTPayload removeData(String key){ if (data == null) return this; data.remove(key); return this; } }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /*here HttpServlet is a class*/ import javax.servlet.http.HttpServletRequest; /*HttpServletRequest is an interface*/ import javax.servlet.http.HttpServletResponse; /* HttpServletResponse is an interface*/ import java.io.PrintWriter; /** * Servlet implementation class helloservlet */ @WebServlet("/helloservlet") public class helloservlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public helloservlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest req, HttpServletResponse res) // object of HttpServletResponse interface is response which will be send to the client,here res is a response throws ServletException, IOException { // TODO Auto-generated method stub res.setContentType("text/html"); PrintWriter out=res.getWriter(); //get the stream(or writer) to write the data out.print("<html><body>"); out.print(" <h3> hello ankit</h3>"); out.print(" </body></html>"); } }
package DataStructures.arrays; import java.util.ArrayList; import java.util.Arrays; /** You're given a 2D board which contains an m x n matrix of chars - char[][] board. Write a method - printPaths that prints all possible paths from the top left cell to the bottom right cell. Your method should return an ArrayList of Strings, where each String represents a path with characters appended in the order of movement. You're only allowed to move down and right on the board. The order of String insertion in the ArrayList does not matter. */ public class PrintPaths { public ArrayList<String> printPaths(int[][] board){ ArrayList<String> result = new ArrayList<>(); if (board == null || board.length == 0) return result; StringBuffer sb = new StringBuffer(); recursivePrintPaths(result, sb, board, 0, 0); return result; } public void recursivePrintPaths(ArrayList<String> result, StringBuffer sb, int[][] board, int row, int col){ if (row >= board.length || col >= board[0].length) { return; } sb.append(board[row][col]); recursivePrintPaths(result, sb, board, row, col + 1); recursivePrintPaths(result, sb, board, row + 1, col); if (sb.length() == (board.length + board[0].length - 1)) { result.add(sb.toString()); } sb.deleteCharAt(sb.length() - 1); } public void print(char arr[][], int row, int col, char result[], int pos){ if(row == arr.length-1 && col == arr[0].length-1){ result[pos] = arr[row][col]; System.out.println(Arrays.toString(result)); return; } if(row >= arr.length || col >= arr[0].length){ return; } result[pos] = arr[row][col]; print(arr,row,col+1,result,pos+1); print(arr,row+1,col,result,pos+1); } public int countPaths(int m, int n) { if (m == 0 || n == 0) return 0; int[][] board = new int[m][n]; printPaths(board); return 0; } public static void main(String a[]) { PrintPaths pp = new PrintPaths(); char[][] c = new char[][]{ /* {'A', 'B', 'C'}, {'D', 'E', 'F'}, {'G', 'H', 'I'}*/ {'A', 'B'}, {'C', 'D'} }; //ArrayList<String> result = pp.printPaths(c); //System.out.println(result); //char result[] = new char[c.length + c[0].length-1]; //pp.print(c, 0, 0, result, 0); pp.countPaths(3, 3); } }
/* * @(#)PlatFormType.java 1.0 2014-1-9 * * Copyright (c) 2007-2014 Shanghai Handpay IT, Co., Ltd. * 16/F, 889 YanAn Road. W., Shanghai, China * All rights reserved. * * This software is the confidential and proprietary information of * Shanghai Handpay IT Co., Ltd. ("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 Handpay. */ package com.handpay.obm.common.utils; import org.apache.commons.lang3.StringUtils; /** * Class description goes here. * * @version 1.0 2014-1-9 * @author "lmbao" * @history * */ public enum PlatFormType { IPHONE("iphone", "iphoneƽ̨"), WAP("xhtml", "WAPƽ̨"), IPAD("ipad", "IPADƽ̨"); private String code; private String desc; private PlatFormType (String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public String getDesc() { return desc; } public static PlatFormType valueOfCode(String code) { for (PlatFormType type : values()){ if(StringUtils.equals(code, type.getCode())){ return type; } } return null; } }
package com.lt.demo.controller; import com.lt.demo.domen.entity.Device; import com.lt.demo.domen.entity.Project; import com.lt.demo.service.DeviceService; import com.lt.demo.service.ProjectService; import lombok.extern.slf4j.Slf4j; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController @Slf4j public class DemoRestController { @Autowired private DeviceService deviceService; @Autowired private ProjectService projectService; @GetMapping("/info/{projectId}") public JSONObject getProjectInfo(@PathVariable int projectId) { Project project = projectService.getProjectById(projectId); JSONObject deviceObject = new JSONObject(); for (Device device : project.getDevices()) { JSONObject body = new JSONObject(); body.put("id", device.getId()); body.put("serialnumber", device.getSerialNumber()); body.put("projectId", projectId); body.put("hasErrors", deviceService.hasErrors(device.getId())); JSONObject summary = new JSONObject(); summary.put("eventCount", deviceService.countEvents(device.getId())); summary.put("warningCount", deviceService.countWarnings(device.getId())); summary.put("errorCount", deviceService.countErrors(device.getId())); body.put("summaryInfo", summary); deviceObject.put(device.getSerialNumber(), body); } return deviceObject; } @GetMapping("/info") public JSONArray getAllProjectsInfo() { JSONArray output = new JSONArray(); for (Project project : projectService.getAllProjects()) { JSONObject projectObject = new JSONObject(); projectObject.put("id", project.getId()); projectObject.put("projectName", project.getName()); JSONObject stats = new JSONObject(); stats.put("deviceCount", deviceService.getDeviceCount(project.getId())); stats.put("deviceWithErrors", deviceService.getErrorCount(project.getId())); stats.put("stable devices", deviceService.getStableCount(project.getId())); JSONArray devices = new JSONArray(); for (Device device : project.getDevices()) { devices.add(device.getSerialNumber()); } projectObject.put("stats", stats); projectObject.put("devices", devices); output.add(projectObject); } return output; } }
package chapter5_heritance.objectAnalyzer_5_14; import java.util.ArrayList; // this program uses reflection to spy on objects public class ObjectAnalyzerTest{ public static void main() { ArrayList<Integer> squares = new ArrayList<>(); for (int i = 1; i <= 5; i++) squares.add(i * i); System.out.println(new ObjectAnalyzer().toString(squares)); } }
package com.pulsarsoft.popspot.Model; /** * @author Aurimas Degutis. */ public class Status { private boolean hasProcessed; public boolean getHasProcessed() { return hasProcessed; } public void setHasProcessed(boolean hasProcessed) { this.hasProcessed = hasProcessed; } }
package view; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTextField; public class GroundSensorsPanel extends JPanel { private static final long serialVersionUID = 1L; private JTextField sensor1, sensor2, sensor3; public GroundSensorsPanel() { //super(new GridBagLayout()); this.sensor1=new JTextField(5); this.sensor2=new JTextField(5); this.sensor3=new JTextField(5); this.sensor1.setEditable(false); this.sensor2.setEditable(false); this.sensor3.setEditable(false); this.add(sensor1); this.add(sensor2); this.add(sensor3); this.setMinimumSize(new Dimension(250,60)); this.setBorder(BorderFactory.createTitledBorder("Ground Sensors")); } public void setValue(double s1, double s2, double s3) { this.sensor1.setText(String.valueOf(s1)); this.sensor2.setText(String.valueOf(s2)); this.sensor3.setText(String.valueOf(s3)); } }
package org.base.algorithm.sort; /** * Created by wangwr on 2016/6/2. */ public class SelectionSort extends Sort{ public static void main(String[] args){ new SelectionSort().run(); } public int[] sort(int[] args){ for(int i=0;i<args.length;i++){ int minIndex = i;//依次取出元素和后面的比较选出最小的交换 int j=i+1; for(;j<args.length;j++){ if(args[j]<args[minIndex]){ minIndex=j; } } //最小的下标与当前下标不一样,则交换 if(minIndex!=i){ P.show("swap %s <--> %s",args[i],args[minIndex]); int temp = args[minIndex]; args[minIndex]=args[i]; args[i]=temp; } } return args; } }
package person.zhao.thread; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 使用Callable + ExecutorService + CompletionService的例子 * 多线程异步执行,并且取得返回结果 * 返回结果按照线程完成的优先顺序。 * * @author zhao_hongsheng * */ public class CallableExecutorDemo2 { public void p() throws InterruptedException, ExecutionException { ExecutorService executor = Executors.newFixedThreadPool(10); CompletionService<String> completionExecutor = new ExecutorCompletionService<String>(executor); Callable<String> callable = null; for (int i = 0; i < 10; i++) { callable = new MyCallable(String.valueOf(i)); completionExecutor.submit(callable); } executor.shutdown(); for (int i = 0; i < 10; i++) { System.out.println(completionExecutor.take().get()); } System.out.println("all done ..."); } public static void main(String[] args) throws InterruptedException, ExecutionException { new CallableExecutorDemo2().p(); } }
package com.smartmadsoft.wear.pdfreader; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.Asset; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.PutDataRequest; import com.google.android.gms.wearable.Wearable; import com.google.android.gms.wearable.WearableListenerService; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.util.Date; import java.util.concurrent.TimeUnit; public class ReceiverService extends WearableListenerService { final static boolean DEBUG = false; final static String TAG = "PdfReader"; GoogleApiClient mGoogleApiClient; @Override public void onDataChanged(DataEventBuffer dataEvents) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(Bundle connectionHint) { log("onConnected: " + connectionHint); } @Override public void onConnectionSuspended(int cause) { log("onConnectionSuspended: " + cause); } }) .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { log("onConnectionFailed: " + result); } }) .addApi(Wearable.API) .build(); log("onDataChanged"); for (DataEvent event : dataEvents) { if (event.getType() == DataEvent.TYPE_CHANGED && event.getDataItem().getUri().getPath().equals("/pdf")) { log("it's pdf file"); PutDataRequest req = PutDataRequest.createFromDataItem(event.getDataItem()); Asset asset = req.getAsset("mainPdf"); if (asset == null) log("asset is null"); else log("asset is not null"); //String text = loadStringFromAsset(asset); //asset.get //log(text); try { String path = ((Context) this).getFilesDir() + File.separator + "main.pdf"; log("path is " + path); saveDataFromAsset(asset, path); log("received saved"); SharedPreferences settings = this.getSharedPreferences("mySettings", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putInt("lastPage", 0); editor.commit(); } catch (Exception x) { x.printStackTrace(); } } } log("onDataChanged finished"); /* Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); //intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra("restart", true); //this.overridePendingTransition(0, 0); this.startActivity(intent); */ launchLater(); } void launchLater() { AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); //mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, MainActivity.RESTART_INTENT); Intent intent = new Intent(this, MainActivity.class); //intent.putExtra(<oneOfThePutExtraFunctions>); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); mgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, pi); System.exit(2); } void log(String text) { if (DEBUG) Log.d(TAG, text); } public void saveDataFromAsset(Asset asset, String path) { if (asset == null) { throw new IllegalArgumentException("Asset must be non-null"); } ConnectionResult result = mGoogleApiClient.blockingConnect(30000, TimeUnit.MILLISECONDS); if (!result.isSuccess()) { return; } InputStream assetInputStream = Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset).await().getInputStream(); mGoogleApiClient.disconnect(); if (assetInputStream == null) { log("Requested an unknown Asset."); return; } try { OutputStream outputStream = new FileOutputStream(new File(path)); int read = 0; byte[] bytes = new byte[1024]; while ((read = assetInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } catch (IOException x) { x.printStackTrace(); } } }
package com.crm.acute.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import com.crm.acute.generics.WebDriverUtils; public class OrganizationPage { @FindBy(xpath = "//img[@title='Create Organization...']") private WebElement createOrgImg; WebDriver driver; public OrganizationPage(WebDriver driver) { this.driver= driver; PageFactory.initElements(driver, this); } public CreatingNewOrganization navigateCreateOrganization() { WebDriverUtils.waitForElementToClick(driver, createOrgImg); createOrgImg.click(); return new CreatingNewOrganization(driver); } }
package DatabaseAccess.View; import DatabaseAccess.Domain.Client.ClientController; import DatabaseAccess.Domain.Client.ClientView; import DatabaseAccess.Domain.Expense.ExpenseController; import DatabaseAccess.Domain.Expense.ExpenseView; import DatabaseAccess.Domain.Package.PackageController; import DatabaseAccess.Domain.Package.PackageView; import DatabaseAccess.Domain.PackageService.PackageService; import DatabaseAccess.Domain.PackageService.PackageServiceController; import DatabaseAccess.Domain.PackageService.PackageServiceView; import DatabaseAccess.Domain.PaymentMethod.PaymentMethodController; import DatabaseAccess.Domain.PaymentMethod.PaymentMethodView; import DatabaseAccess.Domain.Revenue.RevenueController; import DatabaseAccess.Domain.Revenue.RevenueView; import DatabaseAccess.Domain.Service.ServiceController; import DatabaseAccess.Domain.Service.ServiceView; import DatabaseAccess.Domain.ServiceType.ServiceTypeController; import DatabaseAccess.Domain.ServiceType.ServiceTypeView; import DatabaseAccess.Domain.Supplier.SupplierController; import DatabaseAccess.Domain.Supplier.SupplierView; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class GUIView extends Application implements View { @Override public void start(Stage primaryStage) throws Exception { BorderPane root = new BorderPane(); TabPane tabs = new TabPane(); tabs.tabClosingPolicyProperty().setValue(TabPane.TabClosingPolicy.UNAVAILABLE); ClientView clientView = new ClientView(new ClientController(), primaryStage, root); SupplierView supplierView = new SupplierView(new SupplierController(), primaryStage, root); ExpenseView expenseView = new ExpenseView(new ExpenseController(), primaryStage, root); PackageView packageView = new PackageView(new PackageController(), primaryStage, root); PackageServiceView packageServiceView = new PackageServiceView(new PackageServiceController(), primaryStage, root); PaymentMethodView paymentMethodView = new PaymentMethodView(new PaymentMethodController(), primaryStage, root); RevenueView revenue = new RevenueView(new RevenueController(), primaryStage, root); ServiceView serviceView = new ServiceView(new ServiceController(), primaryStage, root); ServiceTypeView serviceTypeView = new ServiceTypeView(new ServiceTypeController(), primaryStage, root); tabs.getTabs().addAll(clientView.tab, supplierView.tab, expenseView.tab, packageView.tab, packageServiceView.tab, paymentMethodView.tab, revenue.tab, serviceView.tab, serviceTypeView.tab); root.setTop(tabs); //initMenu(primaryStage, root); // ViewBuilder.inflateTableView(new Supplier(),primaryStage, root); primaryStage.setTitle("Agencia de Turismo"); primaryStage.setScene(new Scene(root, 1280, 700)); primaryStage.show(); } private void initMenu(Stage primaryStage, BorderPane borderPane) { final Menu menu1 = new Menu("File"); MenuItem open = new MenuItem("Open"); // open.setOnAction(new EventHandler<ActionEvent>() { // @Override // public void handle(ActionEvent actionEvent) { // FileChooser fileChooser = new FileChooser(); // fileChooser.setTitle("Escolha o arquivo .txt"); // File file = fileChooser.showOpenDialog(primaryStage); // if (file != null) { // urlFileLoaderController = new UrlFileLoaderController(); // String path = file.getPath(); // try { // urlFileLoaderController.load(path); // } catch (IOException e) { // Alert alert = new Alert(Alert.AlertType.ERROR); // alert.setTitle("An error has occurred"); // alert.setContentText(e.getMessage()); // alert.showAndWait(); // } // commitAnalyzerController.setInititalRepositories(urlFileLoaderController.getUrlList()); // initTableView(primaryStage, borderPane); // } // } // }); MenuItem exit = new MenuItem("Exit"); exit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { Platform.exit(); } }); menu1.getItems().add(open); menu1.getItems().add(exit); final Menu menu2 = new Menu("Tools"); MenuItem analyzer = new MenuItem("Commit analyzer"); // analyzer.setOnAction(new EventHandler<ActionEvent>() { // @Override // public void handle(ActionEvent actionEvent) { // if (urlFileLoaderController.isEmpty()) return; // // Task<Void> t = new Task<>() { // // @Override // protected Void call() throws Exception { // commitAnalyzerController.getCommitsFromRepository(); // commitAnalyzerController.printRepositories(); // return null; // } // // @Override // protected void succeeded() { // initTableView(primaryStage, borderPane); // } // // @Override // protected void failed() { // Alert alert = new Alert(Alert.AlertType.ERROR); // alert.setTitle("An error has occurred"); // alert.setContentText(this.getException().getMessage()); // if (this.getException() instanceof MalformedURLException) { // alert.setContentText("Invalid Url"); // } else if (this.getException() instanceof ProtocolException) { // alert.setContentText("Error in http protocol"); // } else if (this.getException() instanceof IOException) { // alert.setContentText("Impossible to open a connection"); // } else { // alert.setContentText(this.getException().getMessage()); // } // alert.showAndWait(); // } // }; // new Thread(t).start(); // // } // }); menu2.getItems().add(analyzer); final Menu menu3 = new Menu("Help"); MenuItem about = new MenuItem("About"); about.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("About"); alert.setHeaderText("GitHubAnalyzer"); alert.setContentText("Autor: Roberto Nisxota Menegais"); alert.showAndWait(); } }); menu3.getItems().add(about); MenuBar menuBar = new MenuBar(); menuBar.getMenus().addAll(menu1, menu2, menu3); borderPane.setTop(menuBar); } @Override public void init(String[] args) { launch(args); } }
/* * Sample module ingest job settings panel in the public domain. * Feel free to use this as a template for your module ingest job settings * panels. * * Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] * * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package de.fau.copymoveforgerydetection.modules.ingestModule; import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettings; import org.sleuthkit.autopsy.ingest.IngestModuleIngestJobSettingsPanel; /** * UI component used to make per ingest job settings for sample ingest modules. */ public class CopyMoveIngestModuleIngestJobSettingsPanel extends IngestModuleIngestJobSettingsPanel { /** * Creates new form SampleIngestModuleIngestJobSettings */ public CopyMoveIngestModuleIngestJobSettingsPanel(CopyMoveModuleIngestJobSettings settings) { initComponents(); customizeComponents(settings); } private void customizeComponents(CopyMoveModuleIngestJobSettings settings) { textFieldRegionMinSize.setText(Integer.toString(settings.getRegionMinSize())); labelRegionMinSize.setToolTipText( "Roughly the amount of pixel that constitute a copy move forgery. " + "The number of 10x10 px blocks that are required for combination of different blocks " + "with the same transformationfunction to be considered a copy move forgery. " + "The default value has been determined through a optimization process on images with 10+ megapixel " + "for the most part. When dealing with smaller images it might be beneficial to lower this value accordingly."); } /** * Gets the ingest job settings for an ingest module. * * @return The ingest settings. */ @Override public IngestModuleIngestJobSettings getSettings() { int regionMinSize = Integer.parseInt(textFieldRegionMinSize.getText()); return new CopyMoveModuleIngestJobSettings(regionMinSize); } /** * 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() { labelRegionMinSize = new javax.swing.JLabel(); textFieldRegionMinSize = new javax.swing.JTextField(); org.openide.awt.Mnemonics.setLocalizedText(labelRegionMinSize, org.openide.util.NbBundle.getMessage(CopyMoveIngestModuleIngestJobSettingsPanel.class, "CopyMoveIngestModuleIngestJobSettingsPanel.labelRegionMinSize.text")); // NOI18N textFieldRegionMinSize.setText(org.openide.util.NbBundle.getMessage(CopyMoveIngestModuleIngestJobSettingsPanel.class, "CopyMoveIngestModuleIngestJobSettingsPanel.textFieldRegionMinSize.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(labelRegionMinSize) .addGap(18, 18, 18) .addComponent(textFieldRegionMinSize, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(118, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelRegionMinSize) .addComponent(textFieldRegionMinSize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(182, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel labelRegionMinSize; private javax.swing.JTextField textFieldRegionMinSize; // End of variables declaration//GEN-END:variables }
package doktuhparadox.wordcounter; import org.apache.commons.cli.*; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Type; import java.util.*; import java.util.function.ToIntFunction; import static doktuhparadox.wordcounter.Main.Flag.*; public class Main { enum Flag { ALL_WORDS("all"), SPECIFIC_WORDS("w"), FILE_DIRECTORY_INPUTTED("f"), FILE_DIRECTORY_SELECTED("fc"), CUSTOM_DELIMITING_REGEX("reg"); private String flagString; Flag(String flagString) { this.flagString = flagString; } String flagString() { return flagString; } } public static void main(String[] args) { final Map<String, Map<Integer, Integer>> wordsAndOccurrences; Options options = new Options(); CommandLineParser parser = new BasicParser(); options.addOption(ALL_WORDS.flagString(), false, "Search for all words. Ignores -w."); options.addOption(SPECIFIC_WORDS.flagString(), true, "List wordsAndOccurrences for which to search. Separated by commas."); options.addOption(FILE_DIRECTORY_INPUTTED.flagString(), true, "Designate the input file. Ignores -fc."); options.addOption(FILE_DIRECTORY_SELECTED.flagString(), false, "Use a file chooser to select the input file instead of inputting the directory."); options.addOption(CUSTOM_DELIMITING_REGEX.flagString(), true, "Specify a custom stripping regex."); try { CommandLine cmd = parser.parse(options, args); Optional<File> fileOptional = getInputFile(cmd); File f; if (fileOptional.isPresent()) { f = fileOptional.get(); } else { System.out.println("Missing information: -f or non-null -fc required."); return; } String[] words = readInput(f); if (cmd.hasOption(ALL_WORDS.flagString())) { wordsAndOccurrences = countWords(words, words); } else if (cmd.hasOption(SPECIFIC_WORDS.flagString())) { wordsAndOccurrences = countWords(words, cmd.getOptionValue(SPECIFIC_WORDS.flagString()).split(",")); } else { System.out.println("Missing information: -all or -w required."); return; } if (wordsAndOccurrences != null) { wordsAndOccurrences.forEach((word, countMap) -> { Collection<Integer> countValues = countMap.values(); System.out.printf("-> %s:%n", word); countMap.forEach((chapter, numOccurrences) -> { System.out.printf("--> Chapter %s: %s occurrences", chapter, numOccurrences); System.out.printf("%n"); }); System.out.printf("-> Total: %s ", countValues.stream().mapToInt(i -> i).sum()); System.out.print("("); countValues.stream() .mapToInt(i -> i) .min() .ifPresent(i -> System.out.printf("min: %s, ", i)); countValues.stream() .mapToInt(i -> i) .max() .ifPresent(i -> System.out.printf("max: %s, ", i)); countValues.stream() .mapToInt(i -> i) .average() .ifPresent(d -> System.out.printf("average: %s", Math.round(d))); System.out.print(") "); System.out.printf("occurrences.%n%n"); }); } } catch (IOException | ParseException e) { e.printStackTrace(); } } private static Optional<File> getInputFile(CommandLine cmd) { if (cmd.hasOption(FILE_DIRECTORY_INPUTTED.flagString())) { File f = new File(cmd.getOptionValue(FILE_DIRECTORY_INPUTTED.flagString())); if (!f.exists()) System.out.println("Given input file does not exist."); return Optional.of(f); } else if (cmd.hasOption(FILE_DIRECTORY_SELECTED.flagString())) { JFileChooser jFileChooser = new JFileChooser(); jFileChooser.addChoosableFileFilter(new FileNameExtensionFilter(null, "txt")); int confirm = jFileChooser.showDialog(null, "Select"); if (confirm == JFileChooser.APPROVE_OPTION) { return Optional.of(jFileChooser.getSelectedFile()); } else { return Optional.empty(); } } return Optional.empty(); } private static String[] readInput(File f) throws IOException { ArrayList<String> words = new ArrayList<>(); BufferedReader reader = new BufferedReader(new FileReader(f)); String s; while ((s = reader.readLine()) != null) { Collections.addAll(words, s.replaceAll("[^A-Za-z0-9]+", " ").toLowerCase().split("\\s")); } String[] wordsArr = new String[words.size()]; wordsArr = words.toArray(wordsArr); return wordsArr; } public static Map<String, Map<Integer, Integer>> countWords(String[] input, String[] words) { TreeMap<String, Map<Integer, Integer>> map = new TreeMap<>(); for (String word : words) { map.put(word, new HashMap<>()); } int chapter = 0; for (String word : input) { if (word.matches("[0-9]+")) { chapter++; continue; } if (map.containsKey(word)) { Map<Integer, Integer> wordCount = map.get(word); if (wordCount.containsKey(chapter)) { wordCount.put(chapter, wordCount.get(chapter) + 1); } else { wordCount.put(chapter, 1); } } } return map; } }
package com.itsoul.lab.application.bank; import com.itsoul.lab.domain.models.TransactionSearchQuery; import com.it.soul.lab.sql.SQLExecutor; import com.it.soul.lab.sql.query.QueryType; import com.it.soul.lab.sql.query.SQLJoinQuery; import com.it.soul.lab.sql.query.SQLQuery; import com.it.soul.lab.sql.query.models.Operator; import com.it.soul.lab.sql.query.models.Predicate; import com.it.soul.lab.sql.query.models.Where; import com.itsoul.lab.generalledger.entities.Money; import com.itsoul.lab.generalledger.entities.Transaction; import com.itsoul.lab.generalledger.entities.TransferRequest; import com.itsoul.lab.ledgerbook.accounting.head.ChartOfAccounts; import com.itsoul.lab.ledgerbook.accounting.head.Ledger; import com.itsoul.lab.ledgerbook.connector.SourceConnector; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * This a thread-safe bean: */ public class LedgerBook { private static Logger LOG = Logger.getLogger(LedgerBook.class.getSimpleName()); private SourceConnector connector; private String owner; private String password; private String tenantID; private String currency; public LedgerBook(SourceConnector connector, String owner, String password, String tenantID, String currency) { this.connector = connector; this.owner = owner; this.password = password; this.tenantID = tenantID; this.currency = currency; } public Money createAccount(String prefix, String username, String deposit) throws RuntimeException{ // String cash_account = getACNo(username, prefix); // ChartOfAccounts chartOfAccounts = new ChartOfAccounts.ChartOfAccountsBuilder() .create(cash_account, deposit, currency) .build(); // Money money = null; Ledger book = null; try { book = getLedger(chartOfAccounts); money = Money.toMoney(deposit, currency); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (book != null) book.close(); } return money; } public String validateTransactionRef(String ref){ if (ref.length() > 20) ref = ref.substring(0, 19); return ref; } public Money readBalance(String prefix, String username) { // String cash_account = getACNo(username, prefix); ChartOfAccounts chartOfAccounts = new ChartOfAccounts.ChartOfAccountsBuilder() .retrive(cash_account) .build(); // Money money = null; Ledger book = null; try { book = getLedger(chartOfAccounts); money = book.getAccountBalance(cash_account); } catch (Exception e) { money = Money.NULL_MONEY; } finally { if (book != null) book.close(); } return money; } public boolean isAccountExist(String prefix, String username) { // String cash_account = getACNo(username, prefix); ChartOfAccounts chartOfAccounts = new ChartOfAccounts.ChartOfAccountsBuilder() .retrive(cash_account) .build(); Ledger book = null; boolean isExist = false; try{ book = getLedger(chartOfAccounts); isExist = book.getAccountBalance(cash_account) != null; }catch (Exception e) {} finally { if (book != null) book.close(); } return isExist; } public Money makeTransactions(String type , String ref , String from , String amount , String to) throws RuntimeException{ // Ledger book = null; try { // ChartOfAccounts chartOfAccounts = new ChartOfAccounts.ChartOfAccountsBuilder() .retrive(from) .retrive(to) .build(); // book = getLedger(chartOfAccounts); //Transfer request: TransferRequest transferRequest1 = book.createTransferRequest() .reference(validateTransactionRef(ref)) .type(type) .account(from).debit(amount, currency) .account(to).credit(amount, currency) .build(); book.commit(transferRequest1); //At the end close the ledger book: Money money = book.getAccountBalance(from); return money; }catch (Exception e){ throw new RuntimeException(e.getMessage()); }finally { if (book != null) book.close(); } } private Ledger getLedger(ChartOfAccounts chartOfAccounts){ Ledger book = new Ledger.LedgerBuilder(chartOfAccounts) .name("General Ledger") .connector(getConnector()) .client(owner, tenantID) .secret(password) .skipLogPrinting(true) .build(); return book; } public SourceConnector getConnector() { return connector; } public static String getName(String username){ String name = username.split("@")[0]; if(name.length() > 14) name = name.substring(0, 13); //14-char as Name: +8801712645571 or any unique-name length of 14 char return name; } public static String getACTitle(String username){ String name = username.split("@")[0]; if (name.length() > 20) name = name.substring(0,19); return name; } public static String getACNo(String username, String prefix){ String name = getName(username); int nameLength = name.length(); int howShort = Math.abs(nameLength - 14); if((howShort + 5) < prefix.length()) prefix = prefix.substring(0, (howShort + 5)); //greater then 5 char return prefix + "@" + name; } public static String parseUsername(String accountNo){ try { String name = accountNo.split("@")[1]; return name; } catch (Exception e) {} return ""; } public static String parsePrefix(String accountNo){ String prefix = accountNo.split("@")[0]; return prefix; } public static String generateTransactionRef(String username) { return UUID.randomUUID().toString().substring(0, 18); } public List<Transaction> findTransactions(String prefix, String username) { String cash_account = getACNo(username, prefix); ChartOfAccounts chartOfAccounts = new ChartOfAccounts.ChartOfAccountsBuilder() .retrive(cash_account) .build(); Ledger book = getLedger(chartOfAccounts); List<Transaction> cashAccountTransactionList = book.findTransactions(cash_account); return cashAccountTransactionList; } /** * Select * th.transaction_ref * , th.transaction_type * , th.transaction_date * , tl.account_ref * , tl.amount * , tl.currency * , tl.balance * from transaction_history as th * Left Join transaction_leg as tl on (th.transaction_ref = tl.transaction_ref) * where 1 * and tl.account_ref = 'CASH@towhid' * and tl.tenant_ref = 'my-app-id' * and tl.client_ref = 'sa' * order by th.transaction_date DESC; */ public List<Map<String, Object>> findTransactions(String prefix, String username, TransactionSearchQuery query) { String cash_account = getACNo(username, prefix); Predicate clause = new Where("tl.account_ref").isEqualTo(cash_account) .and("tl.tenant_ref").isEqualTo(tenantID) .and("tl.client_ref").isEqualTo(owner); //Queryable- by Type, From-Date, To-Date if (query.get("type") != null){ clause.and("th.transaction_type").isLike("%"+ query.get("type", String.class)+"%"); } if (query.get("from") != null && query.get("to") != null) { //TODO: clause.between(query.get("from", String.class), query.get("to", String.class)); } else if (query.get("from") != null && query.get("till") != null) { //TODO: clause.between(query.get("from", String.class), query.get("till", String.class)); } else { if (query.get("from") != null) { clause.and("th.transaction_date").isGreaterThenOrEqual(query.get("from", String.class)); } if (query.get("to") != null) { clause.and("th.transaction_date").isLessThenOrEqual(query.get("to", String.class)); } if (query.get("till") != null) { clause.and("th.transaction_date").isLessThen(query.get("till", String.class)); } } // SQLJoinQuery joins = new SQLQuery.Builder(QueryType.LEFT_JOIN) .joinAsAlice("transaction_history", "th" , "transaction_ref", "transaction_type", "transaction_date") .on("transaction_ref", "transaction_ref") .joinAsAlice("transaction_leg", "tl" , "account_ref", "amount", "currency", "balance") .where(clause) .orderBy(Operator.DESC, "th.transaction_date") .build(); //joins.toString(); try (SQLExecutor executor = new SQLExecutor(connector.getConnection())) { ResultSet set = executor.executeSelect(joins); List<Map<String, Object>> data = executor.convertToKeyValuePair(set); return data; } catch (SQLException e) { LOG.log(Level.WARNING, e.getMessage()); } return new ArrayList<>(); } }
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class MenuPanel extends JPanel implements ActionListener { private static final long serialVersionUID = 1L; public static String nazwa; private BufferedImage img = null; public boolean StartingPoint = false; JButton start; public static JTextField name; public MenuPanel() throws IOException { setLayout(null); setFocusable(true); setVisible(true); JLabel textTitle = new JLabel("Flappy Bat"); textTitle.setFont(new Font ("Snap ITC", Font.BOLD, 38 )); textTitle.setForeground(Color.YELLOW); textTitle.setBounds(65, 100, 350, 60); add(textTitle); JLabel textName = new JLabel ("Enter your name"); textName.setBounds(138, 220, 150, 30); textName.setForeground(Color.yellow); name = new JTextField (30); name.setBounds(135, 250, 100, 30); add(textName); add(name); JButton start = new JButton("Start"); start.setBounds(135, 350, 100, 40); start.setFont(new Font ("Snap ITC", Font.BOLD, 12 )); start.setForeground(Color.YELLOW); start.setBackground(Color.BLACK); add(start); start.addActionListener(this); start.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); StartingPoint = true; nazwa = name.getText(); } }); } //tło @Override protected void paintComponent( Graphics g ){ super.paintComponent( g ); Image im = getToolkit().getImage("src/main/resources/tlo_gra.png"); g.drawImage( im, 0, 0, this ); } public void actionPerformed(ActionEvent e) { } }
package fr.softwaresemantics.howmanydroid.util; import android.app.Activity; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.webkit.WebView; import fr.softwaresemantics.howmanydroid.R; import fr.softwaresemantics.howmanydroid.model.formula.FormulaSyntax; /** * Created by cmh on 05/01/14. */ public class MJView { private Activity context; private WebView w; private boolean isInitializing; private boolean somethingWaitingToDisplay; private FormulaSyntax syntax; private String[] formula; public MJView(Activity context, WebView w) { formula = new String[2]; this.w = w; this.context = context; initMathjax(w); } private void initMathjax(WebView w) { isInitializing = true; w.getSettings().setJavaScriptEnabled(true); w.addJavascriptInterface(this, "MJView"); w.loadUrl("file:///android_asset/baseDocMj3.html"); } public void notifyMJInitComplete() { Log.i("notifyMJInitComplete", "MJInitComplete"); isInitializing = false; if (somethingWaitingToDisplay) { // Cette notification est exécuté dans un thread spécifique "Java Bridge" // impropre à l'appel de la webview Handler mainHandler = new Handler(context.getMainLooper()); Runnable myRunnable = new Runnable() { public void run() { for (int i = 0; i < formula.length; i++) { if (formula[i] == null) break; updateFormula(syntax, formula[i],i); } }}; mainHandler.post(myRunnable); } } public void displayMath(FormulaSyntax syntax, String formula) { displayMath(syntax, formula, 0); // FIXME? : effacer les autres lignes ? } public void displayMath(FormulaSyntax syntax, String formula, int line) { this.formula[line] = formula; this.syntax = syntax; // Se synchroniser et attendre la fin de l'init MJ if (!isInitializing) { updateFormula(syntax, formula, line); } else { // marquer à faire plus tard somethingWaitingToDisplay = true; } } // public void updateFormula(FormulaSyntax syntax, String formula) { // switch (syntax) { // case ASCII_MATHML: // w.loadUrl("javascript:UpdateMathAsciiML('" + formula + "', 0);"); // break; // case TEX: // // Attention les formules Tex doivent quoter les _\ // String quoted = formula.replace("\\", "\\\\"); // w.loadUrl("javascript:UpdateMathTexML('" + quoted + "', 0);"); // break; // case DISPLAY_MATHML: // String quoted2 = formula.replace("\\", "\\\\"); // w.loadUrl("javascript:UpdateMathML('" + quoted2 + "', 0);"); // break; // } // } public void updateFormula(FormulaSyntax syntax, String formula, int line) { switch (syntax) { case ASCII_MATHML: w.loadUrl("javascript:UpdateMathAsciiML('" + formula + "', "+line+");"); break; case TEX: // Attention les formules Tex doivent quoter les _\ String quoted = formula.replace("\\", "\\\\"); w.loadUrl("javascript:UpdateMathTexML('" + quoted + "', "+line+");"); break; case DISPLAY_MATHML: String quoted2 = formula.replace("\\", "\\\\"); w.loadUrl("javascript:UpdateMathML('" + quoted2 + "', "+line+");"); break; } } public String loadFormulaFromDemo(String path, String file) { try { String formula = AssetsUtil.loadUTF8AssetAsString(context, path, file); formula = formula.replaceAll("\r|\n", ""); return formula; } catch (Exception ex) { ex.printStackTrace(); return null; } } }
package sie.amplifier_conctroller.ui; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import com.feasycom.s_port.R; import com.feasycom.s_port.ShareFile.FEShare; import com.feasycom.s_port.model.MyLog; import sie.amplifier_conctroller.DataStruct.DataStruct; import sie.amplifier_conctroller.Sie_app_data_share; public class dsp_setting_fq_dv extends AppCompatActivity { final String TAG = dsp_setting_delay.class.getSimpleName(); private FEShare share = FEShare.getInstance(); Sie_app_data_share sie_data_share; Button [] buttonsFreLowList; Button [] buttonsFreHightList; Dialog dialogFrq; View dialogView; Button buttonSure; Button buttonSub; Button buttonInc; SeekBar seekBarInDialog; int curSeekbarProgress = 0; TextView tvFreq; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_xover); sie_data_share = (Sie_app_data_share)getApplication(); initfq(); } @Override protected void onDestroy() { super.onDestroy(); //解除广播接收器 unregisterReceiver(receiver); } // Activity出来时候,绑定广播接收器,监听蓝牙连接服务传过来的事件 @Override protected void onResume() { super.onResume(); registerReceiver(receiver, share.getIntent_ui_fq_dv_Filter()); } private Handler myHandler = new Handler() { // 2.重写消息处理函数 public void handleMessage(Message msg) { switch (msg.what) { case 1: { //flashUIFromProtocol(msg.arg1); break; } } super.handleMessage(msg); } }; private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); Message msg = new Message(); Bundle bundle = new Bundle(); MyLog.v(TAG,"delay"); if (share.SIE_UI_ACTION_CHANLE_FRE.equals(action)) { // 连接成功 msg.what=1; msg.arg1= DataStruct.sieProtocol.prtc_chanleFreFilter; } myHandler.sendMessage(msg); } }; private void initfq() { buttonsFreHightList = new Button[DataStruct.max_channel]; buttonsFreHightList[0] = (Button)findViewById(R.id.id_b_hp_freq_ch0); buttonsFreHightList[1] = (Button)findViewById(R.id.id_b_hp_freq_ch1); buttonsFreHightList[2] = (Button)findViewById(R.id.id_b_hp_freq_ch2); buttonsFreHightList[3] = (Button)findViewById(R.id.id_b_hp_freq_ch3); buttonsFreHightList[4] = (Button)findViewById(R.id.id_b_hp_freq_ch4); buttonsFreHightList[5] = (Button)findViewById(R.id.id_b_hp_freq_ch5); buttonsFreHightList[6] = (Button)findViewById(R.id.id_b_hp_freq_ch6); buttonsFreHightList[7] = (Button)findViewById(R.id.id_b_hp_freq_ch7); buttonsFreLowList = new Button[DataStruct.max_channel]; buttonsFreLowList[0] = (Button)findViewById(R.id.id_b_lp_freq_ch0); buttonsFreLowList[1] = (Button)findViewById(R.id.id_b_lp_freq_ch1); buttonsFreLowList[2] = (Button)findViewById(R.id.id_b_lp_freq_ch2); buttonsFreLowList[3] = (Button)findViewById(R.id.id_b_lp_freq_ch3); buttonsFreLowList[4] = (Button)findViewById(R.id.id_b_lp_freq_ch4); buttonsFreLowList[5] = (Button)findViewById(R.id.id_b_lp_freq_ch5); buttonsFreLowList[6] = (Button)findViewById(R.id.id_b_lp_freq_ch6); buttonsFreLowList[7] = (Button)findViewById(R.id.id_b_lp_freq_ch7); for (int i = 0;i<DataStruct.max_channel;i++) { buttonsFreHightList[i].setText(""+DataStruct.freDivHight[i]+"Hz"); buttonsFreLowList[i].setText(""+DataStruct.freDivLow[i]+"Hz"); buttonsFreHightList[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (int j = 0;j<DataStruct.max_channel;j++) { if (v.getId()==buttonsFreHightList[j].getId()) { MyLog.v(TAG,"show"); curSeekbarProgress = DataStruct.freDivHight[j]; seekBarInDialog.setProgress(curSeekbarProgress); DataStruct.curFreDiv = j; dialogFrq.show(); MyLog.v(TAG,"show end"); } } } }); buttonsFreLowList[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (int j = 0;j<DataStruct.max_channel;j++) { if (v.getId()==buttonsFreLowList[j].getId()) { MyLog.v(TAG,"show?"); curSeekbarProgress = DataStruct.freDivLow[j]; seekBarInDialog.setProgress(curSeekbarProgress); DataStruct.curFreDiv =10 + j; dialogFrq.show(); } } } }); DataStruct.curFreDiv = i; updateCurFreDv(); DataStruct.curFreDiv = i+10; updateCurFreDv(); } DataStruct.curFreDiv = 0; dialogFrq = new Dialog(this); dialogView = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_user_data_dialog, (ViewGroup)findViewById(R.id.LinearLayout_userdata_dialog)); dialogFrq.setContentView(dialogView); dialogFrq.setCanceledOnTouchOutside(false); dialogFrq.setTitle(getResources().getText(R.string.Frequency)); tvFreq = (TextView)dialogView.findViewById(R.id.tv_progress) ; buttonInc = (Button)dialogView.findViewById(R.id.id_b_fre_inc); buttonSub = (Button)dialogView.findViewById(R.id.id_b_fre_sub); buttonSure = (Button)dialogView.findViewById(R.id.id_b_userdata_ok); seekBarInDialog = (SeekBar)dialogView.findViewById(R.id.progress_in_dialog); seekBarInDialog.setMax(20000); seekBarInDialog.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { curSeekbarProgress = progress; tvFreq.setText(""+curSeekbarProgress+"Hz"); if (DataStruct.curFreDiv<10&&DataStruct.curFreDiv>=0) { DataStruct.freDivHight[DataStruct.curFreDiv] = curSeekbarProgress; }else if(DataStruct.curFreDiv>=10) { DataStruct.freDivLow[DataStruct.curFreDiv-10] = curSeekbarProgress; } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); buttonInc.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { curSeekbarProgress++; updateDialog(); } }); buttonSub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { curSeekbarProgress++; updateDialog(); } }); buttonSure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialogFrq.cancel(); updateCurFreDv(); sie_data_share.sendSieData(DataStruct.sieProtocol.prtc_chanleFreFilter); } }); } void updateCurFreDv() { if (DataStruct.curFreDiv<10) { buttonsFreHightList[DataStruct.curFreDiv].setText(String.format("%d"+"Hz",DataStruct.freDivHight[DataStruct.curFreDiv])); }else if(DataStruct.curFreDiv>=10){ buttonsFreLowList[DataStruct.curFreDiv-10].setText(String.format("%d"+"Hz",DataStruct.freDivLow[DataStruct.curFreDiv-10])); } } void updateDialog() { seekBarInDialog.setProgress(curSeekbarProgress); tvFreq.setText(""+curSeekbarProgress+"Hz"); } }
package com.esum.xtrus.boot.classloader; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * xTrus의 Main ClassLoader, xTrus의 Engine 라이브러리가 등로된다. */ public class XtrusBootClassLoader extends URLClassLoader implements XtrusBootClassLoaderMBean { public XtrusBootClassLoader(ClassLoader parent) { super(new URL[0], parent); } public void addClasses(String path){ try { URL clazzPass = new File(path).getAbsoluteFile().toURI().toURL(); addURL(clazzPass); } catch (MalformedURLException e) { } } public void addLib(String path) { List<URL> URLs = listJars(new File(path)); for (URL url : URLs) { addURL(url); } } private List<URL> listJars(File path) { List<URL> jarList = new ArrayList<URL>(); File[] nodes = path.listFiles(); for (File n : nodes) { if (n.isFile()) { try { if (n.getName().toUpperCase().endsWith(".JAR")) { jarList.add(n.toURI().toURL()); } } catch (IOException e) { } } else { jarList.addAll(listJars(n)); } } return jarList; } }
package com.example.tiny.config; import org.springframework.amqp.core.*; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @ClassName: RabbitConfig * @Description: Rabbit配置类 * @Author: yongchen * @Date: 2021/3/17 16:15 **/ @Configuration public class RabbitConfig { /** * 消费队列绑定交换器 **/ @Bean public DirectExchange orderDirect() { return (DirectExchange) ExchangeBuilder.directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange()).durable(true).build(); } /** * 延迟队列绑定交换器 **/ @Bean public DirectExchange orderTtlDirect() { return (DirectExchange) ExchangeBuilder.directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange()).durable(true).build(); } /** * 消费队列 **/ @Bean public Queue orderQueue(){ return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName()); } /** * 延迟队列(死信队列) **/ @Bean public Queue orderTtlQueue(){ return QueueBuilder .durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName()) //到期后转发的交换机 .withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange()) //到期后转发的路由键 .withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey()) .build(); } /** * 将队列绑定到交换器 **/ @Bean public Binding orderBinding(DirectExchange orderDirect, Queue orderQueue){ return BindingBuilder .bind(orderQueue) .to(orderDirect) .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey()); } /** * 将延迟队列绑定到交换器 **/ @Bean public Binding orderTtlBinding(DirectExchange orderTtlDirect, Queue orderTtlQueue){ return BindingBuilder .bind(orderTtlQueue) .to(orderTtlDirect) .with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey()); } }
package com.beike.hesssian.test; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import com.beike.action.pay.hessianclient.TrxHessianServiceGateWay; import com.beike.biz.service.trx.daemon.AccountNotifyDaemon; import com.beike.biz.service.trx.daemon.TrxOrderNotifyDaemon; /** * @Title: RebateProcessServiceTest.java * @Package com.beike.demo.test * @Description: TODO * @date May 10, 2011 1:35:17 PM * @author wh.cheng * @version v1.0 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/applicationContext.xml", "classpath:/springcontexttrx/trx-applicationContext.xml" }) @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class }) public class RebateProcessServiceTest { // @Test // public void testRebateByTrxGoods() { // // Map<String, String> map = new HashMap<String, String>(); // map.put("trxGoodsId", "95"); // // map.put("goodsName", "123|1212|121"); // // Map rspMap=trxHessianService.rebatebyTrxGoodsId(map); // System.out.println(rspMap.get("STATUS")); // System.out.println(rspMap.get("RSPCODE")); // } @Autowired private TrxOrderNotifyDaemon trxOrderNotifyDaemon; //@Test public void testTrxCreate() throws UnsupportedEncodingException { Map<String, String> map = new HashMap<String, String>(); map.put("userId", "1020"); map.put("providerType", "YEEPAY"); map.put("providerChannel", "BOC"); map.put("goodsName", URLEncoder.encode("阿斯顿第三方", "utf-8")); map.put("goodsId", "12496"); map.put("sourcePrice", "20"); map.put("payPrice", "0"); map.put("rebatePrice", "5"); map.put("dividePrice", "10"); map.put("guestId", "123456"); map.put("orderLoseAbsDate", "60"); map.put("orderLoseDate", "null"); map.put("trxType", "NORMAL"); map.put("payMp", "5" + "-" + "13683334717" + "-" + 12496); map.put("prizeId", "100000000"); map.put("des", "123.0"); map.put("reqChannel", "BOSS"); map.put("goodsCount", "10"); Map rspMap = null; System.out.println(rspMap.get("status")); System.out.println(rspMap.get("rspCode")); } @Autowired private AccountNotifyDaemon accountNotifyDaemon; @Test public void testTrxCreateInMC1() throws UnsupportedEncodingException { Map<String, String> map = new HashMap<String, String>(); map.put("userId", "1117051"); map.put("pageOffset", "0"); map.put("isCachePage", "0"); map.put("uuid", "111111111111111111111122"); map.put("pageSize", "10"); map.put("reqChannel", "BOSS"); Map<String,String> rspMap = trxHessianServiceGateWay.queryPurse(map); System.out.println(rspMap.get("rspCode")); System.out.println("**************************"+rspMap); } /* * @Test public void testRefundToBank() { Map<String, String> map = new * HashMap<String, String>(); * * map.put("trxGoodsId", "10227"); * * map.put("operator", "test"); * * Map rspMap = trxHessianService.refundToBank(map); * * System.out.println(rspMap.get("STATUS")); * System.out.println(rspMap.get("RSPCODE")); } */ /* * @Test public void testComplateTrx() { * * Map<String, String> map = new HashMap<String, String>(); * map.put("payRequestId", "Requestf80b70ad0ea445fbb6b"); * map.put("proExternallId", "test11011955s4"); map.put("sucTrxAmount", * "80"); * * Map rspMap = trxHessianService.complateTrx(map); * System.out.println(rspMap.get("STATUS")); * System.out.println(rspMap.get("RSPCODE")); } */ /* * @Test public void testHessianService() { OrderInfo orderInfo = new * OrderInfo(); Map<String,String> map=new HashMap<String,String>(); * map.put("userId", "20"); map.put("trxAmount", "0.01"); * map.put("bizType","test"); //Map * rspMap=trxHessianService.createAccount(map); //Map * rspMap=trxHessianService.getActByUserId(map); Map rspMap; * * * rspMap = trxHessianService.rebate(map); * System.out.println(rspMap.get("STATUS")); * System.out.println(rspMap.get("RSPCODE")); } */ /* * @Test public void testBizProcessFactory() { OrderInfo orderInfo = new * OrderInfo(); * * orderInfo.setBizType("rebate-biz"); orderInfo.setUserId(120L); * orderInfo.setExtendInfo("extendInfo"); orderInfo.setTrxAmount(105D); * orderInfo.setBizProcessType(BizProcessType.REBATE); try { try { * bizProcessFactory.getProcessService(orderInfo); } catch (RebateException * e) { // TODO Auto-generated catch block e.printStackTrace(); } catch * (AccountException e) { // TODO Auto-generated catch block * e.printStackTrace(); } catch (TrxOrderException e) { // TODO * Auto-generated catch block e.printStackTrace(); } catch (PaymentException * e) { // TODO Auto-generated catch block e.printStackTrace(); } catch * (TrxorderGoodsException e) { // TODO Auto-generated catch block * e.printStackTrace(); } } catch (ProcessServiceException e) { // TODO * Auto-generated catch // block e.printStackTrace(); } } /* @Test public * void testAddUserEmailRegist(){ OrderInfo orderInfo=new OrderInfo(); * * orderInfo.setBizType("rebate-biz"); orderInfo.setUserId(123L); * orderInfo.setExtendInfo("extendInfo"); * orderInfo.setTrxAmount(105.676767D); * * try { rebateProcessService.process(orderInfo); } catch * (ProcessServiceException e) { // TODO Auto-generated catch block * e.printStackTrace(); } } */ /* * @Test public void testGuidGenerator(){ * * String iSpecId=guidGenerator.getCode("Trx"); System.out.print(iSpecId); } */ /* * @Test public void testRebRecordService(){ * * RebRecord rebRecord=new RebRecord(); * * * rebRecord.setCreateDate(new Date()); rebRecord.setExternalId("22"); * rebRecord.setRequestId("dsdsds"); rebRecord.setTrxAmount(100L); * rebRecord.setTrxStatus(TrxStatus.INIT); rebRecord.setUserId(5L); * rebRecord.setOrderType(OrderType.REBATE); try { * rebRecordService.create(rebRecord); } catch (RebateException e) { // TODO * Auto-generated catch block e.printStackTrace(); } } */ /* * @Test public void testAccountService(){ * * try { accountService.create(121L); } catch (AccountException e) { // TODO * Auto-generated catch block e.printStackTrace(); } } */ /* * @Test public void testAccountHistoryDao(){ * * AccountHistory actHistory=new AccountHistory(); * * actHistory.setAccountId(100L); * actHistory.setActHistoryType(ActHistoryType.SALES); * actHistory.setBalance(100D); actHistory.setBizType("bizType"); * actHistory.setCreateDate(new Date()); actHistory.setTrxId(100L); * actHistory.setDispaly(true); actHistory.setDescription("desc"); * accountHistoryDao.addAccountHistory(actHistory); } */ //@Test public void testTrxCreateInMC() throws UnsupportedEncodingException { Map<String, String> map = new HashMap<String, String>(); map.put("reqChannel", "PARTNER"); map.put("guestId", "914003183"); map.put("voucherCode", "70784119"); map.put("voucherVerifySource", "SMS"); map.put("subGuestId", "1"); map.put("description","111111"); //List<Map<String, Object>> list = trxorderGoodsDao.findTrxorderGoodsByGoodsIdTrxorderId("1818874","38062"); //trxorderGoodsService.findTrxorderGoodsByUserIdStatus(1020L, 0, 5, "USEDINPFVOU|COMMENTEDINPFVOU|EXPIRED|REFUNDTOACT|RECHECK|REFUNDTOBANK"); /*Map<String, Object> togMap = list.get(0); String lastUpdateDate = DateUtils.dateToStrLong( togMap.get("lastUpdateDate")==null?new Date():(Date)togMap.get("lastUpdateDate")); System.out.println(lastUpdateDate);*/ //Map<String,String> rspMap = trxHessianServiceGateWay.createTrxOrder(map); Map<String,String> rspMap = trxHessianServiceGateWay.validateVoucher(map); System.out.println(rspMap.get("status")); System.out.println(rspMap.get("rspCode")); System.out.println("**************************"+rspMap); } @Resource(name = "webClient.trxHessianServiceGateWay") private TrxHessianServiceGateWay trxHessianServiceGateWay; }
//------------------------------------------------------------------------------ // Copyright (c) 2012 Microsoft Corporation. All rights reserved. // // Description: See the class level JavaDoc comments. //------------------------------------------------------------------------------ package com.microsoft.live; import java.io.InputStream; import android.text.TextUtils; /** * Represents data returned from a download call to the Live Connect Representational State * Transfer (REST) API. */ public class LiveDownloadOperation { static class Builder { private ApiRequestAsync<InputStream> apiRequestAsync; private final String method; private final String path; private InputStream stream; private Object userState; public Builder(String method, String path) { assert !TextUtils.isEmpty(method); assert !TextUtils.isEmpty(path); this.method = method; this.path = path; } /** * Set if the operation to build is an async operation. * * @param apiRequestAsync * @return this Builder */ public Builder apiRequestAsync(ApiRequestAsync<InputStream> apiRequestAsync) { assert apiRequestAsync != null; this.apiRequestAsync = apiRequestAsync; return this; } public LiveDownloadOperation build() { return new LiveDownloadOperation(this); } public Builder stream(InputStream stream) { assert stream != null; this.stream = stream; return this; } public Builder userState(Object userState) { this.userState = userState; return this; } } private final ApiRequestAsync<InputStream> apiRequestAsync; private int contentLength; private final String method; private final String path; private InputStream stream; private final Object userState; LiveDownloadOperation(Builder builder) { this.apiRequestAsync = builder.apiRequestAsync; this.method = builder.method; this.path = builder.path; this.stream = builder.stream; this.userState = builder.userState; } public void cancel() { final boolean isCancelable = this.apiRequestAsync != null; if (isCancelable) { this.apiRequestAsync.cancel(true); } } /** * @return The type of HTTP method used to make the call. */ public String getMethod() { return this.method; } /** * @return The length of the stream. */ public int getContentLength() { return this.contentLength; } /** * @return The path for the stream object. */ public String getPath() { return this.path; } /** * @return The stream object that contains the downloaded file. */ public InputStream getStream() { return this.stream; } /** * @return The user state. */ public Object getUserState() { return this.userState; } void setContentLength(int contentLength) { assert contentLength >= 0; this.contentLength = contentLength; } void setStream(InputStream stream) { assert stream != null; this.stream = stream; } }
package Graphs.directed; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Nput_graph { public Nput_graph() throws NumberFormatException, IOException { // TODO Auto-generated constructor stub create(); } private void create() throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i,j; System.out.println("Input the total no of cities the salesman has to travel through"); int tpairs=Integer.parseInt(br.readLine()); int ar[][]=new int[tpairs][tpairs]; for(i=0;i<tpairs;i++){ for ( j = 0; j < ar.length; j++) { ar[i][j]=Integer.parseInt(br.readLine()); } } System.out.println("input sucess --follow execution for file storage"); } }
package com.larryhsiao.nyx.core.jots.moods; /** * Constant of {@link RankedMood} */ public class ConstRankedMood implements RankedMood { private final String mood; private final int usedTimes; public ConstRankedMood(String mood, int usedTimes) { this.mood = mood; this.usedTimes = usedTimes; } @Override public String mood() { return mood; } @Override public int usedTimes() { return usedTimes; } }
package com.vicutu.batchdownload.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.functors.NOPTransformer; public class URICollectionFilter { private final Collection<String> innerCollection; public static URICollectionFilter valueOf(Collection<String> inputCollection) { return new URICollectionFilter(inputCollection); } private URICollectionFilter() { innerCollection = null; } @SuppressWarnings("unchecked") private URICollectionFilter(Collection<String> input) { super(); innerCollection = CollectionUtils.collect(input, NOPTransformer.INSTANCE); } private URICollectionFilter reborn(Collection<String> c) { return valueOf(c); } public Collection<String> collection() { return innerCollection; } public List<String> list() { if (innerCollection instanceof List<?>) { return (List<String>) innerCollection; } else { return new ArrayList<String>(innerCollection); } } public Set<String> set() { if (innerCollection instanceof Set<?>) { return (Set<String>) innerCollection; } else { return new HashSet<String>(innerCollection); } } public URICollectionFilter removeDuplicate() { return reborn(URIUtils.removeDuplicate(innerCollection)); } public URICollectionFilter removeStartsWith(boolean caseSensitive, String... prefixes) { return reborn(URIUtils.removeStartsWith(innerCollection, caseSensitive, prefixes)); } public URICollectionFilter removeStartsWith(String... prefixes) { return removeStartsWith(true, prefixes); } public URICollectionFilter selectStartsWith(boolean caseSensitive, String... prefixes) { return reborn(URIUtils.selectStartsWith(innerCollection, caseSensitive, prefixes)); } public URICollectionFilter selectStartsWith(String... prefixes) { return selectStartsWith(true, prefixes); } public URICollectionFilter removeEndsWith(boolean caseSensitive, String... suffixes) { return reborn(URIUtils.removeEndsWith(innerCollection, caseSensitive, suffixes)); } public URICollectionFilter removeEndsWith(String... suffixes) { return removeEndsWith(true, suffixes); } public URICollectionFilter selectEndsWith(boolean caseSensitive, String... suffixes) { return reborn(URIUtils.selectEndsWith(innerCollection, caseSensitive, suffixes)); } public URICollectionFilter selectEndsWith(String... suffixes) { return selectEndsWith(true, suffixes); } public URICollectionFilter removeContains(boolean caseSensitive, String... contents) { return reborn(URIUtils.removeContains(innerCollection, caseSensitive, contents)); } public URICollectionFilter removeContains(String... contents) { return removeContains(true, contents); } public URICollectionFilter selectContains(boolean caseSensitive, String... contents) { return reborn(URIUtils.selectContains(innerCollection, caseSensitive, contents)); } public URICollectionFilter selectContains(String... contents) { return selectContains(true, contents); } public URICollectionFilter removeContainsPattern(String... regexes) { return reborn(URIUtils.removeContainsPattern(innerCollection, regexes)); } public URICollectionFilter selectContainsPattern(String... regexes) { return reborn(URIUtils.selectContainsPattern(innerCollection, regexes)); } public URICollectionFilter remove(Predicate... predicates) { return reborn(URIUtils.remove(innerCollection, predicates)); } public URICollectionFilter select(Predicate... predicates) { return reborn(URIUtils.select(innerCollection, predicates)); } }
package plugins.fmp.fmpSequence; import java.io.File; import java.nio.file.attribute.FileTime; import java.util.ArrayList; public class Experiment { public String filename = null; public SequenceVirtual vSequence = null; public ArrayList <SequencePlus> kymographArrayList = null; public FileTime fileTimeImageFirst; public FileTime fileTimeImageLast; public long fileTimeImageFirstMinutes = 0; public long fileTimeImageLastMinutes = 0; public int number_of_frames = 0; public int startFrame = 0; public int step = 1; public int endFrame = 0; public boolean openSequenceAndMeasures() { vSequence = new SequenceVirtual(); if (null == vSequence.loadVirtualStackAt(filename)) return false; fileTimeImageFirst = vSequence.getImageModifiedTime(0); fileTimeImageLast = vSequence.getImageModifiedTime(vSequence.getSizeT()-1); //System.out.println("read expt: "+ filename+" .....size "+ vSequence.getSizeT()); fileTimeImageFirstMinutes = fileTimeImageFirst.toMillis()/60000; fileTimeImageLastMinutes = fileTimeImageLast.toMillis()/60000; if (!vSequence.xmlReadCapillaryTrackDefault()) return false; String directory = vSequence.getDirectory() +File.separator+"results"; kymographArrayList = SequencePlusUtils.openFiles(directory, vSequence.capillaries); vSequence.xmlReadDrosoTrackDefault(); return true; } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.core; /** * RecoveringThread is used to display percentage of job recovered at startup. * * @author The ProActive Team * @since ProActive Scheduling 1.0 */ public class RecoveringThread extends Thread implements RecoverCallback { /** */ private static final long serialVersionUID = 31L; private int jobsToRecover = 1; private int jobsRecovered = 0; @Override public void run() { display("Found " + jobsToRecover + " jobs to retrieve, please wait... ", false); while (!isInterrupted() && jobsRecovered < jobsToRecover) { try { display(threeChar(100 * jobsRecovered / jobsToRecover), true); Thread.sleep(500); } catch (InterruptedException e) { } } display("100%\n", true); } public void init(int nb) { this.jobsToRecover = nb; if (nb > 0) { this.start(); } } public void jobRecovered() { this.jobsRecovered++; } private String threeChar(int i) { if (i < 10) { return " " + i + "%"; } if (i < 100) { return " " + i + "%"; } return i + "%"; } private void display(String msg, boolean backspaces) { if (backspaces) { //remove 4 chars on sysout System.out.print("\010\010\010\010"); } System.out.print(msg); } }
package com.gxtc.huchuan.data; import com.gxtc.commlibrary.data.BaseRepository; import com.gxtc.huchuan.bean.AccountSetInfoBean; import com.gxtc.huchuan.bean.dao.User; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.service.MineApi; import com.gxtc.huchuan.http.service.PayApi; import com.gxtc.huchuan.ui.mine.loginandregister.register.RegisterContract; import com.gxtc.huchuan.ui.mine.withdraw.WithdrawContract; import java.util.HashMap; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by ALing on 2017/2/13 . */ public class WithdrawRepository extends BaseRepository implements WithdrawContract.Source { @Override public void getAccountSetInfo(ApiCallBack<AccountSetInfoBean> callBack, String token) { addSub(PayApi.getInstance().getAccountSetInfo(token).subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<AccountSetInfoBean>>(callBack))); } @Override public void saveExpRecd(ApiCallBack<Void> callBack, HashMap<String, String> map) { addSub(PayApi.getInstance().saveExpRecd(map).subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<Void>>(callBack))); } @Override public void upUser(final ApiCallBack<User> callBack, String token) { Subscription sub = MineApi.getInstance().getUserInfo(token).subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<User>>(new ApiCallBack<User>() { @Override public void onSuccess(User data) { if (data != null) { UserManager.getInstance().saveUser(data); callBack.onSuccess(data); } } @Override public void onError(String errorCode, String message) { callBack.onError(errorCode, message); } })); addSub(sub); } }
class NestFour { void m1(){ System.out.println("m1 NestFour class"); class InnerFour { void m2(){System.out.println("m2 InnerFour class");} } InnerFour f = new InnerFour(); f.m2(); } void m3(){ System.out.println("m3 NestFour class"); class InnerFour { void m4(){System.out.println("m4 InnerFour class");} } InnerFour r = new InnerFour(); r.m4(); } public static void main(String[] args) { NestFour n = new NestFour(); n.m1(); n.m3(); } }
package com.smartboma.development.m_bankingapp.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.smartboma.development.m_bankingapp.R; import com.smartboma.development.m_bankingapp.models.Finances; import java.util.List; /** * Created by Mwatha on 02/11/2016. */ public class FinanceAdapter extends RecyclerView.Adapter<FinanceAdapter.ViewHolder> { List<Finances> financesList; private Context context; public FinanceAdapter(List<Finances> financesList, Context context) { this.financesList = financesList; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.financelayout, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(FinanceAdapter.ViewHolder holder, int position) { Finances finances=financesList.get(position); holder.header.setText(finances.getHeader()); holder.content.setText(finances.getContent()); } @Override public int getItemCount() { return financesList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView header,content; public ViewHolder(View itemView) { super(itemView); header=(TextView) itemView.findViewById(R.id.finance_tip_heading); content=(TextView)itemView.findViewById(R.id.finance_contents); } } }
package ru.shikhovtsev;//java -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=n ru.otus.ru.shikhovtsev.RemoteDebug public class RemoteDebug { public static void main(String[] args) { new RemoteDebug().loop(); } private int counter = 0; private void loop() { while (true) { counter += 1; incInt(); System.out.println(counter); } } private void incInt() { counter += 1000; } public class TestByte { byte valByte; } }
package com.trump.auction.back.order.model; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author wangjian */ @Data public class Logistics { /** * 主键,不为空 */ private Integer id; /** * 物流第三发发货单号 */ private String logisticsId; /** * 物流公司名称 */ private String logisticsName; /** * 物流信息 JSON 大字段 */ private String logisticsInfo; /** * 物流公司code */ private String logisticsCode; /** * 创建时间 */ private Date createDate; /** * 物流发货时间 */ private Date startTime; /** * 物流状态:0未发货,1已发货 */ private Integer logisticsStatus; /** * 订单号 */ private String orderId; /** * 收货人 */ private String transName; /** * 收货人电话 */ private String transTelphone; /** * 收货人手机号 */ private String transPhone; /** * 省 */ private Integer provinceCode; /** * 城市 */ private Integer cityCode; /** * 区 */ private Integer districtCode; /** * 镇 */ private Integer townCode; /** * 收货人详细地址 */ private String address; /** * 收货人 邮编 */ private String receiverCode; /** * 省 */ private String provinceName; /** * 城市 */ private String cityName; /** * 区 */ private String districtName; /** * 镇 */ private String townName; /** * 发货人详细地址 */ private String sendAddress; /** * 发货人联系电话 */ private String sendPhone; /** * 发货人 */ private String sendName; /** * 发货人 邮编 */ private String receiverName; /** * 运费 */ private Long freight; /** * 订单总额 */ private Long totalOrder; /** * 更新时间 */ private Date updateTime; /** * 后台操作人ID */ private Integer backUserId; /** * 备注 */ private String remark; /** * 商品渠道价 */ private BigDecimal productAmount; /** * 商品销售价 */ private BigDecimal productPrice; /** * 订单类型 */ private Integer orderType; /** * 收货人姓名 */ private String userName; /** * 商品名称 */ private String productName; /** * 订单总金额 */ private BigDecimal orderAmount; /** * 创建时间 */ private Date createTime; /** * 实付款 */ private BigDecimal paidMoney; /** * 出价次数 */ private Integer bidTimes; }
package com.greenfox.exam.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Car { @Id @GeneratedValue(strategy = GenerationType.AUTO) long id; String plate; String carBrand; String carModel; int year; String color; public long getId() { return id; } public void setId( long id ) { this.id = id; } public String getPlate() { return plate; } public void setPlate( String plate ) { this.plate = plate; } public String getCarBrand() { return carBrand; } public void setCarBrand( String carBrand ) { this.carBrand = carBrand; } public String getCarModel() { return carModel; } public void setCarModel( String carModel ) { this.carModel = carModel; } public int getYear() { return year; } public void setYear( int year ) { this.year = year; } public String getColor() { return color; } public void setColor( String color ) { this.color = color; } public Car() { } public Car( String plate, String carBrand, String carModel, int year, String color ) { this.plate = plate; this.carBrand = carBrand; this.carModel = carModel; this.year = year; this.color = color; } }
import java.util.Scanner; public class main{ public static void main(String[]args){ Scanner l=new Scanner(System.in); escribiendo es=new escribiendo(); System.out.println("Dame tu nombre: "); es.setA(l.nextLine()); System.out.println("Dame tu numero de control: "); es.setB(l.nextLine()); es.escribir(); } }
package ru.steagle.views; import android.app.FragmentTransaction; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import ru.steagle.R; import ru.steagle.SteagleApplication; import ru.steagle.config.Config; import ru.steagle.config.Keys; import ru.steagle.utils.Utils; public class MainActivity extends ActionBarActivity implements MenuFragment.Listener, AccountFragment.Listener { private MenuFragment menuFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((SteagleApplication) getApplication()).bindSteagleService(); setContentView(R.layout.activity_main); menuFragment = new MenuFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.menuContainer, menuFragment); transaction.commit(); if (Config.isWifiOnly(this)&& Utils.detect3G(this)) { Utils.showConfirmDialog(this, getString(R.string.actung), getString(R.string.mobile_is_off), getString(R.string.btnTurnOn), getString(R.string.btnCancel), new Runnable() { @Override public void run() { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(MainActivity.this); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(Keys.USE_MOBILE_INET.getPrefKey(), true); editor.apply(); } }); } } @Override protected void onDestroy() { ((SteagleApplication) getApplication()).unBindSteagleService(); super.onDestroy(); } @Override public void onBackPressed() { if (!menuFragment.goHome()) { Utils.showConfirmDialog(this, null, getString(R.string.confirmExit), getString(R.string.btnYes), getString(R.string.btnCancel), new Runnable() { @Override public void run() { MainActivity.super.onBackPressed(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. //getMenuInflater().inflate(R.menu.main, menu); return false; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. // switch (item.getItemId()) { // case R.id.action_settings: // return true; // } return super.onOptionsItemSelected(item); } @Override public void onAccountClick() { AccountFragment accountFragment = new AccountFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.contentContainer, accountFragment); transaction.commit(); setTitle(getString(R.string.action_account)); } @Override public void onDevicesClick() { DevicesFragment devicesFragment = new DevicesFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.contentContainer, devicesFragment); transaction.commit(); setTitle(getString(R.string.action_devices)); } @Override public void onHistoryClick() { HistoryFragment historyFragment = new HistoryFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.contentContainer, historyFragment); transaction.commit(); setTitle(getString(R.string.action_history)); } @Override public void onSettingsClick() { SettingsFragment settingsFragment = new SettingsFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.contentContainer, settingsFragment); transaction.commit(); setTitle(getString(R.string.settings)); } @Override public void onNotificationsClick() { Intent intent = new Intent(this, NotificationsActivity.class); startActivity(intent); } @Override public void onBalanceClick() { Intent intent = new Intent(this, BalanceActivity.class); startActivity(intent); } @Override public void onPersonalInfoClick() { Intent intent = new Intent(this, PersonalActivity.class); startActivity(intent); } @Override public void onTimeZonesClick() { Intent intent = new Intent(this, TimeZoneActivity.class); startActivity(intent); } }
package com.oracle.iot.sample.mydriveapp.datalogger; public interface DataLoggerInterface { void setHeaders(Iterable<String> headers) throws IllegalStateException; void addRow(Iterable<String> values) throws IllegalStateException; void writeToFile(); }
package dao; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Properties; public class BoardDAO { private Connection conn; private ResultSet rs; private PreparedStatement psmt; String url = ""; String user = ""; String password = ""; String driver = ""; public BoardDAO() { InputStream input = this.getClass().getResourceAsStream("../../../db.properties"); Properties pro = new Properties(); try { pro.load(input); url = pro.getProperty("url"); user = pro.getProperty("id"); password = pro.getProperty("pw"); driver = pro.getProperty("driver"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private void getConnection() throws ClassNotFoundException, SQLException{ Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } public int boardWrite(String title, String content, String writer) { int state = 0; try { getConnection(); psmt = conn.prepareStatement("insert into bbs values(BOARD_NUM.NEXTVAL, ?, ?, ?, SYSDATE, 1)"); psmt.setString(1, title); psmt.setString(2, content); psmt.setString(3, writer); state = psmt.executeUpdate(); System.out.println(state); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return state; } public ArrayList<BoardDTO> getList(int pageNumber){ ArrayList<BoardDTO> list = new ArrayList<BoardDTO>(); int start = 1+(pageNumber-1)*10; int end = pageNumber*10; try{ getConnection(); psmt = conn.prepareStatement("SELECT * FROM (SELECT rownum rnum, bbs.* FROM bbs) bbs where rnum >= ? and rnum <= ? order by id desc"); psmt.setInt(1, start); psmt.setInt(2, end); rs = psmt.executeQuery(); while(rs.next()){ BoardDTO dto = new BoardDTO(); dto.setId(rs.getInt(2)); dto.setTitle(rs.getString(3)); dto.setContent(rs.getString(4)); dto.setWriter(rs.getString(5)); dto.setTime(rs.getString(6)); dto.setAvailable(rs.getInt(7)); list.add(dto); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } public int totalCount(){ int totalCount= 0; try{ getConnection(); psmt = conn.prepareStatement("select count(*) as totalCount from bbs"); rs = psmt.executeQuery(); if(rs.next()){ totalCount = rs.getInt(1); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return totalCount; } public BoardDTO getBoardView(int id){ BoardDTO dto = new BoardDTO(); try{ getConnection(); psmt = conn.prepareStatement("select *from bbs where id = ?"); psmt.setInt(1, id); rs = psmt.executeQuery(); if(rs.next()){ dto.setId(rs.getInt(1)); dto.setTitle(rs.getString(2)); dto.setContent(rs.getString(3)); dto.setWriter(rs.getString(4)); dto.setTime(rs.getString(5)); dto.setAvailable(rs.getInt(6)); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return dto; } public int boardUpdate(int id, String title, String content) { int state = 0; try{ getConnection(); psmt = conn.prepareStatement("update bbs set title = ?, content = ? where id = ?"); psmt.setString(1, title); psmt.setString(2, content); psmt.setInt(3, id); state = psmt.executeUpdate(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return state; } public int boardDelete(int id) { int state =0; try{ getConnection(); psmt = conn.prepareStatement("delete from bbs where id = ?"); psmt.setInt(1, id); state = psmt.executeUpdate(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return state; } }
import edu.princeton.cs.algs4.MinPQ; import java.util.LinkedList; public class Solver { private final boolean isSolvable; private final int moves; private final LinkedList<Board> solution; private class SearchNode implements Comparable<SearchNode> { private final Board board; private final SearchNode predecessor; private final int moves; private int priority; public SearchNode(Board board, SearchNode predecessor, int moves) { this.board = board; this.predecessor = predecessor; this.moves = moves; this.priority = -1; } @Override public int compareTo(SearchNode that) { // if (that == null) throw new IllegalArgumentException(); // if (this.priority() > that.priority()) return 1; // else if (this.priority() == that.priority()) // return Integer.compare(this.board.hamming(), that.board.hamming()); // else return -1; return Integer.compare(this.priority(), that.priority()); } private int priority() { if (priority == -1) { priority = board.manhattan() + moves; } return priority; } } public Solver(Board initial) { // find a solution to the initial board (using the A* algorithm) if (initial == null) { throw new IllegalArgumentException(); } MinPQ<SearchNode> original = new MinPQ<SearchNode>(); original.insert(new SearchNode(initial, null, 0)); MinPQ<SearchNode> twin = new MinPQ<SearchNode>(); twin.insert(new SearchNode(initial.twin(), null, 0)); SearchNode lastSearchNode; while (true) { lastSearchNode = aStarStep(original); if (lastSearchNode != null) { isSolvable = true; solution = new LinkedList<>(); moves = lastSearchNode.moves; do { solution.addFirst(lastSearchNode.board); lastSearchNode = lastSearchNode.predecessor; } while (lastSearchNode != null); break; } lastSearchNode = aStarStep(twin); if (lastSearchNode != null) { isSolvable = false; moves = -1; solution = null; break; } } } private SearchNode aStarStep(MinPQ<SearchNode> pq) { SearchNode current = pq.delMin(); if (current.board.isGoal()) { return current; } Board predecessorBoard = current.predecessor == null ? null : current.predecessor.board; for (Board neighbor : current.board.neighbors()) { if (!neighbor.equals(predecessorBoard)) { pq.insert(new SearchNode(neighbor, current, current.moves + 1)); } } return null; } public boolean isSolvable() { // is the initial board solvable? return isSolvable; } public int moves() { // min number of moves to solve initial board; -1 if unsolvable return moves; } public Iterable<Board> solution() { // sequence of boards in a shortest solution; null if unsolvable return solution; } public static void main(String[] args) { Solver s = new Solver(new Board(new int[][] { { 0, 1, 3 }, { 4, 2, 5 }, { 7, 8, 6 } })); for (Board b : s.solution()) { System.out.println(b); } } }
package com.sun.xml.bind.v2.runtime.unmarshaller; import com.sun.xml.bind.api.AccessorException; import com.sun.xml.bind.v2.runtime.Transducer; import org.xml.sax.SAXException; /** * Unmarshals a text into an object. * * <p> * If the caller can use {@link LeafPropertyLoader}, that's usually faster. * * @see LeafPropertyLoader * @see ValuePropertyLoader * @author Kohsuke Kawaguchi */ public class TextLoader extends Loader { private final Transducer xducer; public TextLoader(Transducer xducer) { super(true); this.xducer = xducer; } public void text(UnmarshallingContext.State state, CharSequence text) throws SAXException { try { state.target = xducer.parse(text); } catch (AccessorException e) { handleGenericException(e,true); } catch (RuntimeException e) { handleParseConversionException(state,e); } } }
package cz.utb.fai.translator.adapter; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import cz.utb.fai.translator.R; public class ViewPagerAdapter extends PagerAdapter { private Context mContext; public ViewPagerAdapter(Context context) { this.mContext = context; } @Override public Object instantiateItem(ViewGroup collection, int position) { int resId; // set PAGE HOME as default if (position == 0) { resId = R.id.page_home; } else if (position == 1) { resId = R.id.page_history; } else { resId = R.id.page_dictionary; } return collection.findViewById(resId); } @Override public void destroyItem(ViewGroup container, int position, Object object) { } @Override // obarveni aktivniho okna public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public int getCount() { return 3; } @Override //getPageTitle meni nazev aktualne vybrane zalozky public CharSequence getPageTitle(int position) { if (position == 0) { return mContext.getResources().getString(R.string.home); } else if (position == 1) { return mContext.getResources().getString(R.string.history); } else if (position == 2) { return mContext.getResources().getString(R.string.dictionary); } return super.getPageTitle(position); } }
package Arrays; import java.lang.reflect.Array; /** * Created by student on 03-May-16. */ public class Array1 { public static void main(String[] args) { int[] numbers = {1,2,3,4,5,6}; int[][] TwoArray = {{4,2,3},{1,5,4}}; Reminder(); Bigdiff(); System.out.println(CheckArrayLengh(numbers)); System.out.println(FirstLast6(numbers)); System.out.println(CoomonEnd(TwoArray)); SetValue(); } static boolean FirstLast6(int[] Num) { return (Num[0] == 6 || Num[Num.length - 1] == 6 ); } static boolean SameFirstLast(int[] Num) { return ((Num.length >= 1) && (Num[0] == Num[Num.length - 1])); } static boolean CoomonEnd(int[][] TwoArray) { return (TwoArray[0][0] == TwoArray[1][0] || TwoArray[TwoArray.length - 1][TwoArray.length - 1] == TwoArray[0][TwoArray.length - 1]); } static void SetValue() { int[] SetValue = {1,4,3}; int maxValue = 0; for(int i=0 ; i<= SetValue.length - 2 ; i++) { if (SetValue[i] > SetValue[i + 1]) { maxValue = SetValue[i]; } else { maxValue = SetValue[i + 1]; } } SetValue[0] = maxValue; SetValue[1] = maxValue; SetValue[2] = maxValue; for(int i = 0 ; i< SetValue.length; i++) { System.out.println(SetValue[i]); } } static boolean CheckArrayLengh(int[] Num) { for(int i=0;i<= Num.length ; i++) { if ((Num[i] == 2) || (Num[i] == 3)) { return true; } else { return false; } } return false; } static void Reminder() { int[] Num = {6,4,8}; int j = 0,k = 0; for(int i=0;i<= Num.length - 1 ; i++) { j = (Num[i] % 2); { if(j == 0) { k++; } } } System.out.println(k); } static void Bigdiff() { int[] SetValue = {10,3,5,6}; int minValue = 0,maxValue = 0; for(int i=0 ; i<= SetValue.length - 2 ; i++) { if (SetValue[i] > SetValue[i + 1]) { maxValue = SetValue[i]; } else { minValue = SetValue[i]; } } System.out.println(maxValue + minValue); } }
package com.roundarch.codetest.part2; import android.content.Intent; import android.os.Bundle; import android.os.Parcel; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.TextView; import com.roundarch.codetest.R; public class Part2Fragment extends Fragment { private static String EXTRA_MODEL = "extra_model"; private DataModel mModel = new DataModel(); private TextView textView1; private TextView textView3; private TextView textView2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_part2, null); // TODO - view.findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onClick_edit(); } }); textView1 = (TextView)view.findViewById(R.id.textView1); textView2 = (TextView)view.findViewById(R.id.textView2); textView3 = (TextView)view.findViewById(R.id.textView3); if (savedInstanceState != null) { if (savedInstanceState.containsKey(EXTRA_MODEL)) { mModel = (DataModel) savedInstanceState.get(EXTRA_MODEL); } } setTextViews(); return view; } @Override public void onSaveInstanceState(Bundle outState) { outState.putSerializable(EXTRA_MODEL, mModel); super.onSaveInstanceState(outState); } public void onClick_edit() { // TODO - package up the data model and provide it to the new EditActivity as it is being created Intent intent = new Intent(this.getActivity(), EditActivity.class); mModel.setText1(textView1.getText().toString()); mModel.setText2(textView2.getText().toString()); mModel.setText3(Double.valueOf(textView3.getText().toString())); intent.putExtra("data", mModel); // TODO - this probably isn't the best way to start the EditActivty, try to fix it //startActivity(intent); startActivityForResult(intent, 1); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Bundle bundle = data.getExtras(); DataModel newData = (DataModel) bundle.get("newData"); textView1.setText(newData.getText1()); textView2.setText(newData.getText2()); textView3.setText(String.valueOf(newData.getText3())); } // TODO - provide a method to obtain the data model when it is returned from the EditActivity private void setTextViews() { textView1.setText(mModel.getText1()); textView2.setText(mModel.getText2()); textView3.setText(String.valueOf(mModel.getText3())); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.client; import java.io.IOException; import java.util.Iterator; import org.springframework.http.client.ClientHttpRequest; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Simple {@code RequestExpectationManager} that matches requests to expectations * sequentially, i.e. in the order of declaration of expectations. * * <p>When request expectations have an expected count greater than one, * only the first execution is expected to match the order of declaration. * Subsequent request executions may be inserted anywhere thereafter. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 4.3 */ public class SimpleRequestExpectationManager extends AbstractRequestExpectationManager { /** Expectations in the order of declaration (count may be > 1). */ @Nullable private Iterator<RequestExpectation> expectationIterator; /** Track expectations that have a remaining count. */ private final RequestExpectationGroup repeatExpectations = new RequestExpectationGroup(); @Override protected void afterExpectationsDeclared() { Assert.state(this.expectationIterator == null, "Expectations already declared"); this.expectationIterator = getExpectations().iterator(); } @Override protected RequestExpectation matchRequest(ClientHttpRequest request) throws IOException { RequestExpectation expectation = this.repeatExpectations.findExpectation(request); if (expectation == null) { if (this.expectationIterator == null || !this.expectationIterator.hasNext()) { throw createUnexpectedRequestError(request); } expectation = this.expectationIterator.next(); expectation.match(request); } this.repeatExpectations.update(expectation); return expectation; } @Override public void reset() { super.reset(); this.expectationIterator = null; this.repeatExpectations.reset(); } }
package com.github.niwaniwa.whitebird.core.command; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.github.niwaniwa.whitebird.core.util.Util; public class PingCommand implements BaseCommand { @Override public boolean runCommand(CommandSender sender, Command command, String[] args) { if(!(sender instanceof Player)){ sender.sendMessage(pre+"ゲーム内から実行してください"); return true; } Integer ping = Util.getPing((Player) sender); if(ping==null){ sender.sendMessage("§e現在利用できません"); } sender.sendMessage("ping : "+ping); return false; } }
package dao; // Generated 25 janv. 2017 00:17:46 by Hibernate Tools 4.3.1 import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Client generated by hbm2java */ public class Client implements java.io.Serializable { private Integer idClient; private String nom; private String prenom; private Date dateNaissance; private Set<Reservation> reservations = new HashSet<Reservation>(0); private Set<Utilise> utilises = new HashSet<Utilise>(0); public Client() { } public Client(String nom, String prenom) { this.nom = nom; this.prenom = prenom; } public Client(String nom, String prenom, Date dateNaissance, Set<Reservation> reservations, Set<Utilise> utilises) { this.nom = nom; this.prenom = prenom; this.dateNaissance = dateNaissance; this.reservations = reservations; this.utilises = utilises; } public Integer getIdClient() { return this.idClient; } public void setIdClient(Integer idClient) { this.idClient = idClient; } public String getNom() { return this.nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return this.prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public Date getDateNaissance() { return this.dateNaissance; } public void setDateNaissance(Date dateNaissance) { this.dateNaissance = dateNaissance; } public Set<Reservation> getReservations() { return this.reservations; } public void setReservations(Set<Reservation> reservations) { this.reservations = reservations; } public Set<Utilise> getUtilises() { return this.utilises; } public void setUtilises(Set<Utilise> utilises) { this.utilises = utilises; } }
/* Copyright (C) 2013-2014, Securifera, Inc All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Securifera, Inc nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Pwnbrew is provided under the 3-clause BSD license above. The copyright on this package is held by Securifera, Inc */ /* * FileUtilities.java * * Created on June 2, 2013, 11:59 AM */ package pwnbrew.utilities; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** */ abstract public class FileUtilities { // ========================================================================== /** * Returns the os temp dir * <p> * * @return a {@link File} representing the os temp dir * @throws java.io.IOException */ public static File getTempDir() throws IOException { File aFile = File.createTempFile("ttf", null); File rtnFile = aFile.getParentFile(); aFile.delete(); return rtnFile; } // ========================================================================== /** * Returns the SHA-256 hash for the passed file * * @param aFile * * @return a {@code String} representing the hash of the file * * @throws FileNotFoundException if the given {@code File} represents a directory, * or represents a file that doesn't exist or cannot be read by the application * @throws IOException if a problem occurs while reading the file * @throws NoSuchAlgorithmException if the hash algorithm cannot be found */ public static String getFileHash(File aFile ) throws NoSuchAlgorithmException, IOException { int bytesRead = 0; byte[] byteBuffer = new byte[Constants.GENERIC_BUFFER_SIZE]; String theHash = ""; if( aFile.exists() && aFile.canRead() ) { //If the file can be read... MessageDigest hash = MessageDigest.getInstance(Constants.HASH_FUNCTION); FileInputStream theFileStream = new FileInputStream(aFile); BufferedInputStream theBufferedIS = new BufferedInputStream(theFileStream); try { //Read in the bytes and update the hash while( bytesRead != -1){ bytesRead = theBufferedIS.read(byteBuffer); if(bytesRead > 0) hash.update(byteBuffer, 0, bytesRead); } byte[] byteHash = hash.digest(); theHash = Utilities.byteToHexString(byteHash); } finally { //Ensure the file is closed try { theBufferedIS.close(); } catch(IOException ex){ ex = null; } } } else { //If the file doesn't exist or is not actually a file... throw new FileNotFoundException(); } return theHash; } }/* END CLASS FileUtilities */
package by.academy.homework.homework2; import java.util.Scanner; public class Task1 { public static void main(String[] args) { System.out.println("Введите 2 слова: "); Scanner str = new Scanner(System.in); String[] array = new String[2]; for (int i = 0; i < 2; i++) { array[i] = str.nextLine(); } str.close(); boolean result = true; int[] symbols = new int[256]; if (array[0].length() == array[1].length()) { for (int i = 0; i < array[0].length(); i++) { int sym = (int) array[0].charAt(i); symbols[sym]++; } for (int i = 0; i < array[1].length(); i++) { int sym = (int) array[1].charAt(i); if (symbols[sym] - 1 != 0) { result = false; } } } else { result = false; } System.out.println("Результат: " + result); } }
package bcg.common.service; import java.util.List; import bcg.common.entity.CompareBook; public interface SearchService { public List<CompareBook> searchService(String title); }
package com.lfalch.korome; import static org.lwjgl.opengl.GL11.GL_QUADS; import static org.lwjgl.opengl.GL11.glBegin; import static org.lwjgl.opengl.GL11.glEnd; import static org.lwjgl.opengl.GL11.glTexCoord2d; import static org.lwjgl.opengl.GL11.glVertex2d; import java.io.IOException; //Don't touch it, it just... works :D public class Chars { private static final int width = 16, height = 16; public static void drawString(String s, double x, double y) throws IOException{ int add = 0; for(char c: s.toCharArray()){ drawID(x+add, y, getID(c)); add += 15; } } private static int getID(char c){ return c; } private static void drawID(double x, double y, int id) throws IOException{ int iTexX = id % 16; int iTexY = (id - iTexX) / 16; float one16th = 1.0f/16.0f; float texX = iTexX * one16th; float texY = iTexY * one16th; Texture chars = Draw.getTexture("chrs"); chars.bind(); glBegin(GL_QUADS); glTexCoord2d(texX, texY); glVertex2d(x, y); glTexCoord2d(texX + one16th, texY); glVertex2d(x+width, y); glTexCoord2d(texX + one16th, texY+one16th); glVertex2d(x+width, y+height); glTexCoord2d(texX, texY+one16th); glVertex2d(x, y+height); glEnd(); Texture.unbind(); Colour.WHITE.glSet(); } }
package cap.abstractinterface; interface Inf1 { void get(); } class ABC implements Inf1 { public void get() { System.out.println("get of ABC"); } } public class InterfaceDemo { public static void main(String[] args) { ABC a1=new ABC(); a1.get(); //Second Way Inf1 i1=new ABC(); //Upcasting i1.get(); } }
package day13constructors; public class Dog { public String name; public int weight; public int height; /* - I created a constructor - The constructor has no any parameter - The constructor has nothing inside the body - That kind of constructors are same with the default constructor - Note: If you create a constructor Java deletes the "Default one" */ public Dog() { } public Dog(String name) { this.name = name; } public Dog(int weight, int height) { } public Dog(String name, int weight, int height) { this.name = name; this.weight = weight; this.height = height; } public static void main(String[] args) { Dog dog1 = new Dog("Joe"); System.out.println(dog1.name); //Create a dog by using name, weight nad height Dog dog2 = new Dog("Jorge", 32, 12); System.out.println(dog2.name); System.out.println(dog2.weight); System.out.println(dog2.height); } public static void sound() { System.out.println("Dogs bark..."); } }
package com.kotensky.testsk.activity.login.model; import com.kotensky.testsk.activity.login.model.data.User; import rx.Observable; /** * Created by Stas on 09.02.2017. */ public interface IModelLogin { Observable<User> getUser(String basic); }
package com.BDD.blue_whale.service; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.BDD.blue_whale.entities.Source; import com.BDD.blue_whale.repositories.SourceRepository; @Service @Transactional public class SourceServiceImpl implements SourceService{ @Autowired private SourceRepository SourceRepository; @Override public void addSource(Source source) { SourceRepository.save(source); } @Override public List<Source> listSource() { return SourceRepository.findAll(); } @Override public Optional<Source> getSourceById(long source_id) { return SourceRepository.findById(source_id); } @Override public void deleteSource(long source_id) { SourceRepository.deleteById(source_id); } @Override public void updateSource(Source source) { SourceRepository.save(source); } }
package com.softeem.dao; import java.util.List; import com.softeem.bean.GoodsBean; public interface IGoodsDao { // 首页 : 1-12 List<GoodsBean> selectIndexGoods(int begin,int end); // 分类查询(分页查询) List<GoodsBean> selectByCate(int cateId); List<GoodsBean> selectByPageAndCate(int pageNum,int pageSize,int cateId); // 商品详情 : 单个商品 GoodsBean selectById(int goodsId); //获取总页数 int selectTotalPage(int cateId,int pageSize); }
import java.util.Scanner; class Marks { public static void main(String args[]) { int a[]=new int[10]; int high=0; int fail=0; int pass=0; int sum=0; float avg=0; Scanner s=new Scanner(System.in); System.out.println("Enter the marks of ten students"); for(int i=0;i<10;i++) { a[i]=s.nextInt(); } int low=a[1]; for(int j=0;j<10;j++) { if(a[j]>high) high=a[j]; if(a[j]<low) low=a[j]; if(a[j]<40) fail=fail+1; else pass=pass+1; sum=sum+a[j]; avg=sum/10; } System.out.println("Highest mark:"+high); System.out.println("Lowest mark:"+low); System.out.println("No.of students passed:"+pass); System.out.println("No. students failed:"+fail); System.out.println("Average marks:"+avg); } }
package com.niksoftware.snapseed.core; import android.graphics.Bitmap; import com.niksoftware.snapseed.core.filterparameters.FilterParameter; public class FilterChainNode { private final FilterParameter filterParameter; private Bitmap previewLayer = null; public FilterChainNode(FilterParameter filterParameter) { this.filterParameter = filterParameter; } public FilterParameter getFilterParameter() { return this.filterParameter; } public Bitmap getPreviewLayer() { return this.previewLayer; } }
package com.cmi.bache24.data.remote.interfaces; import com.cmi.bache24.data.model.Report; import java.util.List; /** * Created by omar on 12/12/15. */ public interface ReportsCallback extends CallbackBase { void onReportsCallback(List<Report> reports); void onReportsFail(String message); }
package com.game.cwtetris.ui; import android.graphics.Color; import android.view.MotionEvent; import android.view.View; import com.game.cwtetris.CanvasView; /** * Created by gena on 12/15/2016. */ public abstract class UIElement implements View.OnTouchListener { protected int x; protected int y; protected int width; protected int height; private boolean visible = true; private boolean touched = false; public boolean isTouched() { return touched; } public void setTouched(boolean touched) { this.touched = touched; } public boolean isSelected(float eventX, float eventY){ if (eventX >= (x - width/2) && (eventX <= (x + width/2))) { if (eventY >= (y - height/2) && (eventY <= (y + height/2))) { return true; } } return false; } public abstract void draw(CanvasView view); @Override public boolean onTouch(View v, MotionEvent event) { if (isVisible() == false) { return false; } boolean isSelected = isSelected( event.getX(), event.getY() ); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: setTouched(isSelected); break; case MotionEvent.ACTION_UP: boolean result = isSelected && isTouched(); setTouched(false); return result; } return false; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.config.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.Import; /** * Add this annotation to an {@code @Configuration} class to configure * processing WebSocket requests. A typical configuration would look like this: * * <pre class="code"> * &#064;Configuration * &#064;EnableWebSocket * public class MyWebSocketConfig { * * } * </pre> * * <p>Customize the imported configuration by implementing the * {@link WebSocketConfigurer} interface: * * <pre class="code"> * &#064;Configuration * &#064;EnableWebSocket * public class MyConfiguration implements WebSocketConfigurer { * * &#064;Override * public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { * registry.addHandler(echoWebSocketHandler(), "/echo").withSockJS(); * } * * &#064;Bean * public WebSocketHandler echoWebSocketHandler() { * return new EchoWebSocketHandler(); * } * } * </pre> * * @author Rossen Stoyanchev * @since 4.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(DelegatingWebSocketConfiguration.class) public @interface EnableWebSocket { }
package com.ipincloud.iotbj.srv.domain; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Time; import java.sql.Date; import java.sql.Timestamp; import com.alibaba.fastjson.annotation.JSONField; //(Baseman)基站管理 //generate by redcloud,2020-07-24 19:59:20 public class Baseman implements Serializable { private static final long serialVersionUID = 12L; // 自增ID private Long id ; // 名称 private String title ; // 类型 private String type ; // 区域 private String area ; // 厂商 private String factory ; // 最近在线时间 private Long recenttime ; // 状态 private String state ; // IP地址 private String ipaddress ; // 位置图片 private String url ; public Long getId() { return id ; } public void setId(Long id) { this.id = id; } public String getTitle() { return title ; } public void setTitle(String title) { this.title = title; } public String getType() { return type ; } public void setType(String type) { this.type = type; } public String getArea() { return area ; } public void setArea(String area) { this.area = area; } public String getFactory() { return factory ; } public void setFactory(String factory) { this.factory = factory; } public Long getRecenttime() { return recenttime ; } public void setRecenttime(Long recenttime) { this.recenttime = recenttime; } public String getState() { return state ; } public void setState(String state) { this.state = state; } public String getIpaddress() { return ipaddress ; } public void setIpaddress(String ipaddress) { this.ipaddress = ipaddress; } public String getUrl() { return url ; } public void setUrl(String url) { this.url = url; } }
package modelo; /** * * @author Cristobal Torres * @version junio 2019 * Clase Idioma que define los valores del mantenedor Idioma para posterior constructor * @param idIdioma identificador de id idioma * @param idioma variable de tipo string para definir idioma de libros * @param traductor variable string para traductor de idioma */ public class Idioma { int idIdioma; String idioma; String traductor; public Idioma() { } /** * * Constructor Idioma para Realizar Get and Setter */ public Idioma(int idIdioma, String idioma, String traductor) { this.idIdioma = idIdioma; this.idioma = idioma; this.traductor = traductor; } public int getIdIdioma() { return idIdioma; } public void setIdIdioma(int idIdioma) { this.idIdioma = idIdioma; } public String getIdioma() { return idioma; } public void setIdioma(String idioma) { this.idioma = idioma; } public String getTraductor() { return traductor; } public void setTraductor(String traductor) { this.traductor = traductor; } }
package org.huangfugui.ibatis.po; /** * @author zqb * @decription * @create 2017/7/7 */ public class Picture { int id; String path; int mCount; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getmCount() { return mCount; } public void setmCount(int mCount) { this.mCount = mCount; } @Override public String toString() { return "Picture{" + "id=" + id + ", path='" + path + '\'' + ", mCount=" + mCount + '}'; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.function; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.core.io.Resource; import org.springframework.lang.Nullable; /** * @author Arjen Poutsma */ class AttributesTestVisitor implements RouterFunctions.Visitor { private Deque<Map<String, Object>> nestedAttributes = new LinkedList<>(); @Nullable private Map<String, Object> attributes; private List<List<Map<String, Object>>> routerFunctionsAttributes = new LinkedList<>(); private int visitCount; public List<List<Map<String, Object>>> routerFunctionsAttributes() { return this.routerFunctionsAttributes; } public int visitCount() { return this.visitCount; } @Override public void startNested(RequestPredicate predicate) { nestedAttributes.addFirst(attributes); attributes = null; } @Override public void endNested(RequestPredicate predicate) { attributes = nestedAttributes.removeFirst(); } @Override public void route(RequestPredicate predicate, HandlerFunction<?> handlerFunction) { Stream<Map<String, Object>> current = Optional.ofNullable(attributes).stream(); Stream<Map<String, Object>> nested = nestedAttributes.stream().filter(Objects::nonNull); routerFunctionsAttributes.add(Stream.concat(current, nested).collect(Collectors.toUnmodifiableList())); attributes = null; } @Override public void resources(Function<ServerRequest, Optional<Resource>> lookupFunction) { } @Override public void attributes(Map<String, Object> attributes) { this.attributes = attributes; this.visitCount++; } @Override public void unknown(RouterFunction<?> routerFunction) { } }
package io.github.satr.aws.lambda.bookstore; // Copyright © 2020, github.com/satr, MIT License import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.util.Map; //Lambda with JSON as a respond public class BookStoreLexLambdaWithJsonResponse implements RequestHandler<Map<String, Object>, Object> { @Override public Object handleRequest(Map<String, Object> input, Context context) { LambdaLogger logger = context.getLogger(); logger.log(input.toString());//Just to show the input in the CloudWatch log //Read input String userId = (String) input.get("userId"); Map<String, Object> bot = (Map<String, Object>) input.get("bot"); Object botName = bot.get("name"); Map<String, Object> currentIntent = (Map<String, Object>) input.get("currentIntent"); String intentName = (String) currentIntent.get("name"); Map<String, Object> slots = (Map<String, Object>) currentIntent.get("slots"); Map<String, Object> sessionAttributes = (Map<String, Object>) input.get("sessionAttributes"); //Log input properties logger.log("UserId:" + userId); logger.log("Bot name:" + botName); logger.log("Current intent name:" + intentName); logger.log(slots.keySet().isEmpty() ? "No Slots" : "Slots:"); for (String slotName : slots.keySet()) logger.log(" - " + slotName + ":" + slots.get(slotName)); logger.log(sessionAttributes.keySet().isEmpty() ? "No Session Attributes" : "Session Attributes:"); for (String attr : sessionAttributes.keySet()) logger.log(" - " + attr + ":" + sessionAttributes.get(attr)); //Perform some action String respondMessage = intentName.equals("OrderBookIntent") ? String.format("Ordered a book \"%s\" by \"%s\"", slots.get("BookName"), slots.get("AuthorLastName")) : String.format("Received Intent: %s", intentName); //Prepare respond ObjectMapper mapper = new ObjectMapper(); ObjectNode responseNode = mapper.createObjectNode(); ObjectNode dialogActionNode = mapper.createObjectNode(); dialogActionNode.put("type", "Close"); dialogActionNode.put("fulfillmentState", "Fulfilled"); responseNode.set("dialogAction", dialogActionNode); ObjectNode messageNode = mapper.createObjectNode(); messageNode.put("contentType", "PlainText"); messageNode.put("content", respondMessage); dialogActionNode.set("message", messageNode); try { return mapper.readValue(responseNode.toString(), new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { e.printStackTrace(); return null; } } }
package com.lzx.xiuxian.activity; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import com.lzx.xiuxian.Dao.UserDao; import com.lzx.xiuxian.R; import com.lzx.xiuxian.Vo.User; import java.util.Date; public class RegisterActivity extends Activity { private String TAG = "re001"; EditText ivUserName1; EditText ivPhone; EditText ivPassword1; EditText ivPassword2; String username,password,passwordVa,phone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_register); ivPhone = (EditText)findViewById(R.id.iv_userName2); ivUserName1 = (EditText)findViewById(R.id.iv_userName1); ivPassword1 = (EditText)findViewById(R.id.iv_password1); ivPassword2 = (EditText)findViewById(R.id.iv_password2); try{ Button register = (Button)findViewById(R.id.btn_register1); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG,"!!!"); phone = ivPhone.getText().toString(); username = ivUserName1.getText().toString(); password = ivPassword1.getText().toString(); passwordVa = ivPassword2.getText().toString(); final String str = validateForm(username,phone,password,passwordVa); if(!str.equals("正确")){ runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder dialog1 = new AlertDialog.Builder(RegisterActivity.this); dialog1.setTitle("提示") .setMessage(str) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog1.show(); } }); return ; } new Thread() { public void run() { Log.d(TAG,"1"); if (new UserDao().isExist(phone)) { runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG,"2"); AlertDialog.Builder dialog2 = new AlertDialog.Builder(RegisterActivity.this); dialog2.setTitle("提示") .setMessage("账号已注册") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog2.show(); } }); }else{ User user = new User(); user.setName(username); user.setPhone(phone); user.setPsw(password); new UserDao().addUser(user); runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder dialog1 = new AlertDialog.Builder(RegisterActivity.this); dialog1.setTitle("提示") .setMessage("注册成功") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); dialog1.show(); } }); } } ; }.start(); } }); }catch (Exception e){ Log.d(TAG,e.toString()); } } public String validateForm(String username, String phone,String password, String passwordVa) { if ((!TextUtils.isEmpty(phone)) &&(!TextUtils.isEmpty(username)) && (!TextUtils.isEmpty(password)) && (!TextUtils.isEmpty(passwordVa))) { if (password.equals(passwordVa)) return "正确"; return "两次密码填写不同"; } return "请完整填写表单"; } }
package com.fanoi.dream.module.apps.adapter; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.fanoi.dream.R; /** * Created by Administrator on 2016/4/5 0005. */ public class MoreItemViewHolder extends RecyclerView.ViewHolder { public MoreItemViewHolder(View itemView) { super(itemView); assignViews(); } private View findViewById(final int id) { return itemView.findViewById(id); } /** * viewHolder position */ private int position; /** * download id */ private String id; public void update(final String id, final int position) { this.id = id; this.position = position; } public TextView item_fragment_more_title; public TextView item_fragment_more_content; public ProgressBar item_fragment_more_pb; public Button item_fragment_more_mission; public Button item_fragment_more_cancel; public ImageView item_fragment_more_imageView; private void assignViews() { item_fragment_more_imageView =(ImageView)findViewById(R.id.item_fragment_more_imageView); item_fragment_more_title = (TextView) findViewById(R.id.item_fragment_more_title); item_fragment_more_content = (TextView) findViewById(R.id.item_fragment_more_content); item_fragment_more_pb = (ProgressBar) findViewById(R.id.item_fragment_more_pb); item_fragment_more_mission = (Button) findViewById(R.id.item_fragment_more_mission); item_fragment_more_cancel = (Button) findViewById(R.id.item_fragment_more_cancel); } }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; public class ExtraFrame extends JFrame{ /** * */ private static final long serialVersionUID = 1L; //DB Connection conn = null; PreparedStatement state = null; //Up and Down Panel JPanel downPanel = new JPanel(); JPanel upPanel = new JPanel(); //-------Всичко за горния панел------------ //СЪОБЩЕНИЯ JPanel warningPanel = new JPanel(); JLabel labelWarning = new JLabel("Съобщенията ще излизат тук"); //Справка 1: всички книги на автора по Име JLabel descrLabel1 = new JLabel("Име на автора"); JPanel spravka1Panel = new JPanel(); JTextField authorNameTF=new JTextField(); JButton searchButton1=new JButton("Покажи книги"); //Справка 2: всички книги, които е купувал клиент по Клиентски номер JLabel descrLabel2=new JLabel("№ на клиент"); JPanel spravka2Panel = new JPanel(); JTextField clientNumTF = new JTextField(); JButton searchButton2=new JButton("Покажи книги"); //Смесено търсене JButton searchExtraButton = new JButton("Смесено търсене"); //------------Всичко за долния панел------------- JTable table = new JTable(); JScrollPane scroller = new JScrollPane(table); public ExtraFrame() { this.setTitle("Допълнителни справки"); this.setVisible(true); this.setLayout(null); this.setSize(600, 178); this.setResizable(false); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width-this.getSize().width, 0); //---------------------------------- Горен панел --------------------- this.add(upPanel); upPanel.setLocation(0,0); upPanel.setSize(600,150); upPanel.setVisible(true); upPanel.setLayout(new GridLayout(6,1)); //Съобщения upPanel.add(warningPanel); warningPanel.add(labelWarning); warningPanel.setBackground(new Color(89, 89, 89)); warningPanel.setBorder(BorderFactory.createLoweredBevelBorder()); labelWarning.setForeground(new Color(215, 248, 215)); //Справка 1: всички книги на автора по Име upPanel.add(descrLabel1); upPanel.add(spravka1Panel); spravka1Panel.setLayout(new GridLayout(1,2)); spravka1Panel.add(authorNameTF); spravka1Panel.add(searchButton1); searchButton1.addActionListener(new SearchAction1()); //Справка 2: всички книги, които е купувал клиент по Клиентски номер upPanel.add(descrLabel2); upPanel.add(spravka2Panel); spravka2Panel.setLayout(new GridLayout(1,2)); spravka2Panel.add(clientNumTF); spravka2Panel.add(searchButton2); searchButton2.addActionListener(new SearchAction2()); //Справка 3: upPanel.add(searchExtraButton); searchExtraButton.addActionListener(new BonusSearchAction()); //---------------------------- Долен панел --------------------- this.add(downPanel); downPanel.setLocation(0,150); downPanel.setSize(596,340); downPanel.setLayout(new BorderLayout()); downPanel.add(scroller); //table.setModel(DBUtil.getAllModelAuthors()); } private class BonusSearchAction implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { if(clientNumTF.getText().isEmpty() || authorNameTF.getText().isEmpty()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Моля попълнете и двете полета!</html>"); return; } String clientNumber = clientNumTF.getText(); int number; try { number = Integer.parseInt(clientNumber); } catch (NumberFormatException nfe) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Моля въведете клиентски номер!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); return; } if(number<5000) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Клиентските номера започват от 5000!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); return; } conn = DBUtil.getConnected(); if(conn == null) { WarnNoConnection(); return; } String sql ="select client_number from orders where client_number="+number+";"; ResultSet rs=null; try { state = conn.prepareStatement(sql); rs = state.executeQuery(); if(!rs.next()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Клиент "+number+" няма поръчки!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); CloseConn(); return; } //да видя дали този автор въобще съществува при книгите String name = authorNameTF.getText(); sql ="select b.book_number from books b join authors a on b.author_number = a.author_number WHERE a.name like ?;"; state = conn.prepareStatement(sql); state.setString(1, name); rs = state.executeQuery(); if(!rs.next()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Няма книга от автор "+name+"</html>"); authorNameTF.selectAll(); authorNameTF.requestFocusInWindow(); CloseConn(); return; } sql = "select b.book_number, title, isbn, count, price from books b join orders o on b.book_number=o.book_number join authors a on b.author_number = a.author_number where o.client_number="+number+" and b.author_number=select author_number from authors where name like '"+name+"';"; state = conn.prepareStatement(sql); rs = state.executeQuery(); if(!rs.next()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Няма книга от автор "+name+", която да е закупена от клиент с номер "+number+"</html>"); CloseConn(); return; } table.setModel(DBUtil.getModelExtra(name, number)); labelWarning.setForeground(Color.GREEN); labelWarning.setText("<html>Има книга/и от автор "+name+", която/ито да е/са закупена/и от клиент с номер "+number+"</html>"); } catch (SQLException e1) { WarnNotDone(); e1.printStackTrace(); } CloseConn(); setSize(600, 500); } } private class SearchAction2 implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String clientNumber = clientNumTF.getText(); int number; try { number = Integer.parseInt(clientNumber); } catch (NumberFormatException nfe) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Моля въведете клиентски номер!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); return; } if(number<5000) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Клиентските номера започват от 5000!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); return; } conn = DBUtil.getConnected(); if(conn == null) { WarnNoConnection(); return; } String sql ="select client_number from orders where client_number="+number+";"; ResultSet rs=null; try { state = conn.prepareStatement(sql); rs = state.executeQuery(); if(!rs.next()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Клиент "+number+" няма поръчки!</html>"); clientNumTF.selectAll(); clientNumTF.requestFocusInWindow(); CloseConn(); return; } table.setModel(DBUtil.getModelExtra2(number)); sql = "select sum(o.quantity), sum(b.price*o.quantity) from books b join orders o on b.book_number=o.book_number where o.client_number="+number+";"; state = conn.prepareStatement(sql); rs = state.executeQuery(); int count=0; float totalPrice=0; if(rs.next()) { count=rs.getInt(1); totalPrice=rs.getFloat(2); } labelWarning.setForeground(Color.GREEN); labelWarning.setText("<html>Този клиент е закупил "+count+" книги на обща стойност "+totalPrice+"</html>"); clientNumTF.setText(null); } catch (SQLException e1) { WarnNotDone(); e1.printStackTrace(); } CloseConn(); setSize(600, 500); } } private class SearchAction1 implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { if(authorNameTF.getText().isEmpty()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Не сте въвели име на автор!</html>"); authorNameTF.selectAll(); authorNameTF.requestFocusInWindow(); return; } conn = DBUtil.getConnected(); if(conn == null) { WarnNoConnection(); return; } String name = authorNameTF.getText(); String sql ="select author_number from authors where name like ?;"; ResultSet rs=null; int authorNumber=0; try { state = conn.prepareStatement(sql); state.setString(1, name); rs = state.executeQuery(); if(!rs.next()) { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Не съществува автор с това име!</html>"); authorNameTF.selectAll(); authorNameTF.requestFocusInWindow(); CloseConn(); return; } authorNumber=rs.getInt(1); table.setModel(DBUtil.getModelExtra1(authorNumber)); sql ="select count(book_id) from books where author_number = "+authorNumber+";"; state = conn.prepareStatement(sql); rs = state.executeQuery(); int count=0; if(rs.next()) count=rs.getInt(1); labelWarning.setForeground(Color.GREEN); labelWarning.setText("<html>Общ брой на книгите от този автор: "+count+"</html>"); authorNameTF.setText(null); } catch (SQLException e1) { WarnNotDone(); e1.printStackTrace(); } CloseConn(); setSize(600, 500); } } //-- private void WarnNoConnection() { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Неуспешна връзка с датабазата!</html>"); } private void WarnNotDone() { labelWarning.setForeground(Color.RED); labelWarning.setText("<html>Някъде по пътя възникна грешка!</html>"); } private void CloseConn() { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package raceclient; import java.net.DatagramSocket; import java.net.InetAddress; /** * Created by IntelliJ IDEA. * User: julian * Date: Mar 8, 2008 * Time: 6:43:22 PM */ public class SoloDistanceEvaluator implements Evaluator { final int numberOfTrials = 1; final int numberOfTimesteps = 10000; final int maxAllowedDamage = 5000; final Connection connection; public SoloDistanceEvaluator (int port, String address) throws Exception { address = "127.0.0.1"; System.out.print ("Connecting to " + address + ":" + port + "... "); DatagramSocket socket = new DatagramSocket(); InetAddress remote = InetAddress.getByName(address); //connection = new PausingConnection (socket, remote, port); connection = new InterruptingConnection (socket, remote, port); //connection = new SimpleConnection (socket, remote, port); String reply = connection.sendAndReceive("wcci2008"); if (!reply.contains ("identified")) { throw new Exception ("Odd reply from server after connecting: " + reply); } System.out.println ("OK"); } public double evaluate(Controller controller) { double totalTravelledDistance = 0; for (int trial = 0; trial < numberOfTrials; trial++) { controller.reset(); Action action = new Action (); // action.restartRace = true; String reply = connection.sendAndReceive (action.toString ()); action.restartRace = false; // the first reply should be a ***restart*** while (reply.contains("restart")) { //System.out.println("-- no restart yet"); try { Thread.sleep (10); } catch (Exception e) { e.printStackTrace(); } reply = connection.sendAndReceive (action.toString ()); // System.out.println(reply); }//end of while // try { // Thread.sleep (500); // } // catch (Exception e) { // e.printStackTrace(); // } // reply = connection.sendAndReceive ("wcci2008"); // if (!reply.contains ("identified")) { // throw new RuntimeException ("Odd reply from server after connecting: " + reply); // } else System.out.println("Here"); SensorModel model = null; double currentDistanceRaced = 0; for (int step = 0; step < numberOfTimesteps; step++) { // do { reply = connection.sendAndReceive (action.toString ()); //} while (reply.contains ("restart")); MessageParser message = new MessageParser (reply); model = new MessageBasedSensorModel (message); // System.out.println(model); action = controller.control(model); if (currentDistanceRaced == 0 || Math.abs (currentDistanceRaced - model.getDistanceRaced ()) < 100) { currentDistanceRaced = model.getDistanceRaced (); } if (model.getDamage() > maxAllowedDamage) { break; } //System.out.print(model.getDistanceRaced () + " "); // System.out.print(model.getDistanceFromStartLine () + " "); } totalTravelledDistance += currentDistanceRaced; } return totalTravelledDistance / numberOfTrials; } }
package com.qac.nbg_app.entities; //Imports import javax.persistence.*; import javax.validation.constraints.*; @Entity @Table(name = "employeeinventorymanager") //Named Queries @NamedQueries ({ @NamedQuery (name=Employee.FIND_BY_FIRST_NAME, query = "SELECT a FROM EmployeeInventoryManager a WHERE a.firstName = :firstName"), @NamedQuery (name=Employee.FIND_BY_LAST_NAME, query = "SELECT a FROM EmployeeInventoryManager a WHERE a.lastName = :lastName"), @NamedQuery (name=Employee.FIND_BY_ID, query = "SELECT a FROM EmployeeInventoryManager a WHERE a.employeeInventoryManagerId = :employeeInventoryManagerId"), @NamedQuery (name=Employee.FIND_BY_USER_NAME, query = "SELECT a FROM EmployeeInventoryManager a WHERE a.userName = :userName"), }) public class Employee { //Query Declarations public static final String FIND_BY_FIRST_NAME = "EmployeeInventoryManager.findByEmployeeInventoryManager"; public static final String FIND_BY_LAST_NAME = "EmployeeInventoryManager.findByEmployeeInventoryManager"; public static final String FIND_BY_ID = "EmployeeInventoryManager.findByEmployeeInventoryManager"; public static final String FIND_BY_USER_NAME = "EmployeeInventoryManager.findByEmployeeInventoryManager"; //Variable Declarations @Id @Column(name = "employeeInventoryManagerId") @GeneratedValue (strategy = GenerationType.IDENTITY) private int employeeInventoryManagerId; @Column(name = "title", nullable = false, length = 225) @NotNull @Size (min = 2, max = 225) private String title; @Column(name = "firstName", nullable = false, length = 225) @NotNull @Size (min = 2, max = 225) private String firstName; @Column(name = "lastName", nullable = false, length = 225) @NotNull @Size (min = 2, max = 225) private String lastName; @Column(name = "userName", nullable = false, length = 225) @NotNull @Size (min = 2, max = 225) private String userName; @Column(name = "password", nullable = false, length = 225) @NotNull @Size (min = 2, max = 225) private String password; //Constructor public Employee(String title, String firstName,String lastName, String userName, String password) { this.title = title; this.firstName = firstName; this.lastName = lastName; this.userName = userName; this.password = password; } //Getters and Setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getemployeeInventoryManagerId() { return employeeInventoryManagerId; } }
package com.gxtc.huchuan.ui.mine.incomedetail; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import android.widget.LinearLayout; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.recyclerview.RecyclerView; import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.AccountWaterAdapter; import com.gxtc.huchuan.adapter.InComeAllCountAdapter; import com.gxtc.huchuan.bean.AccountWaterBean; import com.gxtc.huchuan.bean.InComeAllCountBean; import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity; import com.gxtc.huchuan.widget.DividerItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.BindView; /** * Describe:收益明细 二级页面 之打赏、交易 * Created by ALing on 2017/5/19 . */ public class InComeDetailListActivity extends BaseTitleActivity implements View.OnClickListener, NewInComeDetailContract.View { @BindView(R.id.rc_list) RecyclerView mRcList; @BindView(R.id.swipe_layout) SwipeRefreshLayout mSwipeLayout; // @BindView(R.id.base_empty_area) View emptyView; private int mType; // 0 打赏 1 交易 private int dateType; // 0 打赏 1 交易 private String streamType; //流水类型 private NewInComeDetailContract.Presenter mPresenter; private InComeAllCountAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.common_recyclerview); } @Override public void initView() { mType = getIntent().getIntExtra("type", 0); dateType = getIntent().getIntExtra("dateType", 0); if (mType == 0) { getBaseHeadView().showTitle(getString(R.string.title_reward)); streamType = "8"; } else { getBaseHeadView().showTitle(getString(R.string.title_deal)); streamType = "0"; } getBaseHeadView().showBackButton(this); initRecycler(); } private void initRecycler() { mSwipeLayout.setColorSchemeResources(R.color.refresh_color1, R.color.refresh_color2, R.color.refresh_color3, R.color.refresh_color4); mRcList.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL,false)); mRcList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST)); mRcList.setLoadMoreView(R.layout.model_footview_loadmore); mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mPresenter.getIncomeList(streamType,"",dateType+"",true); //刷新重新获取数据 日期类型。 0:本日,1:本周,2:本月,3:本年,4:全部 mRcList.reLoadFinish(); } }); mRcList.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() { @Override public void onLoadMoreRequested() { mPresenter.loadMore(streamType,dateType+""); //加载更多 } }); // mAdapter = new AccountWaterAdapter(this,new ArrayList<AccountWaterBean>(),R.layout.item_income_detail_list); mAdapter = new InComeAllCountAdapter(this,new ArrayList<AccountWaterBean>(),R.layout.item_income_detail); mRcList.setAdapter(mAdapter); } @Override public void initData() { super.initData(); // mEmptyView = new EmptyView(emptyView); new NewInComeDetailPresenter(this); mPresenter.getIncomeList(streamType,"",dateType+"",false); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.headBackButton: finish(); break; } } @Override public void tokenOverdue() { GotoUtil.goToActivity(this, LoginAndRegisteActivity.class); } @Override public void showTotalIncomeStatistics(InComeAllCountBean bean) { } @Override public void showIncomeList(List<AccountWaterBean> datas) { mRcList.notifyChangeData(datas,mAdapter); } @Override public void showRefreshIncomeListFinish(List<AccountWaterBean> datas) { mRcList.notifyChangeData(datas,mAdapter); } @Override public void showRefreshTotalIncomeStatisticsFinish(InComeAllCountBean datas) { } @Override public void showLoadMore(List<AccountWaterBean> datas) { mRcList.changeData(datas,mAdapter); } @Override public void showNoMore() { mRcList.loadFinish(); } @Override public void setPresenter(NewInComeDetailContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void showLoad() { getBaseLoadingView().showLoading(); } @Override public void showLoadFinish() { mSwipeLayout.setRefreshing(false); getBaseLoadingView().hideLoading(); } @Override public void showEmpty() { getBaseEmptyView().showEmptyContent(getString(R.string.empty_no_data)); } @Override public void showReLoad() { // mPresenter.getIncomeList(false); } @Override public void showError(String info) { getBaseEmptyView().showEmptyContent(info); } @Override protected void onDestroy() { super.onDestroy(); mPresenter.destroy(); } @Override public void showNetError() { getBaseEmptyView().showNetWorkView(new View.OnClickListener() { @Override public void onClick(View v) { showReLoad(); } }); } }
package com.ants.theantsgo.base; import com.ants.theantsgo.util.JSONUtils; import com.ants.theantsgo.util.L; import com.lzy.okgo.callback.StringCallback; import com.lzy.okgo.model.Progress; import com.lzy.okgo.model.Response; import java.util.Map; import okhttp3.Call; /** * ===============Txunda=============== * 作者:DUKE_HwangZj * 日期:2017/11/19 0019 * 时间:17:56 * 描述: * ===============Txunda=============== */ public class DataCallBack extends StringCallback { private BaseView baseView; private String flag = "code"; private String success = "1"; public DataCallBack(BaseView baseView) { this.baseView = baseView; } public DataCallBack(BaseView baseView, String flag, String success) { this.baseView = baseView; this.flag = flag; this.success = success; } @Override public void onSuccess(Response<String> response) { Call call = response.getRawCall(); Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response.body());//GsonUtil.GsonToMaps(response.body()); // 七号店大淘客专用 if (flag.equals("") || success.equals("")) { baseView.onComplete(call.request().url().toString(), response.body()); return; } if (map.get(flag).equals(success)) { baseView.onComplete(call.request().url().toString(), response.body()); } else { baseView.OnError(call.request().url().toString(), map); } } @Override public void onError(Response<String> response) { super.onError(response); L.e("=====异常链接=====", response.getRawCall().request().url().toString()); baseView.onException(response); } @Override public void uploadProgress(Progress progress) { super.uploadProgress(progress); baseView.uploadProgress(progress); } @Override public void downloadProgress(Progress progress) { super.downloadProgress(progress); baseView.downloadProgress(progress); } public void setFlag(String flag) { this.flag = flag; } public void setSuccess(String success) { this.success = success; } }
package de.lezleoh.mathgame.term; public class Sum extends TermWithMultipleOperands { public Sum() { super((a, b) -> a + b, () -> "+", new Integer(0)); } @Override public TypeOfTerm getTypeOfTerm() { return TypeOfTerm.SUM; } @Override public TermInt copy() { Sum newTerm = new Sum(); for (TermInt operand : operands) { newTerm.addOperand(operand.copy()); } return newTerm; } }
package br.com.dercilima.myfirstapp; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class DetalhesActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalhes); final TextView nomeText = findViewById(R.id.nome_text); final TextView idadeText = findViewById(R.id.idade_text); final TextView cursoText = findViewById(R.id.curso_text); // Extrair o nome do EditText // String nome = getIntent().getStringExtra("nome"); // Setar o nome para o TextView // nomeText.setText(nome); // Forma abreviada // idadeText.setText(getIntent().getStringExtra("idade")); // cursoText.setText(getIntent().getStringExtra("curso")); long id = getIntent().getLongExtra("id", 0); // Instanciar o banco de dados DbHelper helper = new DbHelper(this); SQLiteDatabase database = helper.getReadableDatabase(); String[] columns = {"NOME", "IDADE", "CURSO"}; String selection = "_id = ?"; String[] selectionArgs = {String.valueOf(id)}; Cursor cursor = database.query("ALUNOS", columns, selection, selectionArgs, null, null, null); if (cursor.moveToFirst()) { // Extrair dados do cursor String nome = cursor.getString(cursor.getColumnIndex("NOME")); String idade = cursor.getString(cursor.getColumnIndex("IDADE")); String curso = cursor.getString(cursor.getColumnIndex("CURSO")); // Exibir os dados na tela nomeText.setText(nome); idadeText.setText(idade); cursoText.setText(curso); } // Fechar o cursor cursor.close(); // Fechar o banco de dados helper.close(); } }
package com.log4analytics.mobile.voiderecording; import android.app.Activity; import java.util.Arrays; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.media.AudioRecord.OnRecordPositionUpdateListener; import java.net.DatagramSocket; import java.io.IOException; //import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Send extends Activity implements OnClickListener, OnRecordPositionUpdateListener { private static final int DEFAULT_AUDIO_SOURCE = MediaRecorder.AudioSource.VOICE_RECOGNITION; private static final int DEFAULT_SAMPLE_RATE = 16000; private static int RESOLUTION = AudioFormat.ENCODING_PCM_16BIT; private static final short RESOLUTION_IN_BYTES = 2; // Number of channels (MONO = 1, STEREO = 2) final short CHANNELS = 1; private int mFramePeriod; private int mBufferSize; private Button startButton,stopButton; private short[][] buffers; private int ix; public static DatagramSocket socket; private int port=50005; AudioRecord recorder; private int sampleRate = DEFAULT_SAMPLE_RATE ; // 44100 for music private int channelConfig = AudioFormat.CHANNEL_IN_DEFAULT; private int audioFormat = AudioFormat.ENCODING_PCM_16BIT; int minBufSize = 0; private boolean status = true; private short[] buffer; @Override public void onMarkerReached(AudioRecord arg0) { // TODO Auto-generated method stub } public void stopRecording() { if (null != recorder) { status = false; recorder.stop(); recorder.release(); recorder = null; streamThread = null; } Log.w("VS", "Audio recording stopped"); } @Override public void onPeriodicNotification(AudioRecord arg0) { float norm; short[] buf = buffers[ix % buffers.length]; int vol = 0; for (int i = 0; i < buf.length; i++) vol = Math.max(vol, Math.abs(buf[i])); norm = (float) vol / (float) Short.MAX_VALUE; // glSurface.setLightness(norm); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_button: // startRecording(); // setRecordMode(); break; case R.id.stop_button: // stopRecording(); // setRecordMode(); break; default: break; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout); startButton = (Button) findViewById (R.id.start_button); stopButton = (Button) findViewById (R.id.stop_button); startButton.setOnClickListener (startListener); stopButton.setOnClickListener(stopListener); } private final View.OnClickListener stopListener = new View.OnClickListener() { @Override public void onClick(View arg0) { status = false; stopRecording(); Log.d("VS", "Recorder released"); } }; private final View.OnClickListener startListener = new View.OnClickListener() { @Override public void onClick(View arg0) { status = true; startRecording(); } }; private AudioRecord findAudioRecord() { // TODO Auto-generated method stub int[] mSampleRates = new int[]{8000}; for (int rate : mSampleRates) { for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_16BIT }) { for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO}) { try { Log.w("AudiopRecording", "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: " + channelConfig); minBufSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat); if (minBufSize != AudioRecord.ERROR_BAD_VALUE) { // check if we can instantiate and have a success recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, rate, channelConfig, audioFormat, minBufSize); int result = recorder.getState(); if (result == AudioRecord.STATE_INITIALIZED) { System.out.println(result); buffers = new short[256][minBufSize]; return recorder; } } else { System.out.println("ERROR BAD VALUE"); } } catch (Exception e) { Log.e("AudiopRecording", rate + "Exception, keep trying.",e); } } } } Log.d("VS","no audioRecorder"); return null; } private Thread streamThread; // convert short to byte private byte[] short2byte(short[] sData) { int shortArrsize = sData.length; byte[] bytes = new byte[shortArrsize * 2]; for (int i = 0; i < shortArrsize; i++) { bytes[i * 2] = (byte) (sData[i] & 0x00FF); bytes[(i * 2) + 1] = (byte) (sData[i] >> 8); sData[i] = 0; } return bytes; } public void startRecording() { streamThread = new Thread(new Runnable() { @Override public void run() { //DatagramSocket socket = new DatagramSocket(); Log.d("VS", "Socket Created"); //final InetAddress destination = InetAddress.getByName("192.168.1.5"); Log.w("VS", "Address retrieved"); AudioRecord recorder = findAudioRecord(); Log.w("VS", "Buffer created of size " + minBufSize); //DatagramPacket packet; Log.w("VS", "Recorder initialized"); if (recorder != null) { recorder.startRecording(); ix = 0; int read = 0; while (status == true) { //reading data from MIC into buffer // minBufSize = recorder.read(buffer, 0, buffer.length); recorder.setPositionNotificationPeriod(minBufSize); //long t1 = System.currentTimeMillis(); int index = ix++ % buffers.length; buffer = buffers[index]; read = recorder.read(buffer, 0, buffer.length); //time after reading //read_time = System.currentTimeMillis(); //Log.d(LOG_TAG, "read bytes: " + read); //Log.d(LOG_TAG, "read_time=" + (read_time - t1)); //int vol = 0; //for (int i=0;i<buffer.length;i++) // vol = Math.max(vol, Math.abs(buffer[i])); //float norm = (float)vol/(float)Short.MAX_VALUE; //glSurface.setLightness(norm); //putting buffer in the packet //packet = new DatagramPacket (buffer,buffer.length,destination,port); //socket.send(packet); System.out.println("MinBufferSize: " + minBufSize); System.out.println("index: " + index); byte[] b = short2byte(buffer); System.out.println(Arrays.toString(b)); } } else { System.out.println("null"); } } }); streamThread.start(); } }
package statistics; /** * Interfejs dla statystyk rycerza. * @author Piotrek */ public interface KnightStatistics_Interface { /** * Setter dla liczby zabitych smoków. * @param int numberOfKilledDragons * @return KnightStatistics_Interface */ public KnightStatistics_Interface setNumberOfKilledDragons(int numberOfKilledDragons); /** * Getter dla liczby zabitych smoków. * @return int */ public int getNumberOfKilledDragons(); /** * Setter dla liczby wizyt w grodach. * @param int numberOfVisitsInCities * @return KnightStatistics_Interface */ public KnightStatistics_Interface setNumberOfVisitsInCities(int numberOfVisitsInCities); /** * Getter dla liczby wizyt w grodach. * @return int */ public int getNumberOfVisitsInCities(); }
package practise; public class TestMath { private int i,j,k,l; float f,f1; double d,d1; public TestMath(int i, int j) { super(); this.i = i; this.j = j; } void evaluate() { f=12.456f; d=3.0; System.out.println("sum is "+Math.addExact(i, j)); System.out.println(Math.abs(f)); System.out.println(Math.abs(d)); System.out.println("max blw two int : "+Math.max(i, j)); System.out.println("minimum between two number : "+Math.min(i, j)); System.out.println(Math.pow(12,7)); System.out.println(Math.round(d)); System.out.println(Math.exp(d)); System.out.println(); } public static void main(String[] args) { TestMath te=new TestMath(12, 4); te.evaluate(); } }
package com.example.ajays.dirac.Forum; import java.lang.reflect.Array; import java.util.ArrayList; public class ForumModel { String post_title; String post_description; Integer num_upvotes; ArrayList<String> comments; public ForumModel(){} public ForumModel(String post_title, String post_description, Integer num_upvotes, ArrayList<String> comments) { this.post_title = post_title; this.post_description = post_description; this.num_upvotes = num_upvotes; this.comments = comments; } public String getPost_title() { return post_title; } public void setPost_title(String post_title) { this.post_title = post_title; } public Integer getNum_upvotes() { return num_upvotes; } public void setNum_upvotes(Integer num_upvotes) { this.num_upvotes = num_upvotes; } public String getPost_description() { return post_description; } public void setPost_description(String post_description) { this.post_description = post_description; } public ArrayList<String> getComments() { return comments; } public void setComments(ArrayList<String> comments) { this.comments = comments; } }
package com.heyskill.element_core.fragments.bottom; import java.util.LinkedHashMap; /** * 把每一个Fragment和底部的按钮对象进行绑定,组装成一个LinkedHashMap的集合 */ public final class ItemBuilder { private final LinkedHashMap<BottomTabBean,BottomItemFragment> ITEMS = new LinkedHashMap<>(); //简单工厂模式 static ItemBuilder builder(){ return new ItemBuilder(); } public final ItemBuilder addItem(BottomTabBean bean,BottomItemFragment fragment){ ITEMS.put(bean,fragment); return this; } public final ItemBuilder addItems(LinkedHashMap<BottomTabBean,BottomItemFragment> items){ ITEMS.putAll(items); return this; } public final LinkedHashMap<BottomTabBean,BottomItemFragment> build(){ return ITEMS; } }
package by.client.android.railwayapp.support.database.room; import android.arch.persistence.room.Database; import android.arch.persistence.room.RoomDatabase; import by.client.android.railwayapp.model.SearchTrain; /** * Created by PanteleevRV on 04.09.2018. * * @author Q-RPA */ @Database(entities = {SearchTrain.class}, version = 1) public abstract class SearchTrainDataBase extends RoomDatabase { public abstract SearchTrainDao searchTrainDao(); }
package com.allure.service.request; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.NotEmpty; /** * Created by yang_shoulai on 7/20/2017. */ @Setter @Getter public class TokenRefreshRequest { @NotEmpty(message = "NotEmpty.tokenRefreshRequest.accessToken") private String accessToken; @NotEmpty(message = "NotEmpty.tokenRefreshRequest.refreshToken") private String refreshToken; }
package com.macys.util.json.generator; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.macys.mobile.gateway.sdpstub.fitnesse.json.ComparisonResult; import com.macys.mobile.gateway.sdpstub.fitnesse.json.JsonComparator; import com.macys.mobile.gateway.sdpstub.utils.Utils; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.LinkedList; import java.util.List; /** * @author Artem Zhdanov <azhdanov@griddynamics.com> * @since 27/11/2014 */ public class MergeTest { @Test public void simpleTest1() throws URISyntaxException, IOException { Gson gs = new GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create(); List<JsonObject> schemas = new LinkedList<JsonObject>(); final URL resource1 = getClass().getClassLoader().getResource("testData/res1.json"); SchemaGenerator generator = SchemaGenerator.fromTxt(new FileReader(new File(resource1.toURI()))); final JsonObject schema1 = generator.getSchemaElement(); schemas.add(schema1); final URL resource2 = getClass().getClassLoader().getResource("testData/res2.json"); generator = SchemaGenerator.fromTxt(new FileReader(new File(resource2.toURI()))); final JsonObject schema2 = generator.getSchemaElement(); schemas.add(schema2); SchemaMerger merger = new SchemaMerger(); final JsonElement result = merger.mergeSchemas(schemas); final String mergeResultActual = gs.toJson(result); final URL expectedResource = getClass().getClassLoader().getResource("testData/expectedMerge.json"); String expectedResponse = Utils.readFile(new File(expectedResource.toURI())); ComparisonResult checkResult = JsonComparator.compare(expectedResponse, mergeResultActual); checkResult.logFailed(); Assert.assertTrue(checkResult.equal()); } }
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.client.v8.model; import java.util.Objects; import com.cloudera.director.client.v8.model.ConfigurationPropertyValue; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A configuration property associated with provider metadata */ @ApiModel(description = "A configuration property associated with provider metadata") public class ConfigurationProperty { @SerializedName("configKey") private String configKey = null; @SerializedName("name") private String name = null; @SerializedName("description") private String description = null; @SerializedName("sensitive") private Boolean sensitive = null; @SerializedName("required") private Boolean required = null; @SerializedName("basic") private Boolean basic = null; /** * Configuration property type */ @JsonAdapter(TypeEnum.Adapter.class) public enum TypeEnum { BOOLEAN("BOOLEAN"), INTEGER("INTEGER"), DOUBLE("DOUBLE"), STRING("STRING"); private String value; TypeEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static TypeEnum fromValue(String text) { for (TypeEnum b : TypeEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<TypeEnum> { @Override public void write(final JsonWriter jsonWriter, final TypeEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public TypeEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return TypeEnum.fromValue(String.valueOf(value)); } } } @SerializedName("type") private TypeEnum type = null; /** * Widget used to display this property */ @JsonAdapter(WidgetEnum.Adapter.class) public enum WidgetEnum { RADIO("RADIO"), CHECKBOX("CHECKBOX"), TEXT("TEXT"), PASSWORD("PASSWORD"), NUMBER("NUMBER"), TEXTAREA("TEXTAREA"), FILE("FILE"), LIST("LIST"), OPENLIST("OPENLIST"), MULTI("MULTI"), OPENMULTI("OPENMULTI"); private String value; WidgetEnum(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } public static WidgetEnum fromValue(String text) { for (WidgetEnum b : WidgetEnum.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } public static class Adapter extends TypeAdapter<WidgetEnum> { @Override public void write(final JsonWriter jsonWriter, final WidgetEnum enumeration) throws IOException { jsonWriter.value(enumeration.getValue()); } @Override public WidgetEnum read(final JsonReader jsonReader) throws IOException { String value = jsonReader.nextString(); return WidgetEnum.fromValue(String.valueOf(value)); } } } @SerializedName("widget") private WidgetEnum widget = null; @SerializedName("defaultValue") private String defaultValue = null; @SerializedName("listSeparator") private String listSeparator = null; @SerializedName("placeholder") private String placeholder = null; @SerializedName("validValues") private List<ConfigurationPropertyValue> validValues = null; public ConfigurationProperty() { // Do nothing } private ConfigurationProperty(ConfigurationPropertyBuilder builder) { this.configKey = builder.configKey; this.name = builder.name; this.description = builder.description; this.sensitive = builder.sensitive; this.required = builder.required; this.basic = builder.basic; this.type = builder.type; this.widget = builder.widget; this.defaultValue = builder.defaultValue; this.listSeparator = builder.listSeparator; this.placeholder = builder.placeholder; this.validValues = builder.validValues; } public static ConfigurationPropertyBuilder builder() { return new ConfigurationPropertyBuilder(); } public static class ConfigurationPropertyBuilder { private String configKey = null; private String name = null; private String description = null; private Boolean sensitive = null; private Boolean required = null; private Boolean basic = null; private TypeEnum type = null; private WidgetEnum widget = null; private String defaultValue = null; private String listSeparator = null; private String placeholder = null; private List<ConfigurationPropertyValue> validValues = new ArrayList<ConfigurationPropertyValue>(); public ConfigurationPropertyBuilder configKey(String configKey) { this.configKey = configKey; return this; } public ConfigurationPropertyBuilder name(String name) { this.name = name; return this; } public ConfigurationPropertyBuilder description(String description) { this.description = description; return this; } public ConfigurationPropertyBuilder sensitive(Boolean sensitive) { this.sensitive = sensitive; return this; } public ConfigurationPropertyBuilder required(Boolean required) { this.required = required; return this; } public ConfigurationPropertyBuilder basic(Boolean basic) { this.basic = basic; return this; } public ConfigurationPropertyBuilder type(TypeEnum type) { this.type = type; return this; } public ConfigurationPropertyBuilder widget(WidgetEnum widget) { this.widget = widget; return this; } public ConfigurationPropertyBuilder defaultValue(String defaultValue) { this.defaultValue = defaultValue; return this; } public ConfigurationPropertyBuilder listSeparator(String listSeparator) { this.listSeparator = listSeparator; return this; } public ConfigurationPropertyBuilder placeholder(String placeholder) { this.placeholder = placeholder; return this; } public ConfigurationPropertyBuilder validValues(List<ConfigurationPropertyValue> validValues) { this.validValues = validValues; return this; } public ConfigurationProperty build() { return new ConfigurationProperty(this); } } public ConfigurationPropertyBuilder toBuilder() { return builder() .configKey(configKey) .name(name) .description(description) .sensitive(sensitive) .required(required) .basic(basic) .type(type) .widget(widget) .defaultValue(defaultValue) .listSeparator(listSeparator) .placeholder(placeholder) .validValues(validValues) ; } public ConfigurationProperty configKey(String configKey) { this.configKey = configKey; return this; } /** * Configuration property key * @return configKey **/ @ApiModelProperty(required = true, value = "Configuration property key") public String getConfigKey() { return configKey; } public void setConfigKey(String configKey) { this.configKey = configKey; } public ConfigurationProperty name(String name) { this.name = name; return this; } /** * Configuration property name * @return name **/ @ApiModelProperty(value = "Configuration property name") public String getName() { return name; } public void setName(String name) { this.name = name; } public ConfigurationProperty description(String description) { this.description = description; return this; } /** * Configuration property description * @return description **/ @ApiModelProperty(value = "Configuration property description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ConfigurationProperty sensitive(Boolean sensitive) { this.sensitive = sensitive; return this; } /** * Whether this property is sensitive * @return sensitive **/ @ApiModelProperty(value = "Whether this property is sensitive") public Boolean isSensitive() { return sensitive; } public void setSensitive(Boolean sensitive) { this.sensitive = sensitive; } public ConfigurationProperty required(Boolean required) { this.required = required; return this; } /** * Whether this property is required * @return required **/ @ApiModelProperty(value = "Whether this property is required") public Boolean isRequired() { return required; } public void setRequired(Boolean required) { this.required = required; } public ConfigurationProperty basic(Boolean basic) { this.basic = basic; return this; } /** * Whether this property is basic * @return basic **/ @ApiModelProperty(value = "Whether this property is basic") public Boolean isBasic() { return basic; } public void setBasic(Boolean basic) { this.basic = basic; } public ConfigurationProperty type(TypeEnum type) { this.type = type; return this; } /** * Configuration property type * @return type **/ @ApiModelProperty(value = "Configuration property type") public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this.type = type; } public ConfigurationProperty widget(WidgetEnum widget) { this.widget = widget; return this; } /** * Widget used to display this property * @return widget **/ @ApiModelProperty(value = "Widget used to display this property") public WidgetEnum getWidget() { return widget; } public void setWidget(WidgetEnum widget) { this.widget = widget; } public ConfigurationProperty defaultValue(String defaultValue) { this.defaultValue = defaultValue; return this; } /** * Default value for this property * @return defaultValue **/ @ApiModelProperty(value = "Default value for this property") public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } public ConfigurationProperty listSeparator(String listSeparator) { this.listSeparator = listSeparator; return this; } /** * Character to use to separate lists * @return listSeparator **/ @ApiModelProperty(value = "Character to use to separate lists") public String getListSeparator() { return listSeparator; } public void setListSeparator(String listSeparator) { this.listSeparator = listSeparator; } public ConfigurationProperty placeholder(String placeholder) { this.placeholder = placeholder; return this; } /** * Placeholder value to use if the value is unset * @return placeholder **/ @ApiModelProperty(value = "Placeholder value to use if the value is unset") public String getPlaceholder() { return placeholder; } public void setPlaceholder(String placeholder) { this.placeholder = placeholder; } public ConfigurationProperty validValues(List<ConfigurationPropertyValue> validValues) { this.validValues = validValues; return this; } public ConfigurationProperty addValidValuesItem(ConfigurationPropertyValue validValuesItem) { if (this.validValues == null) { this.validValues = new ArrayList<ConfigurationPropertyValue>(); } this.validValues.add(validValuesItem); return this; } /** * List of all valid values for this property * @return validValues **/ @ApiModelProperty(value = "List of all valid values for this property") public List<ConfigurationPropertyValue> getValidValues() { return validValues; } public void setValidValues(List<ConfigurationPropertyValue> validValues) { this.validValues = validValues; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfigurationProperty configurationProperty = (ConfigurationProperty) o; return Objects.equals(this.configKey, configurationProperty.configKey) && Objects.equals(this.name, configurationProperty.name) && Objects.equals(this.description, configurationProperty.description) && Objects.equals(this.sensitive, configurationProperty.sensitive) && Objects.equals(this.required, configurationProperty.required) && Objects.equals(this.basic, configurationProperty.basic) && Objects.equals(this.type, configurationProperty.type) && Objects.equals(this.widget, configurationProperty.widget) && Objects.equals(this.defaultValue, configurationProperty.defaultValue) && Objects.equals(this.listSeparator, configurationProperty.listSeparator) && Objects.equals(this.placeholder, configurationProperty.placeholder) && Objects.equals(this.validValues, configurationProperty.validValues); } @Override public int hashCode() { return Objects.hash(configKey, name, description, sensitive, required, basic, type, widget, defaultValue, listSeparator, placeholder, validValues); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ConfigurationProperty {\n"); sb.append(" configKey: ").append(toIndentedString(configKey)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" sensitive: ").append(toIndentedString(sensitive)).append("\n"); sb.append(" required: ").append(toIndentedString(required)).append("\n"); sb.append(" basic: ").append(toIndentedString(basic)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" widget: ").append(toIndentedString(widget)).append("\n"); sb.append(" defaultValue: ").append(toIndentedString(defaultValue)).append("\n"); sb.append(" listSeparator: ").append(toIndentedString(listSeparator)).append("\n"); sb.append(" placeholder: ").append(toIndentedString(placeholder)).append("\n"); sb.append(" validValues: ").append(toIndentedString(validValues)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package EntityManagers.Offline; import java.util.List; import javax.ejb.Stateless; import javax.enterprise.inject.Default; import javax.inject.Inject; import Entities.Screen; import Entities.Seat; import EntityManagers.ScreenManager; import Utilities.DummyData; @Default @Stateless public class ScreenManagerOffline implements ScreenManager { @Inject private DummyData dummyData; public void persistScreen(Screen input) { dummyData.getScreens().add(input); } public void updateScreenSize(int id, int input) { for(Screen s : dummyData.getScreens()){ if(s.getId() == id){ s.setScreenSize(input); break; } } } public void updateScreenLayout(int id, Seat[][] input) { for(Screen s : dummyData.getScreens()){ if(s.getId() == id){ s.setLayout(input); break; } } } public void deleteScreen(int id) { List<Screen> list = dummyData.getScreens(); for(int i = 0; i < list.size(); i++){ if(list.get(i).getId() == id){ list.remove(i); break; } } } }
package com.leador.picassodemo; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by xuwei on 2016/12/4. */ public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { Context context; List<NewsBean> list; MyItemClickListner listner; public MyAdapter(Context context,List<NewsBean> list) { this.context = context; this.list = list; } public void setOnItemClickListener(MyItemClickListner listener) { this.listner = listener; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.news_item_review,null); MyViewHolder holder = new MyViewHolder(view,listner); return holder; } public void onBindViewHolder(MyViewHolder holder, int position) { holder.tvTitle.setText(list.get(position).getTitle()); holder.tvDetail.setText(list.get(position).getDescription()); holder.tvTime.setText(list.get(position).getCtime()); list.get(position).setPicUrl("http://i.imgur.com/DvpvklR.png"); Picasso.with(context).load(list.get(position).getPicUrl()).into(holder.img); } @Override public int getItemCount() { return list.size(); } interface MyItemClickListner { void onItemClick(View view,int position); } static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView tvTitle; private TextView tvDetail; private TextView tvTime; private ImageView img; MyItemClickListner listner; public MyViewHolder(View itemView,MyItemClickListner listner) { super(itemView); this.listner = listner; itemView.setOnClickListener(this); tvTitle = (TextView) itemView.findViewById(R.id.tvTitle); tvDetail = (TextView) itemView.findViewById(R.id.tvDetail); tvTime = (TextView) itemView.findViewById(R.id.tvTime); img = (ImageView) itemView.findViewById(R.id.iv); } @Override public void onClick(View view) { if (listner != null) { listner.onItemClick(view,getPosition()); } } } }
package com.alex; import com.alex.eat.DyploNutsCollection; import com.alex.eat.Nut; import org.assertj.core.api.Assertions; import org.junit.Assert; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Set; public class DyploNutsCollectionTest { @Test public void testAddNutToOneElementDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(1); Nut nut = new Nut(10, "kedr"); dyploCollection.addNut(nut); Set<Nut> nuts = dyploCollection.getAllNuts(); Assert.assertEquals("Size should be 1", 1, nuts.size()); Assert.assertEquals("Added nut is really that we add", nut, nuts.iterator().next()); } @Test public void testGetNutFromOneElementDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(1); Nut nut = new Nut(10, "kedr"); dyploCollection.addNut(nut); Nut nutFromeDyplo = dyploCollection.getNut(); Assert.assertEquals(nut, nutFromeDyplo); } @Test public void testGetNutToZeroElementDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(0); Nut nut = new Nut(10, "kedr"); dyploCollection.addNut(nut); Assert.assertEquals(0, dyploCollection.getCurrentSize()); } @Test(expected = IllegalStateException.class) public void testGetNutFromZeroElementDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(0); Nut nutFromDyplo = dyploCollection.getNut(); } @Test public void testAddNut() { DyploNutsCollection dyploCollection = new DyploNutsCollection(3); dyploCollection.addNut(new Nut(1, "kedr")); dyploCollection.addNut(new Nut(2, "shishka")); Assert.assertEquals(2, dyploCollection.getCurrentSize()); } @Test public void testAddNutToFullDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(3); Nut kedrNut = new Nut(1, "kedr"); Nut shishkaNut = new Nut(2, "shishka"); Nut semyNut = new Nut(3, "semy"); Nut gelydNut = new Nut(4, "gelyd"); dyploCollection.addNut(kedrNut); dyploCollection.addNut(shishkaNut); dyploCollection.addNut(semyNut); dyploCollection.addNut(gelydNut); Assert.assertEquals(3, dyploCollection.getCurrentSize()); Set<Nut> nuts = dyploCollection.getAllNuts(); Assert.assertTrue("Dyplo should contain kedr nut", nuts.contains(kedrNut)); Assert.assertTrue("Dyplo should contain shishka nut", nuts.contains(shishkaNut)); Assert.assertTrue("Dyplo should contain semy nut", nuts.contains(semyNut)); } @Test(expected = IllegalStateException.class) public void testGetNutFromEmptyDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(3); dyploCollection.getNut(); } @Test public void testGetCurrentNut() { DyploNutsCollection dyploArray = new DyploNutsCollection(3); Nut kedrNut = new Nut(1, "kedr"); Nut shishkaNut = new Nut(2, "shishka"); Nut semyNut = new Nut(3, "semy"); Nut gelydNut = new Nut(4, "gelyd"); dyploArray.addNut(kedrNut); dyploArray.addNut(shishkaNut); dyploArray.addNut(semyNut); dyploArray.addNut(gelydNut); Assert.assertEquals(3, dyploArray.getCurrentSize()); List<Nut> testNuts = new ArrayList<>(); testNuts.add(semyNut); testNuts.add(shishkaNut); testNuts.add(kedrNut); Nut currentTestNut = dyploArray.getNut(); Assertions.assertThat(currentTestNut).isIn(testNuts); testNuts.remove(currentTestNut); currentTestNut = dyploArray.getNut(); Assertions.assertThat(currentTestNut).isIn(testNuts); testNuts.remove(currentTestNut); currentTestNut = dyploArray.getNut(); Assertions.assertThat(currentTestNut).isIn(testNuts); testNuts.remove(currentTestNut); Assert.assertEquals(0, dyploArray.getCurrentSize()); } @Test public void testWeightOfDyplo() { DyploNutsCollection dyploCollection = new DyploNutsCollection(3); Nut kedrNut = new Nut(1, "kedr"); Nut shishkaNut = new Nut(2, "shishka"); Nut semyNut = new Nut(3, "semy"); dyploCollection.addNut(kedrNut); dyploCollection.addNut(shishkaNut); dyploCollection.addNut(semyNut); Assert.assertEquals(6,dyploCollection.getWeight()); } }
package com.git.test; /** * @Author 牛技艺 * @Date 2019-07-12 14:24 */ public class user { private String name; private int age; private int a; //wgw private String wgw; }
package com.snxy.pay.service.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * Created by 24398 on 2018/11/14. */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class WxBillSuccessPay { /* 交易时间,应用ID,商户ID,设备号,微信订单号,商户订单号,用户标识, 交易类 型,交易状态,付款银行,货币种类,总金额, 代金券或立减券优惠金额,商品名称,商 户数据包,手续费,费率,门店ID,门店名称,收银员ID,扩展参数1,扩展参数2,扩展参 数 3,扩展参数 4*/ private String tradeTime; // 交易时间 0 private String appid; // 不同商户的appid 和mch_id不同 1 private String mch_id; // 商户ID 2 private String device_info; // 设备号 3 private String transaction_id; // 微信订单号 4 private String out_trade_no; // 商户订单号 5 private String openid ; // 用户标识 6 private String tradeType; // 交易类型 7 private String tradeStatus ;// 交易状态 8 private String payBank; // 付款银行 9 private String fee_type ;// 货币种类 10 private String total_fee; // 总金额 11 private String coupon_fee; // 代金券或立减券优惠金额 12 /* private String refund_id; // 微信退款单号 private String out_refund_no; // 商户退款单号 private String refund_fee; // 退款金额 private String coupon_refund_fee; // 代金券或立减券退款金额 private String refund_type; // 退款类型 private String refund_status; // 退款状态*/ private String goods_name; // 商品名称 13 private String attach; // 商户数据包 14 private String service_charge; // 手续费 15 private String rate; // 费率 16 private String store_appid; // 门店 ID 17 private String store_name; // 门店名称 18 private String cashier; // 收银员 ID 19 private String extend_para1; // 扩展参数 1 20 private String extend_para2; // 扩展参数 2 21 private String extend_para3; // 扩展参数 3 22 private String extend_para4; // 扩展参数 4 23 }
package de.varylab.discreteconformal.startup; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.GridLayout; import java.awt.Image; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import javax.swing.JPanel; import de.jtem.jrworkspace.plugin.simplecontroller.widget.SplashScreen; import de.varylab.discreteconformal.ConformalLab; import de.varylab.discreteconformal.plugin.image.ImageHook; public class ConformalLabSplashScreen extends SplashScreen { private static final long serialVersionUID = 1L; private Image lowResImage = null, hiResImage = null; private String status = "Status"; private double progress = 0.0; private SplashComponent splashComponent = new SplashComponent(); private boolean useHighRes = false; private static boolean isWindows = false, isLinux = false; private double statusX = 0.32, statusY = 0.52, fontSize = 0.02; static { isWindows = System.getProperty("os.name").toLowerCase().contains("win"); isLinux = System.getProperty("os.name").toLowerCase().contains("linux"); } public ConformalLabSplashScreen() { this( ImageHook.getImage("splash2014_lores.png"), ImageHook.getImage("splash2014_hires.png") ); } public ConformalLabSplashScreen(Image lowResImage, Image hiResImage) { setIconImage(ImageHook.getImage("icon_24.png")); setIconImages(ConformalLab.getMainIconList()); this.setTitle("Discrete Conformal Lab"); this.lowResImage = lowResImage; this.hiResImage = hiResImage; setBackground(new Color(1, 1, 1, 0)); setAlwaysOnTop(false); GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(); int[] dpi = getDPI(gc); useHighRes = dpi[0] > 110; if (isLinux) { useHighRes = false; } Dimension size = new Dimension(); if (useHighRes) { size.width = hiResImage.getWidth(this) / 2; size.height = hiResImage.getHeight(this) / 2; if (isWindows) { size.width = hiResImage.getWidth(this); size.height = hiResImage.getHeight(this); } } else { size.width = lowResImage.getWidth(this); size.height = lowResImage.getHeight(this); } setSize(size); setPreferredSize(size); setMinimumSize(size); setLayout(new GridLayout()); add(splashComponent); } public static int[] getDPI(final GraphicsConfiguration gc){ // get the Graphics2D of a compatible image for this configuration final Graphics2D g2d = (Graphics2D) gc.createCompatibleImage(1, 1).getGraphics(); // after these transforms, 72 units in either direction == 1 inch; see JavaDoc for getNormalizingTransform() g2d.setTransform(gc.getDefaultTransform() ); g2d.transform(gc.getNormalizingTransform() ); final AffineTransform oneInch = g2d.getTransform(); g2d.dispose(); return new int[]{(int) (oneInch.getScaleX() * 72), (int) (oneInch.getScaleY() * 72) }; } private class SplashComponent extends JPanel { private static final long serialVersionUID = 1L; private Font font = null; @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (isLinux) { g2d.setBackground(Color.WHITE); g2d.clearRect(0, 0, getWidth(), getHeight()); g2d.setComposite(AlphaComposite.SrcAtop); } else { g2d.setComposite(AlphaComposite.Src); } if (useHighRes) { int w = hiResImage.getWidth(this); int h = hiResImage.getHeight(this); if (!isWindows) { w /= 2; h /= 2; } g2d.drawImage(hiResImage, 0, 0, w, h, this); } else { int w = lowResImage.getWidth(this); int h = lowResImage.getHeight(this); g2d.drawImage(lowResImage, 0, 0, w, h, this); } g2d.setColor(Color.BLACK); g2d.setFont(getStatusFont()); int percentage = (int)Math.round(progress * 100); String progressString = status; if (progress != 0.0) { progressString = percentage + "% - " + progressString; } int textX = (int)(statusX * getWidth()); int textY = (int)(statusY * getHeight()); g2d.setComposite(AlphaComposite.SrcOver); g2d.drawString(progressString, textX, textY); } private Font getStatusFont() { if (font == null) { int fontSize = (int)(ConformalLabSplashScreen.this.fontSize * getHeight()); font =new Font("verdana", Font.PLAIN, fontSize); } return font; } } @Override public void setStatus(String status) { this.status = status; repaint(); } @Override public void setProgress(double progress) { this.progress = progress; repaint(); } public static void main(String[] args) throws Exception { ConformalLabSplashScreen splash = new ConformalLabSplashScreen(); splash.setVisible(true); } }
package com.discount.calculator.model; import com.discount.calculator.util.CustomerType; public class OrderDetails { private Double purchaseAmount; private CustomerType customerType; public OrderDetails(Double purchaseAmount, CustomerType customerType) { this.purchaseAmount = purchaseAmount; this.customerType = customerType; } public void setPurchaseAmount(Double purchaseAmount) { this.purchaseAmount = purchaseAmount; } public void setCustomerType(CustomerType customerType) { this.customerType = customerType; } public double getPurchaseAmount() { return purchaseAmount; } public CustomerType getCustomerType() { return customerType; } }