List of usage examples for org.apache.commons.lang3 ArrayUtils toPrimitive
public static boolean[] toPrimitive(final Boolean[] array)
Converts an array of object Booleans to primitives.
This method returns null for a null input array.
From source file:net.larry1123.elec.util.test.config.AbstractConfigTest.java
public void ShortArrayTest(String fieldName, Field testField) { try {/*from ww w .j a va2s.c om*/ short[] testFieldValue = ArrayUtils.toPrimitive((Short[]) testField.get(getConfigBase())); Assert.assertTrue(ArrayUtils.isEquals(getPropertiesFile().getShortArray(fieldName), testFieldValue)); } catch (IllegalAccessException e) { assertFailFieldError(fieldName); } }
From source file:edu.pitt.csb.stability.StabilitySearch.java
public void searchParallel() { //final int numVars = data.getNumColumns(); //final DoubleMatrix2D thetaMat = DoubleFactory2D.dense.make(numVars, numVars, 0.0); //final HashMap<Edge, Double> thetaList = new HashMap<>(); //final int[][] samps = subSampleNoReplacement(data.getNumRows(), b, N); class StabilityAction extends RecursiveAction { private int chunk; private int from; private int to; public StabilityAction(int chunk, int from, int to) { this.chunk = chunk; this.from = from; this.to = to; }// ww w .j a v a2 s .c om //could avoid using syncronized if we keep track of array of mats and add at end, but that needs lots of //memory /*private void addToMat(DoubleMatrix2D matSum, DoubleMatrix2D curMat){ matSum.assign(curMat, Functions.plus); if(!matSum.equals(Algebra.DEFAULT.transpose(matSum))) { System.out.println("NOT SYMMETRIC!!!:\n" + matSum + "\ncurmat:\n" + curMat); //throw new IllegalStateException("not symmetric"); } }*/ @Override protected void compute() { if (to - from <= chunk) { for (int s = from; s < to; s++) { try { synchronized (edgeStab) { pwLog.write("Starting subsamp " + s + "...\n"); pwLog.flush(); } DataGraphSearch curGs; DataSet dataSubSamp; //synchronized (gs) { int[] inds = ArrayUtils.toPrimitive(samps.get(s).toArray(new Integer[0])); dataSubSamp = MixedUtils.deepCopy((ColtDataSet) data.subsetRows(inds)); curGs = gs.copy(); //} long start = System.currentTimeMillis(); Graph g = curGs.search(dataSubSamp); long end = System.currentTimeMillis(); synchronized (edgeStab) { addEdges(g); if (runDir != null) { saveNet(s, g); pwTime.write("sn" + s + "\t" + (end - start) / 1000.0 + "\n"); pwTime.flush(); } pwLog.write("Subsamp " + s + " complete\n"); pwLog.flush(); } } catch (Throwable t) { synchronized (edgeStab) { pwLog.write("Subsamp " + s + " failed. "); pwLog.write("Message: " + t.getMessage() + "\n"); pwLog.flush(); } } //DoubleMatrix2D curAdj = MixedUtils.skeletonToMatrix(g); //set weights so that undirected stability works //synchronized (thetaMat) { // addToMat(thetaMat, curAdj); //} } return; } else { List<StabilityAction> tasks = new ArrayList<StabilityAction>(); final int mid = (to - from) / 2; tasks.add(new StabilityAction(chunk, from, from + mid)); tasks.add(new StabilityAction(chunk, from + mid, to)); invokeAll(tasks); return; } } } long startMain = System.currentTimeMillis(); final int chunk = 1; pool.invoke(new StabilityAction(chunk, 0, numSubs)); updateThetaMat(); if (runDir != null) { pwTime.write("Total\t" + (System.currentTimeMillis() - startMain) / 1000.0 + "\n"); pwTime.flush(); } //thetaMat.assign(Functions.mult(1.0 / numSubs)); //do this elsewhere //thetaMat.assign(thetaMat.copy().assign(Functions.minus(1.0)), Functions.mult).assign(Functions.mult(-2.0)); //return thetaMat; }
From source file:edu.stanford.slac.archiverappliance.PB.data.BoundaryConditionsSimulationValueGenerator.java
public DBR getJCASampleValue(ArchDBRTypes type, int secondsIntoYear) { switch (type) { case DBR_SCALAR_STRING: DBR_TIME_String retvalss = new DBR_TIME_String(new String[] { Integer.toString(secondsIntoYear) }); retvalss.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalss.setSeverity(1);//from w w w . j av a 2 s . co m retvalss.setStatus(0); return retvalss; case DBR_SCALAR_SHORT: DBR_TIME_Short retvalsh; if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value retvalsh = new DBR_TIME_Short(new short[] { (short) (Short.MIN_VALUE + secondsIntoYear) }); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value retvalsh = new DBR_TIME_Short(new short[] { (short) (Short.MAX_VALUE - (secondsIntoYear - 1000)) }); } else { // Check for some numbers around 0 retvalsh = new DBR_TIME_Short(new short[] { (short) (secondsIntoYear - 2000) }); } retvalsh.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalsh.setSeverity(1); retvalsh.setStatus(0); return retvalsh; case DBR_SCALAR_FLOAT: DBR_TIME_Float retvalfl; if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value retvalfl = new DBR_TIME_Float(new float[] { Float.MIN_VALUE + secondsIntoYear }); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value retvalfl = new DBR_TIME_Float(new float[] { Float.MAX_VALUE - (secondsIntoYear - 1000) }); } else { // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits retvalfl = new DBR_TIME_Float(new float[] { (secondsIntoYear - 2000.0f) / secondsIntoYear }); } retvalfl.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalfl.setSeverity(1); retvalfl.setStatus(0); return retvalfl; case DBR_SCALAR_ENUM: DBR_TIME_Enum retvalen; retvalen = new DBR_TIME_Enum(new short[] { (short) (secondsIntoYear) }); retvalen.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalen.setSeverity(1); retvalen.setStatus(0); return retvalen; case DBR_SCALAR_BYTE: DBR_TIME_Byte retvalby; retvalby = new DBR_TIME_Byte(new byte[] { ((byte) (secondsIntoYear % 255)) }); retvalby.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalby.setSeverity(1); retvalby.setStatus(0); return retvalby; case DBR_SCALAR_INT: DBR_TIME_Int retvalint; if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value retvalint = new DBR_TIME_Int(new int[] { Integer.MIN_VALUE + secondsIntoYear }); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value retvalint = new DBR_TIME_Int(new int[] { Integer.MAX_VALUE - (secondsIntoYear - 1000) }); } else { // Check for some numbers around 0 retvalint = new DBR_TIME_Int(new int[] { (secondsIntoYear - 2000) }); } retvalint.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvalint.setSeverity(1); retvalint.setStatus(0); return retvalint; case DBR_SCALAR_DOUBLE: DBR_TIME_Double retvaldb; if (0 <= secondsIntoYear && secondsIntoYear < 1000) { // Check for some numbers around the minimum value retvaldb = new DBR_TIME_Double(new double[] { (Double.MIN_VALUE + secondsIntoYear) }); } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) { // Check for some numbers around the maximum value retvaldb = new DBR_TIME_Double(new double[] { (Double.MAX_VALUE - (secondsIntoYear - 1000)) }); } else { // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits retvaldb = new DBR_TIME_Double( new double[] { ((secondsIntoYear - 2000.0) / (secondsIntoYear * 1000000)) }); } retvaldb.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvaldb.setSeverity(1); retvaldb.setStatus(0); return retvaldb; case DBR_WAVEFORM_STRING: DBR_TIME_String retvst; // Varying number of copies of a typical value retvst = new DBR_TIME_String( Collections.nCopies(secondsIntoYear, Integer.toString(secondsIntoYear)).toArray(new String[0])); retvst.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvst.setSeverity(1); retvst.setStatus(0); return retvst; case DBR_WAVEFORM_SHORT: DBR_TIME_Short retvsh; retvsh = new DBR_TIME_Short( ArrayUtils.toPrimitive(Collections.nCopies(1, (short) secondsIntoYear).toArray(new Short[0]))); retvsh.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvsh.setSeverity(1); retvsh.setStatus(0); return retvsh; case DBR_WAVEFORM_FLOAT: DBR_TIME_Float retvf; // Varying number of copies of a typical value retvf = new DBR_TIME_Float(ArrayUtils.toPrimitive( Collections.nCopies(secondsIntoYear, (float) Math.cos(secondsIntoYear * Math.PI / 3600)) .toArray(new Float[0]))); retvf.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvf.setSeverity(1); retvf.setStatus(0); return retvf; case DBR_WAVEFORM_ENUM: DBR_TIME_Enum retven; retven = new DBR_TIME_Enum(ArrayUtils .toPrimitive(Collections.nCopies(1024, (short) secondsIntoYear).toArray(new Short[0]))); retven.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retven.setSeverity(1); retven.setStatus(0); return retven; case DBR_WAVEFORM_BYTE: DBR_TIME_Byte retvb; // Large number of elements in the array retvb = new DBR_TIME_Byte(ArrayUtils.toPrimitive(Collections .nCopies(65536 * secondsIntoYear, ((byte) (secondsIntoYear % 255))).toArray(new Byte[0]))); retvb.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvb.setSeverity(1); retvb.setStatus(0); return retvb; case DBR_WAVEFORM_INT: DBR_TIME_Int retvint; // Varying number of copies of a typical value retvint = new DBR_TIME_Int(ArrayUtils.toPrimitive(Collections .nCopies(secondsIntoYear, secondsIntoYear * secondsIntoYear).toArray(new Integer[0]))); retvint.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvint.setSeverity(1); retvint.setStatus(0); return retvint; case DBR_WAVEFORM_DOUBLE: DBR_TIME_Double retvd; // Varying number of copies of a typical value retvd = new DBR_TIME_Double(ArrayUtils.toPrimitive(Collections .nCopies(secondsIntoYear, Math.sin(secondsIntoYear * Math.PI / 3600)).toArray(new Double[0]))); retvd.setTimeStamp(convertSecondsIntoYear2JCATimeStamp(secondsIntoYear)); retvd.setSeverity(1); retvd.setStatus(0); return retvd; case DBR_V4_GENERIC_BYTES: throw new RuntimeException("Currently don't support " + type + " when generating sample data"); default: throw new RuntimeException("We seemed to have missed a DBR type when generating sample data"); } }
From source file:net.larry1123.elec.util.test.config.AbstractConfigTest.java
public void ShortArrayListTest(String fieldName, Field testField) { try {// w w w. j av a 2 s . c o m //noinspection unchecked,unchecked short[] testFieldValue = ArrayUtils.toPrimitive(((ArrayList<Short>) testField.get(getConfigBase())) .toArray(new Short[((ArrayList<Short>) testField.get(getConfigBase())).size()])); Assert.assertTrue(ArrayUtils.isEquals(getPropertiesFile().getShortArray(fieldName), testFieldValue)); } catch (IllegalAccessException e) { assertFailFieldError(fieldName); } }
From source file:edu.iu.subgraph.colorcount_HJ.java
/** * @brief init members related to communications * * @param mapper_id_vertex//ww w .j a va 2 s .c o m * @param mapper */ void init_comm(int[] mapper_id_vertex, long send_array_limit, boolean rotation_pipeline) { //create abs mapping structure this.abs_v_to_mapper = mapper_id_vertex; this.send_array_limit = send_array_limit; this.rotation_pipeline = rotation_pipeline; // init members this.mapper_num = this.mapper.getNumWorkers(); this.local_mapper_id = this.mapper.getSelfID(); this.abs_v_to_queue = new int[this.max_abs_id + 1]; // this.chunks_mapper = divide_chunks(this.mapper_num, this.thread_num); // init comm mappers this.comm_mapper_vertex = new HashSet[this.mapper_num]; for (int i = 0; i < this.mapper_num; i++) this.comm_mapper_vertex[i] = new HashSet<>(); //loop over all the adj of local graph verts //adj_array stores abs id int[] adj_array = this.g.adjacencies(); for (int i = 0; i < adj_array.length; i++) { int adj_abs_id = adj_array[i]; int mapper_id = this.abs_v_to_mapper[adj_abs_id]; this.comm_mapper_vertex[mapper_id].add(new Integer(adj_abs_id)); } this.update_map = new int[this.num_verts_graph][]; for (int i = 0; i < this.num_verts_graph; i++) this.update_map[i] = new int[this.g.out_degree(i)]; this.update_map_size = new int[this.num_verts_graph]; this.update_queue_pos = new int[this.mapper_num][][]; this.update_queue_counts = new float[this.mapper_num][][]; this.update_queue_index = new short[this.mapper_num][][]; this.update_mapper_len = new int[this.mapper_num]; //convert set to arraylist this.comm_vertex_table = new Table<>(0, new IntArrPlus()); this.send_vertex_table = new Table<>(0, new IntArrPlus()); this.compress_cache_array = new float[this.num_verts_graph][]; this.compress_cache_index = new short[this.num_verts_graph][]; this.compress_cache_len = new int[this.num_verts_graph]; this.map_ids_cache_pip = new int[this.num_verts_graph][]; this.chunk_ids_cache_pip = new int[this.num_verts_graph][]; this.chunk_internal_offsets_cache_pip = new int[this.num_verts_graph][]; // prepareing send/recv information // the requested adj_abs_v queues will be sent to each mapper for (int i = 0; i < this.mapper_num; i++) { // i is the mapper id from which local_mapper demands adj data if ((i != this.local_mapper_id) && this.comm_mapper_vertex[i].size() > 0) { //create partition id, the upper 16 bits stores requested id //the lower 16 bits stores sender id (local id) int comm_id = ((i << 16) | this.local_mapper_id); // retrieve communicated adj_abs_id ArrayList<Integer> temp_array = new ArrayList<>(comm_mapper_vertex[i]); int[] temp_array_primitive = ArrayUtils .toPrimitive(temp_array.toArray(new Integer[temp_array.size()])); // recored the length of total vertices array received from other mappers this.update_mapper_len[i] = temp_array_primitive.length; //create mapping from adj_abs_id to relative t in update offset queue for (int j = 0; j < temp_array_primitive.length; j++) this.abs_v_to_queue[temp_array_primitive[j]] = j; IntArray comm_array = new IntArray(temp_array_primitive, 0, temp_array_primitive.length); //table to communicate with other mappers this.comm_vertex_table.addPartition(new Partition<>(comm_id, comm_array)); } } if (this.verbose) LOG.info("Start regroup comm_vertex_table"); this.mapper.regroup("sc", "regroup-send-recv-vertex", this.comm_vertex_table, new SCPartitioner(this.mapper_num)); // the name of barrier should not be the same as that of regroup // otherwise may cause a deadlock this.mapper.barrier("sc", "regroup-send-recv-sync"); if (this.verbose) LOG.info("Finish regroup comm_vertex_table"); // pack the received requested adj_v_id information into send queues for (int comm_id : this.comm_vertex_table.getPartitionIDs()) { int dst_mapper_id = comm_id & ((1 << 16) - 1); // this shall equal to local_mapper_id int src_mapper_id = comm_id >>> 16; //create send table send_vertex_table .addPartition(new Partition(dst_mapper_id, comm_vertex_table.getPartition(comm_id).get())); if (this.verbose) { //check src id add assertion assertEquals("comm_vertex_table sender not matched ", this.local_mapper_id, src_mapper_id); LOG.info("Send from mapper: " + src_mapper_id + " to mapper: " + dst_mapper_id + "; partition size: " + comm_vertex_table.getPartition(comm_id).get().get().length); } } //release memory for (int i = 0; i < this.mapper_num; i++) this.comm_mapper_vertex[i] = null; this.comm_mapper_vertex = null; }
From source file:com.houghtonassociates.bamboo.plugins.dao.GerritService.java
private GerritCmdProcessor getGerritCmdProcessor() { if (cmdProcessor == null) { cmdProcessor = new GerritCmdProcessor(new GerritConnectionConfig2() { @Override//from ww w . ja v a2s .c o m public File getGerritAuthKeyFile() { return gc.getAuth().getPrivateKeyFile(); } @Override public String getGerritAuthKeyFilePassword() { return gc.getAuth().getPrivateKeyFilePassword(); } @Override public Authentication getGerritAuthentication() { return gc.getAuth(); } @Override public String getGerritHostName() { return gc.getHost(); } @Override public int getGerritSshPort() { return gc.getPort(); } @Override public String getGerritUserName() { return gc.getUsername(); } @Override public String getGerritEMail() { return gc.getUserEmail(); } @Override public int getWatchdogTimeoutSeconds() { // return // (int)TimeUnit.MINUTES.toSeconds(watchdogTimeoutMinutes); return 0; } @Override public WatchTimeExceptionData getExceptionData() { List<Integer> days = new LinkedList<Integer>(); List<TimeSpan> exceptionTimes = new LinkedList<TimeSpan>(); int[] daysAsInt = new int[] {}; daysAsInt = ArrayUtils.toPrimitive(days.toArray(new Integer[days.size()])); return new WatchTimeExceptionData(daysAsInt, exceptionTimes); } @Override public String getGerritProxy() { return gc.getProxy(); } @Override public String getGerritFrontEndUrl() { // TODO Auto-generated method stub return null; } @Override public Credentials getHttpCredentials() { // TODO Auto-generated method stub return null; } @Override public int getWatchdogTimeoutMinutes() { // TODO Auto-generated method stub return 0; } }); } return cmdProcessor; }
From source file:cn.annoreg.mc.s11n.SerializationManager.java
private void initInternalSerializers() { //First part: java internal class. {/*from www .j a va 2 s .c o m*/ InstanceSerializer ser = new InstanceSerializer<Enum>() { @Override public Enum readInstance(NBTBase nbt) throws Exception { NBTTagCompound tag = (NBTTagCompound) nbt; try { Class enumClass = Class.forName(tag.getString("class")); Object[] objs = (Object[]) enumClass.getMethod("values").invoke(null); return (Enum) objs[tag.getInteger("ordinal")]; } catch (Exception e) { ARModContainer.log.error("Failed in enum deserialization. Class: {}.", tag.getString("class")); e.printStackTrace(); return null; } } @Override public NBTBase writeInstance(Enum obj) throws Exception { NBTTagCompound ret = new NBTTagCompound(); ret.setString("class", obj.getClass().getName()); ret.setByte("ordinal", (byte) ((Enum) obj).ordinal()); return ret; } }; setInstanceSerializerFor(Enum.class, ser); } { DataSerializer ser = new DataSerializer<Byte>() { @Override public Byte readData(NBTBase nbt, Byte obj) throws Exception { return ((NBTTagByte) nbt).func_150290_f(); } @Override public NBTBase writeData(Byte obj) throws Exception { return new NBTTagByte(obj); } }; setDataSerializerFor(Byte.TYPE, ser); setDataSerializerFor(Byte.class, ser); } { DataSerializer ser = new DataSerializer<Byte[]>() { @Override public Byte[] readData(NBTBase nbt, Byte[] obj) throws Exception { return ArrayUtils.toObject(((NBTTagByteArray) nbt).func_150292_c()); } @Override public NBTBase writeData(Byte[] obj) throws Exception { return new NBTTagByteArray(ArrayUtils.toPrimitive(obj)); } }; setDataSerializerFor(Byte[].class, ser); } { DataSerializer ser = new DataSerializer<byte[]>() { @Override public byte[] readData(NBTBase nbt, byte[] obj) throws Exception { return ((NBTTagByteArray) nbt).func_150292_c(); } @Override public NBTBase writeData(byte[] obj) throws Exception { return new NBTTagByteArray(obj); } }; setDataSerializerFor(byte[].class, ser); } { DataSerializer ser = new DataSerializer<Double>() { @Override public Double readData(NBTBase nbt, Double obj) throws Exception { return ((NBTTagDouble) nbt).func_150286_g(); } @Override public NBTBase writeData(Double obj) throws Exception { return new NBTTagDouble(obj); } }; setDataSerializerFor(Double.TYPE, ser); setDataSerializerFor(Double.class, ser); } { DataSerializer ser = new DataSerializer<Float>() { @Override public Float readData(NBTBase nbt, Float obj) throws Exception { return ((NBTTagFloat) nbt).func_150288_h(); } @Override public NBTBase writeData(Float obj) throws Exception { return new NBTTagFloat(obj); } }; setDataSerializerFor(Float.TYPE, ser); setDataSerializerFor(Float.class, ser); } { DataSerializer ser = new DataSerializer<Integer>() { @Override public Integer readData(NBTBase nbt, Integer obj) throws Exception { return ((NBTTagInt) nbt).func_150287_d(); } @Override public NBTBase writeData(Integer obj) throws Exception { return new NBTTagInt(obj); } }; setDataSerializerFor(Integer.TYPE, ser); setDataSerializerFor(Integer.class, ser); } { DataSerializer ser = new DataSerializer<Integer[]>() { @Override public Integer[] readData(NBTBase nbt, Integer[] obj) throws Exception { return ArrayUtils.toObject(((NBTTagIntArray) nbt).func_150302_c()); } @Override public NBTBase writeData(Integer[] obj) throws Exception { return new NBTTagIntArray(ArrayUtils.toPrimitive(obj)); } }; setDataSerializerFor(Integer[].class, ser); } { DataSerializer ser = new DataSerializer<int[]>() { @Override public int[] readData(NBTBase nbt, int[] obj) throws Exception { return ((NBTTagIntArray) nbt).func_150302_c(); } @Override public NBTBase writeData(int[] obj) throws Exception { return new NBTTagIntArray(obj); } }; setDataSerializerFor(int[].class, ser); } { DataSerializer ser = new DataSerializer<Long>() { @Override public Long readData(NBTBase nbt, Long obj) throws Exception { return ((NBTTagLong) nbt).func_150291_c(); } @Override public NBTBase writeData(Long obj) throws Exception { return new NBTTagLong(obj); } }; setDataSerializerFor(Long.TYPE, ser); setDataSerializerFor(Long.class, ser); } { DataSerializer ser = new DataSerializer<Short>() { @Override public Short readData(NBTBase nbt, Short obj) throws Exception { return ((NBTTagShort) nbt).func_150289_e(); } @Override public NBTBase writeData(Short obj) throws Exception { return new NBTTagShort(obj); } }; setDataSerializerFor(Short.TYPE, ser); setDataSerializerFor(Short.class, ser); } { DataSerializer ser = new DataSerializer<String>() { @Override public String readData(NBTBase nbt, String obj) throws Exception { return ((NBTTagString) nbt).func_150285_a_(); } @Override public NBTBase writeData(String obj) throws Exception { return new NBTTagString(obj); } }; setDataSerializerFor(String.class, ser); } { //TODO: Maybe there is a more data-friendly method? DataSerializer ser = new DataSerializer<Boolean>() { @Override public Boolean readData(NBTBase nbt, Boolean obj) throws Exception { return ((NBTTagCompound) nbt).getBoolean("v"); } @Override public NBTBase writeData(Boolean obj) throws Exception { NBTTagCompound tag = new NBTTagCompound(); tag.setBoolean("v", obj); return tag; } }; setDataSerializerFor(Boolean.class, ser); setDataSerializerFor(Boolean.TYPE, ser); } //Second part: Minecraft objects. { DataSerializer ser = new DataSerializer<NBTTagCompound>() { @Override public NBTTagCompound readData(NBTBase nbt, NBTTagCompound obj) throws Exception { return (NBTTagCompound) nbt; } @Override public NBTBase writeData(NBTTagCompound obj) throws Exception { return obj; } }; setDataSerializerFor(NBTTagCompound.class, ser); } { InstanceSerializer ser = new InstanceSerializer<Entity>() { @Override public Entity readInstance(NBTBase nbt) throws Exception { int[] ids = ((NBTTagIntArray) nbt).func_150302_c(); World world = SideHelper.getWorld(ids[0]); if (world != null) { return world.getEntityByID(ids[1]); } return null; } @Override public NBTBase writeInstance(Entity obj) throws Exception { return new NBTTagIntArray(new int[] { obj.dimension, obj.getEntityId() }); } }; setInstanceSerializerFor(Entity.class, ser); } { InstanceSerializer ser = new InstanceSerializer<TileEntity>() { @Override public TileEntity readInstance(NBTBase nbt) throws Exception { int[] ids = ((NBTTagIntArray) nbt).func_150302_c(); World world = SideHelper.getWorld(ids[0]); if (world != null) { return world.getTileEntity(ids[1], ids[2], ids[3]); } return null; } @Override public NBTBase writeInstance(TileEntity obj) throws Exception { return new NBTTagIntArray(new int[] { obj.getWorldObj().provider.dimensionId, obj.xCoord, obj.yCoord, obj.zCoord }); } }; setInstanceSerializerFor(TileEntity.class, ser); } { //TODO this implementation can not be used to serialize player's inventory container. InstanceSerializer ser = new InstanceSerializer<Container>() { @Override public Container readInstance(NBTBase nbt) throws Exception { int[] ids = ((NBTTagIntArray) nbt).func_150302_c(); World world = SideHelper.getWorld(ids[0]); if (world != null) { Entity entity = world.getEntityByID(ids[1]); if (entity instanceof EntityPlayer) { return SideHelper.getPlayerContainer((EntityPlayer) entity, ids[2]); } } return SideHelper.getPlayerContainer(null, ids[2]); } @Override public NBTBase writeInstance(Container obj) throws Exception { EntityPlayer player = SideHelper.getThePlayer(); if (player != null) { //This is on client. The server needs player to get the Container. return new NBTTagIntArray(new int[] { player.worldObj.provider.dimensionId, player.getEntityId(), obj.windowId }); } else { //This is on server. The client doesn't need player (just use thePlayer), use MAX_VALUE here. return new NBTTagIntArray(new int[] { Integer.MAX_VALUE, 0, obj.windowId }); } } }; setInstanceSerializerFor(Container.class, ser); } { InstanceSerializer ser = new InstanceSerializer<World>() { @Override public World readInstance(NBTBase nbt) throws Exception { return SideHelper.getWorld(((NBTTagInt) nbt).func_150287_d()); } @Override public NBTBase writeInstance(World obj) throws Exception { return new NBTTagInt(obj.provider.dimensionId); } }; setInstanceSerializerFor(World.class, ser); } { DataSerializer ser = new DataSerializer<ItemStack>() { @Override public ItemStack readData(NBTBase nbt, ItemStack obj) throws Exception { if (obj == null) { return ItemStack.loadItemStackFromNBT((NBTTagCompound) nbt); } else { obj.readFromNBT((NBTTagCompound) nbt); return obj; } } @Override public NBTBase writeData(ItemStack obj) throws Exception { NBTTagCompound nbt = new NBTTagCompound(); obj.writeToNBT(nbt); return nbt; } }; setDataSerializerFor(ItemStack.class, ser); } { DataSerializer ser = new DataSerializer<Vec3>() { @Override public Vec3 readData(NBTBase nbt, Vec3 obj) throws Exception { NBTTagCompound tag = (NBTTagCompound) nbt; return Vec3.createVectorHelper(tag.getFloat("x"), tag.getFloat("y"), tag.getFloat("z")); } @Override public NBTBase writeData(Vec3 obj) throws Exception { NBTTagCompound nbt = new NBTTagCompound(); nbt.setFloat("x", (float) obj.xCoord); nbt.setFloat("y", (float) obj.yCoord); nbt.setFloat("z", (float) obj.zCoord); return nbt; } }; setDataSerializerFor(Vec3.class, ser); } //network part { DataSerializer ser = new DataSerializer<NetworkTerminal>() { @Override public NetworkTerminal readData(NBTBase nbt, NetworkTerminal obj) throws Exception { return NetworkTerminal.fromNBT(nbt); } @Override public NBTBase writeData(NetworkTerminal obj) throws Exception { return obj.toNBT(); } }; setDataSerializerFor(NetworkTerminal.class, ser); } { Future.FutureSerializer ser = new Future.FutureSerializer(); setDataSerializerFor(Future.class, ser); setInstanceSerializerFor(Future.class, ser); } //misc { DataSerializer ser = new DataSerializer<BitSet>() { @Override public BitSet readData(NBTBase nbt, BitSet obj) throws Exception { NBTTagCompound tag = (NBTTagCompound) nbt; BitSet ret = BitSet.valueOf(tag.getByteArray("l")); return ret; } @Override public NBTBase writeData(BitSet obj) throws Exception { NBTTagCompound tag = new NBTTagCompound(); byte[] barray = obj.toByteArray(); tag.setByteArray("l", barray); return tag; } }; setDataSerializerFor(BitSet.class, ser); } }
From source file:at.tugraz.sss.serv.SSFileU.java
public static String readPNGToBase64Str(final String pngFilePath) throws Exception { final DataInputStream fileReader = new DataInputStream(new FileInputStream(new File(pngFilePath))); final List<Byte> bytes = new ArrayList<>(); byte[] chunk = new byte[SSSocketU.socketTranmissionSize]; int fileChunkLength; while (true) { fileChunkLength = fileReader.read(chunk); if (fileChunkLength == -1) { break; }/*from ww w. j a v a2 s . co m*/ for (int counter = 0; counter < fileChunkLength; counter++) { bytes.add(chunk[counter]); } } return "data:image/png;base64," + DatatypeConverter .printBase64Binary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()]))); }
From source file:de.hpi.isg.mdms.benchmark.ConstraintInsertPerfomanceBenchmark.java
@Test public void testInsertUniqueColumnCombinationsIntoDefaultMetadataStore() throws Exception { LOGGER.info("Creating Java-serialized metadata store..."); File metadataStoreFile = createTempFile("ser"); MetadataStore metadataStore = MetadataStoreFactory.createAndSaveDefaultMetadataStore(metadataStoreFile); LOGGER.info("Creating schema..."); int numTables = 1000; int numColumnsPerTable = 100; int numColumns = numTables * numColumnsPerTable; Schema schema = createSchema(metadataStore, numTables, numColumnsPerTable); metadataStore.flush();/*from w ww . j av a 2s . c o m*/ LOGGER.info("Generating UCCs..."); int numDesiredInds = 100000; double indProbablity = numDesiredInds / Math.pow(numTables * numColumnsPerTable, 2); // Boost probablity to speed up generation. indProbablity = Math.sqrt(indProbablity); Collection<Column[]> inclusionDependencies = new LinkedList<Column[]>(); Random random = new Random(); OuterLoop: for (final Table table1 : schema.getTables()) { for (final Table table2 : schema.getTables()) { for (final Column column1 : table1.getColumns()) { for (final Column column2 : table2.getColumns()) { if (column1 != column2 && random.nextDouble() <= indProbablity) { inclusionDependencies.add(new Column[] { column1, column2 }); if (inclusionDependencies.size() >= numDesiredInds) { break OuterLoop; } } } } } } LOGGER.info("Inserting the {} generated UCCs...", inclusionDependencies.size()); long startTimeGross = System.currentTimeMillis(); ConstraintCollection<UniqueColumnCombination> constraintCollection = metadataStore .createConstraintCollection(null, UniqueColumnCombination.class); long startTimeNet = System.currentTimeMillis(); for (Column[] columnPair : inclusionDependencies) { Collection<Column> uniqueColumns = Collections.singleton(columnPair[0]); List<Integer> ids = new ArrayList<>(); for (Column c : uniqueColumns) { ids.add(c.getId()); } int[] intArray = ArrayUtils.toPrimitive(ids.toArray(new Integer[ids.size()])); final UniqueColumnCombination.Reference reference = new UniqueColumnCombination.Reference(intArray); UniqueColumnCombination.buildAndAddToCollection(reference, constraintCollection); } long endTimeNet = System.currentTimeMillis(); metadataStore.flush(); long endTimeGross = System.currentTimeMillis(); double numInsertsPerSecGross = 1000d * numColumns / (endTimeGross - startTimeGross); double numInsertsPerSecNet = 1000d * numColumns / (endTimeNet - startTimeNet); LOGGER.info("[gross] Inserted in {} ms ({} inserts/s)", endTimeGross - startTimeGross, numInsertsPerSecGross); LOGGER.info("[net] Inserted in {} ms ({} inserts/s)", endTimeNet - startTimeNet, numInsertsPerSecNet); LOGGER.info("File size: {} MB", metadataStoreFile.length() / (1024 * 1024)); }
From source file:de.vanita5.twittnuker.util.AsyncTwitterWrapper.java
@NonNull public long[] getSendingDraftIds() { return ArrayUtils.toPrimitive(mSendingDraftIds.toArray(new Long[mSendingDraftIds.size()])); }