text
stringlengths 10
2.72M
|
|---|
package com.ex1;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class P8 {
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
String superhero;
MysqlDataSource mysqlDS = new MysqlDataSource();
mysqlDS.setURL("jdbc:mysql://localhost:3306/superheroes");
mysqlDS.setUser("root");
mysqlDS.setPassword("");
Connection conn = mysqlDS.getConnection();
Statement myStmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
System.out.println("Enter a Superhero to increase powers by 1:");
superhero = sc.nextLine();
String query = "Update superhero_table " +
"set powers = powers + 1 " +
"where name like '" + superhero + "'";
int rs = myStmt.executeUpdate(query);
if (rs > 0)
System.out.println(superhero+"'s powers successfully updated.");
else
System.out.println(superhero+ " does not exist in database.");
query="select powers from superhero_table where name = '" + superhero + "'";
ResultSet r = myStmt.executeQuery(query);
while( r.next() ) {
Double powers = r.getDouble("powers");
System.out.println(superhero +" now has the powers of: " + powers);
}
conn.close();
myStmt.close();
sc.close();
}//main
}//P8
|
package com.dreamcatcher.member.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.dreamcatcher.action.Action;
import com.dreamcatcher.factory.MemberActionFactory;
import com.dreamcatcher.member.model.MemberDto;
import com.dreamcatcher.member.model.service.MemberServiceImpl;
import com.dreamcatcher.util.CharacterConstant;
import com.dreamcatcher.util.StringCheck;
import com.google.gson.Gson;
public class MemberLoginAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String id = StringCheck.nullToBlank(request.getParameter("id"));
String password = StringCheck.nullToBlank(request.getParameter("password"));
Map validMap = new HashMap();
validMap.put("id",id);
validMap.put("password", password);
MemberDto memberDto = MemberServiceImpl.getInstance().login(validMap);
JSONObject jSONObject = new JSONObject();
if(memberDto != null){
String idSave = StringCheck.nullToBlank(request.getParameter("idSave"));
if("saveOk".equals(idSave)){
Cookie cookie = new Cookie("loginId", id);
cookie.setPath(request.getContextPath());
cookie.setMaxAge(60*60*24*365*10); // 10년
response.addCookie(cookie);
}else{
Cookie cookies[] = request.getCookies();
if( cookies != null ){
int length = cookies.length;
for(int i=0; i < length; i++){
if(cookies[i].getName().equals("loginId")){
cookies[i].setPath(request.getContextPath()); // 삭제 시 경로 설정에 유의
cookies[i].setMaxAge(0);
response.addCookie(cookies[i]);
break; // return 하면 에러!!!
}
}
}
}
int memberState = memberDto.getM_state();
// memberState = 0 : 가입대기 상태 | 1 : 가입완료 상태 | 2: 비밀번호 리셋 상태
if(memberState == 1){
HttpSession session = request.getSession();
session.setAttribute("memberInfo", memberDto);
}else{
Gson gson = new Gson();
jSONObject.put("memberInfo",gson.toJsonTree(memberDto));
}
jSONObject.put("result", "loginSuccess"); // 정상적인 로그인
jSONObject.put("memberState", memberState); // 회원 상태 담기
}else{
jSONObject.put("result", "loginFailed"); // 로그인 실패
}
String jSONStr = jSONObject.toJSONString();
response.setContentType("text/plain; charset="+CharacterConstant.DEFAULT_CHAR);
response.getWriter().write(jSONStr);
return null;
}
}
|
package com.tencent.mm.plugin.appbrand.widget.recyclerview;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.c;
import com.tencent.mm.plugin.appbrand.widget.recyclerview.LoadMoreRecyclerView.a;
class LoadMoreRecyclerView$2 extends c {
final /* synthetic */ LinearLayoutManager gPY;
final /* synthetic */ LoadMoreRecyclerView gPZ;
LoadMoreRecyclerView$2(LoadMoreRecyclerView loadMoreRecyclerView, LinearLayoutManager linearLayoutManager) {
this.gPZ = loadMoreRecyclerView;
this.gPY = linearLayoutManager;
}
public final void ad(int i, int i2) {
super.ad(i, i2);
if (this.gPZ.gPW && this.gPY.fj() == this.gPZ.gQa.getItemCount() - 1 && LoadMoreRecyclerView.a(this.gPZ) != null) {
a a = LoadMoreRecyclerView.a(this.gPZ);
RecyclerView.a aVar = this.gPZ.gQa.QU;
a.anH();
}
}
}
|
package util;
import org.sqlite.JDBC;
import java.sql.*;
public class DatabaseUtils {
public Connection conn;
//public Statement statement;
//public static ResultSet resSet;
public DatabaseUtils() throws ClassNotFoundException, SQLException {
conn = null;
Class.forName("org.sqlite.JDBC");
DriverManager.registerDriver(new JDBC());
conn = DriverManager.getConnection("jdbc:sqlite:G:\\find-song\\server\\song.db");
}
public void execSqlUpdate(String sql) throws SQLException {
conn.createStatement().executeUpdate(sql);
}
public ResultSet execSqlQuery(String sql) throws SQLException {
return conn.createStatement().executeQuery(sql);
}
// --------Закрытие--------
public void CloseDB() throws ClassNotFoundException, SQLException {
conn.close();
// statement.close();
}
}
|
/*
You are given a sequence of the speeds of cars in a single-lane street.
A car can catch up to the car B, only if B is in front of A and the speed
of A is greater than the speed of B, and then the speed of A is lowered
to the speed of B. Each gathering of cars is called a group. Your task
is to find the sum of the initial speeds of the longest group of cars
(the group with most cars in it). If more than one group with equal length exists,
then find the biggest sum of the initial speeds of these groups.
Additional notes
Cars cannot outrun each other
They can only catch up
The street is very very long and no matter the speed
No car with any speed can get out of it until the end of the exam
Cars with equal speeds do not catch up to each other
They do not form a group
*/
import java.util.Scanner;
public class Speed {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int groupSpeed = scanner.nextInt();
int groupLenght = 1;
int groupSum = groupSpeed;
int bestLenght = 1;
int bestSum = groupSum;
for(int i = 0; i < n -1; i ++){
int speed = scanner.nextInt();
if(groupSpeed < speed){
groupLenght ++;
groupSum += speed;
} else {
groupSpeed = speed;
groupSum = speed;
groupLenght = 1;
}
if (bestLenght < groupLenght){
bestLenght = groupLenght;
bestSum = groupSum;
}else if (bestLenght == groupLenght){
bestSum = Math.max(bestSum, groupSum);
}
}
System.out.println(bestSum);
}
}
|
/*
* Copyright (C), 2013-2014, 上海汽车集团股份有限公司
* FileName: CustomInfoVo.java
* Author: baowenzhou
* Date: 2014年8月22日 上午10:33:25
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.service.crazyjavachapter7;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈功能详细描述〉
*
* @author baowenzhou
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class CustomInfoVo2 implements Serializable {
/**
*/
private static final long serialVersionUID = -502804796037460530L;
// 微信号
private String wxNo;
// openId类型(4:微信,6:车享宝)
private String openType;
// 客户ID
private String custId;
// 客户名称
private String custName;
// 手机
private String mobilePhone;
// 车享ID
private String cxId;
// 用户账户
private String userName;
// 用户密码
private String passwd;
// 车辆信息
private List<CarModelInfoVo2> carInfo = new ArrayList<CarModelInfoVo2>();
public String getWxNo() {
return wxNo;
}
public void setWxNo(String wxNo) {
this.wxNo = wxNo;
}
public String getOpenType() {
return openType;
}
public void setOpenType(String openType) {
this.openType = openType;
}
public String getCustId() {
return custId;
}
public void setCustId(String custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getCxId() {
return cxId;
}
public void setCxId(String cxId) {
this.cxId = cxId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public List<CarModelInfoVo2> getCarInfo() {
return carInfo;
}
public void setCarInfo(List<CarModelInfoVo2> carInfo) {
this.carInfo = carInfo;
}
}
|
package cn.izouxiang.domain;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class TransactionRecord implements Serializable{
private static final long serialVersionUID = -6949226383735654353L;
private String id;
private String preId;
private String memberId;
private int changeOfAvailable;
private int changeOfBlock;
private Wallet before;
private Wallet alter;
private Integer type;
private String message;
private Date createTime;
private Long createUserId;
}
|
/******************************************************
Cours: LOG121
Projet: Framework.TP3
Nom du fichier: CollectionDes.java
Date créé: 2016-02-18
*******************************************************
Historique des modifications
*******************************************************
*@author Vincent Leclerc(LECV07069406)
*@author Gabriel Déry(DERG30049401)
2016-02-18 Version initiale
*******************************************************/
package Framework.Des;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Classe qui gère la collection de dés
* Created by Utilisateur on 2016-02-18.
*/
public class CollectionDes
{
private ArrayList<De> listeDe = new ArrayList<De>();
CollectionDes(){}
/**
* Permet d'ajouter un dé dans la collection
* @param d Dé à ajouter
*/
public void ajouterDe(De d){
listeDe.add(d);
}
/**
* Constructeur qui va initialiser la collection
* @param des listes de dés
*/
public void CollectionDe(ArrayList<De> des)
{
this.listeDe = des;
}
/**
* @return retourne la longeur de la collection
*/
public int getLength()
{
return listeDe.size();
}
/**
* @param index position du dé dans la collection
* @return le dé à la position de l'index
*/
public De get(int index){
return listeDe.get(index);
}
/**
* Permet de créer un itérateur à partir de la collection
* @return l'itérateur de dé
*/
public Iterator<De> creerIterateur(){
return new DeIterateur(this);
}
/**
* méthode qui va trier la collection en ordre croissant
*/
public void TrierCollection(){Collections.sort(listeDe);}
}
|
package org.sankozi.rogueland.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.*;
import org.sankozi.rogueland.model.coords.Coords;
import static org.junit.Assert.*;
import static org.sankozi.rogueland.util.Formatters.*;
/**
* FormattersTest
*
* @author sankozi
*/
public class FormattersTest {
private final static Logger LOG = LogManager.getLogger(FormattersTest.class);
@Test
public void formatParamTest(){
assertEquals("1",formatParam(1f));
assertEquals("2.1",formatParam(2.11f));
assertEquals("3.1",formatParam(3.199f));
assertEquals("40",formatParam(40.0009f));
}
}
|
/**
* RemoveBookAction.java
* Purpose: removing books from a base file, which are able to be borrowed from library.
*
* @version 1.0 23/02/2018
* @author Jakub Mitulski
*/
package com.library.actions.book;
import com.library.actions.Action;
import com.library.common.Book;
import com.library.common.User;
import com.library.utilities.ReadUserInputUtil;
import com.library.utilities.SaveListToFileUtil;
import com.library.utilities.SearchBookUtil;
import java.util.List;
public class RemoveBookAction implements Action {
@Override
public void doAction(List<Book> booksBase, List<User> usersBase) throws NullPointerException {
System.out.println("Type the book title to remove from books base: ");
String searchedTitle = ReadUserInputUtil.userString();
Book book = SearchBookUtil.searchBook(booksBase, searchedTitle);
if (book != null) {
booksBase.remove(book);
System.out.println(book.getTitle() + " removed from the database.");
SaveListToFileUtil.saveToFile(booksBase, "booksBase.tmp");
} else {
System.out.println("Wrong title!");
}
}
}
|
package com.tencent.mm.plugin.bottle.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class BottleWizardStep1$2 implements OnMenuItemClickListener {
final /* synthetic */ BottleWizardStep1 hlz;
BottleWizardStep1$2(BottleWizardStep1 bottleWizardStep1) {
this.hlz = bottleWizardStep1;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
this.hlz.YC();
this.hlz.finish();
return true;
}
}
|
package hrishi.gad.service;
import hrishi.gad.entity.Alerts;
import hrishi.gad.entity.Priority;
import hrishi.gad.entity.Readings;
import hrishi.gad.entity.Vehicles;
import hrishi.gad.exception.VehicleNotFoundException;
import hrishi.gad.repository.AlertsRepository;
import hrishi.gad.repository.ReadingsRepository;
import hrishi.gad.repository.TiresRepository;
import hrishi.gad.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class EntityServiceImplementation implements EntityService{
@Autowired
private VehicleRepository vehicleRepository;
@Autowired
private ReadingsRepository readingsRepository;
@Autowired
private TiresRepository tiresRepository;
@Autowired
private AlertsRepository alertsRepository;
@Override
@Transactional
public Vehicles[] update(Vehicles[] vehicles) {
for(Vehicles vehicle: vehicles) {
vehicleRepository.save(vehicle);
}
return vehicles;
}
@Override
@Transactional
public Readings create(Readings readings) {
Optional<Vehicles> existing = vehicleRepository.findById(readings.getVin());
if (existing.isPresent()) {
Optional<Readings> existing1 = readingsRepository.findById(readings.getVin());
existing1.ifPresent(value -> tiresRepository.delete(value.getTires()));
tiresRepository.save(readings.getTires());
readingsRepository.save(readings);
if(createAlert(readings));
return readings;
}
throw new VehicleNotFoundException("Cannot input Readings. Vehicle with id: " + readings.getVin() + " not found");
}
@Override
@Transactional
public boolean createAlert(Readings readings) {
List<Alerts> existing = alertsRepository.findByVin(readings.getVin());
if(!existing.isEmpty())
{
for(Alerts alert : existing){
alertsRepository.delete(alert);
}
}
if(readings.getEngineRpm() > vehicleRepository.findById(readings.getVin()).get().getRedlineRpm()){
Alerts alert = new Alerts();
alert.setVin(readings.getVin());
alert.setPriority(Priority.HIGH);
alert.setMessage("Engine RPM over Readline RPM");
alertsRepository.save(alert);
}
if(readings.getFuelVolume() < 0.1*(vehicleRepository.findById(readings.getVin()).get().getMaxFuelVolume())){
Alerts alert = new Alerts();
alert.setVin(readings.getVin());
alert.setPriority(Priority.MEDIUM);
alert.setMessage("Fuel Volume is less than 10% of Maximum Fuel Volume");
alertsRepository.save(alert);
}
if(readings.isEngineCoolantLow() || readings.isCheckEngineLightOn()){
Alerts alert = new Alerts();
alert.setVin(readings.getVin());
alert.setPriority(Priority.LOW);
alert.setMessage("Engine Coolant Low or Engine Light On");
alertsRepository.save(alert);
}
if((readings.getTires().getFrontLeft() < 32 || readings.getTires().getFrontRight() < 32 || readings.getTires().getRearLeft() < 32 || readings.getTires().getRearRight() < 32) || (readings.getTires().getFrontLeft() > 36 || readings.getTires().getFrontRight() > 36 || readings.getTires().getRearLeft() > 36 || readings.getTires().getRearRight() > 36)){
Alerts alert = new Alerts();
alert.setVin(readings.getVin());
alert.setPriority(Priority.LOW);
alert.setMessage("Check Tire Pressure");
alertsRepository.save(alert);
}
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package TFD.Presentation;
import TFD.DomainModel.Especialidade;
import TFD.DomainModel.EspecialidadeRepositorio;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.inject.Named;
/**
*
* @author Rosy
*/
@Named(value = "especialidadeController")
@SessionScoped
public class EspecialidadeController extends ControllerGenerico<Especialidade> implements Serializable{
// Especialidade entidade;
// Especialidade filtro;
// List<Especialidade> lista;
//
@EJB
EspecialidadeRepositorio dao;
public EspecialidadeController() {
entidade = new Especialidade();
filtro = new Especialidade();
}
public void validarEspacoEmBranco(FacesContext contexto, UIComponent componente, Object valor) {
String valorString = (String) valor;
if (valorString.trim().equals("")) {
((UIInput) componente).setValid(false);
String mensagem = componente.getAttributes().get("label")
+ ":Não é permitido espaço em branco. ";
FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, mensagem, mensagem);
contexto.addMessage(componente.getClientId(contexto), facesMessage);
}
}
// public void exibirMensagem(String msg) {
// FacesContext context = FacesContext.getCurrentInstance();
// context.addMessage(null, new FacesMessage(msg));
// }
/**
*
Criando o Metodo de salvar */
public void salvar() {
if(dao.Salvar(entidade)){
listagem = null;
} else {
//mensagem de erro
}
}
public String editar() {
return "Especialidades.xhtml";
}
public String novo(){
entidade = new Especialidade();
return "Especialidades.xhtml";
}
@Override
public String abrir() {
return "Especialidades.xhtml";
}
public String criar() {
entidade = new Especialidade();
return "EspecialidadeListar.xhtml";
}
@Override
public String cancelar() {
return "EspecialidadeListar.xhtml";
}
@Override
public String excluir() {
if(dao.Apagar(entidade)){
listagem = null;
return "";
} else {
return "";
}
}
@Override
public void filtrar() {
listagem = dao.Buscar(filtro);
}
// public String voltar() {
// lista = null;
// return "EspecialidadeListar.xhtml";
// }
public EspecialidadeRepositorio getDao() {
return dao;
}
public void setDao(EspecialidadeRepositorio dao) {
this.dao = dao;
}
}
|
/****************************************************
* $Project: DinoAge $
* $Date:: Jan 27, 2008 2:14:06 AM $
* $Revision: $
* $Author:: khoanguyen $
* $Comment:: $
**************************************************/
package org.ddth.blogging;
public class BlogPost extends Post {
private String title;
private String tags;
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
package twilight.bgfx;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import twilight.bgfx.buffers.DynamicIndexBuffer;
import twilight.bgfx.buffers.DynamicVertexBuffer;
import twilight.bgfx.buffers.IndexBuffer;
import twilight.bgfx.buffers.InstanceDataBuffer;
import twilight.bgfx.buffers.TransientIndexBuffer;
import twilight.bgfx.buffers.TransientVertexBuffer;
import twilight.bgfx.buffers.VertexBuffer;
import twilight.bgfx.window.Window;
/**
* <p>
* Main context class for BGFX, a cross-platform, graphics API agnostic,
* "Bring Your Own Engine/Framework" style rendering library.
* </p>
*
* <p>
* Twilight BGFX is a java binding for the original library.
* </p>
*
* <p>
* BGFX is final and should not be extended.
* </p>
*
* <p>
* <ul>
* <li>Twilight BGFX: https://github.com/enleeten/twilight-bgfx</li>
* <li>BGFX home page: https://github.com/bkaradzic/bgfx</li>
* </ul>
* </p>
*
* @author Tony McCrary (tmccrary@l33tlabs.com)
*
*/
final public class BGFX {
/** The native library name. */
private static final String LIB_NAME = "twilight-bgfx";
/** Invalid BFGX handle (buffers, shaders, etc.) */
public final static int INVALID_HANDLE = 65535;
/** Used with setViewFramebuffer(view, framebuffer) */
public final static int DEFAULT_FRAMEBUFFER = 65535;
/** The BGFX submission thread. */
private Thread submitThread;
/**
* A list of allocated transient vertex buffers. These are freed after every
* frame.
*/
private List<Long> vertexPointerList = new ArrayList<Long>();
/**
* A list of allocated transient index buffers. These are freed after every
* frame.
*/
private List<Long> indexPointerList = new ArrayList<Long>();
/** Whether the init call has been successfully made. */
private boolean inititalized = false;
/** Whether the natives have been loaded. */
private static boolean libraryLoaded = false;
static {
if(!libraryLoaded) {
try {
System.loadLibrary(LIB_NAME);
libraryLoaded = true;
} catch(Exception e) {
throw new BGFXException("Could not load BGFX native library: " + e.getMessage());
}
}
}
public BGFX() {
}
/**
* <pVerifies that the supplied BGFX context is active and valid for the
* current thread.
* </p>
*
* @param context
* the BGFX context to validate
*/
public static void checkValidContext(BGFX context) {
if(context == null) {
throw new BGFXException("Null BGFX context");
}
if(!context.isValidThread()) {
throw new BGFXException("Invalid BGFX thread.");
}
}
/**
*
* @param context
* @return
*/
public static boolean isValidContext(BGFX context) {
if(context == null) {
return false;
}
if(!context.isValidThread()) {
return false;
}
return context.inititalized;
}
/**
* <p>
* Returns true if the supplied BGFX shader/texture/etc handle is valid,
* false otherwise.
* </p>
*
* @param handleId
* a BGFX resource handle to test
*
* @return true if the supplied BGFX handle is valid, false otherwise
*/
public static boolean isValidHandle(int handleId) {
return handleId != BGFX.INVALID_HANDLE;
}
/**
* <p>
* Returns true if the current calling thread is the BGFX submission thread,
* false otherwise.
* </p>
*
* @return true if the current thread is the BGFX submission thread, false
* otherwise
*/
private boolean isValidThread() {
if (!Thread.currentThread().equals(submitThread)) {
return false;
}
return true;
}
/**
* <p>
* Checks the input ByteBuffer for use with BGFX. The input object cannot be
* null, must be a direct ByteBuffer and cannot be empty.
* </p>
*
* <p>
* If the input buffer is invalid, a runtime exception will be thrown.
* </p>
*
* @param memory
* the ByteBuffer to test
*/
private void checkValidByteBuffer(ByteBuffer memory) {
if (memory == null) {
throw new NullPointerException(Messages.getString("BGFX.NullByteBuffer")); //$NON-NLS-1$
}
if (!memory.isDirect()) {
throw new BGFXException(Messages.getString("BGFX.NonDirectBufferError")); //$NON-NLS-1$
}
if (memory.capacity() == 0) {
throw new BGFXException(Messages.getString("BGFX.EmptyDirectBufferError")); //$NON-NLS-1$
}
}
/**
* <p>
* Returns the type of renderer BGFX is using to draw graphics.
* </p>
*
* @return the RendererType that is being used to draw graphics
*/
public RendererType getRendererType() {
int index = ngetRendererType();
return RendererType.values()[index];
}
/**
*
* <p>
* Pack vec4 into vertex stream format.
* </p>
*
* @param input
* @param inputNormalized
* @param attr
* @param decl
* @param data
* @param index
*/
public void vertexPack(float input[], boolean inputNormalized, Attrib attr, VertexDecl decl, long data, long index) {
nvertexPack(input, inputNormalized, attr, decl, data, index);
}
/**
* <p>
* Unpack vec4 from vertex stream format.
* </p>
*
* @param output
* @param attr
* @param decl
* @param data
* @param index
*/
public void vertexUnpack(float output, Attrib attr, VertexDecl decl, long data, long index) {
nvertexUnpack(output, attr, decl, data, index);
}
/**
* <p>
* Converts vertex stream data from one vertex stream format to another.
* </p>
*
* @param destDecl
* Destination vertex stream declaration.
* @param destData
* Destination vertex stream.
* @param srcDecl
* Source vertex stream declaration.
* @param srcData
* Source vertex stream data.
* @param num
* Number of vertices to convert from source to destination.
*/
public void vertexConvert(VertexDecl destDecl, long destData, VertexDecl srcDecl, long srcData, long num) {
nvertexConvert(destDecl, destData, srcDecl, srcData, num);
}
/**
* <p>
* Weld vertices.
* </p>
*
* @param output
* Welded vertices remapping table. The size of buffer must be
* the same as number of vertices.
* @param decl
* Vertex stream declaration.
* @param data
* Vertex stream.
* @param num
* Number of vertices in vertex stream.
* @param epsilon
* Error tolerance for vertex position comparison.
* @return Number of unique vertices after vertex welding.
*/
public int weldVertices(long output, VertexDecl decl, long data, int num, float epsilon) {
return nweldVertices(output, decl, data, num, epsilon);
}
/**
* <p>
* Swizzle RGBA8 image to BGRA8.
* </p>
*
* @param width
* Width of input image (pixels).
* @param height
* Width of input image (pixels).
* @param pitch
* Pitch of input image (bytes).
* @param src
* Source image.
* @param dst
* Destination image. Must be the same size as input image. dst
* might be pointer to the same memory as src.
*/
public void imageSwizzleBgra8(long width, long height, long pitch, long src, long dst) {
nimageSwizzleBgra8(width, height, pitch, src, dst);
}
/**
* <p>
* Downsample RGBA8 image with 2x2 pixel average filter.
* </p>
*
* @param width
* Width of input image (pixels).
* @param height
* Height of input image (pixels).
* @param pitch
* Pitch of input image (bytes).
* @param src
* Source image.
* @param dst
* Destination image. Must be at least quarter size of
*/
public void imageRgba8Downsample2x2(long width, long height, long pitch, long src, long dst) {
nimageRgba8Downsample2x2(width, height, pitch, src, dst);
}
/**
* <p>
* Initialize bgfx library.
* </p>
*
* @param rendererType
* Select rendering backend. When set to RendererType::Count
* @param deviceVendor
* Vendor PCI id. If set to BGFX_PCI_ID_NONE it will select the
* first device.
* @param deviceId
* Device id. If set to 0 it will select first device, or device
* with matching id.
*/
public void init(RendererType rendererType, long deviceVendor, int deviceId) {
submitThread = Thread.currentThread();
ninit(rendererType.ordinal(), (int) deviceVendor, deviceId);
}
/**
* <p>
* Overloaded convenience method for init(RendererType, long, int)
* </p>
* <p>
* Uses default/autodetect settings.
* </p>
*/
public void init() {
submitThread = Thread.currentThread();
ninit(RendererType.Count.ordinal(), (int) BGFX_PCI_ID_NONE, 0);
inititalized = true;
}
/**
* <p>
* Shutdown bgfx library.
* </p>
*/
public void shutdown() {
nshutdown();
}
/**
* <p>
* Reset graphic settings and back-buffer size.
* </p>
*
* @param width
* Back-buffer width.
* @param height
* Back-buffer height.
* @param flags
* Allows you to specify flags with BGFX_RESET_* enums
* <ul>
* <li>BGFX_RESET_NONE - No reset flags.</li>
* <li>BGFX_RESET_FULLSCREEN - Not supported yet.</li>
* <li>BGFX_RESET_MSAA_X[2/4/8/16] - Enable 2, 4, 8 or 16 x MSAA.
* </li>
* <li>BGFX_RESET_VSYNC - Enable V-Sync.</li>
* <li>BGFX_RESET_MAXANISOTROPY - Turn on/off max anisotropy.
* </li>
* <li>BGFX_RESET_CAPTURE - Begin screen capture.</li>
* <li>BGFX_RESET_HMD - HMD stereo rendering.</li>
* <li>BGFX_RESET_HMD_DEBUG - HMD stereo rendering debug mode.
* </li>
* <li>BGFX_RESET_HMD_RECENTER - HMD calibration.</li>
* <li>BGFX_RESET_FLIP_AFTER_RENDER - This flag specifies where
* flip occurs. Default behavior is that flip occurs before
* rendering new frame. This flag only has effect when compiled
* with <i>BGFX_CONFIG_MULTITHREADED=0</i>.</li>
* </ul>
*
* <b>Note:</b> This call doesn't actually change window size, it
* just resizes back-buffer. Windowing code has to change window
* size.
*
*/
public void reset(long width, long height, long flags) {
nreset(width, height, flags);
}
/**
* <p>
* Advance to next frame. When using multithreaded renderer, this call just
* swaps internal buffers, kicks render thread, and returns. In
* single threaded renderer this call does frame rendering.
* </p>
*
* @return Current frame number. This might be used in conjunction with
* double/multi buffering data outside the library and passing it to
* library via `bgfx::makeRef` calls.
*/
public long frame() {
long result = nframe();
freeTransientVertexPointers();
freeTransientIndexPointers();
return result;
}
/**
* <p>
* Returns renderer capabilities.
* </p>
*
* @return capabilities instance.
*/
public Caps getCaps() {
return ngetCaps();
}
/**
* <p>
* Allocate buffer to pass to bgfx calls. Data will be freed inside bgfx.
* </p>
*
* @param size
* the number of bytes to allocate.
*
* @return a direct ByteBuffer of the specified size
*/
public ByteBuffer alloc(long size) {
return alloc(size);
}
/**
* <p>
* Allocate buffer and copy data into it. Data will be freed inside bgfx.
* </p>
*
* @param dataPointer
* pointer to memory to allocate
* @param size
* the byte size of the memory at the pointer
*
* @return a direct ByteBuffer of the specified size
*/
public ByteBuffer copy(long dataPointer, long size) {
return ncopy(dataPointer, size);
}
/**
* <p>
* Make reference to data to pass to bgfx. Unlike `bgfx::alloc` this call
* doesn't allocate memory for data. It just copies pointer to data. You can
* pass `ReleaseFn` function pointer to release this memory after it's
* consumed, or you must make sure data is available for at least 2
* `bgfx::frame` calls. `ReleaseFn` function must be able to be called
* called from any thread.
* </p>
*
* <b>This method needs some refactoring.</b>
*
* @param data
* pointer to create a reference for
* @param size
* the byte size of the memory at the pointer
* @return a direct ByteBuffer of the specified size
*/
public ByteBuffer makeRef(long data, long size) {
return nmakeRef(data, size);
}
/**
* <p>
* Set debug flags.
* </p>
*
* <b>Note: these flags need to be OR'd together</b>
*
* @param debug
* integer containing OR'd flags to set
*
* <b>Available flags:</b>
* <ul>
* <li><b>BGFX_DEBUG_IFH</b> - Infinitely fast hardware. When
* this flag is set all rendering calls will be skipped. It's
* useful when profiling to quickly assess bottleneck between CPU
* and GPU.</li>
* <li><b>BGFX_DEBUG_STATS</b> - Display internal statistics.
* </li>
* <li><b>BGFX_DEBUG_TEXT</b> - Display debug text.</li>
* <li><b>BGFX_DEBUG_WIREFRAME</b> - Wireframe rendering. All
* rendering primitives will be rendered as lines.</li>
* </ul>
*/
public void setDebug(long debug) {
nsetDebug(debug);
}
/**
* <p>
* Clear internal debug text buffer.
* </p>
*
* @param attr
* the attribute to clear
* @param small
* small text
*/
public void dbgTextClear(short attr, boolean small) {
ndbgTextClear(attr, small);
}
/**
* <p>
* Clear internal debug text buffer.
* </p>
* <p>
* Uses defaults (0, false)
* </p>
*/
public void dbgTextClear() {
ndbgTextClear((short) 0, false);
}
/**
* <p>
* Print into internal debug text buffer
* </p>
*
* @param x
* the x coordinate to print to
* @param y
* the y coordinate to print to
* @param attr
* the attributes (color, etc) to print
* @param format
* the string message
*/
public void dbgTextPrintf(int x, int y, short attr, String format) {
ndbgTextPrintf(x, y, attr, format);
}
/**
* <p>
* Draw image into internal debug text buffer.
* </p>
*
* @param x
* X position from top-left.
* @param y
* Y position from top-left.
* @param width
* Image width.
* @param height
* Image height.
* @param imageData
* Raw image data (character/attribute raw encoding).
* @param pitch
* Image pitch in bytes
*/
public void dbgTextImage(int x, int y, int width, int height, ByteBuffer imageData, int pitch) {
throw new RuntimeException("Not Implemented!");
}
/**
* <p>
* Create static index buffer. Convenience method, prefer the ByteBuffer
* implementation if possible.
* </p>
*
* <p>
* NOTE: This method needs to be updated to support BGFX flags.
* </p>
*
* @param indices
* a short array containing index values
*
* @return a GPU BGFX IndexBuffer handle containing indices from the
* supplied array
*/
public IndexBuffer createIndexBuffer(short[] indices) {
ByteBuffer indexData = ByteBuffer.allocateDirect(indices.length * 2).order(ByteOrder.nativeOrder());
indexData.asShortBuffer().put(indices);
indexData.rewind();
return createIndexBuffer(indexData);
}
/**
* <p>
* Create static index buffer.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param mem
* a direct ByteBuffer containing index values
*
* @return a GPU BGFX IndexBuffer handle containing indices from the
* supplied buffer
*/
public IndexBuffer createIndexBuffer(ByteBuffer mem) {
checkValidByteBuffer(mem);
return new IndexBuffer(ncreateIndexBuffer(mem));
}
/**
* <p>
* Destroy static index buffer.
* </p>
*
* @param handle
* the buffer handle to destroy
*/
public void destroyIndexBuffer(int handle) {
ndestroyIndexBuffer(handle);
}
/**
* <p>
* Create static vertex buffer. Convenience method, prefer the ByteBuffer
* version if possible.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
* <p>
* Note: this currently assumes 32-bit floats.
* </p>
*
* @param mem
* Vertex buffer data in a float array.
* @param decl
* Vertex declaration.
* @return Static vertex buffer handle.
*/
public VertexBuffer createVertexBuffer(float[] mem, VertexDecl decl) {
ByteBuffer vertexData = ByteBuffer.allocateDirect(mem.length * 4).order(ByteOrder.nativeOrder());
vertexData.asFloatBuffer().put(mem);
vertexData.rewind();
return createVertexBuffer(vertexData, decl);
}
/**
* <p>
* Create static vertex buffer.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param mem
* Vertex buffer data in direct ByteBuffer
* @param decl
* Vertex declaration.
* @return Static vertex buffer handle.
*/
public VertexBuffer createVertexBuffer(ByteBuffer mem, VertexDecl decl) {
checkValidByteBuffer(mem);
if (decl == null) {
throw new NullPointerException(Messages.getString("BGFX.NullVertexDeclaration")); //$NON-NLS-1$
}
if (!decl.isValid()) {
throw new BGFXException(Messages.getString("BGFX.InvalidVertexDeclaration")); //$NON-NLS-1$
}
int handle = ncreateVertexBuffer(mem, decl);
return new VertexBuffer(handle);
}
/**
* <p>
* Destroy static vertex buffer.
* </p>
*
* @param handle
* the buffer handle to destroy
*/
public void destroyVertexBuffer(VertexBuffer handle) {
ndestroyVertexBuffer((int) handle.getHandle());
}
/**
* <p>
* Create dynamic index buffer.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param mem
* a direct ByteBuffer containing index values
*
* @return a GPU BGFX IndexBuffer handle containing indices from the
* supplied buffer
*/
public DynamicIndexBuffer createDynamicIndexBuffer(ByteBuffer mem) {
checkValidByteBuffer(mem);
int handle = ncreateDynamicIndexBuffer(mem);
return new DynamicIndexBuffer(handle);
}
/**
* <p>
* Update dynamic index buffer.
* </p>
*
* @param handle
* Dynamic index buffer handle
* @param mem
* Index buffer data.
*/
public void updateDynamicIndexBuffer(DynamicIndexBuffer handle, ByteBuffer mem) {
checkValidByteBuffer(mem);
nupdateDynamicIndexBuffer((int) handle.getHandle(), mem);
}
/**
* <p>
* Destroy dynamic index buffer.
* </p>
*
* @param handle
* the buffer handle to destroy
*/
public void destroyDynamicIndexBuffer(DynamicIndexBuffer handle) {
ndestroyDynamicIndexBuffer((int) handle.getHandle());
}
/**
* <p>
* Create empty dynamic vertex buffer.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param num
* Number of vertices.
* @param decl
* Vertex declaration.
* @return Dynamic vertex buffer handle.
*/
public DynamicVertexBuffer createDynamicVertexBuffer(int num, VertexDecl decl) {
int bufferHandle = ncreateDynamicVertexBuffer(num, decl);
if (bufferHandle == BGFX.INVALID_HANDLE) {
throw new BGFXException(Messages.getString("BGFX.ErrorCreatingVertexBuffer") + bufferHandle); //$NON-NLS-1$
}
return new DynamicVertexBuffer(bufferHandle);
}
/**
* <p>
* Create dynamic vertex buffer. Convenience method, prefer the ByteBuffer
* version if possible.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param mem
* Vertex buffer data in a float array
* @param decl
* Vertex declaration.
* @return Static vertex buffer handle.
*/
public DynamicVertexBuffer createDynamicVertexBuffer(float[] mem, VertexDecl decl) {
ByteBuffer vertexData = ByteBuffer.allocateDirect(mem.length * 4).order(ByteOrder.nativeOrder());
vertexData.asFloatBuffer().put(mem);
vertexData.rewind();
return createDynamicVertexBuffer(vertexData, decl);
}
/**
* <p>
* Create dynamic vertex buffer.
* </p>
*
* <p>
* Note: This method needs to be updated to support BGFX flags.
* </p>
*
* @param mem
* Vertex buffer data in direct ByteBuffer
* @param decl
* Vertex declaration.
* @return Static vertex buffer handle.
*/
public DynamicVertexBuffer createDynamicVertexBuffer(ByteBuffer mem, VertexDecl decl) {
int bufferHandle = ncreateDynamicVertexBuffer(mem, decl);
if (bufferHandle == BGFX.INVALID_HANDLE) {
throw new BGFXException(Messages.getString("BGFX.ErrorCreatingVertexBuffer") + bufferHandle); //$NON-NLS-1$
}
return new DynamicVertexBuffer(bufferHandle);
}
/**
* <p>
* Update dynamic vertex buffer.
* </p>
*
* @param handle
* Dynamic vertex buffer handle
* @param mem
* vertex buffer data.
*/
public void updateDynamicVertexBuffer(int handle, ByteBuffer mem) {
checkValidByteBuffer(mem);
nupdateDynamicVertexBuffer(handle, mem);
}
/**
* <p>
* Destroy dynamic vertex buffer.
* </p>
*
* @param handle
* the buffer handle to destroy
*/
public void destroyDynamicVertexBuffer(int handle) {
ndestroyDynamicVertexBuffer(handle);
}
/**
* <p>
* Returns true if internal transient index buffer has enough space.
* </p>
*
* @param num
* Number of indices.
* @return true if internal transient index buffer has enough space.
*/
public boolean checkAvailTransientIndexBuffer(long num) {
return ncheckAvailTransientIndexBuffer(num);
}
/**
* <p>
* Returns true if internal transient vertex buffer has enough space.
* </p>
*
* @param num
* Number of vertices.
* @param decl
* the Vertex Declaration
* @return true if internal transient vertex buffer has enough space.
*/
public boolean checkAvailTransientVertexBuffer(long num, VertexDecl decl) {
return ncheckAvailTransientVertexBuffer(num, decl);
}
/**
* <p>
* Returns true if internal instance data buffer has enough space.
* </p>
*
* @param num
* Number of instances.
* @param decl
* Stride per instance.
* @return true if internal transient vertex buffer has enough space.
*/
public boolean checkAvailInstanceDataBuffer(long num, int stride) {
return ncheckAvailInstanceDataBuffer(num, stride);
}
/**
* <p>
* Returns true if both internal transient index and vertex buffer have
* enough space.
* </p>
*
* @param numVertices
* Number of vertices.
* @param decl
* the Vertex Declaration
* @param numIndices
* Number of indices.
* @return true if internal transient vertex buffer has enough space.
*/
public boolean checkAvailTransientBuffers(long numVertices, VertexDecl decl, long numIndices) {
return ncheckAvailTransientBuffers(numVertices, decl, numIndices);
}
/**
* <p>
* Allocate transient index buffer.
* </p>
*
* <ol>
* <li>You must call setIndexBuffer after alloc in order to avoid memory
* leak.</li>
* <li>Only 16-bit index buffer is supported.</li>
* </ol>
*
* @param num
* Number of indices to allocate.
* @return TransientIndexBuffer instance
*/
public TransientIndexBuffer allocTransientIndexBuffer(long num) {
TransientIndexBuffer buffer = nallocTransientIndexBuffer(num);
long pointer = buffer.pointer;
storeTransientIndexPointer(pointer);
return buffer;
}
/**
* <p>
* Allocate transient vertex buffer.
* </p>
*
* <ol>
* <li>You must call setVertexBuffer after alloc in order to avoid memory
* leak.</li>
* </ol>
*
* @param num
* Number of vertices to allocate.
* @return TransientVertexBuffer instance
*/
public TransientVertexBuffer allocTransientVertexBuffer(long num, VertexDecl decl) {
TransientVertexBuffer buffer = nallocTransientVertexBuffer(num, decl);
long pointer = buffer.pointer;
storeTransientVertexPointer(pointer);
return buffer;
}
private void storeTransientVertexPointer(long pointer) {
vertexPointerList.add(pointer);
}
private void storeTransientIndexPointer(long pointer) {
indexPointerList.add(pointer);
}
/**
* <p>
* Allocate instance data buffer.
* </p>
*
* <p>
* Note: You must call setInstanceDataBuffer after alloc in order to avoid
* memory leak.
* </p>
*
* @param num
* the number of instances
* @param stride
* the stride between instances
* @return InstanceDataBuffer instance
*/
public InstanceDataBuffer allocInstanceDataBuffer(long num, int stride) {
return nallocInstanceDataBuffer(num, stride);
}
/**
* <p>
* Create shader from memory buffer.
* </p>
*
* @param mem
* ByteBuffer containing BGFX shader data
* @return a ShaderHandle id
*/
public int createShader(ByteBuffer mem) {
checkValidByteBuffer(mem);
return ncreateShader(mem);
}
/**
* <p>
* Note: This method needs more work to match up with the native use case.
* </p>
*
* @return Returns num of uniforms
*/
public int getShaderUniforms(int handle, int uniforms, int max) {
return ngetShaderUniforms(handle, uniforms, max);
}
/**
* <p>
* Destroy shader. Once program is created with shader it is safe to destroy
* shader.
* </p>
*
* @param handle
* ShaderHandle id
*/
public void destroyShader(int handle) {
ndestroyShader(handle);
}
/**
* <p>
* Create program with vertex and fragment shaders.
* </p>
*
* @param vsh
* Vertex shader.
* @param fsh
* Fragment shader.
* @param destroyShaders
* If true, shaders will be destroyed when program is destroyed.
* @return Program handle if vertex shader output and fragment shader input
* are matching, otherwise returns invalid program handle.
*/
public int createProgram(int vsh, int fsh, boolean destroyShaders) {
return ncreateProgram(vsh, fsh, destroyShaders);
}
/**
* <p>
* Destroy program.
* </p>
*
* @param handle
*/
public void destroyProgram(int handle) {
ndestroyProgram(handle);
}
/***
* <p>
* Note: This method needs more work to match up with the native use case.
* </p>
*
* @param info
* @param width
* @param height
* @param depth
* @param numMips
* @param format
*/
public void calcTextureSize(TextureInfo info, int width, int height, int depth, short numMips, TextureFormat format) {
ncalcTextureSize(info, width, height, depth, numMips, format);
}
/**
* <p>
* Create texture from memory buffer.
* </p>
*
* @param mem
* DDS, KTX or PVR texture data.
* @param flags
* Default texture sampling mode is linear, and wrap mode
* @param skip
* Skip top level mips when parsing texture.
* @param info
* When non-`NULL` is specified it returns parsed texture
* information.
* @return Texture handle.
*/
public int createTexture(ByteBuffer mem, long flags, int skip, TextureInfo info) {
checkValidByteBuffer(mem);
return ncreateTexture(mem, flags, (short) skip, info);
}
/**
* <p>
* Create 2D texture.
* </p>
*
* @param width
* Width.
* @param height
* Height.
* @param numMips
* Number of mip-maps.
* @param format
* Texture format. See: `TextureFormat::Enum`.
* @param flags
* Default texture sampling mode is linear, and wrap mode is
* repeat
* @param mem
* ByteBuffer containing texture data
*
* <ul>
* <li>BGFX_TEXTURE_[U/V/W]_[MIRROR/CLAMP] - Mirror or clamp to
* edge wrap mode.</li>
* <li>BGFX_TEXTURE_[MIN/MAG/MIP]_[POINT/ANISOTROPIC] - Point or
* anisotropic sampling.</li>
* </ul>
*
* @return TextureHandle id for the new texture
*/
public int createTexture2D(int width, int height, int numMips, TextureFormat format, long flags, ByteBuffer mem) {
if (format == null) {
throw new BGFXException(Messages.getString("BGFX.InvalidTextureFormat"));
}
if (mem != null && !mem.isDirect()) {
throw new BGFXException(Messages.getString("BGFX.NonDirectBufferError")); //$NON-NLS-1$
}
return ncreateTexture2D(width, height, (short) numMips, format, flags, mem);
}
/**
* <p>
* Update 2D texture.
* </p>
*
* @param handle
* Texture handle.
* @param mip
* Mip level.
* @param x
* X offset in texture.
* @param y
* Y offset in texture.
* @param width
* Width of texture block.
* @param height
* Height of texture block.
* @param mem
* Texture update data.
* @param pitch
* Pitch of input image (bytes). When pitch is set to
* UINT16_MAX, it will be calculated internally based on width.
*/
public void updateTexture2D(int handle, short mip, int x, int y, int width, int height, ByteBuffer mem, int pitch) {
nupdateTexture2D(handle, mip, x, y, width, height, mem, pitch);
}
/**
* <p>
* Create 3D texture.
* </p>
*
* @param width
* Width.
* @param height
* Height.
* @param depth
* Depth.
* @param numMips
* Number of mip-maps.
* @param format
* Texture format. See: `TextureFormat::Enum`.
* @param flags
* Default texture sampling mode is linear, and wrap mode is
* repeat.
* @param mem
* Texture data.
*
* @return TextureHandle id
*/
public int createTexture3D(int width, int height, int depth, short numMips, TextureFormat format, long flags, ByteBuffer mem) {
return ncreateTexture3D(width, height, depth, numMips, format, flags, mem);
}
/**
* <p>
* Update 3D texture.
* </p>
*
* @param handle
* Texture handle.
* @param mip
* Mip level.
* @param x
* X offset in texture.
* @param y
* Y offset in texture.
* @param z
* Z offset in texture.
* @param width
* Width of texture block.
* @param height
* Height of texture block.
* @param depth
* Depth of texture block.
* @param mem
* Texture update data.
*/
public void updateTexture3D(int handle, short mip, int x, int y, int z, int width, int height, int depth, ByteBuffer mem) {
nupdateTexture3D(handle, mip, x, y, z, width, height, depth, mem);
}
/**
* <p>
* Create Cube texture.
* </p>
*
* @param size
* Cube side size.
* @param numMips
* Number of mip-maps.
* @param format
* Texture format. See: `TextureFormat::Enum`.
* @param flags
* Default texture sampling mode is linear, and wrap mode is
* repeat.
* @param mem
* Texture data.
*
* <ol>
* <il>BGFX_TEXTURE_[U/V/W]_[MIRROR/CLAMP] - Mirror or clamp to
* edge wrap mode.</il>
* <il>BGFX_TEXTURE_[MIN/MAG/MIP]_[POINT/ANISOTROPIC] - Point or
* anisotropic sampling.</il>
* </ol>
*
* @return TextureHandle id
*/
public int createTextureCube(int size, short numMips, TextureFormat format, long flags, ByteBuffer mem) {
return ncreateTextureCube(size, numMips, format, flags, mem);
}
/**
* <p>
* Update Cube texture.
* </p>
*
* @param handle
* Texture handle.
* @param side
* Cubemap side, where 0 is +X, 1 is -X, 2 is +Y, 3 is -Y, 4 is
* +Z, and 5 is -Z.
* @param mip
* Mip level.
* @param x
* X offset in texture.
* @param y
* Y offset in texture.
* @param width
* Width of texture block.
* @param height
* Height of texture block.
* @param mem
* Texture update data.
* @param pitch
* Pitch of input image (bytes). When pitch is set to
* UINT16_MAX, it will be calculated internally based on width.
*
* <pre>
* +----------+
* |-z 2|
* | ^ +y |
* | | |
* | +---->+x |
* +----------+----------+----------+----------+
* |+y 1|+y 4|+y 0|+y 5|
* | ^ -x | ^ +z | ^ +x | ^ -z |
* | | | | | | | | |
* | +---->+z | +---->+x | +---->-z | +---->-x |
* +----------+----------+----------+----------+
* |+z 3|
* | ^ -y |
* | | |
* | +---->+x |
* +----------+
* </pre>
*/
public void updateTextureCube(int handle, short side, short mip, int x, int y, int width, int height, ByteBuffer mem, int pitch) {
nupdateTextureCube(handle, side, mip, x, y, width, height, mem, pitch);
}
/**
* <p>
* Destroy texture.
* </p>
*
* @param handle
* TextureHandle id of the texture to destroy
*/
public void destroyTexture(int handle) {
ndestroyTexture(handle);
}
/**
* <p>
* Create frame buffer (simple).
* </p>
*
* @param width
* Texture width.
* @param height
* Texture height.
* @param format
* Texture format. See: `TextureFormat::Enum`.
* @param textureFlags
* Default texture sampling mode is linear, and wrap mode
* @return FramebufferHandle id
*/
public int createFrameBuffer(int width, int height, TextureFormat format, long textureFlags) {
return ncreateFrameBuffer(width, height, format, textureFlags);
}
/**
* <p>
* Create a framebuffer with attachmennts.
* </p>
*
* @param num
* the number of texture attachments
* @param handles
* array of TextureHandle ids
* @param destroyTextures
* If true, textures will be destroyed when frame buffer is
* destroyed.
* @return FramebufferHandle id
*/
public int createFrameBuffer(int num, int[] handles, boolean destroyTextures) {
return ncreateFrameBuffer(num, handles, destroyTextures);
}
/**
* <p>
* Create frame buffer for multiple window rendering.
* </p>
*
* @param window
* OS' target native window handle.
* @param width
* Window back buffer width.
* @param height
* Window back buffer height.
* @param format
* Window back buffer depth format.
*
* @return FramebufferHandle id
*/
public int createFrameBuffer(Window window, int width, int height, TextureFormat format) {
return ncreateFrameBuffer(window.getNativeHandle(), width, height, format);
}
/**
* <p>
* Destroy frame buffer.
* </p>
*
* @param handle
*/
public void destroyFrameBuffer(int handle) {
ndestroyFrameBuffer(handle);
}
/**
* <p>
* Create shader uniform parameter.
* </p>
*
* @param name
* Uniform name in shader.
* @param type
* Type of uniform (See: `bgfx::UniformType`).
* @param num
* Number of elements in array.
* @return Handle to uniform object.
*
* Predefined uniforms (declared in `bgfx_shader.sh`):
*
* <ul>
* <li>u_viewRect vec4(x, y, width, height) - view rectangle for
* current view.</li>
* <li>u_viewTexel vec4(1.0/width, 1.0/height, undef, undef) -
* inverse width and height</li>
* <li>u_view mat4 - view matrix</li>
* <li>u_invView mat4 - inverted view matrix</li>
* <li>u_proj mat4 - projection matrix</li>
* <li>u_invProj mat4 - inverted projection matrix</li>
* <li>u_viewProj mat4 - concatenated view projection matrix</li>
* <li>u_invViewProj mat4 - concatenated inverted view projection
* matrix</li>
* <li>u_model mat4[BGFX_CONFIG_MAX_BONES] - array of model
* matrices.</li>
* <li>u_modelView mat4 - concatenated model view matrix, only first
* model matrix from array is used.</li>
* <li>u_modelViewProj mat4 - concatenated model view projection
* matrix.</li>
* <li>u_alphaRef float` - alpha reference value for alpha test.
* </li>
* </ul>
*/
public int createUniform(String name, UniformType type, int num) {
return ncreateUniform(name, type.ordinal(), num);
}
/**
* <p>
* Destroys the uniform.
* </p>
*
* @param handle
* UniformHandle id
*/
public void destroyUniform(int handle) {
ndestroyUniform(handle);
}
/**
* <p>
* Set view name
* </p>
*
* @param id
* View id.
* @param name
* View name.
*
* <pre>
* This is debug only feature.
*
* In graphics debugger view name will appear as:
*
* "nnnce <view name>"
* ^ ^^ ^
* | |+-- eye (L/R)
* | +-- compute (C)
* +-- view id
* </pre>
*/
public void setViewName(int id, String name) {
nsetViewName((short) id, name);
}
/**
* <p>
* Set view rectangle. Draw primitive outside view will be clipped.
* </p>
*
* @param id
* View id.
* @param x
* Position x from the left corner of the window.
* @param y
* Position y from the top corner of the window.
* @param width
* Width of view port region.
* @param height
* Height of view port region.
*/
public void setViewRect(int id, int x, int y, int width, int height) {
nsetViewRect((short) id, x, y, width, height);
}
/**
* <p>
* Set view scissor. Draw primitive outside view will be clipped. When x,
* y, width and height are set to 0, scissor will be disabled.
* </p>
*
* @param id
* View id
* @param x
* Position x from the left corner of the window.
* @param y
* Position y from the top corner of the window.
* @param width
* Width of scissor region.
* @param height
* Height of scissor region.
*/
public void setViewScissor(int id, int x, int y, int width, int height) {
nsetViewScissor((short) id, x, y, width, height);
}
/**
* <p>
* Set view clear flags.
* </p>
*
* @param id
* View id.
* @param flags
* Clear flags. Use `BGFX_CLEAR_NONE` to remove any clear
* operation. See: `BGFX_CLEAR_*`.
* @param rgba
* Color clear value.
* @param depth
* Depth clear value.
* @param stencil
* Stencil clear value.
*/
public void setViewClear(int id, long flags, long rgba, float depth, int stencil) {
nsetViewClear((short) id, (short) flags, rgba, depth, (short) stencil);
}
/**
* <p>
* Set view into sequential mode. Draw calls will be sorted in the same
* order in which submit calls were called.
* </p>
*
* <p>
* This is particularly useful for rendering GUI systems.
* </p>
*
* @param id
* view id
* @param enabled
* if true, all render calls will retain their sequential order
* and will not be sorted for better performance.
*/
public void setViewSeq(int id, boolean enabled) {
nsetViewSeq((short) id, enabled);
}
/**
* <p>
* Set view frame buffer.
* </p>
*
* @param id
* View id.
* @param handle
* Frame buffer handle. Passing `BGFX_INVALID_HANDLE` as frame
* buffer handle will draw primitives from this view into
*/
public void setViewFrameBuffer(int id, int handle) {
nsetViewFrameBuffer((short) id, handle);
}
/**
* <p>
* Set view view and projection matrices, all draw primitives in this view
* will use these matrices.
* </p>
*
* @param id
* View id.
* @param view
* View matrix.
* @param proj
* Projection matrix. When using stereo rendering this projection
* matrix represent projection matrix for left eye.
*/
public void setViewTransform(int id, float[] view, float[] proj) {
nsetViewTransform((short) id, view, proj);
}
/**
* <p>
* Sets debug marker.
* </p>
*
* @param marker
* marker text
*/
public void setMarker(String marker) {
nsetMarker(marker);
}
/**
* <p>
* Set render states for draw primitive.
* </p>
*
* @param state
* State flags. Default state for primitive type is triangles.
* @param rgba
* Sets blend factor used by `BGFX_STATE_BLEND_FACTOR`
* and`BGFX_STATE_BLEND_INV_FACTOR` blend modes.
*
* See: `BGFX_STATE_DEFAULT`.
*
* <ul>
* <li>BGFX_STATE_ALPHA_WRITE` - Enable alpha write.</li>
* <li>BGFX_STATE_DEPTH_WRITE` - Enable depth write.</li>
* <li>BGFX_STATE_DEPTH_TEST_*` - Depth test function.</li>
* <li>BGFX_STATE_BLEND_*` - See remark 1 about
* BGFX_STATE_BLEND_FUNC.</li>
* <li>BGFX_STATE_BLEND_EQUATION_*` - See remark 2.</li>
* <li>BGFX_STATE_CULL_*` - Backface culling mode.</li>
* <li>BGFX_STATE_RGB_WRITE` - Enable RGB write.</li>
* <li>BGFX_STATE_MSAA` - Enable MSAA.</li>
* <li>BGFX_STATE_PT_[TRISTRIP/LINES/POINTS]` - Primitive type.
* </li>
* </ul>
*
* <ol>
* <li>Use `BGFX_STATE_ALPHA_REF`, `BGFX_STATE_POINT_SIZE` and
* `BGFX_STATE_BLEND_FUNC` macros to setup more complex states.
* </li>
* <li>`BGFX_STATE_BLEND_EQUATION_ADD` is set when no other blend
* equation is specified.</li>
* </ol>
*
*/
public void setState(long state, long rgba) {
nsetState(state, rgba);
}
/**
* <p>
* Set stencil test state.
* </p>
*
* @param fstencil
* Front stencil state.
* @param bstencil
* Back stencil state. If back is set to `BGFX_STENCIL_NONE`
* fstencil is applied to both front and back facing primitives.
*/
public void setStencil(long fstencil, long bstencil) {
nsetStencil(fstencil, bstencil);
}
/**
* <p>
* Set scissor for draw primitive. For scissor for all primitives in view
* see setViewScissor.
* </p>
*
* @param x
* Position x from the left corner of the window.
* @param y
* Position y from the top corner of the window.
* @param width
* Width of scissor region.
* @param height
* Height of scissor region.
*
* @return Scissor cache index.
*/
public int setScissor(int x, int y, int width, int height) {
return nsetScissor(x, y, width, height);
}
/**
* <p>
* Set scissor from cache for draw primitive.
* </p>
*
* @param cache
* Index in scissor cache. Passing UINT16_MAX unset primitive
* scissor and primitive will use view scissor instead.
*/
public void setScissor(int cache) {
nsetScissor(cache);
}
/**
* <p>
* Set model matrix for draw primitive. If it is not called model will be
* rendered with identity model matrix.
* </p>
*
* @param mtx
* Pointer to first matrix in array.
* @param num
* Number of matrices in array.
* @return index into matrix cache in case the same model matrix has to be
* used for other draw primitive call.
*/
public long setTransform(float[] mtx, int num) {
return nsetTransform(mtx, num);
}
/**
* <p>
* Set shader uniform parameter for draw primitive.
* </p>
*
* @param handle
* handle Uniform.
* @param buffer
* direct ByteBuffer containing uniform data.
* @param num
* Number of elements.
*/
public void setUniform(int handle, ByteBuffer buffer, int num) {
nsetUniform(handle, buffer, num);
}
/**
* <p>
* Set shader uniform parameter for draw primitive. Convenience method.
* </p>
*
* @param handle
* handle Uniform.
* @param value
* array containing containing uniform data.
* @param num
* Number of elements.
*/
public void setUniform(int handle, float[] value, int num) {
nsetUniform(handle, value, num);
}
/**
* <p>
* Set shader uniform parameter for draw primitive.
* </p>
*
* @param handle
* handle Uniform.
* @param value
* float value
* @param num
* Number of elements.
*/
public void setUniform(int handle, float value, int num) {
nsetUniform(handle, value, num);
}
/**
* <p>
* Set index buffer for draw primitive.
* </p>
*
* @param handle
* Index buffer.
* @param firstIndex
* First index to render.
* @param numIndices
* Number of indices to render.
*/
public void setIndexBuffer(IndexBuffer handle, long firstIndex, long numIndices) {
nsetIndexBuffer(handle, firstIndex, numIndices);
}
/**
* <p>
* Set index buffer for draw primitive.
* </p>
*
* @param handle
* Index buffer.
* @param firstIndex
* First index to render.
* @param numIndices
* Number of indices to render.
*/
public void setIndexBuffer(DynamicIndexBuffer handle, long firstIndex, long numIndices) {
nsetIndexBuffer(handle, firstIndex, numIndices);
}
/**
* <p>
* Set index buffer for draw primitive.
* </p>
*
* @param handle
* Index buffer.
*/
public void setIndexBuffer(TransientIndexBuffer tib) {
nsetIndexBuffer(tib);
}
/**
* <p>
* Set index buffer for draw primitive.
* </p>
*
* @param handle
* Index buffer.
* @param firstIndex
* First index to render.
* @param numIndices
* Number of indices to render.
*/
public void setIndexBuffer(TransientIndexBuffer tib, long firstIndex, long numIndices) {
nsetIndexBuffer(tib, firstIndex, numIndices);
}
/**
* <p>
* Set vertex buffer for draw primitive.
* </p>
*
* @param buffer
* Vertex buffer.
*/
public void setVertexBuffer(VertexBuffer buffer) {
nsetVertexBuffer(buffer);
}
/**
* <p>
* Set vertex buffer for draw primitive.
* </p>
*
* @param handle
* Vertex buffer.
* @param startVertex
* First vertex to render.
* @param numVertices
* Number of vertices to render.
*/
public void setVertexBuffer(VertexBuffer handle, long startVertex, long numVertices) {
nsetVertexBuffer(handle, startVertex, numVertices);
}
/**
* <p>
* Set vertex buffer for draw primitive.
* </p>
*
* @param handle
* Vertex buffer.
* @param numVertices
* Number of vertices to render.
*/
public void setVertexBuffer(DynamicVertexBuffer handle, long numVertices) {
nsetVertexBuffer(handle, numVertices);
}
/**
* <p>
* Set vertex buffer for draw primitive.
* </p>
*
* @param handle
* Vertex buffer.
*/
public void setVertexBuffer(TransientVertexBuffer tvb) {
nsetVertexBuffer(tvb);
}
/**
* <p>
* Set vertex buffer for draw primitive.
* </p>
*
* @param handle
* Vertex buffer.
* @param startVertex
* First vertex to render.
* @param numVertices
* Number of vertices to render.
*/
public void setVertexBuffer(TransientVertexBuffer tvb, long startVertex, long numVertices) {
nsetVertexBuffer(tvb, startVertex, numVertices);
}
/**
* <p>
* Set instance data buffer for draw primitive.
* </p>
*
* @param idb
* instance buffer
* @param num
* number of instances
*/
public void setInstanceDataBuffer(InstanceDataBuffer idb, int num) {
nsetInstanceDataBuffer(idb, num);
}
/**
* <p>
* Set program for draw primitive.
* </p>
*
* @param handle
* ProgramHandle ind
*/
public void setProgram(int handle) {
nsetProgram(handle);
}
/**
* <p>
* Set texture stage for draw primitive.
* </p>
*
* @param stage
* Texture unit.
* @param sampler
* Program sampler.
* @param handle
* Texture handle.
* @param flags
* Texture sampling mode. Default value UINT32_MAX uses texture
* sampling settings from the texture.
*
* <ul>
* <li>BGFX_TEXTURE_[U/V/W]_[MIRROR/CLAMP] - Mirror or clamp to
* edge wrap mode.</li>
* <li>BGFX_TEXTURE_[MIN/MAG/MIP]_[POINT/ANISOTROPIC] - Point or
* anisotropic sampling.</li>
* </ul>
*/
public void setTexture(int stage, int sampler, int handle, long flags) {
nsetTexture((short) stage, sampler, handle, flags);
}
/**
* <p>
* Set texture stage for draw primitive.
* </p>
*
* @param stage
* Texture unit.
* @param sampler
* Program sampler.
* @param handle
* Frame buffer handle.
* @param attachment
* Attachment index.
* @param flags
* Texture sampling mode. Default value UINT32_MAX uses texture
* sampling settings from the texture.
*
* <ul>
* <li>BGFX_TEXTURE_[U/V/W]_[MIRROR/CLAMP] - Mirror or clamp to
* edge wrap mode.</li>
* <li>BGFX_TEXTURE_[MIN/MAG/MIP]_[POINT/ANISOTROPIC] - Point or
* anisotropic sampling.</li>
* </ul>
*/
public void setTexture(short stage, int sampler, int handle, short attachment, long flags) {
nsetTexture(stage, sampler, handle, attachment, flags);
}
/**
* <p>
* Submit primitive for rendering.
* </p>
*
* @param id
* View id.
* @return Number of draw calls.
*/
public long submit(int id) {
return submit(id, 0);
}
/**
* <p>
* Submit primitive for rendering.
* </p>
*
* @param id
* View id.
* @param depth
* Depth for sorting.
*
* @return Number of draw calls.
*/
public long submit(int id, int depth) {
return nsubmit((short) id, (short) depth);
}
/**
* <p>
* Discard all previously set state for draw or compute call.
* </p>
*/
public void discard() {
ndiscard();
}
/**
* <p>
* Request screen shot.
* </p>
*
* @param filePath
* Will be passed to `bgfx::CallbackI::screenShot` callback.
*
* <p>
* <b>Note:</b> `bgfx::CallbackI::screenShot` must be
* implemented.
* </p>
*/
public void saveScreenShot(File filePath) {
nsaveScreenShot(filePath.getAbsolutePath());
}
private void freeTransientIndexPointers() {
int indexPointerSize = indexPointerList.size();
if (indexPointerSize == 0) {
return;
}
long[] pointers = new long[indexPointerSize];
for (int i = 0; i < indexPointerSize; i++) {
pointers[i] = indexPointerList.get(i);
}
indexPointerList.clear();
nfreeTransientIndexBuffers(pointers);
}
private void freeTransientVertexPointers() {
int vertexPointerSize = vertexPointerList.size();
if (vertexPointerSize == 0) {
return;
}
long[] pointers = new long[vertexPointerSize];
for (int i = 0; i < vertexPointerSize; i++) {
pointers[i] = vertexPointerList.get(i);
}
vertexPointerList.clear();
nfreeTransientVertexBuffers(pointers);
}
protected native void nfreeTransientIndexBuffers(long[] pointers);
protected native void nfreeTransientVertexBuffers(long[] pointers);
protected native void nvertexPack(float _input[], boolean _inputNormalized, Attrib _attr, VertexDecl _decl, long _data, long _index);
protected native void nvertexUnpack(float _output, Attrib _attr, VertexDecl _decl, long _data, long _index);
protected native void nvertexConvert(VertexDecl _destDecl, long _destData, VertexDecl _srcDecl, long _srcData, long _num);
protected native int nweldVertices(long _output, VertexDecl _decl, long _data, int _num, float _epsilon);
protected native void nimageSwizzleBgra8(long _width, long _height, long _pitch, long _src, long _dst);
protected native void nimageRgba8Downsample2x2(long _width, long _height, long _pitch, long _src, long _dst);
protected native int ngetRendererType();
protected native void ninit(int rendererType, int vendorId, int deviceId);
protected native void nshutdown();
protected native void nreset(long _width, long _height, long _flags);
protected native long nframe();
protected native Caps ngetCaps();
protected native ByteBuffer nalloc(long _size);
protected native ByteBuffer ncopy(long _data, long _size);
protected native ByteBuffer nmakeRef(long _data, long _size);
protected native void nsetDebug(long _debug);
protected native void ndbgTextClear(short _attr, boolean _small);
protected native void ndbgTextPrintf(int _x, int _y, short _attr, String _format);
protected native int ncreateIndexBuffer(ByteBuffer _mem);
protected native void ndestroyIndexBuffer(int _handle);
protected native int ncreateVertexBuffer(ByteBuffer _mem, VertexDecl _decl);
protected native void ndestroyVertexBuffer(int _handle);
protected native int ncreateDynamicIndexBuffer(long _num);
protected native int ncreateDynamicIndexBuffer(ByteBuffer _mem);
protected native void nupdateDynamicIndexBuffer(int _handle, ByteBuffer _mem);
protected native void ndestroyDynamicIndexBuffer(int _handle);
protected native int ncreateDynamicVertexBuffer(int _handle, VertexDecl _decl);
protected native int ncreateDynamicVertexBuffer(ByteBuffer _mem, VertexDecl _decl);
protected native void nupdateDynamicVertexBuffer(int _handle, ByteBuffer _mem);
protected native void ndestroyDynamicVertexBuffer(int _handle);
protected native boolean ncheckAvailTransientIndexBuffer(long _num);
protected native boolean ncheckAvailTransientVertexBuffer(long _num, VertexDecl _decl);
protected native boolean ncheckAvailInstanceDataBuffer(long _num, int _stride);
protected native boolean ncheckAvailTransientBuffers(long _numVertices, VertexDecl _decl, long _numIndices);
protected native TransientIndexBuffer nallocTransientIndexBuffer(long _num);
protected native TransientVertexBuffer nallocTransientVertexBuffer(long _num, VertexDecl _decl);
protected native InstanceDataBuffer nallocInstanceDataBuffer(long _num, int _stride);
protected native int ncreateShader(ByteBuffer _mem);
protected native int ngetShaderUniforms(int _handle, int _uniforms, int _max);
protected native void ndestroyShader(int _handle);
protected native int ncreateProgram(int _vsh, int _fsh, boolean _destroyShaders);
protected native void ndestroyProgram(int _handle);
protected native void ncalcTextureSize(TextureInfo _info, int _width, int _height, int _depth, short _numMips, TextureFormat _format);
protected native int ncreateTexture(ByteBuffer _mem, long _flags, short _skip, TextureInfo _info);
protected native int ncreateTexture2D(int _width, int _height, short _numMips, TextureFormat _format, long _flags, ByteBuffer _mem);
protected native int ncreateTexture3D(int _width, int _height, int _depth, short _numMips, TextureFormat _format, long _flags, ByteBuffer _mem);
protected native int ncreateTextureCube(int _size, short _numMips, TextureFormat _format, long _flags, ByteBuffer _mem);
protected native void nupdateTexture2D(int _handle, short _mip, int _x, int _y, int _width, int _height, ByteBuffer _mem, int _pitch);
protected native void nupdateTexture3D(int _handle, short _mip, int _x, int _y, int _z, int _width, int _height, int _depth, ByteBuffer _mem);
protected native void nupdateTextureCube(int _handle, short _side, short _mip, int _x, int _y, int _width, int _height, ByteBuffer _mem, int _pitch);
protected native void ndestroyTexture(int _handle);
protected native int ncreateFrameBuffer(long nativeWindowHandle, int _width, int _height, TextureFormat _format);
protected native int ncreateFrameBuffer(int _width, int _height, TextureFormat _format, long _textureFlags);
protected native int ncreateFrameBuffer(int _num, int[] _handles, boolean _destroyTextures);
protected native void ndestroyFrameBuffer(int _handle);
protected native int ncreateUniform(String _name, int _type, int _num);
protected native void ndestroyUniform(int _handle);
protected native void nsetViewName(short _id, String _name);
protected native void nsetViewRect(short _id, int _x, int _y, int _width, int _height);
protected native void nsetViewRectMask(long _viewMask, int _x, int _y, int _width, int _height);
protected native void nsetViewScissor(short _id, int _x, int _y, int _width, int _height);
protected native void nsetViewScissorMask(long _viewMask, int _x, int _y, int _width, int _height);
protected native void nsetViewClear(short _id, short _flags, long _rgba, float _depth, short _stencil);
protected native void nsetViewClearMask(long _viewMask, short _flags, long _rgba, float _depth, short _stencil);
protected native void nsetViewSeq(short _id, boolean _enabled);
protected native void nsetViewSeqMask(long _viewMask, boolean _enabled);
protected native void nsetViewFrameBuffer(short _id, int _handle);
protected native void nsetViewFrameBufferMask(long _viewMask, int _handle);
protected native void nsetViewTransform(short _id, float[] _view, float[] _proj);
protected native void nsetViewTransformMask(long _viewMask, long _view, long _proj, short _otherxff);
protected native void nsetMarker(String _marker);
protected native void nsetState(long _state, long _rgba);
protected native void nsetStencil(long _fstencil, long _bstencil);
protected native int nsetScissor(int _x, int _y, int _width, int _height);
protected native void nsetScissor(int _cache);
protected native long nsetTransform(float[] _mtx, int _num);
protected native void nsetUniform(int _handle, ByteBuffer _value, int _num);
protected native void nsetUniform(int _handle, float _value, int _num);
protected native void nsetUniform(int _handle, float[] _value, int _num);
protected native void nsetIndexBuffer(IndexBuffer _handle, long _firstIndex, long _numIndices);
protected native void nsetIndexBuffer(DynamicIndexBuffer _handle, long _firstIndex, long _numIndices);
protected native void nsetIndexBuffer(TransientIndexBuffer _tib);
protected native void nsetIndexBuffer(TransientIndexBuffer _tib, long _firstIndex, long _numIndices);
protected native void nsetDynamicVertexBuffer(int _handle);
protected native void nsetVertexBuffer(VertexBuffer _handle);
protected native void nsetVertexBuffer(VertexBuffer _handle, long _startVertex, long _numVertices);
protected native void nsetVertexBuffer(DynamicVertexBuffer _handle, long _numVertices);
protected native void nsetVertexBuffer(TransientVertexBuffer _tvb);
protected native void nsetVertexBuffer(TransientVertexBuffer _tvb, long _startVertex, long _numVertices);
protected native void nsetInstanceDataBuffer(InstanceDataBuffer _idb, int _num);
protected native void nsetProgram(int _handle);
protected native void nsetTexture(short _stage, int _sampler, int _handle, long _flags);
protected native void nsetTexture(short _stage, int _sampler, int _handle, short _attachment, long _flags);
protected native long nsubmit(short _id, short depth);
protected native long nsubmitMask(long _viewMask, int _depth);
protected native void ndiscard();
protected native void nsaveScreenShot(String _filePath);
protected static long blendFunc(long src, long dst) {
return ndoBlendFunc(src, dst, src, dst);
}
protected static long blendFuncSeparate(long srcRGB, long dstRGB, long srcA, long dstA) {
return ndoBlendFunc(srcRGB, dstRGB, srcA, dstA);
}
protected native static long ndoBlendFunc(long srcRGB, long dstRGB, long srcA, long dstA);
/// BGFX States
public static final long BGFX_PCI_ID_NONE = 0x0000000000000000L;
public static final long BGFX_PCI_ID_SOFTWARE_RASTERIZER = 0x0000000000000001L;
public static final long BGFX_PCI_ID_AMD = 0x0000000000001002L;
public static final long BGFX_PCI_ID_INTEL = 0x0000000000008086L;
public static final long BGFX_PCI_ID_NVIDIA = 0x00000000000010deL;
public static final long BGFX_STATE_RGB_WRITE = 0x0000000000000001L;
public static final long BGFX_STATE_ALPHA_WRITE = 0x0000000000000002L;
public static final long BGFX_STATE_DEPTH_WRITE = 0x0000000000000004L;
public static final long BGFX_STATE_DEPTH_TEST_LESS = 0x0000000000000010L;
public static final long BGFX_STATE_DEPTH_TEST_LEQUAL = 0x0000000000000020L;
public static final long BGFX_STATE_DEPTH_TEST_EQUAL = 0x0000000000000030L;
public static final long BGFX_STATE_DEPTH_TEST_GEQUAL = 0x0000000000000040L;
public static final long BGFX_STATE_DEPTH_TEST_GREATER = 0x0000000000000050L;
public static final long BGFX_STATE_DEPTH_TEST_NOTEQUAL = 0x0000000000000060L;
public static final long BGFX_STATE_DEPTH_TEST_NEVER = 0x0000000000000070L;
public static final long BGFX_STATE_DEPTH_TEST_ALWAYS = 0x0000000000000080L;
public static final long BGFX_STATE_DEPTH_TEST_SHIFT = 4L;
public static final long BGFX_STATE_DEPTH_TEST_MASK = 0x00000000000000f0L;
public static final long BGFX_STATE_BLEND_ZERO = 0x0000000000001000L;
public static final long BGFX_STATE_BLEND_ONE = 0x0000000000002000L;
public static final long BGFX_STATE_BLEND_SRC_COLOR = 0x0000000000003000L;
public static final long BGFX_STATE_BLEND_INV_SRC_COLOR = 0x0000000000004000L;
public static final long BGFX_STATE_BLEND_SRC_ALPHA = 0x0000000000005000L;
public static final long BGFX_STATE_BLEND_INV_SRC_ALPHA = 0x0000000000006000L;
public static final long BGFX_STATE_BLEND_DST_ALPHA = 0x0000000000007000L;
public static final long BGFX_STATE_BLEND_INV_DST_ALPHA = 0x0000000000008000L;
public static final long BGFX_STATE_BLEND_DST_COLOR = 0x0000000000009000L;
public static final long BGFX_STATE_BLEND_INV_DST_COLOR = 0x000000000000a000L;
public static final long BGFX_STATE_BLEND_SRC_ALPHA_SAT = 0x000000000000b000L;
public static final long BGFX_STATE_BLEND_FACTOR = 0x000000000000c000L;
public static final long BGFX_STATE_BLEND_INV_FACTOR = 0x000000000000d000L;
public static final long BGFX_STATE_BLEND_SHIFT = 12L;
public static final long BGFX_STATE_BLEND_MASK = 0x000000000ffff000L;
public static final long BGFX_STATE_BLEND_EQUATIOnSUB = 0x0000000010000000L;
public static final long BGFX_STATE_BLEND_EQUATIOnREVSUB = 0x0000000020000000L;
public static final long BGFX_STATE_BLEND_EQUATIOnMIN = 0x0000000030000000L;
public static final long BGFX_STATE_BLEND_EQUATIOnMAX = 0x0000000040000000L;
public static final long BGFX_STATE_BLEND_EQUATIOnSHIFT = 28L;
public static final long BGFX_STATE_BLEND_EQUATIOnMASK = 0x00000003f0000000L;
public static final long BGFX_STATE_BLEND_INDEPENDENT = 0x0000000400000000L;
public static final long BGFX_STATE_CULL_CW = 0x0000001000000000L;
public static final long BGFX_STATE_CULL_CCW = 0x0000002000000000L;
public static final long BGFX_STATE_CULL_SHIFT = 36L;
public static final long BGFX_STATE_CULL_MASK = 0x0000003000000000L;
public static final long BGFX_STATE_ALPHA_REF_SHIFT = 40L;
public static final long BGFX_STATE_ALPHA_REF_MASK = 0x0000ff0000000000L;
public static final long BGFX_STATE_PT_TRISTRIP = 0x0001000000000000L;
public static final long BGFX_STATE_PT_LINES = 0x0002000000000000L;
public static final long BGFX_STATE_PT_POINTS = 0x0003000000000000L;
public static final long BGFX_STATE_PT_SHIFT = 48L;
public static final long BGFX_STATE_PT_MASK = 0x0003000000000000L;
public static final long BGFX_STATE_POINT_SIZE_SHIFT = 52L;
public static final long BGFX_STATE_POINT_SIZE_MASK = 0x0ff0000000000000L;
public static final long BGFX_STATE_MSAA = 0x1000000000000000L;
public static final long BGFX_STATE_RESERVED_MASK = 0xe000000000000000L;
public static final long BGFX_STATE_NONE = 0x0000000000000000L;
public static final long BGFX_STATE_MASK = 0xffffffffffffffffL;
public static final long BGFX_STATE_DEFAULT = 0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_DEPTH_WRITE | BGFX_STATE_MSAA;
// public static final long BGFX_STATE_ALPHA_REF(_ref; (
// (uint64_t(_ref;<<BGFX_STATE_ALPHA_REF_SHIFT;&BGFX_STATE_ALPHA_REF_MASK;
// public static final long BGFX_STATE_POINT_SIZE(_size; (
// (uint64_t(_size;<<BGFX_STATE_POINT_SIZE_SHIFT;&BGFX_STATE_POINT_SIZE_MASK;
///
// public static final long BGFX_STATE_BLEND_FUNC_SEPARATE(_srcRGB, _dstRGB,
/// _srcA, _dstA; (0 \
// | ( (uint64_t(_srcRGB;|(uint64_t(_dstRGB;<<4; ; ; \
// | ( (uint64_t(_srcA ;|(uint64_t(_dstA ;<<4; ;<<8; \
// ;
// public static final long BGFX_STATE_BLEND_EQUATIOnSEPARATE(_rgb, _a;
// (uint64_t(_rgb;|(uint64_t(_a;<<3; ;
///
// public static final long BGFX_STATE_BLEND_FUNC(_src, _dst;
/// BGFX_STATE_BLEND_FUNC_SEPARATE(_src, _dst, _src, _dst;
// public static final long BGFX_STATE_BLEND_EQUATION(_equation;
/// BGFX_STATE_BLEND_EQUATIOnSEPARATE(_equation, _equation;
public static final long BGFX_STATE_BLEND_ADD = blendFunc(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE);
public static final long BGFX_STATE_BLEND_ALPHA = blendFunc(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA);
public static final long BGFX_STATE_BLEND_DARKEN = blendFunc(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE);
public static final long BGFX_STATE_BLEND_LIGHTEN = blendFunc(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_ONE);
public static final long BGFX_STATE_BLEND_MULTIPLY = blendFunc(BGFX_STATE_BLEND_DST_COLOR, BGFX_STATE_BLEND_ZERO);
public static final long BGFX_STATE_BLEND_NORMAL = blendFunc(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_ALPHA);
public static final long BGFX_STATE_BLEND_SCREEN = blendFunc(BGFX_STATE_BLEND_ONE, BGFX_STATE_BLEND_INV_SRC_COLOR);
public static final long BGFX_STATE_BLEND_LINEAR_BURN = blendFunc(BGFX_STATE_BLEND_DST_COLOR, BGFX_STATE_BLEND_INV_DST_COLOR);
///
// public static final long BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst; (0 \
// | ( uint32_t( (_src;>>BGFX_STATE_BLEND_SHIFT; \
// | ( uint32_t( (_dst;>>BGFX_STATE_BLEND_SHIFT;<<4; ; \
// ;
// public static final long BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst,
// _equation; (0 \
// | BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst; \
// | ( uint32_t( (_equation;>>BGFX_STATE_BLEND_EQUATIOnSHIFT;<<8; \
// ;
// public static final long BGFX_STATE_BLEND_FUNC_RT_1(_src, _dst;
// (BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst;<< 0;
// public static final long BGFX_STATE_BLEND_FUNC_RT_2(_src, _dst;
// (BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst;<<11;
// public static final long BGFX_STATE_BLEND_FUNC_RT_3(_src, _dst;
// (BGFX_STATE_BLEND_FUNC_RT_x(_src, _dst;<<22;
// public static final long BGFX_STATE_BLEND_FUNC_RT_1E(_src, _dst,
// _equation; (BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation;<< 0;
// public static final long BGFX_STATE_BLEND_FUNC_RT_2E(_src, _dst,
// _equation; (BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation;<<11;
// public static final long BGFX_STATE_BLEND_FUNC_RT_3E(_src, _dst,
// _equation; (BGFX_STATE_BLEND_FUNC_RT_xE(_src, _dst, _equation;<<22;
///
public static final long BGFX_STENCIL_FUNC_REF_SHIFT = 0L;
public static final long BGFX_STENCIL_FUNC_REF_MASK = 0x000000ffL;
public static final long BGFX_STENCIL_FUNC_RMASK_SHIFT = 8L;
public static final long BGFX_STENCIL_FUNC_RMASK_MASK = 0x0000ff00L;
public static final long BGFX_STENCIL_TEST_LESS = 0x00010000L;
public static final long BGFX_STENCIL_TEST_LEQUAL = 0x00020000L;
public static final long BGFX_STENCIL_TEST_EQUAL = 0x00030000L;
public static final long BGFX_STENCIL_TEST_GEQUAL = 0x00040000L;
public static final long BGFX_STENCIL_TEST_GREATER = 0x00050000L;
public static final long BGFX_STENCIL_TEST_NOTEQUAL = 0x00060000L;
public static final long BGFX_STENCIL_TEST_NEVER = 0x00070000L;
public static final long BGFX_STENCIL_TEST_ALWAYS = 0x00080000L;
public static final long BGFX_STENCIL_TEST_SHIFT = 16L;
public static final long BGFX_STENCIL_TEST_MASK = 0x000f0000L;
public static final long BGFX_STENCIL_OP_FAIL_S_ZERO = 0x00000000L;
public static final long BGFX_STENCIL_OP_FAIL_S_KEEP = 0x00100000L;
public static final long BGFX_STENCIL_OP_FAIL_S_REPLACE = 0x00200000L;
public static final long BGFX_STENCIL_OP_FAIL_S_INCR = 0x00300000L;
public static final long BGFX_STENCIL_OP_FAIL_S_INCRSAT = 0x00400000L;
public static final long BGFX_STENCIL_OP_FAIL_S_DECR = 0x00500000L;
public static final long BGFX_STENCIL_OP_FAIL_S_DECRSAT = 0x00600000L;
public static final long BGFX_STENCIL_OP_FAIL_S_INVERT = 0x00700000L;
public static final long BGFX_STENCIL_OP_FAIL_S_SHIFT = 20L;
public static final long BGFX_STENCIL_OP_FAIL_S_MASK = 0x00f00000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_ZERO = 0x00000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_KEEP = 0x01000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_REPLACE = 0x02000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_INCR = 0x03000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_INCRSAT = 0x04000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_DECR = 0x05000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_DECRSAT = 0x06000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_INVERT = 0x07000000L;
public static final long BGFX_STENCIL_OP_FAIL_Z_SHIFT = 24L;
public static final long BGFX_STENCIL_OP_FAIL_Z_MASK = 0x0f000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_ZERO = 0x00000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_KEEP = 0x10000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_REPLACE = 0x20000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_INCR = 0x30000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_INCRSAT = 0x40000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_DECR = 0x50000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_DECRSAT = 0x60000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_INVERT = 0x70000000L;
public static final long BGFX_STENCIL_OP_PASS_Z_SHIFT = 28L;
public static final long BGFX_STENCIL_OP_PASS_Z_MASK = 0xf0000000L;
public static final long BGFX_STENCIL_NONE = 0x00000000L;
public static final long BGFX_STENCIL_MASK = 0xffffffffL;
public static final long BGFX_STENCIL_DEFAULT = 0x00000000L;
// public static final long BGFX_STENCIL_FUNC_REF(_ref; (
// (uint32_t(_ref;<<BGFX_STENCIL_FUNC_REF_SHIFT;&BGFX_STENCIL_FUNC_REF_MASK;
// public static final long BGFX_STENCIL_FUNC_RMASK(_mask; (
// (uint32_t(_mask;<<BGFX_STENCIL_FUNC_RMASK_SHIFT;&BGFX_STENCIL_FUNC_RMASK_MASK;
///
public static final long BGFX_CLEAR_NONE = 0x00L;
public static final long BGFX_CLEAR_COLOR_BIT = 0x01L;
public static final long BGFX_CLEAR_DEPTH_BIT = 0x02L;
public static final long BGFX_CLEAR_STENCIL_BIT = 0x04L;
///
public static final long BGFX_DEBUG_NONE = 0x00000000L;
public static final long BGFX_DEBUG_WIREFRAME = 0x00000001L;
public static final long BGFX_DEBUG_IFH = 0x00000002L;
public static final long BGFX_DEBUG_STATS = 0x00000004L;
public static final long BGFX_DEBUG_TEXT = 0x00000008L;
///
public static final long BGFX_TEXTURE_NONE = 0x00000000L;
public static final long BGFX_TEXTURE_U_MIRROR = 0x00000001L;
public static final long BGFX_TEXTURE_U_CLAMP = 0x00000002L;
public static final long BGFX_TEXTURE_U_SHIFT = 0L;
public static final long BGFX_TEXTURE_U_MASK = 0x00000003L;
public static final long BGFX_TEXTURE_V_MIRROR = 0x00000004L;
public static final long BGFX_TEXTURE_V_CLAMP = 0x00000008L;
public static final long BGFX_TEXTURE_V_SHIFT = 2L;
public static final long BGFX_TEXTURE_V_MASK = 0x0000000cL;
public static final long BGFX_TEXTURE_W_MIRROR = 0x00000010L;
public static final long BGFX_TEXTURE_W_CLAMP = 0x00000020L;
public static final long BGFX_TEXTURE_W_SHIFT = 4L;
public static final long BGFX_TEXTURE_W_MASK = 0x00000030L;
public static final long BGFX_TEXTURE_MInPOINT = 0x00000040L;
public static final long BGFX_TEXTURE_MInANISOTROPIC = 0x00000080L;
public static final long BGFX_TEXTURE_MInSHIFT = 6L;
public static final long BGFX_TEXTURE_MInMASK = 0x000000c0L;
public static final long BGFX_TEXTURE_MAG_POINT = 0x00000100L;
public static final long BGFX_TEXTURE_MAG_ANISOTROPIC = 0x00000200L;
public static final long BGFX_TEXTURE_MAG_SHIFT = 8L;
public static final long BGFX_TEXTURE_MAG_MASK = 0x00000300L;
public static final long BGFX_TEXTURE_MIP_POINT = 0x00000400L;
public static final long BGFX_TEXTURE_MIP_SHIFT = 10L;
public static final long BGFX_TEXTURE_MIP_MASK = 0x00000400L;
public static final long BGFX_TEXTURE_RT = 0x00001000L;
public static final long BGFX_TEXTURE_RT_MSAA_X2 = 0x00002000L;
public static final long BGFX_TEXTURE_RT_MSAA_X4 = 0x00003000L;
public static final long BGFX_TEXTURE_RT_MSAA_X8 = 0x00004000L;
public static final long BGFX_TEXTURE_RT_MSAA_X16 = 0x00005000L;
public static final long BGFX_TEXTURE_RT_MSAA_SHIFT = 12L;
public static final long BGFX_TEXTURE_RT_MSAA_MASK = 0x00007000L;
public static final long BGFX_TEXTURE_RT_BUFFER_ONLY = 0x00008000L;
public static final long BGFX_TEXTURE_RT_MASK = 0x0000f000L;
public static final long BGFX_TEXTURE_COMPARE_LESS = 0x00010000L;
public static final long BGFX_TEXTURE_COMPARE_LEQUAL = 0x00020000L;
public static final long BGFX_TEXTURE_COMPARE_EQUAL = 0x00030000L;
public static final long BGFX_TEXTURE_COMPARE_GEQUAL = 0x00040000L;
public static final long BGFX_TEXTURE_COMPARE_GREATER = 0x00050000L;
public static final long BGFX_TEXTURE_COMPARE_NOTEQUAL = 0x00060000L;
public static final long BGFX_TEXTURE_COMPARE_NEVER = 0x00070000L;
public static final long BGFX_TEXTURE_COMPARE_ALWAYS = 0x00080000L;
public static final long BGFX_TEXTURE_COMPARE_SHIFT = 16L;
public static final long BGFX_TEXTURE_COMPARE_MASK = 0x000f0000L;
public static final long BGFX_TEXTURE_RESERVED_SHIFT = 24L;
public static final long BGFX_TEXTURE_RESERVED_MASK = 0xff000000L;
public static final long BGFX_TEXTURE_SAMPLER_BITS_MASK = 0 | BGFX_TEXTURE_U_MASK | BGFX_TEXTURE_V_MASK | BGFX_TEXTURE_W_MASK | BGFX_TEXTURE_MInMASK | BGFX_TEXTURE_MAG_MASK | BGFX_TEXTURE_MIP_MASK | BGFX_TEXTURE_COMPARE_MASK;
///
public static final long BGFX_RESET_NONE = 0x00000000L;
public static final long BGFX_RESET_FULLSCREEN = 0x00000001L;
public static final long BGFX_RESET_FULLSCREEnSHIFT = 0L;
public static final long BGFX_RESET_FULLSCREEnMASK = 0x00000001L;
public static final long BGFX_RESET_MSAA_X2 = 0x00000010L;
public static final long BGFX_RESET_MSAA_X4 = 0x00000020L;
public static final long BGFX_RESET_MSAA_X8 = 0x00000030L;
public static final long BGFX_RESET_MSAA_X16 = 0x00000040L;
public static final long BGFX_RESET_MSAA_SHIFT = 4L;
public static final long BGFX_RESET_MSAA_MASK = 0x00000070L;
public static final long BGFX_RESET_VSYNC = 0x00000080L;
public static final long BGFX_RESET_CAPTURE = 0x00000100L;
///
public static final long BGFX_CAPS_TEXTURE_FORMAT_BC1 = 0x0000000000000001L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_BC2 = 0x0000000000000002L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_BC3 = 0x0000000000000004L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_BC4 = 0x0000000000000008L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_BC5 = 0x0000000000000010L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_ETC1 = 0x0000000000000020L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_ETC2 = 0x0000000000000040L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_ETC2A = 0x0000000000000080L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_ETC2A1 = 0x0000000000000100L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC12 = 0x0000000000000200L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC14 = 0x0000000000000400L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC14A = 0x0000000000000800L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC12A = 0x0000000000001000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC22 = 0x0000000000002000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_PTC24 = 0x0000000000004000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D16 = 0x0000000000008000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D24 = 0x0000000000010000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D24S8 = 0x0000000000020000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D32 = 0x0000000000040000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D16F = 0x0000000000080000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D24F = 0x0000000000100000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D32F = 0x0000000000200000L;
public static final long BGFX_CAPS_TEXTURE_FORMAT_D0S8 = 0x0000000000400000L;
public static final long BGFX_CAPS_TEXTURE_COMPARE_LEQUAL = 0x0000000001000000L;
public static final long BGFX_CAPS_TEXTURE_COMPARE_ALL = 0x0000000003000000L;
public static final long BGFX_CAPS_TEXTURE_3D = 0x0000000004000000L;
public static final long BGFX_CAPS_VERTEX_ATTRIB_HALF = 0x0000000008000000L;
public static final long BGFX_CAPS_INSTANCING = 0x0000000010000000L;
public static final long BGFX_CAPS_RENDERER_MULTITHREADED = 0x0000000020000000L;
public static final long BGFX_CAPS_FRAGMENT_DEPTH = 0x0000000040000000L;
public static final long BGFX_CAPS_BLEND_INDEPENDENT = 0x0000000080000000L;
public static final long BGFX_CAPS_TEXTURE_DEPTH_MASK = 0 | BGFX_CAPS_TEXTURE_FORMAT_D16 | BGFX_CAPS_TEXTURE_FORMAT_D24 | BGFX_CAPS_TEXTURE_FORMAT_D24S8 | BGFX_CAPS_TEXTURE_FORMAT_D32 | BGFX_CAPS_TEXTURE_FORMAT_D16F | BGFX_CAPS_TEXTURE_FORMAT_D24F | BGFX_CAPS_TEXTURE_FORMAT_D32F | BGFX_CAPS_TEXTURE_FORMAT_D0S8;
}
|
package com.esc.fms.service.base.impl;
import com.esc.fms.dao.FileTypeMapper;
import com.esc.fms.entity.FileType;
import com.esc.fms.service.base.FileTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by tangjie on 2017/4/8.
*/
@Service("fileTypeService")
public class FileTypeServiceImpl implements FileTypeService {
@Autowired
private FileTypeMapper fileTypeMapper;
public List<FileType> getAllFileType() {
return fileTypeMapper.getALLFileType();
}
public int getRecordCount() {
return fileTypeMapper.getRecordCount();
}
public List<FileType> getFileTypePageList(int offset, int pageSize) {
return fileTypeMapper.getFileTypePageList(offset,pageSize);
}
public FileType getFileTypeByID(Integer fileTypeID) {
return fileTypeMapper.selectByPrimaryKey(fileTypeID);
}
public int addFileType(FileType fileType) {
return fileTypeMapper.insert(fileType);
}
public int updateByFileTypeID(FileType record) {
return fileTypeMapper.updateByPrimaryKey(record);
}
public boolean delFileTypes(List<Integer> fileTypeIDs) {
for(Integer fileTypeID : fileTypeIDs){
fileTypeMapper.disableFileType(fileTypeID);
}
return true;
}
}
|
package com.example.android.inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventoryapp.data.InventoryDbHelper;
import com.example.android.inventoryapp.data.StorageContract.ProductsEntry;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
ProductCursorAdapter cursorAdapter;
private static final int URL_LOADER = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup FAB to open ProductActivity
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProductActivity.class);
startActivity(intent);
}
});
ListView productList = findViewById(R.id.listView);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
productList.setEmptyView(emptyView);
cursorAdapter = new ProductCursorAdapter(this, null);
productList.setAdapter(cursorAdapter);
getLoaderManager().initLoader(URL_LOADER, null, this);
productList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Uri uri = ContentUris.withAppendedId(ProductsEntry.CONTENT_URI, id);
Intent intent = new Intent(MainActivity.this, ProductActivity.class);
intent.setData(uri);
startActivity(intent);
}
});
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
ProductsEntry._ID,
ProductsEntry.COLUMN_PRODUCT_NAME,
ProductsEntry.COLUMN_PRICE,
ProductsEntry.COLUMN_QUANTITY
};
return new CursorLoader(this, ProductsEntry.CONTENT_URI,
projection, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
cursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
|
package com.tencent.mm.plugin.sns.ui.previewimageview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build.VERSION;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import com.tencent.mm.plugin.sns.i$d;
import com.tencent.mm.plugin.sns.i.f;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class DynamicGridView extends WrappingGridView {
private int cF = -1;
boolean iDm = false;
private List<Long> idList = new ArrayList();
private int if = 0;
private BitmapDrawable olM;
private Rect olN;
private Rect olO;
private Rect olP;
private int olQ = 0;
private int olR = 0;
private int olS = -1;
private int olT = -1;
private int olU = -1;
private int olV = -1;
private int olW;
private long olX = -1;
private boolean olY = false;
private boolean olZ;
private int oma = 0;
private boolean omb = false;
private List<ObjectAnimator> omc = new LinkedList();
boolean omd;
boolean ome;
boolean omf = true;
private boolean omg = true;
private OnScrollListener omh;
private f omi;
private e omj;
private g omk;
private OnItemClickListener oml;
private OnItemClickListener omm = new 1(this);
private boolean omn;
private Stack<a> omo;
private a omp;
private h omq;
private View omr;
d oms = new d(this, (byte) 0);
int omt = -1;
float omu;
float omv;
private float omw;
private float omx;
private OnScrollListener omy = new 2(this);
private static class a {
List<Pair<Integer, Integer>> omF = new Stack();
a() {
}
public final void dI(int i, int i2) {
this.omF.add(new Pair(Integer.valueOf(i), Integer.valueOf(i2)));
}
}
private class c implements j {
int yA;
int yz;
private class a implements OnPreDrawListener {
static final /* synthetic */ boolean $assertionsDisabled = (!DynamicGridView.class.desiredAssertionStatus());
private final int Sv;
private final int omH;
a(int i, int i2) {
this.omH = i;
this.Sv = i2;
}
public final boolean onPreDraw() {
DynamicGridView.this.getViewTreeObserver().removeOnPreDrawListener(this);
DynamicGridView.this.olQ = DynamicGridView.this.olQ + c.this.yA;
DynamicGridView.this.olR = DynamicGridView.this.olR + c.this.yz;
DynamicGridView.a(DynamicGridView.this, this.omH, this.Sv);
new StringBuilder("id ").append(DynamicGridView.this.fq(DynamicGridView.this.olX));
if (!(DynamicGridView.this.omr == null || DynamicGridView.this.omr == null)) {
if ($assertionsDisabled || DynamicGridView.this.omr != null) {
DynamicGridView.this.omr.setVisibility(0);
DynamicGridView.this.omr = DynamicGridView.this.fr(DynamicGridView.this.olX);
if (DynamicGridView.this.omr != null) {
if ($assertionsDisabled || DynamicGridView.this.omr != null) {
DynamicGridView.this.omr.setVisibility(4);
} else {
throw new AssertionError();
}
}
}
throw new AssertionError();
}
return true;
}
}
public c(int i, int i2) {
this.yz = i;
this.yA = i2;
}
public final void dJ(int i, int i2) {
DynamicGridView.this.getViewTreeObserver().addOnPreDrawListener(new a(i, i2));
}
}
public interface h {
}
static /* synthetic */ void a(DynamicGridView dynamicGridView, int i, int i2) {
Object obj = i2 > i ? 1 : null;
Collection linkedList = new LinkedList();
int min;
View fr;
if (obj != null) {
for (min = Math.min(i, i2); min < Math.max(i, i2); min++) {
fr = dynamicGridView.fr(dynamicGridView.xM(min));
if ((min + 1) % dynamicGridView.getColumnCount() == 0) {
linkedList.add(d(fr, (float) ((-fr.getWidth()) * (dynamicGridView.getColumnCount() - 1)), (float) fr.getHeight()));
} else {
linkedList.add(d(fr, (float) fr.getWidth(), 0.0f));
}
}
} else {
for (min = Math.max(i, i2); min > Math.min(i, i2); min--) {
fr = dynamicGridView.fr(dynamicGridView.xM(min));
if ((dynamicGridView.getColumnCount() + min) % dynamicGridView.getColumnCount() == 0) {
linkedList.add(d(fr, (float) (fr.getWidth() * (dynamicGridView.getColumnCount() - 1)), (float) (-fr.getHeight())));
} else {
linkedList.add(d(fr, (float) (-fr.getWidth()), 0.0f));
}
}
}
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(linkedList);
animatorSet.setDuration(300);
animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
animatorSet.addListener(new 10(dynamicGridView));
animatorSet.start();
}
static /* synthetic */ void b(DynamicGridView dynamicGridView) {
boolean z = (dynamicGridView.omd || dynamicGridView.ome) ? false : true;
dynamicGridView.setEnabled(z);
}
public DynamicGridView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init(context);
}
public DynamicGridView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
init(context);
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
this.omh = onScrollListener;
}
public void setOnDropListener(f fVar) {
this.omi = fVar;
}
public void setOnDragListener(e eVar) {
this.omj = eVar;
}
public final void xK(int i) {
if (this.omg) {
requestDisallowInterceptTouchEvent(true);
if (bES() && this.omf) {
bEO();
}
if (i != -1) {
this.iDm = xL(i);
if (this.iDm) {
this.olY = true;
}
}
}
}
public void setEditModeEnabled(boolean z) {
this.omg = z;
}
public void setOnEditModeChangeListener(g gVar) {
this.omk = gVar;
}
public void setWobbleInEditMode(boolean z) {
this.omf = z;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.oml = onItemClickListener;
super.setOnItemClickListener(this.omm);
}
public void setUndoSupportEnabled(boolean z) {
if (this.omn != z) {
if (z) {
this.omo = new Stack();
} else {
this.omo = null;
}
}
this.omn = z;
}
public void setOnSelectedItemBitmapCreationListener(h hVar) {
this.omq = hVar;
}
@TargetApi(11)
private void bEO() {
for (int i = 0; i < getChildCount(); i++) {
View childAt = getChildAt(i);
if (!(childAt == null || Boolean.TRUE == childAt.getTag(f.dgv_wobble_tag))) {
if (i % 2 == 0) {
cR(childAt);
} else {
cS(childAt);
}
childAt.setTag(f.dgv_wobble_tag, Boolean.valueOf(true));
}
}
}
@TargetApi(11)
final void iu(boolean z) {
for (Animator cancel : this.omc) {
cancel.cancel();
}
this.omc.clear();
for (int i = 0; i < getChildCount(); i++) {
View childAt = getChildAt(i);
if (childAt != null) {
if (z) {
childAt.setRotation(0.0f);
}
childAt.setTag(f.dgv_wobble_tag, Boolean.valueOf(false));
}
}
}
private void init(Context context) {
super.setOnScrollListener(this.omy);
this.oma = (int) ((context.getResources().getDisplayMetrics().density * 8.0f) + 0.5f);
this.olW = getResources().getDimensionPixelSize(i$d.dgv_overlap_if_switch_straight_line);
}
@TargetApi(11)
private void cR(View view) {
ObjectAnimator cT = cT(view);
cT.setFloatValues(new float[]{-2.0f, 2.0f});
cT.start();
this.omc.add(cT);
}
@TargetApi(11)
private void cS(View view) {
ObjectAnimator cT = cT(view);
cT.setFloatValues(new float[]{2.0f, -2.0f});
cT.start();
this.omc.add(cT);
}
@TargetApi(11)
private ObjectAnimator cT(View view) {
if (!bET()) {
view.setLayerType(1, null);
}
ObjectAnimator objectAnimator = new ObjectAnimator();
objectAnimator.setDuration(180);
objectAnimator.setRepeatMode(2);
objectAnimator.setRepeatCount(-1);
objectAnimator.setPropertyName("rotation");
objectAnimator.setTarget(view);
objectAnimator.addListener(new 3(this, view));
return objectAnimator;
}
private void dH(int i, int i2) {
getAdapterInterface().dG(i, i2);
}
private int getColumnCount() {
return getAdapterInterface().getColumnCount();
}
private d getAdapterInterface() {
return (d) getAdapter();
}
private void fp(long j) {
this.idList.clear();
int fq = fq(j);
int firstVisiblePosition = getFirstVisiblePosition();
while (firstVisiblePosition <= getLastVisiblePosition()) {
if (fq != firstVisiblePosition && getAdapterInterface().xG(firstVisiblePosition)) {
this.idList.add(Long.valueOf(xM(firstVisiblePosition)));
}
firstVisiblePosition++;
}
}
public final int fq(long j) {
View fr = fr(j);
if (fr == null) {
return -1;
}
return getPositionForView(fr);
}
public final View fr(long j) {
int firstVisiblePosition = getFirstVisiblePosition();
ListAdapter adapter = getAdapter();
for (int i = 0; i < getChildCount(); i++) {
View childAt = getChildAt(i);
if (adapter.getItemId(firstVisiblePosition + i) == j) {
return childAt;
}
}
return null;
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
boolean onInterceptTouchEvent = super.onInterceptTouchEvent(motionEvent);
new StringBuilder("onInterceptTouchEvent ").append(motionEvent.getAction()).append(" ").append(onInterceptTouchEvent);
return onInterceptTouchEvent;
}
public boolean onTouchEvent(MotionEvent motionEvent) {
int findPointerIndex = motionEvent.findPointerIndex(this.cF);
new StringBuilder("onTouchEvent ").append(motionEvent.getAction());
switch (motionEvent.getAction() & 255) {
case 0:
this.omu = motionEvent.getX();
this.omv = motionEvent.getY();
this.omt = f.a(this, motionEvent.getX(), motionEvent.getY());
new StringBuilder("onTouchEvent ").append(motionEvent.getAction()).append(",downPos ").append(this.omt);
if (!this.omd && this.omt >= 0) {
d dVar = this.oms;
dVar.removeMessages(1);
dVar.sendEmptyMessageDelayed(1, 300);
}
this.olU = -1;
this.olV = -1;
this.olS = (int) motionEvent.getX();
this.olT = (int) motionEvent.getY();
this.cF = motionEvent.getPointerId(0);
if (this.iDm && isEnabled()) {
layoutChildren();
xL(pointToPosition(this.olS, this.olT));
break;
} else if (!isEnabled()) {
return false;
}
break;
case 1:
bER();
if (this.omn && this.omp != null) {
a aVar = this.omp;
Collections.reverse(aVar.omF);
if (!aVar.omF.isEmpty()) {
this.omo.push(this.omp);
this.omp = new a();
break;
}
}
break;
case 2:
this.omu = motionEvent.getX();
this.omv = motionEvent.getY();
if (this.olY && this.cF != -1) {
if (this.olV == -1 && this.olU == -1) {
this.olU = (int) motionEvent.getY(findPointerIndex);
this.olV = (int) motionEvent.getX(findPointerIndex);
this.olS = this.olV;
this.olT = this.olU;
break;
}
this.omw = motionEvent.getRawX();
this.omx = motionEvent.getRawY();
this.olU = (int) motionEvent.getY(findPointerIndex);
this.olV = (int) motionEvent.getX(findPointerIndex);
int i = this.olV - this.olS;
this.olN.offsetTo((i + this.olP.left) + this.olR, ((this.olU - this.olT) + this.olP.top) + this.olQ);
if (this.olM != null) {
this.olM.setBounds(this.olN);
}
invalidate();
bEV();
this.olZ = false;
bEQ();
if (this.omj == null) {
return false;
}
Rect rect = new Rect(this.olN);
rect.offset(0, this.olN.height() >>> 1);
this.omj.k(rect);
return false;
}
break;
case 3:
bEU();
bER();
break;
case 6:
if (motionEvent.getPointerId((motionEvent.getAction() & 65280) >> 8) == this.cF) {
bER();
break;
}
break;
}
return super.onTouchEvent(motionEvent);
}
private boolean bEP() {
int fq = fq(this.olX);
if (fq == -1) {
return false;
}
this.omj.xJ(fq);
if (this.omr == null) {
return false;
}
j bVar;
int positionForView = getPositionForView(this.omr);
int childCount = getChildCount() - 1;
new StringBuilder("switch ").append(positionForView).append(",").append(childCount);
dH(positionForView, childCount);
if (this.omn) {
this.omp.dI(positionForView, childCount);
}
this.olT = this.olU;
this.olS = this.olV;
if (bES() && bET()) {
bVar = new b(this, 0, 0);
} else if (bET()) {
bVar = new i(this, 0, 0);
} else {
bVar = new c(0, 0);
}
fp(this.olX);
bVar.dJ(positionForView, childCount);
return true;
}
private boolean xL(int i) {
if (!getAdapterInterface().xF(i)) {
return false;
}
this.olQ = 0;
this.olR = 0;
View childAt = getChildAt(i - getFirstVisiblePosition());
if (childAt == null) {
return false;
}
this.olX = getAdapter().getItemId(i);
int width = childAt.getWidth();
int height = childAt.getHeight();
int top = childAt.getTop();
int left = childAt.getLeft();
Bitmap createBitmap = Bitmap.createBitmap(childAt.getWidth(), childAt.getHeight(), Config.ARGB_8888);
childAt.draw(new Canvas(createBitmap));
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), createBitmap);
this.olO = new Rect(left, top, left + width, top + height);
this.olN = new Rect(this.olO.left - ((int) (((float) width) * 0.05f)), this.olO.top - ((int) (((float) height) * 0.05f)), ((int) (((float) width) * 0.05f)) + this.olO.right, ((int) (((float) height) * 0.05f)) + this.olO.bottom);
this.olP = new Rect(this.olN);
bitmapDrawable.setBounds(this.olO);
this.olM = bitmapDrawable;
ObjectAnimator ofObject = ObjectAnimator.ofObject(this.olM, "bounds", new 4(this), new Object[]{this.olN});
ofObject.addUpdateListener(new 5(this));
ofObject.addListener(new 6(this));
ofObject.setDuration(10);
ofObject.start();
if (bES()) {
childAt.setVisibility(4);
}
fp(this.olX);
if (this.omj != null) {
this.omj.xI(i);
}
return true;
}
private void bEQ() {
boolean z = true;
Rect rect = this.olN;
int computeVerticalScrollOffset = computeVerticalScrollOffset();
int height = getHeight();
int computeVerticalScrollExtent = computeVerticalScrollExtent();
int computeVerticalScrollRange = computeVerticalScrollRange();
int i = rect.top;
int height2 = rect.height();
if (i <= 0 && computeVerticalScrollOffset > 0) {
smoothScrollBy(-this.oma, 0);
} else if (height2 + i < height || computeVerticalScrollOffset + computeVerticalScrollExtent >= computeVerticalScrollRange) {
z = false;
} else {
smoothScrollBy(this.oma, 0);
}
this.olZ = z;
}
public void setAdapter(ListAdapter listAdapter) {
super.setAdapter(listAdapter);
}
private void bER() {
this.oms.removeMessages(1);
final View fr = fr(this.olX);
Rect rect;
if (this.olN != null) {
rect = new Rect(this.olN);
rect.offset(0, this.olN.height() >>> 1);
} else {
rect = null;
}
if (this.omj != null && this.omj.l(rect) && bEP()) {
this.olM = null;
bEU();
if (this.omi != null) {
this.omi.bEN();
}
} else if (fr == null || !(this.olY || this.omb)) {
bEU();
} else {
this.olY = false;
this.omb = false;
this.olZ = false;
this.cF = -1;
this.olN.set(fr.getLeft(), fr.getTop(), fr.getRight(), fr.getBottom());
new StringBuilder("animating to ").append(this.olN);
if (VERSION.SDK_INT > 11) {
ObjectAnimator ofObject = ObjectAnimator.ofObject(this.olM, "bounds", new 7(this), new Object[]{this.olN});
ofObject.addUpdateListener(new AnimatorUpdateListener() {
public final void onAnimationUpdate(ValueAnimator valueAnimator) {
DynamicGridView.this.invalidate();
}
});
ofObject.addListener(new AnimatorListenerAdapter() {
public final void onAnimationStart(Animator animator) {
DynamicGridView.this.omd = true;
DynamicGridView.b(DynamicGridView.this);
}
public final void onAnimationEnd(Animator animator) {
DynamicGridView.this.omd = false;
DynamicGridView.b(DynamicGridView.this);
if (!(DynamicGridView.this.olM == null || DynamicGridView.this.omi == null)) {
DynamicGridView.this.omi.bEN();
}
DynamicGridView.this.cU(fr);
}
});
ofObject.setDuration(200);
ofObject.start();
} else {
this.olM.setBounds(this.olN);
invalidate();
cU(fr);
}
}
if (this.omj != null) {
this.omj.bEM();
}
}
private void cU(View view) {
this.idList.clear();
this.olX = -1;
view.setVisibility(0);
this.olM = null;
if (bES() && this.omf) {
if (this.iDm) {
iu(false);
bEO();
} else {
iu(true);
}
}
for (int i = 0; i < getLastVisiblePosition() - getFirstVisiblePosition(); i++) {
View childAt = getChildAt(i);
if (childAt != null) {
childAt.setVisibility(0);
}
}
invalidate();
}
static boolean bES() {
return VERSION.SDK_INT >= 11;
}
private static boolean bET() {
return VERSION.SDK_INT < 21;
}
private void bEU() {
View fr = fr(this.olX);
if (fr != null) {
if (this.olY) {
cU(fr);
}
this.olY = false;
this.olZ = false;
this.cF = -1;
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private void bEV() {
/*
r14 = this;
r0 = r14.olU;
r1 = r14.olT;
r6 = r0 - r1;
r0 = r14.olV;
r1 = r14.olS;
r7 = r0 - r1;
r0 = r14.olO;
r0 = r0.centerY();
r1 = r14.olQ;
r0 = r0 + r1;
r8 = r0 + r6;
r0 = r14.olO;
r0 = r0.centerX();
r1 = r14.olR;
r0 = r0 + r1;
r9 = r0 + r7;
r0 = r14.olX;
r0 = r14.fr(r0);
r14.omr = r0;
r0 = r14.omr;
if (r0 != 0) goto L_0x002f;
L_0x002e:
return;
L_0x002f:
r4 = 0;
r2 = 0;
r1 = 0;
r0 = r14.omr;
r10 = r14.cV(r0);
r0 = r14.idList;
r11 = r0.iterator();
L_0x003e:
r0 = r11.hasNext();
if (r0 == 0) goto L_0x0164;
L_0x0044:
r0 = r11.next();
r0 = (java.lang.Long) r0;
r12 = r0.longValue();
r5 = r14.fr(r12);
if (r5 == 0) goto L_0x01e1;
L_0x0054:
r3 = r14.cV(r5);
r0 = r3.y;
r12 = r10.y;
if (r0 >= r12) goto L_0x014f;
L_0x005e:
r0 = r3.x;
r12 = r10.x;
if (r0 <= r12) goto L_0x014f;
L_0x0064:
r0 = 1;
L_0x0065:
if (r0 == 0) goto L_0x0073;
L_0x0067:
r0 = r5.getBottom();
if (r8 >= r0) goto L_0x0073;
L_0x006d:
r0 = r5.getLeft();
if (r9 > r0) goto L_0x0124;
L_0x0073:
r0 = r3.y;
r12 = r10.y;
if (r0 >= r12) goto L_0x0152;
L_0x0079:
r0 = r3.x;
r12 = r10.x;
if (r0 >= r12) goto L_0x0152;
L_0x007f:
r0 = 1;
L_0x0080:
if (r0 == 0) goto L_0x008e;
L_0x0082:
r0 = r5.getBottom();
if (r8 >= r0) goto L_0x008e;
L_0x0088:
r0 = r5.getRight();
if (r9 < r0) goto L_0x0124;
L_0x008e:
r0 = r3.y;
r12 = r10.y;
if (r0 <= r12) goto L_0x0155;
L_0x0094:
r0 = r3.x;
r12 = r10.x;
if (r0 <= r12) goto L_0x0155;
L_0x009a:
r0 = 1;
L_0x009b:
if (r0 == 0) goto L_0x00a9;
L_0x009d:
r0 = r5.getTop();
if (r8 <= r0) goto L_0x00a9;
L_0x00a3:
r0 = r5.getLeft();
if (r9 > r0) goto L_0x0124;
L_0x00a9:
r0 = r3.y;
r12 = r10.y;
if (r0 <= r12) goto L_0x0158;
L_0x00af:
r0 = r3.x;
r12 = r10.x;
if (r0 >= r12) goto L_0x0158;
L_0x00b5:
r0 = 1;
L_0x00b6:
if (r0 == 0) goto L_0x00c4;
L_0x00b8:
r0 = r5.getTop();
if (r8 <= r0) goto L_0x00c4;
L_0x00be:
r0 = r5.getRight();
if (r9 < r0) goto L_0x0124;
L_0x00c4:
r0 = r3.y;
r12 = r10.y;
if (r0 >= r12) goto L_0x015b;
L_0x00ca:
r0 = r3.x;
r12 = r10.x;
if (r0 != r12) goto L_0x015b;
L_0x00d0:
r0 = 1;
L_0x00d1:
if (r0 == 0) goto L_0x00dc;
L_0x00d3:
r0 = r5.getBottom();
r12 = r14.olW;
r0 = r0 - r12;
if (r8 < r0) goto L_0x0124;
L_0x00dc:
r0 = r3.y;
r12 = r10.y;
if (r0 <= r12) goto L_0x015e;
L_0x00e2:
r0 = r3.x;
r12 = r10.x;
if (r0 != r12) goto L_0x015e;
L_0x00e8:
r0 = 1;
L_0x00e9:
if (r0 == 0) goto L_0x00f4;
L_0x00eb:
r0 = r5.getTop();
r12 = r14.olW;
r0 = r0 + r12;
if (r8 > r0) goto L_0x0124;
L_0x00f4:
r0 = r3.y;
r12 = r10.y;
if (r0 != r12) goto L_0x0160;
L_0x00fa:
r0 = r3.x;
r12 = r10.x;
if (r0 <= r12) goto L_0x0160;
L_0x0100:
r0 = 1;
L_0x0101:
if (r0 == 0) goto L_0x010c;
L_0x0103:
r0 = r5.getLeft();
r12 = r14.olW;
r0 = r0 + r12;
if (r9 > r0) goto L_0x0124;
L_0x010c:
r0 = r3.y;
r12 = r10.y;
if (r0 != r12) goto L_0x0162;
L_0x0112:
r0 = r3.x;
r3 = r10.x;
if (r0 >= r3) goto L_0x0162;
L_0x0118:
r0 = 1;
L_0x0119:
if (r0 == 0) goto L_0x01e1;
L_0x011b:
r0 = r5.getRight();
r3 = r14.olW;
r0 = r0 - r3;
if (r9 >= r0) goto L_0x01e1;
L_0x0124:
r0 = com.tencent.mm.plugin.sns.ui.previewimageview.f.cP(r5);
r3 = r14.omr;
r3 = com.tencent.mm.plugin.sns.ui.previewimageview.f.cP(r3);
r0 = r0 - r3;
r3 = java.lang.Math.abs(r0);
r0 = com.tencent.mm.plugin.sns.ui.previewimageview.f.cQ(r5);
r12 = r14.omr;
r12 = com.tencent.mm.plugin.sns.ui.previewimageview.f.cQ(r12);
r0 = r0 - r12;
r0 = java.lang.Math.abs(r0);
r12 = (r3 > r2 ? 1 : (r3 == r2 ? 0 : -1));
if (r12 < 0) goto L_0x01e1;
L_0x0146:
r12 = (r0 > r1 ? 1 : (r0 == r1 ? 0 : -1));
if (r12 < 0) goto L_0x01e1;
L_0x014a:
r2 = r3;
r4 = r5;
L_0x014c:
r1 = r0;
goto L_0x003e;
L_0x014f:
r0 = 0;
goto L_0x0065;
L_0x0152:
r0 = 0;
goto L_0x0080;
L_0x0155:
r0 = 0;
goto L_0x009b;
L_0x0158:
r0 = 0;
goto L_0x00b6;
L_0x015b:
r0 = 0;
goto L_0x00d1;
L_0x015e:
r0 = 0;
goto L_0x00e9;
L_0x0160:
r0 = 0;
goto L_0x0101;
L_0x0162:
r0 = 0;
goto L_0x0119;
L_0x0164:
if (r4 == 0) goto L_0x002e;
L_0x0166:
r0 = r14.omr;
r1 = r14.getPositionForView(r0);
r2 = r14.getPositionForView(r4);
r0 = new java.lang.StringBuilder;
r3 = "switch ";
r0.<init>(r3);
r0 = r0.append(r1);
r3 = ",";
r0 = r0.append(r3);
r0.append(r2);
r0 = r14.getAdapterInterface();
r3 = -1;
if (r2 == r3) goto L_0x0199;
L_0x018d:
r3 = r0.xG(r1);
if (r3 == 0) goto L_0x0199;
L_0x0193:
r0 = r0.xG(r2);
if (r0 != 0) goto L_0x01a0;
L_0x0199:
r0 = r14.olX;
r14.fp(r0);
goto L_0x002e;
L_0x01a0:
r14.dH(r1, r2);
r0 = r14.omn;
if (r0 == 0) goto L_0x01ac;
L_0x01a7:
r0 = r14.omp;
r0.dI(r1, r2);
L_0x01ac:
r0 = r14.olU;
r14.olT = r0;
r0 = r14.olV;
r14.olS = r0;
r0 = bES();
if (r0 == 0) goto L_0x01cf;
L_0x01ba:
r0 = bET();
if (r0 == 0) goto L_0x01cf;
L_0x01c0:
r0 = new com.tencent.mm.plugin.sns.ui.previewimageview.DynamicGridView$b;
r0.<init>(r14, r7, r6);
L_0x01c5:
r4 = r14.olX;
r14.fp(r4);
r0.dJ(r1, r2);
goto L_0x002e;
L_0x01cf:
r0 = bET();
if (r0 == 0) goto L_0x01db;
L_0x01d5:
r0 = new com.tencent.mm.plugin.sns.ui.previewimageview.DynamicGridView$i;
r0.<init>(r14, r7, r6);
goto L_0x01c5;
L_0x01db:
r0 = new com.tencent.mm.plugin.sns.ui.previewimageview.DynamicGridView$c;
r0.<init>(r7, r6);
goto L_0x01c5;
L_0x01e1:
r0 = r1;
goto L_0x014c;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.mm.plugin.sns.ui.previewimageview.DynamicGridView.bEV():void");
}
private Point cV(View view) {
int positionForView = getPositionForView(view);
int columnCount = getColumnCount();
return new Point(positionForView % columnCount, positionForView / columnCount);
}
private long xM(int i) {
return getAdapter().getItemId(i);
}
@TargetApi(11)
private static AnimatorSet d(View view, float f, float f2) {
ObjectAnimator ofFloat = ObjectAnimator.ofFloat(view, "translationX", new float[]{f, 0.0f});
ObjectAnimator ofFloat2 = ObjectAnimator.ofFloat(view, "translationY", new float[]{f2, 0.0f});
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(new Animator[]{ofFloat, ofFloat2});
return animatorSet;
}
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (this.olM != null) {
this.olM.draw(canvas);
}
}
}
|
package org.mitre.hapifhir;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.interceptor.api.Hook;
import ca.uhn.fhir.interceptor.api.Interceptor;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.parser.IParser;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hl7.fhir.r4.model.CanonicalType;
import org.hl7.fhir.r4.model.Meta;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.Parameters.ParametersParameterComponent;
import org.mitre.hapifhir.model.SubscriptionTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Interceptor
public class TopicListInterceptor {
private final Logger myLogger = LoggerFactory.getLogger(TopicListInterceptor.class.getName());
private FhirContext myCtx;
private IParser jparser;
private List<SubscriptionTopic> subscriptionTopics;
private static final String TOPIC_LIST_EXT_URL =
"http://hl7.org/fhir/uv/subscriptions-backport/StructureDefinition/backport-subscription-topic-canonical-urls";
/**
* Create a new interceptor.
*
* @param ctx - the fhir context to use
* @param subscriptionTopics - list of subscription topics this server supports
*/
public TopicListInterceptor(FhirContext ctx, List<SubscriptionTopic> subscriptionTopics) {
this.myCtx = ctx;
this.jparser = this.myCtx.newJsonParser();
this.subscriptionTopics = subscriptionTopics;
}
/**
* Override the incomingRequestPreProcessed method, which is called
* for each incoming request before any processing is done.
*
* @param theRequest - the HttpServletRequest
* @param theResponse - the HttpServletResponse
* @return true when processing should continue as normal, false when interceptor is activated
*/
@Hook(Pointcut.SERVER_INCOMING_REQUEST_PRE_PROCESSED)
public boolean incomingRequestPreProcessed(HttpServletRequest theRequest, HttpServletResponse theResponse) {
if (theRequest.getPathInfo() != null
&& theRequest.getPathInfo().equals("/Subscription/$topic-list")
&& theRequest.getMethod().equals("GET")) {
myLogger.info("Request received for $topic-list");
try {
handleTopicList(theResponse);
} catch (Exception e) {
myLogger.error("Exception: " + e.getMessage(), e);
}
return false;
}
return true;
}
/**
* The handler to send the response of the operation.
*
* @param theResponse - HttpServletResponse object
* @throws IOException when unable to write response
*/
public void handleTopicList(HttpServletResponse theResponse) throws IOException {
Meta meta = new Meta();
meta.addProfile(TOPIC_LIST_EXT_URL);
Parameters topicList = new Parameters();
topicList.setMeta(meta);
for (SubscriptionTopic subscriptionTopic : this.subscriptionTopics) {
ParametersParameterComponent parameter = new ParametersParameterComponent();
parameter.setName(subscriptionTopic.getName());
parameter.setValue(new CanonicalType(subscriptionTopic.getTopicUrl()));
topicList.addParameter(parameter);
}
theResponse.setStatus(200);
theResponse.setContentType("application/json");
theResponse.setCharacterEncoding("UTF-8");
PrintWriter out = theResponse.getWriter();
out.print(jparser.setPrettyPrint(true).encodeResourceToString(topicList));
out.flush();
}
}
|
package com.automation.utilities;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.testng.Reporter;
public class TestNGAppender extends AppenderSkeleton {
public void close() {
}
public boolean requiresLayout() {
return true;
}
@Override
protected void append(LoggingEvent event) {
Reporter.log(eToS(event));
}
private String eToS(LoggingEvent event) {
Object message = event.getMessage();
if(message instanceof String) {
return (String) message;
}
return null;
}
}
|
package eg.ipvii.fotp.init;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
public class MobDropsHandler {
@SubscribeEvent
public void onMobDrops(LivingDropsEvent event) {
if (event.getEntity() instanceof EntityCow) {
ItemStack stack = new ItemStack(ModItems.okra);
EntityItem drop = new EntityItem(event.getEntity().getEntityWorld(), event.getEntity().posX, event.getEntity().posY, event.getEntity().posZ, stack);
event.getDrops().add(drop);
}
}
}
|
package com.sendi.netrequest.rxquest;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import rx.Observable;
public interface APImap2 {
@Headers({"Content-Type: application/json","Accept: application/json"})//需要添加头
@POST ("build_monitor/map/select")
Observable<ResponseBody> getMessage(@Body RequestBody info); // 请求体味RequestBody 类型
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entities.dto;
import entities.SchoolClass;
import entities.SchoolSignedUp;
import entities.SchoolStudent;
import java.util.Date;
/**
*
* @author emilt
*/
public class SchoolSignedUpDTO {
//
private String grade;
private Date passedDate;
private SchoolStudentDTO student;
private SchoolClassDTO schoolClass;
//
public SchoolSignedUpDTO(SchoolSignedUp su) {
this.grade = su.getGrade();
this.passedDate = su.getPassedDate();
//this.student = new SchoolStudentDTO(su.getStudent());
//this.schoolClass = new SchoolClassDTO(su.getSchoolClass());
}
//
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Date getPassedDate() {
return passedDate;
}
public void setPassedDate(Date passedDate) {
this.passedDate = passedDate;
}
public SchoolStudentDTO getStudent() {
return student;
}
public void setStudent(SchoolStudentDTO student) {
this.student = student;
}
public SchoolClassDTO getSchoolClass() {
return schoolClass;
}
public void setSchoolClass(SchoolClassDTO schoolClass) {
this.schoolClass = schoolClass;
}
}
|
package com.tencent.mm.ui.tools;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.widget.Toast;
import com.jg.EType;
import com.jg.JgClassChecked;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.booter.NotifyReceiver;
import com.tencent.mm.g.a.ch;
import com.tencent.mm.k.b;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req;
import com.tencent.mm.opensdk.modelmsg.WXFileObject;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage.IMediaObject;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXVideoFileObject;
import com.tencent.mm.plugin.account.ui.SimpleLoginUI;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.pluginsdk.i.d;
import com.tencent.mm.protocal.c.ol;
import com.tencent.mm.protocal.c.vx;
import com.tencent.mm.protocal.c.wl;
import com.tencent.mm.protocal.c.wr;
import com.tencent.mm.sdk.platformtools.MMBitmapFactory.DecodeResultLogger;
import com.tencent.mm.sdk.platformtools.MMBitmapFactory.KVStatHelper;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.o;
import com.tencent.mm.sdk.platformtools.s;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.MMWizardActivity;
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.Iterator;
import java.util.List;
@com.tencent.mm.ui.base.a(3)
@JgClassChecked(author = 12, fComment = "checked", lastDate = "20141010", reviewer = 20, vComment = {EType.ACTIVITYCHECK})
public class AddFavoriteUI extends MMActivity implements e {
private ProgressDialog eHw = null;
String filePath = null;
private ag handler = new 12(this);
private Intent intent = null;
Uri uri = null;
private ag uvA = new 11(this);
private ch uvx;
ArrayList<String> uvy = null;
private ag uvz = new ag() {
public final void handleMessage(Message message) {
AddFavoriteUI.this.dismissDialog();
x.i("MicroMsg.AddFavoriteUI", "dealWithText: %b", new Object[]{Boolean.valueOf(AddFavoriteUI.this.czx())});
}
};
private class a implements Runnable {
private Uri aMJ;
private b uvC;
public a(Uri uri, b bVar) {
this.aMJ = uri;
this.uvC = bVar;
}
public final void run() {
AddFavoriteUI.this.filePath = AddFavoriteUI.a(AddFavoriteUI.this, this.aMJ);
if (bi.oW(AddFavoriteUI.this.filePath) || !new File(AddFavoriteUI.this.filePath).exists()) {
if (AddFavoriteUI.aaZ(AddFavoriteUI.this.getContentResolver().getType(this.aMJ)) == 2) {
AddFavoriteUI.this.filePath = d.a(AddFavoriteUI.this.getContentResolver(), this.aMJ, 1);
} else {
AddFavoriteUI.this.filePath = d.a(AddFavoriteUI.this.getContentResolver(), this.aMJ);
}
}
if (this.uvC != null) {
this.uvC.czz();
}
}
}
static /* synthetic */ void f(AddFavoriteUI addFavoriteUI) {
x.i("MicroMsg.AddFavoriteUI", "filepath:[%s]", new Object[]{addFavoriteUI.filePath});
int aaZ = aaZ(addFavoriteUI.getIntent().resolveType(addFavoriteUI));
if (aaZ == -1) {
x.e("MicroMsg.AddFavoriteUI", "launch, msgType is invalid");
addFavoriteUI.finish();
return;
}
x.i("MicroMsg.AddFavoriteUI", "filepath:[%s] dealWithMultiItem msgType is %d", new Object[]{addFavoriteUI.filePath, Integer.valueOf(aaZ)});
if (aaZ == 8 && !bi.oW(addFavoriteUI.filePath)) {
addFavoriteUI.bd(aaZ, addFavoriteUI.filePath);
} else if (s.a(addFavoriteUI.getIntent(), "Intro_Switch", false) || !au.HW() || au.Dr()) {
ArrayList arrayList;
Intent intent = new Intent(addFavoriteUI, AddFavoriteUI.class);
intent.setAction("android.intent.action.SEND_MULTIPLE");
if (bi.cX(addFavoriteUI.uvy)) {
arrayList = new ArrayList(0);
} else {
ArrayList arrayList2 = new ArrayList(addFavoriteUI.uvy.size());
Iterator it = addFavoriteUI.uvy.iterator();
while (it.hasNext()) {
arrayList2.add(Uri.fromFile(new File((String) it.next())));
}
arrayList = arrayList2;
}
intent.putParcelableArrayListExtra("android.intent.extra.STREAM", arrayList);
intent.addFlags(268435456).addFlags(WXMediaMessage.THUMB_LENGTH_LIMIT);
intent.setType(addFavoriteUI.getIntent().getType());
MMWizardActivity.b(addFavoriteUI, new Intent(addFavoriteUI, SimpleLoginUI.class).addFlags(WXMediaMessage.THUMB_LENGTH_LIMIT).addFlags(268435456), intent);
addFavoriteUI.finish();
} else {
ch chVar = new ch();
List<String> list = addFavoriteUI.uvy;
if (list == null || list.isEmpty()) {
x.w("MicroMsg.GetFavDataSource", "fill favorite event fail, event is null or paths is empty");
chVar.bJF.bJL = R.l.favorite_fail_argument_error;
} else if (list.size() > 9) {
chVar.bJF.bJL = R.l.favorite_fail_images_count_error;
} else {
x.i("MicroMsg.GetFavDataSource", "do fill event info(fav simple images), paths %s sourceType %d", new Object[]{list, Integer.valueOf(13)});
wl wlVar = new wl();
wr wrVar = new wr();
for (String str : list) {
if (!bi.oW(str)) {
vx vxVar = new vx();
vxVar.CF(2);
vxVar.UP(str);
vxVar.kY(true);
wlVar.rBI.add(vxVar);
}
}
wrVar.Vw(q.GF());
wrVar.Vx(q.GF());
wrVar.CO(13);
wrVar.fU(bi.VF());
wlVar.a(wrVar);
chVar.bJF.title = "";
chVar.bJF.bJH = wlVar;
chVar.bJF.type = 2;
}
chVar.bJF.activity = addFavoriteUI;
chVar.bJF.bJN = new 13(addFavoriteUI);
chVar.bJF.bJO = new 14(addFavoriteUI);
au.DF().a(837, addFavoriteUI);
g.DF().a(new com.tencent.mm.modelsimple.d(1, addFavoriteUI.uvy, addFavoriteUI.cqk()), 0);
addFavoriteUI.showDialog();
addFavoriteUI.uvx = chVar;
}
}
static /* synthetic */ void h(AddFavoriteUI addFavoriteUI) {
x.i("MicroMsg.AddFavoriteUI", "filepath:[%s]", new Object[]{addFavoriteUI.filePath});
int aaZ = aaZ(addFavoriteUI.getIntent().resolveType(addFavoriteUI));
if (aaZ == -1) {
x.e("MicroMsg.AddFavoriteUI", "launch, msgType is invalid");
addFavoriteUI.finish();
return;
}
x.i("MicroMsg.AddFavoriteUI", "filepath:[%s] dealWithSimpleItem msgType is %d", new Object[]{addFavoriteUI.filePath, Integer.valueOf(aaZ)});
if (!bi.oW(addFavoriteUI.filePath)) {
addFavoriteUI.bd(aaZ, addFavoriteUI.filePath);
} else if (s.a(addFavoriteUI.getIntent(), "Intro_Switch", false) || !au.HW() || au.Dr()) {
addFavoriteUI.finish();
addFavoriteUI.czw();
} else {
ch chVar = new ch();
com.tencent.mm.pluginsdk.model.e.a(chVar, 13, addFavoriteUI.filePath);
chVar.bJF.activity = addFavoriteUI;
chVar.bJF.bJN = new 15(addFavoriteUI);
chVar.bJF.bJO = new 2(addFavoriteUI);
com.tencent.mm.sdk.b.a.sFg.m(chVar);
}
}
public void onCreate(Bundle bundle) {
x.i("MicroMsg.AddFavoriteUI", "on create");
super.onCreate(bundle);
setTitleVisibility(8);
int a = s.a(getIntent(), "wizard_activity_result_code", 0);
switch (a) {
case -1:
case 0:
NotifyReceiver.xA();
initView();
return;
case 1:
finish();
return;
default:
x.e("MicroMsg.AddFavoriteUI", "onCreate, should not reach here, resultCode = " + a);
finish();
return;
}
}
protected void onSaveInstanceState(Bundle bundle) {
x.i("MicroMsg.AddFavoriteUI", "on SaveInstanceState");
super.onSaveInstanceState(bundle);
}
protected void onNewIntent(Intent intent) {
x.i("MicroMsg.AddFavoriteUI", "on NewIntent");
super.onNewIntent(intent);
}
protected void onRestoreInstanceState(Bundle bundle) {
x.i("MicroMsg.AddFavoriteUI", "on RestoreInstanceState");
super.onRestoreInstanceState(bundle);
}
protected void onDestroy() {
x.i("MicroMsg.AddFavoriteUI", "on Destroy");
au.DF().b(837, this);
super.onDestroy();
}
protected final int getLayoutId() {
return -1;
}
protected final void initView() {
this.intent = getIntent();
if (this.intent == null) {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, intent is null");
czy();
finish();
return;
}
String action = this.intent.getAction();
Bundle aq = s.aq(this.intent);
if (bi.oW(action)) {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, action is null");
czy();
finish();
return;
}
if (aq != null) {
Parcelable parcelable = aq.getParcelable("android.intent.extra.STREAM");
if (parcelable instanceof Uri) {
this.uri = (Uri) parcelable;
if (!bi.n(this.uri)) {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, not accept, %s", new Object[]{this.uri});
czy();
finish();
return;
}
} else if (parcelable != null) {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, uri check fail, %s", new Object[]{parcelable});
czy();
finish();
return;
}
}
if (action.equals("android.intent.action.SEND")) {
x.i("MicroMsg.AddFavoriteUI", "send signal: " + action);
if (this.uri == null) {
showDialog();
com.tencent.mm.sdk.f.e.post(new 1(this), "AddFavoriteUI_dealWithTextHandler");
return;
}
showDialog();
com.tencent.mm.sdk.f.e.post(new a(this.uri, new 8(this)), "AddFavoriteUI_getFilePath");
} else if (action.equals("android.intent.action.SEND_MULTIPLE") && aq != null && aq.containsKey("android.intent.extra.STREAM")) {
x.i("MicroMsg.AddFavoriteUI", "send multi: %s, mimeType %s", new Object[]{action, getIntent().resolveType(this)});
if (bi.aG(getIntent().resolveType(this), "").contains("image")) {
this.uvy = aj(aq);
if (this.uvy == null || this.uvy.size() == 0) {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, filePathList is null");
Gf(1);
finish();
return;
}
showDialog();
com.tencent.mm.sdk.f.e.post(new 9(this), "AddFavoriteUI_dealWithMultiItemHandler");
return;
}
x.e("MicroMsg.AddFavoriteUI", "launch : fail, mimeType not contains image");
Gf(1);
finish();
} else {
x.e("MicroMsg.AddFavoriteUI", "launch : fail, uri is null");
czy();
finish();
}
}
private void czw() {
Intent intent = new Intent(this, AddFavoriteUI.class);
intent.setAction("android.intent.action.SEND");
intent.putExtra("android.intent.extra.STREAM", bi.oW(this.filePath) ? null : Uri.fromFile(new File(this.filePath)));
intent.addFlags(268435456).addFlags(WXMediaMessage.THUMB_LENGTH_LIMIT);
intent.setType(getIntent().getType());
MMWizardActivity.b(this, new Intent(this, SimpleLoginUI.class).addFlags(WXMediaMessage.THUMB_LENGTH_LIMIT).addFlags(268435456), intent);
}
private ArrayList<String> aj(Bundle bundle) {
ArrayList parcelableArrayList = bundle.getParcelableArrayList("android.intent.extra.STREAM");
if (parcelableArrayList == null || parcelableArrayList.size() <= 0) {
x.e("MicroMsg.AddFavoriteUI", "getParcelableArrayList failed");
return null;
}
ArrayList<String> arrayList = new ArrayList();
Iterator it = parcelableArrayList.iterator();
while (it.hasNext()) {
int i;
Parcelable parcelable = (Parcelable) it.next();
if (parcelable == null || !(parcelable instanceof Uri)) {
x.e("MicroMsg.AddFavoriteUI", "getMultiSendFilePath failed, error parcelable, %s", new Object[]{parcelable});
} else {
Uri uri = (Uri) parcelable;
if (!bi.n(uri) || uri.getScheme() == null) {
x.e("MicroMsg.AddFavoriteUI", "unaccepted uri: " + uri);
} else {
String h = bi.h(this, uri);
if (!bi.oW(h)) {
if (bi.Xh(h) && aaY(h)) {
x.i("MicroMsg.AddFavoriteUI", "multisend file path: " + h);
arrayList.add(h);
i = 1;
continue;
if (i == 0) {
return null;
}
}
x.w("MicroMsg.AddFavoriteUI", "multisend tries to send illegal img: " + h);
}
}
}
i = 0;
continue;
if (i == 0) {
return null;
}
}
return arrayList.size() > 0 ? arrayList : null;
}
private static boolean aaY(String str) {
DecodeResultLogger decodeResultLogger = new DecodeResultLogger();
boolean b = o.b(str, decodeResultLogger);
if (!b && decodeResultLogger.getDecodeResult() >= 2000) {
h.mEJ.k(12712, KVStatHelper.getKVStatString(str, 5, decodeResultLogger));
}
return b;
}
private boolean czx() {
this.intent = getIntent();
if (this.intent == null) {
x.e("MicroMsg.AddFavoriteUI", "intent is null");
return false;
}
String j = s.j(this.intent, "android.intent.extra.TEXT");
if (j == null || j.length() == 0) {
x.i("MicroMsg.AddFavoriteUI", "text is null");
return false;
}
WXMediaMessage wXMediaMessage = new WXMediaMessage(new WXTextObject(j));
wXMediaMessage.description = j;
Req req = new Req();
req.transaction = null;
req.message = wXMediaMessage;
int type = req.message.getType();
Bundle bundle = new Bundle();
req.toBundle(bundle);
bundle.putInt(ConstantsAPI.SDK_VERSION, 620823808);
bundle.putString(ConstantsAPI.APP_PACKAGE, "com.tencent.mm.openapi");
bundle.putString("SendAppMessageWrapper_AppId", "wx4310bbd51be7d979");
if (!au.HW() || au.Dr()) {
x.w("MicroMsg.AddFavoriteUI", "not logged in, jump to simple login");
MMWizardActivity.b(this, new Intent(this, SimpleLoginUI.class), getIntent().addFlags(67108864));
finish();
} else {
ch chVar = new ch();
String str = com.tencent.mm.a.e.cq(this.filePath) + "." + com.tencent.mm.a.e.cp(this.filePath);
if (type == 1) {
Boolean.valueOf(com.tencent.mm.pluginsdk.model.e.b(chVar, j, 13));
} else {
Boolean.valueOf(com.tencent.mm.pluginsdk.model.e.a(chVar, 13, this.filePath, str, ""));
}
chVar.bJF.activity = this;
chVar.bJF.bJN = new 3(this);
chVar.bJF.bJO = new 4(this);
this.uvx = chVar;
List arrayList = new ArrayList();
arrayList.add(j);
com.tencent.mm.modelsimple.d dVar = new com.tencent.mm.modelsimple.d(5, arrayList, cqk());
au.DF().a(837, this);
g.DF().a(dVar, 0);
showDialog();
}
return true;
}
private void bd(int i, String str) {
if (str == null || str.length() == 0) {
x.e("MicroMsg.AddFavoriteUI", "dealWithFile fail, filePath is empty");
return;
}
int cm = com.tencent.mm.a.e.cm(str);
x.i("MicroMsg.AddFavoriteUI", "filelength: [%d]", new Object[]{Integer.valueOf(cm)});
if (cm == 0) {
x.e("MicroMsg.AddFavoriteUI", "dealWithFile fail, fileLength is 0");
Toast.makeText(this, R.l.favorite_file_length_zero, 1).show();
finish();
} else if (cm > 26214400) {
x.e("MicroMsg.AddFavoriteUI", "dealWithFile fail, fileLength is too large");
Toast.makeText(this, R.l.favorite_too_large, 1).show();
finish();
} else if (!au.HW() || au.Dr()) {
x.w("MicroMsg.AddFavoriteUI", "not logged in, jump to simple login");
finish();
czw();
} else {
IMediaObject wXImageObject;
l dVar;
List arrayList = new ArrayList();
arrayList.add(str);
ch chVar = new ch();
String str2 = com.tencent.mm.a.e.cq(str) + "." + com.tencent.mm.a.e.cp(str);
switch (i) {
case 2:
wXImageObject = new WXImageObject();
((WXImageObject) wXImageObject).setImagePath(str);
dVar = new com.tencent.mm.modelsimple.d(1, arrayList, cqk());
com.tencent.mm.pluginsdk.model.e.a(chVar, 13, str);
break;
case 4:
wXImageObject = new WXVideoFileObject(str);
dVar = new com.tencent.mm.modelsimple.d(3, arrayList, cqk());
String str3 = "";
if (!bi.oW(str)) {
x.d("MicroMsg.GetFavDataSource", "do fill event info(fav simple file), title %s, desc %s, path %s, sourceType %d", new Object[]{str2, str3, str, Integer.valueOf(13)});
if (new File(str).length() <= ((long) b.AB())) {
wl wlVar = new wl();
wr wrVar = new wr();
vx vxVar = new vx();
vxVar.UP(str);
vxVar.CF(4);
vxVar.UL(com.tencent.mm.a.e.cp(str));
vxVar.UQ(null);
vxVar.CE(0);
vxVar.UB(str2);
vxVar.UC(str3);
wrVar.Vw(q.GF());
wrVar.Vx(q.GF());
wrVar.CO(13);
wrVar.fU(bi.VF());
wlVar.a(wrVar);
wlVar.rBI.add(vxVar);
chVar.bJF.title = vxVar.title;
chVar.bJF.desc = vxVar.title;
chVar.bJF.bJH = wlVar;
chVar.bJF.type = 4;
break;
}
chVar.bJF.bJL = R.l.favorite_too_large;
break;
}
x.w("MicroMsg.GetFavDataSource", "fill favorite event fail, event is null or image path is empty");
chVar.bJF.bJL = R.l.favorite_fail_argument_error;
break;
default:
wXImageObject = new WXFileObject(str);
dVar = new com.tencent.mm.modelsimple.d(4, arrayList, cqk());
com.tencent.mm.pluginsdk.model.e.a(chVar, 13, str, str2, "");
break;
}
WXMediaMessage wXMediaMessage = new WXMediaMessage(wXImageObject);
wXMediaMessage.title = new File(str).getName();
if (bi.oW(null)) {
wXMediaMessage.description = bi.bF((long) cm);
} else {
wXMediaMessage.description = null;
}
if (cm < 30720) {
wXMediaMessage.thumbData = com.tencent.mm.a.e.e(str, 0, -1);
} else {
x.i("MicroMsg.AddFavoriteUI", "thumb data is exceed 30k, ignore");
}
Req req = new Req();
req.transaction = null;
req.message = wXMediaMessage;
Bundle bundle = new Bundle();
req.toBundle(bundle);
bundle.putInt(ConstantsAPI.SDK_VERSION, 620823808);
bundle.putString(ConstantsAPI.APP_PACKAGE, "com.tencent.mm.openapi");
bundle.putString("SendAppMessageWrapper_AppId", "wx4310bbd51be7d979");
chVar.bJF.activity = this;
chVar.bJF.bJN = new 5(this);
chVar.bJF.bJO = new 6(this);
this.uvx = chVar;
g.DF().a(837, this);
g.DF().a(dVar, 0);
showDialog();
}
}
private String a(Uri uri, Cursor cursor) {
FileNotFoundException e;
IOException e2;
Throwable e3;
Exception e4;
if (uri != null) {
String str = "contact.vcf";
int columnIndex = cursor.getColumnIndex("_display_name");
if (columnIndex != -1) {
str = cursor.getString(columnIndex);
if (str != null) {
str = str.replaceAll("[^.\\w]+", "_");
}
x.i("MicroMsg.AddFavoriteUI", "vcard file name: " + str);
}
cursor.close();
AssetFileDescriptor openAssetFileDescriptor;
FileInputStream createInputStream;
FileOutputStream openFileOutput;
try {
openAssetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
try {
createInputStream = openAssetFileDescriptor.createInputStream();
try {
byte[] bArr = new byte[((int) openAssetFileDescriptor.getDeclaredLength())];
if (createInputStream.read(bArr) > 0) {
au.HU();
if (c.isSDCardAvailable()) {
String str2 = com.tencent.mm.compatible.util.e.bnE + "share";
str = com.tencent.mm.compatible.util.e.bnE + "share/" + str;
File file = new File(str2);
if (!file.exists()) {
file.mkdir();
}
File file2 = new File(str);
if (!file2.exists()) {
file2.createNewFile();
}
if (com.tencent.mm.a.e.b(str, bArr, bArr.length) == 0) {
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e5) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e5, e5.getMessage(), new Object[0]);
return str;
}
}
if (openAssetFileDescriptor == null) {
return str;
}
openAssetFileDescriptor.close();
return str;
}
}
deleteFile(str);
openFileOutput = openFileOutput(str, 0);
try {
openFileOutput.write(bArr);
openFileOutput.flush();
str = getFilesDir().getPath() + "/" + str;
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e52) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e52, e52.getMessage(), new Object[0]);
return str;
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput == null) {
return str;
}
openFileOutput.close();
return str;
} catch (FileNotFoundException e6) {
e = e6;
} catch (IOException e7) {
e2 = e7;
x.e("MicroMsg.AddFavoriteUI", "vcard uri ioexception" + e2.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e32) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e32, e32.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Exception e8) {
e4 = e8;
x.e("MicroMsg.AddFavoriteUI", "vcard uri exception" + e4.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e322) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e322, e322.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
}
}
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e3222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e3222, e3222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
} catch (FileNotFoundException e9) {
e = e9;
openFileOutput = null;
try {
x.e("MicroMsg.AddFavoriteUI", "vcard uri file not found " + e.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e32222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e32222, e32222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Throwable th) {
e32222 = th;
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e522) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e522, e522.getMessage(), new Object[0]);
throw e32222;
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
throw e32222;
}
} catch (IOException e10) {
e2 = e10;
openFileOutput = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri ioexception" + e2.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e322222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e322222, e322222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Exception e11) {
e4 = e11;
openFileOutput = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri exception" + e4.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e3222222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e3222222, e3222222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Throwable th2) {
e3222222 = th2;
openFileOutput = null;
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e5222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e5222, e5222.getMessage(), new Object[0]);
throw e3222222;
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
throw e3222222;
}
} catch (FileNotFoundException e12) {
e = e12;
openFileOutput = null;
createInputStream = null;
} catch (IOException e13) {
e2 = e13;
openFileOutput = null;
createInputStream = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri ioexception" + e2.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e32222222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e32222222, e32222222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Exception e14) {
e4 = e14;
openFileOutput = null;
createInputStream = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri exception" + e4.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e322222222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e322222222, e322222222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Throwable th3) {
e322222222 = th3;
openFileOutput = null;
createInputStream = null;
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e52222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e52222, e52222.getMessage(), new Object[0]);
throw e322222222;
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
throw e322222222;
}
} catch (FileNotFoundException e15) {
e = e15;
openFileOutput = null;
createInputStream = null;
openAssetFileDescriptor = null;
} catch (IOException e16) {
e2 = e16;
openFileOutput = null;
createInputStream = null;
openAssetFileDescriptor = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri ioexception" + e2.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e3222222222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e3222222222, e3222222222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Exception e17) {
e4 = e17;
openFileOutput = null;
createInputStream = null;
openAssetFileDescriptor = null;
x.e("MicroMsg.AddFavoriteUI", "vcard uri exception" + e4.getMessage());
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e32222222222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e32222222222, e32222222222.getMessage(), new Object[0]);
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
return null;
} catch (Throwable th4) {
e32222222222 = th4;
openFileOutput = null;
createInputStream = null;
openAssetFileDescriptor = null;
if (createInputStream != null) {
try {
createInputStream.close();
} catch (Throwable e522222) {
x.printErrStackTrace("MicroMsg.AddFavoriteUI", e522222, e522222.getMessage(), new Object[0]);
throw e32222222222;
}
}
if (openAssetFileDescriptor != null) {
openAssetFileDescriptor.close();
}
if (openFileOutput != null) {
openFileOutput.close();
}
throw e32222222222;
}
}
return null;
}
private static int aaZ(String str) {
if (str == null || str.length() == 0) {
x.e("MicroMsg.AddFavoriteUI", "map : mimeType is null");
return -1;
}
String toLowerCase = str.toLowerCase();
if (toLowerCase.contains("image") || toLowerCase.equals("application/vnd.google.panorama360+jpg")) {
return 2;
}
if (toLowerCase.contains("video")) {
return 4;
}
x.d("MicroMsg.AddFavoriteUI", "map : unknown mimetype, send as file");
return 8;
}
private void czy() {
Gf(0);
Toast.makeText(this, R.l.shareimg_get_res_fail, 1).show();
}
private void Gf(int i) {
switch (i) {
case 1:
Toast.makeText(this, R.l.shareimg_err_not_support_type, 1).show();
return;
default:
Toast.makeText(this, R.l.shareimg_get_res_fail, 1).show();
return;
}
}
private void showDialog() {
getString(R.l.app_tip);
this.eHw = com.tencent.mm.ui.base.h.a((Context) this, getString(R.l.app_waiting), true, new 7(this));
}
private void dismissDialog() {
if (this.eHw != null && this.eHw.isShowing()) {
this.eHw.dismiss();
}
}
public final void a(int i, int i2, String str, l lVar) {
x.i("MicroMsg.AddFavoriteUI", "onSceneEnd, errType = %d, errCode = %d, errMsg = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
dismissDialog();
if (!(lVar instanceof com.tencent.mm.modelsimple.d)) {
return;
}
if (i == 0 && i2 == 0) {
if (this.uvx != null) {
com.tencent.mm.sdk.b.a.sFg.m(this.uvx);
this.uvx = null;
}
} else if (lVar.dJd != null) {
ol olVar = (ol) ((com.tencent.mm.ab.b) lVar.dJd).dIE.dIL;
if (olVar != null && !bi.oW(olVar.rsN)) {
Intent intent = new Intent();
intent.putExtra("rawUrl", olVar.rsN);
intent.putExtra("showShare", false);
intent.putExtra("show_bottom", false);
intent.putExtra("needRedirect", false);
com.tencent.mm.bg.d.b(this, "webview", ".ui.tools.WebViewUI", intent);
finish();
} else if (this.uvx != null) {
com.tencent.mm.sdk.b.a.sFg.m(this.uvx);
this.uvx = null;
}
}
}
}
|
package com.jim.multipos.ui.signing.sign_in.presenter;
import com.jim.multipos.ui.signing.sign_in.view.LoginDetailsView;
import javax.inject.Inject;
/**
* Created by DEV on 31.07.2017.
*/
public class LoginDetailsPresenterImpl implements LoginDetailsPresenter {
private LoginDetailsView view;
@Inject
public LoginDetailsPresenterImpl() {
}
@Override
public void init(LoginDetailsView view) {
this.view = view;
}
@Override
public void registerFounder() {
// view.onRegistration();
}
@Override
public void loginFounder() {
// view.onLogin();
}
}
|
package com.brainmentors.apps.annotationdemo;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component("m")
@Scope("prototype")
@Primary
public class Y implements IY {
public Y() {
System.out.println("Y Object");
}
@Override
public void emi() {
// TODO Auto-generated method stub
System.out.println("Monthly");
}
}
|
package by.epam.parser.entity;
/**
* <p>Help to create and work with object Document
* which is an object representation of xml document.
* Root is only one element contains list of its child
* elements.</p>
*
* @author VeronikaChigir
* @version 2.0
*/
public class Document {
private Element root;
public Document(){}
public Element getRoot() {
return root;
}
public void setRoot(Element root) {
this.root = root;
}
@Override
public String toString() {
return "Document{" +
"root=" + root +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Document document = (Document) o;
return !(root != null ? !root.equals(document.root) : document.root != null);
}
@Override
public int hashCode() {
return root != null ? root.hashCode() : 0;
}
}
|
package org.icabanas.jee.api.integracion.modelo;
import java.io.Serializable;
import org.icabanas.jee.api.integracion.manager.exceptions.ValidacionException;
public interface Entidad<ID extends Serializable> {
/**
* Método que devuelve el identificador de la entidad.
*
* @return
*/
public ID getId();
/**
* Método que establece el identificador de la entidad.
*
* @param id
*/
public void setId(ID id);
/**
* Método que comprueba si la entidad es vacía, es decir, que el valor de todos sus campos son nulos o
* vacíos.
*
* @return
*/
public boolean esVacia();
/**
* Valida una entidad.
*
* @return
* True si la entidad es válida.
*
* @throws ValidacionException
* En el caso que la entidad no sea válida, indicando los campos erróneos.
*/
public boolean valida() throws ValidacionException;
}
|
package sim.perfil;
import java.io.Serializable;
import javax.persistence.*;
@Entity
@Table(name="perfil")
public class Perfil implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4360284891228836761L;
@Id
@GeneratedValue
@Column(name="id_perfil")
private Integer codigo;
private String nome;
private Integer permissoes;
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Integer getPermissoes() {
return permissoes;
}
public void setPermissoes(Integer permissoes) {
this.permissoes = permissoes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result
+ ((permissoes == null) ? 0 : permissoes.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;
Perfil other = (Perfil) obj;
if (codigo == null) {
if (other.codigo != null)
return false;
} else if (!codigo.equals(other.codigo))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
if (permissoes == null) {
if (other.permissoes != null)
return false;
} else if (!permissoes.equals(other.permissoes))
return false;
return true;
}
}
|
package week3.tests;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
/**
* Created by Benedikt on 27.10.2016.
*/
public class ATest {
private static final InputStream sIn = System.in;
public static final PrintStream sOut = System.out;
static String inputOutput(String input) {
try {
InputStream inputStream = new ByteArrayInputStream(input.getBytes("UTF-8"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
System.setIn(inputStream);
week3.A.main(new String[1]);
System.out.flush();
System.setIn(sIn);
System.setOut(sOut);
return outputStream.toString("UTF-8").trim();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@Test
public void firstGivenTest() throws IOException {
String input = "2\n" +
"2\n" +
"0 0 0\n" +
"1 1 1\n" +
"\n" +
"4\n" +
"0 0 0\n" +
"1 0 0\n" +
"0 1 0\n" +
"0 0 1";
String shouldOutput = "Case #1: 3\n" +
"Case #2: 3";
Assert.assertEquals(shouldOutput.trim(), inputOutput(input));
}
@Test
public void secondGivenTest() throws IOException {
String input = "8\n" +
"4\n" +
"7 6 5\n" +
"9 9 7\n" +
"4 1 9\n" +
"4 9 2\n" +
"\n" +
"4\n" +
"4 10 9\n" +
"9 10 10\n" +
"0 1 10\n" +
"2 9 2\n" +
"\n" +
"3\n" +
"6 8 2\n" +
"8 4 9\n" +
"3 6 2\n" +
"\n" +
"2\n" +
"7 5 1\n" +
"0 10 9\n" +
"\n" +
"2\n" +
"2 10 10\n" +
"0 5 3\n" +
"\n" +
"3\n" +
"1 6 5\n" +
"9 7 5\n" +
"10 8 10\n" +
"\n" +
"5\n" +
"7 6 2\n" +
"7 5 2\n" +
"8 7 4\n" +
"3 0 7\n" +
"6 2 10\n" +
"\n" +
"4\n" +
"3 8 7\n" +
"2 5 7\n" +
"7 10 8\n" +
"7 0 8";
String shouldOutput = "Case #1: 28\n" +
"Case #2: 30\n" +
"Case #3: 18\n" +
"Case #4: 20\n" +
"Case #5: 14\n" +
"Case #6: 16\n" +
"Case #7: 25\n" +
"Case #8: 21";
Assert.assertEquals(shouldOutput.trim(), inputOutput(input));
}
// @Test
// public void Test() throws IOException {
// String input = "";
// String shouldOutput = "";
// Assert.assertEquals(shouldOutput.trim(), inputOutput(input));
// }
}
|
package com.simonk.api.interactions.services;
import com.simonk.api.interactions.dto.Booking;
import io.qameta.allure.Step;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
public class RestfulBookerService extends AbstractBaseService {
private final String apiEndpoint = getBaseUrl() + "booking/";
public RestfulBookerService(String base) {
super(base);
}
@Step("Pinging service: Booking API")
public Response pingService() {
return given().when().get(getBaseUrl() + "ping");
}
@Step("Retrieve a list of all bookings")
public Response getBookings() {
return given().spec(getSpec()).get(apiEndpoint);
}
@Step("Getting booking {id}")
public Response getBooking(int id) {
return given().spec(getSpec()).get(
apiEndpoint + Integer.toString(id));
}
@Step("Saving a new booking")
public Response postBooking(Booking payload) {
return given().spec(getSpec()).body(payload).when()
.post(apiEndpoint);
}
@Step("Deleting a booking: {id}")
public Response deleteBooking(int id, String tokenValue) {
return given().spec(getSpec()).header("Cookie", "token=" + tokenValue).delete(
apiEndpoint + Integer.toString(id));
}
}
|
package ba.bitcamp.LabS04D02;
public class SabiranjeIzTXTFileV2 {
public static void main(String[] args) {
TextIO.readUserSelectedFile();
int sum = 0;
while(TextIO.eof() != true) {
try {
String str = TextIO.getWord();
int broj = Integer.parseInt(str);
sum += broj;
} catch (NumberFormatException e) {
TextIO.putln("Razmak");
}catch (IllegalArgumentException ia) {
TextIO.putln("Moramo skontati kako getWord radi");
break;
}
}
TextIO.putln("Suma: " + sum);
}
}
|
package io.jenkins.plugins.credentials.secretsmanager.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Polyfill for the Java 9 Map.of API methods.
*/
public final class Maps {
public static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2) {
final Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
return Collections.unmodifiableMap(m);
}
public static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
final Map<K, V> m = new HashMap<>();
m.put(k1, v1);
m.put(k2, v2);
m.put(k3, v3);
m.put(k4, v4);
return Collections.unmodifiableMap(m);
}
}
|
package algorithms.dynamic_programming.knapsack;
import java.util.Arrays;
public class TargetSum {
public int findTargetSubsets(int[] num, int s) {
// Sum(s1) - Sum(s2) = s -------------(1)
// Sum(s1) + Sum(s2) = Sum(num) ------(2)
// Adding equation (1) and (2)
// 2 * Sum(s1) = s + Sum(num)
// Sum(s1) = (s + Sum(num)) / 2
// Now the problem deduced to count of subsets with the given target
CountOfSubsetSum countOfSubsetSum = new CountOfSubsetSum();
int target = (s + Arrays.stream(num).sum()) / 2;
return countOfSubsetSum.countSubsetsMemoization(num, target);
}
public static void main(String[] args) {
TargetSum ts = new TargetSum();
int[] num = {1, 1, 2, 3};
System.out.println(ts.findTargetSubsets(num, 1));
num = new int[]{1, 2, 7, 1};
System.out.println(ts.findTargetSubsets(num, 9));
}
}
|
package com.tt.miniapp.debug;
import android.os.Handler;
import android.text.TextUtils;
import com.he.jsbinding.JsContext;
import com.he.jsbinding.JsScopedContext;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.debug.appData.AppData;
import com.tt.miniapp.debug.appData.AppDataReporter;
import com.tt.miniapp.debug.storage.StorageReporter;
import com.tt.miniapp.jsbridge.JsRuntimeManager;
import com.tt.miniapp.storage.Storage;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.entity.AppInfoEntity;
import com.tt.miniapphost.util.DebugUtil;
import java.io.IOException;
import okhttp3.ac;
import okhttp3.ae;
import okhttp3.ai;
import okhttp3.aj;
import okhttp3.y;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class RemoteDebugManager {
public AppDataReporter appDataReporter = new AppDataReporter();
private String baseDebugURL;
public ai remoteWs;
public StorageReporter storageReporter = new StorageReporter();
public void clearStorage(int paramInt, boolean paramBoolean) throws JSONException {
sendMessageByRemoteWs(this.storageReporter.clearStorage(paramInt, paramBoolean));
}
public void closeRemoteWs(String paramString) {
AppBrandLogger.e("RemoteDebugManager", new Object[] { "close_remote_ws", paramString });
ai ai1 = this.remoteWs;
if (ai1 != null)
ai1.b(3999, paramString);
}
public AppDataReporter getAppDataReporter() {
return this.appDataReporter;
}
public String getBaseDebugURL() {
return this.baseDebugURL;
}
public void getDOMStorageItems(int paramInt, JSONArray paramJSONArray) throws JSONException {
sendMessageByRemoteWs(this.storageReporter.getDOMStorageItems(paramInt, paramJSONArray));
}
public boolean initRemoteDebugInfo(AppInfoEntity paramAppInfoEntity) {
if (paramAppInfoEntity != null && !TextUtils.isEmpty(paramAppInfoEntity.session) && !TextUtils.isEmpty(paramAppInfoEntity.gtoken) && !TextUtils.isEmpty(paramAppInfoEntity.roomid)) {
StringBuilder stringBuilder = new StringBuilder("ws://gate.snssdk.com/debug_room?session=");
stringBuilder.append(paramAppInfoEntity.session);
stringBuilder.append("&gToken=");
stringBuilder.append(paramAppInfoEntity.gtoken);
stringBuilder.append("&room_id=");
stringBuilder.append(paramAppInfoEntity.roomid);
stringBuilder.append("&need_cache=1");
this.baseDebugURL = stringBuilder.toString();
return true;
}
return false;
}
public void openRemoteWsClient(final Handler debugHandler) {
StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.append(this.baseDebugURL);
stringBuilder1.append("&cursor=webview&role=phone");
String str = stringBuilder1.toString();
StringBuilder stringBuilder2 = new StringBuilder("openRemoteWsClient: ");
stringBuilder2.append(str);
AppBrandLogger.d("RemoteDebugManager", new Object[] { stringBuilder2.toString() });
y y = (new y.a()).a();
ac ac = (new ac.a()).a(str).c();
debugHandler.sendEmptyMessageDelayed(-1, 10000L);
y.a(ac, new aj() {
public void onClosed(ai param1ai, int param1Int, String param1String) {
StringBuilder stringBuilder = new StringBuilder("remoteWsClient code: ");
stringBuilder.append(param1Int);
stringBuilder.append(" reason: ");
stringBuilder.append(param1String);
AppBrandLogger.d("RemoteDebugManager", new Object[] { stringBuilder.toString() });
RemoteDebugManager.this.remoteWs = null;
debugHandler.sendEmptyMessage(-1000);
}
public void onFailure(ai param1ai, Throwable param1Throwable, ae param1ae) {
StringBuilder stringBuilder = new StringBuilder("remoteWsClient onFailure");
stringBuilder.append(param1Throwable.toString());
AppBrandLogger.d("RemoteDebugManager", new Object[] { stringBuilder.toString() });
debugHandler.sendEmptyMessage(-1000);
}
public void onMessage(ai param1ai, String param1String) {
StringBuilder stringBuilder = new StringBuilder("onMessage remoteWsClient ");
stringBuilder.append(param1String);
AppBrandLogger.d("RemoteDebugManager", new Object[] { stringBuilder.toString() });
if (TextUtils.equals(param1String, "entrustDebug")) {
if (debugHandler.hasMessages(-1))
debugHandler.removeMessages(-1);
debugHandler.sendEmptyMessage(1000);
return;
}
if (TextUtils.equals(param1String, "cancelDebug")) {
if (debugHandler.hasMessages(-1))
debugHandler.removeMessages(-1);
RemoteDebugManager.this.closeRemoteWs(param1String);
debugHandler.sendEmptyMessage(-1000);
return;
}
try {
final AppData appData;
JSONArray jSONArray;
String str1;
JSONObject jSONObject2 = new JSONObject(param1String);
String str2 = jSONObject2.optString("method");
JSONObject jSONObject1 = jSONObject2.optJSONObject("params");
int i = jSONObject2.optInt("id");
if (TextUtils.equals(str2, "AppData")) {
appData = AppData.parseJson(jSONObject1);
((JsRuntimeManager)AppbrandApplicationImpl.getInst().getService(JsRuntimeManager.class)).getCurrentRuntime().executeInJsThread(new JsContext.ScopeCallback() {
public void run(JsScopedContext param2JsScopedContext) {
try {
StringBuilder stringBuilder = new StringBuilder("var pageStacks = getCurrentPages();\nvar currentPages = pageStacks[pageStacks.length-1];\ncurrentPages.setData(");
stringBuilder.append(appData.data);
stringBuilder.append("); ");
param2JsScopedContext.eval(stringBuilder.toString(), null);
RemoteDebugManager.this.appDataReporter.addAppData(appData);
return;
} catch (Exception exception) {
DebugUtil.outputError("RemoteDebugManager", new Object[] { "AppData setData fail", exception });
return;
}
}
});
return;
}
if (TextUtils.equals(str2, "DOMStorage.getDOMStorageItems")) {
RemoteDebugManager.this.storageReporter.setStorageId(appData.optJSONObject("storageId"));
jSONArray = Storage.getKeys();
RemoteDebugManager.this.getDOMStorageItems(i, jSONArray);
return;
}
boolean bool = TextUtils.equals(str2, "DOMStorage.removeDOMStorageItem");
if (bool) {
str1 = jSONArray.optString("key");
bool = Storage.removeStorage(str1);
RemoteDebugManager.this.removeDOMStorageItem(i, bool, str1);
return;
}
if (TextUtils.equals(str2, "DOMStorage.setDOMStorageItem")) {
String str = str1.optString("key");
str1 = str1.optString("value");
try {
str2 = Storage.getValue(str);
bool = Storage.setValue(str, str1, "String");
RemoteDebugManager.this.setDOMStorageItem(i, bool, str, str2, str1);
return;
} catch (IOException iOException) {
return;
}
}
if (TextUtils.equals(str2, "DOMStorage.clear")) {
bool = Storage.clearStorage();
RemoteDebugManager.this.clearStorage(i, bool);
return;
}
} catch (JSONException jSONException) {}
DebugManager.getInst().sendMessageToCurrentWebview(param1String);
}
public void onOpen(ai param1ai, ae param1ae) {
AppBrandLogger.d("RemoteDebugManager", new Object[] { "onOpen remoteWsClient" });
RemoteDebugManager.this.remoteWs = param1ai;
}
});
}
public void removeDOMStorageItem(int paramInt, boolean paramBoolean, String paramString) throws JSONException {
sendMessageByRemoteWs(this.storageReporter.removeDOMStorageItem(paramInt, paramBoolean, paramString));
}
public void sendMessageByRemoteWs(String paramString) {
ai ai1 = this.remoteWs;
if (ai1 != null) {
ai1.b(paramString);
AppBrandLogger.d("RemoteDebugManager", new Object[] { paramString });
}
}
public void sendMessageToIDE(String paramString) {
ai ai1 = this.remoteWs;
if (ai1 != null) {
StringBuilder stringBuilder = new StringBuilder("__IDE__");
stringBuilder.append(paramString);
ai1.b(stringBuilder.toString());
AppBrandLogger.d("RemoteDebugManager", new Object[] { paramString });
}
}
public void setDOMStorageItem(int paramInt, boolean paramBoolean, String paramString1, String paramString2, String paramString3) throws JSONException {
sendMessageByRemoteWs(this.storageReporter.setDOMStorageItem(paramInt, paramBoolean, paramString1, paramString2, paramString3));
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\debug\RemoteDebugManager.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package system.dao;
import org.apache.ibatis.annotations.Param;
import system.model.School;
import java.util.List;
public interface SchoolMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
int insert(School record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
int insertSelective(School record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
School selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(School record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table school
*
* @mbg.generated
*/
int updateByPrimaryKey(School record);
School findBySchoolName(@Param("schoolName") String schoolName);
List<Integer> findByAreaIds(@Param("areaIds") List<Integer> areaIds);
List<School> findByAreaId(@Param("areaId")Integer areaId);
School findBySchoolCode(@Param("schoolCode")Integer schoolCode);
}
|
/**
* Copyright 2013-present febit.org (support@febit.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.febit.web.upload;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import jodd.io.FileUtil;
public class UploadFile {
public final String fieldName;
public final String fileName;
public final String contentType;
public final boolean valid;
public final int size;
public final boolean fileTooBig;
protected final File tempFile;
protected final byte[] data;
public UploadFile(MultipartRequestHeader header, boolean valid, int size, boolean fileTooBig, File tempFile, byte[] data) {
this.fieldName = header.fieldName;
this.fileName = header.fileName;
this.contentType = header.contentType;
this.valid = valid;
this.size = size;
this.fileTooBig = fileTooBig;
this.tempFile = tempFile;
this.data = data;
}
public boolean isInMemory() {
return data != null;
}
/**
* Deletes file uploaded item from disk or memory.
*/
public void delete() {
if (tempFile != null) {
tempFile.delete();
}
}
/**
* Writes file upload item to destination file.
*/
public File write(String destination) throws IOException {
return write(new File(destination));
}
/**
* Writes file upload item to destination file.
*/
public File write(File destination) throws IOException {
if (data != null) {
FileUtil.writeBytes(destination, data);
} else if (tempFile != null) {
FileUtil.move(tempFile, destination);
}
return destination;
}
/**
* Returns the content of file upload item.
*/
public byte[] getFileContent() throws IOException {
if (data != null) {
return data;
}
if (tempFile != null) {
return FileUtil.readBytes(tempFile);
}
return null;
}
public InputStream getInputStream() throws IOException {
if (data != null) {
return new ByteArrayInputStream(data);
}
if (tempFile != null) {
return new BufferedInputStream(new FileInputStream(tempFile));
}
return null;
}
}
|
package GUI;
import com.barcodelib.barcode.QRCode;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.Document;
import javax.swing.text.Element;
import ACFinal.*;
/**
*
* @author Carlos Alberto Mestas Escarcena
*/
public class Conexion extends javax.swing.JFrame {
Game game = new GameTresEnRaya();
PrintBoard printL = new PrintBoard(game);
static Socket s;
static ServerSocket ss;
static InputStreamReader isr;
static BufferedReader br;
static String message;
static String ipJugador1;
static String ipJugador2;
static String model1;
static String model2;
/**
* Creates new form NewJFrame
*/
public Conexion() {
initComponents();
setLocationRelativeTo(null);
setResizable(false);
setTitle("Games for all");
((JPanel)getContentPane()).setOpaque(false);
ImageIcon uno=new ImageIcon(this.getClass().getResource("/images/Barquito_de_papel2.jpg"));
JLabel fondo= new JLabel();
fondo.setIcon(uno);
getLayeredPane().add(fondo,JLayeredPane.FRAME_CONTENT_LAYER);
fondo.setBounds(0,0,uno.getIconWidth(),uno.getIconHeight());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
buttonAddPlayer1 = new javax.swing.JButton();
buttonAddPlayer2 = new javax.swing.JButton();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel1.setText("jLabel1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(515, 530));
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jTextArea1.setEnabled(false);
jTextArea1.setName("jTextArea1"); // NOI18N
jScrollPane1.setViewportView(jTextArea1);
buttonAddPlayer1.setText("Agregar Jugador 1");
buttonAddPlayer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddPlayer1ActionPerformed(evt);
}
});
buttonAddPlayer2.setText("Agregar Jugador 2");
buttonAddPlayer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonAddPlayer2ActionPerformed(evt);
}
});
jTextField2.setEnabled(false);
jTextField3.setEnabled(false);
jTextField3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField3ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Book Antiqua", 1, 20)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("GAMES FOR ALL");
jButton4.setText("Conectar");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jLabel3.setText("Ventana de acciones");
jButton1.setText("TRES EN RAYA");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(78, 78, 78)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(buttonAddPlayer2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField3))
.addGroup(layout.createSequentialGroup()
.addComponent(buttonAddPlayer1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextField2)))
.addGap(63, 63, 63))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(126, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(123, 123, 123))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(136, 136, 136)))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton1)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonAddPlayer1)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(buttonAddPlayer2)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(28, 28, 28)
.addComponent(jButton4)
.addGap(57, 57, 57)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void buttonAddPlayer1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddPlayer1ActionPerformed
try {
// Creacion del codigo QR, genera el codigo de acuerdo a la direccion IP de la computadora
// Tanto para el jugador 1 y para jugador 2 se genera el mismo codigo QR
// Porque ambos realizaran la conexion con la misma computadora
createQRCode();
// Creacion de la imagen
ImageIcon icon = new ImageIcon("src/images/QRCode.jpg");
// Muestra de la imagen
JOptionPane.showMessageDialog(null, "Escanea el código qr.\nJugador 1",
"JUGADOR 1", JOptionPane.INFORMATION_MESSAGE, icon);
} catch (Exception ex) {
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonAddPlayer1ActionPerformed
// Funciona de la misma manera que el boton anterior en la creacion y muestra del codigo QR
private void buttonAddPlayer2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddPlayer2ActionPerformed
try {
createQRCode();
ImageIcon icon = new ImageIcon("src/images/QRCode.jpg");
JOptionPane.showMessageDialog(null, "Escanea el código qr.\nJugador 2",
"JUGADOR 2", JOptionPane.INFORMATION_MESSAGE, icon);
} catch (Exception ex) {
Logger.getLogger(Conexion.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_buttonAddPlayer2ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// Realiza la conexion con las direcciones ip enviadas por los celulares
// Se extrae solamente la direccion IP del texto recibido
// Ya que se recibe la IP y el modelo del celular
ipJugador1 = jTextField2.getText().substring(0,13);
// Luego de recibir la direccion solamente seleccionamos el modelo del celular para mostrarlo
model1 = jTextField2.getText().substring(14,jTextField2.getText().length());
jTextField2.setText(jTextField2.getText().substring(13,jTextField2.getText().length()));
ipJugador2 = jTextField3.getText().substring(0,13);
model2 = jTextField3.getText().substring(14,jTextField2.getText().length());
jTextField3.setText(jTextField3.getText().substring(13,jTextField3.getText().length()));
System.out.println(ipJugador1+"\n"+ipJugador2);
System.out.println(model1+"\n"+model2);
try{
// Se crean dos sockes, con el mismo puerto pero con diferente direccion de envio
// Una direccion de envio para cada celular de acuerdo al jugador
Socket s1 = new Socket(ipJugador1,7801);
Socket s2 = new Socket(ipJugador2,7801);
PrintWriter pw1 = new PrintWriter(s1.getOutputStream());
PrintWriter pw2 = new PrintWriter(s2.getOutputStream());
// Mensaje enviado a cada celular, en cada celular aparecera un mensaje de celular conectado
pw1.write("Jugador 1 Conectado");
pw2.write("Jugador 2 Conectado");
pw1.flush();
pw2.flush();
pw1.close();
pw2.close();
s1.close();
s2.close();
}
catch(IOException e){
}
}//GEN-LAST:event_jButton4ActionPerformed
private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField3ActionPerformed
// Se envia el nombre del juego que se va a jugar, en este caso tres en raya
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try{
// Generacion de los sockets
Socket s1 = new Socket(ipJugador1,7801);
Socket s2 = new Socket(ipJugador2,7801);
PrintWriter pw1 = new PrintWriter(s1.getOutputStream());
PrintWriter pw2 = new PrintWriter(s2.getOutputStream());
// Se envia la informacion del juego
// Ya en android al recibir este mensaje se cambiara a otra actividad donde se
// encontrara la interfaz de Android
pw1.write("3eR");
pw2.write("3eR");
pw1.flush();
pw2.flush();
pw1.close();
pw2.close();
s1.close();
s2.close();
}
catch(IOException e){
}
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Conexion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
Conexion conexion = new Conexion();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Conexion().setVisible(true);
}
});
// El primer metodo donde vamos a recibir los datos
try{
// Creamos un socket con el puerto donde recibiremos los mensajes
ss = new ServerSocket(7800);
while(true){
s = ss.accept();
isr = new InputStreamReader(s.getInputStream());
br = new BufferedReader(isr);
message = br.readLine();
System.out.println(message);
// Se va imprimiendo los mensajes enviados
if(jTextArea1.getText().toString().equals("")){
jTextArea1.setText(message);
}
else{
jTextArea1.setText(jTextArea1.getText() + "\n" + message);
}
// Primeramente donde veremos la primera direccion y modelo
// En el caso de que este vacio lo considerara como jugador 1
if(jTextField2.getText().equals("")){
jTextField2.setText(message);
ipJugador1 = message;
System.out.println(ipJugador1);
}
// En el caso de que ya este lleno, se llenara con otros dos valores
else if(jTextField2.getText().equals(ipJugador1.toString())){
if(jTextField3.getText().equals("")){
jTextField3.setText(message);
ipJugador2 = message.substring(0,11);;
}
}
else{// if((jTextField2.getText().length() != 0) && (jTextField3.getText().length() != 0)){
conexion.sendMessage(message);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
// Metodo donde generamos el codigo QR
public void createQRCode() throws Exception{
String myLocalIPv4 = getLocalIPv4();
int udm = 0, resol = 72, rot = 0;
float mi = 0.000f, md = 0.000f, ms = 0.000f, min = 0.000f, tam = 5.00f;
try{
QRCode ipCode = new QRCode();
// Colocamos la informacion de la direccion IP de la computadora
ipCode.setData(myLocalIPv4);
ipCode.setDataMode(QRCode.MODE_BYTE);
ipCode.setUOM(udm);
ipCode.setLeftMargin(mi);
ipCode.setRightMargin(md);
ipCode.setTopMargin(ms);
ipCode.setBottomMargin(min);
ipCode.setResolution(resol);
ipCode.setRotate(rot);
ipCode.setModuleSize(tam);
// Se crea la imagen respectiva de la direccion ip
String file = System.getProperty("user.dir")+("/src/images/QRCode.jpg");
ipCode.renderBarcode(file);
}
catch(Exception e){
}
}
// Obtencion de la direccion IP de la computadora
public String getLocalIPv4() throws Exception{
InetAddress address = InetAddress.getLocalHost();
return address.getHostAddress();
}
public void sendMessage(String message){
System.out.println(message.substring(0,9));
if(message.substring(0,9).equals("Jugador 1")){
try{
Socket s2 = new Socket(ipJugador2,7801);
PrintWriter pw2 = new PrintWriter(s2.getOutputStream());
pw2.write(message);
pw2.flush();
pw2.close();
s2.close();
}
catch(IOException e){
}
}
if(message.substring(0,9).equals("Jugador 2")){
try{
Socket s2 = new Socket(ipJugador1,7801);
PrintWriter pw2 = new PrintWriter(s2.getOutputStream());
pw2.write(message);
pw2.flush();
pw2.close();
s2.close();
}
catch(IOException e){
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton buttonAddPlayer1;
private javax.swing.JButton buttonAddPlayer2;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private static javax.swing.JTextArea jTextArea1;
private static javax.swing.JTextField jTextField2;
private static javax.swing.JTextField jTextField3;
// End of variables declaration//GEN-END:variables
}
|
package geekbrains.lesson4_homework;
import java.util.Random;
import java.util.Scanner;
public class Lesson4 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
play(scanner, random);
}
static void play(Scanner scanner, Random random) {
char[][] field = getField();
drawField(field);
do {
doPlayerMove(scanner, field);
if (isFinal(field, 'X')) {
break;
}
doAIMove(random, field);
if (isFinal(field, 'O')) {
break;
}
drawField(field);
} while (true);
System.out.println("Final score");
drawField(field);
}
static boolean isFinal(char[][] field, char sign) {
if (isWin(field, sign)) {
String name = sign == 'X' ? "Player" : "AI";
System.out.println(String.format("%s won", name));
return true;
}
if (isDraw(field)) {
System.out.println("There is draw detected. Thanks god no one won!");
return true;
}
return false;
}
static boolean isWin(char[][] field, char sign) {
//Проверка горизонталей
for (int i = 0; i < field.length; i++) {
if (field[i][0] == sign && field[i][1] == sign && field[i][2] == sign) {
return true;
}
}
// Проверка вертикалей
for (int i = 0; i < field.length; i++) {
if (field[0][i] == sign && field[1][i] == sign && field[2][i] == sign) {
return true;
}
}
// Проверка диагоналей
{
if (field[0][0] == sign && field[1][1] == sign && field[2][2] == sign) {
return true;
}
if (field[0][2] == sign && field[1][1] == sign && field[2][0] == sign) {
return true;
}
}
return false;
}
static boolean isDraw(char[][] field) {
int count = field.length * field.length;
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field.length; j++) {
if (field[i][j] != '-') {
count--;
}
}
}
return count == 0;
}
static void doAIMove(Random random, char[][] field) {
int x, y;
do {
x = random.nextInt(3);
y = random.nextInt(3);
} while (field[x][y] != '-');
field[x][y] = 'O';
}
static void doPlayerMove(Scanner scanner, char[][] field) {
int x, y;
do {
x = getCoordinate(scanner, 'X');
y = getCoordinate(scanner, 'Y');
} while (field[x][y] != '-');
field[x][y] = 'X';
}
static int getCoordinate(Scanner scanner, char coordName) {
int coord;
do {
System.out.println(String.format("Please input %s-coordinate in range [1, 3] ...", coordName));
coord = scanner.nextInt() - 1;
} while (coord < 0 || coord > 2);
return coord;
}
static char[][] getField() {
return new char[][]{
{'-', '-', '-'},
{'-', '-', '-'},
{'-', '-', '-'}
};
}
static void drawField(char[][] field) {
for (int i = 0; i < field.length; i++) {
for (int j = 0; j < field.length; j++) {
System.out.print(field[i][j]);
}
System.out.println();
}
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public interface kk$b {
void a(float f);
void b(float f);
}
|
/*
* Copyright: 2020 forchange Inc. All rights reserved.
*/
package com.research.api.datasteam.window;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
/**
* @fileName: TumblingWindows.java
* @description: 滚动窗口
* @author: by echo huang
* @date: 2020-02-16 18:36
*/
public class TumblingWindows {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
//基于event时间特征配置,这里不能设置为event time,否则执行报错
// environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
DataStreamSource<String> data = environment.socketTextStream("localhost", 10001);
//指定event time或processing time滚动窗口 依赖于setStreamTimeCharacteristic设置类型
data.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
@Override
public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
String[] tokens = s.split(" ");
for (String token : tokens) {
collector.collect(new Tuple2<>(token, 1));
}
}
}).keyBy("f0")
.timeWindow(Time.seconds(5))
.sum("f1")
.print();
//按照数量来统计
/* data.map(new MapFunction<String, String>() {
@Override
public String map(String s) throws Exception {
return "wx:" + s;
}
}).keyBy((KeySelector<String, String>) value -> value)
.countWindow(3).sum(1)
.print();*/
environment.execute("tumbling windows");
}
}
|
/*
* This software is licensed under the MIT License
* https://github.com/GStefanowich/MC-Server-Protection
*
* Copyright (c) 2019 Gregory Stefanowich
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.theelm.sewingmachine.deathchests.mixins.Entities;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.decoration.ArmorStandEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.theelm.sewingmachine.interfaces.BackpackCarrier;
import net.theelm.sewingmachine.deathchests.interfaces.PlayerCorpse;
import net.theelm.sewingmachine.base.objects.PlayerBackpack;
import net.theelm.sewingmachine.utilities.EntityUtils;
import net.theelm.sewingmachine.utilities.nbt.NbtUtils;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Iterator;
import java.util.UUID;
/**
* Created on Jun 25 2023 at 7:58 PM.
* By greg in sewingmachine
*/
@Mixin(value = ArmorStandEntity.class, priority = 1)
public abstract class ArmorStandEntityMixin extends LivingEntity implements PlayerCorpse {
private UUID corpsePlayerUUID = null;
private NbtList corpsePlayerItems = null;
private NbtList corpsePlayerBackpack = null;
protected ArmorStandEntityMixin(EntityType<? extends LivingEntity> entityType, World world) {
super(entityType, world);
}
@Inject(at = @At("HEAD"), method = "interactAt", cancellable = true)
public void onPlayerInteract(PlayerEntity player, Vec3d vec3d, Hand hand, CallbackInfoReturnable<ActionResult> callback) {
// Armor Stand is a corpse
if (this.corpsePlayerUUID != null) {
// Return the items back to their owner
if (EntityUtils.canEntityTakeDeathChest(player, this.corpsePlayerUUID))
this.returnItemsToPlayer(player);
else {
// Deny if the corpse does not belong to this player
callback.setReturnValue(ActionResult.FAIL);
}
}
}
@Override
public void onPlayerCollision(PlayerEntity player) {
// If the corpse belongs to the player
if ( (this.corpsePlayerUUID != null) && player.getUuid().equals(this.corpsePlayerUUID)) {
this.returnItemsToPlayer(player);
return;
}
// Regular collision
super.onPlayerCollision(player);
}
@Override
public void setCorpseData(UUID owner, NbtList inventory, NbtList backpack) {
this.corpsePlayerUUID = owner;
this.corpsePlayerItems = inventory;
this.corpsePlayerBackpack = backpack;
}
private void giveCorpseItems(@NotNull final PlayerEntity player) {
Iterator<NbtElement> items;
// Get all of the items to give back
if (this.corpsePlayerItems != null) {
items = this.corpsePlayerItems.iterator();
while (items.hasNext()) {
// Create the item from the tag
ItemStack itemStack = ItemStack.fromNbt((NbtCompound) items.next());
// Try equipping the item if the slot is available
EquipmentSlot slot = null;
if (itemStack.getItem() instanceof ArmorItem && !EnchantmentHelper.hasBindingCurse(itemStack)) {
// If armor
slot = ((ArmorItem) itemStack.getItem()).getSlotType();
} else if (itemStack.getItem().equals(Items.SHIELD)) {
// If shield
slot = EquipmentSlot.OFFHAND;
}
// If slot is set, equip it there (If allowed)
if ((slot != null) && player.getEquippedStack(slot).getItem() == Items.AIR)
player.equipStack(slot, itemStack);
else // Add to the inventory (If not equipped)
player.getInventory().offerOrDrop(itemStack);
// Remove from the iterator (Tag list)
items.remove();
}
}
// Get all of the backpack items back
if (this.corpsePlayerBackpack != null) {
items = this.corpsePlayerBackpack.iterator();
while (items.hasNext()) {
// Create the item from the tag
ItemStack itemStack = ItemStack.fromNbt((NbtCompound) items.next());
PlayerBackpack backpack = ((BackpackCarrier) player).getBackpack();
// Attempt to put items into the backpack
if ((backpack == null) || (!backpack.insertStack(itemStack)))
player.getInventory().offerOrDrop(itemStack);
// Remove from the iterator (Tag list)
items.remove();
}
}
}
private void returnItemsToPlayer(@NotNull final PlayerEntity player) {
// Give the items back to the player
this.giveCorpseItems(player);
if (((this.corpsePlayerItems == null) || this.corpsePlayerItems.isEmpty()) && ((this.corpsePlayerBackpack == null) || this.corpsePlayerBackpack.isEmpty())) {
BlockPos blockPos = this.getBlockPos().up();
// Play sound
player.playSound(SoundEvents.ENTITY_ITEM_PICKUP, SoundCategory.BLOCKS, 1.0f, 1.0f);
// Spawn particles
((ServerWorld) this.getWorld()).spawnParticles(ParticleTypes.TOTEM_OF_UNDYING,
blockPos.getX() + 0.5D,
blockPos.getY() + 1.0D,
blockPos.getZ() + 0.5D,
150,
1.0D,
0.5D,
1.0D,
0.3D
);
// Remove the armor stand
this.discard();
}
}
@Inject(at=@At("TAIL"), method = "writeCustomDataToNbt")
public void onSavingData(NbtCompound tag, CallbackInfo callback) {
// Save the player warp location for restarts
if ( this.corpsePlayerUUID != null ) {
tag.putUuid("corpsePlayerUUID", this.corpsePlayerUUID);
if ((this.corpsePlayerItems != null) && (!this.corpsePlayerItems.isEmpty()))
tag.put("corpsePlayerItems", this.corpsePlayerItems);
if ((this.corpsePlayerBackpack != null) && (!this.corpsePlayerBackpack.isEmpty()))
tag.put("corpsePlayerBackpack", this.corpsePlayerBackpack);
}
}
@Inject(at=@At("TAIL"), method = "readCustomDataFromNbt")
public void onReadingData(NbtCompound tag, CallbackInfo callback) {
if ( NbtUtils.hasUUID(tag, "corpsePlayerUUID") ) {
this.corpsePlayerUUID = NbtUtils.getUUID(tag, "corpsePlayerUUID");
if (tag.contains("corpsePlayerItems", NbtElement.LIST_TYPE))
this.corpsePlayerItems = tag.getList("corpsePlayerItems", NbtElement.COMPOUND_TYPE);
if (tag.contains("corpsePlayerBackpack", NbtElement.LIST_TYPE))
this.corpsePlayerBackpack = tag.getList("corpsePlayerBackpack", NbtElement.COMPOUND_TYPE);
}
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.scan;
import android.os.ParcelUuid;
public final class ScanFilterCompat$a {
byte[] fNA;
byte[] fNB;
int fNC = -1;
byte[] fND;
byte[] fNE;
ParcelUuid fNG;
String fNv;
String fNw;
ParcelUuid fNx;
ParcelUuid fNz;
public final ScanFilterCompat$a a(ParcelUuid parcelUuid) {
this.fNx = parcelUuid;
this.fNG = null;
return this;
}
public final ScanFilterCompat aix() {
return new ScanFilterCompat(this.fNv, this.fNw, this.fNx, this.fNG, this.fNz, this.fNA, this.fNB, this.fNC, this.fND, this.fNE, (byte) 0);
}
}
|
/*
* Copyright 2015 Alexandre Terrasa <alexandre@moz-code.org>.
*
* 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 tree;
import com.google.java.contract.Ensures;
import com.google.java.contract.Requires;
public interface Tree<E> {
int size();
@Ensures("result == (size() == 0)")
boolean isEmpty();
boolean hasRoot();
@Requires("!hasRoot()")
@Ensures({
"hasRoot()",
"size() == old(size()) + 1",})
void setRoot(E rootValue);
@Requires("hasRoot()")
E getRoot();
@Requires("hasRoot()")
boolean hasNode(E nodeValue);
@Requires({
"hasRoot()",
"hasNode(parentNodeValue)",
"!hasNode(nodeValue)"
})
@Ensures({
"hasNode(nodeValue)",
"size() == old(size()) + 1"
})
void addNode(E parentNodeValue, E nodeValue);
}
|
package com.designpattern.structuralpattern.composite;
/**
* 组合模式测试类
*/
public class CompositeTest {
public static void main(String[] args) {
}
}
|
/*
3. Készítsük el a publikus geometry.Circle osztályt, mely egy kört fog ábrázolni! Az osztály megvalósítja a Figure interfész műveleteit.
a) Deklaráljunk három privát int adattagot, melyek a kör közepének koordinátáit és a kör sugarát tárolják!
b) Készítsünk egy konstruktort, mely paraméterül várja a kör középpontjának x, y koordinátáit és a kör sugarát, és ezekkel inicializálja az adattagokat!
c) Készítsünk egy alapértelmezett konstruktort is, mely a kör középpontját az origóba és a kör sugarát 1-re állítja!
d) Valósítsuk meg a Figure interfész műveleteit! Ezek a következők: move(), area(), compareTo() és show().
A show() eredményére egy lehetséges példa: "Circle at (2,4) radius: 5"
*/
package geometry;
public class Circle implements Figure {
private int x, y, r;
public Circle(int r, int x, int y) {
this.r = r;
this.x = x;
this.y = y;
}
public String show() {
// return "Circle at (" + x + ", " + y + "), radius: " + r;
return String.format("Circle at (%d, %d), radius: %d", x, y, r);
}
public void move(int dx, int dy) {
x += dx,
y += dy,
}
public double area() {
return Math.PI * r * r;
}
public int compareTo(Figure f) {
return this.area() ...;
}
}
|
package com.example.homestay_kha;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.example.homestay_kha.Adapers.Adapter_viewpaper_Home;
import com.example.homestay_kha.Model.Hotel_model;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener,
RadioGroup.OnCheckedChangeListener {
ViewPager viewPagerHome;
RadioButton btn_hotel_current, btn_history_route;
RadioGroup radioGroup_Home;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPagerHome = findViewById(R.id.viewpaper_Home);
btn_hotel_current = findViewById(R.id.hotel_current_btn);
btn_history_route= findViewById(R.id.history_btn);
radioGroup_Home = findViewById(R.id.radio_group_home);
Adapter_viewpaper_Home adapterViewpaperHome = new Adapter_viewpaper_Home(getSupportFragmentManager());
viewPagerHome.setAdapter(adapterViewpaperHome);
viewPagerHome.addOnPageChangeListener(this);
radioGroup_Home.setOnCheckedChangeListener(this);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
switch (position)
{
case 0:
btn_hotel_current.setChecked(true);
break;
case 1:
btn_history_route.setChecked(true);
break;
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case R.id.hotel_current_btn:
viewPagerHome.setCurrentItem(0);
break;
case R.id.history_btn:
viewPagerHome.setCurrentItem(1);
break;
}
}
}
|
package com.example.lib.event;
/**
* @Author jacky.peng
* @Date 2021/4/12 11:07 AM
* @Version 1.0
*/
public class FragmentEvent extends Event {
public static final String NAME_ON_VIEW_CREATED = "onViewCreated";
public static final String NAME_ON_VIEW_DESTROYED = "onViewDestroyed";
public static final String NAME_ON_VIEW_RESUMED = "onFragmentResumed";
private String activityName;
private String fragmentName;
private long onCreateTimeStamp;
private long onDestroyTimeStamp;
/**
* View在整个视图树中的唯一id
* 1.root->viewgroup->viewgroup->view
*/
private String viewId;
public String getActivityName() {
return activityName;
}
public long getOnCreateTimeStamp() {
return onCreateTimeStamp;
}
public long getOnDestroyTimeStamp() {
return onDestroyTimeStamp;
}
public FragmentEvent(String tag) {
this.tag = tag;
}
public FragmentEvent() {
}
public static class Builder {
private String activityName;
private String tag;
private String fragmentName;
private String viewPath;
private long onCreateTimeStamp;
private long onDestroyTimeStamp;
public Builder setTag(String tag) {
this.tag = tag;
return this;
}
public Builder setViewPath(String viewPath) {
this.viewPath = viewPath;
return this;
}
public Builder setActivityName(String activityName) {
this.activityName = activityName;
return this;
}
public Builder setOnCreateTimeStamp(long onCreateTimeStamp) {
this.onCreateTimeStamp = onCreateTimeStamp;
return this;
}
public Builder setFragmentName(String fragmentName) {
this.fragmentName = fragmentName;
return this;
}
public Builder setOnDestroyTimeStamp(long onDestroyTimeStamp) {
this.onDestroyTimeStamp = onDestroyTimeStamp;
return this;
}
public FragmentEvent build() {
FragmentEvent event = new FragmentEvent(this.tag);
event.activityName = this.activityName;
event.onCreateTimeStamp = this.onCreateTimeStamp;
event.onDestroyTimeStamp = this.onDestroyTimeStamp;
event.fragmentName = this.fragmentName;
return event;
}
}
}
|
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetNull {
public static void main(String[] args) {
Set<Integer> lhs = new LinkedHashSet<>();
lhs.add(null);
lhs.add(122);
lhs.add(133);
System.out.println(lhs);
}
}
|
package com.stark.netty.section_11.charpter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
* Created by Stark on 2018/3/15.
* TODO 暂时不知道他的作用
*
*/
public class Global {
public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
|
package com.example.xiaohei.newsdemo.weather.model;
import android.content.Context;
/**
*
* Created by xiaohei on 2017/4/22.
*/
public interface WeatherModel {
void loadWeatherData(String cityName, WeatherModelImpl.LoadWeatherListener listener);
void loadLocation(Context context, WeatherModelImpl.LoadLocationListener listener);
}
|
package com.kush.lib.expressions.factory;
import com.kush.lib.expressions.clauses.ConstantIntExpression;
class DefaultConstantIntExpression extends BaseTerminalExpression implements ConstantIntExpression {
private final int value;
public DefaultConstantIntExpression(int value) {
this.value = value;
}
@Override
public int getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(getValue());
}
}
|
package com.andyadc.seckill.infrastructure.crypto;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.util.ByteSource;
/**
* https://blog.swierczynski.net/2013/01/strong-passwords-hashing-wtih-apache-shiro
*/
public class CryptoUtil {
private static final int hashIterations = 2;
public static String encrypt(String username, String clearTextPassword) {
ByteSource salt = ByteSource.Util.bytes(username);
return hashAndSaltPassword(clearTextPassword, salt);
}
public static boolean match(String username, String clearTextPassword, String dbStoredHashedPassword) {
ByteSource byteSource = ByteSource.Util.bytes(username);
String hashedPassword = hashAndSaltPassword(clearTextPassword, byteSource);
return hashedPassword.equals(dbStoredHashedPassword);
}
public static void main(String[] args) {
ByteSource byteSource = getSalt();
System.out.println(byteSource.toHex());
String clearTextPassword = "123456";
String hashedPassword = hashAndSaltPassword(clearTextPassword, byteSource);
System.out.println(hashedPassword);
System.out.println(passwordsMatch(
"a3a6c659230fce75cc4d77f1cbaead2569939406eec1be5b7a2f37cc285d29aaed1a68f093466a25faa2886d787640a18e3dedefcf6ab592efdb9c457940df2e",
"fe00fc8b5fe6de665ce29be732a9f9a2",
clearTextPassword)
);
System.out.println("----------------------");
System.out.println(encrypt("adc", "123"));
System.out.println(match("adc", "123",
"0ac5f88f461440ff8e74bbe62b4942d45690ec3e3682715bc15399e019986bd6a1c1993de84deba221135832037f7b9e2decfe6676787d66bb976005f3e8037d"));
}
public static boolean passwordsMatch(String dbStoredHashedPassword, String salt, String clearTextPassword) {
ByteSource byteSource = ByteSource.Util.bytes(Hex.decode(salt));
String hashedPassword = hashAndSaltPassword(clearTextPassword, byteSource);
return hashedPassword.equals(dbStoredHashedPassword);
}
private static ByteSource getSalt() {
return new SecureRandomNumberGenerator().nextBytes();
}
private static String hashAndSaltPassword(String clearTextPassword, ByteSource salt) {
return new Sha512Hash(clearTextPassword, salt, hashIterations).toHex();
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.types.service.predicate;
import com.google.common.base.Preconditions;
import de.hybris.platform.cms2.servicelayer.services.AttributeDescriptorModelHelperService;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.core.model.type.AttributeDescriptorModel;
import de.hybris.platform.core.model.type.ComposedTypeModel;
import de.hybris.platform.jalo.Item;
import de.hybris.platform.servicelayer.type.TypeService;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import static org.apache.commons.lang3.StringUtils.isBlank;
import org.springframework.beans.factory.annotation.Required;
/**
* Predicate to test if an attribute type is assignable from the input <code>typeCode</code> passed from
* the configuration. If matches, will return true else false.
* Optionally it will check as well whether the declaring enclosing type is assignable from <code>enclosingTypeCode</code> passed from
* the configuration
*/
public class AssignableFromAttributePredicate implements Predicate<AttributeDescriptorModel>
{
private String typeCode;
private String enclosingTypeCode;
private AttributeDescriptorModelHelperService attributeDescriptorModelHelperService;
private TypeService typeService;
@Override
public boolean test(final AttributeDescriptorModel attributeDescriptor)
{
Preconditions.checkArgument(isNotBlank(this.getTypeCode()) || isNotBlank(this.getEnclosingTypeCode()), "either typeCode or enclosingTypeCode must be provided.");
final BiPredicate<String, Class<?>> isTypeOf = (providedTypeCode, modelClass) ->
{
ComposedTypeModel composedTypeForCode = getTypeService().getComposedTypeForCode(providedTypeCode);
Class<ItemModel> parentClass = getTypeService().getModelClass(composedTypeForCode);
return parentClass.isAssignableFrom(modelClass);
};
boolean isAttributeAssignableFrom = true;
if (isNotBlank(this.getTypeCode())){
isAttributeAssignableFrom = isTypeOf.test(getTypeCode(), getAttributeDescriptorModelHelperService().getAttributeClass(attributeDescriptor));
}
boolean isEnclosingTypeAssignableFrom = true;
if (isNotBlank(this.getEnclosingTypeCode())){
isEnclosingTypeAssignableFrom = isTypeOf.test(getEnclosingTypeCode(), getAttributeDescriptorModelHelperService().getDeclaringEnclosingTypeClass(attributeDescriptor));
}
return isAttributeAssignableFrom && isEnclosingTypeAssignableFrom;
}
protected String getTypeCode()
{
return typeCode;
}
public void setTypeCode(final String typeCode)
{
this.typeCode = typeCode;
}
protected String getEnclosingTypeCode()
{
return enclosingTypeCode;
}
public void setEnclosingTypeCode(String enclosingTypeCode)
{
this.enclosingTypeCode = enclosingTypeCode;
}
protected AttributeDescriptorModelHelperService getAttributeDescriptorModelHelperService()
{
return attributeDescriptorModelHelperService;
}
@Required
public void setAttributeDescriptorModelHelperService(
AttributeDescriptorModelHelperService attributeDescriptorModelHelperService)
{
this.attributeDescriptorModelHelperService = attributeDescriptorModelHelperService;
}
protected TypeService getTypeService()
{
return typeService;
}
@Required
public void setTypeService(final TypeService typeService)
{
this.typeService = typeService;
}
}
|
package thecardyard.teamcomrade.github.com.thecardyard;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends Activity{
Button button;
ImageView imageview;
TextView textView;
static final int CAM_REQUEST = 1;
private DBCommunicate db;
private String dbCall = "";
Activity act = this;
private Context c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
c = this;
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
imageview = findViewById(R.id.image_view);
textView = findViewById(R.id.tessdata);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RequestwritePerms();
Intent Picture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Picture.resolveActivity(getPackageManager()) != null) {
startActivityForResult(Picture, CAM_REQUEST);
}
createNew(c);
db.execute();
}
});
}
private void createNew(Context context){
db = new DBCommunicate(context, dbCall);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == CAM_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
File f = new File(this.getCacheDir(),"image");
try{
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 0, bytes);
fos.write(bytes.toByteArray());
fos.flush();
fos.close();
Tess ts = new Tess();
ts.Setup(this);
textView.setText(ts.executeOCR(f));
//ts.executeOCR(f);
imageview.setImageBitmap(imageBitmap);
}catch(IOException | NullPointerException e){
Log.v("Errors",e.toString());
}
}
}
public void RequestwritePerms(){
PermissionRequest.requestPermission(this.act);
}
}
|
/*
* Copyright 2005-2010 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 sdloader.util;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* テキストをフォーマットします。 テキスト中の${name}の部分を、nameをキーにしてプロパティから 値を取り出し、置換します。
*
* @author c9katayama
*/
public class TextFormatUtil {
private static final Pattern REPLACE_PATTERN = Pattern
.compile("\\$\\{[^}]*\\}");
public static String formatTextBySystemProperties(final String text) {
return formatTextByProperties(text, System.getProperties());
}
public static String formatTextByProperties(final String text,
final Properties prop) {
final Matcher m = REPLACE_PATTERN.matcher(text);
final StringBuffer buf = new StringBuffer();
while (m.find()) {
String key = trimKey(m.group());
String value = prop.getProperty(key);
if (value == null)
throw new RuntimeException("Property not found.property key="
+ key);
m.appendReplacement(buf, value);
}
m.appendTail(buf);
return buf.toString();
}
private static String trimKey(String key) {
String trimKey = key.substring(2);// &{
return trimKey.substring(0, trimKey.length() - 1);// }
}
}
|
package com.tencent.mm.plugin.sns;
public final class i$m {
public static final int appbrandcomm_sqlite_lint_whitelist = 2131099655;
public static final int enmicromsg_sqlite_lint_whitelist = 2131099688;
public static final int face_debug_pref = 2131099691;
public static final int settings_face_print = 2131099724;
public static final int settings_sns_background = 2131099740;
public static final int sns_premission = 2131099746;
public static final int snsmicromsg_sqlite_lint_whitelist = 2131099747;
public static final int sqlite_lint_whitelist = 2131099749;
public static final int tag_detail_pref = 2131099751;
}
|
package com.example.movierecommendation.model;
import java.util.List;
public class Movie {
public String Metascore;
public String BoxOffice;
public String Website;
public List<Rating> Ratings = null;
public String Runtime;
public String Language;
public String Rated;
public String Production;
public String Released;
public String Plot;
public String Director;
public String Title;
public String Actors;
public String Response;
public String Type;
public String Awards;
public String DVD;
public String Year;
public String Poster;
public String Country;
public String Genre;
public String Writer;
public String Error;
public String Name;
public String imdbVotes;
public String imdbID;
public String imdbRating;
public String totalSeasons;
public Boolean isLiked = false;
public float id;
@Override
public String toString() {
return "Movie{" +
"Metascore='" + Metascore + '\'' +
", BoxOffice='" + BoxOffice + '\'' +
", Website='" + Website + '\'' +
", Ratings=" + Ratings +
", Runtime='" + Runtime + '\'' +
", Language='" + Language + '\'' +
", Rated='" + Rated + '\'' +
", Production='" + Production + '\'' +
", Released='" + Released + '\'' +
", Plot='" + Plot + '\'' +
", Director='" + Director + '\'' +
", Title='" + Title + '\'' +
", Actors='" + Actors + '\'' +
", Response='" + Response + '\'' +
", Type='" + Type + '\'' +
", Awards='" + Awards + '\'' +
", DVD='" + DVD + '\'' +
", Year='" + Year + '\'' +
", Poster='" + Poster + '\'' +
", Country='" + Country + '\'' +
", Genre='" + Genre + '\'' +
", Writer='" + Writer + '\'' +
", Error='" + Error + '\'' +
", Name='" + Name + '\'' +
", imdbVotes='" + imdbVotes + '\'' +
", imdbID='" + imdbID + '\'' +
", imdbRating='" + imdbRating + '\'' +
", totalSeasons='" + totalSeasons + '\'' +
", isLiked=" + isLiked +
", id=" + id +
'}';
}
public Movie() {
}
}
|
package com.bytedance.sandboxapp.a.a.a;
import com.bytedance.sandboxapp.b.b.a;
import com.bytedance.sandboxapp.c.a.a.f;
import org.json.JSONArray;
import org.json.JSONObject;
public final class c {
private String a;
private Integer b;
private JSONObject c;
private String d;
private Boolean e;
private JSONArray f;
private String g;
private String h;
public static c a() {
return new c();
}
public final c a(Boolean paramBoolean) {
this.e = paramBoolean;
return this;
}
public final c a(Integer paramInteger) {
this.b = paramInteger;
return this;
}
public final c a(String paramString) {
this.a = paramString;
return this;
}
public final c a(JSONArray paramJSONArray) {
this.f = paramJSONArray;
return this;
}
public final c a(JSONObject paramJSONObject) {
this.c = paramJSONObject;
return this;
}
public final c b(String paramString) {
this.d = paramString;
return this;
}
public final f b() {
a a = new a();
a.a("state", this.a);
a.a("requestTaskId", this.b);
a.a("header", this.c);
a.a("statusCode", this.d);
a.a("isPrefetch", this.e);
a.a("__nativeBuffers__", this.f);
a.a("data", this.g);
a.a("errMsg", this.h);
return new f(a);
}
public final c c(String paramString) {
this.g = paramString;
return this;
}
public final c d(String paramString) {
this.h = paramString;
return this;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\a\a\a\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package ru.kappers.logic.controller;
import com.google.gson.Gson;
import com.ibm.icu.text.StringTransform;
import com.ibm.icu.text.Transliterator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import ru.kappers.model.Fixture;
import ru.kappers.model.catalog.Team;
import ru.kappers.model.dto.TeamBridgeDTO;
import ru.kappers.model.leonmodels.CompetitorLeon;
import ru.kappers.model.mapping.TeamBridge;
import ru.kappers.service.CompetitorLeonService;
import ru.kappers.service.FixtureService;
import ru.kappers.service.TeamBridgeService;
import ru.kappers.service.TeamService;
import java.util.*;
import java.util.stream.Collectors;
/**
* Контроллер предназначен для маппинга сущностей Команд: Team и CompetitorLeon
* @author Ashamaz Shomakhov
*/
@Slf4j
@RestController
@RequestMapping(value = "/rest/mapper")
public class EntityMapperController {
private static final String CYRILLIC_TO_LATIN = "Latin-Russian/BGN";
private static final Gson GSON = new Gson();
private final TeamService teamService;
private final CompetitorLeonService competitorService;
private final FixtureService fixtureService;
private final TeamBridgeService teamBridgeService;
private final StringTransform toLatinTranslit = Transliterator.getInstance(CYRILLIC_TO_LATIN);
@Autowired
public EntityMapperController(TeamService teamService, CompetitorLeonService competitorService, FixtureService fixtureService, TeamBridgeService teamBridgeService) {
this.teamService = teamService;
this.competitorService = competitorService;
this.fixtureService = fixtureService;
this.teamBridgeService = teamBridgeService;
}
/**
* getUnmappedRapidTeams возвращает не смапленные сущности Team из базы данных
*/
@ResponseBody
@RequestMapping(value = "/teams/unmapped/rapidteams", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Team> getUnmappedRapidTeams() {
log.debug("getUnmappedRapidTeams()...");
List<Integer> mappedIds = teamBridgeService.getAll().stream()
.map(s -> s.getRapidTeam().getId())
.collect(Collectors.toList());
return teamService.getAllByIdIsNotIn(mappedIds);
}
/**
* getUnmappedLeonCompetitors возвращает не смапленные сущности CompetitorLeon из базы данных
*/
@ResponseBody
@RequestMapping(value = "/teams/unmapped/competitors", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<CompetitorLeon> getUnmappedLeonCompetitors() {
log.debug("getUnmappedLeonCompetitors()...");
List<Long> mappedIds = teamBridgeService.getAll().stream()
.map(s -> s.getLeonCompetitor().getId())
.collect(Collectors.toList());
return competitorService.getAllByIdIsNotIn(mappedIds);
}
/**
* completeRapidTeamsFromExistFixtures получает все имеющиеся Fixture и сохраняет в сущности Team
* все команды, участвующие в этих событиях
*/
@ResponseBody
@RequestMapping(value = "/teams/getTeamsFromFixtures", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Set<Team> completeRapidTeamsFromExistFixtures() {
log.debug("completeRapidTeamsFromExistFixtures()...");
Set<Team> teamsFromFixtures = new HashSet<>();
List<Fixture> fixtureList = fixtureService.getAll();
for (Fixture f : fixtureList) {
Team byId = teamService.getById(f.getAwayTeamId());
if (byId == null) {
teamsFromFixtures.add(teamService.save(Team.builder()
.id(f.getAwayTeamId())
.name(f.getAwayTeam())
.build()));
}
byId = teamService.getById(f.getHomeTeamId());
if (byId == null) {
teamsFromFixtures.add(teamService.save(Team.builder()
.id(f.getHomeTeamId())
.name(f.getHomeTeam())
.build()));
}
}
return teamsFromFixtures;
}
/**
* tryMappingRapidTeamAndLeonCompetitor - метод получает все сущности Team и CompetitorLeon
* и пытается их смапить по названию через транслитерацию
*/
@ResponseBody
@RequestMapping(value = "/teams/map", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<Team, CompetitorLeon> tryMappingRapidTeamAndLeonCompetitor() {
log.debug("tryMappingRapidTeamAndLeonCompetitor()...");
final Set<String> rapidTeams = teamService.getAll().stream()
.map(Team::getName)
.collect(Collectors.toSet());
log.debug("tryMappingRapidTeamAndLeonCompetitor(): получено {} сущностей Team", rapidTeams.size());
final List<String> leonComps = competitorService.getAll().stream()
.map(CompetitorLeon::getName)
.collect(Collectors.toList());
log.debug("tryMappingRapidTeamAndLeonCompetitor(): получено {} сущностей CompetitorLeon", leonComps.size());
final Map<Team, CompetitorLeon> result = new HashMap<>(rapidTeams.size());
TeamBridge teamBridge;
for (String st : rapidTeams) {
if (leonComps.contains(st)) {
teamBridge = saveTeamBridge(teamService.getByName(st), competitorService.getByName(st));
result.put(teamBridge.getRapidTeam(), teamBridge.getLeonCompetitor());
} else {
String res = toLatinTranslit.transform(st);
if (leonComps.contains(res)) {
teamBridge = saveTeamBridge(teamService.getByName(st), competitorService.getByName(res));
result.put(teamBridge.getRapidTeam(), teamBridge.getLeonCompetitor());
}
}
}
return result;
}
/**
* saveMappedTeams - сохраняет в БД смапленную сущность, полученную через POST запрос с фронта
* Пример JSON который надо получить
* {
* "rapidTeam":"1088",
* "leonCompetitor":"281474976793815"
* }
*/
@RequestMapping(value = "/teams/save", method = RequestMethod.POST, headers = "Accept=application/json",
produces = MediaType.APPLICATION_JSON_VALUE)
public TeamBridge saveMappedTeams(@RequestBody String content) {
log.debug("saveMappedTeams(content: {})...", content);
TeamBridgeDTO bridge = GSON.fromJson(content, TeamBridgeDTO.class);
Team team = teamService.getById(Integer.parseInt(bridge.getRapidTeam()));
CompetitorLeon competitorLeon = competitorService.getById(Long.parseLong(bridge.getLeonCompetitor()));
return saveTeamBridge(team, competitorLeon);
}
private TeamBridge saveTeamBridge(Team team, CompetitorLeon competitor) {
return teamBridgeService.save(TeamBridge.builder()
.rapidTeam(team)
.leonCompetitor(competitor)
.build());
}
}
|
package com.timebusker.utils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.io.Serializable;
/**
* @DESC:MongoDBPageable:分页实现类
* @author:timebusker
* @date:2018/9/7
*/
public class MongoDBPageable implements Pageable, Serializable {
private Integer pagenum = 1;
private Integer pagesize = 10;
private Sort sort = null;
public MongoDBPageable() {
}
public MongoDBPageable(Integer pagenum) {
this.pagenum = pagenum;
}
public MongoDBPageable(Integer pagenum, Integer pagesize) {
this.pagenum = pagenum;
this.pagesize = pagesize;
}
public MongoDBPageable(Integer pagenum, Integer pagesize, Sort sort) {
this.pagenum = pagenum;
this.pagesize = pagesize;
this.sort = sort;
}
@Override
public int getPageNumber() {
return 0;
}
@Override
public int getPageSize() {
return getPagesize();
}
@Override
public int getOffset() {
return (getPagenum() - 1) * getPageSize();
}
@Override
public Sort getSort() {
return sort;
}
@Override
public Pageable next() {
return null;
}
@Override
public Pageable previousOrFirst() {
return null;
}
@Override
public Pageable first() {
return null;
}
@Override
public boolean hasPrevious() {
return false;
}
public Integer getPagenum() {
return pagenum;
}
public void setPagenum(Integer pagenum) {
this.pagenum = pagenum;
}
public Integer getPagesize() {
return pagesize;
}
public void setPagesize(Integer pagesize) {
this.pagesize = pagesize;
}
public void setSort(Sort sort) {
this.sort = sort;
}
}
|
package com.mango.leo.zsproject.industrialservice.createrequirements.carditems.presenter;
import android.content.Context;
/**
* Created by admin on 2018/5/22.
*/
public interface UpdateItemPresenter {
void visitUpdateItem(Context context ,int type ,Object o);
}
|
package com.bridgeit.metadata;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
public class ResultSetMetaDataDemo {
public static void main(String[] args) {
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
PreparedStatement preparedStatement=connection.prepareStatement("select * from login");
ResultSet resultSet=preparedStatement.executeQuery();
ResultSetMetaData resultSetMetaData=resultSet.getMetaData();
System.out.println("Total columns: "+resultSetMetaData.getColumnCount());
System.out.println("Column Name of 1st column: "+resultSetMetaData.getColumnName(2));
System.out.println("Column Type Name of 1st column: "+resultSetMetaData.getColumnTypeName(1));
connection.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
|
package com.hpg.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("Comment")
public class CommentController {
}
|
package com.danielsandrutski.convert.namedata;
/**
* Создано DanielSand 03.11.2017
* Класс, представляющий структуру наименования разрядов больших или равных тысячи
* @version 1.0
* @autor Daniel Sandrutski
*/
public class BigDigit {
/** Род наименования (false - мужской, true - женский) */
int sex;
/** Наименование для единственного числа */
String one;
/** Наименование для чисел от 2 до 4 */
String twoToFour;
/** Наименование для чисел больших 4 */
String another;
/**
* Конструктор класса по умолчанию
*/
public BigDigit() { }
/**
* Конструктор класса, инициализирующий все поля принимаемыми значениями
* @param sex Род наименования (false - мужской, true - женский)
* @param one Наименование для единственного числа
* @param twoToFour Наименование для чисел от 2 до 4
* @param another Наименование для чисел больших 4
*/
BigDigit(int sex, String one, String twoToFour, String another) {
this.sex = sex;
this.one = one;
this.twoToFour = twoToFour;
this.another = another;
}
/** Метод, позволяющий получить род наименования (false - мужской, true - женский)*/
public int getSex() {
return sex;
}
/** Метод, позволяющий получить наименование для единственного числа */
public String getOne() {
return one;
}
/** Метод, позволяющий получить наименование для чисел от 2 до 4 */
public String getTwoToFour() {
return twoToFour;
}
/** Метод, позволяющий получить наименование для чисел больших 4 */
public String getAnother() {
return another;
}
/** Метод, позволяющий задать род наименования (false - мужской, true - женский)*/
public void setSex(int sex) {
this.sex = sex;
}
/** Метод, позволяющий задать наименование для единственного числа */
public void setOne(String one) {
this.one = one;
}
/** Метод, позволяющий задать наименование для чисел от 2 до 4 */
public void setTwoToFour(String twoToFour) {
this.twoToFour = twoToFour;
}
/** Метод, позволяющий задать наименование для чисел больших 4 */
public void setAnother(String another) {
this.another = another;
}
}
|
package sample;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Main extends Application {
/*
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}*/
Label response;
public void start(Stage myStage)
{
myStage.setTitle("ButtonImageDemo");
FlowPane rootNode = new FlowPane(10,10);
rootNode.setAlignment(Pos.CENTER);
Scene myScene = new Scene(rootNode,500,500);
myStage.setScene(myScene);
myStage.setResizable(false);
response =new Label("Push A Button");
ImageView hourGlassIV=new ImageView("hourglass.png");
Button myButton = new Button("hourglass",hourGlassIV);
Button myButton2 = new Button("Analog Clock",new ImageView("analog.jpg"));
myButton.setContentDisplay(ContentDisplay.TOP);
myButton2.setContentDisplay(ContentDisplay.TOP);
myButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
response.setText("HourGlass Pressed.");
}
});
myButton2.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
response.setText("Analog Clock Pressed.");
}
});
rootNode.getChildren().addAll(myButton,myButton2,response);
myStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
|
package 자바기본;
public class 데이터타입 {
public static void main(String[] args) {
// 기본데이터 타입: 정수, 실수, 문자, 논리=값
// 참조데이터 타입: 나머지 다, 배열, 클래스=주소,...
// 정수데이터 타입
byte b = 100; // ~128~127, 1byte, 8bit의 모음
// bit(비트) : 신호 하나, 1/0
// @ : 0,1 (2개)
// @@ : 00, 01, 10, 11 (4개)
// @@@ : 000, 001, ...(8개)
// @@@@@@@@ : (256개) -128~127
short s = 30000; // 2byte +-3만
int i = 100000000; // 4byte +-21억
long l = 2200000000L; // 8byte // 220000000L;
double d = 4.456789123456; // 8byte
float f = 1.234567F; // 1.234567f
char c = 'A'; // 2byte
System.out.println(c + 1);
boolean bo = true; // false; // 1byte
}
}
|
package com.sgic.library.client;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sgic.library.model.Classification;
import com.sgic.library.service.ClassificationService;
import com.sgic.library.service.impl.ClassificationServiceImpl;
public class Test {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("SpringConfig.xml");
ClassificationService classificationService = context.getBean("classificationService",
ClassificationServiceImpl.class);
Classification classification = new Classification();
classification.setClassificationName("maths_ne");
classificationService.createClassification(classification);
System.out.println("Save");
}
}
|
package com.example.springweb.mapper;
import com.example.springweb.dao.AppUser;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface AppMapper {
@Select("select * from app ")
@Results({
@Result(property = "name", column = "name"),
@Result(property = "class_1", column = "class1"),
@Result(property = "class_2", column = "class2"),
@Result(property = "class_3", column = "class3"),
@Result(property = "level_1", column = "level1"),
@Result(property = "level_2", column = "level2"),
@Result(property = "level_3", column = "level3")
})
List<AppUser> findAll();
@Insert("insert into app(name,class1,class2,class3,level1,level2,level3) values(#{name},#{class_1},#{class_2},#{class_3},#{level_1},#{level_2},#{level_3})")
void insert(AppUser appUser);
@Select("select * from app where name = #{name}")
@Results({
@Result(property = "name",column = "name"),
@Result(property = "class_1", column = "class1"),
@Result(property = "class_2", column = "class2"),
@Result(property = "class_3", column = "class3"),
@Result(property = "level_1", column = "level1"),
@Result(property = "level_2", column = "level2"),
@Result(property = "level_3", column = "level3")
})
AppUser getOne(String name);
@Update("update app set name = #{name}, class1 = #{class_1}, class2 = #{class_2}, class3 = #{class_3}, level1 = #{level_1}, level2 = #{level_2}, level3 = #{level_3}, where name = #{name}")
void updateByID(AppUser appUser);//UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
@Delete("delete from app where name = #{name}")
void deleteByName(String name);//DELETE FROM 表名称 WHERE 列名称 = 值
}
|
package com.msir.service;
import com.msir.pojo.UserDO;
import java.util.Set;
/**
* Created by HSH on 2017/7/10.
*/
public interface ITestService {
int query();
UserDO queryInfoByUsername(String userName);
/**
* 获取用户的角色
* @param userName
* @return
*/
Set<String> getUserRoles(String userName);
/**
* 获取用户的权限
* @param userName
* @return
*/
Set<String> getUserPermissions(String userName);
}
|
package com.hesoyam.pharmacy.pharmacy.exceptions;
public class InvalidPharmacyCreateRequest extends Exception{
public InvalidPharmacyCreateRequest(String message){
super(message);
}
}
|
package com.zitiger.plugin.xdkt.coder.generator;
import com.zitiger.plugin.xdkt.coder.model.TableInfo;
/**
*
*
* @author linglh
* @version 2.12.0 on 2018/9/24
*/
public class DTOGenerator extends BaseGenerator {
@Override
protected String getModuleName() {
return "facade";
}
@Override
protected String getFileName(TableInfo tableInfo) {
return tableInfo.getClassName() + "DTO.java";
}
@Override
public String getTemplateName() {
return "DTO.java";
}
@Override
protected String getPackageName() {
return super.getPackageName() + ".dto";
}
}
|
package org.spring.fom.support.task.parse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
/**
*
* @author shanhm1991@163.com
*
*/
class PatternUtil {
private static Map<String, Pattern> patternMap = new ConcurrentHashMap<>();
private static Pattern get(String regex){
Pattern pattern = patternMap.get(regex);
if(pattern != null){
return pattern;
}
pattern = Pattern.compile(regex);
patternMap.put(regex, pattern);
return pattern;
}
public static boolean match(String regex, String target){
if(StringUtils.isBlank(regex)){
return true;
}
return get(regex).matcher(target).matches();
}
}
|
package org.fao.unredd.api.model.geostore;
import it.geosolutions.geostore.services.dto.search.AndFilter;
import it.geosolutions.geostore.services.dto.search.BaseField;
import it.geosolutions.geostore.services.dto.search.CategoryFilter;
import it.geosolutions.geostore.services.dto.search.FieldFilter;
import it.geosolutions.geostore.services.dto.search.SearchFilter;
import it.geosolutions.geostore.services.dto.search.SearchOperator;
import it.geosolutions.geostore.services.rest.GeoStoreClient;
import it.geosolutions.unredd.geostore.model.UNREDDCategories;
import org.fao.unredd.api.model.LayerUpdates;
public class GeostoreLayerLayerUpdates extends AbstractGeostoreLayerUpdateList
implements LayerUpdates {
private GeoStoreClient geostoreClient;
private long layerId;
public GeostoreLayerLayerUpdates(Long layerId, GeoStoreClient geostoreClient) {
this.layerId = layerId;
this.geostoreClient = geostoreClient;
}
@Override
protected GeoStoreClient getGeostoreClient() {
return geostoreClient;
}
@Override
protected SearchFilter getFilter() {
return new AndFilter(
new CategoryFilter(UNREDDCategories.LAYERUPDATE.getName(),
SearchOperator.EQUAL_TO), new FieldFilter(BaseField.ID,
Long.toString(layerId), SearchOperator.EQUAL_TO));
}
}
|
package asu.shell.sh.commands;
@Cmd("ls")
public class LS extends ShellCommandWrapper {
public LS() {
super("ls");
}
}
|
public class supercons {
supercons() {
System.out.println("no-arg constructor of parent class");
}
supercons(String str) {
System.out.println("paramaterized constructor of parent class");
}
}
|
package org.fuserleer.ledger.events;
import java.util.Objects;
import org.fuserleer.ledger.Block;
public class BlockCommitEvent extends BlockEvent
{
public BlockCommitEvent(final Block block)
{
super(Objects.requireNonNull(block, "Block is null"));
}
}
|
package com.designPattern.creational.prototype;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Netflix {
private static Map<String, List<? extends PrototypeCapable>> CONTENT_MAP;
static {
System.out.println("Start Loading Data in Prototype Object");
CONTENT_MAP = new HashMap<>();
List<Movie> movies = new ArrayList<>();
movies.addAll(Arrays.asList(new Movie("Interstellar"), new Movie("Batman Begins"), new Movie("Avengers")));
CONTENT_MAP.put("movies", movies);
List<TVShow> tvShows = Arrays.asList(new TVShow("Friends"), new TVShow("Big Bang Theory"), new TVShow("Breaking Bad"));
CONTENT_MAP.put("tvShows", tvShows);
List<WebSeries> webSeries = new ArrayList<>();
webSeries.addAll(Arrays.asList(new WebSeries("Sacred Games"), new WebSeries("Ghoul"), new WebSeries("Bard of Blood")));
CONTENT_MAP.put("webSeries", webSeries);
System.out.println("Data Loaded in Prototype Object - " + CONTENT_MAP);
System.out.println();
}
public static List<PrototypeCapable> getContent(String type) throws CloneNotSupportedException {
List<PrototypeCapable> contents = new ArrayList<>();
for(PrototypeCapable content : CONTENT_MAP.get(type))
contents.add(((PrototypeCapable) content).clone());
return contents;
}
}
|
package ec.com.yacare.y4all.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.TimeZone;
import ec.com.yacare.y4all.asynctask.ws.GuardarFotoEquipoAsyncTask;
import ec.com.yacare.y4all.lib.asynctask.hotspot.ComandoHotSpotScheduledTask;
import ec.com.yacare.y4all.lib.enumer.TipoConexionEnum;
import ec.com.yacare.y4all.lib.enumer.TipoEquipoEnum;
import ec.com.yacare.y4all.lib.resources.YACSmartProperties;
import ec.com.yacare.y4all.lib.sqllite.EquipoDataSource;
import ec.com.yacare.y4all.lib.tareas.EnviarComandoThread;
import ec.com.yacare.y4all.lib.util.AudioQueu;
import static ec.com.yacare.y4all.activities.R.id.nombreDispositivo;
public class PreferenciasActivity extends FragmentActivity {
private ToggleButton toggleApertura;
private ToggleButton toggleSensor;
private ToggleButton toggleLuzExterna;
private ToggleButton toggleLuzWifi;
private ToggleButton toggleTono;
private ToggleButton togglePuertos;
private ToggleButton toggleTimbreExterno;
private ToggleButton toggleModo;
private ToggleButton toggleWifi;
private ToggleButton toggleVolumenAlto;
private CheckBox checkBoxVecesTimbre;
private EditText editMensajeTimbrar;
private EditText editClavePuerta;
private EditText editNombreWifi;
private EditText editClaveWifi;
private EditText editMensajeApertura;
private EditText editMensajePuerta;
private TextView txtTipoVozSeleccionada, txtTiempoEncenderLuz, txtValorEncenderLuz;
private String codigoVoz;
private ArrayList<String> voces;
private ArrayList<String> tiempo;
private Button btnGuardarPreferencias, btnReiniciarNumeroSerie;
private ImageButton btnPlay;
private DatosAplicacion datosAplicacion;
private String chosenRingtone = "";
private String clavePuerta;
private ImageButton btnProfileDispositivo;
private ImageView fotoPerfilDispositivo;
private String userChoosenTask;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1, PIC_CROP = 2;
Boolean mensajeWifi = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setRequestedOrientation(AudioQueu.getRequestedOrientation());
setContentView(R.layout.ac_preferences);
if (isScreenLarge()) {
onConfigurationChanged(getResources().getConfiguration());
} else {
AudioQueu.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
datosAplicacion = (DatosAplicacion) getApplicationContext();
fotoPerfilDispositivo = (ImageView) findViewById(R.id.fotoPerfilDispositivo);
Bitmap bitmap ;
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie()+".jpg");
if(file.exists()){
Bitmap bmImg = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Y4Home/" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() + ".jpg");
if(bmImg != null){
File foto = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() +".jpg");
if(foto.exists()){
bmImg = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() +".jpg");
if(bmImg != null){
mostrarImagen(fotoPerfilDispositivo, bmImg);
}
}
}
}else {
bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.usuario)).getBitmap();
mostrarImagen(fotoPerfilDispositivo, bitmap);
}
btnProfileDispositivo = (ImageButton) findViewById(R.id.btnProfileDispositivo);
btnProfileDispositivo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CharSequence[] items = { "Tomar Foto", "Galeria",
"Cancelar" };
AlertDialog.Builder builder = new AlertDialog.Builder(PreferenciasActivity.this);
builder.setTitle("Foto de Perfil");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Tomar Foto")) {
userChoosenTask="Tomar Foto";
cameraIntent();
} else if (items[item].equals("Galeria")) {
userChoosenTask="Galeria";
galleryIntent();
} else if (items[item].equals("Cancelar")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
toggleApertura = (ToggleButton) findViewById(R.id.toggleApertura);
toggleSensor = (ToggleButton) findViewById(R.id.toggleSensor);
toggleLuzExterna = (ToggleButton) findViewById(R.id.toggleLuzExterna);
toggleLuzWifi = (ToggleButton) findViewById(R.id.toggleLuzWifi);
toggleTono = (ToggleButton) findViewById(R.id.toggleTono);
togglePuertos = (ToggleButton) findViewById(R.id.togglePuertos);
toggleTimbreExterno = (ToggleButton) findViewById(R.id.toggleTimbreExterno);
toggleModo = (ToggleButton) findViewById(R.id.toggleModo);
toggleWifi = (ToggleButton) findViewById(R.id.toggleWifi);
toggleVolumenAlto = (ToggleButton) findViewById(R.id.toggleVolumenAlto);
checkBoxVecesTimbre = (CheckBox) findViewById(R.id.checkBoxVecesTimbre);
editMensajeTimbrar = (EditText) findViewById(R.id.editMensajeTimbrar);
editClavePuerta = (EditText) findViewById(R.id.editClavePuerta);
editNombreWifi = (EditText) findViewById(R.id.editNombreWifi);
editMensajeApertura = (EditText) findViewById(R.id.editMensajeApertura);
editClaveWifi = (EditText) findViewById(R.id.editClaveWifi);
editMensajePuerta = (EditText) findViewById(R.id.editMensajePuerta);
editClavePuerta.setText("");
txtTipoVozSeleccionada = (TextView) findViewById(R.id.txtTipoVozSeleccionada);
txtTiempoEncenderLuz = (TextView) findViewById(R.id.txtTiempoEncenderLuz);
txtValorEncenderLuz = (TextView) findViewById(R.id.txtValorEncenderLuz);
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnGuardarPreferencias = (Button) findViewById(R.id.btnGuardarPreferencias);
btnReiniciarNumeroSerie = (Button) findViewById(R.id.btnReiniciarNumeroSerie);
btnReiniciarNumeroSerie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
String datosConfT = "Z99" //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";";
EnviarComandoThread enviarComandoThread = new EnviarComandoThread(PreferenciasActivity.this, datosConfT, null,
null, null, datosAplicacion.getEquipoSeleccionado().getIpLocal(), YACSmartProperties.PUERTO_COMANDO_DEFECTO, null);
enviarComandoThread.start();
}
});
if(datosAplicacion.getEquipoSeleccionado().getTiempoEncendidoLuz() == null ){
txtValorEncenderLuz.setText("5 min");
}else{
txtValorEncenderLuz.setText( datosAplicacion.getEquipoSeleccionado().getTiempoEncendidoLuz() / 60 / 1000 + " min" );
}
txtValorEncenderLuz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Typeface fontRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PreferenciasActivity.this);
LayoutInflater inflater1 = getLayoutInflater();
View convertView = (View) inflater1.inflate(R.layout.seleccionar_equipo, null);
View convertViewTitulo = (View) inflater1.inflate(R.layout.seleccionar_equipo_titulo, null);
TextView titulo = (TextView) convertViewTitulo.findViewById(R.id.titulo);
titulo.setText("Seleccione el tiempo");
titulo.setTypeface(fontRegular);
alertDialog.setCustomTitle(convertViewTitulo);
alertDialog.setView(convertView);
tiempo = new ArrayList<String>();
tiempo.add("1 min");
tiempo.add("2 min");
tiempo.add("3 min");
tiempo.add("4 min");
tiempo.add("5 min");
ArrayAdapter<String> adapterVoces = new ArrayAdapter<String>( getApplicationContext(), R.layout.li_mensaje_texto,R.id.nombreMensaje, tiempo);
alertDialog.setCancelable(true);
alertDialog.setSingleChoiceItems(adapterVoces, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
txtValorEncenderLuz.setText(tiempo.get(which));
datosAplicacion.getEquipoSeleccionado().setTiempoEncendidoLuz((which + 1) * 60 * 1000);
dialog.dismiss();
}
});
alertDialog.show();
}
});
txtTiempoEncenderLuz.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Typeface fontRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PreferenciasActivity.this);
LayoutInflater inflater1 = getLayoutInflater();
View convertView = (View) inflater1.inflate(R.layout.seleccionar_equipo, null);
View convertViewTitulo = (View) inflater1.inflate(R.layout.seleccionar_equipo_titulo, null);
TextView titulo = (TextView) convertViewTitulo.findViewById(R.id.titulo);
titulo.setText("Seleccione el tiempo");
titulo.setTypeface(fontRegular);
alertDialog.setCustomTitle(convertViewTitulo);
alertDialog.setView(convertView);
tiempo = new ArrayList<String>();
tiempo.add("1 min");
tiempo.add("2 min");
tiempo.add("3 min");
tiempo.add("4 min");
tiempo.add("5 min");
ArrayAdapter<String> adapterVoces = new ArrayAdapter<String>( getApplicationContext(), R.layout.li_mensaje_texto,R.id.nombreMensaje, tiempo);
alertDialog.setCancelable(true);
alertDialog.setSingleChoiceItems(adapterVoces, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
txtValorEncenderLuz.setText(tiempo.get(which));
datosAplicacion.getEquipoSeleccionado().setTiempoEncendidoLuz((which + 1) * 60 * 1000);
dialog.dismiss();
}
});
alertDialog.show();
}
});
if(datosAplicacion.getEquipoSeleccionado().getPuerta() != null && datosAplicacion.getEquipoSeleccionado().getPuerta().equals("1")){
toggleApertura.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getSensor() != null && datosAplicacion.getEquipoSeleccionado().getSensor().equals("1")){
toggleSensor.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getLuz() != null && datosAplicacion.getEquipoSeleccionado().getLuz().equals("1")){
toggleLuzExterna.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getLuzWifi() != null && datosAplicacion.getEquipoSeleccionado().getLuzWifi().equals("1")){
toggleLuzWifi.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getTono() != null && !datosAplicacion.getEquipoSeleccionado().getTono().equals("0")){
toggleTono.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getPuertoActivo() != null && datosAplicacion.getEquipoSeleccionado().getPuertoActivo().equals("1")){
togglePuertos.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getVolumen() != null && datosAplicacion.getEquipoSeleccionado().getVolumen().equals(1)){
toggleVolumenAlto.setChecked(true);
}
if(datosAplicacion.getEquipoSeleccionado().getTimbreExterno() != null && datosAplicacion.getEquipoSeleccionado().getTimbreExterno().equals("1")){
toggleTimbreExterno.setChecked(true);
checkBoxVecesTimbre.setVisibility(View.VISIBLE);
checkBoxVecesTimbre.setEnabled(true);
}else if(datosAplicacion.getEquipoSeleccionado().getTimbreExterno() != null && datosAplicacion.getEquipoSeleccionado().getTimbreExterno().equals("2")){
toggleTimbreExterno.setChecked(true);
checkBoxVecesTimbre.setButtonDrawable(android.R.drawable.checkbox_on_background);
checkBoxVecesTimbre.setVisibility(View.VISIBLE);
checkBoxVecesTimbre.setEnabled(true);
checkBoxVecesTimbre.setChecked(true);
}
toggleTimbreExterno.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
checkBoxVecesTimbre.setVisibility(View.VISIBLE);
checkBoxVecesTimbre.setEnabled(true);
}else{
checkBoxVecesTimbre.setVisibility(View.GONE);
}
}
});
checkBoxVecesTimbre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxVecesTimbre.setButtonDrawable(android.R.drawable.checkbox_on_background);
}else{
checkBoxVecesTimbre.setButtonDrawable(android.R.drawable.checkbox_off_background);
}
}
});
if(datosAplicacion.getEquipoSeleccionado().getModo() != null && datosAplicacion.getEquipoSeleccionado().getModo().equals(YACSmartProperties.MODO_WIFI)){
toggleWifi.setChecked(true);
}else{
toggleWifi.setChecked(false);
}
if(datosAplicacion.getEquipoSeleccionado().getVozMensaje() != null){
if(datosAplicacion.getEquipoSeleccionado().getVozMensaje().equals(YACSmartProperties.VOZ_HOMBRE1) ){
txtTipoVozSeleccionada.setText("Voz de Hombre");
}else if(datosAplicacion.getEquipoSeleccionado().getVozMensaje().equals(YACSmartProperties.VOZ_MUJER2)){
txtTipoVozSeleccionada.setText("Voz de Mujer Latina");
}else{
txtTipoVozSeleccionada.setText("Voz de Mujer");
}
codigoVoz = datosAplicacion.getEquipoSeleccionado().getVozMensaje();
}else{
txtTipoVozSeleccionada.setText("Voz de Mujer Latina");
codigoVoz = YACSmartProperties.VOZ_MUJER2;
}
txtTipoVozSeleccionada.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Typeface fontRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
AlertDialog.Builder alertDialog = new AlertDialog.Builder(PreferenciasActivity.this);
LayoutInflater inflater1 = getLayoutInflater();
View convertView = (View) inflater1.inflate(R.layout.seleccionar_equipo, null);
View convertViewTitulo = (View) inflater1.inflate(R.layout.seleccionar_equipo_titulo, null);
TextView titulo = (TextView) convertViewTitulo.findViewById(R.id.titulo);
titulo.setText("Seleccione el tipo de voz");
titulo.setTypeface(fontRegular);
alertDialog.setCustomTitle(convertViewTitulo);
alertDialog.setView(convertView);
voces = new ArrayList<String>();
voces.add("Voz de Hombre");
voces.add("Voz de Mujer Latina");
voces.add("Voz de Mujer");
ArrayAdapter<String> adapterVoces = new ArrayAdapter<String>( getApplicationContext(), R.layout.li_mensaje_texto,R.id.nombreMensaje, voces );
alertDialog.setCancelable(true);
alertDialog.setSingleChoiceItems(adapterVoces, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == 0){
txtTipoVozSeleccionada.setText("Voz de Hombre");
codigoVoz = YACSmartProperties.VOZ_HOMBRE1;
}else if(which == 1){
txtTipoVozSeleccionada.setText("Voz de Mujer Latina");
codigoVoz = YACSmartProperties.VOZ_MUJER2;
}else{
txtTipoVozSeleccionada.setText("Voz de Mujer");
codigoVoz = YACSmartProperties.VOZ_MUJER1;
}
dialog.dismiss();
}
});
alertDialog.show();
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
InputStream is = null;
if(codigoVoz.equals(YACSmartProperties.VOZ_MUJER1)){
is = getResources().openRawResource(R.raw.m1);
}else if(codigoVoz.equals(YACSmartProperties.VOZ_MUJER2)){
is = getResources().openRawResource(R.raw.m2);
}else if(codigoVoz.equals(YACSmartProperties.VOZ_HOMBRE1)){
is = getResources().openRawResource(R.raw.h1);
}
int size = is.available();
byte[] buffer = new byte[size]; //declare the size of the byte array with size of the file
is.read(buffer); //read file
is.close();
playStreamAudio(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
chosenRingtone = datosAplicacion.getEquipoSeleccionado().getTono();
editMensajeTimbrar.setText(datosAplicacion.getEquipoSeleccionado().getMensajeInicial());
editMensajeApertura.setText(datosAplicacion.getEquipoSeleccionado().getMensajeApertura());
editMensajePuerta.setText(datosAplicacion.getEquipoSeleccionado().getMensajePuerta());
toggleTono.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
startActivityForResult(intent, 5);
} else {
chosenRingtone = "0";
}
}
});
// toggleModo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
// @Override
// public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// if (isChecked) {
// if (AudioQueu.getTipoConexion().equals(TipoConexionEnum.WIFI.getCodigo())) {
//
// SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
//
// String datosConfT = YACSmartProperties.HOTSPOT_MODO_HOTSPOT //0
// + ";" + nombreDispositivo //1
// + ";" + "ANDROID" //2
// + ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
// + ";";
//
// EnviarComandoThread enviarComandoThread = new EnviarComandoThread(PreferenciasActivity.this, datosConfT, null,
// null, null, datosAplicacion.getEquipoSeleccionado().getIpLocal(), YACSmartProperties.PUERTO_COMANDO_DEFECTO, null);
// enviarComandoThread.start();
// }
//
// }
// }
// });
toggleWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
if(mensajeWifi) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
PreferenciasActivity.this);
alertDialogBuilder.setTitle(YACSmartProperties.intance.getMessageForKey("titulo.informacion"))
.setMessage(YACSmartProperties.intance.getMessageForKey("texto.cambiar.wifi"))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (isChecked) {
if (AudioQueu.getTipoConexion().equals(TipoConexionEnum.WIFI.getCodigo())) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
String datosConfT = YACSmartProperties.COM_HABILITAR_WIFI //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";";
EnviarComandoThread enviarComandoThread = new EnviarComandoThread(PreferenciasActivity.this, datosConfT, null,
null, null, datosAplicacion.getEquipoSeleccionado().getIpLocal(), YACSmartProperties.PUERTO_COMANDO_DEFECTO, null);
enviarComandoThread.start();
} else {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
String datosConfT = YACSmartProperties.COM_HABILITAR_WIFI //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";";
AudioQueu.getComandoEnviado().put(AudioQueu.contadorComandoEnviado, datosConfT);
AudioQueu.contadorComandoEnviado++;
}
datosAplicacion.getEquipoSeleccionado().setModo(YACSmartProperties.MODO_WIFI);
} else {
if (AudioQueu.getTipoConexion().equals(TipoConexionEnum.WIFI.getCodigo())) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
String datosConfT = YACSmartProperties.COM_DESHABILITAR_WIFI //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";";
EnviarComandoThread enviarComandoThread = new EnviarComandoThread(PreferenciasActivity.this, datosConfT, null,
null, null, datosAplicacion.getEquipoSeleccionado().getIpLocal(), YACSmartProperties.PUERTO_COMANDO_DEFECTO, null);
enviarComandoThread.start();
} else {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
String datosConfT = YACSmartProperties.COM_DESHABILITAR_WIFI //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";";
AudioQueu.getComandoEnviado().put(AudioQueu.contadorComandoEnviado, datosConfT);
AudioQueu.contadorComandoEnviado++;
}
datosAplicacion.getEquipoSeleccionado().setModo(YACSmartProperties.MODO_CABLE);
}
EquipoDataSource equipoDataSource = new EquipoDataSource(getApplicationContext());
equipoDataSource.open();
equipoDataSource.updateEquipo(datosAplicacion.getEquipoSeleccionado());
equipoDataSource.close();
mensajeWifi = true;
}
}).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mensajeWifi = false;
toggleWifi.setChecked(!toggleWifi.isChecked());
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}else{
mensajeWifi = true;
}
}
});
btnGuardarPreferencias.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(datosAplicacion.getEquipoSeleccionado().getModo().equals(YACSmartProperties.MODO_AP)){
if (!editNombreWifi.getText().toString().equals("") && !editClaveWifi.getText().toString().equals("") ) {
TimeZone tz = TimeZone.getDefault();
String comando = YACSmartProperties.HOTSPOT_WIFI + ";"+ "1" + ";" + editNombreWifi.getText().toString() + ";" + editClaveWifi.getText().toString() + ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie()
+ ";" + datosAplicacion.getEquipoSeleccionado().getNombreEquipo() + ";" + tz.getID() + ";";
//Validar el numero de serie
ComandoHotSpotScheduledTask genericoAsyncTask = new ComandoHotSpotScheduledTask(null, comando);
genericoAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}else {
clavePuerta = "";
if (!editClavePuerta.getText().toString().equals("")) {
clavePuerta = YACSmartProperties.Encriptar(editClavePuerta.getText().toString());
}
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String nombreDispositivo = sharedPrefs.getString("prefNombreDispositivo", "");
TimeZone tz = TimeZone.getDefault();
String valorTimbreExterno = "0";
if(toggleTimbreExterno.isChecked()){
if(checkBoxVecesTimbre.isChecked()){
valorTimbreExterno = "2";
}else{
valorTimbreExterno = "1";
}
}
String datosConfT = YACSmartProperties.COM_CONFIGURAR_PARAMETROS //0
+ ";" + nombreDispositivo //1
+ ";" + "ANDROID" //2
+ ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() //3
+ ";" + (toggleApertura.isChecked() ? "1" : "0") //4
+ ";" + clavePuerta //5
+ ";" + (toggleSensor.isChecked() ? "1" : "0") //6
+ ";" + (toggleLuzExterna.isChecked() ? "1" : "0") //7
+ ";" + (toggleLuzWifi.isChecked() ? "1" : "0") //8
+ ";" + editMensajeTimbrar.getText().toString() //9
+ ";" + "1100" //10 Contador timbre sensibilidad para leer
+ ";" + (togglePuertos.isChecked() ? "1" : "0") //11
+ ";" + "20000" //12 Tiempo de espera del buzon
+ ";" + "6500" //13 Contador sensor de puerta sensibilidad
+ ";" + "15000" //14 Tiempo de grabacion del buzon
// + ";" + (toggleTimbreExterno.isChecked() ? "1" : "0") //15
+ ";" + valorTimbreExterno //15
+ ";" + editMensajeApertura.getText().toString() //16
+ ";" + editMensajePuerta.getText().toString() //17
+ ";" + tz.getID() //18
+ ";" + datosAplicacion.getEquipoSeleccionado().getTiempoEncendidoLuz() //19
+ ";" + (toggleVolumenAlto.isChecked() ? "1" : "0") //20
+ ";";
EquipoDataSource equipoDataSource = new EquipoDataSource(getApplicationContext());
equipoDataSource.open();
datosAplicacion.getEquipoSeleccionado().setTono(chosenRingtone);
datosAplicacion.getEquipoSeleccionado().setVozMensaje(codigoVoz);
equipoDataSource.updateEquipo(datosAplicacion.getEquipoSeleccionado());
equipoDataSource.close();
if (AudioQueu.getTipoConexion().equals(TipoConexionEnum.WIFI.getCodigo())) {
EnviarComandoThread enviarComandoThread = new EnviarComandoThread(PreferenciasActivity.this, datosConfT, null,
null, null, datosAplicacion.getEquipoSeleccionado().getIpLocal(), YACSmartProperties.PUERTO_COMANDO_DEFECTO, null);
enviarComandoThread.start();
} else {
AudioQueu.getComandoEnviado().put(AudioQueu.contadorComandoEnviado, datosConfT);
AudioQueu.contadorComandoEnviado++;
}
finish();
}
}
});
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK && requestCode == 5)
{
Uri uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri != null)
{
this.chosenRingtone = uri.toString();
}
else
{
this.chosenRingtone = "";
}
}else if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(intent);
}else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(intent);
}else{
//get the returned data
Bundle extras = intent.getExtras();
//get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
FileOutputStream fileOuputStream = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
thePic.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
fileOuputStream = new FileOutputStream(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() + ".jpg");
fileOuputStream.write(bitmapdata);
fileOuputStream.close();
if(datosAplicacion.getEquipoSeleccionado().getTipoEquipo().equals(TipoEquipoEnum.PORTERO.getCodigo())) {
String imageString = Base64.encodeToString(bitmapdata, Base64.DEFAULT);
String datosConfT = YACSmartProperties.COM_GUARDAR_FOTO_PERFIL + ";" + nombreDispositivo + ";" + "ANDROID" + ";" + datosAplicacion.getEquipoSeleccionado().getNumeroSerie() + ";" + imageString + ";";
AudioQueu.getComandoEnviado().put(AudioQueu.contadorComandoEnviado, datosConfT);
AudioQueu.contadorComandoEnviado++;
}else {
GuardarFotoEquipoAsyncTask guardarFotoEquipoAsyncTask = new GuardarFotoEquipoAsyncTask(PreferenciasActivity.this, bitmapdata, datosAplicacion.getEquipoSeleccionado().getNumeroSerie());
guardarFotoEquipoAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//display the returned cropped image
mostrarImagen(fotoPerfilDispositivo, thePic);
}
}
}
public boolean isScreenLarge() {
final int screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
return screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
|| screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private void mostrarImagen(ImageView mimageView, Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 2000;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
mimageView.setImageBitmap(output);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Seleccione una foto"), SELECT_FILE);
}
private void onCaptureImageResult(Intent data) {
Uri picUri = data.getData();
performCrop(picUri);
}
private void performCrop(Uri picUri ){
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
catch(ActivityNotFoundException anfe){
//display an error message
}
}
private void onSelectFromGalleryResult(Intent data) {
Uri picUri = data.getData();
performCrop(picUri);
}
AudioTrack audioTrack;
AudioManager audioManager;
public void playStreamAudio( byte[] d) {
initPlayer(d);
audioTrack.write(d, 0, d.length);
if (audioTrack != null && audioTrack.getState() != AudioTrack.STATE_UNINITIALIZED) {
audioTrack.release();
}
}
/**
* Initialize AudioTrack by getting buffersize
*/
private void initPlayer(byte[] d) {
synchronized (this) {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
int bs = AudioTrack.getMinBufferSize(22050, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_VOICE_CALL,
22050,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
bs,
AudioTrack.MODE_STREAM);
if (audioTrack != null) {
audioTrack.setNotificationMarkerPosition(d.length / 2);
audioTrack.play();
audioTrack.setPlaybackPositionUpdateListener(new AudioTrack.OnPlaybackPositionUpdateListener() {
@Override
public void onMarkerReached(AudioTrack track) {
if(track.getState() == AudioTrack.STATE_INITIALIZED){
audioManager.setSpeakerphoneOn(false);
track.stop();
track.release();
}
}
@Override
public void onPeriodicNotification(AudioTrack track) {
}
});
}
}
}
}
|
package com.naka.rabbitmqproducer;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.util.Date;
import java.text.SimpleDateFormat;
public class Send
{
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(System.getenv().getOrDefault("RABBITMQ_HOST", "localhost"));
factory.setUsername(System.getenv().getOrDefault("RABBITMQ_USERNAME", "guest"));
factory.setPassword(System.getenv().getOrDefault("RABBITMQ_PASSWORD", "guest"));
int numOfMessages = Integer.parseInt(System.getenv().getOrDefault("NUM_OF_MESSAGES", "10"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try (Connection connection = factory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
for (int n = 1; n<=numOfMessages; n++) {
Date date = new Date(System.currentTimeMillis());
System.out.println(formatter.format(date));
String message = String.format("%s [%d/%d]", formatter.format(date), n, numOfMessages);
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println("[x] Sent '" + message + "'");
}
}
}
}
|
package com.training.springbasics.Components;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class ComponentDAO {
@Autowired
JdbcComponent jdbcComponent;
public JdbcComponent getJdbcComponent() {
return jdbcComponent;
}
public void setJdbcComponent(JdbcComponent jdbcComponent) {
this.jdbcComponent = jdbcComponent;
}
}
|
package com.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 com.model.Login;
import com.model.DataBo;
/**
* Servlet implementation class DataController
*/
@WebServlet("/DataController")
public class DataController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public DataController() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String x = request.getParameter("customer_id");
String y = request.getParameter("password");
PrintWriter out = response.getWriter();
Login loginobj = new Login();
loginobj.setcustomer_id(x);
loginobj.setPassword(y);
System.out.println(x);
System.out.println(y);
DataBo databusiness = new DataBo();
boolean business = databusiness.validate(loginobj);
HttpSession session = request.getSession(true);
session.setAttribute("currentcustomerid", x);
System.out.println(business);
if (business == true){
request.getRequestDispatcher("customer.html").forward(request, response);
} else {
out.println("<script type=\"text/javascript\">");
out.println("alert('User or password incorrect');");
out.println("</script>");
RequestDispatcher r = request.getRequestDispatcher("customerLogin.html");
r.include(request, response);
}
}
}
|
package com.java.abs_factory;
import com.java.rkp.factory.PlaneFactory;
public class AbstractPlaneFactory {
public static Object getPlaneFactory(Choice s) {
switch (s) {
case TYPE: {
PlaneFactory factory = new PlaneFactory();
//builder.getPlanType();
}
case PRICE: {
PlaneFactory factory = new PlaneFactory();
// builder.getPlanPrice();
}
} return null;
}
}
|
package com.tencent.mm.g.a;
public final class hs$a {
public boolean isResume = false;
}
|
package cn.jishuz.library.fragment;
import cn.jishuz.library.R;
import cn.jishuz.library.activity.BookDetails;
import cn.jishuz.library.adpter.BasketAdapter;
import cn.jishuz.library.db.Mydata;
import cn.jishuz.library.until.Basket;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
public class BasketFragment extends Fragment {
private Mydata dbHelp;
private List<Integer> mId = new ArrayList<Integer>();
private ArrayList<Basket> mArr = new ArrayList<Basket>();
private ListView listView;
private Context mcontext;
private BasketAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.tab03, container,false);
setData();
adapter = new BasketAdapter(mcontext, mArr);
listView = (ListView) view.findViewById(R.id.mbasket_listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), BookDetails.class);
intent.putExtra("type", "basket");
intent.putExtra("id", mId.get(position));
getActivity().startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
// TODO Auto-generated method stub
final int p = position;
AlertDialog.Builder builder = new AlertDialog.Builder(mcontext);
builder.setTitle("警告");
builder.setIcon(android.R.drawable.ic_input_delete);
builder.setMessage("你确定要从书蓝里删除此书吗?");
builder.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dbHelp = new Mydata(mcontext);
SQLiteDatabase db = dbHelp.getReadableDatabase();
db.delete("basket", "bookid = ?", new String[]{mId.get(p).toString()});
// BasketAdapter adapter = (BasketAdapter) listView.getAdapter();
mArr.remove(p);
adapter = new BasketAdapter(mcontext, mArr);
listView.setAdapter(adapter);
db.close();
dbHelp.close();
}
});
builder.setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.show();
return true;
}
});
return view;
}
private void setData(){
dbHelp = new Mydata(mcontext);
Cursor cursor = dbHelp.queryAll("basket");
if(cursor.moveToFirst()){
do {
mId.add(cursor.getInt(cursor.getColumnIndex("bookid")));
} while (cursor.moveToNext());
}
cursor.close();
Iterator it = mId.iterator();
while(it.hasNext()){
SQLiteDatabase sql = dbHelp.getReadableDatabase();
Object whereString = it.next();
Cursor cursor1 = sql.query("book", null, "_id = ?", new String[]{whereString.toString()},null, null, null);
if(cursor1.moveToFirst()){
String name = cursor1.getString(cursor1.getColumnIndex("name"));
String author = cursor1.getString(cursor1.getColumnIndex("author"));
String s = cursor1.getString(cursor1.getColumnIndex("score"));
String image = cursor1.getString(cursor1.getColumnIndex("Image"));
float score = Float.valueOf(s);
AssetManager assets = getActivity().getAssets();
InputStream is = null;
try {
is = assets.open("images/" + image + ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitMap = BitmapFactory.decodeStream(is, null, options);
mArr.add(new Basket(bitMap, name, author, score, score));
}
}
dbHelp.close();
}
public void onAttach(Activity activity){
super.onAttach(activity);
mcontext = activity;
}
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.verticalviewpager.a;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView$a;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.tencent.mm.bp.a;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.ad;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.i;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.verticalviewpager.DummyViewPager;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.s;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.z;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.c;
import com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.d;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.smtt.utils.TbsLog;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
public final class b extends Fragment {
private static int nHk;
private int bgColor;
private boolean eBZ;
private int eHG;
private boolean eaR;
private int hmV;
private int hmW;
private LinearLayoutManager nCQ;
private final Map<String, Bitmap> nEi = new WeakHashMap();
private int nEs = TbsLog.TBSLOG_CODE_SDK_BASE;
private int nEt = 700;
private c nHg;
public com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.b nHl;
private z nHm;
private boolean nHn;
private boolean nHo;
public boolean nHp;
public boolean nHq = false;
private int nHr;
public int nHs;
private ah nHt;
private a nHu;
private b nHv;
private a nHw;
private boolean nHx;
static /* synthetic */ void a(b bVar, String str, ImageView imageView) {
Bitmap decodeFile = BitmapFactory.decodeFile(str);
LayoutParams layoutParams = imageView.getLayoutParams();
if (Float.compare(bVar.nHm.width, 0.0f) > 0) {
layoutParams.width = (int) bVar.nHm.width;
} else {
layoutParams.width = -1;
}
if (Float.compare(bVar.nHm.height, 0.0f) > 0) {
layoutParams.height = (int) bVar.nHm.height;
} else {
layoutParams.height = -2;
}
if (layoutParams instanceof MarginLayoutParams) {
((MarginLayoutParams) layoutParams).bottomMargin = (int) bVar.nHm.nAZ;
}
imageView.setImageBitmap(decodeFile);
}
static /* synthetic */ void a(b bVar, String str, String str2, String str3) {
if (bVar.nHt == null) {
bVar.nHt = new ah();
}
bVar.nHt.H(new 3(bVar, str, str2, str3));
}
public static Fragment a(c cVar, DummyViewPager dummyViewPager, z zVar, boolean z, a aVar, boolean z2, boolean z3) {
Bundle bundle = new Bundle();
bundle.putSerializable("pageInfo", cVar);
bundle.putSerializable("viewpager", dummyViewPager);
bundle.putSerializable("lifecycle", aVar);
bundle.putSerializable("pageDownIconInfo", zVar);
bundle.putBoolean("isLastPage", z);
bundle.putBoolean("needEnterAnimation", z2);
bundle.putBoolean("needDirectionAnimation", z3);
b bVar = new b();
bVar.setArguments(bundle);
return bVar;
}
public final void onCreate(Bundle bundle) {
super.onCreate(bundle);
nHk = a.fromDPToPix(getContext(), 60);
int[] ee = ad.ee(getContext());
this.hmV = ee[0];
this.hmW = ee[1];
if (this.nHg == null) {
this.nHg = (c) getArguments().getSerializable("pageInfo");
}
this.nHu = (a) getArguments().getSerializable("lifecycle");
this.nHm = (z) getArguments().getSerializable("pageDownIconInfo");
this.eBZ = getArguments().getBoolean("isLastPage");
this.nHn = getArguments().getBoolean("needEnterAnimation");
this.nHo = getArguments().getBoolean("needDirectionAnimation");
}
public final View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
View inflate = layoutInflater.inflate(g.ad_landing_page_item, viewGroup, false);
this.nHv = new b((byte) 0);
this.nHv.nHH = inflate;
this.nHv.nHI = (ImageView) inflate.findViewById(f.sns_ad_native_landing_pages_background_img);
this.nHv.fyt = (LinearLayout) inflate.findViewById(f.sns_ad_native_landing_pages_sub_linear_layout);
this.nHv.nHJ = (ImageView) inflate.findViewById(f.sns_native_landing_pages_next_img);
this.nHv.gxh = (RecyclerView) inflate.findViewById(f.content_list);
this.nHv.nHL = (LinearLayout) inflate.findViewById(f.fake_container);
RecyclerView recyclerView = this.nHv.gxh;
recyclerView.setOverScrollMode(2);
recyclerView.setOnTouchListener(new com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.verticalviewpager.a((DummyViewPager) getArguments().getSerializable("viewpager")));
getActivity();
this.nCQ = new LinearLayoutManager();
recyclerView.setLayoutManager(this.nCQ);
this.nHw = new a(this.nHg, this.bgColor, getActivity(), this.nCQ);
recyclerView.setAdapter(this.nHw);
this.nHl = new com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget.b(recyclerView, this);
recyclerView.a(new 1(this));
inflate.setTag(this.nHv);
aMv();
if (this.nHu != null) {
this.nHu.p(this);
}
return inflate;
}
public final void onResume() {
super.onResume();
x.i("ContentFragment", this + " onResume " + getUserVisibleHint());
this.eaR = true;
if (this.nHl != null && getUserVisibleHint()) {
this.nHl.bzN();
}
}
public final void onPause() {
super.onPause();
new StringBuilder().append(this).append(" onPause ").append(getUserVisibleHint());
this.eaR = false;
if (this.nHl != null && getUserVisibleHint()) {
this.nHl.bAo();
}
}
public final void onDestroy() {
super.onDestroy();
if (this.nHl != null) {
this.nHl.nGP.onDestroy();
}
}
public final void setUserVisibleHint(boolean z) {
super.setUserVisibleHint(z);
if (z) {
if (this.nHl != null) {
this.nHl.bzN();
}
} else if (this.nHl != null) {
this.nHl.bAo();
}
}
public final void bAq() {
if (this.nHl != null) {
this.nHl.bAn();
}
}
public final void a(c cVar) {
if (this.nHg != cVar) {
this.nHg = cVar;
aMv();
}
}
private void aMv() {
if (this.nHv != null) {
bAr();
if (this.nHg.nIg == null || this.nHg.nIg.length() <= 0) {
bAr();
} else {
String str = this.nHg.nIg;
x.i("ContentFragment", "bg need blur %b, url %s", new Object[]{Boolean.valueOf(this.nHg.nIh), str});
if (this.nEi.containsKey(str)) {
x.i("ContentFragment", "bg has cache bitmap");
J((Bitmap) this.nEi.get(str));
} else {
d.b("adId", str, false, 1000000001, new 2(this, str));
}
}
if (this.nHw != null) {
if (this.nHg.nIg == null || this.nHg.nIg.length() <= 0) {
this.nHw.bgColor = this.bgColor;
} else {
this.nHw.bgColor = 0;
}
RecyclerView$a recyclerView$a = this.nHw;
c cVar = this.nHg;
if (recyclerView$a.nHg != cVar) {
recyclerView$a.nHg = cVar;
recyclerView$a.RR.notifyChanged();
}
}
}
}
private void bAr() {
if (this.nHg.fpc != null && this.nHg.fpc.length() > 0) {
x.i("ContentFragment", "setting bg color %s", new Object[]{this.nHg.fpc});
try {
this.bgColor = Color.parseColor(this.nHg.fpc);
} catch (Exception e) {
x.e("ContentFragment", "the color is error : " + this.nHg.fpc);
}
this.nHv.nHH.setBackgroundColor(this.bgColor);
this.nHv.nHI.setBackgroundColor(this.bgColor);
this.nHv.fyt.setBackgroundColor(this.bgColor);
bAs();
}
}
private void J(Bitmap bitmap) {
if (bitmap != null) {
this.nHv.nHH.setBackgroundColor(0);
this.nHv.nHI.setBackgroundColor(0);
this.nHv.fyt.setBackgroundColor(0);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) this.nHv.nHI.getLayoutParams();
layoutParams.height = layoutParams.height >= this.hmW ? layoutParams.height : this.hmW;
this.nHv.nHI.setLayoutParams(layoutParams);
this.nHv.nHI.setImageBitmap(bitmap);
} else {
bAr();
}
bAs();
}
private void bAs() {
if (this.bgColor == 0 && this.nHg.fpc != null && this.nHg.fpc.length() > 0) {
x.i("ContentFragment", "setDirectionColor bg color %s", new Object[]{this.nHg.fpc});
try {
this.bgColor = Color.parseColor(this.nHg.fpc);
} catch (Exception e) {
x.e("ContentFragment", "the color is error : " + this.nHg.fpc);
}
}
if (this.bgColor - -16777216 <= -1 - this.bgColor) {
this.nHv.nHJ.setImageDrawable(a.f(getActivity(), e.page_down_direction_down));
} else {
this.nHv.nHJ.setImageDrawable(a.f(getActivity(), e.page_down_dark_xxhdpi));
}
}
public final RecyclerView bAt() {
if (this.nHv != null) {
return this.nHv.gxh;
}
return null;
}
public final Collection<i> bAu() {
if (this.nHw == null) {
return Collections.EMPTY_LIST;
}
a aVar = this.nHw;
return aVar.nHh == null ? Collections.EMPTY_LIST : aVar.nHh.values();
}
public final void bAv() {
if (this.nHv.nHJ.getVisibility() == 0) {
this.nHv.nHJ.clearAnimation();
this.nHv.nHJ.setVisibility(4);
}
}
public final void bAw() {
if (b() && !this.nHq) {
this.nHv.nHJ.clearAnimation();
this.nHv.nHJ.setVisibility(0);
Animation alphaAnimation = new AlphaAnimation(0.0f, 0.8f);
alphaAnimation.setDuration((long) this.nEs);
alphaAnimation.setInterpolator(new DecelerateInterpolator(1.2f));
alphaAnimation.setStartOffset((long) this.nEs);
alphaAnimation.setAnimationListener(new 4(this));
if (this.nHm == null || this.nHm.equals(this.nHv.nHJ.getTag())) {
this.nHv.nHJ.startAnimation(alphaAnimation);
return;
}
this.nHv.nHJ.setTag(this.nHm);
this.nHv.nHJ.setVisibility(8);
d.a(this.nHm.iconUrl, 1000000001, new 5(this, alphaAnimation));
}
}
/* renamed from: bAx */
public final boolean b() {
if (!this.nHo || this.nHr != 0 || this.nHs != 0) {
return false;
}
int fi = this.nCQ.fi();
int fj = this.nCQ.fj();
if (fi == fj && fi == -1) {
return false;
}
boolean z;
for (int i = fj; i >= fi; i--) {
a aVar = this.nHw;
i iVar = (i) aVar.nHh.get(((s) aVar.nHg.nIi.get(i)).nAW);
if (iVar instanceof com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.z) {
fj = ((com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.z) iVar).bAl();
if (fj >= 0 && fj < nHk) {
z = false;
break;
}
}
}
z = true;
if (z && this.eBZ) {
z = this.nCQ.fj() != this.nHw.getItemCount() + -1;
}
return z;
}
}
|
package com.github.netudima.jmeter.junit.report;
import java.io.IOException;
public class JtlToJUnitReportTransformer {
public void transform(String jtlFile, String junitReportFile, String testSuiteName) throws IOException {
try (final DomXmlJUnitReportWriter writer
= new DomXmlJUnitReportWriter(junitReportFile, testSuiteName)) {
JtlFileReader reader = new JtlFileReader();
reader.parseCsvJtl(jtlFile, new JtlRecordProcessor() {
@Override
public void process(JtlRecord jtlRecord) {
writer.write(jtlRecord);
}
});
}
}
public void transform(String jtlFile, String junitReportFile) throws IOException {
transform(jtlFile, junitReportFile, "");
}
}
|
package services;
import entity.User;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import repositories.UserRepository;
/**
* Created by Manuel on 24.10.17.
*/
public class SecretMessage extends Controller {
@Transactional
public Result sendSecretMessage(String email) {
User u1 = UserRepository.findByEmail(email);
String randomString = u1.getRandomString();
if(randomString == null) {
return status(UNAUTHORIZED);
} else {
return ok("sie sind online");
}
}
}
|
package org.metaborg.sunshine.arguments;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.MetaborgException;
import org.metaborg.core.MetaborgRuntimeException;
import org.metaborg.core.language.ILanguageIdentifierService;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.core.language.IdentifiedResource;
import org.metaborg.core.resource.IResourceService;
import com.beust.jcommander.Parameter;
import javax.inject.Inject;
public class InputDelegate {
// @formatter:off
@Parameter(names = { "-i", "--input" }, required = true, description = "Path to the input. Can be an absolute path, "
+ "or a relative path to the project if set, otherwise a relative path to the current directory")
private String inputPath;
// @formatter:on
private final IResourceService resourceService;
private final ILanguageIdentifierService languageIdentifierService;
@Inject public InputDelegate(IResourceService resourceService, ILanguageIdentifierService languageIdentifierService) {
this.resourceService = resourceService;
this.languageIdentifierService = languageIdentifierService;
}
public FileObject inputResource() throws MetaborgException {
try {
return resourceService.resolve(inputPath);
} catch(MetaborgRuntimeException e) {
final String message = String.format("Cannot resolve %s", inputPath);
throw new MetaborgException(message, e);
}
}
public final IdentifiedResource inputIdentifiedResource(Iterable<? extends ILanguageImpl> languages)
throws MetaborgException {
final FileObject resource = inputResource();
final IdentifiedResource identified = languageIdentifierService.identifyToResource(resource, languages);
if(identified == null) {
final String message = String.format("Cannot not identify language of %s", resource);
throw new MetaborgException(message);
}
return identified;
}
public FileObject inputResource(FileObject base) throws MetaborgException {
try {
return base.resolveFile(inputPath);
} catch(FileSystemException e) {
final String message = String.format("Cannot resolve %s", inputPath);
throw new MetaborgException(message, e);
}
}
public final IdentifiedResource
inputIdentifiedResource(FileObject base, Iterable<? extends ILanguageImpl> languages) throws MetaborgException {
final FileObject resource = inputResource(base);
final IdentifiedResource identified = languageIdentifierService.identifyToResource(resource, languages);
if(identified == null) {
final String message = String.format("Cannot not identify language of %s", resource);
throw new MetaborgException(message);
}
return identified;
}
}
|
package eu.ewar.serverpanel.core.servlet;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DeliveryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,
IOException {
File file = new File("test.html");
resp.setContentType("text/html");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuilder buffer = new StringBuilder();
while (bufferedReader.ready()) {
buffer.append(bufferedReader.readLine()).append("\n");
}
bufferedReader.close();
resp.getOutputStream().println(buffer.toString());
}
}
|
package com.yoandypv.elasticsearch.geoinfo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Collections;
/**
* Created by yoandypv on 14/12/18.
* Configuration class to load Swagger specifications attributes
*/
@Configuration
@EnableSwagger2
public class Swagger {
@Value("${microservice.title}")
private String title ;
@Value("${microservice.description}")
private String description ;
@Value("${microservice.version}")
private String version ;
@Value("${microservice.termsOfServiceUrl}")
private String termsOfServiceUrl ;
@Value("${microservice.contact.name}")
private String contactName ;
@Value("${microservice.contact.website}")
private String contactWebsite ;
@Value("${microservice.contact.email}")
private String contactEmail ;
@Value("${microservice.license.name}")
private String licenseName ;
@Value("${microservice.license.website}")
private String licenseWebsite ;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.yoandypv.elasticsearch.geoinfo"))
.build()
.apiInfo(new ApiInfo(title,
description,
version,
termsOfServiceUrl,
new Contact(contactName, contactWebsite,contactEmail),
licenseName,
licenseWebsite,
Collections.emptyList()));
}
}
|
package com.song.demo;
import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.song.http.QSHttp;
import org.song.http.framework.HttpCallback;
import org.song.http.framework.HttpException;
import org.song.http.framework.Parser;
import org.song.http.framework.HttpCallbackProgress;
import org.song.http.framework.QSHttpCallback;
import org.song.http.framework.QSHttpConfig;
import org.song.http.framework.ResponseParams;
import org.song.http.framework.TrustAllCerts;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
TextView tv;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
tv = (TextView) findViewById(R.id.textview);
imageView = (ImageView) findViewById(R.id.imageView);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NetManager.select4GNetwork();
}
});
String url = "/api_test";
normalGET(url);
normalPost(url);
jsonPost(url);
downGET(url);
upLoad(url);
parserJson();
}
//普通带参数 get
public void normalGET(String url) {
QSHttp.get(url)
.param("wd", "安卓http")
.param("ie", "UTF-8")//自动构建url--https://www.baidu.com/s?ie=UTF-8&wd=安卓http
//.path(123,11) 这个参数会构建这样的url--https://www.baidu.com/s/123/11
.buildAndExecute(new HttpCallback() {
@Override
public void onSuccess(ResponseParams response) {
tv.append(response.requestParams().url() + "成功get\n");
}
@Override
public void onFailure(HttpException e) {
e.show();
}
});
}
//普通键值对 post, application/x-www-form-urlencoded
public void normalPost(String url) {
QSHttp.post(url)
.param("userid", 10086)
.param("password", "qwe123456对")
.buildAndExecute(new MyHttpCallback<JSONObject>() {
@Override
public void onComplete(JSONObject dataBean) {
tv.append(response.requestParams().url() + "成功post\n");
}
});
}
//post一个json给服务器,并自动解析服务器返回信息,application/json
public void jsonPost(String url) {
QSHttp.postJSON(url)
.param("userid", 10086)
.param("password", "qwe123456")
//.jsonBody(Object) 这个参数可以直接传一个实体类,fastjson会自动转化成json字符串
//.jsonModel(User.class)//解析模型
.buildAndExecute(new HttpCallback() {
@Override
public void onSuccess(ResponseParams response) {
tv.append(response.requestParams().url() + "成功postJSON\n");
// User b = response.parserObject();//解析好的模型
// b.getUserName();
}
@Override
public void onFailure(HttpException e) {
e.show();
}
});
QSHttp.putJSON(url)
.param("userid", 10086)
.param("password", "qwe123456")
.buildAndExecute(new MyHttpCallback<JSONObject>() {
@Override
public void onComplete(JSONObject dataBean) {
tv.append(response.requestParams().url() + "成功postJSON\n");
}
});
}
//文件下载
public void downGET(String url) {
QSHttp.download(url, getExternalCacheDir().getPath() + "/http.txt")
.buildAndExecute(new HttpCallbackProgress() {
@Override
public void onProgress(long var1, long var2, String var3) {
Log.d("downGET:", var1 * 100 / var2 + "%\n");
}
@Override
public void onSuccess(ResponseParams response) {
tv.append(response.requestParams().url() + "成功down\n");
}
@Override
public void onFailure(HttpException e) {
e.show();
}
});
}
//文件上传,multipart/form-data
public void upLoad(String url) {
QSHttp.upload(url)
.param("userid", 10086)
.param("password", "qwe123456")
.param("bytes", new byte[1024])//multipart方式上传一个字节数组
.param("file", new File(getExternalCacheDir(), "http.txt"))//multipart方式上传一个文件
//IdentityHashMap支持重复key,需new
.multipartBody(new String("img"), "image/*", "qs.jpg", new byte[1024])
.multipartBody(new String("img"), "image/*", "qs.jpg", new byte[1024])
.buildAndExecute(new HttpCallbackProgress() {
@Override
public void onProgress(long var1, long var2, String var3) {
Log.d("upLoad:", var1 * 100 / var2 + "%" + var3 + "\n");
}
@Override
public void onSuccess(ResponseParams response) {
tv.append(response.requestParams().url() + "成功upload\n");
}
@Override
public void onFailure(HttpException e) {
e.show();
}
});
}
private void parserJson() {
User dataUser = new User();
User dataUser2 = new User();
dataUser.setUserName("Yolanda");
dataUser2.setUserName("Song");
List<User> users = Arrays.asList(dataUser2);
dataUser.setRows(users);
QSHttp.postJSON("https://api.reol.top/test/json")
.jsonBody(dataUser)
.buildAndExecute(new MyHttpCallback<User<User>>() {
@Override
public void onComplete(User<User> dataUser) {
tv.append("MyHttpCallback.User<User>=" + JSON.toJSONString(dataUser) + dataUser.getRows().get(0).getClass() + "\n");
}
});
QSHttp.postJSON("https://api.reol.top/test/json")
.jsonBody("3.666489")
.buildAndExecute(new MyHttpCallback<Double>() {
@Override
public void onComplete(Double dataUser) {
tv.append("MyHttpCallback.Double=" + JSON.toJSONString(dataUser) + "\n");
}
});
QSHttp.postJSON("https://api.reol.top/test/json")
.header("row", "row")
.jsonBody(users)
.buildAndExecute(new QSHttpCallback<List<User>>() {
@Override
public void onComplete(List<User> dataUser) {
tv.append("QSHttpCallback.List<User>=" + JSON.toJSONString(dataUser) + dataUser.get(0).getClass() + "\n");
}
});
QSHttp.postJSON("https://api.reol.top/test/json")
.header("row", "row")
.jsonBody(dataUser)
.buildAndExecute(new QSHttpCallback<User>() {
@Override
public void onComplete(User dataUser) {
tv.append("QSHttpCallback.User=" + JSON.toJSONString(dataUser) + dataUser.getClass() + "\n");
}
});
QSHttp.postJSON("https://api.reol.top/test/json")
.header("row", "row")
.jsonBody("3.6")
.buildAndExecute(new QSHttpCallback<String>() {
@Override
public void onComplete(String dataUser) {
tv.append("QSHttpCallback.String=" + dataUser + "\n");
}
});
}
//基本所有api介绍
public void allAPI() {
String url = "https://www.baidu.com/s";
QSHttp.post(url)//选择请求的类型
.header("User-Agent", "QsHttp/Android")//添加请求头
.path(2333, "video")//构建成这样的url https://www.baidu.com/s/2233/video
.param("userid", 123456)//键值对参数
.param("password", "asdfgh")//键值对参数
.param(new User())//键值对参数
.toJsonBody()//把 params 转为json;application/json
.jsonBody(new User())//传入一个对象,会自动转化为json上传;application/json
.requestBody("image/jpeg", new File("xx.jpg"))//直接上传自定义的内容 自定义contentType (postjson内部是调用这个实现)
.param("bytes", new byte[1024])//传一个字节数组,multipart支持此参数
.param("file", new File("xx.jpg"))//传一个文件,multipart支持此参数
.toMultiBody()//把 params 转为multipartBody参数;multipart/form-data
.parser(parser)//自定义解析,由自己写解析逻辑
.jsonModel(User.class)//使用FastJson自动解析json,传一个实体类即可
.resultByBytes()//请求结果返回一个字节组 默认是返回字符
.resultByFile(".../1.txt")//本地路径 有此参数 请求的内容将被写入文件
.errCache()//开启这个 [联网失败]会使用缓存,如果有的话
.clientCache(24 * 3600)//开启缓存,有效时间一天
.timeOut(10 * 1000)
.openServerCache()//开启服务器缓存规则 基于okhttp支持
//构建好参数和配置后调用执行联网
.buildAndExecute(new HttpCallbackProgress() {
//-----回调均已在主线程
@Override
public void onProgress(long var1, long var2, String var3) {
//进度回调 不需要监听进度 buildAndExecute()传 new HttpCallback(){...}即可
long i = var1 * 100 / var2;//百分比
//var3 在传文件的时候为文件路径 其他无意义
}
@Override
public void onSuccess(ResponseParams response) {
response.string();//获得响应字符串 *默认
response.file();//设置了下载 获得路径
response.bytes();//设置了返回字节组 获得字节组
response.headers();//获得响应头
//获得自动解析/自定义解析的结果
User b = response.parserObject();
b.getUserName();
}
@Override
public void onFailure(HttpException e) {
e.show();//弹出错误提示 网络连接失败 超时 404 解析失败 ...等
}
});
//配置多个client
QSHttp.addClient("CELLULAR", QSHttpConfig.Build(getApplication())
.cacheSize(128 * 1024 * 1024)
.connectTimeout(18 * 1000)
// .network(network)//配置蜂窝网络通道
.debug(true)
//拦截器 添加头参数 鉴权
.interceptor(new QSInterceptor())
.build());
QSHttp.get("url").qsClient("CELLULAR").buildAndExecute();//该请求将使用上述的配置,走蜂窝网路
}
Parser parser = new Parser<User>() {
@Override
public User parser(String result) throws Exception {
return null;
}
};
}
|
package fr.univavignon.pokedex.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import fr.univavignon.pokedex.api.IPokedex;
import fr.univavignon.pokedex.api.IPokemonFactory;
import fr.univavignon.pokedex.api.IPokemonMetadataProvider;
import fr.univavignon.pokedex.api.PokedexException;
import fr.univavignon.pokedex.api.Pokemon;
import fr.univavignon.pokedex.api.PokemonMetadata;
public class Pokedex implements IPokedex,Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private IPokemonFactory pokemonFactory;
private IPokemonMetadataProvider pokemonMetadataProvider;
private List<Pokemon> pokemonList;
public Pokedex(IPokemonFactory pokemonFactory,IPokemonMetadataProvider pokemonMetadataProvider) {
super();
this.pokemonFactory = pokemonFactory;
this.pokemonMetadataProvider = pokemonMetadataProvider;
pokemonList = new ArrayList<Pokemon>();
}
@Override
public PokemonMetadata getPokemonMetadata(int index) throws PokedexException {
return pokemonMetadataProvider.getPokemonMetadata(index);
}
@Override
public Pokemon createPokemon(int index, int cp, int hp, int dust, int candy) {
return pokemonFactory.createPokemon(index, cp, hp, dust, candy);
}
@Override
public int size() {
return pokemonList.size();
}
@Override
public int addPokemon(Pokemon pokemon) {
pokemonList.add(pokemon);
return (pokemonList.indexOf(pokemon));
}
@Override
public Pokemon getPokemon(int id) throws PokedexException {
Pokemon pokemon = null;
try{
pokemon = pokemonList.get(id);
}
catch(IndexOutOfBoundsException ex){
throw new PokedexException("Impossible de trouver le pokemon d'id "+id);
}
if(pokemon == null){
throw new PokedexException("Impossible de trouver le pokemon d'id "+id);
}
return pokemon;
}
@Override
public List<Pokemon> getPokemons() {
return Collections.unmodifiableList(pokemonList);
}
@Override
public List<Pokemon> getPokemons(Comparator<Pokemon> order) {
List<Pokemon> sortedList = pokemonList;
sortedList.sort(order);
return Collections.unmodifiableList(sortedList) ;
}
}
|
package prj5;
import java.io.FileNotFoundException;
/**
* @author nataliekakish
*
*/
public class Input {
/**
* the main method
*
* @param args the files to be read
* @throws FileNotFoundException
*/
public static void main(String args[]) throws FileNotFoundException {
if (args.length != 2) {
new GUIDisplay("MusicSurveyData2019F.csv", "SongList2019F.csv");
}
else {
new GUIDisplay(args[1], args[0]);
}
}
}
|
package leafNode;
import bplusTree.BPlusTree;
import com.carrotsearch.hppc.LongObjectHashMap;
import junit.framework.Assert;
import org.junit.Test;
import org.openjdk.jol.datamodel.X86_32_DataModel;
import org.openjdk.jol.datamodel.X86_64_COOPS_DataModel;
import org.openjdk.jol.datamodel.X86_64_DataModel;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.layouters.CurrentLayouter;
import org.openjdk.jol.layouters.HotSpotLayouter;
import org.openjdk.jol.layouters.Layouter;
import java.util.HashMap;
/**
* Created by dharmeshsing on 1/07/15.
*/
public class LayoutTest {
@Test
public void testOrderEntry(){
System.out.println(ClassLayout.parseClass(OrderEntry.class).toPrintable());
}
@Test
public void testOrderEntryDivisbleBy8(){
int header = 12;
long objectSize = OrderEntry.getObjectSize();
System.out.println(header + objectSize);
boolean result = (header + objectSize) % 8 == 0;
Assert.assertEquals(true, result);
}
@Test
public void testOrderList(){
System.out.println(ClassLayout.parseClass(OrderListImpl.class).toPrintable());
}
@Test
public void testBPlusTree(){
System.out.println(ClassLayout.parseClass(BPlusTree.class).toPrintable());
}
@Test
public void testDiffLayouts(){
Layouter l;
l = new CurrentLayouter();
System.out.println("***** " + l);
System.out.println(ClassLayout.parseClass(HashMap.class, l).toPrintable());
l = new HotSpotLayouter(new X86_32_DataModel());
System.out.println("***** " + l);
System.out.println(ClassLayout.parseClass(HashMap.class, l).toPrintable());
l = new HotSpotLayouter(new X86_64_DataModel());
System.out.println("***** " + l);
System.out.println(ClassLayout.parseClass(HashMap.class, l).toPrintable());
l = new HotSpotLayouter(new X86_64_COOPS_DataModel());
System.out.println("***** " + l);
System.out.println(ClassLayout.parseClass(HashMap.class, l).toPrintable());
}
@Test
public void testHashMap(){
System.out.println(ClassLayout.parseClass(HashMap.class).toPrintable());
System.out.println(ClassLayout.parseClass(LongObjectHashMap.class).toPrintable());
}
}
|
package dejan.snakedrools;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class GameCanvas extends Canvas{
private final static int WIDTH = 300;
private final static int HEIGHT = 300;
public final int X_GRID_SIZE = 30;
public final int Y_GRID_SIZE = 30;
private final int RECT_WIDTH = WIDTH / X_GRID_SIZE;
private final int RECT_HEIGHT = HEIGHT / Y_GRID_SIZE;
GraphicsContext gc;
public GameCanvas() {
super(WIDTH, HEIGHT);
gc = getGraphicsContext2D();
}
public void drawBlock(int xPos, int yPos, Color color) {
int x = RECT_WIDTH * xPos;
int y = RECT_HEIGHT * yPos;
gc.setFill(color);
gc.fillRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}
public void clear() {
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, WIDTH, HEIGHT);
}
}
|
package chapter09.Exercise09_10;
import java.util.Scanner;
public class TestQuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a, b, c in the equation: ax2 + bx + x = 0");
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
QuadraticEquation equation = new QuadraticEquation(a, b, c);
if (equation.getDiscriminant() == 0) {
System.out.println("Root: " + equation.getRoot1());
} else if (equation.getDiscriminant() < 0) {
System.out.println("The equation has no roots.");
} else {
System.out.println("Root1: " + equation.getRoot1());
System.out.println("Root2: " + equation.getRoot2());
}
}
}
|
package org.inftel.scrum.lists;
import org.inftel.scrum.R;
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
public class PokerCardsAdapter extends BaseAdapter {
private Context ctx;
private String[] cartas = { "1", "2", "3", "5", "8", "13", "20", "40",
"100", "\u221E" };
public PokerCardsAdapter(Context ctx) {
this.ctx = ctx;
}
public int getCount() {
return cartas.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View v, ViewGroup parent) {
TextView carta;
if (v == null) { // if it's not recycled, initialize some attributes
carta = new TextView(ctx);
carta.setLayoutParams(new GridView.LayoutParams(85, 85));
carta.setText(cartas[position]);
if (position == cartas.length - 2) {
carta.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 25);
} else {
carta.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35);
}
carta.setGravity(Gravity.CENTER_VERTICAL
| Gravity.CENTER_HORIZONTAL);
carta.setTextColor(ctx.getResources()
.getColor(R.color.verde_oscuro));
} else {
carta = (TextView) v;
}
carta.setBackgroundResource(R.drawable.fondo_blanco);
return carta;
}
}
|
package com.wt.jiaduo.dto.jpa;
// Generated 2018-3-31 15:55:00 by Hibernate Tools 5.2.8.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* XiaomaiTiaoxiubingHouqi generated by hbm2java
*/
@Entity
@Table(name = "xiaomai_tiaoxiubing_houqi", catalog = "jiaduo")
public class XiaomaiTiaoxiubingHouqi implements java.io.Serializable {
private Integer id;
private String place;
private Date dateTime;
private String variety;
private String fieldNum;
private String growthPeriod;
private String typeField1Rate;
private String typeField1Severity;
private String typeField2Rate;
private String typeField2Severity;
private String typeField3Rate;
private String typeField3Severity;
private String typeField4Rate;
private String typeField4Severity;
private String typeField5Rate;
private String typeField5Severity;
private String typeAverageRate;
private String typeAverageSeverity;
private Integer userId;
private String userName;
private String longitude;
private String latitude;
private String remark;
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public XiaomaiTiaoxiubingHouqi() {
}
public XiaomaiTiaoxiubingHouqi(String place, Date dateTime, String variety, String fieldNum, String growthPeriod,
String typeField1Rate, String typeField1Severity, String typeField2Rate, String typeField2Severity,
String typeField3Rate, String typeField3Severity, String typeField4Rate, String typeField4Severity,
String typeField5Rate, String typeField5Severity, String typeAverageRate, String typeAverageSeverity,
Integer userId, String userName, String longitude, String latitude) {
this.place = place;
this.dateTime = dateTime;
this.variety = variety;
this.fieldNum = fieldNum;
this.growthPeriod = growthPeriod;
this.typeField1Rate = typeField1Rate;
this.typeField1Severity = typeField1Severity;
this.typeField2Rate = typeField2Rate;
this.typeField2Severity = typeField2Severity;
this.typeField3Rate = typeField3Rate;
this.typeField3Severity = typeField3Severity;
this.typeField4Rate = typeField4Rate;
this.typeField4Severity = typeField4Severity;
this.typeField5Rate = typeField5Rate;
this.typeField5Severity = typeField5Severity;
this.typeAverageRate = typeAverageRate;
this.typeAverageSeverity = typeAverageSeverity;
this.userId = userId;
this.userName = userName;
this.longitude = longitude;
this.latitude = latitude;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "place")
public String getPlace() {
return this.place;
}
public void setPlace(String place) {
this.place = place;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date_time", length = 19)
public Date getDateTime() {
return this.dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
@Column(name = "variety")
public String getVariety() {
return this.variety;
}
public void setVariety(String variety) {
this.variety = variety;
}
@Column(name = "field_num")
public String getFieldNum() {
return this.fieldNum;
}
public void setFieldNum(String fieldNum) {
this.fieldNum = fieldNum;
}
@Column(name = "growth_period")
public String getGrowthPeriod() {
return this.growthPeriod;
}
public void setGrowthPeriod(String growthPeriod) {
this.growthPeriod = growthPeriod;
}
@Column(name = "type_field1_rate")
public String getTypeField1Rate() {
return this.typeField1Rate;
}
public void setTypeField1Rate(String typeField1Rate) {
this.typeField1Rate = typeField1Rate;
}
@Column(name = "type_field1_severity")
public String getTypeField1Severity() {
return this.typeField1Severity;
}
public void setTypeField1Severity(String typeField1Severity) {
this.typeField1Severity = typeField1Severity;
}
@Column(name = "type_field2_rate")
public String getTypeField2Rate() {
return this.typeField2Rate;
}
public void setTypeField2Rate(String typeField2Rate) {
this.typeField2Rate = typeField2Rate;
}
@Column(name = "type_field2_severity")
public String getTypeField2Severity() {
return this.typeField2Severity;
}
public void setTypeField2Severity(String typeField2Severity) {
this.typeField2Severity = typeField2Severity;
}
@Column(name = "type_field3_rate")
public String getTypeField3Rate() {
return this.typeField3Rate;
}
public void setTypeField3Rate(String typeField3Rate) {
this.typeField3Rate = typeField3Rate;
}
@Column(name = "type_field3_severity")
public String getTypeField3Severity() {
return this.typeField3Severity;
}
public void setTypeField3Severity(String typeField3Severity) {
this.typeField3Severity = typeField3Severity;
}
@Column(name = "type_field4_rate")
public String getTypeField4Rate() {
return this.typeField4Rate;
}
public void setTypeField4Rate(String typeField4Rate) {
this.typeField4Rate = typeField4Rate;
}
@Column(name = "type_field4_severity")
public String getTypeField4Severity() {
return this.typeField4Severity;
}
public void setTypeField4Severity(String typeField4Severity) {
this.typeField4Severity = typeField4Severity;
}
@Column(name = "type_field5_rate")
public String getTypeField5Rate() {
return this.typeField5Rate;
}
public void setTypeField5Rate(String typeField5Rate) {
this.typeField5Rate = typeField5Rate;
}
@Column(name = "type_field5_severity")
public String getTypeField5Severity() {
return this.typeField5Severity;
}
public void setTypeField5Severity(String typeField5Severity) {
this.typeField5Severity = typeField5Severity;
}
@Column(name = "type_average_rate")
public String getTypeAverageRate() {
return this.typeAverageRate;
}
public void setTypeAverageRate(String typeAverageRate) {
this.typeAverageRate = typeAverageRate;
}
@Column(name = "type_average_severity")
public String getTypeAverageSeverity() {
return this.typeAverageSeverity;
}
public void setTypeAverageSeverity(String typeAverageSeverity) {
this.typeAverageSeverity = typeAverageSeverity;
}
@Column(name = "user_id")
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Column(name = "user_name")
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "longitude")
public String getLongitude() {
return this.longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
@Column(name = "latitude")
public String getLatitude() {
return this.latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
}
|
package com.hua.beautifulimage.utils;
/**
*
*/
public class Constants {
public static final String BASE_IMAGE_URL = "http://tnfs.tngou.net/image";
public static final int DEFAULT_PAGE_ROWS = 10;
public static final String EXTRA_SHOW_PICTURE_ID = "EXTRA_SHOW_PICTURE_ID";
public static class Config {
public static final boolean DEVELOPER_MODE = true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.