text
stringlengths
10
2.72M
package com.example.lemonimagelibrary.util; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Created by ShuWen on 2017/3/20. */ @SuppressWarnings({"unchecked", "JavaDoc"}) public abstract class BitmapDecoder { public Bitmap decodeBitmap(int reqWidth,int reqHeight){ BitmapFactory.Options options = new BitmapFactory.Options(); //只读取图片的大小 options.inJustDecodeBounds = true; decodeBitmapWithOptions(options); calculateBitmap(options,reqWidth,reqHeight); Bitmap bitmap = decodeBitmapWithOptions(options); deleteFile(); return bitmap; } public abstract void deleteFile(); private void calculateBitmap(BitmapFactory.Options options, int reqWidth, int reqHeight) { int width = options.outWidth; int height = options.outHeight; //图片缩放比 int inSampleSizeX = 1; if (width > reqHeight || height > reqHeight){ int widthSample = Math.round((float)width/(float)reqWidth); int heightSample = Math.round((float)height/(float)reqHeight); inSampleSizeX = Math.max(widthSample,heightSample); } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSizeX; /** * bitmap是8888还是565编码,后者内存占用相当于前者一半,前者显示效果要好一点点,但两者效果不会差太多 */ options.inPreferredConfig = Bitmap.Config.RGB_565; options.inPurgeable = true; options.inInputShareable = true; } protected abstract Bitmap decodeBitmapWithOptions(BitmapFactory.Options options); }
package com.example.hp.legendaryquiz; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //* This code initializes the score variable*// int score; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //* The following holds instances of all legendaryQuiz valid data entry points*// final EditText nameField = (EditText) findViewById(R.id.name_field); final EditText ngr = (EditText) findViewById(R.id.naija_capital); final EditText rus = (EditText) findViewById(R.id.russia_capital); final RadioGroup rg1 = (RadioGroup) findViewById(R.id.rg1); final RadioGroup rg2 = (RadioGroup) findViewById(R.id.rg2); final RadioGroup rg3 = (RadioGroup) findViewById(R.id.rg3); final CheckBox nig = (CheckBox) findViewById(R.id.naija); final CheckBox egy = (CheckBox) findViewById(R.id.egypt); final CheckBox eth = (CheckBox) findViewById(R.id.ethiopia); final CheckBox ghn = (CheckBox) findViewById(R.id.ghana); final CheckBox cristiano = (CheckBox) findViewById(R.id.cristiano); final CheckBox roberto = (CheckBox) findViewById(R.id.baggio); final CheckBox ronaldh = (CheckBox) findViewById(R.id.ronaldinho); final CheckBox lionel = (CheckBox) findViewById(R.id.messi); //* This line of code identifies, intializes and holds an instance of the of the reset button*// Button btn = (Button) findViewById(R.id.reset); //* This method call rests all data entry points on legendaryQuiz *// btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // The following lines resets every valid data interaction points on LegendaryQuiz App**// nameField.setText(""); ngr.getText().clear(); rus.setText(""); rg1.clearCheck(); rg2.clearCheck(); rg3.clearCheck(); nig.setChecked(false); egy.setChecked(false); eth.setChecked(false); ghn.setChecked(false); cristiano.setChecked(false); roberto.setChecked(false); ronaldh.setChecked(false); lionel.setChecked(false); score = 0; display("Attempt all Questions before You Submit"); } }); } /*** This Method Displays Text(student's name and Total score) on TextView**/ public void display(String message) { TextView gradeTextView = (TextView) findViewById(R.id.grade_view); gradeTextView.setText(message); } /*** This Method is called when submit button is clicked**/ public void submit(View view) { EditText nameField = (EditText) findViewById(R.id.name_field); String name = nameField.getText().toString(); EditText ngr = (EditText) findViewById(R.id.naija_capital); String ngrCap = ngr.getText().toString().trim(); EditText rus = (EditText) findViewById(R.id.russia_capital); String rusCap = rus.getText().toString().trim(); CheckBox lionel = (CheckBox) findViewById(R.id.messi); Boolean lionelMessi = lionel.isChecked(); CheckBox cristiano = (CheckBox) findViewById(R.id.cristiano); Boolean cristianoRonaldo = cristiano.isChecked(); CheckBox ronaldh = (CheckBox) findViewById(R.id.ronaldinho); Boolean ronaldinho = cristiano.isChecked(); CheckBox nig = (CheckBox) findViewById(R.id.naija); Boolean abj = nig.isChecked(); CheckBox egy = (CheckBox) findViewById(R.id.egypt); Boolean car = egy.isChecked(); CheckBox eth = (CheckBox) findViewById(R.id.ethiopia); Boolean drs = eth.isChecked(); CheckBox ghn = (CheckBox) findViewById(R.id.ghana); Boolean acc = ghn.isChecked(); name = "Name: " + name + "\nFinal Score: " + calculateGrade(abj, acc, ngrCap, rusCap, cristianoRonaldo, lionelMessi, ronaldinho); Toast.makeText(this, name, Toast.LENGTH_LONG).show(); display(name); score = 0; } //** This method aggregates all scores obtainable on legendaryQuiz**// private int calculateGrade(Boolean n, Boolean g, String ngrCap, String rusCap, Boolean cr7, boolean lio, boolean ron) { CheckBox nig = (CheckBox) findViewById(R.id.naija); Boolean abj = nig.isChecked(); CheckBox ghn = (CheckBox) findViewById(R.id.ghana); Boolean acc = ghn.isChecked(); CheckBox egy = (CheckBox) findViewById(R.id.egypt); Boolean car = egy.isChecked(); CheckBox eth = (CheckBox) findViewById(R.id.ethiopia); Boolean drs = eth.isChecked(); if (abj == true && acc == true && !car == true && !drs == true ) { score = score + 6; } else if (car == true) { score = score - 5; } else if (drs == true) { score = score - 5; } if (ngrCap.equalsIgnoreCase("Abuja")) { score = score + 10; } if (rusCap.equalsIgnoreCase("Moscow")) { score = score + 10; } CheckBox cristiano = (CheckBox) findViewById(R.id.cristiano); Boolean cristianoRonaldo = cristiano.isChecked(); CheckBox lionel = (CheckBox) findViewById(R.id.messi); Boolean lionelMessi = lionel.isChecked(); CheckBox ronaldh = (CheckBox) findViewById(R.id.ronaldinho); Boolean ronaldinho = cristiano.isChecked(); CheckBox roberto = (CheckBox) findViewById(R.id.baggio); Boolean robertoBaggio = roberto.isChecked(); if (cristianoRonaldo == true && lionelMessi == true && ronaldinho == true && !robertoBaggio == true) { score = score + 9; } else if (robertoBaggio == true) { score = score - 5; } RadioButton uk = (RadioButton) findViewById(R.id.elizabeth); boolean ukMonarch = uk.isChecked(); if (ukMonarch == true) { score = score + 5; } RadioButton newDeal = (RadioButton) findViewById(R.id.roosevelt); boolean americanNewDeal = newDeal.isChecked(); if (americanNewDeal == true) { score = score + 5; } RadioButton president = (RadioButton) findViewById(R.id.azikiwe); boolean firstPresident = president.isChecked(); if (firstPresident == true) { score = score + 5; } if (score > 50) { Toast.makeText(this, "You should RESET the Quiz", Toast.LENGTH_SHORT).show(); score = 0; } return score; } }
package uk.co.probablyfine.inject; class MultipleLevelDependencyClass { private final InnerTwo innerTwo; static class InnerOne { public InnerOne() {} public String say() { return "Hello One"; } } static class InnerTwo { private final InnerOne innerOne; public InnerTwo(InnerOne innerOne) { this.innerOne = innerOne; } public String say() { return this.innerOne.say() + ", World Two!"; } } public MultipleLevelDependencyClass(InnerTwo innerTwo) { this.innerTwo = innerTwo; } public String say() { return this.innerTwo.say(); } }
package com.company.treesandgraphs; import java.util.*; public class RouteFinder { /* Cracking the coding interview question 4.1 - Route Between Nodes Given a directed graph, design an algorithm to find out whether there is a route between two nodes. */ /* Response & Reasoning: As I see it, this could be approached as a depth first search, or a breadth first search. This will depend on the general structure of the graph, i.e. if we have a very deep graph, DFS may be best, if we know that nodes will have a very large number of neighbors, BFS may be memory expensive. Here I'll do BFS first. */ public static boolean routeBetweenBfs(Node start, Node end){ Set<Node> visitedNodes = new HashSet<Node>(); visitedNodes.add(start); LinkedList<Node> nodesToVisit = new LinkedList<Node>(); for(Node neighbor : start.adjacentNodes){ nodesToVisit.add(neighbor); } while(!nodesToVisit.isEmpty()){ Node visiting = nodesToVisit.pop(); if(visiting.equals(end)){return true;} for(Node neighbor : visiting.adjacentNodes){ if(!visitedNodes.contains(neighbor)){ nodesToVisit.add(neighbor); } } } return false; } public static class Node{ int value; List<Node> adjacentNodes; public Node(int value, List<Node> neighbors){ this.value = value; this.adjacentNodes = neighbors; } public boolean equals(Node compare){ if(compare.value == this.value){ return true; } return false; } } }
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UserDao; import domain.User; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("name"); String password = request.getParameter("pass"); User user = new User(); user.setPassword(password); user.setUsername(username); String yanzhengma = request.getParameter("yanzhengma"); UserDao dao = new UserDao(); dao.login(user, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package Action; import Service.accessRecord.AccessRecord; import Service.building.Room; import Service.pay.Pay; import Service.user.Manager; import Service.user.Student; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet(name = "insertPay",urlPatterns = "/insertPay") public class insertPay extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码格式和参数 response.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8"); //获取前端数据 HttpSession httpSession = request.getSession(); // Manager manager = (Manager) httpSession.getAttribute("aManager"); Student student = (Student) httpSession.getAttribute("aStudent"); Pay pay = new Pay(); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); pay.setBuildingID(student.getBuildingId()); pay.setRoomID(student.getRoomId()); pay.setCost(Float.parseFloat(request.getParameter("cost"))); pay.setPayType(request.getParameter("payType")); pay.setPayDate(format.format(new Date())); //将数据存入数据库 String state = ""; if(Pay.insertPay(pay)) { state = "1"; } else { state = "0"; } Room.changeBanlance(student,pay.getPayType(),pay.getCost()); //返回相应数据 JSONObject respJson = new JSONObject(); respJson.put("state",state); response.getOutputStream().write(respJson.toString().getBytes("UTF-8")); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
package fr.utt.if26.memoria; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import static android.content.Context.MODE_PRIVATE; class Memory { private static final int MAX_SAVES = 5; public static final int DEFAULT_CARDS_AMOUNT = 12; private static Memory instance; private Context context; private Memory(Context ctx0) { this.context = ctx0; } public static Memory getInstance(Context ctx0) { if( Memory.instance == null ) Memory.instance = new Memory(ctx0); else Memory.instance.setContext(ctx0); return Memory.instance; } public void setContext(Context c) { this.context = c; } public void setNbCartes(int nbCartes) { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("nbCartes", nbCartes); editor.commit(); } public int getNbCartes() { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); int nbCartes; try { nbCartes = sharedPref.getInt("nbCartes", Memory.DEFAULT_CARDS_AMOUNT); } catch( ClassCastException e ) { nbCartes = Memory.DEFAULT_CARDS_AMOUNT; } return nbCartes; } public void toggleSounds(boolean flag) { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean("Sounds", flag); editor.commit(); } public boolean areSoundsOn() { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); boolean sounds; try { sounds = sharedPref.getBoolean("Sounds", true); } catch( ClassCastException e ) { sounds = true; } return sounds; } public void toggleMusic(boolean flag) { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean("Music", flag); editor.commit(); } public boolean isMusicOn() { SharedPreferences sharedPref = this.context.getSharedPreferences("Options", MODE_PRIVATE); boolean music; try { music = sharedPref.getBoolean("Music", true); } catch( ClassCastException e ) { music=true; } return music; } }
import gov.nih.mipav.plugins.PlugInGeneric; public class PlugInConvertToByteNIFTI implements PlugInGeneric { @Override public void run() { // TODO Auto-generated method stub new PlugInDialogConvertToByteNIFTI(true); } }
package a3.test; import aiantwars.EAction; import aiantwars.EAntType; import a3.algorithm.model.Node; import org.junit.Test; import static org.junit.Assert.*; import a3.utility.Calc; /** * * @author Tobias */ public class CalcTest { @Test public void GetMovementActionTest() { int currentDirection = 1; int direction = 2; EAction movementAction = Calc.getMovementAction(currentDirection, direction, true); assertEquals(EAction.TurnRight, movementAction); currentDirection = 4; direction = 2; movementAction = Calc.getMovementAction(currentDirection, direction, true); assertEquals(EAction.MoveBackward, movementAction); currentDirection = 3; direction = 2; movementAction = Calc.getMovementAction(currentDirection, direction, true); assertEquals(EAction.TurnLeft, movementAction); } @Test public void GetMovementCostTest() { int turnLeft = Calc.getMovementCost(EAction.TurnLeft, EAntType.QUEEN, true); int turnRight = Calc.getMovementCost(EAction.TurnRight, EAntType.QUEEN, true); int moveBackward = Calc.getMovementCost(EAction.MoveBackward, EAntType.QUEEN, true); int moveForward = Calc.getMovementCost(EAction.MoveForward, EAntType.QUEEN, true); assertEquals(5, turnLeft); assertEquals(5, turnRight); assertEquals(4, moveBackward); assertEquals(3, moveForward); } @Test public void getMovementDirectionTest() { Node parent = new Node(2, 3, 0); Node child = new Node(1, 3, -1); int direction = Calc.getMovementDirection(parent, child); assertEquals(3, direction); parent = new Node(2, 3, 0); child = new Node(2, 4, -1); direction = Calc.getMovementDirection(parent, child); assertEquals(0, direction); parent = new Node(2, 3, 0); child = new Node(3, 3, -1); direction = Calc.getMovementDirection(parent, child); assertEquals(1, direction); parent = new Node(2, 3, 0); child = new Node(2, 2, -1); direction = Calc.getMovementDirection(parent, child); assertEquals(2, direction); } }
package ru.cft.focusstart.task2; public enum FiguresType { CIRCLE, RECTANGLE, TRIANGLE; @Override public String toString() { switch(this) { case CIRCLE: return "Круг"; case RECTANGLE: return "Прямоугольник"; case TRIANGLE: return "Треугольник"; default: throw new IllegalArgumentException(); } } }
/* * Copyright 2002-2017 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.core.style; import org.springframework.lang.Nullable; /** * A strategy interface for pretty-printing {@code toString()} methods. * Encapsulates the print algorithms; some other object such as a builder * should provide the workflow. * * @author Keith Donald * @since 1.2.2 */ public interface ToStringStyler { /** * Style a {@code toString()}'ed object before its fields are styled. * @param buffer the buffer to print to * @param obj the object to style */ void styleStart(StringBuilder buffer, Object obj); /** * Style a {@code toString()}'ed object after it's fields are styled. * @param buffer the buffer to print to * @param obj the object to style */ void styleEnd(StringBuilder buffer, Object obj); /** * Style a field value as a string. * @param buffer the buffer to print to * @param fieldName the name of the field * @param value the field value */ void styleField(StringBuilder buffer, String fieldName, @Nullable Object value); /** * Style the given value. * @param buffer the buffer to print to * @param value the field value */ void styleValue(StringBuilder buffer, Object value); /** * Style the field separator. * @param buffer the buffer to print to */ void styleFieldSeparator(StringBuilder buffer); }
package com.example.game_set_match; import android.util.Log; import androidx.annotation.NonNull; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static android.content.ContentValues.TAG; public class Game_type { private List<User> listOfUsers; public Game_type(String doc, FirebaseFirestore db){ //if (db.collection("GameType").document(doc).get()) listOfUsers = (List<User>) db.collection("GameType").document(doc).get(); db.collection("GameType").document(doc).set(this); } public void addUser(User u){ listOfUsers.add(u); } public void deleteUser(User u){ listOfUsers.remove(u); } public List<User> getListOfUsers(){return listOfUsers;} }
package myshop.mapper; import java.util.Date; import org.apache.ibatis.annotations.Param; import myshop.model.User; public interface UserMapper { void register(@Param("username") String username, @Param("password") String encodedPassword); User findOneByUsername(String username); void updateLastLoginTime(@Param("id")Long id, @Param("date")Date date); }
package com.newbig.im.common.utils; import lombok.Data; import lombok.Getter; import java.io.Serializable; import java.util.concurrent.atomic.AtomicReference; public class IntervalSequencer { private final long MASK; private final long INTERVAL; private final AtomicReference<TimestampedLong> updater; public IntervalSequencer(long mask, IntervalType intervalType) { MASK = mask; INTERVAL = (null == intervalType ? IntervalType.MILLISECOND : intervalType).getInterval(); TimestampedLong initValue = new TimestampedLong(getTime(), 0); updater = new AtomicReference<>(initValue); } public IntervalSequencer(long mask) { this(mask, IntervalType.MILLISECOND); } public IntervalSequencer() { this(Long.MAX_VALUE + 1); } private long getTime() { return System.currentTimeMillis() / INTERVAL; } public long next() { return nextStamped().value; } public TimestampedLong nextStamped() { return updater.updateAndGet(this::next); } private TimestampedLong next(TimestampedLong prev) { long seq = prev.getValue(); long prevTs = prev.getTimestamp(); long ts = getTime(); if (ts == prevTs) { seq = (seq + 1) & MASK; while (0 == seq && (ts = getTime()) == prevTs) ; // wait to next interval } else { seq = 0; } return new TimestampedLong(ts, seq); } static enum IntervalType { MILLISECOND(1), SECOND(1000), MINUTE(60 * 1000), HOUR(60 * 60 * 1000), DAY(24 * 60 * 60 * 1000), WEEK(7 * 24 * 60 * 60 * 1000); @Getter private int interval; private IntervalType(int milliseconds) { interval = milliseconds; } } @Data static class TimestampedLong implements Serializable { private static final long serialVersionUID = 1L; private final long timestamp; private final long value; private TimestampedLong(long timestamp, long value) { this.timestamp = timestamp; this.value = value; } } }
package br.com.salon.carine.lima.services; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.salon.carine.lima.converters.ConvertersCarrinho; import br.com.salon.carine.lima.converters.ConvertersServico; import br.com.salon.carine.lima.dto.ServicoDTO; import br.com.salon.carine.lima.dto.ServicoItemCarrinhoDTO; import br.com.salon.carine.lima.models.Carrinho; import br.com.salon.carine.lima.models.Servico; import br.com.salon.carine.lima.models.ServicoItemCarrinho; @Service public class CarrinhoService { @Autowired private Carrinho carrinho; public List<ServicoItemCarrinhoDTO> getServicosCarrinho(){ Map<ServicoItemCarrinho, Integer> mapServicosCarrinho = carrinho.getServicos(); List<ServicoItemCarrinhoDTO> listServicosCarrinho = ConvertersCarrinho. deMapServicoItemCarrinhoParaListServicoItemCarrinhoDTO(mapServicosCarrinho); calcularPrecoTotalPorItem(listServicosCarrinho); return listServicosCarrinho; } private void calcularPrecoTotalPorItem(List<ServicoItemCarrinhoDTO> listServicosCarrinho) { listServicosCarrinho.forEach((servicoItemCarrinhoDTO) -> servicoItemCarrinhoDTO.setPrecoTotal(carrinho.getTotalUnidadeServicoCarrinho(new ServicoItemCarrinho( ConvertersServico.deServicoDTOparaServico( servicoItemCarrinhoDTO.getServicoDTO())))) ); } public ServicoItemCarrinhoDTO addServicoCarrinho(ServicoDTO servicoDTO) { Servico servico = ConvertersServico.deServicoDTOparaServico(servicoDTO); ServicoItemCarrinho servicoAdicionadoCarrinho = new ServicoItemCarrinho(); servicoAdicionadoCarrinho.setServico(servico); servicoAdicionadoCarrinho.setPrecoAtual(servico.getPreco()); ServicoItemCarrinhoDTO itemAdicionado = carrinho.adicionarItemCarrinho(servicoAdicionadoCarrinho); return itemAdicionado; } public ServicoItemCarrinhoDTO removerItemCarrinho(ServicoDTO servicoDTO){ Servico servico = ConvertersServico.deServicoDTOparaServico(servicoDTO); ServicoItemCarrinho servicoRemovidoCarrinho = new ServicoItemCarrinho(); servicoRemovidoCarrinho.setServico(servico); ServicoItemCarrinhoDTO itemRemovido = carrinho.removerUnidadeItemCarrinho(servicoRemovidoCarrinho); return itemRemovido; } public boolean removerServicoCarrinho(ServicoDTO servicoDTO) { Servico servico = ConvertersServico.deServicoDTOparaServico(servicoDTO); ServicoItemCarrinho servicoItemCarrinho = new ServicoItemCarrinho(); servicoItemCarrinho.setServico(servico); boolean removido = carrinho.removerItemCarrinho(servicoItemCarrinho); return removido; } public Integer getQuantidadeTotalItensCarrinho() { return carrinho.getTotalUnidadeItemCarrinho(); } public Integer getQuantidadePorItemCarrinho(ServicoItemCarrinho item) { return carrinho.getQuantidadeItemCarrinho(item); } public void esvaziarCarrinho() { this.carrinho.esvaziarCarrinho(); } public BigDecimal getValorTotalPorServicoCarrinho(ServicoItemCarrinho item) { return this.carrinho.getTotalUnidadeServicoCarrinho(item); } public BigDecimal getValorTotalCarrinho() { return carrinho.getPrecoTotalCarrinho(); } public List<ServicoItemCarrinhoDTO> finalizarAtendimentoItensCarrinho() { List<ServicoItemCarrinhoDTO> servicosCarrinho = getServicosCarrinho(); return servicosCarrinho; } }
package sop.vo; import java.util.List; import sop.persistence.beans.CustAttn; /** * @Author: LCF * @Date: 2020/1/9 11:42 * @Package: sop.vo */ public class OfferSheetCombos { private List<TxnVo> txns; private List<CustomerVo> customers; private List<CustAttn> custAttns; public List<TxnVo> getTxns() { return txns; } public void setTxns(List<TxnVo> txns) { this.txns = txns; } public List<CustomerVo> getCustomers() { return customers; } public void setCustomers(List<CustomerVo> customers) { this.customers = customers; } public List<CustAttn> getCustAttns() { return custAttns; } public void setCustAttns(List<CustAttn> custAttns) { this.custAttns = custAttns; } }
package com.tessoft.nearhere.activities; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.tessoft.common.Constants; import com.tessoft.common.Util; import com.tessoft.domain.APIResponse; import com.tessoft.nearhere.LocationService; import com.tessoft.nearhere.NearhereApplication; import com.tessoft.nearhere.R; import org.codehaus.jackson.type.TypeReference; import java.util.HashMap; public class ShareRealtimeMyLocationActivity extends BaseActivity implements OnMapReadyCallback , View.OnClickListener{ int ZoomLevel = 14; @Override protected void onCreate(Bundle savedInstanceState) { try { super.onCreate(savedInstanceState); setContentView(R.layout.activity_share_my_realtime_location); setTitle("내 위치 공유"); findViewById(R.id.btnRefresh).setVisibility(ViewGroup.GONE); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); Button btnShare = (Button) findViewById(R.id.btnShare); btnShare.setOnClickListener(this); if ( NearhereApplication.bLocationServiceExecuting && !Util.isEmptyString( NearhereApplication.strRealtimeLocationID ) ) { btnShare.setText("종료하기"); TextView txtURL = (TextView) findViewById(R.id.txtURL); txtURL.setVisibility(ViewGroup.VISIBLE); txtURL.setText(Constants.getServerURL() + "/ul.do?ID=" + java.net.URLEncoder.encode( NearhereApplication.strRealtimeLocationID, "utf-8")); } } catch( Exception ex ) { application.catchException(this, ex); } } @Override public void onMapReady(GoogleMap map ) { // TODO Auto-generated method stub try { double latitude = Double.parseDouble(NearhereApplication.latitude); double longitude = Double.parseDouble(NearhereApplication.longitude); LatLng location = new LatLng( latitude , longitude); CameraUpdate center= CameraUpdateFactory.newLatLng( location ); map.moveCamera(center); CameraUpdate zoom= CameraUpdateFactory.zoomTo(ZoomLevel); map.animateCamera(zoom); map.setMyLocationEnabled(true); } catch( Exception ex ) { application.catchException(this, ex); } } public void shareURL(View v ) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, ((TextView)v).getText()); sendIntent.setType("text/plain"); startActivity(sendIntent); } @Override public void onClick(View v) { try { Button btn = (Button) v; if ( v.getId() == R.id.btnShare && "공유하기".equals(btn.getText()) ) { HashMap hash = new HashMap(); hash.put("userID", application.getLoginUser().getUserID()); sendHttp("/location/getNewLocation.do", mapper.writeValueAsString(hash), Constants.HTTP_GET_NEW_LOCATION); btn.setText("종료하기"); } else if ( v.getId() == R.id.btnShare && "종료하기".equals( btn.getText()) ) { Intent intent = new Intent( getApplicationContext(), LocationService.class ); stopService(intent); btn.setText("공유하기"); if ( !Util.isEmptyString( NearhereApplication.strRealtimeLocationID ) ) { HashMap hash = new HashMap(); hash.put("locationID", NearhereApplication.strRealtimeLocationID); sendHttp("/location/finishLocationTracking.do", mapper.writeValueAsString(hash), Constants.HTTP_FINISH_LOCATION_TRACKING); } } } catch( Exception ex ) { } } @Override public void doPostTransaction(int requestCode, Object result) { try { if ( Constants.FAIL.equals(result) ) { showOKDialog("통신중 오류가 발생했습니다.\r\n다시 시도해 주십시오.", null); return; } super.doPostTransaction(requestCode, result); APIResponse response = mapper.readValue(result.toString(), new TypeReference<APIResponse>(){}); if ( "0000".equals( response.getResCode() ) ) { if ( requestCode == Constants.HTTP_GET_NEW_LOCATION ) { String userString = mapper.writeValueAsString(response.getData()); HashMap data = mapper.readValue(userString, new TypeReference<HashMap>() {}); TextView txtURL = (TextView) findViewById(R.id.txtURL); txtURL.setVisibility(ViewGroup.VISIBLE); NearhereApplication.strRealtimeLocationID = data.get("locationID").toString(); txtURL.setText(Constants.getServerURL() + "/ul.do?ID=" + java.net.URLEncoder.encode( NearhereApplication.strRealtimeLocationID, "utf-8")); Intent intent = new Intent( getApplicationContext(), LocationService.class ); intent.putExtra("locationID", NearhereApplication.strRealtimeLocationID); startService(intent); } else if ( requestCode == Constants.HTTP_FINISH_LOCATION_TRACKING ) { findViewById(R.id.txtURL).setVisibility(ViewGroup.GONE); NearhereApplication.strRealtimeLocationID = ""; } } } catch( Exception ex ) { catchException(this, ex ); } } }
package com.meehoo.biz.core.basic.vo.security; import com.meehoo.biz.common.util.BaseUtil; import com.meehoo.biz.core.basic.domain.security.Organization; import com.meehoo.biz.core.basic.vo.common.AddressEntityVO; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; /** * Created by CZ on 2018/1/19. */ @Setter @Getter @NoArgsConstructor @Accessors(chain = true) public class OrganizationVO extends AddressEntityVO { private String orgName; /** * 机构类型 */ private String proOrgType; /** * 是否系统预设 * 0 否 * 1 是 */ private int isDefault; private String isDefaultShow; private String parentOrgId; private String parentOrgName; private String contactPerson; // 联系人 private String contactPhone; // 联系电话 private String description; public OrganizationVO(Organization organization) { super(organization); this.orgName=organization.getName(); this.contactPerson = organization.getContactPerson(); this.contactPhone = organization.getContactPhone(); this.address = organization.getAddress(); this.description = organization.getDescription(); this.isDefault = organization.getIsDefault(); this.isDefaultShow = this.isDefault == Organization.ISDefault_YES ? "是" : "否"; if (organization.getParentOrg()!=null){ this.parentOrgId = organization.getParentOrg().getId(); this.parentOrgName =organization.getParentOrg().getName(); } this.proOrgType = organization.getProOrgType(); } }
package co.company.spring.dao; import lombok.Data; @Data public class Depts { String departmentId; String departmentName; }
package TD1.TD1; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; /** * Unit test for simple App. */ public class PanierTest { @Test public void addItem() { final Panier p = new Panier(); final Item carrot = new Item("Carrot", 2.5); p.add(carrot, 1); Assert.assertEquals(p.getContenu(), new HashMap<Item, Integer>(){{ put(carrot, 1); }}); } @Test public void computePriceWithoutTaxes() { final Panier p = new Panier(); final Item carrot = new Item("Carrot", 2.5); p.add(carrot, 1); p.add(new Item("Apple", 1), 25); p.add(new Item("Banana 1kg, ", 5), 3); Assert.assertEquals(p.getPriceWithoutTaxes(), 42.5, 0.0001); } @Test public void computePriceWithTaxesFR() { final Panier p = new Panier(); final Item carrot = new Item("Carrot", 2.5); p.add(carrot, 1); p.add(new Item("Apple", 1), 25); p.add(new Item("Banana 1kg, ", 5), 3); Assert.assertEquals(p.getPriceWithTaxes(Country.France), 50.83, 0.0001); } @Test public void computePriceWithTaxesDE() { final Panier p = new Panier(); final Item carrot = new Item("Carrot", 2.5); p.add(carrot, 1); p.add(new Item("Apple", 1), 25); p.add(new Item("Banana 1kg, ", 5), 3); Assert.assertEquals(p.getPriceWithTaxes(Country.DE), 50.5749 , 0.0001); } @Test public void prixAveccReductionTest() { final Panier p = new Panier(); final Item carrot = new Item("Carrot", 2.5); p.add(carrot, 189); p.add(new Item("Apple", 56), 25); p.add(new Item("Banana 1kg, ", 9), 332); Assert.assertEquals(p.prixAvecReduction(), 4714.685, 0.0001); Assert.assertEquals(p.getPriceWithTaxes(Country.DK), 5893.35625, 0.0001); } }
package ua.training.model.entity.enums; /** * This is the enums of food intake per day * {@link ua.training.model.entity.RationComposition#foodIntake} * * @author Zakusylo Pavlo */ public enum FoodIntake { BREAKFAST("BREAKFAST"), DINNER("DINNER"), SUPPER("SUPPER"); private String value; FoodIntake(String value) { this.value = value; } public String getValue() { return value; } @Override public String toString() { return super.toString(); } }
package model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import configuration.TestConfig; public class CityFactory { public static List<City> generate() { if (TestConfig.CIRCLE_CITIES) { return generateCircle(TestConfig.NUM_CITIES); } List<City> cities = new ArrayList<City>(); City city = new City(60, 200); cities.add(city); City city2 = new City(180, 200); cities.add(city2); City city3 = new City(80, 180); cities.add(city3); City city4 = new City(140, 180); cities.add(city4); City city5 = new City(20, 160); cities.add(city5); City city6 = new City(100, 160); cities.add(city6); City city7 = new City(200, 160); cities.add(city7); City city8 = new City(140, 140); cities.add(city8); City city9 = new City(40, 120); cities.add(city9); City city10 = new City(100, 120); cities.add(city10); City city11 = new City(180, 100); cities.add(city11); City city12 = new City(60, 80); cities.add(city12); City city13 = new City(120, 80); cities.add(city13); City city14 = new City(180, 60); cities.add(city14); City city15 = new City(20, 40); cities.add(city15); City city16 = new City(100, 40); cities.add(city16); City city17 = new City(200, 40); cities.add(city17); City city18 = new City(20, 20); cities.add(city18); City city19 = new City(60, 20); cities.add(city19); City city20 = new City(160, 20); cities.add(city20); return cities; } public static List<City> generateCircle(int numCities) { int center = 100; int radius = 75; List<City> cities = new ArrayList<City>(); for (int i=0; i<numCities; i++) { double x = (center + radius * Math.cos(2 * Math.PI * i / numCities)); double y = (center + radius * Math.sin(2 * Math.PI * i / numCities)); City city = new City((int) x, (int) y); cities.add(city); } Collections.shuffle(cities); return cities; } }
package com.mydiaryapplication.userdiary.userdata; import com.mydiaryapplication.userdiary.validation.PasswordMatch; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import java.io.Serializable; @PasswordMatch public class UserData implements Serializable { @NotEmpty(message = "User Id can not be empty") private String userId; @NotEmpty(message = "First name can not be empty") private String firstName; @NotEmpty(message = "Last name can not be empty") private String lastName; @NotEmpty(message = "Email can not be empty") @Email(message = "please provide a valid email id") private String email; @NotEmpty(message = "Password can not be empty") private String password; @NotEmpty(message = "Confirm password can not be empty") private String confirmPassword; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } 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 getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } }
package kosta.student.test; import java.util.Scanner; import kosta.student.service.*; public class StudentManageTest { public static void main(String[] args) { // 1. 학생정보 추가(번호/이름/주소/성별/반/키/나이/학년) // 2. 성적정보 추가(번호입력-> 성적입력 // 3. 학생 리스트 출력 // 3.1 이름순 오름차순 정렬 // 3.2 성적순 내림차순 정렬 // 3.3 반별 리스트 출력 // 4. 학생 정보 검색 // 4.1 주소검색 // 4.2 이름검색 // 5. 통계 // 5.1 성별별 그룹핑 // 5.2 반별 성적 평균 // 5.3 주소별 성적 평균 // 5.4 학년별 키 평균 // 0. 종료 Scanner scan = new Scanner(System.in); StudentService ss = null; while(true){ System.out.println("1.학생정보 추가, 2.성적정보 추가, 3.학생 리스트 출력, 4.학생 정보 검색, 5.통계, 0.종료"); switch (scan.nextInt()) { case 1: ss = new StudentService1(); ss.start(scan); break; case 2: ss = new StudentService2(); ss.start(scan); break; case 3: ss = new StudentService3(); ss.start(scan); break; case 4: ss = new StudentService4(); ss.start(scan); break; case 5: ss = new StudentService5(); ss.start(scan); break; case 0: System.exit(0); break; default: break; } } } }
package libraryproject.service; import libraryproject.domain.book.*; import libraryproject.domain.user.EBookEntry; import libraryproject.domain.user.User; import libraryproject.repositories.BookRepository; import libraryproject.repositories.QueueRepository; import libraryproject.repositories.UserRepository; import java.time.LocalDate; public class BorrowController { private AuthenticationController authenticationController; QueueRepository queueRepository = new QueueRepository(); public BorrowController(AuthenticationController authenticationController) { this.authenticationController = authenticationController; } public String borrowPaperBook(User user, PaperBook book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } else if (user == null) { throw new IllegalArgumentException("User can not be null!"); } else if (!authenticationController.doesUserHaveToken(user)) { throw new IllegalArgumentException("User is not Registered"); } else if (book instanceof PaperBook) { if ((isBookAvailableForBorrowing(book)) || (QueueRepository.getQueueByBook(book).hasAccess(user))) { UserRepository.getUserProfile(user).getBorrowedBooks().add(new BorrowedBook(book, LocalDate.now(), LocalDate.now().plusDays(14))); bookAvailableCopiesUpdate(book, -1); return "\nThe book has been borrowed!"; } else { BorrowQueue borrowQueue = QueueRepository.getQueueByBook(book); borrowQueue.addUserToQueue(UserRepository.getUserProfile(user)); return "\nAdded to Queue. The book will be available at " + borrowQueue.getNextAvailableDate(); } } return "The book is not a PaperBook"; } public void returnPaperBook(User user, PaperBook book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } else if (user == null) { throw new IllegalArgumentException("User can not be null!"); } else if (!authenticationController.doesUserHaveToken(user)) { throw new IllegalArgumentException("User is not Registered"); }else if (book instanceof PaperBook) { BorrowedBook bookToReturn = null; for(BorrowedBook borrowedBooks : UserRepository.getUserProfile(user).getBorrowedBooks()) { if (borrowedBooks.getBook().equals(book)) { bookToReturn = borrowedBooks; } else { throw new IllegalArgumentException("Book is not borrowed by this user!"); } } QueueRepository.getQueueByBook(book).pullFromQueue(); UserRepository.getUserProfile(user).addHistoryPaperBookEntry(bookToReturn); UserRepository.getUserProfile(user).getBorrowedBooks().remove(bookToReturn); bookAvailableCopiesUpdate(book, 1); } } public String viewEbook(User user, EBook book) { if (book instanceof EBook) { if (user == null) { throw new IllegalArgumentException("User can not be null!"); } else if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } else if (!authenticationController.doesUserHaveToken(user)) { throw new IllegalArgumentException("User is not Registered"); } EBook ebook = (EBook)BookRepository.getBook(book); if((ebook.isDownloadable())) { UserRepository.getUserProfile(user).getHistory().add(new EBookEntry(book, LocalDate.now())); return ebook.getDownloadLink(); } else { UserRepository.getUserProfile(user).addHistoryEBookEntry(book); return ebook.getReadLink(); } } return "Book not available!"; } public boolean isBookBorrowed(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } return BookRepository.getCurrentlyBorrowedBooks().contains(book); } public boolean isBookAvailableForBorrowing(Book book) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } if(book instanceof PaperBook) { if (isBookBorrowed(book)) { for (Book books : BookRepository.getCurrentlyBorrowedBooks()) { if (books.equals(book)) { if((((PaperBook)books).getAvailableCopies()) > 0) { return true; } } } } else if (!isBookBorrowed(book)) { return true; } } return false; } public void bookAvailableCopiesUpdate(PaperBook book, int set) { if (book == null) { throw new IllegalArgumentException("Book can not be null!"); } if (set == 1) { ((PaperBook) BookRepository.getBook(book)).addCopy(); } else if (set == -1) { ((PaperBook) BookRepository.getBook(book)).extractCopy(); } // PaperBook bookToUpdate = (PaperBook)BookRepository.getBook(book); // bookToUpdate.setAvailableCopies((bookToUpdate.getAvailableCopies() + set));} } }
package com.web.jdbc; import java.sql.*; abstract public class JDBC { private String connStr = null; private Connection conn = null; private String server; private int port; private String database; private String user; private String password; public JDBC(String serverIP, int serverPort, String user, String password) { this.server = serverIP; this.port = serverPort; this.user = user; this.password = password; } public JDBC(String server, int port, String database, String user, String password) { this.server = server; this.port = port; this.database = database; this.user = user; this.password = password; } public String getServer() { return server; } public int getPort() { return port; } public String getDatabase() { return database; } public String getUser() { return user; } public String getPassword() { return password; } protected Connection getConn() { return conn; } protected void setConn(Connection conn) { this.conn = conn; } protected String getConnStr() { return connStr; } protected void setConnStr(String connStr) { this.connStr = connStr; } /** * default set auto commit is false * @return */ abstract public boolean createConnection(); /** * default set auto commit is false * @return */ abstract public boolean createConnection(String database); public void connectionClose() throws SQLException { this.conn.close(); } /** * Set MSSQL server Database Engine. * @param autoCommit : True is explicit transaction, false is implicit transaction * @throws SQLException */ public void setAutoCommit(boolean autoCommit) throws SQLException { this.conn.setAutoCommit(autoCommit); } /** * * @throws SQLException */ public void commit() throws SQLException { this.conn.commit(); } /** * * @throws SQLException */ public void rollback() throws SQLException { this.conn.rollback(); } /** * * @param sqlStr * @return ResultSet * @throws SQLException */ public ResultSet executeQuery(String sqlStr) throws SQLException { return conn.createStatement().executeQuery(sqlStr); } /** * * @param sqlStr * @return int * @throws SQLException */ public int executeUpdate(String sqlStr) throws SQLException { return conn.createStatement().executeUpdate(sqlStr); } }
package org.itachi.cms.action; import org.glassfish.jersey.server.mvc.Viewable; import org.itachi.cms.dto.AdmusergroupDTO; import org.itachi.cms.dto.GroupRoleRelDTO; import org.itachi.cms.dto.PagerDTO; import org.itachi.cms.dto.RoleTreeDTO; import org.itachi.cms.repository.AdminUserGroupRepository; import org.itachi.cms.repository.GroupRoleRelRepository; import org.itachi.cms.repository.RoleRepository; import org.itachi.cms.util.StringUtil; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by itachi on 2017/3/18. * User: itachi * Date: 2017/3/18 * Time: 20:01 */ @Path("/admusergroup") public class AdmUserGroupAction extends BaseAction { @Autowired private AdminUserGroupRepository adminUserGroupRepository; @Autowired private GroupRoleRelRepository groupRoleRelRepository; @Autowired private RoleRepository roleRepository; /** * 进入管理员组管理页面 */ @GET @Path("/list") @Produces(MediaType.TEXT_HTML) public Viewable list() throws Exception { return new Viewable("/admusergroup/admUserGroupList"); } /** * 获取管理员组列表数据 */ @POST @Path("/gridlist") @Consumes("application/x-www-form-urlencoded") public Map<String, Object> gridlist(@FormParam("groupName") String groupName, @FormParam("page") int page, @FormParam("rows") int rows) throws Exception { PagerDTO pager = new PagerDTO(page, rows); Map<String, Object> map = new HashMap<String, Object>(); map.put("pager", pager); map.put("groupname", groupName); Map<String, Object> result = adminUserGroupRepository.findAdmUserGroup(map); return result; } /** * 进入添加页面 */ @GET @Path("/toadd") @Produces(MediaType.TEXT_HTML) public Viewable toadd() throws Exception { return new Viewable("/admusergroup/addAdmusergroup"); } /** * 添加管理员组 */ @POST @Path("/addadmusergroup") @Consumes("application/x-www-form-urlencoded") public String addadmusergroup(@FormParam("groupname") String groupname, @FormParam("describe") String describe, @FormParam("ids") String ids) throws Exception { if (!StringUtil.isNotNull(groupname)) { return "管理员组名称不能为空"; } if (!StringUtil.isMaxSize(groupname, 20)) { return "管理员组名称长度不能超过20个字符"; } if (!StringUtil.isNotNull(describe)) { return "描述信息不能为空"; } if (!StringUtil.isMaxSize(describe, 50)) { return "权限名称长度不能超过50个字符"; } if (!StringUtil.MinSize(ids)) { return "权限请至少选择一个"; } AdmusergroupDTO usergroupDTO = new AdmusergroupDTO(); usergroupDTO.setGroupname(groupname); usergroupDTO.setDes(describe); usergroupDTO.setIsdel(1); int num = adminUserGroupRepository.addUserGroup(usergroupDTO); if (num < 1) { return "添加失败"; } int[] gids; try { gids = StringUtil.strArrToIntArr(ids); } catch (Exception e) { return "ids不是数字,添加管理员组失败。"; } long newid = adminUserGroupRepository.findnewUGroupDTO(usergroupDTO); List<GroupRoleRelDTO> list = new ArrayList<GroupRoleRelDTO>(); for (int i = 0; i < gids.length; i++) { long gid = gids[i]; GroupRoleRelDTO groupRoleRelDTO = new GroupRoleRelDTO(); groupRoleRelDTO.setIsdel(1); groupRoleRelDTO.setGroupid(newid); groupRoleRelDTO.setRoleid(gid); list.add(groupRoleRelDTO); } num = groupRoleRelRepository.addUserGroupRels(list); if (num < 1) { return "出现异常,部分权限添加失败,请补充添加权限。"; } return SUCCESS; } /** * 进入修改管理员组页面 */ @GET @Path("/tomodify") @Produces(MediaType.TEXT_HTML) public Viewable tomodify(@QueryParam("admusergroupid") long id) throws Exception { AdmusergroupDTO admusergroupDTO = adminUserGroupRepository.admusergroupById(id); request.setAttribute("admusergroup", admusergroupDTO); return new Viewable("/admusergroup/modifyAdmusergroup"); } /** * 修改管理员组 */ @POST @Path("/modifyadmusergroup") @Consumes("application/x-www-form-urlencoded") public String modifyadmusergroup(@FormParam("id") long id, @FormParam("groupname") String groupname, @FormParam("describe") String describe, @FormParam("ids") String ids) throws Exception { if (!StringUtil.isNotNull(groupname)) { return "管理员组名称不能为空"; } if (!StringUtil.isMaxSize(groupname, 20)) { return "管理员组名称长度不能超过20个字符"; } if (!StringUtil.isNotNull(describe)) { return "描述信息不能为空"; } if (!StringUtil.isMaxSize(describe, 50)) { return "权限名称长度不能超过50个字符"; } if (!StringUtil.MinSize(ids)) { return "权限请至少选择一个"; } AdmusergroupDTO usergroupDTO = new AdmusergroupDTO(); usergroupDTO.setId(id); usergroupDTO.setGroupname(groupname); usergroupDTO.setDes(describe); usergroupDTO.setIsdel(1); int num = adminUserGroupRepository.updateUserGroup(usergroupDTO); if (num < 1) { return "修改失败"; } int[] gids; try { gids = StringUtil.strArrToIntArr(ids); } catch (Exception e) { return "ids不是数字,添加管理员组失败。"; } groupRoleRelRepository.delGroupRoleRel(id); List<GroupRoleRelDTO> list = new ArrayList<GroupRoleRelDTO>(); for (int i = 0; i < gids.length; i++) { long gid = gids[i]; GroupRoleRelDTO groupRoleRelDTO = new GroupRoleRelDTO(); groupRoleRelDTO.setIsdel(1); groupRoleRelDTO.setGroupid(id); groupRoleRelDTO.setRoleid(gid); list.add(groupRoleRelDTO); } groupRoleRelRepository.addUserGroupRels(list); return SUCCESS; } /** * 删除管理员组 */ @POST @Path("/delete") @Consumes("application/x-www-form-urlencoded") public String delete(@FormParam("ids") String ids) throws Exception { int[] gids; try { gids = StringUtil.strArrToIntArr(ids); } catch (Exception e) { return "ids不是数字,删除管理员组失败。"; } int num=0; num = adminUserGroupRepository.delUserGroup(gids); if (num < 1) { return "删除失败"; } num = groupRoleRelRepository.delGRoleRelList(gids); if (num < 1) { return "删除失败"; } return SUCCESS; } /** * 加载权限树(用于添加管理员组的时候选择权限) */ @POST @Path("/loadtreewithoutroot") @Consumes(MediaType.APPLICATION_JSON) public List<RoleTreeDTO> loadtreewithoutroot() throws Exception { List<RoleTreeDTO> list =null; list = roleRepository.listtree(null,false); return list; } /** * 加载权限树(用于修改管理员组的时候选择权限-添加时选择的权限在修改的时候需要选中) */ @POST @Path("/loadtreechecked") @Consumes("application/x-www-form-urlencoded") public List<RoleTreeDTO> loadtreechecked(@FormParam("admgroupuserid") long admgroupuserid) throws Exception { List<RoleTreeDTO> list =null; List<Long> roleids =null; try { roleids = groupRoleRelRepository.findroleid(admgroupuserid); }catch (Exception e){ } Map<String, Boolean> map = new HashMap<String, Boolean>(); if(roleids!=null&&roleids.size()>0){ for (Long roleid : roleids) { map.put(roleid + "", true); } } list = roleRepository.listtree(null,false); for (int i = 0, sies = list.size(); i < sies; i++) { if(map.containsKey(list.get(i).getId())) list.get(i).setChecked(true); } return list; } /* func (this *AdmUserGroupController) Loadtreechecked() { admgroupuserid, _ := this.GetInt64("admgroupuserid") roleIdMap := service.AdmUserGroupService.GetAllRoleByGroupId(admgroupuserid) //查询树结构不加载root节点 roles := service.RoleService.Listtree(false) if roleIdMap == nil { //展开一级目录 for i, role := range roles { if role.Pid == 0 { roles[i].Open = true } } } else { for i, role := range roles { if role.Pid == 0 { roles[i].Open = true } if _, ok := roleIdMap[role.Id]; ok { roles[i].Checked = true } } } this.jsonResult(roles) }*/ }
package codePlus.AGBasic1.dp; import java.util.*; public class DP_1463 { public static int[] d; public static int go(int n) { if (n == 1) { System.out.println("0을 뱉어낸다."); return 0; } //맨 처음 숫자를 입력했을 땐 이 조건문 통과x -> why? 배열의 모든 값이 모두 0으로 초기화 되어 있음 if (d[n] > 0) { System.out.println("n="+n+", d[n]="+d[n]); return d[n]; } //맨 처음 입력한 숫자가 여길 제일 먼저 들어가지 d[n] = go(n-1) + 1; System.out.println("n="+n); System.out.println("d["+n+"]="+d[n]); /* * for (int i : d) { System.out.print(d[i]+"-"); } */ for(int i=0; i<d.length; i++) { System.out.print("d["+i+"]="+d[i]+" "); } System.out.println(); //n=2 if (n%2 == 0) { int temp = go(n/2)+1; System.out.println(n+"temp= "+temp); if (d[n] > temp) { d[n] = temp; } } if (n%3 == 0) { int temp = go(n/3)+1; System.out.println("temp= "+temp); if (d[n] > temp) { d[n] = temp; } } return d[n]; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); d = new int[n+1]; //기본타입의 배열의 경우, 초기값 존재(int = 0, String = "") System.out.println("초기배열 상태"); /* * for (int i : d) { System.out.print(d[i]+" "+i); } */ for(int i=0; i<d.length; i++) { System.out.print("d["+i+"]="+d[i]+" "); } System.out.println(); System.out.println(go(n)); } }
package com.icogroup.baseprojectdatabinding.data.sections.movie; import com.icogroup.baseprojectdatabinding.data.model.Movie; import java.util.List; /** * Created by Ulises.harris on 6/1/16. */ public interface MoviesProvider { void getMovies(String search); interface MoviesDataOutput{ void setMovies(List<Movie> movies); void setError(String error); } }
package com.metoo.manage.seller.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.annotation.SecurityMapping; import com.metoo.core.domain.virtual.SysMap; import com.metoo.core.mv.JModelAndView; import com.metoo.core.query.support.IPageList; import com.metoo.core.tools.CommUtil; import com.metoo.core.tools.WebForm; import com.metoo.foundation.domain.Article; import com.metoo.foundation.domain.query.ArticleQueryObject; import com.metoo.foundation.service.IArticleService; import com.metoo.foundation.service.IStoreService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; /** * * <p> * Title: StoreNoticeAction.java * </p> * * <p> * Description: 商家后台店铺公告管理控制器 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-4-2 * * @version koala_b2b2c v2.0 2015版 */ @Controller public class StoreNoticeAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IStoreService storeService; @Autowired private IArticleService articleService; /** * 商家店铺公告列表 * * @param currentPage * @param orderBy * @param orderType * @param request * @param response * @return */ @SecurityMapping(title = "商家店铺公告列表", value = "/seller/store_notice.htm*", rtype = "seller", rname = "店内公告", rcode = "store_notice", rgroup = "我的店铺") @RequestMapping("/seller/store_notice.htm") public ModelAndView store_notice(HttpServletRequest request, HttpServletResponse response, String currentPage, String orderBy, String orderType) { ModelAndView mv = new JModelAndView( "user/default/sellercenter/store_notice.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); ArticleQueryObject qo = new ArticleQueryObject(currentPage, mv, orderBy, orderType); WebForm wf = new WebForm(); wf.toQueryPo(request, qo, Article.class, mv); qo.setOrderBy("addTime"); qo.setOrderType("desc"); qo.setPageSize(10); qo.addQuery("obj.type", new SysMap("type", "store"), "="); IPageList pList = this.articleService.list(qo); CommUtil.saveIPageList2ModelAndView("", "", null, pList, mv); return mv; } /** * 商家店铺公告详情 * * @param id * @return mv */ @SecurityMapping(title = "商家店铺公告详情", value = "/seller/store_notice_detail.htm*", rtype = "seller", rname = "店内公告", rcode = "store_notice", rgroup = "我的店铺") @RequestMapping("/seller/store_notice_detail.htm") public ModelAndView store_notice_detail(HttpServletRequest request, HttpServletResponse response, String id) { ModelAndView mv = new JModelAndView( "user/default/sellercenter/store_notice_detail.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 0, request, response); Article article = this.articleService .getObjById(CommUtil.null2Long(id)); mv.addObject("obj", article); return mv; } }
package com.github.vincedall.wenote; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class SelectionAdapter extends ArrayAdapter<ListItemsSelection> { private final Context context; private final ArrayList<ListItemsSelection> itemsArrayList; public SelectionAdapter(Context context, ArrayList<ListItemsSelection> itemsArrayList) { super(context, R.layout.list_view_selection, itemsArrayList); this.context = context; this.itemsArrayList = itemsArrayList; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.list_view_selection, parent, false); TextView title = (TextView) view.findViewById(R.id.item_title); title.setText(itemsArrayList.get(position).getTitle()); TextView date = (TextView) view.findViewById(R.id.item_date); date.setText(itemsArrayList.get(position).getDate()); date.setTextColor(Color.GRAY); if (itemsArrayList.get(position).getSelected() || itemsArrayList.get(position).getWasSelected()){ final ImageView image = view.findViewById(R.id.check); final int pos = position; image.setVisibility(View.VISIBLE); if (itemsArrayList.get(position).getWasSelected()){ image.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { itemsArrayList.get(pos).setWasSelected(false); Animation unexpand = AnimationUtils.loadAnimation(image.getContext(), R.anim.unexpand); image.startAnimation(unexpand); unexpand.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { image.setVisibility(View.INVISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); } @Override public void onViewDetachedFromWindow(View v) { } }); } if (!itemsArrayList.get(position).getAnimationPlayed()) { image.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() { @Override public void onViewAttachedToWindow(View v) { Animation expand = AnimationUtils.loadAnimation(image.getContext(), R.anim.expand); image.startAnimation(expand); itemsArrayList.get(pos).setAnimationPlayed(true); } @Override public void onViewDetachedFromWindow(View v) { } }); } } return view; } }
package com.gaoshin.cj.api; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import com.gaoshin.Api; public class CjApi extends Api{ private static final String token = "008edb2fc516166be40c3b9feeb3d0fd064c65ee316e1d2d012ebb5ab24aa774040f85d838d2b627f1b6ba862faaf5bbf21f053587e87daf97ce655a6dd09238a1/53a12140018432b9182837a268062a79eb73a893ab60cd1dea1ba826c3e96fd2a49261d256f422fa4aad77542f5a1e6b0dbe83115390269bf45fc515afa0ff59"; private static final String websiteId = "6194229"; public static void searchLink() { } public static String getString(String url) throws IOException { HttpResponse response = execute(url); InputStream stream = response.getEntity().getContent(); StringWriter sw = new StringWriter(); byte[] buff = new byte[8192]; while(true) { int len = stream.read(buff); if(len < 0) break; sw.write(new String(buff, 0, len)); } stream.close(); return sw.toString(); } public static LinkSearchResponse searchLinks(LinkSearchRequest req) throws Exception { String url = "https://link-search.api.cj.com/v2/link-search?" + req.toString(); HttpResponse response = execute(url); InputStream stream = response.getEntity().getContent(); JAXBContext ctx = JAXBContext.newInstance(LinkSearchResponse.class); Unmarshaller unm = ctx.createUnmarshaller(); LinkSearchResponse resp = (LinkSearchResponse) unm.unmarshal(stream); stream.close(); return resp; } public static void getCategories() throws IOException { String url = "https://support-services.api.cj.com/v2/categories?"; HttpResponse response = execute(url); InputStream stream = response.getEntity().getContent(); String string = IOUtils.toString(stream); System.out.println(string); } public static AdvertiserLookupResponse getAdvertisers(List<String> ids) throws IOException, JAXBException { String url = "https://advertiser-lookup.api.cj.com/v3/advertiser-lookup?advertiser-ids=" + ids.toString().replaceAll("[ \\[\\]]+", ""); HttpResponse response = execute(url); InputStream stream = response.getEntity().getContent(); JAXBContext ctx = JAXBContext.newInstance(AdvertiserLookupResponse.class); Unmarshaller unmarshaller = ctx.createUnmarshaller(); AdvertiserLookupResponse resp = (AdvertiserLookupResponse) unmarshaller.unmarshal(stream); stream.close(); return resp; } public static void main(String[] args) throws Exception { List<String> test = new ArrayList<String>(); test.add("1104648"); test.add("1813911"); test.add("1834639"); getAdvertisers(test); } public static void searchLinksTest() throws Exception { LinkSearchRequest req = new LinkSearchRequest(); req.setCategory("Handbags"); LinkSearchResponse response = searchLinks(req); JAXBContext ctx = JAXBContext.newInstance(LinkSearchResponse.class); Marshaller m = ctx.createMarshaller(); m.setProperty("jaxb.formatted.output", true); m.marshal(response, System.out); } }
public class person { int age; String name; double height; public person(int a, String n) { age = a; name = n; } public void getInfo(){ System.out.println("Navn: " + name + "\r\n Alder: " + age); } public static void main(String[] args) { } }
package com.example.compasso.controller; import com.example.compasso.model.City; import com.example.compasso.model.dto.CityDTO; import com.example.compasso.service.ICityService; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/city") public class CityController { @Autowired private ICityService iCityService; @PostMapping public ResponseEntity<City> insert(@RequestBody @Valid CityDTO cityDTO){ City city = new ModelMapper().map(cityDTO, City.class); return new ResponseEntity<>(iCityService.insert(city), HttpStatus.CREATED); } @GetMapping("/name/{name}") public ResponseEntity<Page<City>> findByName(@PathVariable String name, Pageable pageable){ return new ResponseEntity<>(iCityService.findByName(name, pageable), HttpStatus.OK); } @GetMapping("/state/{state}") public ResponseEntity<Page<City>> findByState(@PathVariable String state, Pageable pageable){ return new ResponseEntity<>(iCityService.findByState(state, pageable), HttpStatus.OK); } }
package com.xld.common.other; import java.util.Random; /** * 编号生成工具类 [去除相似的字母和数字] * @author xld */ public class CodeUtil { public static String createInvitationCode(int digitNumber) { StringBuffer invitationCode = new StringBuffer(); Random random = new Random(); String[] seed = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "3", "4", "5", "6", "7", "8", "9" }; for (int i = 0; i < digitNumber; i++) { int index = random.nextInt(seed.length); invitationCode.append(seed[index]); } return invitationCode.toString(); } }
package services; import model.Product; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Random; @Service public class ProductService { private List<Product> productList; ProductService(){ Product product1 = new Product("TV",getRandomNumberInRange(50,300)); Product product2 = new Product("Akwaruim",getRandomNumberInRange(50,300)); Product product3 = new Product("Szafa",getRandomNumberInRange(50,300)); Product product4 = new Product("Krzesło",getRandomNumberInRange(50,300)); Product product5 = new Product("Głośniki",getRandomNumberInRange(50,300)); productList = new ArrayList<>(); productList.add(product1); productList.add(product2); productList.add(product3); productList.add(product4); productList.add(product5); } public void showProduct(){ productList.forEach(System.out::println); } public static int getRandomNumberInRange(int min, int max) { Random r = new Random(); return r.ints(min, (max + 1)).limit(1).findFirst().getAsInt(); } public void addProduct(Product product){ productList.add(product); productList.forEach(System.out::println); } public List<Product> getProductList() { return productList; } public void setProductList(List<Product> productList) { this.productList = productList; } }
package com.tuyenmonkey.stackoverflowmvvm.ui.search.viewmodel; import com.tuyenmonkey.stackoverflowmvvm.entity.Question; import junit.framework.TestCase; /** * Created by Tiki on 2/23/16. */ public class QuestionViewModelTest extends TestCase { private Question mQuestion; private QuestionViewModel mViewModel; public void setUp() throws Exception { super.setUp(); mQuestion = new Question(); mViewModel = new QuestionViewModel(mQuestion); } public void testGetTitle() throws Exception { mQuestion.setTitle("How to...?"); assertEquals("How to...?", mViewModel.getTitle()); } public void testGetLink() throws Exception { mQuestion.setLink("http://nntuyen.com"); assertEquals("http://nntuyen.com", mViewModel.getLink()); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.facade.security; import javax.ejb.Remote; /** * * @author esmata */ @Remote public interface SecurityFacadeRemote { public org.inbio.ara.dto.security.SystemUserDTO getSystemUserByNameAndPass(java.lang.String name, java.lang.String pass); public java.util.List<org.inbio.ara.dto.security.NomenclaturalGroupDTO> getNomenclaturalGroupList(java.lang.Long userId); public java.lang.Long countUsers(); public java.util.List<org.inbio.ara.dto.security.SystemUserDTO> getAllUsersPaginated(int first, int totalResults); public org.inbio.ara.dto.security.SystemUserDTO saveNewSystemUser(org.inbio.ara.dto.security.SystemUserDTO uDTO); public void updateSystemUser(org.inbio.ara.dto.security.SystemUserDTO dto); public void deleteSystemUser(org.inbio.ara.dto.security.SystemUserDTO dto); public java.util.List<org.inbio.ara.dto.security.NomenclaturalGroupDTO> getAllNomenclaturalGroup(); public void deleteUserTaxonsByUser(java.lang.Long userId); public void deleteNomenclaturalGroupsByUser(java.lang.Long userId); public void saveUserTaxon(java.lang.Long taxonId, java.lang.Long userId, java.lang.Long secuence); public void saveUserNomenclaturalGroup(java.lang.Long groupId, java.lang.Long userId, java.lang.Long secuence); public Long getCollecionIdByNomenclaturalGroupId(Long nomenclatural); public boolean isAdmin(java.lang.Long userId); }
package com.example.admin.schoolhelper; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; public class Science extends ActionBarActivity { private Button addTeacher,addContact,viewTeacher,viewContact; private EditText editTeacherName,editContactName,editContactPhone; public static ArrayList<Teacher> teacherObjectList = new ArrayList<Teacher>(); public static ArrayList<String> contacts = new ArrayList<String>(); public static ArrayList<Contact> contactsObjectList = new ArrayList<Contact>(); public static ArrayList<String> contactPhoneNumbers = new ArrayList<String>(); public static ArrayList<String> teachers = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_science); addTeacher = (Button) findViewById(R.id.addTeacherScienceButton); addContact = (Button) findViewById(R.id.addScienceContactButton); viewContact = (Button) findViewById(R.id.scienceContactsButton); viewTeacher = (Button) findViewById(R.id.scienceTeachersButton); editTeacherName = (EditText) findViewById(R.id.inputScienceTeacherName); editContactName = (EditText) findViewById(R.id.inputScienceContactName); editContactPhone = (EditText) findViewById(R.id.inputSciencePhoneNumber); } public static void addTeacher(String teacherName) { Science.teachers.add(new String(teacherName)); Log.w("ADDED TEACHER STRING", "YEP"); } public static void addContact(String contact) { Science.contacts.add(contact); } public void onClickViewTeachers(View view) { Intent i = new Intent(this, ScienceTeachers.class); startActivity(i); } public void onCLickViewContacts(View view) { Intent i = new Intent(this, ScienceContacts.class); startActivity(i); } public void onClickAddContact(View view) { Science.addContact(editContactName.getText().toString()); Science.contactPhoneNumbers.add(editContactPhone.getText().toString()); Log.w("ADDED","PHONENUMBER"); Science.contactsObjectList.add(new Contact(editContactName.getText().toString(), editContactPhone.getText().toString())); Log.w("ADDED CONTACT", "yep"); } public void onClickAddTeacher(View view) { Science.addTeacher(editTeacherName.getText().toString()); Science.teacherObjectList.add(new Teacher(editTeacherName.getText().toString())); Log.w("ADDED TEACER", "yep"); } }
package date; import java.text.SimpleDateFormat; import java.text.ParseException; public class DateTest { /** * Check the date on the correctness * * @param inDate date to be verified. * @return true if date are valid and false if date if wrong. */ public static boolean isValidDate(String inDate) { if (inDate == null) { return false; } SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm"); if (inDate.trim().length() != dateFormat.toPattern().length()) { return false; } dateFormat.setLenient(false); try { dateFormat.parse(inDate.trim()); } catch (ParseException pe) { return false; } return true; } }
public class Aereo extends Vehiculo { public String nombreAereo=""; public Aereo(){ System.out.println("creando aereo"); } public String volar(){ return "Método volar desde clase Aereo"; } }
package estados; import cartas.Puntos; import configuraciones.ConfiguracionDeOpciones; import configuraciones.MostrarOpcionesDeModoAtaque; import efectos.EfectoDeVolteo; import efectos.EfectoInvocacionMonstruo; import juego.FormaDeAfectarAlJugador; import juego.Restar; public class ModoAtaque extends EstadoDeCartaMonstruo { public ModoAtaque(Puntos puntosDeAtaque) { super(); this.puntosAsociadosAlEstado = puntosDeAtaque; } @Override public FormaDeAfectarAlJugador formaDeAfectar(int diferencia) { return new Restar(diferencia); } @Override public void activar(EfectoDeVolteo efecto) { } @Override public void activar(EfectoInvocacionMonstruo efectoInvocacionMonstruo){ efectoInvocacionMonstruo.activar(); } @Override public ConfiguracionDeOpciones obtenerConfiguracionDeOpciones() { return new MostrarOpcionesDeModoAtaque(); } }
package nyc.c4q; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; /** * Created by c4q-marbella on 8/30/15. */ public class MySQLiteOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "memberManager"; // Contacts table name private static final String TABLE_MEMBERS = "members"; public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } public static abstract class MemberEntry implements BaseColumns{ // Contacts Table Columns names private static final String KEY_ID = "id"; private static final String KEY_NAME = "name"; private static final String KEY_DOB = "dob"; private static final String KEY_LOCATION = "location"; } // CREATE TABLE private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + MemberEntry.TABLE_NAME; private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + MemberEntry.TABLE_NAME; }
package se.rtz.tool.util.csv.impl; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import se.rtz.tool.util.csv.RecordWithMap; public class CsvRecord implements Iterable<String> { private final ArrayList<String> values = new ArrayList<>(); private CsvHeader header; public CsvRecord(List<String> list) { values.addAll(list); } public CsvRecord() {} public CsvRecord(String... string) { for (String v: string) { values.add(v); } } public CsvRecord(CsvRecord header) { this(header.asList()); } public CsvRecord(Collection<Entry<String, String>> valuePairs) { header = new CsvHeader(); valuePairs.forEach(t -> { header.add(t.getKey()); values.add(t.getValue()); }); } @Override public String toString() { return "CsvRecord [values=" + values + "]"; } public String get(int i) { if (i < values.size()) return values.get(i); else return ""; } @Override public Iterator<String> iterator() { return values.iterator(); } public CsvRecord add(String... strings) { for (String string: strings) { values.add(string); } return this; } public List<String> asList() { return new ArrayList<>(values); } public RecordWithMap makeRecordWithMap(CsvRecord csvRecord) { return new RecordWithMap(this, csvRecord); } @Override public int hashCode() { final int prime = 31; int result = 1; for (int i = 0; i < values.size(); i++) { result = prime * result + get(i).hashCode(); } return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CsvRecord other = (CsvRecord) obj; if (values.size() != other.values.size()) return false; boolean result = true; for (int i = 0; i < values.size(); i++) { result = result && get(i).equals(other.get(i)); } return result; } public String[] toArray() { String[] result = new String[values.size()]; for (int i = 0; i < result.length; i++) { result[i] = values.get(i); } return result; } public String toCsvString(char delimeter) { StringBuilder resul = new StringBuilder(); boolean[] isFirst = { true }; values.forEach(d -> { String value = d; if (value.contains("\"")) { value = value.replaceAll("\"", "\"\""); } if (value.contains("\"") || value.contains(Character.toString(delimeter))) { value = "\"" + value + "\""; } if (!isFirst[0]) resul.append(delimeter); isFirst[0] = false; resul.append(value); }); return resul.toString(); } void setHeader(CsvHeader header) { this.header= header; } public CsvHeader getHeader() { return header; } /** * So why just not return a Map<String, String>... the order of the elements are important. * @return */ public List<Entry<String, String>> entries() { ArrayList<Entry<String, String>> result = new ArrayList<>(); String[] vs = toArray(); String[] hs = getHeader().toArray(); int max = Math.min(vs.length, hs.length); for (int i = 0; i < max; i++) { String v = vs[i]; String h = hs[i]; result.add(new AbstractMap.SimpleImmutableEntry<String, String>(h, v)); } return result; } public boolean isHeader() { return false; } }
package com.gaoshin.fbobuilder.client.model; import java.io.File; public class PosterOwner { public static final String ContentFileName = "CONTENT"; private PosterId posterId; private String ownerId; public PosterOwner() { } public PosterOwner(String ownerId, PosterId posterId) { this.ownerId = ownerId; this.setPosterId(posterId); } public String getOwnerId() { return ownerId; } public void setOwnerId(String userId) { this.ownerId = userId; } public String getRealPath(String base) { return base + File.separator + getPath(); } public String getPath() { return getPath(this.ownerId) + File.separator + posterId.getPath(); } public PosterId getPosterId() { return posterId; } public void setPosterId(PosterId posterId) { this.posterId = posterId; } public UserAsset getVisibilityAsset(Visibility visibility) { return new UserAsset(this, visibility.getFileName()); } public UserAsset getContentAsset() { return new UserAsset(this, ContentFileName); } public static String getPath(String ownerId) { String p1 = ownerId.substring(0, 5); String p2 = ownerId.substring(5, 8); String p3 = ownerId.substring(8, 11); return p1 + File.separator + p2 + File.separator + p3 + File.separator + ownerId; } public static PosterOwner fromPath(String ownerId, String path) { int pos = path.indexOf(ownerId); String[] items = path.substring(pos).split(File.separator); int version = Integer.parseInt(items[items.length - 1]); String artifactId = items[items.length - 2]; StringBuilder sb = new StringBuilder(); for(int i = 1; i<items.length - 2; i++) { if(sb.length() > 0) sb.append("."); sb.append(items[i]); } String groupId = sb.toString(); return new PosterOwner(ownerId, new PosterId(groupId, artifactId, version)); } public String getUrlPath() { return ownerId + "/" + posterId.getUrlPath(); } }
/* * 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.core.codec; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import reactor.core.publisher.Flux; import org.springframework.core.ResolvableType; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.util.MimeType; /** * Benchmarks for {@link DataBufferUtils}. * * @author Rossen Stoyanchev */ @BenchmarkMode(Mode.Throughput) public class StringDecoderBenchmark { @Benchmark public void parseSseLines(SseLinesState state, Blackhole blackhole) { blackhole.consume(state.parseLines().blockLast()); } @State(Scope.Benchmark) @SuppressWarnings({"NotNullFieldNotInitialized", "ConstantConditions"}) public static class SseLinesState { private static final Charset CHARSET = StandardCharsets.UTF_8; private static final ResolvableType ELEMENT_TYPE = ResolvableType.forClass(String.class); @Param("10240") int totalSize; @Param("2000") int chunkSize; List<DataBuffer> chunks; StringDecoder decoder = StringDecoder.textPlainOnly(Arrays.asList("\r\n", "\n"), false); MimeType mimeType = new MimeType("text", "plain", CHARSET); @Setup(Level.Trial) public void setup() { String eventTemplate = """ id:$1 event:some-event :some-comment-$1-aa :some-comment-$1-bb data:abcdefg-$1-hijklmnop-$1-qrstuvw-$1-xyz-$1 """; int eventLength = String.format(eventTemplate, String.format("%05d", 1)).length(); int eventCount = this.totalSize / eventLength; DataBufferFactory bufferFactory = new DefaultDataBufferFactory(); this.chunks = Flux.range(1, eventCount) .map(index -> String.format(eventTemplate, String.format("%05d", index))) .buffer(this.chunkSize > eventLength ? this.chunkSize / eventLength : 1) .map(strings -> String.join("", strings)) .map(chunk -> { byte[] bytes = chunk.getBytes(CHARSET); DataBuffer buffer = bufferFactory.allocateBuffer(bytes.length); buffer.write(bytes); return buffer; }) .collectList() .block(); } public Flux<String> parseLines() { Flux<DataBuffer> input = Flux.fromIterable(this.chunks).doOnNext(DataBufferUtils::retain); return this.decoder.decode(input, ELEMENT_TYPE, this.mimeType, Collections.emptyMap()); } } }
package be.mxs.common.util.io; public class LocalDebet { String encounterType; String encounterUid; String prestationCode; String prestationName; double patientAmount; double insurerAmount; double quantity; String uid; java.util.Date date; }
package com.goldenasia.lottery.pattern; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; import com.goldenasia.lottery.R; import com.goldenasia.lottery.app.GoldenAsiaApp; import com.goldenasia.lottery.component.QuantityView; import com.goldenasia.lottery.component.QuantityView.OnQuantityChangeListener; import com.goldenasia.lottery.material.ShoppingCart; /** * 购物车多倍操作 * Created by ACE-PC on 2016/2/5. */ public class ShroudViewNoChase { private static final String TAG = ShroudViewNoChase.class.getSimpleName(); private QuantityView doubleText; //倍数 private RadioGroup viewGroup; //无角分操作 private RadioButton radioYuan, radioJiao, radioFen, radioLi; private OnModeItemClickListener modeItemListener; public ShroudViewNoChase(View view) { doubleText = (QuantityView) view.findViewById(R.id.double_number_view); viewGroup = (RadioGroup) view.findViewById(R.id.lucremode_sett); doubleText.setMinQuantity(1); doubleText.setMaxQuantity(50000); doubleText.setQuantity(ShoppingCart.getInstance().getMultiple()); doubleText.setLimitMax(true);//添加 限制最大值 radioYuan = (RadioButton) view.findViewById(R.id.lucremode_yuan); radioJiao = (RadioButton) view.findViewById(R.id.lucremode_jiao); radioFen = (RadioButton) view.findViewById(R.id.lucremode_fen); radioLi = (RadioButton) view.findViewById(R.id.lucremode_li); defaultSelected(); doubleText.setOnQuantityChangeListener(new OnQuantityChangeListener() { @Override public void onQuantityChanged(int newQuantity, boolean programmatically) { modeItemListener.onModeItemClick(newQuantity, setLucreMode()); } @Override public void onLimitReached() { } }); viewGroup.setOnCheckedChangeListener((group, checkedId) -> modeItemListener.onModeItemClick(doubleText .getQuantity(), setLucreMode())); } public void setModeItemListener(OnModeItemClickListener modeItemListener) { this.modeItemListener = modeItemListener; } private int setLucreMode() { int check = 0; switch (viewGroup.getCheckedRadioButtonId()) { case R.id.lucremode_yuan: check = 0; break; case R.id.lucremode_jiao: check = 1; break; case R.id.lucremode_fen: check = 2; break; case R.id.lucremode_li: check = 3; break; default: check = 0; } GoldenAsiaApp.getUserCentre().setLucreMode(check); return check; } public QuantityView getDoubleText() { return doubleText; } private void defaultSelected() { switch (GoldenAsiaApp.getUserCentre().getLucreMode()) { case 0: radioYuan.setChecked(true); break; case 1: radioJiao.setChecked(true); break; case 2: radioFen.setChecked(true); break; case 3: radioLi.setChecked(true); break; } } /** * 选中监听器 */ public interface OnModeItemClickListener { void onModeItemClick(int multiple, int lucreMode); } }
package sohage.example.com.numberverify.Model; /** * Created by Mohamed_Ahmed on 16/04/2018. */ public class ResponseModel {// this class is the model that contains response data private String number; private String Valid; private String local_format; private String international_format; private String country_prefix; private String country_code; private String country_name; private String location; private String carrier; private String line_type; public ResponseModel() { this.number = ""; Valid = null; this.local_format = ""; this.international_format = ""; this.country_prefix = ""; this.country_code = ""; this.country_name = ""; this.location = ""; this.carrier = ""; this.line_type = ""; } public ResponseModel(String number, String valid, String local_format, String international_format, String country_prefix, String country_code, String country_name, String location, String carrier, String line_type) { this.number = number; Valid = valid; this.local_format = local_format; this.international_format = international_format; this.country_prefix = country_prefix; this.country_code = country_code; this.country_name = country_name; this.location = location; this.carrier = carrier; this.line_type = line_type; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getValid() { return Valid; } public void setValid(String valid) { Valid = valid + ""; } public String getLocal_format() { return local_format; } public void setLocal_format(String local_format) { this.local_format = local_format; } public String getInternational_format() { return international_format; } public void setInternational_format(String international_format) { this.international_format = international_format; } public String getCountry_prefix() { return country_prefix; } public void setCountry_prefix(String country_prefix) { this.country_prefix = country_prefix; } public String getCountry_code() { return country_code; } public void setCountry_code(String country_code) { this.country_code = country_code; } public String getCountry_name() { return country_name; } public void setCountry_name(String country_name) { this.country_name = country_name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCarrier() { return carrier; } public void setCarrier(String carrier) { this.carrier = carrier; } public String getLine_type() { return line_type; } public void setLine_type(String line_type) { this.line_type = line_type; } }
package com.ets.gti785.labo1; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.wifi.WifiManager; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import com.ets.gti785.labo1.controller.HttpController; import com.ets.gti785.labo1.model.Song; import com.ets.gti785.labo1.model.Songs; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutionException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { final private String TAG = "MainActivity"; final private int STATE_STOP = 0; final private int STATE_PLAYING = 1; final private int STATE_PAUSE = 2; final private int MODE_NORMAL = 0; final private int MODE_SHUFFLE = 1; final private int MODE_REPEAT = 2; private int state = STATE_STOP; private int mode = MODE_NORMAL; private HttpController httpController; private ImageButton btnPlay; private ImageButton btnPause; private ImageButton btnStop; private ImageButton btnPrevious; private ImageButton btnNext; private ImageButton btnShuffle; private ImageButton btnRepeat; private ImageButton btnVolumeUp; private ImageButton btnVolumeDown; private ProgressBar progressBar; private ListView listView; private SongArrayAdapter songAdapter; private TextView tvCurrentSong; private TextView tvDurationCurrent; private TextView tvDurationSong; private SeekBar sbTime; private MediaPlayer mediaPlayer; private int currentSongIndex; private int currentSongTimeSecCounter; private List<Song> playlist; private boolean isStreaming = false; private Handler timerHandler; private Runnable updater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); PreferenceManager.setDefaultValues(this, R.xml.preferences, false); initViews(); httpController = new HttpController(); currentSongTimeSecCounter = 0; try { initAdapters(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } initListeners(); createMediaPlayer(); startSongTimerWatcher(); Log.e("MainActivity client ip:", getWifiIpAddress(this)); } @Override protected void onResume() { super.onResume(); if(isStreaming != isStreamingPref()){ isStreaming = !isStreaming; if(isStreaming && state == STATE_PLAYING){ stop(); } httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/streaming"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.player_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.open_settings: Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void initViews(){ btnPlay = (ImageButton)findViewById(R.id.button_play); btnPause = (ImageButton)findViewById(R.id.button_pause); btnStop = (ImageButton)findViewById(R.id.button_stop); btnPrevious = (ImageButton)findViewById(R.id.button_previous); btnNext = (ImageButton)findViewById(R.id.button_next); btnShuffle = (ImageButton)findViewById(R.id.button_shuffle); btnRepeat = (ImageButton)findViewById(R.id.button_repeat); btnVolumeUp = (ImageButton)findViewById(R.id.button_volume_up); btnVolumeDown = (ImageButton)findViewById(R.id.button_volume_dowwn); tvCurrentSong = (TextView)findViewById(R.id.current_song_title); tvDurationCurrent = (TextView)findViewById(R.id.duration_current); tvDurationSong = (TextView)findViewById(R.id.duration_song); sbTime = (SeekBar)findViewById(R.id.song_seekbar); sbTime.setActivated(false); listView = (ListView) findViewById(R.id.playlist); progressBar = (ProgressBar) findViewById(R.id.progressBar); } private void initAdapters() throws ExecutionException, InterruptedException { playlist = new ArrayList<>(); loadSongs(); Log.d("filelist:",playlist.toString()); currentSongIndex = 0; songAdapter = new SongArrayAdapter(this, playlist); listView.setAdapter(songAdapter); } private void initListeners(){ listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { play(position); currentSongTimeSecCounter = 0; refreshViewsCurrentSong(); refreshListView(); refreshButtons(); } }); /*sbTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(state == STATE_PLAYING && fromUser){ mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } });*/ btnPlay.setOnClickListener(this); btnPause.setOnClickListener(this); btnStop.setOnClickListener(this); btnPrevious.setOnClickListener(this); btnNext.setOnClickListener(this); btnShuffle.setOnClickListener(this); btnRepeat.setOnClickListener(this); btnVolumeUp.setOnClickListener(this); btnVolumeDown.setOnClickListener(this); sbTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(progress == Math.round(playlist.get(currentSongIndex).getDuration())) { next(); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } private boolean isStreamingPref() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); return prefs.getBoolean("pref_streaming", true); } private void createMediaPlayer(){ mediaPlayer = new MediaPlayer(); /*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if(mode == MODE_NORMAL){ next(); } else if(mode == MODE_SHUFFLE){ Random rand = new Random(); int nextSong = rand.nextInt((playlist.size())); play(nextSong); } else if(mode == MODE_REPEAT){ play(currentSongIndex); } } });*/ } public void refreshViewsCurrentSong(){ if(isStreaming){ int secs = (mediaPlayer.getCurrentPosition() / 1000); int mins= secs / 60; secs = secs % 60; String duration = String.format("%02d:%02d", mins, secs); tvDurationCurrent.setText(duration); sbTime.setMax(mediaPlayer.getDuration()); sbTime.setProgress(mediaPlayer.getCurrentPosition()); } else { int secsMax = (int)songAdapter.getItem(currentSongIndex).getDuration(); sbTime.setMax(secsMax); int secs = currentSongTimeSecCounter; int mins= secs / 60; secs = secs % 60; String duration = String.format("%02d:%02d", mins, secs); tvDurationCurrent.setText(duration); sbTime.setProgress(currentSongTimeSecCounter); } int secs = (int)songAdapter.getItem(currentSongIndex).getDuration(); int mins= secs / 60; secs = secs % 60; String duration = String.format("%02d:%02d", mins, secs); tvDurationSong.setText(duration); } protected String getWifiIpAddress(Context context) { WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); // Convert little-endian to big-endianif needed if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) { ipAddress = Integer.reverseBytes(ipAddress); } byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray(); String ipAddressString; try { ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress(); } catch (UnknownHostException ex) { Log.e("WIFIIP", "Unable to get host address."); ipAddressString = null; } return ipAddressString; } void startSongTimerWatcher() { timerHandler = new Handler(); updater = new Runnable() { @Override public void run() { if(state == STATE_PLAYING){ currentSongTimeSecCounter ++; refreshViewsCurrentSong(); } timerHandler.postDelayed(updater,1000); } }; timerHandler.post(updater); } private void play(int newSongId){ state = STATE_PLAYING; currentSongIndex = newSongId; String json = httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/play", String.valueOf(currentSongIndex)); Song returnSong = gsonStringToSong(json); currentSongIndex = returnSong.getId(); if(isStreaming){ if(mediaPlayer != null){ if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); } mediaPlayer.reset(); } createMediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mediaPlayer.setDataSource(httpController.getServerURL(this)+"/play"); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.start(); } }); mediaPlayer.prepare(); // Opération qui prend beaucoup de temps. } catch (IOException e) { e.printStackTrace(); } } refreshViewsCurrentSong(); } private void pause(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/pause"); if(isStreaming){ mediaPlayer.pause(); } state = STATE_PAUSE; } private void stop(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/stop"); if(isStreaming){ mediaPlayer.stop(); mediaPlayer.reset(); } state = STATE_STOP; currentSongTimeSecCounter = 0; refreshViewsCurrentSong(); } private void previous(){ String json = httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/back"); state = STATE_PLAYING; Song returnSong = gsonStringToSong(json); currentSongIndex = returnSong.getId(); if(isStreaming){ play(currentSongIndex); } currentSongTimeSecCounter = 0; refreshViewsCurrentSong(); refreshListView(); } private void next(){ String json = httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/next"); state = STATE_PLAYING; Song returnSong = gsonStringToSong(json); currentSongIndex = returnSong.getId(); if(isStreaming){ play(currentSongIndex); } currentSongTimeSecCounter = 0; refreshViewsCurrentSong(); refreshListView(); } private void shuffle(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/shuffle"); if(mode == MODE_SHUFFLE){ mode = MODE_NORMAL; } else{ mode = MODE_SHUFFLE; } } private void repeat(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/repeat"); if(mode == MODE_REPEAT){ mode = MODE_NORMAL; } else{ mode = MODE_REPEAT; } } private void volumeUp(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/volumeUp"); } private void volumeDown(){ httpController.sendHttpPostRequest(httpController.getServerURL(this)+"/volumeDown"); } private void loadSongs() throws ExecutionException, InterruptedException { Gson gson = new GsonBuilder().create(); String json = httpController.sendHttpGetRequest(httpController.getServerURL(this)+"/songs"); Log.d("Songs", json.toString()); if(json != null && !json.equals("")) { Songs songs = gson.fromJson(json, Songs.class); this.playlist = songs.getSongs(); } } private Song gsonStringToSong(String json){ Gson gson = new GsonBuilder().create(); Song song = new Song(0,"","","",0); if(json != null && !json.equals("")) { song = gson.fromJson(json, Song.class); } return song; } @Override public void onClick(View v) { int id = v.getId(); if(id == R.id.button_play){ play(currentSongIndex); } else if(id == R.id.button_pause){ pause(); } else if(id == R.id.button_stop){ stop(); } else if(id == R.id.button_previous){ previous(); } else if(id == R.id.button_next){ next(); } else if(id == R.id.button_shuffle){ shuffle(); } else if(id == R.id.button_repeat){ repeat(); } else if(id == R.id.button_volume_up){ volumeUp(); } else if(id == R.id.button_volume_dowwn){ volumeDown(); } refreshButtons(); refreshListView(); } public void refreshButtons(){ if(state == STATE_PLAYING){ btnPlay.setVisibility(View.GONE); btnPause.setVisibility(View.VISIBLE); } else { btnPlay.setVisibility(View.VISIBLE); btnPause.setVisibility(View.GONE); } btnRepeat.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary)); btnShuffle.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary)); if(mode == MODE_REPEAT){ btnRepeat.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark)); } else if(mode == MODE_SHUFFLE){ btnShuffle.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark)); } } public void refreshListView(){ listView.invalidateViews(); } private class SongArrayAdapter extends ArrayAdapter<Song> { HashMap<String, Integer> mIdMap = new HashMap<String, Integer>(); public SongArrayAdapter(Context context, List<Song> songs) { super(context, 0, songs); } @Override public View getView(int position, View convertView, ViewGroup parent) { Song song = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_song, parent, false); } // Lookup view for data population TextView songTitle = (TextView) convertView.findViewById(R.id.songTitle); TextView songArtist = (TextView) convertView.findViewById(R.id.songArtist); songTitle.setText(song.getTitle()); songArtist.setText(song.getArtist()); if (position == currentSongIndex && (state == STATE_PLAYING ||state == STATE_PAUSE)) { convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorAccent)); } else { convertView.setBackgroundColor(Color.WHITE); } return convertView; } } String getPlayJson(int songId, boolean isStreaming) { return "{'Id':"+songId + "}"; } }
package com.xh.util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ActivityManager; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.view.Display; /** * 手机信息收集 添加权限 <uses-permission * android:name="android.permission.READ_PHONE_STATE" /> <!-- 在SDCard中创建与删除文件权限 * --> <uses-permission * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- * 往SDCard写入数据权限 --> <uses-permission * android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission * android:name="android.permission.READ_PHONE_STATE" /> <uses-permission * android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> * <uses-permission * android:name="android.permission.INTERNET"></uses-permission> <!-- wifi权限 --> * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> * <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <!-- * 查询网络状态权限 --> <uses-permission * android:name="android.permission.ACCESS_NETWORK_STATE" /> */ public class XhPhoneInformation { /** * 手机屏幕高度 */ public static int height = 0; /** * 手机屏幕宽度 */ public static int width = 0; /** * 手机宽度上的像素 */ public static int widthPixels = 0; /** * 手机高度上的像素 */ public static int heightPixels = 0; /** * 手机IMEI 设备ID */ public static String IMEI = ""; /** * 手机 IESI 订阅者ID */ public static String IESI = ""; /** * 手机型号 MODEL */ public static String MODEL = ""; /** * 手机号码 有的能拿到,有的不可以,这个要看生产商是否注册了 */ public static String numer = ""; /** * sdk版本 */ public static String sdk = ""; /** * 系统版本号 */ public static String VERSION_RELEASE = ""; /** * The name of the underlying board, like "goldfish". */ public static String BOARD = ""; /** * The system bootloader version number. */ public static String BOOTLOADER = ""; /** * The brand (e.g., carrier) the software is customized for, if any. */ public static String BRAND = ""; /** * The name of the instruction set (CPU type + ABI convention) of native * code. */ public static String CPU_ABI = ""; /** * The name of the second instruction set (CPU type + ABI convention) of * native code. */ public static String CPU_ABI2 = ""; /** * The name of the industrial design. */ public static String DEVICE = ""; /** * A build ID string meant for displaying to the user */ public static String DISPLAY = ""; /** * A string that uniquely identifies this build. */ public static String FINGERPRINT = ""; /** * The name of the hardware (from the kernel command line or /proc). */ public static String HARDWARE = ""; public static String HOST = ""; /** * Either a changelist number, or a label like "M4-rc20". */ public static String ID = ""; /** * The manufacturer of the product/hardware. */ public static String MANUFACTURER = ""; /** * The name of the overall product. */ public static String PRODUCT = ""; /** * The radio firmware version number. */ public static String RADIO = ""; /** * A hardware serial number, if available. */ public static String SERIAL = ""; /** * Comma-separated tags describing the build, like "unsigned,debug". */ public static String TAGS = ""; public static long TIME = 0l; /** * The type of build, like "user" or "eng". */ public static String TYPE = ""; /** * Value used for when a build property is unknow */ public static String UNKNOWN = ""; public static String USER = ""; /** * 手机MAC地址 */ public static String MAC = ""; /** * cpu 型号 */ public static String CPU_MODE = ""; /** * cpu频率 */ public static String CPU_FREQUENCY = ""; /** * 系统总内存 单位为kb */ public static long TOTAL_RAM = 0l; /** * 系统剩余内存 单位为kb */ public static long AVAIL_RAM = 0l; /** * SDCARD总内存 单位为kb */ public static long TOTAL_SDCARD = 0l; /** * SDCARD剩余内存单位为kb */ public static long AVAIL_SDCARD = 0l; /** * 总内存 */ public static long TOTAL_MEMORY = 0l; /** * 总剩余内存 */ public static long TOTAL_REMAIN_MEMORY = 0l; /** * 像素密度 */ public float density; /** * 密度dpi */ public float densityDpi; public float scaledDensity; public static XhPhoneInformation xhPhoneInformation; private final static String TAG = XhPhoneInformation.class.getName(); /** * 构造方法私有化,不需创造对象 */ private XhPhoneInformation(Activity activity) { // TODO Auto-generated constructor stub getPhonWidthAndHeigth(activity); getPixel(activity); getInfo(activity); getPhoneInformation(); getMacAddress(activity); getCpuInfo(); getTotalMemory(activity); getSDCARD(); getRAM(); } /** * app初始化时候调用 * * @param activity */ public static XhPhoneInformation initialize(Activity activity) { if (xhPhoneInformation != null) return xhPhoneInformation; synchronized (TAG) { if (xhPhoneInformation != null) return xhPhoneInformation; xhPhoneInformation = new XhPhoneInformation(activity); } return xhPhoneInformation; } /** * 获取总内存 */ public void getRAM() { // TODO Auto-generated method stub File path2 = Environment.getDataDirectory(); StatFs stat2 = new StatFs(path2.getPath()); @SuppressWarnings("deprecation") long blockSize2 = stat2.getBlockSize(); @SuppressWarnings("deprecation") long totalBlocks2 = stat2.getBlockCount(); @SuppressWarnings("deprecation") long availableBlocks2 = stat2.getAvailableBlocks(); long totalSize2 = totalBlocks2 * blockSize2; long availSize2 = availableBlocks2 * blockSize2; TOTAL_MEMORY = totalSize2; TOTAL_REMAIN_MEMORY = availSize2; } /** * 获sdc内存 */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") public void getSDCARD() { // 得到文件系统的信息:存储块大小,总的存储块数量,可用存储块数量 // 获取sd卡空间 // 存储设备会被分为若干个区块 // 每个区块的大小 * 区块总数 = 存储设备的总大小 // 每个区块的大小 * 可用区块的数量 = 存储设备可用大小 File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize; long totalBlocks; long availableBlocks; // 由于API18(Android4.3)以后getBlockSize过时并且改为了getBlockSizeLong // 因此这里需要根据版本号来使用那一套API if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { blockSize = stat.getBlockSizeLong(); totalBlocks = stat.getBlockCountLong(); availableBlocks = stat.getAvailableBlocksLong(); } else { blockSize = stat.getBlockSize(); totalBlocks = stat.getBlockCount(); availableBlocks = stat.getAvailableBlocks(); } /** * 内存总大小 * */ TOTAL_SDCARD = blockSize * totalBlocks; /** * 内存可用大小 */ AVAIL_SDCARD = blockSize * availableBlocks; } /** * 获取系统内存 */ public void getTotalMemory(Activity activity) { ActivityManager mActivityManager = (ActivityManager) activity .getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); mActivityManager.getMemoryInfo(mi); long mTotalMem = 0; long mAvailMem = mi.availMem; String str1 = "/proc/meminfo"; String str2; String[] arrayOfString; try { FileReader localFileReader = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader( localFileReader, 8192); str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); mTotalMem = Integer.valueOf(arrayOfString[1]).intValue() * 1024; localBufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } TOTAL_RAM = mTotalMem; AVAIL_RAM = mAvailMem; } /** * 手机CPU信息 */ private void getCpuInfo() { String str1 = "/proc/cpuinfo"; String str2 = ""; String[] arrayOfString; try { FileReader fr = new FileReader(str1); BufferedReader localBufferedReader = new BufferedReader(fr, 8192); str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); for (int i = 2; i < arrayOfString.length; i++) { CPU_MODE = CPU_MODE + arrayOfString[i] + " "; } str2 = localBufferedReader.readLine(); arrayOfString = str2.split("\\s+"); CPU_FREQUENCY += arrayOfString[2]; localBufferedReader.close(); } catch (IOException e) { } } /** * 获取手机MAC地址 */ public void getMacAddress(Context activity) { WifiManager wifiManager = (WifiManager) activity .getSystemService(Context.WIFI_SERVICE); if (wifiManager == null) return; WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo == null) return; MAC = wifiInfo.getMacAddress(); } /** * 获取手机设备信息 */ @SuppressLint("NewApi") @SuppressWarnings("deprecation") private void getPhoneInformation() { MODEL = Build.MODEL; // 手机型号 sdk = android.os.Build.VERSION.SDK; VERSION_RELEASE = Build.VERSION.RELEASE; BOARD = Build.BOARD; BOOTLOADER = Build.BOOTLOADER; BRAND = Build.BRAND; CPU_ABI = Build.CPU_ABI; CPU_ABI2 = Build.CPU_ABI2; DEVICE = Build.DEVICE; DISPLAY = Build.DISPLAY; FINGERPRINT = Build.FINGERPRINT; HARDWARE = Build.HARDWARE; HOST = Build.HOST; ID = Build.ID; MANUFACTURER = Build.MANUFACTURER; PRODUCT = Build.PRODUCT; RADIO = Build.RADIO; SERIAL = Build.SERIAL; TAGS = Build.TAGS; TIME = Build.TIME; TYPE = Build.TYPE; UNKNOWN = Build.UNKNOWN; USER = Build.USER; } /** * 获取手机宽度和高度 * * @param activity * @return */ @SuppressWarnings("deprecation") private void getPhonWidthAndHeigth(Activity activity) { Display display = activity.getWindowManager().getDefaultDisplay(); height = display.getHeight(); width = display.getWidth(); } /** * 获取手机像素 * * @param activity * @return */ private void getPixel(Activity activity) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); widthPixels = dm.widthPixels; heightPixels = dm.heightPixels; density = dm.density; scaledDensity = dm.scaledDensity; densityDpi = dm.densityDpi; } /** * 获取手机标示 * * @param activity */ private void getInfo(Activity activity) { TelephonyManager mTm = (TelephonyManager) activity .getSystemService(Activity.TELEPHONY_SERVICE); if (mTm == null) return; IMEI = mTm.getDeviceId(); IESI = mTm.getSubscriberId(); numer = mTm.getLine1Number(); } /** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) xh 2017-2-15 下午6:02:54 * * @param context * @param dpValue * @return */ public int dip2px(float dpValue) { return (int) (dpValue * density + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp xh 2017-2-15 下午6:02:59 * * @param context * @param pxValue * @return */ public int px2dip(float pxValue) { return (int) (pxValue / density + 0.5f); } /** * * lhl 2017-12-19 下午5:02:11 说明:像素转为sp * * @param pxValue * @return int */ public int px2sp(float pxValue) { return (int) (pxValue / scaledDensity + 0.5f); } /** * * lhl 2017-12-19 下午5:02:28 说明: sp转为像素 * * @param spValue * @return int */ public int sp2px(float spValue) { return (int) (spValue * scaledDensity + 0.5f); } }
package ec.edu.upse.modelo; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the tbl_sga_horario database table. * */ @Entity @Table(name="tbl_sga_horario") @NamedQueries({ @NamedQuery(name="TblSgaHorario.findAll", query="SELECT t FROM TblSgaHorario t"), @NamedQuery(name="TblSgaHorario.BuscaPorConsulta", query="SELECT t FROM TblSgaHorario t " + "where t.tblSgaCursoparalelo.tblSgaPeriodoncurso.tblSgaPeriodonivel.tblSgaPeriodolectivo.perId = :idPeriodo and " + "t.tblSgaCursoparalelo.tblSgaPeriodoncurso.tblSgaPeriodonivel.tblSgaNivel.nivelId = :idNivel and " + "t.tblSgaCursoparalelo.tblSgaPeriodoncurso.tblSgaCurso.curId = :idCurso and t.tblSgaCursoparalelo.tblSgaParalelo.paralId = :idParalelo and t.tblSgaDia.diaIdPk = :idDia") }) public class TblSgaHorario implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="hor_id_pk") private Integer horIdPk; private String estado; @Temporal(TemporalType.DATE) private Date fechaingreso; @Column(name="hor_observacion") private String horObservacion; private String usuario; //bi-directional many-to-one association to TblSgaAsistencia @OneToMany(mappedBy="tblSgaHorario") private List<TblSgaAsistencia> tblSgaAsistencias; //bi-directional many-to-one association to TblSgaDia @ManyToOne @JoinColumn(name="hor_dia_id_fk") private TblSgaDia tblSgaDia; //bi-directional many-to-one association to TblSgaDistributivo @ManyToOne @JoinColumn(name="hor_distributivo_fk") private TblSgaDistributivo tblSgaDistributivo; //bi-directional many-to-one association to TblSgaEspaciofisico @ManyToOne @JoinColumn(name="hor_esf_id_fk") private TblSgaEspaciofisico tblSgaEspaciofisico; //bi-directional many-to-one association to TblSgaHora @ManyToOne @JoinColumn(name="hor_hrs_id_fk") private TblSgaHora tblSgaHora; //bi-directional many-to-one association to TblSgaCursoparalelo @ManyToOne @JoinColumn(name="hor_curparal_fk") private TblSgaCursoparalelo tblSgaCursoparalelo; public TblSgaHorario() { } public Integer getHorIdPk() { return this.horIdPk; } public void setHorIdPk(Integer horIdPk) { this.horIdPk = horIdPk; } public String getEstado() { return this.estado; } public void setEstado(String estado) { this.estado = estado; } public Date getFechaingreso() { return this.fechaingreso; } public void setFechaingreso(Date fechaingreso) { this.fechaingreso = fechaingreso; } public String getHorObservacion() { return this.horObservacion; } public void setHorObservacion(String horObservacion) { this.horObservacion = horObservacion; } public String getUsuario() { return this.usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public List<TblSgaAsistencia> getTblSgaAsistencias() { return this.tblSgaAsistencias; } public void setTblSgaAsistencias(List<TblSgaAsistencia> tblSgaAsistencias) { this.tblSgaAsistencias = tblSgaAsistencias; } public TblSgaAsistencia addTblSgaAsistencia(TblSgaAsistencia tblSgaAsistencia) { getTblSgaAsistencias().add(tblSgaAsistencia); tblSgaAsistencia.setTblSgaHorario(this); return tblSgaAsistencia; } public TblSgaAsistencia removeTblSgaAsistencia(TblSgaAsistencia tblSgaAsistencia) { getTblSgaAsistencias().remove(tblSgaAsistencia); tblSgaAsistencia.setTblSgaHorario(null); return tblSgaAsistencia; } public TblSgaDia getTblSgaDia() { return this.tblSgaDia; } public void setTblSgaDia(TblSgaDia tblSgaDia) { this.tblSgaDia = tblSgaDia; } public TblSgaDistributivo getTblSgaDistributivo() { return this.tblSgaDistributivo; } public void setTblSgaDistributivo(TblSgaDistributivo tblSgaDistributivo) { this.tblSgaDistributivo = tblSgaDistributivo; } public TblSgaEspaciofisico getTblSgaEspaciofisico() { return this.tblSgaEspaciofisico; } public void setTblSgaEspaciofisico(TblSgaEspaciofisico tblSgaEspaciofisico) { this.tblSgaEspaciofisico = tblSgaEspaciofisico; } public TblSgaHora getTblSgaHora() { return this.tblSgaHora; } public void setTblSgaHora(TblSgaHora tblSgaHora) { this.tblSgaHora = tblSgaHora; } public TblSgaCursoparalelo getTblSgaCursoparalelo() { return this.tblSgaCursoparalelo; } public void setTblSgaCursoparalelo(TblSgaCursoparalelo tblSgaCursoparalelo) { this.tblSgaCursoparalelo = tblSgaCursoparalelo; } }
package delhivery; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Scanner; class TestClass { static Scanner scanner; public static void main(String args[] ) throws Exception { scanner=new Scanner(System.in); int T=scanner.nextInt(); while(T>0){ int N=scanner.nextInt(); int K=scanner.nextInt(); int[] array=new int[N]; // for(int i=0;i<array.length;i++) // { // array[i]=scanner.nextInt(); // } Random rand = new Random(); for(int i=0;i<array.length;i++) { array[i]= rand.nextInt(200)-100; } // System.out.println(Arrays.toString(array)); System.out.println(findingMinimumSumSubarray(array, K)); T--; } } public static int findingMinimumSumSubarray(int[] values, int k) { int N = values.length; int res = values[0]; for (int L = 0; L < N; L++) { for (int R = L; R < N; R++) { List<Integer> A= new ArrayList<Integer>(); List<Integer> B = new ArrayList<Integer>(); int ashu = 0; for (int i = 0; i < N; i++) { if (i >= L && i <= R) { A.add(values[i]); ashu += values[i]; } else { B.add(values[i]); } } Collections.sort(A); Collections.sort(B); Collections.reverse(B); res = Math.min(res, ashu); for (int t = 1; t <= k; t++) { if (t > A.size() || t > B.size()) break; ashu -= A.get(A.size() - t); ashu += B.get(B.size() - t); res = Math.min(res, ashu); } } } return res; } }
package com.yoke.poseidon.order.service; import com.yoke.poseidon.order.entity.OrderItem; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 订单商品关联表 服务类 * </p> * * @author yoke * @since 2019-02-03 */ public interface OrderItemService extends IService<OrderItem> { }
/* * Copyright © 2018 huiyunetwork.com All Rights Reserved. * * 感谢您加入辉娱网络,不用多久,您就会升职加薪、当上总经理、出任CEO、迎娶白富美、从此走上人生巅峰 * 除非符合本公司的商业许可协议,否则不得使用或传播此源码,您可以下载许可协议文件: * * http://www.huiyunetwork.com/LICENSE * * 1、未经许可,任何公司及个人不得以任何方式或理由来修改、使用或传播此源码; * 2、禁止在本源码或其他相关源码的基础上发展任何派生版本、修改版本或第三方版本; * 3、无论你对源代码做出任何修改和优化,版权都归辉娱网络所有,我们将保留所有权利; * 4、凡侵犯辉娱网络相关版权或著作权等知识产权者,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.converter.list; import xyz.noark.core.annotation.TemplateConverter; import xyz.noark.core.converter.Converter; import java.lang.reflect.Field; import java.lang.reflect.Parameter; import java.util.ArrayList; import java.util.Map; /** * ArrayList转化器. * * @author 小流氓[176543888@qq.com] * @since 3.4.6 */ @TemplateConverter(ArrayList.class) public class ArrayListConverter extends AbstractListConverter implements Converter<ArrayList<Object>> { @Override protected ArrayList<Object> createList(int length) { return new ArrayList<>(length); } @Override public ArrayList<Object> convert(Field field, String value) throws Exception { return (ArrayList<Object>) super.convert(field, value); } @Override public ArrayList<Object> convert(Parameter parameter, String value) throws Exception { return (ArrayList<Object>) super.convert(parameter, value); } @Override public ArrayList<Object> convert(Field field, Map<String, String> data) throws Exception { return (ArrayList<Object>) super.convert(field, data); } @Override public String buildErrorMsg() { return super.buildErrorMsg(); } }
package ru.alekseisivkov.treeofgoods; import android.app.LoaderManager; import android.content.Loader; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.Toast; import com.unnamed.b.atv.model.TreeNode; import com.unnamed.b.atv.view.AndroidTreeView; import java.util.ArrayList; import java.util.List; import ru.alekseisivkov.treeofgoods.API.TreeLoader; import ru.alekseisivkov.treeofgoods.Tree.TreeOfGoods; import ru.alekseisivkov.treeofgoods.Database.DatabaseTable; import ru.alekseisivkov.treeofgoods.Tree.CustomHolder; public class MainActivity extends AppCompatActivity { FrameLayout containerView, mainLayout; Button updateButton; List<TreeOfGoods> tree; DatabaseTable databaseTable; AndroidTreeView treeView; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); databaseTable = new DatabaseTable(this); containerView = (FrameLayout)findViewById(R.id.containerView); updateButton = (Button)findViewById(R.id.refreshButton); progressBar = (ProgressBar)findViewById(R.id.progressBar); mainLayout = (FrameLayout)findViewById(R.id.mainView); tree = new ArrayList<>(); updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showProgress(true); getLoaderManager().initLoader(1, null, callback); } }); showProgress(true); if (databaseTable.isEmpty()) { getLoaderManager().restartLoader(1, null, callback); } else { fillList(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @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. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void showProgress(boolean show) { //по какому-то неведомому мне косяку, данная вещь работает только один раз. if (show) { // Log.d("PROGRESS", "SHOW container " + containerView.getVisibility() + " progress " + progressBar.getVisibility() + // " main layout " + mainLayout.getVisibility()); // containerView.setVisibility(View.GONE); progressBar.setVisibility(View.VISIBLE); updateButton.setEnabled(false); } else { // Log.d("PROGRESS", "GONE container " + containerView.getVisibility() + " progress " + progressBar.getVisibility() + // " main layout " + mainLayout.getVisibility()); // containerView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); updateButton.setEnabled(true); } } private void fillList() { TreeNode root = TreeNode.root(); if (treeView != null) { //После обновления данные и для перерисовки дерева на экране. Иначе будет наложение. containerView.removeAllViews(); containerView.addView(updateButton); tree = new ArrayList<>(); } databaseTable.addRootsToModel(tree); for (int i = 0; i < tree.size(); i++) { TreeNode elem = new TreeNode(tree.get(i)).setViewHolder(new CustomHolder(getBaseContext())); root.addChild(elem); } treeView = new AndroidTreeView(getApplicationContext(), root); treeView.setDefaultAnimation(true); treeView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom); treeView.setDefaultNodeClickListener(new TreeNode.TreeNodeClickListener() { @Override public void onClick(TreeNode treeNode, Object o) { if (treeNode.isSelectable()) { //если дети есть и если они не были ранее загружены TreeOfGoods node = (TreeOfGoods) o; List<TreeOfGoods> temp = tree; for (int i = 1; i < node.getLevel(); i++) { //на каждое значение уровня, мы углубляемся по модели вниз temp = temp.get(node.getParentId() - 1).getLeaves(); //сделано, чтобы изменения происходили в модели, а не в представлении } TreeOfGoods currElem = temp.get(temp.indexOf(o)); if (!currElem.isLoadedChildren()) { Toast.makeText(getApplicationContext(), "Ask DB", Toast.LENGTH_SHORT).show(); databaseTable.addLeavesToModel(currElem, currElem.getLeft(), currElem.getRight(), currElem.getId()); for (int i = 0; i < currElem.getLeavesQuantity(); i++) { TreeNode elem = new TreeNode(currElem.getLeaves().get(i)).setViewHolder(new CustomHolder(getBaseContext())); treeNode.addChild(elem); } currElem.setChilrenLoaded(true); } } } }); showProgress(false); containerView.addView(treeView.getView()); } private LoaderManager.LoaderCallbacks<List<TreeOfGoods>> callback = new LoaderManager.LoaderCallbacks<List<TreeOfGoods>>() { @Override public Loader<List<TreeOfGoods>> onCreateLoader(int id, Bundle args) { return new TreeLoader(getApplicationContext()); } @Override public void onLoadFinished(Loader<List<TreeOfGoods>> loader, List<TreeOfGoods> data) { databaseTable.upgradeDB(); data.get(data.size()-1).resetID(); for (int i = 0; i < data.size(); i++) { data.get(i).numerateTree(); data.get(i).storeDataInDB(databaseTable.getDB()); } runOnUiThread(new Runnable() { @Override public void run() { fillList(); } }); } @Override public void onLoaderReset(Loader<List<TreeOfGoods>> loader) { loader.forceLoad(); } }; }
package Ejercicio; import java.util.Scanner; import javax.swing.JOptionPane; public class Burbuja { public static void main(String[] args) { Scanner entrada = new Scanner (System.in); int arreglo[],nElementos, aux; nElementos = Integer.parseInt(JOptionPane.showInputDialog("Digite la cantidad de números a ordenar")); arreglo=new int[nElementos]; for (int i=0; i<nElementos; i++) { System.out.println((i+1)+ "\n Digite el número a ordenar:"); arreglo [i] = entrada.nextInt(); } for (int i=0; i< (nElementos-1); i++) { for(int j=0; j<(nElementos-1);j++){ if(arreglo[j] > arreglo[j+1]) { aux = arreglo[j]; arreglo[j] =arreglo[j+1]; arreglo[j+1] = aux; } } } System.out.print("\n arreglo creciente"); for (int i=0; i<nElementos; i++) { System.out.println(arreglo[i]); } System.out.println(""); } }
/******************************************************************************* * Copyright (c) 2012, Eka Heksanov Lie * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the organization 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 COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package com.ehxnv.pvm.execution; import com.ehxnv.pvm.api.Process; import com.ehxnv.pvm.api.data.Data; import com.ehxnv.pvm.api.execution.NodeHandler; import com.ehxnv.pvm.api.execution.ProcessExecutionException; import com.ehxnv.pvm.api.execution.ProcessExecutor; import java.util.Set; /** * Abstract implementation of {@link ProcessExecutor} which adds state checking on initialize, execution and cleanup phase. * * @author Eka Lie */ public abstract class AbstractProcessExecutor implements ProcessExecutor { /** Represents the current state of the process executor. **/ private State state = State.UNINITIALIZED; /** * {@inheritDoc} */ public void init(final Process process, final Set<Data> datas) throws ProcessExecutionException { if (state != State.UNINITIALIZED) { throw new IllegalStateException("Failed to initialize process executor from non uninitialized state"); } initInternal(process, datas); state = State.READY; } /** * {@inheritDoc} */ @Override public Object executeNodeHandler(final Process process, final NodeHandler nodeHandler) throws ProcessExecutionException { if (state != State.READY) { throw new IllegalStateException("Failed to execute node handler from non ready state"); } return executeNodeHandlerInternal(process, nodeHandler); } /** * {@inheritDoc} */ public void finish() throws ProcessExecutionException { if (state != State.READY) { throw new IllegalStateException("Failed to finish process executor from non ready state"); } finishInternal(); } /** * Internal implementation of process executor to initialize itself. * @param process target process * @param datas execution input datas * @throws ProcessExecutionException if any exception occured during process execution */ protected abstract void initInternal(Process process, Set<Data> datas) throws ProcessExecutionException; /** * Internal implementation of process executor to execute a particular node handler * @param process target process * @param nodeHandler target node handler * @return execution result * @throws ProcessExecutionException if any exception occured during process execution */ protected abstract Object executeNodeHandlerInternal(Process process, NodeHandler nodeHandler) throws ProcessExecutionException; /** * Internal implementation of process executor for cleanup after process execution * @throws ProcessExecutionException if any exception occured during process execution */ protected abstract void finishInternal() throws ProcessExecutionException; /** * Process executor avaiable states. */ private static enum State { /** Process executor is not initialized and not ready to be used for execution. **/ UNINITIALIZED, /** Process executor is ready to be used for execution. **/ READY, /** Process executor has done his job. **/ FINISHED } }
/* * Copyright 2002-2020 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.http.server; import java.util.List; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; /** * Default implementation of {@link RequestPath}. * * @author Rossen Stoyanchev * @since 5.0 */ class DefaultRequestPath implements RequestPath { private final PathContainer fullPath; private final PathContainer contextPath; private final PathContainer pathWithinApplication; DefaultRequestPath(String rawPath, @Nullable String contextPath) { this.fullPath = PathContainer.parsePath(rawPath); this.contextPath = initContextPath(this.fullPath, contextPath); this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath); } private DefaultRequestPath(RequestPath requestPath, String contextPath) { this.fullPath = requestPath; this.contextPath = initContextPath(this.fullPath, contextPath); this.pathWithinApplication = extractPathWithinApplication(this.fullPath, this.contextPath); } private static PathContainer initContextPath(PathContainer path, @Nullable String contextPath) { if (!StringUtils.hasText(contextPath) || StringUtils.matchesCharacter(contextPath, '/')) { return PathContainer.parsePath(""); } validateContextPath(path.value(), contextPath); int length = contextPath.length(); int counter = 0; for (int i = 0; i < path.elements().size(); i++) { PathContainer.Element element = path.elements().get(i); counter += element.value().length(); if (length == counter) { return path.subPath(0, i + 1); } } // Should not happen.. throw new IllegalStateException("Failed to initialize contextPath '" + contextPath + "'" + " for requestPath '" + path.value() + "'"); } private static void validateContextPath(String fullPath, String contextPath) { int length = contextPath.length(); if (contextPath.charAt(0) != '/' || contextPath.charAt(length - 1) == '/') { throw new IllegalArgumentException("Invalid contextPath: '" + contextPath + "': " + "must start with '/' and not end with '/'"); } if (!fullPath.startsWith(contextPath)) { throw new IllegalArgumentException("Invalid contextPath '" + contextPath + "': " + "must match the start of requestPath: '" + fullPath + "'"); } if (fullPath.length() > length && fullPath.charAt(length) != '/') { throw new IllegalArgumentException("Invalid contextPath '" + contextPath + "': " + "must match to full path segments for requestPath: '" + fullPath + "'"); } } private static PathContainer extractPathWithinApplication(PathContainer fullPath, PathContainer contextPath) { return fullPath.subPath(contextPath.elements().size()); } // PathContainer methods.. @Override public String value() { return this.fullPath.value(); } @Override public List<Element> elements() { return this.fullPath.elements(); } // RequestPath methods.. @Override public PathContainer contextPath() { return this.contextPath; } @Override public PathContainer pathWithinApplication() { return this.pathWithinApplication; } @Override public RequestPath modifyContextPath(String contextPath) { return new DefaultRequestPath(this, contextPath); } @Override public boolean equals(@Nullable Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } DefaultRequestPath otherPath= (DefaultRequestPath) other; return (this.fullPath.equals(otherPath.fullPath) && this.contextPath.equals(otherPath.contextPath) && this.pathWithinApplication.equals(otherPath.pathWithinApplication)); } @Override public int hashCode() { int result = this.fullPath.hashCode(); result = 31 * result + this.contextPath.hashCode(); result = 31 * result + this.pathWithinApplication.hashCode(); return result; } @Override public String toString() { return this.fullPath.toString(); } }
package com.dqm.msg.common; import com.dqm.annotations.Index; import lombok.Getter; import lombok.Setter; /** * Created by dqm on 2018/8/31. */ @Getter @Setter public class InvVect { @Index(val = 0, specialType = Index.SpecialType.UINT32) private long type;//uint32_t【包含的值:0表示ERROR,数据可忽略;1表示MSG_TX,hash是关于交易的;2表示MSG_BLOCK,hash是关于区块的】 @Index(val = 1, size = 32) private String hash; }
package it.sevenbits.codecorrector.reader; /** * IReader interface * interface describes classes which provides character by character reading */ public interface IReader { /** * Read one character from reading stream * @return character of the reading stream * @throws ReaderException */ Character read() throws ReaderException; /** * Check for available characters to read * @return true if there are characters available for reading, false if not * @throws ReaderException */ Boolean hasNext() throws ReaderException; /** * Close reading stream * @throws ReaderException */ //void close() throws ReaderException; }
package com.gxtc.huchuan.ui.live.conversation; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.RectF; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.util.Base64; import android.widget.Toast; import com.gxtc.commlibrary.data.BaseRepository; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.FileUtil; import com.gxtc.commlibrary.utils.LogUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.bean.ChatInFoStatusBean; import com.gxtc.huchuan.bean.ChatInfosBean; import com.gxtc.huchuan.bean.LiveInsertBean; import com.gxtc.huchuan.bean.UploadPPTFileBean; import com.gxtc.huchuan.bean.event.EventMessageBean; import com.gxtc.huchuan.bean.event.EventSelectFriendForPostCardBean; import com.gxtc.huchuan.bean.pay.OrdersRequestBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.helper.GreenDaoHelper; import com.gxtc.huchuan.helper.RxTaskHelper; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.service.AllApi; import com.gxtc.huchuan.http.service.LiveApi; import com.gxtc.huchuan.im.Extra; import com.gxtc.huchuan.im.MessageFactory; import com.gxtc.huchuan.im.bean.RemoteMessageBean; import com.gxtc.huchuan.im.bean.RemoteMessageBeanDao; import com.gxtc.huchuan.im.manager.AudioRecordManager; import com.gxtc.huchuan.im.manager.ConversationManager; import com.gxtc.huchuan.im.manager.MessageManager; import com.gxtc.huchuan.im.manager.MessageUploadMyService; import com.gxtc.huchuan.im.provide.BlacklistMessage; import com.gxtc.huchuan.im.provide.CountDownMessage; import com.gxtc.huchuan.im.provide.PPTMessage; import com.gxtc.huchuan.im.provide.ReceivedMessage; import com.gxtc.huchuan.im.provide.RedPacketMessage; import com.gxtc.huchuan.im.provide.RemoveMessage; import com.gxtc.huchuan.im.provide.SilentMessage; import com.gxtc.huchuan.im.provide.VoiceMessageAdapter; import com.gxtc.huchuan.utils.DateUtil; import com.gxtc.huchuan.utils.ImMessageUtils; import com.gxtc.huchuan.utils.RIMErrorCodeUtil; import com.gxtc.huchuan.utils.RongIMTextUtil; import com.gxtc.huchuan.utils.StringUtil; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.model.FunctionConfig; import com.luck.picture.lib.model.FunctionOptions; import com.luck.picture.lib.model.PictureConfig; import org.greenrobot.eventbus.Subscribe; import org.json.JSONException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; import io.rong.common.FileUtils; import io.rong.imkit.RongIM; import io.rong.imlib.IRongCallback; import io.rong.imlib.MessageTag; import io.rong.imlib.RongIMClient; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Message; import io.rong.imlib.model.UserInfo; import io.rong.message.ImageMessage; import io.rong.message.TextMessage; import io.rong.message.VoiceMessage; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import top.zibin.luban.Luban; import top.zibin.luban.OnCompressListener; /** * Created by Gubr on 2017/2/20. * */ public class LiveConversationPresenter extends BaseRepository implements LiveConversationContract.Presenter, PictureConfig.OnSelectResultCallback { private static final String TAG = "LiveConversationPresent"; private static final int REQUSET_IMAGE = 1 << 3; public static final String THUMURI_SUFFIX = "!upyun200"; private LiveConversationContract.View mView; private ChatInfosBean mBean; private String chatRoomId; private String author, host;//作者 主持人: private List<Message> discuss; private UserInfo mUserInfo; private Handler mHandler; private Message message; private Message mObtain; private boolean hasCoundDown, hasInvitationLecturer, hasInVitationAudience, hasReceivedMessage; private String token; //因为 倒计时 邀请 等信息体是不会传到服务器的 但是又要显示在信息里面 为了避免错乱 在跟服务器请求更多历史消息的时候 要先减掉这个数 private int getMinus() { int temp = 0; if (hasCoundDown) ++temp; if (hasInvitationLecturer) ++temp; if (hasInVitationAudience) ++temp; if (hasReceivedMessage) ++temp; return temp; } public LiveConversationPresenter(LiveConversationContract.View view, ChatInfosBean bean, String chatRoomId, String author, String host) { mBean = bean; token = com.gxtc.huchuan.data.UserManager.getInstance().getToken(); this.chatRoomId = mBean.getId(); this.author = author; this.host = host; EventBusUtil.register(this); ConversationManager.getInstance().init(mBean); mHandler = new MyHandler(); String headPic = UserManager.getInstance().getUser().getHeadPic(); Uri uri = null; if (headPic != null) { uri = Uri.parse(headPic); } mUserInfo = new UserInfo(UserManager.getInstance().getUserCode(), UserManager.getInstance().getUser().getName(), uri); mView = view; mView.setPresenter(this); //获取服务器上的课件数据 getChatInfoSlideList(); mView.notifyChangeData(); mView.showLoadDialog(true); //这里获取聊天历史记录 ConversationManager.getInstance().getremoteHistory(10000, "", new ConversationManager.CallBack() { @Override public void onSuccess(List<Message> messages) { if(mView == null) return; mView.showLoadDialog(false); /** * isBackLoadMsg * 这个表示是判断是否是从后台播放语音的时候 从服务器拿数据的标志 * 因为后台播放语音的时候拿的数据 只拿 语音消息 有可能语音消息之前参杂有图片消息文字消息 * 这时候再进入课堂页面听课的话 就拿不到前面的消息了 ,这时候需要根据这个标志去后台从新请求课堂页面全部的消息回来 */ MessageManager.getInstance().addMessages(messages); addConversationHeadViews(); mView.notifyChangeData(); } @Override public void onError(String message) { if(mView == null) return; mView.showLoadDialog(false); } @Override public void onCancel() { if(mView == null) return; mView.showLoadDialog(false); } }); } private boolean islaodTopicHistoring = false; @Override public void remoteTopicHistory() { if (islaodTopicHistoring) { return; } HashMap<String, String> map = new HashMap<>(); map.put("token", com.gxtc.huchuan.data.UserManager.getInstance().getToken()); map.put("targetType", Conversation.ConversationType.CHATROOM.getValue() + ""); map.put("targetId", chatRoomId); map.put("start", "0"); map.put("roleType", "2"); LiveApi.getInstance() .getMessageRecordList(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .map(new Func1<ApiResponseBean<List<RemoteMessageBean>>, List<Message>>() { @Override public List<Message> call(ApiResponseBean<List<RemoteMessageBean>> listApiResponseBean) { return MessageFactory.create(listApiResponseBean.getResult()); } }) .subscribe(new Observer<List<Message>>() { @Override public void onCompleted() { islaodTopicHistoring = false; } @Override public void onError(Throwable e) { } @Override public void onNext(List<Message> messages) { if (mView != null) { mView.showDiscussIntro(messages); } } }); } /** * 如果新建的话 应该可以添加 如果是拿 历史数据的话 应该是 先看是否已经到最上面的时候再添加这些消息。 */ private void addConversationHeadViews() { if (!TextUtils.isEmpty(mBean.getStarttime()) && DateUtil.isDeadLine(mBean.getStarttime())) { addCoundDownView(); } } /** * 获取后面的历史数据 */ @Override public void getDownRemoteHistory() { Message lastMessage = MessageManager.getInstance().getLastMessage(); Extra extra = null; if (lastMessage != null) { extra = new Extra(extraStr(lastMessage)); } if (extra != null) { ConversationManager.getInstance().downRmoteHistory(extra.getMsgId(), "1", "2", new ConversationManager.CallBack() { @Override public void onSuccess(List<Message> messages) { if(mView == null) return; if (messages.size() == 0) { mView.downRefreshFinish(); } else { MessageManager.getInstance().addMessages(messages); mView.notifyChangeData(); } } @Override public void onError(String message) {} @Override public void onCancel() {} }); } else { if(mView == null) return; mView.downRefreshFinish(); } } /** * 获取更前的历史数据 */ @Override public void getUpRemoteHistory() { Message firstMessage = MessageManager.getInstance().getFirstMessage(); String extraStr = null; if(mView == null) return; if (firstMessage == null) { mView.upRefreshFinish(); return; } else { extraStr = extraStr(firstMessage); if (extraStr == null) { mView.upRefreshFinish(); return; } Extra extra = new Extra(extraStr); if (extra != null) ConversationManager.getInstance().upRemoteHistory(extra.getMsgId(), "1", "1", new ConversationManager.CallBack() { @Override public void onSuccess(List<Message> messages) { if (messages.size() > 0) { MessageManager.getInstance().addMessagesToHead(messages); } else { addConversationHeadViews(); } if(mView == null) return; mView.upRefreshFinish(); } @Override public void onError(String message) { if(mView == null) return; mView.upRefreshFinish(); } @Override public void onCancel() { if(mView == null) return; mView.upRefreshFinish(); } }); } } private void addCoundDownView() { Message message = null; if (MessageManager.getInstance().getMessages().size() > 0) { message = MessageManager.getInstance().getMessages().get(0); } if (message == null || (!"XM:CdMsg".equals(message.getObjectName()) && !hasCoundDown)) { CountDownMessage countDownMessage = new CountDownMessage(new byte[]{}); countDownMessage.setTimestamp(mBean.getStarttime()); countDownMessage.setContent(mBean.getSubtitle()); Message message1 = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, countDownMessage); message1.setObjectName(CountDownMessage.class.getAnnotation(MessageTag.class).value()); MessageManager.getInstance().addMessage(message1, 0); } hasCoundDown = true; } @Override public void setCanLoadRemoteMessage(boolean flag) { ConversationManager.getInstance().setCanLoadRemoteMessage(flag); } private void addReceivedMessage() { int tempPosition = 0; if (hasReceivedMessage) return; if (hasCoundDown) ++tempPosition; Message message = null; if (MessageManager.getInstance().getMessages().size() > tempPosition) { message = MessageManager.getInstance().getMessages().get(tempPosition); } if (message == null || (!"XM:ReMsg".equals(message.getObjectName()))) { ReceivedMessage receivedMessage = new ReceivedMessage(new byte[]{}); receivedMessage.setContent(mBean.getId()); receivedMessage.setUserInfo(mUserInfo); Message obtain = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, receivedMessage); obtain.setObjectName(ReceivedMessage.class.getAnnotation(MessageTag.class).value()); MessageManager.getInstance().addMessage(obtain, tempPosition); } hasReceivedMessage = true; } @Override public void showDiscussIntro() { } @Override public void showDiscussLabel() { } @Override public void showRedpacket() { } /** * 获取服务器上的课件数据 */ private void getChatInfoSlideList() { addSub(LiveApi.getInstance() .getChatInfoSlideList(UserManager.getInstance().getToken(), chatRoomId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<List<UploadPPTFileBean>>>( new ApiCallBack<List<UploadPPTFileBean>>() { @Override public void onSuccess(List<UploadPPTFileBean> data) { if (mView != null) { ArrayList<Uri> uris = new ArrayList<>(); for (UploadPPTFileBean uploadPPTFileBean : data) { uris.add(Uri.parse(uploadPPTFileBean.getPicUrl())); } mView.showPPT(uris); } } @Override public void onError(String errorCode, String message) {} }))); } @Override public void showImageSelectView() { FunctionOptions options = new FunctionOptions.Builder() .setType(FunctionConfig.TYPE_IMAGE) .setSelectMode(FunctionConfig.MODE_MULTIPLE) .setMaxSelectNum(9) .setImageSpanCount(3) .setEnableQualityCompress(false) //是否启质量压缩 .setEnablePixelCompress(false) //是否启用像素压缩 .setEnablePreview(true) // 是否打开预览选项 .setShowCamera(true) .setPreviewVideo(true) .create(); PictureConfig.getInstance().init(options).openPhoto((Activity) mView.getContext(), this); } @Override public void sendAudienceMessage(String msg, boolean b) { sendMessage(msg, "2", b); } private void sendMessage(String msg, String sendertype, boolean b) { TextMessage myTextMessage = TextMessage.obtain(msg); long currentTimeMillis = System.currentTimeMillis(); long msgId = currentTimeMillis + (new Random().nextInt(99999 - 10000) + 10000); final Extra extra = Extra.obtan(sendertype, b, mBean.getId() + msgId, "1"); extra.setSentTime(currentTimeMillis); myTextMessage.setUserInfo(mUserInfo); myTextMessage.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, myTextMessage); message.setExtra(extra.encode()); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { message.setExtra(((TextMessage) message.getContent()).getExtra()); Extra extra1 = new Extra(((TextMessage) message.getContent()).getExtra()); if(mView != null){ if ("2".equals(extra1.getSenderType())) { mView.addDiscussIntro(message); } else { mView.addMessage(message); } } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { if(mView == null) return; ToastUtil.showShort(mView.getContext(),RIMErrorCodeUtil.handleErrorCode(errorCode)); } }); } /** * 发送文本信息 * * @param string */ @Override public void sendMessage(String string) { sendMessage(string, mBean.isSelff() ? "3" : "1", false); } @Override public void start() { RongIMClient.getInstance().joinExistChatRoom("lskdjf", 50, new RongIMClient.OperationCallback() { @Override public void onSuccess() {} @Override public void onError(RongIMClient.ErrorCode errorCode) {} }); } @Override public void destroy() { super.destroy(); mView = null; EventBusUtil.unregister(this); RxTaskHelper.getInstance().cancelTask(this); } @Subscribe public void onEvent(EventMessageBean bean){ if (!bean.mMessage.getTargetId().equals(chatRoomId) && mView != null) { return ; } String extraStr = extraStr(bean.mMessage); Extra extra = null; if (extraStr != null) { extra = new Extra(extraStr); switch (extra.getSenderType()) { case "1": case "3": setCanLoadRemoteMessage(false); //只要监听到收到消息 就不再可以去服务器请求历史消息 if (mView != null) { mView.downRefreshFinish(); } mView.addMessage(bean.mMessage); break; case "2": if("XM:RmMsg".equals(bean.mMessage.getObjectName())){ mView.showRemoveDiscussIntro(bean.mMessage); }else{ mView.addDiscussIntro(bean.mMessage); } break; case "4": if (bean.mMessage.getObjectName().equals("XM:SLMsg")) { changeSilentModel(bean.mMessage); } if (bean.mMessage.getObjectName().equals("XM:PPTMsg")) { changePPT(); } if (bean.mMessage.getObjectName().equals("XM:RmMsg")) { removeMessagebyRemote(bean.mMessage); } if(bean.mMessage.getObjectName().equals("XM:BLMsg")){ kickOutRoom(bean.mMessage); } break; case "": changePPT(); } } } //踢出聊天室 private void kickOutRoom(Message message) { BlacklistMessage blackMsg = (BlacklistMessage) message.getContent(); if(blackMsg.getUserCode().equals(UserManager.getInstance().getUserCode())){ mView.showKickOutRoom(); } } private void removeMessagebyRemote(Message message) { RemoveMessage removeMessage = (RemoveMessage) message.getContent(); List<RemoteMessageBean> list = GreenDaoHelper.getInstance().getSeeion().getRemoteMessageBeanDao().queryBuilder().where( RemoteMessageBeanDao.Properties.MsgId.eq(removeMessage.getContent())).limit( 1).build().list(); if (list.size() > 0) { GreenDaoHelper.getInstance().getSeeion().getRemoteMessageBeanDao().deleteInTx(list); } Message message1 = MessageManager.getInstance().removeMessage(String.valueOf(removeMessage.getContent())); mView.removeMessage(message1); } private void changePPT() { addSub(LiveApi.getInstance() .getChatInfoSlideList(UserManager.getInstance().getToken(), chatRoomId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<List<UploadPPTFileBean>>>( new ApiCallBack<List<UploadPPTFileBean>>() { @Override public void onSuccess(List<UploadPPTFileBean> data) { if (mView != null) { ArrayList<Uri> uris = new ArrayList<>(); for (UploadPPTFileBean uploadPPTFileBean : data) { uris.add(Uri.parse(uploadPPTFileBean.getPicUrl())); } mView.changePPT(uris); } } @Override public void onError(String errorCode, String message) { } }))); } private void changeSilentModel(Message message) { SilentMessage content = (SilentMessage) message.getContent(); boolean b = Boolean.parseBoolean(content.getContent()); String targetUserCode = content.getUserCode(); if (content.getUserCode().equals("0") || targetUserCode.equals(UserManager.getInstance().getUserCode())) { mBean.setIsBanned(b ? "1" : "0"); mView.setSilentModel(b); } } LinkedList<String> mImageList; @Override public void sendImageMessage(List<String> imagePath) { if (mImageList == null) { mImageList = new LinkedList<>(); } mImageList.addAll(imagePath); sendImageMessage(); } @Override public void sendRedPacketMessage(OrdersRequestBean requestBean) { String extra1 = requestBean.getExtra(); String totalPrice = requestBean.getTotalPrice(); double money = Double.valueOf(totalPrice); double price = money / 100.0d; String userCode = ""; String name = ""; try { org.json.JSONObject jsonObject = new org.json.JSONObject(extra1); if (jsonObject.has("userCode")) { userCode = jsonObject.optString("userCode"); } if (jsonObject.has("name")) { name = jsonObject.optString("name"); } } catch (JSONException e) { e.printStackTrace(); } RedPacketMessage redPacketMessage = RedPacketMessage.obtain(mUserInfo.getName(), name, price + ""); long currentTimeMillis = System.currentTimeMillis(); final Extra extra = Extra.obtan("1", false, mBean.getId() + currentTimeMillis, "1"); extra.setSentTime(currentTimeMillis); redPacketMessage.setUserInfo(mUserInfo); redPacketMessage.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, redPacketMessage); message.setExtra(extra.encode()); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) {} @Override public void onSuccess(Message message) { message.setExtra(((RedPacketMessage) message.getContent()).getExtra()); Extra extra1 = new Extra(((RedPacketMessage) message.getContent()).getExtra()); if ("2".equals(extra1.getSenderType())) { mView.addDiscussIntro(message); } else { mView.addMessage(message); } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { Toast.makeText(MyApplication.getInstance(), "信息发送失败", Toast.LENGTH_SHORT).show(); } }); } @Override public void sendPPTChnageMessage() { PPTMessage pptMessage = PPTMessage.obtain(); long currentTimeMillis = System.currentTimeMillis(); final Extra extra = Extra.obtan("4", false, mBean.getId() + currentTimeMillis,"0"); extra.setSentTime(currentTimeMillis); pptMessage.setUserInfo(mUserInfo); pptMessage.setExtra(extra.encode()); Message message = Message.obtain(mBean.getId(), Conversation.ConversationType.CHATROOM, pptMessage); message.setExtra(extra.encode()); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } }); } //删除消息 不要加isClass标记 public void sendRemoveMessage(long msgId) { RemoveMessage removeMessage = RemoveMessage.obtain(); long currentTimeMillis = System.currentTimeMillis(); final Extra extra = Extra.obtan("4", false, mBean.getId() + currentTimeMillis,"0"); extra.setSentTime(currentTimeMillis); removeMessage.setUserInfo(mUserInfo); removeMessage.setContent(String.valueOf(msgId)); removeMessage.setExtra(extra.encode()); Message message = Message.obtain(mBean.getId(), Conversation.ConversationType.CHATROOM, removeMessage); message.setExtra(extra.encode()); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } }); } @Override public void sendPPTImageMessage(String clickImage) { ImageMessage imageMessage = new ImageMessage(); long currentTimeMillis = System.currentTimeMillis(); Extra extra = Extra.obtan(mBean.isSelff() ? "3" : "1", false, mBean.getId() + currentTimeMillis,"1"); extra.setSentTime(currentTimeMillis); imageMessage.setUserInfo(mUserInfo); Uri imageUri = Uri.parse(clickImage); imageMessage.setLocalUri(imageUri); imageMessage.setRemoteUri(imageUri); imageMessage.setThumUri(imageUri); imageMessage.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, imageMessage); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { message.setExtra(((ImageMessage) message.getContent()).getExtra()); Extra extra1 = new Extra(((ImageMessage) message.getContent()).getExtra()); if ("2".equals(extra1.getSenderType())) { mView.addDiscussIntro(message); } else { mView.addMessage(message); } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } }); } public void sendImageMessage() { if (mImageList.size() > 0) compressImg(mImageList.removeLast()); } public void compressImg(final String s) { //将图片进行压缩 final File file = new File(s); final long minSize= Constant.COMPRESS_VALUE; if(FileUtil.getSize(file) > minSize){ Luban.get(MyApplication.getInstance()).load(file) //传人要压缩的图片 .putGear(Luban.THIRD_GEAR) //设定压缩档次,默认三挡 .setCompressListener(new OnCompressListener() { @Override public void onStart() { } @Override public void onSuccess(File file) { sendImageMessage(file); } // 当压缩过去出现问题时调用 @Override public void onError(Throwable e) { } }).launch(); }else { sendImageMessage(file); } } /** * 发送图片 * * @param imagePath 图片地址 */ public void sendImageMessage(File imagePath) { final ImageMessage imgMsg = ImageMessage.obtain(Uri.fromFile(imagePath), Uri.fromFile(imagePath), false); imgMsg.setUserInfo(mUserInfo); Extra extra = Extra.obtan(mBean.isSelff() ? "3" : "1", mView.getIsAsk(), mBean.getId() + System.currentTimeMillis(),"1"); imgMsg.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, imgMsg); RongIM.getInstance().sendImageMessage(message, null, null, new RongIMClient.SendImageMessageWithUploadListenerCallback() { @Override public void onAttached(Message message, RongIMClient.UploadImageStatusListener uploadImageStatusListener) { Uri localUri = ((ImageMessage) message.getContent()).getLocalUri(); uploadImage(localUri, uploadImageStatusListener); } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } @Override public void onSuccess(Message message) { if(mView == null) return; ImageMessage content = (ImageMessage) message.getContent(); String s = content.getRemoteUri().toString(); s = s + THUMURI_SUFFIX; content.setThumUri(Uri.parse(s)); content.setLocalUri(content.getRemoteUri()); message.setExtra(content.getExtra()); mView.addMessage(message); sendImageMessage(); } @Override public void onProgress(Message message, int i) { } }); } public void sendImageMessage(String imagePath) { long l = System.currentTimeMillis(); File imageFileSource = new File(mView.getContext().getCacheDir(), l + "source.jpg"); File imageFileThumb = new File(mView.getContext().getCacheDir(), l + "thumb.jpg"); File file = new File(imagePath); if (file.exists()) { try { FileInputStream inputStream = new FileInputStream(file); Bitmap bmpSource = BitmapFactory.decodeStream(inputStream); imageFileSource.createNewFile(); FileOutputStream fosSource = new FileOutputStream(imageFileSource); bmpSource.compress(Bitmap.CompressFormat.JPEG, 100, fosSource); Matrix matrix = new Matrix(); RectF rectF = new RectF(); if (bmpSource.getWidth() > 480) { double i = bmpSource.getWidth() / 480.0; int height = (int) (bmpSource.getHeight() / i); rectF.set(0, 0, 480, height); } else { rectF.set(0, 0, bmpSource.getWidth(), bmpSource.getHeight()); } matrix.setRectToRect(new RectF(0, 0, bmpSource.getWidth(), bmpSource.getHeight()), rectF, Matrix.ScaleToFit.CENTER); Bitmap bmpThumb = Bitmap.createBitmap(bmpSource, 0, 0, bmpSource.getWidth(), bmpSource.getHeight(), matrix, true); imageFileThumb.createNewFile(); FileOutputStream fosThumb = new FileOutputStream(imageFileThumb); bmpThumb.compress(Bitmap.CompressFormat.JPEG, 80, fosThumb); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } final ImageMessage imgMsg = ImageMessage.obtain(Uri.fromFile(imageFileThumb), Uri.fromFile(imageFileSource), true); imgMsg.setUserInfo(mUserInfo); Extra extra = Extra.obtan(mBean.isSelff() ? "3" : "1", mView.getIsAsk(), mBean.getId() + System.currentTimeMillis(),"1"); imgMsg.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, imgMsg); RongIM.getInstance().sendImageMessage(message, null, null, new RongIMClient.SendImageMessageWithUploadListenerCallback() { @Override public void onAttached(Message message, RongIMClient.UploadImageStatusListener uploadImageStatusListener) { Uri localUri = ((ImageMessage) message.getContent()).getLocalUri(); uploadImage(localUri, uploadImageStatusListener); } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { } @Override public void onSuccess(Message message) { ImageMessage content = (ImageMessage) message.getContent(); content.setThumUri(content.getRemoteUri()); content.setLocalUri(content.getRemoteUri()); mView.addMessage(message); sendImageMessage(); } @Override public void onProgress(Message message, int i) { } }); } } /** * 上传IM图片到自己的服务器 */ public void uploadImage(Uri uri, final RongIMClient.UploadImageStatusListener uploadImageStatusListener) { File file = new File(uri.getPath()); MultipartBody build = new MultipartBody.Builder().setType( MultipartBody.FORM).addFormDataPart("token", token).addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image*//**//*"), file)).build(); addSub(LiveApi.getInstance() .uploadIMFile(build) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<List<String>>>(new ApiCallBack<List<String>>() { @Override public void onSuccess(List<String> data) { if(uploadImageStatusListener == null) return; if (data.size() > 0) { String uriString = data.get(0); Uri iamgeUri = Uri.parse(uriString); uploadImageStatusListener.success(iamgeUri); } else { uploadImageStatusListener.error(); } } @Override public void onError(String errorCode, String message) { if(uploadImageStatusListener == null) return; uploadImageStatusListener.error(); } }))); } /** * 发送语音信息 */ @Override public void sendVoiceMessage() { Uri audioPath = AudioRecordManager.getInstance().getAudioPath(); int duration = AudioRecordManager.getInstance().getDuration(); if (audioPath == null || duration < 3) { //这里 取消发送 return; } VoiceMessage vocMsg = VoiceMessage.obtain(audioPath, duration); vocMsg.setUserInfo(mUserInfo); Extra extra = Extra.obtan(mBean.isSelff() ? "3" : "1", mView.getIsAsk(), mBean.getId() + System.currentTimeMillis(),"1"); vocMsg.setExtra(extra.encode()); Message message = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, vocMsg); RongIM.getInstance().sendMessage(message, null, null, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { VoiceMessage content = (VoiceMessage) message.getContent(); } @Override public void onSuccess(Message message) { VoiceMessage content = (VoiceMessage) message.getContent(); uploadVoiceMessagev2(content); if(mView == null) return; mView.addMessage(message); LogUtil.i("发送语音消息成功 : 时长" + content.getDuration()); } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { LogUtil.i("发送语音消息失败 : " + errorCode ); } }); } @Override public void joinChatRoom(String charRoomgId) { } @Override public void removeMessage(final Message message) { MessageUploadMyService.removeMessage(message, new MessageUploadMyService.CallBack() { @Override public void onSuccess() { Extra extra = MessageFactory.getExtrabyMessage(message); if (extra==null) { return; } MessageManager.getInstance().removeMessage(message); mView.removeMessage(message); List<RemoteMessageBean> list = GreenDaoHelper.getInstance().getSeeion().getRemoteMessageBeanDao().queryBuilder().where( RemoteMessageBeanDao.Properties.MsgId.eq(extra.getMsgId())).limit( 1).build().list(); if (list.size() > 0) { GreenDaoHelper.getInstance().getSeeion().getRemoteMessageBeanDao().deleteInTx( list); } sendRemoveMessage(Long.valueOf(extra.getMsgId())); } @Override public void onError(String message) { } @Override public void onCancel() { } }); } private void uploadVoiceMessagev2(final VoiceMessage message) { File file = new File(message.getUri().getPath()); Subscription sub = Observable.just(message) .subscribeOn(Schedulers.io()) .map(new Func1<VoiceMessage, Message>() { @Override public Message call(VoiceMessage voiceMessage) { Uri uri = voiceMessage.getUri(); byte[] voiceData = FileUtils.getByteFromUri(uri); try { String var9 = Base64.encodeToString(voiceData, 2); voiceMessage.setBase64(var9); } catch (IllegalArgumentException var8) { var8.printStackTrace(); } Message mObtain = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, voiceMessage); mObtain.setObjectName(VoiceMessageAdapter.class.getAnnotation(MessageTag.class).value()); mObtain.setExtra(voiceMessage.getExtra()); return mObtain; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Message>() { @Override public void call(Message message) { } }); addSub(sub); } private void uploadVoiceMessage(final VoiceMessage message) { File file = new File(message.getUri().getPath()); final RequestBody requestBody = new MultipartBody.Builder().setType( MultipartBody.FORM).addFormDataPart("token", com.gxtc.huchuan.data.UserManager.getInstance().getToken()).addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("audio*//**/*"), file)).build(); Subscription sub = LiveApi.getInstance() .uploadIMFile(requestBody) .subscribeOn(Schedulers.io()) .map(new Func1<ApiResponseBean<List<String>>, Message>() { @Override public Message call(ApiResponseBean<List<String>> uploadFileBeanApiResponseBean) { List<String> datas = uploadFileBeanApiResponseBean.getResult(); VoiceMessageAdapter voiceMessageAdapter = null; for (String data : datas) { voiceMessageAdapter = new VoiceMessageAdapter(message, data); } mObtain = Message.obtain(chatRoomId, Conversation.ConversationType.CHATROOM, voiceMessageAdapter); mObtain.setObjectName(VoiceMessageAdapter.class.getAnnotation(MessageTag.class).value()); mObtain.setExtra(message.getExtra()); return mObtain; } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Message>() { @Override public void call(Message message) { } }); addSub(sub); } @Override public void collect(String classId) { HashMap<String, String> map = new HashMap<>(); map.put("token", UserManager.getInstance().getToken()); map.put("bizType", "2"); map.put("bizId", classId); Subscription subThumbsup = AllApi.getInstance().saveCollection(map).subscribeOn( Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(mView != null){ mView.showCollectResult(true,""); } } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showCollectResult(false,message); } } })); RxTaskHelper.getInstance().addTask(this,subThumbsup); } @Override public void follow() { if(mBean != null){ mView.showLoad(); Subscription sub = LiveApi.getInstance() .setUserFollow(UserManager.getInstance().getToken(), "2", mBean.getChatRoom()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack() { @Override public void onSuccess(Object data) { mBean.setIsFollow("1"); if(mView != null){ mView.showLoadFinish(); mView.showFollowResult(true, null); } } @Override public void onError(String errorCode, String message) { if(mView != null){ mView.showLoadFinish(); mView.showError(message); } } })); RxTaskHelper.getInstance().addTask(this,sub); } } //分享到好友 @Override public void shareMessage(final String targetId, final Conversation.ConversationType type, final String title, String img, String id,final String liuyan){ ImMessageUtils.shareMessage(targetId, type, id, title, img, "2", new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) {} @Override public void onSuccess(Message message) { if(mView != null){ mView.sendMessage(); if(!TextUtils.isEmpty(liuyan)){ RongIMTextUtil.INSTANCE.relayMessage (liuyan,targetId,type); } } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { if(mView != null){ mView.showError("分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode)); } } }); } //发送名片 @Override public void sendVisitingCard(final EventSelectFriendForPostCardBean bean) { // 1:圈子,2:文章,3:课程,4:交易,5:商品 6: 个人名片 LiveInsertBean insertBean = new LiveInsertBean(StringUtil.toInt(bean.userCode)); insertBean.setInfoType(LiveInsertChooseActivity.TYPE_VISITING_CARD + ""); insertBean.setTitle(bean.name); insertBean.setCover(bean.picHead); ImMessageUtils.sendShareMessage(mBean.isSelff()? "3" : "1", chatRoomId,insertBean, new IRongCallback.ISendMessageCallback() { @Override public void onAttached(Message message) { } @Override public void onSuccess(Message message) { if(mView != null){ mView.addMessage(message); if(!TextUtils.isEmpty(bean.liuyan)){ sendMessage(bean.liuyan, mBean.isSelff()? "3" : "1", false); } } } @Override public void onError(Message message, RongIMClient.ErrorCode errorCode) { if(mView != null){ mView.showError("发送失败 : " + errorCode); } } }); } @Override public void getChatinfosStatus() { HashMap<String, String> map = new HashMap<>(); map.put("token", UserManager.getInstance().getToken()); map.put("chatInfoId", mBean.getId()); addSub(LiveApi.getInstance() .getChatInfoStatus(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<ChatInFoStatusBean>>( new ApiCallBack<ChatInFoStatusBean>() { @Override public void onSuccess(ChatInFoStatusBean data) { if(mBean == null) return; if("1".equals(mBean.getIsBanned()) || "1".equals(data.getIsBanned()) || "1".equals(data.getIsBlock()) || "1".equals(data.getIsBlack())){ mView.setSilentModel(true); }else{ mView.setSilentModel(false); } } @Override public void onError(String errorCode, String message) {} }))); } @Override public void onSelectSuccess(List<LocalMedia> resultList) { List<String> paths = new ArrayList<>(); for(LocalMedia media: resultList){ paths.add(media.getPath()); } sendImageMessage(paths); } @Override public void onSelectSuccess(LocalMedia media) { } private class MyHandler extends Handler { @Override public void handleMessage(android.os.Message msg) { if (msg != null && msg.obj instanceof Message) { } else { super.handleMessage(msg); } } } private String extraStr(Message message) { switch (message.getObjectName()) { case "RC:VcMsg": return ((VoiceMessage) message.getContent()).getExtra(); case "RC:TxtMsg": return ((TextMessage) message.getContent()).getExtra(); case "RC:ImgMsg": return ((ImageMessage) message.getContent()).getExtra(); case "XM:CdMsg": return ((CountDownMessage) message.getContent()).getExtra(); case "XM:RpMsg": return ((RedPacketMessage) message.getContent()).getExtra(); case "XM:SLMsg": return ((SilentMessage) message.getContent()).getExtra(); case "XM:PPTMsg": return ((PPTMessage) message.getContent()).getExtra(); case "XM:RmMsg": return ((RemoveMessage) message.getContent()).getExtra(); case "XM:BLMsg": return ((BlacklistMessage) message.getContent()).getExtra(); } return null; } }
package com.zym.blog.model.example; import java.util.ArrayList; import java.util.Date; import java.util.List; public class BlogExample { protected String pk_name = "blog_id"; protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public BlogExample() { oredCriteria = new ArrayList<Criteria>(); } public void setPk_name(String pk_name) { this.pk_name = pk_name; } public String getPk_name() { return pk_name; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andBlogIdIsNull() { addCriterion("blog_id is null"); return (Criteria) this; } public Criteria andBlogIdIsNotNull() { addCriterion("blog_id is not null"); return (Criteria) this; } public Criteria andBlogIdEqualTo(Integer value) { addCriterion("blog_id =", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdNotEqualTo(Integer value) { addCriterion("blog_id <>", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdGreaterThan(Integer value) { addCriterion("blog_id >", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdGreaterThanOrEqualTo(Integer value) { addCriterion("blog_id >=", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdLessThan(Integer value) { addCriterion("blog_id <", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdLessThanOrEqualTo(Integer value) { addCriterion("blog_id <=", value, "blogId"); return (Criteria) this; } public Criteria andBlogIdIn(List<Integer> values) { addCriterion("blog_id in", values, "blogId"); return (Criteria) this; } public Criteria andBlogIdNotIn(List<Integer> values) { addCriterion("blog_id not in", values, "blogId"); return (Criteria) this; } public Criteria andBlogIdBetween(Integer value1, Integer value2) { addCriterion("blog_id between", value1, value2, "blogId"); return (Criteria) this; } public Criteria andBlogIdNotBetween(Integer value1, Integer value2) { addCriterion("blog_id not between", value1, value2, "blogId"); return (Criteria) this; } public Criteria andBlogTitleIsNull() { addCriterion("blog_title is null"); return (Criteria) this; } public Criteria andBlogTitleIsNotNull() { addCriterion("blog_title is not null"); return (Criteria) this; } public Criteria andBlogTitleEqualTo(String value) { addCriterion("blog_title =", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleNotEqualTo(String value) { addCriterion("blog_title <>", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleGreaterThan(String value) { addCriterion("blog_title >", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleGreaterThanOrEqualTo(String value) { addCriterion("blog_title >=", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleLessThan(String value) { addCriterion("blog_title <", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleLessThanOrEqualTo(String value) { addCriterion("blog_title <=", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleLike(String value) { addCriterion("blog_title like", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleNotLike(String value) { addCriterion("blog_title not like", value, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleIn(List<String> values) { addCriterion("blog_title in", values, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleNotIn(List<String> values) { addCriterion("blog_title not in", values, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleBetween(String value1, String value2) { addCriterion("blog_title between", value1, value2, "blogTitle"); return (Criteria) this; } public Criteria andBlogTitleNotBetween(String value1, String value2) { addCriterion("blog_title not between", value1, value2, "blogTitle"); return (Criteria) this; } public Criteria andBlogTypeIsNull() { addCriterion("blog_type is null"); return (Criteria) this; } public Criteria andBlogTypeIsNotNull() { addCriterion("blog_type is not null"); return (Criteria) this; } public Criteria andBlogTypeEqualTo(Integer value) { addCriterion("blog_type =", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeNotEqualTo(Integer value) { addCriterion("blog_type <>", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeGreaterThan(Integer value) { addCriterion("blog_type >", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeGreaterThanOrEqualTo(Integer value) { addCriterion("blog_type >=", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeLessThan(Integer value) { addCriterion("blog_type <", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeLessThanOrEqualTo(Integer value) { addCriterion("blog_type <=", value, "blogType"); return (Criteria) this; } public Criteria andBlogTypeIn(List<Integer> values) { addCriterion("blog_type in", values, "blogType"); return (Criteria) this; } public Criteria andBlogTypeNotIn(List<Integer> values) { addCriterion("blog_type not in", values, "blogType"); return (Criteria) this; } public Criteria andBlogTypeBetween(Integer value1, Integer value2) { addCriterion("blog_type between", value1, value2, "blogType"); return (Criteria) this; } public Criteria andBlogTypeNotBetween(Integer value1, Integer value2) { addCriterion("blog_type not between", value1, value2, "blogType"); return (Criteria) this; } public Criteria andBlogLabelIsNull() { addCriterion("blog_label is null"); return (Criteria) this; } public Criteria andBlogLabelIsNotNull() { addCriterion("blog_label is not null"); return (Criteria) this; } public Criteria andBlogLabelEqualTo(String value) { addCriterion("blog_label =", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelNotEqualTo(String value) { addCriterion("blog_label <>", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelGreaterThan(String value) { addCriterion("blog_label >", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelGreaterThanOrEqualTo(String value) { addCriterion("blog_label >=", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelLessThan(String value) { addCriterion("blog_label <", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelLessThanOrEqualTo(String value) { addCriterion("blog_label <=", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelLike(String value) { addCriterion("blog_label like", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelNotLike(String value) { addCriterion("blog_label not like", value, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelIn(List<String> values) { addCriterion("blog_label in", values, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelNotIn(List<String> values) { addCriterion("blog_label not in", values, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelBetween(String value1, String value2) { addCriterion("blog_label between", value1, value2, "blogLabel"); return (Criteria) this; } public Criteria andBlogLabelNotBetween(String value1, String value2) { addCriterion("blog_label not between", value1, value2, "blogLabel"); return (Criteria) this; } public Criteria andAuthorIsNull() { addCriterion("author is null"); return (Criteria) this; } public Criteria andAuthorIsNotNull() { addCriterion("author is not null"); return (Criteria) this; } public Criteria andAuthorEqualTo(String value) { addCriterion("author =", value, "author"); return (Criteria) this; } public Criteria andAuthorNotEqualTo(String value) { addCriterion("author <>", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThan(String value) { addCriterion("author >", value, "author"); return (Criteria) this; } public Criteria andAuthorGreaterThanOrEqualTo(String value) { addCriterion("author >=", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThan(String value) { addCriterion("author <", value, "author"); return (Criteria) this; } public Criteria andAuthorLessThanOrEqualTo(String value) { addCriterion("author <=", value, "author"); return (Criteria) this; } public Criteria andAuthorLike(String value) { addCriterion("author like", value, "author"); return (Criteria) this; } public Criteria andAuthorNotLike(String value) { addCriterion("author not like", value, "author"); return (Criteria) this; } public Criteria andAuthorIn(List<String> values) { addCriterion("author in", values, "author"); return (Criteria) this; } public Criteria andAuthorNotIn(List<String> values) { addCriterion("author not in", values, "author"); return (Criteria) this; } public Criteria andAuthorBetween(String value1, String value2) { addCriterion("author between", value1, value2, "author"); return (Criteria) this; } public Criteria andAuthorNotBetween(String value1, String value2) { addCriterion("author not between", value1, value2, "author"); return (Criteria) this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return (Criteria) this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return (Criteria) this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return (Criteria) this; } public Criteria andCreateTimeIn(List<Date> values) { addCriterion("create_time in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotIn(List<Date> values) { addCriterion("create_time not in", values, "createTime"); return (Criteria) this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return (Criteria) this; } public Criteria andUpdateTimeIsNull() { addCriterion("update_time is null"); return (Criteria) this; } public Criteria andUpdateTimeIsNotNull() { addCriterion("update_time is not null"); return (Criteria) this; } public Criteria andUpdateTimeEqualTo(Date value) { addCriterion("update_time =", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotEqualTo(Date value) { addCriterion("update_time <>", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThan(Date value) { addCriterion("update_time >", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) { addCriterion("update_time >=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThan(Date value) { addCriterion("update_time <", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeLessThanOrEqualTo(Date value) { addCriterion("update_time <=", value, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeIn(List<Date> values) { addCriterion("update_time in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotIn(List<Date> values) { addCriterion("update_time not in", values, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeBetween(Date value1, Date value2) { addCriterion("update_time between", value1, value2, "updateTime"); return (Criteria) this; } public Criteria andUpdateTimeNotBetween(Date value1, Date value2) { addCriterion("update_time not between", value1, value2, "updateTime"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.bedroom.common.pojo; import java.io.Serializable; import java.util.Date; /** * 用户实体类 user_account varchar user_name varchar user_password varchar user_nickname varchar user_sex varchar user_age int user_phone varchar user_college_name varchar grade_level varchar user_foundtime datetime bedroom_id int user_level char * */ public class User implements Serializable{ private static final long serialVersionUID = 1L; // private String userAccount;//主键,bu自增长 private String userName;//用户账号 private String userPassword;//用户t密码 private String userNickname;//用户昵称 private String userSex;//用户性别 private Integer userAge;//用户年龄 private String userPhone;//电话 private String userCollegeName;//学院 private String gradeLevel;//年级,哪一届 private Date userFoundtime;//创建时间 private Integer bedroomId;//宿舍id private String userLevel;//身份('0'-学生,'1'-教师,'2'-管理员) //set and get public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserNickname() { return userNickname; } public void setUserNickname(String userNickname) { this.userNickname = userNickname; } public String getUserSex() { return userSex; } public void setUserSex(String userSex) { this.userSex = userSex; } public Integer getUserAge() { return userAge; } public void setUserAge(Integer userAge) { this.userAge = userAge; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public String getUserCollegeName() { return userCollegeName; } public void setUserCollegeName(String userCollegeName) { this.userCollegeName = userCollegeName; } public String getGradeLevel() { return gradeLevel; } public void setGradeLevel(String gradeLevel) { this.gradeLevel = gradeLevel; } public Date getUserFoundtime() { return userFoundtime; } public void setUserFoundtime(Date userFoundtime) { this.userFoundtime = userFoundtime; } public Integer getBedroomId() { return bedroomId; } public void setBedroomId(Integer bedroomId) { this.bedroomId = bedroomId; } public String getUserLevel() { return userLevel; } public void setUserLevel(String userLevel) { this.userLevel = userLevel; } public static long getSerialversionuid() { return serialVersionUID; } @Override public String toString() { return "User [userAccount=" + userAccount + ", userName=" + userName + ", userPassword=" + userPassword + ", userNickname=" + userNickname + ", userSex=" + userSex + ", userAge=" + userAge + ", userPhone=" + userPhone + ", userCollegeName=" + userCollegeName + ", gradeLevel=" + gradeLevel + ", userFoundtime=" + userFoundtime + ", bedroomId=" + bedroomId + ", userLevel=" + userLevel + "]"; } }
package com.egakat.io.conciliaciones.heinz.components.decorators; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import com.egakat.integration.commons.archivos.dto.EtlRequestDto; import com.egakat.integration.commons.archivos.dto.RegistroDto; import com.egakat.integration.core.files.components.decorators.Decorator; import com.egakat.io.conciliaciones.domain.SaldoInventario; import lombok.val; public class SaldosInventarioCorregirLineasDecorator extends Decorator<SaldoInventario, Long> { public SaldosInventarioCorregirLineasDecorator(Decorator<SaldoInventario, Long> inner) { super(inner); } @Override public EtlRequestDto<SaldoInventario, Long> transformar(EtlRequestDto<SaldoInventario, Long> archivo) { val result = super.transformar(archivo); val registros = new ArrayList<RegistroDto<SaldoInventario, Long>>(); int n = result.getRegistros().size(); if (n > 0) { val campo = result.getCampo(SaldoInventario.FECHA_CORTE); val separadorCampos = result.getUnescapedSeparadorCampos(); val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd H:mm:ss"); val fechaCorte = LocalDateTime.now().format(formatter); for (int i = 4; i < n; i++) { val registro = result.getRegistros().get(i); String s; if (i == 4) { s = campo.get().getNombre(); } else { s = fechaCorte; } registro.setLinea(s + separadorCampos + registro.getLinea()); registros.add(registro); } } result.getRegistros().clear(); result.getRegistros().addAll(registros); return result; } }
package lk.ijse.dinemore.service.custom; import lk.ijse.dinemore.dto.ItemDTO; import lk.ijse.dinemore.service.SuperSarvice; import java.util.List; public interface ItemService extends SuperSarvice { public boolean add(ItemDTO itemDTO) throws Exception; public void delete(int id) throws Exception; public void update(ItemDTO itemDTO) throws Exception; public ItemDTO findById(int id) throws Exception; public List<ItemDTO> getAll() throws Exception; }
package util; import java.util.HashMap; import java.util.List; import util.exceptions.ServiceReturnException; import util.interfaces.WebBean; /** * * @author Andriy */ public class ServiceReturn { private final HashMap<String, Object> RESULT; public ServiceReturn () { RESULT = new HashMap<>(); } public HashMap<String, Object> getResult() { return RESULT; } public ServiceReturn addItem(String itemName, Object item) { RESULT.put(itemName, item); return this; } public ServiceReturn addItem(String itemName, Object item, boolean prepareForWeb) throws Exception { if (prepareForWeb && item instanceof WebBean) { if (item instanceof WebBean) { ((WebBean) item).prepareForWeb(); } else if (item instanceof List) { for (WebBean webBean: (List<WebBean>) item) { webBean.prepareForWeb(); } } else { System.err.println("Item is not an WebBean."); } } addItem(itemName, item); return this; } public Object getItem(String itemName) { return RESULT.get(itemName); } public String getAsString(String itemName) { String item; try { item = (String) RESULT.get(itemName); } catch(Exception e) { item = null; System.err.println(e.getMessage()); } return item; } public Integer getAsInteger(String itemName) { Integer item; try { item = (Integer) RESULT.get(itemName); } catch(Exception e) { item = null; System.err.println(e.getMessage()); } return item; } public Boolean getAsBoolean(String itemName) { Boolean item; try { item = (Boolean) RESULT.get(itemName); } catch(Exception e) { item = null; System.err.println(e.getMessage()); } return item; } public Double getAsDouble(String itemName) { Double item; try { item = (Double) RESULT.get(itemName); } catch(Exception e) { item = null; System.err.println(e.getMessage()); } return item; } public Float getAsFloat(String itemName) { Float item; try { item = (Float) RESULT.get(itemName); } catch(Exception e) { item = null; System.err.println(e.getMessage()); } return item; } public int getAsInt(String itemName) throws ServiceReturnException { int item; try { item = (int) RESULT.get(itemName); } catch(Exception e) { throw new ServiceReturnException(ErrorMsgs.ERR_PARSING); } return item; } }
package com.hcl.neo.dctm.microservices.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.hcl.dctm.data.params.ExportMetadataParams; import com.hcl.dctm.data.params.OperationObjectDetail; import com.hcl.neo.dctm.microservices.exceptions.ServiceException; import com.hcl.neo.dctm.microservices.model.ServiceResponse; import com.hcl.neo.dctm.microservices.services.DctmExportMetadataService; import com.hcl.neo.dctm.microservices.services.DctmOperationService; import com.hcl.neo.eloader.common.JsonApi; /** * A RESTFul controller for Job Process Controller. * * @author souvik.das */ @RestController public class DctmObjectController { static final Logger logger = LoggerFactory.getLogger(DctmObjectController.class); @RequestMapping(method = RequestMethod.POST, value = "/services/cms/dctm/export/{repository}/{jobId}", consumes=MediaType.APPLICATION_JSON_VALUE, produces={MediaType.APPLICATION_JSON_VALUE} ) public ServiceResponse<List<OperationObjectDetail>> exportObjects( HttpServletRequest request, @PathVariable(value="repository") String repository, @PathVariable(value="jobId") String jobId, @RequestBody(required=true) String json) throws ServiceException{ logger.info("begin - post - /export/"+repository); logger.info(json); ExportMetadataParams params = JsonApi.fromJson(json, ExportMetadataParams.class); logger.info(params.toString()); ServiceResponse<List<OperationObjectDetail>> serviceRes = operationService.execOperation(request, repository, jobId, params); logger.info("end - post - /export/"+repository); return serviceRes; } @RequestMapping(method = RequestMethod.POST, value = "/services/cms/dctm/exportMetadata/{repository}/{jobId}", consumes=MediaType.APPLICATION_JSON_VALUE, produces={MediaType.APPLICATION_JSON_VALUE} ) public ServiceResponse<List<OperationObjectDetail>> exportMetadata( HttpServletRequest request, @PathVariable(value="repository") String repository, @PathVariable(value="jobId") String jobId, @RequestBody(required=true) String json) throws ServiceException{ logger.info("begin - post - /exportMetadata/"+repository); logger.info(json); ExportMetadataParams params = JsonApi.fromJson(json, ExportMetadataParams.class); logger.info(params.toString()); ServiceResponse<List<OperationObjectDetail>> serviceRes = exportMetadataService.executeOperation(request, repository, jobId, params); logger.info("end - post - /exportMetadata/"+repository); return serviceRes; } @Autowired private DctmOperationService operationService; @Autowired private DctmExportMetadataService exportMetadataService; }
import org.junit.Assert; import org.junit.Test; public class MyLinkedListTest { @Test public void whenCallWelcomeMethod_shouldReturnTrue() { boolean welcomeReturns = MyLinkedList.printWelcomeMsg(); Assert.assertEquals(true, welcomeReturns); } //UC1 test case to create simple linked list @Test public void givenThreeElements_whenInALinkedList_shouldPassLinkedListTest() { MyLinkedList<Integer> myFirstNode = new MyLinkedList<>(56); MyLinkedList<Integer> mySecondNode = new MyLinkedList<>(30); MyLinkedList<Integer> myThirdNode = new MyLinkedList<>(70); myFirstNode.setNext(mySecondNode); mySecondNode.setNext(myThirdNode); boolean result = myFirstNode.getNext().equals(mySecondNode) && mySecondNode.getNext().equals(myThirdNode); Assert.assertTrue(result); } // UC2 test cases to add elements to Linked list @Test public void given3elementsWhenLinkedShouldBeAddedToTop() { MyLinkedList<Integer> thirdNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> firstNode = new MyLinkedList<>(70); LinkedListUtils linkedList = new LinkedListUtils(); linkedList.add(firstNode); linkedList.add(secondNode); linkedList.add(thirdNode); boolean result = linkedList.head.equals(thirdNode) && linkedList.head.getNext().equals(secondNode) && linkedList.tail.equals(firstNode); Assert.assertTrue(result); } @Test public void givenThreeElements_whenLinked_shouldBeAddedAtEnd() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils linkedList = new LinkedListUtils(); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); boolean result = linkedList.head.equals(firstNode) && linkedList.head.getNext().equals(secondNode) && linkedList.tail.equals(thirdNode); Assert.assertTrue(result); } // UC4 insert a node between two nodes @Test public void givenTwoNodes_shouldInsertThirdNodeBetweenThem() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils linkedList = new LinkedListUtils(); linkedList.append(firstNode); linkedList.append(thirdNode); linkedList.insert(firstNode, secondNode); boolean result = linkedList.head.equals(firstNode) && linkedList.head.getNext().equals(secondNode) && linkedList.tail.equals(thirdNode); Assert.assertTrue(result); } //UC5 delete first node of linked list @Test public void givenThreeNode_shouldDeleteFirstNode() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils linkedList = new LinkedListUtils(); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); linkedList.pop(); boolean result = linkedList.head.equals(secondNode) && linkedList.head.getNext().equals(thirdNode) && linkedList.tail.equals(thirdNode); Assert.assertTrue(result); } // UC6 delete last node of linked list @Test public void givenThreeNode_shouldDeleteLastNode() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils linkedList = new LinkedListUtils(); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); linkedList.popLastNode(); boolean result = linkedList.head.equals(firstNode) && linkedList.head.getNext().equals(secondNode) && linkedList.tail.equals(secondNode); Assert.assertTrue(result); } @Test public void givenKeyValue_shouldReturnNodeWithKey() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils<Integer> linkedList = new LinkedListUtils<>(); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); INode<Integer> resultNode = linkedList.findNode(30); boolean result = resultNode.equals(secondNode); Assert.assertTrue(result); } // UC8 find the node with given key value and insert a new node @Test public void givenThreeNodes_findANode_shoudlInsertNewNode() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); LinkedListUtils<Integer> linkedList = new LinkedListUtils<>(); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); INode<Integer> nodeFound = linkedList.findNode(30); MyLinkedList<Integer> newNode = new MyLinkedList<>(40); linkedList.insert(nodeFound, newNode); boolean result = linkedList.head.equals(firstNode) && linkedList.head.getNext().equals(secondNode) && linkedList.head.getNext().getNext().equals(newNode) && linkedList.tail.equals(thirdNode); Assert.assertTrue(result); } // UC9 find the node delete it and print the size of final linked list @Test public void givenFourNodes_findANode_deleteIt_shouldReturnSizeOfLinkedList() { LinkedListUtils<Integer> linkedList = new LinkedListUtils<>(); MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(40); MyLinkedList<Integer> fourthNode = new MyLinkedList<>(70); linkedList.append(firstNode); linkedList.append(secondNode); linkedList.append(thirdNode); linkedList.append(fourthNode); INode<Integer> nodeFound = linkedList.findNode(40); linkedList.deleteGivenNode(nodeFound); int size = linkedList.getSize(); Assert.assertEquals(size, 3); } // UC10 make a sorted linked list @Test public void givenNodes_shouldAddInOrder() { LinkedListUtils<Integer> linkedList = new LinkedListUtils<>(); MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(40); MyLinkedList<Integer> fourthNode = new MyLinkedList<>(70); linkedList.addInOrder(firstNode); linkedList.addInOrder(secondNode); linkedList.addInOrder(thirdNode); linkedList.addInOrder(fourthNode); boolean result = linkedList.head.equals(secondNode) && linkedList.head.getNext().equals(thirdNode) && linkedList.head.getNext().getNext().equals(firstNode) && linkedList.tail.equals(fourthNode); Assert.assertTrue(result); } //UC1 create stack @Test public void given3NumbersAddedInStackShouldHaveLastAddedNode () { MyLinkedList<Integer> myThirdNode = new MyLinkedList<>(56); MyLinkedList<Integer> mySecondNode = new MyLinkedList<>(30); MyLinkedList<Integer> myFirstNode = new MyLinkedList<>(70); MyStack stack = new MyStack(); stack.push(myFirstNode); stack.push(mySecondNode); stack.push(myThirdNode); INode peek = stack.peek(); Assert.assertEquals(myThirdNode, peek); } // UC2 pop an element stack @Test public void givenThreeNumbersAddedInStack_shouldDeleteLastAddedNode() { MyLinkedList<Integer> thirdNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> firstNode = new MyLinkedList<>(70); MyStack<Integer> stack = new MyStack<Integer>(); stack.push(firstNode); stack.push(secondNode); stack.push(thirdNode); stack.pop(); stack.pop(); stack.pop(); boolean isEmpty = stack.isStackEmpty(); Assert.assertEquals(true, isEmpty); } //UC3 create a queue and enqueue elements @Test public void givenThreeNumbers_enQueueThem_shouldBeAppened() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); MyQueue<Integer> queue = new MyQueue<Integer>(); queue.enqueue(firstNode); queue.enqueue(secondNode); queue.enqueue(thirdNode);; INode<Integer> peek = queue.peek(); Assert.assertEquals(firstNode, peek); } //UC3 create a queue and enqueue elements @Test public void givenThreeNumbersAddedInQueue_shouldDeleteFirstAddedNode() { MyLinkedList<Integer> firstNode = new MyLinkedList<>(56); MyLinkedList<Integer> secondNode = new MyLinkedList<>(30); MyLinkedList<Integer> thirdNode = new MyLinkedList<>(70); MyQueue<Integer> queue = new MyQueue<Integer>(); queue.enqueue(firstNode); queue.enqueue(secondNode); queue.enqueue(thirdNode); queue.dequeue(); INode<Integer> peek = queue.peek(); Assert.assertEquals(secondNode, peek); } }
package com.pisen.ott.launcher.appmanage; import android.content.Context; import android.izy.widget.BaseListAdapter; import android.view.View; import android.view.ViewGroup; import com.pisen.ott.launcher.R; import com.pisen.ott.launcher.widget.AppManageItemView; /** * 应用程序适配器 * @author Liuhc * @version 1.0 2015年4月17日 下午5:02:27 */ public class AppManageAdapter extends BaseListAdapter<AppInfo> { Context context; public AppManageAdapter(Context context) { this.context = context; } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = View.inflate(context, R.layout.app_manage_item, null); } AppManageItemView itemApp = (AppManageItemView) convertView.findViewById(R.id.itemAppManage); AppInfo info = getItem(position); if (info != null) { itemApp.setName(info.getAppName()); if (info.getAppIcon() != null) { // itemApp.setBackground(info.getAppIcon()); itemApp.setAppIcon(info.getAppIcon()); } } return convertView; } }
package com.zadapps.scratchtest; import java.io.IOException; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; public class MainActivity extends FragmentActivity{ ProgressDialog prgDialog; RequestParams params = new RequestParams(); GoogleCloudMessaging gcmObj; Context applicationContext; String regId = ""; private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; AsyncTask<Void, Void, String> createRegIdTask; public static final String REG_ID = "regId"; public static final String EMAIL_ID = "eMailId"; EditText emailET; private MainFragment mainFragment; private static final String TAG = "MainFragment"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); setContentView(R.layout.activity_main); applicationContext = getApplicationContext(); // emailET = (EditText) findViewById(R.id.email); sad asfd asd prgDialog = new ProgressDialog(this); // Set Progress Dialog Text prgDialog.setMessage("Molimo pričekajte..."); // Set Cancelable as False prgDialog.setCancelable(false); SharedPreferences prefs = getSharedPreferences("UserDetails", Context.MODE_PRIVATE); String registrationId = prefs.getString(REG_ID, ""); System.out.println("regid: " + registrationId); // if (!TextUtils.isEmpty(registrationId)) { // Intent i = new Intent(applicationContext, GreetingActivity.class); // i.putExtra("regId", registrationId); // startActivity(i); // finish(); // } if (savedInstanceState == null) { // Add the fragment on initial activity setup mainFragment = new MainFragment(); getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, mainFragment) .commit(); } else { // Or set the fragment from restored state info mainFragment = (MainFragment) getSupportFragmentManager() .findFragmentById(android.R.id.content); } // +++++++++++++ KEY HASH // try { // // PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); // // for (Signature signature : info.signatures) // { // MessageDigest md = MessageDigest.getInstance("SHA"); // md.update(signature.toByteArray()); // Log.d("Dejo:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); // } // // } catch (NameNotFoundException e) { // Log.e("name not found", e.toString()); // } catch (NoSuchAlgorithmException e) { // Log.e("no such an algorithm", e.toString()); // } // // pocinje task za Register // String emailID = GlobalVariables.emailID; String emailID = "petard@mail.com"; if (TextUtils.isEmpty(registrationId)) { // Check if Google Play Service is installed in Device // Play services is needed to handle GCM stuffs if (checkPlayServices()) { // Register Device in GCM Server.. registerInBackground(emailID); } } // When Email is invalid else { // Toast.makeText(applicationContext, "Please enter valid email", // Toast.LENGTH_LONG).show(); } System.out.println("gotov oncreate"); } // When Register Me button is clicked // public void RegisterUser(View view) { //// String emailID = emailET.getText().toString(); // String emailID = GlobalVariables.emailID; // System.out.println(emailID); // System.out.println("test reg user"); // if (!TextUtils.isEmpty(emailID) && Utility.validate(emailID)) { // // Check if Google Play Service is installed in Device // // Play services is needed to handle GCM stuffs // if (checkPlayServices()) { // // // Register Device in GCM Server // registerInBackground(emailID); // } // } // // When Email is invalid // else { // Toast.makeText(applicationContext, "Please enter valid email", // Toast.LENGTH_LONG).show(); // } // } // AsyncTask to register Device in GCM Server private void registerInBackground(final String emailID) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcmObj == null) { gcmObj = GoogleCloudMessaging .getInstance(applicationContext); } regId = gcmObj .register(ApplicationConstants.GOOGLE_PROJ_ID); msg = "Registration ID :" + regId; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { if (!TextUtils.isEmpty(regId)) { storeRegIdinSharedPref(applicationContext, regId, emailID); // Toast.makeText( // applicationContext, // "Registered with GCM Server successfully.\n\n" // + msg, Toast.LENGTH_SHORT).show(); } else { // Toast.makeText( // applicationContext, // "Reg ID Creation Failed.\n\nEither you haven't enabled Internet or GCM server is busy right now. Make sure you enabled Internet and try registering again after some time." // + msg, Toast.LENGTH_LONG).show(); } } }.execute(null, null, null); } // Store RegId and Email entered by User in SharedPref private void storeRegIdinSharedPref(Context context, String regId, String emailID) { SharedPreferences prefs = getSharedPreferences("UserDetails", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString(REG_ID, regId); editor.putString(EMAIL_ID, emailID); editor.commit(); storeRegIdinServer(regId, emailID); } // Share RegID and Email ID with GCM Server Application (Php) private void storeRegIdinServer(String regId2, String emailID) { prgDialog.show(); params.put("emailId", emailID); params.put("regId", regId); System.out.println("Email id = " + emailID + " Reg Id = " + regId); // Make RESTful webservice call using AsyncHttpClient object AsyncHttpClient client = new AsyncHttpClient(); client.post(ApplicationConstants.APP_SERVER_URL, params, new AsyncHttpResponseHandler() { // When the response returned by REST has Http // response code '200' @Override public void onSuccess(String response) { // Hide Progress Dialog prgDialog.hide(); if (prgDialog != null) { prgDialog.dismiss(); } // Toast.makeText(applicationContext, // "Reg Id shared successfully with Web App ", // Toast.LENGTH_LONG).show(); // Intent i = new Intent(applicationContext, // GreetingActivity.class); // i.putExtra("regId", regId); // startActivity(i); // finish(); } // When the response returned by REST has Http // response code other than '200' such as '404', // '500' or '403' etc @Override public void onFailure(int statusCode, Throwable error, String content) { // Hide Progress Dialog prgDialog.hide(); if (prgDialog != null) { prgDialog.dismiss(); } // When Http response code is '404' if (statusCode == 404) { // Toast.makeText(applicationContext, // "Requested resource not found", // Toast.LENGTH_LONG).show(); } // When Http response code is '500' else if (statusCode == 500) { // Toast.makeText(applicationContext, // "Something went wrong at server end", // Toast.LENGTH_LONG).show(); } // When Http response code other than 404, 500 else { // Toast.makeText( // applicationContext, // "Unexpected Error occcured! [Most common Error: Device might " // + "not be connected to Internet or remote server is not up and running], check for other errors as well", // Toast.LENGTH_LONG).show(); } } }); } // Check if Google Playservices is installed in Device or not private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil .isGooglePlayServicesAvailable(this); // When Play services not found in device if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { // Show Error dialog to install Play services GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { // Toast.makeText( // applicationContext, // "This device doesn't support Play services, App will not work normally", // Toast.LENGTH_LONG).show(); finish(); } return false; } else { // Toast.makeText( // applicationContext, // "This device supports Play services, App will work normally", // Toast.LENGTH_LONG).show(); } return true; } // When Application is resumed, check for Play services support to make sure // app will be running normally @Override protected void onResume() { super.onResume(); checkPlayServices(); } // @Override // protected void onResume() { // // TODO Auto-generated method stub // super.onResume(); // AppEventsLogger.activateApp(this); // // } // // @Override // protected void onPause() { // // TODO Auto-generated method stub // super.onPause(); // AppEventsLogger.deactivateApp(this); // } @Override public boolean onCreateOptionsMenu(Menu menu) { System.out.println("opcreateoption"); // // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true;} @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. int id = item.getItemId(); // if (id == R.id.action_settings) { // return true; // } if (id == R.id.admin) { Intent intent = new Intent(this, AdminLogin.class); startActivity(intent); } // if (id == R.id.Greetings) { // Intent i = new Intent(applicationContext, GreetingActivity.class); // startActivity(i); //// finish(); // } return super.onOptionsItemSelected(item); } }
package prosjektoppgave.models; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; /** * Data model for Landlord objects */ public class Landlord extends Person implements Serializable { private static final long serialVersionUID = 1L; private String companyName; private long companyNumber; //Organisasjonsnr fra brønnøysundregisteret. private HashSet<Housing> housings; /** * Creates a new Landlord object * @param name The landlord's name * @param address An Address object containing the landlord's address * @param email The email address for the landlord * @param phoneNumber The landlord's phone number * @param companyName The name of the landlord's company * @param companyNumber The company number for the landlord's company */ public Landlord(String name, Address address, String email, long phoneNumber, String companyName, long companyNumber){ super(name, address, email, phoneNumber); this.companyName = companyName; this.companyNumber = companyNumber; housings = new HashSet<>(); } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public long getCompanyNumber() { return companyNumber; } public void setCompanyNumber(long companyNumber) { this.companyNumber = companyNumber; } /** * Adds a new Housing object to the Landlord object's HashSet of Housing objects * @param housing The Housing object to add */ public void addHousing(Housing housing){ housings.add(housing); } /** * Removes a Housing object from the Landlord object's HashSet of Housing objects * @param housing the housing to remove */ public void removeHousing(Housing housing){ housings.remove(housing); } /** * @return A Collection containing the Landlord object's HashSet of Housing objects */ public Collection<Housing> getHousings(){ return housings; } }
package DAO; import model.ModelUsuarios; import connections.ConexaoMySql; import java.sql.SQLException; import java.util.ArrayList; /** * * @author Vinicius Lisboa */ public class DAOUsuarios extends ConexaoMySql { /** * grava Usuarios * @param pModelUsuarios * return int */ public int salvarUsuariosDAO(ModelUsuarios pModelUsuarios){ try { this.conectar(); return this.insertSQL( "INSERT INTO tbl_usuarios (" + "nome," + "email," + "senha" + ") VALUES (" + "'" + pModelUsuarios.getUsuarioNome() + "'," + "'" + pModelUsuarios.getUsuarioEmail() + "'," + "'" + pModelUsuarios.getUsuarioSenha() + "'" + ");" ); }catch(Exception e){ e.printStackTrace(); return 0; }finally{ this.fecharConexao(); } } /** * recupera Usuarios * @param pUsuarioId * return ModelUsuarios */ public ModelUsuarios getUsuariosDAO(int pUsuarioId){ ModelUsuarios modelUsuarios = new ModelUsuarios(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_id_usuario," + "nome," + "email," + "senha" + " FROM" + " tbl_usuarios" + " WHERE" + " pk_id_usuario = '" + pUsuarioId + "'" + ";" ); while(this.getResultSet().next()){ modelUsuarios.setUsuarioId(this.getResultSet().getInt(1)); modelUsuarios.setUsuarioNome(this.getResultSet().getString(2)); modelUsuarios.setUsuarioEmail(this.getResultSet().getString(3)); modelUsuarios.setUsuarioSenha(this.getResultSet().getString(4)); } }catch(Exception e){ e.printStackTrace(); }finally{ this.fecharConexao(); } return modelUsuarios; } /** * recupera uma lista de Usuarios * return ArrayList */ public ArrayList<ModelUsuarios> getListaUsuariosDAO(){ ArrayList<ModelUsuarios> listamodelUsuarios = new ArrayList(); ModelUsuarios modelUsuarios = new ModelUsuarios(); try { this.conectar(); this.executarSQL( "SELECT " + "pk_id_usuario," + "nome," + "email," + "senha" + " FROM" + " tbl_usuarios" + ";" ); while(this.getResultSet().next()){ modelUsuarios = new ModelUsuarios(); modelUsuarios.setUsuarioId(this.getResultSet().getInt(1)); modelUsuarios.setUsuarioNome(this.getResultSet().getString(2)); modelUsuarios.setUsuarioEmail(this.getResultSet().getString(3)); modelUsuarios.setUsuarioSenha(this.getResultSet().getString(4)); listamodelUsuarios.add(modelUsuarios); } }catch(Exception e){ e.printStackTrace(); }finally{ this.fecharConexao(); } return listamodelUsuarios; } /** * atualiza Usuarios * @param pModelUsuarios * return boolean */ public boolean atualizarUsuariosDAO(ModelUsuarios pModelUsuarios){ try { this.conectar(); return this.executarUpdateDeleteSQL( "UPDATE tbl_usuarios SET " + "pk_id_usuario = '" + pModelUsuarios.getUsuarioId() + "'," + "nome = '" + pModelUsuarios.getUsuarioNome() + "'," + "email = '" + pModelUsuarios.getUsuarioEmail() + "'," + "senha = '" + pModelUsuarios.getUsuarioSenha() + "'" + " WHERE " + "pk_id_usuario = '" + pModelUsuarios.getUsuarioId() + "'" + ";" ); }catch(Exception e){ e.printStackTrace(); return false; }finally{ this.fecharConexao(); } } /** * exclui Usuarios * @param pUsuarioId * return boolean * @return */ public boolean excluirUsuariosDAO(int pUsuarioId){ try { this.conectar(); return this.executarUpdateDeleteSQL( "DELETE FROM tbl_usuarios " + " WHERE " + "pk_id_usuario = '" + pUsuarioId + "'" + ";" ); }catch(Exception e){ return false; }finally{ this.fecharConexao(); } } public boolean getValidarUsuarioDAO(ModelUsuarios pModelUsuarios) { try { this.conectar(); this.executarSQL( "SELECT " + "email," + "senha" + " FROM" + " tbl_usuarios" + " WHERE" + " email = '" + pModelUsuarios.getUsuarioEmail() + "' AND senha = '" + pModelUsuarios.getUsuarioSenha() + "'" + ";" ); return this.getResultSet().next(); }catch(SQLException e){ return false; }finally{ this.fecharConexao(); } } private int getUsuarioPorId(ModelUsuarios pModelUsuarios) { try { this.conectar(); this.executarSQL( "SELECT " + "pk_id_usuario" + " FROM" + " tbl_usuarios" + " WHERE" + " email = '" + pModelUsuarios.getUsuarioEmail() + "'" + ";" ); if(this.getResultSet().next()) { System.out.println(pModelUsuarios.getUsuarioId()); return pModelUsuarios.getUsuarioId(); } } catch(SQLException e){ return 0; } finally{ this.fecharConexao(); } return pModelUsuarios.getUsuarioId(); } }
package com.sunny.jvm.oom; /** * <Description> java.lang.StackOverflowError<br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/09/05 15:48 <br> * @see com.sunny.jvm.oom <br> */ public class StackOverflowErrorExample { public static void recursivePrint(int num) { System.out.println("Number: " + num); if(num == 0) return; else recursivePrint(++num); } public static void main(String[] args) { StackOverflowErrorExample.recursivePrint(1); } }
package cat_tests.trash; public class Notes { /* By.xpath("//a[contains(text(),'часть текста')]") By.xpath("//button[contains(@class,'btn-text') and contains(text(), 'Добавить')]") --------------- selectByVisibleText: Select selectByVisibleText = new Select (driver.findElement(By.id(“id_of_some_element”))); selectByVisibleText.selectByVisibleText(“some_visible_text”); */ public static void main(String[] args) { } }
package com.happiestminds.imageservices.ui; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.VideoView; import com.bumptech.glide.Glide; import com.happiestminds.imageservices.R; import com.happiestminds.imageservices.model.ImageCaptureType; import com.happiestminds.imageservices.model.VideoCaptureType; import com.happiestminds.imageservices.utils.Constants; import com.happiestminds.imageservices.utils.VideoServices; public class VideoServicesActivity extends AppCompatActivity { VideoView mVideoView; ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } }
package com.ljnewmap.modules.policy.dao; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.ljnewmap.modules.policy.entity.PolicyEntity; import org.apache.ibatis.annotations.Mapper; @Mapper public interface PolicyDao extends BaseMapper<PolicyEntity> { }
package ru.netology; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import ru.netology.Route; @Data @AllArgsConstructor @NoArgsConstructor public class RouteRepository { private Route[] routes = new Route[0]; public void save(Route route) { int length = routes.length + 1; Route[] tmp = new Route[length]; System.arraycopy(routes, 0, tmp, 0, routes.length); int lastIndex = tmp.length - 1; tmp[lastIndex] = route; routes = tmp; } public Route[] findAll() { return routes; } public Route findByID(int id) { for (Route route : findAll()) { int productID = route.getId(); if (productID == id) { return route; } } return null; } public void removeById(int id) { if (findByID(id) == null){ new NotFoundException("Element with id: \" + id + \" not found"); } int length = routes.length - 1; Route[] tmp = new Route[length]; int index = 0; for (Route item : routes) { if (item.getId() != id) { tmp[index] = item; index++; } } routes = tmp; } }
package com.custom.job.portal.service; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.time.Clock; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.text.WordUtils; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import com.custom.job.portal.data.model.Job; import com.custom.job.portal.data.repository.JobRepository; import com.custom.job.portal.dto.JobDto; import com.custom.job.portal.dto.JobPositionDto; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @author sabrina * * The JobService provides basic operations of database model Job. * */ @Validated @Service public class JobService { private JobRepository jobRepository; private final RestTemplate restTemplate; private static final String JOB_SEARCH_URL = "http://api.dataatwork.org/v1/jobs/autocomplete"; private static final String JOB_POSITION_URL = "https://jobs.github.com/positions.json"; public JobService(RestTemplateBuilder restTemplateBuilder, JobRepository jobRepository) { this.restTemplate = restTemplateBuilder.build(); this.jobRepository = jobRepository; } /** * attempts to save the incoming jobDto object into the database. * @param jobDto is the incoming information about job. * @return the saved JobDto or null. */ public JobDto addJob(@Valid JobDto jobDto) { if (null == jobDto) { return null; } // builds the http header and uri to call the external Open Skill API. HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); UriComponentsBuilder builder = null; try { builder = UriComponentsBuilder.fromHttpUrl(JOB_SEARCH_URL).queryParam("begins_with", URLEncoder.encode(jobDto.getTitle(), "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpEntity<?> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); if (200 == response.getStatusCodeValue()) { // parses the json response into JobDto list ObjectMapper mapper = new ObjectMapper(); JsonNode root = null; List<JobDto> jobDtos = new ArrayList<>(); try { root = mapper.readTree(response.getBody()); Iterator<JsonNode> iterator = root.iterator(); while (iterator.hasNext()) { JsonNode node = iterator.next(); JobDto job = new JobDto(); job.setId(null); job.setJobId(node.findValue("uuid").asText()); job.setTitle(node.findValue("suggestion").asText()); job.setNormalizedTitle(node.findValue("normalized_job_title").asText()); job.setLocation(WordUtils.capitalize(jobDto.getLocation())); jobDtos.add(job); } } catch (IOException e) { e.printStackTrace(); } // gets the first job to store into database JobDto closestMatchJob = findClosestMatchJobTitle(jobDtos, jobDto); if (null == closestMatchJob && !jobDtos.isEmpty()) { closestMatchJob = jobDtos.get(0); } Optional<Job> jobOptional = this.jobRepository.findByTitleAndLocationAndDeleted(closestMatchJob.getTitle(), closestMatchJob.getLocation(), false); if (jobOptional.isPresent()) { return this.convertToDto(jobOptional.get()); } return this.convertToDto(this.jobRepository.save(this.convertToModel(closestMatchJob))); } return null; } /** * retrieves all non-deleted jobs from the database. * @return a list of JobDto. */ public List<JobDto> getAllJobs() { List<Job> jobList = this.jobRepository.findByDeleted(false); return StreamSupport.stream(jobList.spliterator(), false).map(this::convertToDto).collect(Collectors.toList()); } /** * retrieves job by its id from database. * @param id of the job. * @return the found JobDto or null. */ public JobDto getJobById(UUID id) { if (null == id) { return null; } Optional<Job> jobOptional = this.jobRepository.findByIdAndDeleted(id, false); if (!jobOptional.isPresent()) { return null; } return this.convertToDto(jobOptional.get()); } /** * retrieves all job positions by title and location using external rest api. * @param id of the existing job in the database. * @return a list of JobPositionDto. */ public List<JobPositionDto> getJobPostionsById(UUID id) { if (null == id) { return null; } JobDto jobDto = this.getJobById(id); if (null == jobDto) { return null; } // builds the uri to fetch the job position data UriComponentsBuilder builder = null; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); try { builder = UriComponentsBuilder.fromHttpUrl(JOB_POSITION_URL) .queryParam("description", URLEncoder.encode(jobDto.getTitle(), "UTF-8")) .queryParam("location", URLEncoder.encode(jobDto.getLocation(), "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } HttpEntity<?> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); if (200 == response.getStatusCodeValue()) { ObjectMapper mapper = new ObjectMapper(); JsonNode root = null; List<JobPositionDto> jobPositionDtos = new ArrayList<>(); // builds the list from json data try { root = mapper.readTree(response.getBody()); Iterator<JsonNode> iterator = root.iterator(); while (iterator.hasNext()) { JsonNode node = iterator.next(); JobPositionDto jobPosition = new JobPositionDto(); jobPosition.setId(node.findValue("id").asText()); jobPosition.setType(node.findValue("type").asText()); jobPosition.setCompany(node.findValue("company").asText()); jobPosition.setTitle(node.findValue("title").asText()); jobPosition.setLocation(node.findValue("location").asText()); jobPosition.setDescription(node.findValue("description").asText()); jobPosition.setHowToApply(node.findValue("how_to_apply").asText()); jobPosition.setCompanyLogo(node.findValue("company_logo").asText()); jobPositionDtos.add(jobPosition); } } catch (IOException e) { e.printStackTrace(); } return jobPositionDtos; } return Collections.emptyList(); } /** * converts Job Dto to Model object * @param jobDto object. * @return Job model. */ public Job convertToModel(@Valid JobDto jobDto) { Job job = new Job(); job.setId(jobDto.getId()); job.setJobId(jobDto.getJobId()); job.setTitle(jobDto.getTitle()); job.setLocation(jobDto.getLocation()); job.setNormalizedTitle(jobDto.getNormalizedTitle()); job.setCreatedOn(LocalDateTime.now(Clock.systemUTC())); return job; } /** * converts Job model to Dto object. * @param job model. * @return JobDto. */ public JobDto convertToDto(@Valid Job job) { JobDto jobDto = new JobDto(); jobDto.setId(job.getId()); jobDto.setJobId(job.getJobId()); jobDto.setTitle(job.getTitle()); jobDto.setLocation(job.getLocation()); jobDto.setNormalizedTitle(job.getNormalizedTitle()); return jobDto; } private JobDto findClosestMatchJobTitle(List<JobDto> jobList, JobDto target) { int distance = Integer.MAX_VALUE; JobDto jobDto = null; for (JobDto job : jobList) { int currentDistance = StringUtils.getLevenshteinDistance(job.getTitle(), target.getTitle()); if(currentDistance < distance) { distance = currentDistance; jobDto = job; } } return jobDto; } }
package com.ahav.reserve.pojo; public class Room { private Integer meetingRoomId; private Integer meetingRoomScale; private String meetingRoomName; private String meEquipmentList; private Integer meetingRoomStatus; public Integer getMeetingRoomId() { return meetingRoomId; } public void setMeetingRoomId(Integer meetingRoomId) { this.meetingRoomId = meetingRoomId; } public Integer getMeetingRoomScale() { return meetingRoomScale; } public void setMeetingRoomScale(Integer meetingRoomScale) { this.meetingRoomScale = meetingRoomScale; } public String getMeetingRoomName() { return meetingRoomName; } public void setMeetingRoomName(String meetingRoomName) { this.meetingRoomName = meetingRoomName == null ? null : meetingRoomName.trim(); } public String getMeEquipmentList() { return meEquipmentList; } public void setMeEquipmentList(String meEquipmentList) { this.meEquipmentList = meEquipmentList == null ? null : meEquipmentList.trim(); } public Integer getMeetingRoomStatus() { return meetingRoomStatus; } public void setMeetingRoomStatus(Integer meetingRoomStatus) { this.meetingRoomStatus = meetingRoomStatus; } @Override public String toString() { return "Room{" + "meetingRoomId=" + meetingRoomId + ", meetingRoomScale=" + meetingRoomScale + ", meetingRoomName='" + meetingRoomName + '\'' + ", meEquipmentList='" + meEquipmentList + '\'' + ", meetingRoomStatus=" + meetingRoomStatus + '}'; } }
package com.seven.contract.manage.common; /** * Created by apple on 2018/12/12. */ public class AppRuntimeException extends Exception { private String reqCode ; //异常对应的返回码 private String msg; //异常对应的描述信息 public AppRuntimeException() { super(); } public AppRuntimeException(String message) { super(message); msg = message; } public AppRuntimeException(String reqCode, String message) { super(); this.reqCode = reqCode; this.msg = message; } public String getReqCode() { return reqCode; } public String getMsg() { return msg; } }
package me.hjjang.templateMethod; public class Cat extends Animal { // public void playWithOwner() { // System.out.println("귀염둥이 이리온.."); // System.out.println("야용~! 야옹~!"); // } @Override void play() { System.out.println("야옹~ 야옹~"); } @Override void runSomthing() { System.out.println("야옹~ 야옹~ 꼬리 살랑 살랑~~"); } }
package cs3500.animator.view; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import cs3500.animator.shape.IShape; import cs3500.animator.shape.ReadableShape; import cs3500.animator.util.ButtonListener; /** * A view that will interact with the user and will have capabilities of the visual view, * in that it will actually show the animation being played. It will also have capabilities of the * SVG view, in that it will be able to create and export the animation in SVG format. In this * sense, this will be a hybrid of two existing views. */ public class HybridView extends JFrame implements IView, ActionListener, ChangeListener, ItemListener { private MyPanel myPanel = new MyPanel(); static final int FPS_MIN = 1; static final int FPS_MAX = 300; JLabel actionDisplay; JSlider scrubber; private ButtonListener buttonListener; private ArrayList<ReadableShape> listOfShapes; /** * Constructs a HybridView. */ public HybridView() { //to make public this.listOfShapes = new ArrayList<>(); } @Override public void export() { setSize(800, 1000); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JScrollPane jScrollPane = new JScrollPane(myPanel); add(jScrollPane); JPanel buttonsPanel = new JPanel(); buttonsPanel.setSize(800, 100); this.add(buttonsPanel, BorderLayout.SOUTH); JButton startButton = new JButton("Start"); startButton.setActionCommand("Start animation"); startButton.addActionListener(buttonListener); startButton.addActionListener(this); buttonsPanel.add(startButton); JButton pauseButton = new JButton("Pause"); pauseButton.setActionCommand("Pause animation"); pauseButton.addActionListener(buttonListener); pauseButton.addActionListener(this); buttonsPanel.add(pauseButton); JButton resumeButton = new JButton("Resume"); resumeButton.setActionCommand("Resume animation"); resumeButton.addActionListener(buttonListener); resumeButton.addActionListener(this); buttonsPanel.add(resumeButton); JButton restartButton = new JButton("Restart"); restartButton.setActionCommand("Restart animation"); restartButton.addActionListener(buttonListener); restartButton.addActionListener(this); buttonsPanel.add(restartButton); JLabel fpsSliderLabel = new JLabel("FPS Speed", JLabel.CENTER); fpsSliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT); JSlider fpsControl = new JSlider(JSlider.HORIZONTAL, FPS_MIN, FPS_MAX, 20); fpsControl.setName("FPS"); fpsControl.addChangeListener(buttonListener); fpsControl.addChangeListener(this); //Turn on labels at major tick marks. fpsControl.setMajorTickSpacing(100); fpsControl.setMinorTickSpacing(10); fpsControl.setPaintTicks(false); fpsControl.setPaintLabels(false); buttonsPanel.add(fpsSliderLabel); buttonsPanel.add(fpsControl); JButton exportToSVGButton = new JButton("Export to SVG"); exportToSVGButton.setActionCommand("Export to SVG"); exportToSVGButton.addActionListener(this); exportToSVGButton.addActionListener(buttonListener); buttonsPanel.add(exportToSVGButton); JCheckBox loopButton = new JCheckBox("Loop"); loopButton.setSelected(false); loopButton.setActionCommand("Loop animation"); loopButton.addItemListener(buttonListener); loopButton.addItemListener(this); loopButton.addActionListener(buttonListener); loopButton.addActionListener(this); buttonsPanel.add(loopButton); JPanel actionPanel = new JPanel(); this.add(actionPanel, BorderLayout.NORTH); actionDisplay = new JLabel("Ready to start"); actionPanel.add(actionDisplay); // SCRUBBING JPanel scrubPanel = new JPanel(new BorderLayout()); scrubPanel.setPreferredSize(new Dimension(770, 90)); buttonsPanel.add(scrubPanel, BorderLayout.SOUTH); // trying to set max to max frame int max = this.getEnd(); scrubber = new JSlider(JSlider.HORIZONTAL, 0, max, 0); scrubber.setName("Scrub"); scrubber.addMouseListener(buttonListener); scrubber.addChangeListener(buttonListener); scrubber.setMajorTickSpacing(50); scrubber.setMinorTickSpacing(1); scrubber.setPaintTicks(true); scrubber.setPaintLabels(true); scrubPanel.add(scrubber); setVisible(true); } @Override public void drawShapes(ArrayList<ReadableShape> shape) throws IOException { myPanel.setShapes(shape); myPanel.repaint(); } @Override public void drawForSVG(List<IShape> shape) throws IOException { throw new UnsupportedOperationException("This doesnt need a list of IShapes"); } @Override public void drawString(String in) { throw new UnsupportedOperationException("This doesnt need to draw strings"); } @Override public void setFilePath(String filePath) { //doesnt throw and error, but doesnt return anything return; } @Override public void setFps(int fps) { throw new UnsupportedOperationException("Doesnt use the setFPS method"); } @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "Start animation": actionDisplay.setText("Animation was started"); break; case "Pause animation": actionDisplay.setText("Animation was paused"); break; case "Resume animation": actionDisplay.setText("Animation was resumed"); break; case "Restart animation": actionDisplay.setText("Animation was restarted"); break; default: } } @Override public void setButtonListener(ButtonListener buttonListener) { this.buttonListener = buttonListener; } @Override public String getFinal() { throw new UnsupportedOperationException(); } @Override public void setLooping(double maxFrame) { throw new UnsupportedOperationException(); } @Override public void stateChanged(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { int fps = (int) source.getValue(); actionDisplay.setText("Speed changed to " + Integer.toString(fps) + " fps."); } } @Override public void itemStateChanged(ItemEvent e) { String s = ((JCheckBox) e.getItemSelectable()).getActionCommand(); if (s.equals("Loop animation")) { if (e.getStateChange() == ItemEvent.SELECTED) { actionDisplay.setText("Looping..."); } else { actionDisplay.setText(""); } } } public String getActionText() { return actionDisplay.getText(); } // getting the max frame @Override public int getEnd() { int maxTime = 0; for (int i = 0; i < this.listOfShapes.size(); i++) { int endTime = (int) listOfShapes.get(i).getEnd(); if (endTime > maxTime) { maxTime = endTime; } } return maxTime; } @Override public void setShapes(ArrayList<ReadableShape> shapes) { this.listOfShapes = shapes; } @Override public boolean scrubContains(Point e) { return scrubber.contains(e); } }
package br.com.ifpb.facade; public class SistemaDeInput { public void configurarJoystick() { System.out.println("Joystick configurado"); } public void configurarTeclado() { System.out.println("Teclado configurado"); } public void lerInput() { } }
package rocks.zipcode.io.assessment4.fundamentals; import java.util.Arrays; /** * @author leon on 09/12/2018. */ public class VowelUtils { public static Boolean hasVowels(String word) { String[] vowels = {"a", "e", "i", "o", "u"}; String[] wordArray = word.toLowerCase().split(""); for (int i = 0; i < vowels.length; i++) { for (int j = 0; j < wordArray.length; j++) { if (vowels[i].equals(wordArray[j])) { return true; } } } return false; } public static Integer getIndexOfFirstVowel(String word) { String[] vowels = {"a", "e", "i", "o", "u"}; String[] wordArray = word.toLowerCase().split(""); for (int j = 0; j < wordArray.length; j++) { for (int i = 0; i < vowels.length; i++) { if (vowels[i].equals(wordArray[j])) { return j; } } } return -1; } public static Boolean startsWithVowel(String word) { String[] vowels = {"a", "e", "i", "o", "u"}; String[] wordArray = word.toLowerCase().split(""); for (int i = 0; i < vowels.length; i++) { if (vowels[i].equals(wordArray[0])) { return true;} } return false; } public static Boolean isVowel(Character character) { String s = character.toString().toLowerCase(); String[] vowels = {"a", "e", "i", "o", "u"}; return Arrays.stream(vowels).anyMatch(s::equals); } }
/** * */ package com.dg.android.lcp.activities; import com.dg.android.lcp.utils.AndroidUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; /** * @author MehrozKarim * */ public class TermsOfUseActivity extends Activity { Context context; WebView webview; // Button back; ProgressDialog progressdilog; String url; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; setContentView(R.layout.terms_use); Bundle extras = getIntent().getExtras(); if (extras != null) url = AndroidUtil.MENU_ZOES; else url = AndroidUtil.TERMS_OF_USE; // url = getString(R.string.terms_url); //"http://app.relevantmobile.com/terms_of_use"; // back = (Button) findViewById(R.id.back); webview = (WebView) findViewById(R.id.webview); webview.getSettings().setJavaScriptEnabled(true); webview.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { } }); // back.setOnClickListener(new OnClickListener() { // // @Override // public void onClick(View arg0) { // if (webview.canGoBack()) { // webview.goBack(); // } // } // }); webview.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // Handle the error } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("tel:")) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url)); startActivity(intent); } else if (url.startsWith("http:") || url.startsWith("https:")) { view.loadUrl(url); } return true; } public void onPageFinished(WebView view, String url) { progressdilog.dismiss(); } }); webview.loadUrl(url); progressdilog = ProgressDialog.show(TermsOfUseActivity.this, "", getString(R.string.loading), true); if (progressdilog.getProgress() == 100) progressdilog.dismiss(); } }
package com.yhkx.core.util; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * 日志记录入口 * * @author LiSs * @date on 2018/7/8 */ public class ApiLogger { private static Logger errorLog = LoggerFactory.getLogger("error"); private static Logger warnLog = LoggerFactory.getLogger("warn"); private static Logger infoLog = LoggerFactory.getLogger("info"); private static Logger debugLog = LoggerFactory.getLogger("debug"); private static Logger redisLog = LoggerFactory.getLogger("redis"); private static Logger rocketMqLog = LoggerFactory.getLogger("rocketmq"); public ApiLogger() { } public static void error(Object msg) { if (msg != null) { String log = assembleRequestId(msg.toString()); errorLog.error(log); } } public static void error(String msg, Object... args) { msg = assembleRequestId(msg); errorLog.error(msg, args); } public static void error(String msg, Throwable e) { msg = assembleRequestId(msg); errorLog.error(msg, e); } public static void warn(Object msg) { if (msg != null) { String log = assembleRequestId(msg.toString()); warnLog.warn(log); } } public static void warn(String msg, Object... args) { msg = assembleRequestId(msg); warnLog.warn(msg, args); } public static void warn(String msg, Throwable e) { msg = assembleRequestId(msg); warnLog.warn(msg, e); } public static void info(Object msg) { if (msg != null && infoLog.isInfoEnabled()) { String msg1 = assembleRequestId(msg.toString()); infoLog.info(msg1.toString()); } } public static void info(String msg, Object... args) { if (infoLog.isInfoEnabled()) { msg = assembleRequestId(msg); infoLog.info(msg, args); } } public static void redisLog(Object msg, Throwable e) { if (msg != null && redisLog.isInfoEnabled()) { String msg1 = assembleRequestId(msg.toString()); redisLog.error(msg1.toString(), e); } } public static void rocketMqLog(Object msg, Throwable e) { if (msg != null && rocketMqLog.isInfoEnabled()) { String msg1 = assembleRequestId(msg.toString()); rocketMqLog.info(msg1.toString(), e); } } public static String assembleRequestId(String msg) { if (msg != null) { msg = assembleRequestId(msg, " "); } else { msg = assembleRequestId("null", " "); } return msg; } private static String assembleRequestId(String msg, String spit) { String requestId = getTraceId(); StringBuilder buf = new StringBuilder(msg); if (!StringUtils.isEmpty(requestId)) { buf.append(spit).append(requestId); msg = buf.toString(); } return msg; } public static String getTraceId() { return MDC.get("traceId"); } }
/** * Lab 5 - enters data into a linked list and array list, and sorts them based on the speed stat * * @author Muhammad Faizan Ali(100518916) * @version 1.0 */ import java.util.Random; public class ComparisionDriver { public static void main(String[] args) { SortedDoublyLinkedList list = new SortedDoublyLinkedList(); SortedArray array = new SortedArray(); // insert 100 elements into both lists (randomly generated) for(int i = 0; i < 100; i++){ Warrior newWarrior = new Warrior("Generic",genStat(50),genStat(50),genStat(200)); list.insert(newWarrior); array.insert(newWarrior); } // compare the number of assignment operations: System.out.println("Linked List assignmentCount:  " + list.assignmentCount); System.out.println("Sorted Array assignmentCount: " + array.assignmentCount); } /** * generates a integer random number * @param max the max number that can be generated * @return the number generated */ public static int genStat(int max){ // randomly choose an integer between 1 and max Random rand = new Random(); return rand.nextInt(max)+1; } }
package br.com.fiap.entity; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="compradores") @ManagedBean(name="beanComp") @RequestScoped public class Compradores { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="CODIGO") private int codigo; @Column(name="NOME") private String nome; @Column(name="EMAIL") private String email; @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="CODLIVRO") private Livros livro; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Livros getLivro() { return livro; } public void setLivro(Livros livro) { this.livro = livro; } }
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sandy.user.domain; import com.sandy.infrastructure.common.AbstractDateEntity; /** * Account * * @author Sandy * @since 1.0.0 11th 10 2018 */ public class Account extends AbstractDateEntity<Long> { private static final long serialVersionUID = -8086719111874165087L; private String nickName; private String userName; private String headPortrait; private String email; private String mobile; private String password; private Integer isLocked = 0x00; public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getHeadPortrait() { return headPortrait; } public void setHeadPortrait(String headPortrait) { this.headPortrait = headPortrait; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getIsLocked() { return isLocked; } public void setIsLocked(Integer isLocked) { this.isLocked = isLocked; } @Override public String toString() { StringBuilder buffer = new StringBuilder(200); buffer.append(getClass().getName()).append('['); buffer.append("id=").append(getId()); buffer.append(",nickName=").append(nickName); buffer.append(",headPortrait=").append(headPortrait); buffer.append(",userName=").append(userName); buffer.append(",email=").append(email); buffer.append(",mobile=").append(mobile); buffer.append(",password=").append(password); buffer.append(",isLocked=").append(isLocked); buffer.append(",createdId=").append(getCreatedId()); buffer.append(",createdTime=").append(getCreatedTime()); buffer.append(",updatedId=").append(getUpdatedId()); buffer.append(",updatedTime=").append(getUpdatedTime()); buffer.append(']'); return buffer.toString(); } }
package org.maple.jdk8.methodReference; /** * @Author Mapleins * @Date 2019-04-05 0:51 * @Description */ public class StudentComparator { //根据分数排序,升序 public int compareStudentByScore(Student s1,Student s2){ return s1.getScore() - s2.getScore(); } //根据名字进行比较 public int compareStudentByName(Student s1,Student s2){ return s1.getName().compareToIgnoreCase(s2.getName()); } }
package com.game.chess.console.service; import com.game.chess.console.domain.jwt.CustomUserDetails; import com.game.chess.db.model.User; import com.game.chess.db.repository.UserRepository; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Optional; @Slf4j @AllArgsConstructor(onConstructor_ = {@Autowired}) @Service public class CustomUserDetailsService implements UserDetailsService { private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String email) { Optional<User> userOptional = userRepository.findByEmail(email); LOG.info("Fetched by email: {}", email); return userOptional.map(user -> CustomUserDetails.builder().user(user).build()) .orElseThrow(() -> new UsernameNotFoundException("Couldn't find a matching user email in the database for " + email)); } }
package com.kieferlam.battlelan.game.map; import org.jbox2d.collision.shapes.CircleShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.*; /** * Created by Kiefer on 02/05/2015. */ public class PhysicsCharacterBody { public static final float angularDampening = 50.0f; public static final float friction = 0.3f; public static final float density = 10.0f; public static final BodyType bodyType = BodyType.DYNAMIC; public static final float bodyRadius = 1.0f; public static final float angularImpulseMovement = 10.0f; public static final Vec2 jumpImpulse = new Vec2(0.0f, 300.0f); public static final BodyDef bodyDefinition = new BodyDef(); public static final FixtureDef fixtureDefinition = new FixtureDef(); public static final CircleShape bodyShape = new CircleShape(); static{ //BODY bodyDefinition.setAngularDamping(angularDampening); bodyDefinition.setType(bodyType); //SHAPE bodyShape.setRadius(bodyRadius); //FIXTURE fixtureDefinition.setDensity(density); fixtureDefinition.friction = friction; fixtureDefinition.shape = bodyShape; } public final Body body; public PhysicsCharacterBody(World world, Vec2 position){ bodyDefinition.setPosition(position); body = world.createBody(bodyDefinition); body.createFixture(fixtureDefinition); } public Vec2 getWorldPosition(){ return body.getPosition(); } public Vec2 getRenderPosition(float unitsPerMeter){ return body.getPosition().mul(unitsPerMeter); } public void moveRight(float delta){ applyAngularImpulse(-angularImpulseMovement, delta); } public void moveLeft(float delta){ applyAngularImpulse(angularImpulseMovement, delta); } public void jump(){ body.applyLinearImpulse(jumpImpulse, body.getWorldCenter(), true); } public void applyAngularImpulse(float impulse, float delta){ body.applyAngularImpulse(impulse * delta); } }
package com.health.eureka; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @EnableEurekaServer @SpringBootApplication public class HealthEurekaApplication { public static void main(String[] args) { SpringApplication.run(HealthEurekaApplication.class, args); } }
package com.agamidev.newsfeedsapp.Utils; import android.util.Log; import com.agamidev.newsfeedsapp.Models.NewsModel; public class NewsDate { public static String getFinalDate(NewsModel n){ String date = splitString(n.getPublishedAt(),"T")[0]; String[] dateArray = splitString(date,"-"); String year = dateArray[0]; String month = dateArray[1]; String day = dateArray[2]; return getMonthName(month)+" "+day+", "+year; } private static String[] splitString(String s, String splitChar){ String[] myArray = s.split(splitChar); return myArray; } private static String getMonthName(String month){ String monthName; switch(month) { case "01": monthName = "January"; break; case "02": monthName = "February"; break; case "03": monthName = "March"; break; case "04": monthName = "April"; break; case "05": monthName = "May"; break; case "06": monthName = "June"; break; case "07": monthName = "July"; break; case "08": monthName = "August"; break; case "09": monthName = "September"; break; case "10": monthName = "October"; break; case "11": monthName = "November"; break; case "12": monthName = "December"; break; default: monthName = " "; } return monthName; } }
//https://leetcode.com/problems/single-number/ class SingleNumber{ public static int singleNumber(int [] nums){ int result = 0; for(int i : nums) result ^= i; return result; } }
package ArrayPractice; import java.util.Scanner; //input an array and find largest element in it and its location. public class Demo2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); int[] a=new int[5]; S; foystem.out.println("Enter array elements")r(int i=0;i<5;i++) a[i]=s.nextInt(); int max,loc; max=a[0]; loc=0; for(int i=0;i<5;i++) { if(max<a[i]) max=a[i]; loc=i; } System.out.println("Largest element is "+max); System.out.println("Location of largest element is "+loc); } }
package aeroportSpring.model; import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; @Entity @DiscriminatorValue("CM") @NamedQueries({ @NamedQuery(name = "ClientMoral.findAllClientMoral", query = "select cm from ClientMoral cm"), @NamedQuery(name = "ClientMoral.findClientMoralByVille", query = "select cm from ClientMoral cm where lower(cm.adresse.ville) like :ville") }) public class ClientMoral extends Client { @Column(name = "siret_client",length=20) private String siret; public ClientMoral() { } public ClientMoral(String siret) { super(); this.siret = siret; } public String getSiret() { return siret; } public void setSiret(String siret) { this.siret = siret; } }
import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; class SearchEngine { private Search search; void setSearch(Search search) { this.search = search; } void find(ArrayList<String> people, Map<String, HashSet<Integer>> list) throws IOException { this.search.find(people,list); } }
package com.natsu.threaddemo.threadZExample; import java.util.LinkedList; public class ThreadPool { //线程池大小 int threadPoolSize; //任务容器 LinkedList<Runnable> tasks = new LinkedList<>(); //试图消费任务的线程 public ThreadPool() { threadPoolSize = 10; //启动10个消费线程 synchronized (tasks) { for (int i = 0; i < threadPoolSize; i++) { new TaskConsumeThread("Custom thread: " + i).start(); } } } public void add(Runnable runnable){ synchronized (tasks){ tasks.add(runnable); tasks.notifyAll(); } } class TaskConsumeThread extends Thread { public TaskConsumeThread(String name) { super(name); } Runnable task; @Override public void run() { System.out.println("run: " + this.getName()); while (true) { synchronized (tasks) { while (tasks.isEmpty()) { try { tasks.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } task = tasks.removeLast(); // 允许添加任务的线程可以继续添加 任务 tasks.notifyAll(); } System.out.println(this.getName() + " get task, is running"); task.run(); } } } }