List of usage examples for org.apache.commons.lang ArrayUtils subarray
public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive)
Produces a new boolean
array containing the elements between the start and end indices.
From source file:org.carrot2.text.vsm.TermDocumentMatrixBuilder.java
/** * Builds a term document matrix from data provided in the <code>context</code>, * stores the result in there./*from w w w. j a va 2s. c o m*/ */ public void buildTermDocumentMatrix(VectorSpaceModelContext vsmContext) { final PreprocessingContext preprocessingContext = vsmContext.preprocessingContext; final int documentCount = preprocessingContext.documents.size(); final int[] stemsTf = preprocessingContext.allStems.tf; final int[][] stemsTfByDocument = preprocessingContext.allStems.tfByDocument; final byte[] stemsFieldIndices = preprocessingContext.allStems.fieldIndices; if (documentCount == 0) { vsmContext.termDocumentMatrix = NNIDoubleFactory2D.nni.make(0, 0); vsmContext.stemToRowIndex = new IntIntOpenHashMap(); return; } // Determine the index of the title field int titleFieldIndex = -1; final String[] fieldsName = preprocessingContext.allFields.name; for (int i = 0; i < fieldsName.length; i++) { if (Document.TITLE.equals(fieldsName[i])) { titleFieldIndex = i; break; } } // Determine the stems we, ideally, should include in the matrix int[] stemsToInclude = computeRequiredStemIndices(preprocessingContext); // Sort stems by weight, so that stems get included in the matrix in the order // of frequency final double[] stemsWeight = new double[stemsToInclude.length]; for (int i = 0; i < stemsToInclude.length; i++) { final int stemIndex = stemsToInclude[i]; stemsWeight[i] = termWeighting.calculateTermWeight(stemsTf[stemIndex], stemsTfByDocument[stemIndex].length / 2, documentCount) * getWeightBoost(titleFieldIndex, stemsFieldIndices[stemIndex]); } final int[] stemWeightOrder = IndirectSort.sort(0, stemsWeight.length, new IndirectComparator.DescendingDoubleComparator(stemsWeight)); // Calculate the number of terms we can include to fulfill the max matrix size final int maxRows = maximumMatrixSize / documentCount; final DoubleMatrix2D tdMatrix = NNIDoubleFactory2D.nni.make(Math.min(maxRows, stemsToInclude.length), documentCount); for (int i = 0; i < stemWeightOrder.length && i < maxRows; i++) { final int stemIndex = stemsToInclude[stemWeightOrder[i]]; final int[] tfByDocument = stemsTfByDocument[stemIndex]; final int df = tfByDocument.length / 2; final byte fieldIndices = stemsFieldIndices[stemIndex]; int tfByDocumentIndex = 0; for (int documentIndex = 0; documentIndex < documentCount; documentIndex++) { if (tfByDocumentIndex * 2 < tfByDocument.length && tfByDocument[tfByDocumentIndex * 2] == documentIndex) { double weight = termWeighting.calculateTermWeight(tfByDocument[tfByDocumentIndex * 2 + 1], df, documentCount); weight *= getWeightBoost(titleFieldIndex, fieldIndices); tfByDocumentIndex++; tdMatrix.set(i, documentIndex, weight); } } } // Convert stemsToInclude into tdMatrixStemIndices GenericPermuting.permute(stemsToInclude, stemWeightOrder); stemsToInclude = ArrayUtils.subarray(stemsToInclude, 0, tdMatrix.rows()); final IntIntOpenHashMap stemToRowIndex = new IntIntOpenHashMap(); for (int i = 0; i < stemsToInclude.length; i++) { stemToRowIndex.put(stemsToInclude[i], i); } // Store the results vsmContext.termDocumentMatrix = tdMatrix; vsmContext.stemToRowIndex = stemToRowIndex; }
From source file:org.codehaus.groovy.grails.commons.metaclass.BaseApiProvider.java
@SuppressWarnings("unchecked") public void addApi(final Object apiInstance) { if (apiInstance == null) { return;//from ww w.ja v a 2s .c o m } Class<?> currentClass = apiInstance.getClass(); while (currentClass != Object.class) { final Method[] declaredMethods = currentClass.getDeclaredMethods(); for (final Method javaMethod : declaredMethods) { final int modifiers = javaMethod.getModifiers(); if (!isNotExcluded(javaMethod, modifiers)) { continue; } if (Modifier.isStatic(modifiers)) { if (isConstructorCallMethod(javaMethod)) { constructors.add(javaMethod); } else { staticMethods.add(javaMethod); } } else { instanceMethods.add(new ReflectionMetaMethod(new CachedMethod(javaMethod)) { @Override public String getName() { String methodName = super.getName(); if (isConstructorCallMethod(javaMethod)) { return CTOR_GROOVY_METHOD; } return methodName; } @Override public Object invoke(Object object, Object[] arguments) { if (arguments.length == 0) { return super.invoke(apiInstance, new Object[] { object }); } return super.invoke(apiInstance, ArrayUtils.add(checkForGStrings(arguments), 0, object)); } private Object[] checkForGStrings(Object[] arguments) { for (int i = 0; i < arguments.length; i++) { if (arguments[i] instanceof GString) { arguments[i] = arguments[i].toString(); } } return arguments; } @Override public CachedClass[] getParameterTypes() { final CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length > 0) { return (CachedClass[]) ArrayUtils.subarray(paramTypes, 1, paramTypes.length); } return paramTypes; } }); } } currentClass = currentClass.getSuperclass(); } }
From source file:org.codehaus.groovy.grails.web.util.StreamByteBuffer.java
public String readAsString(Charset charset) throws CharacterCodingException { int unreadSize = totalBytesUnread(); if (unreadSize > 0) { CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE); CharBuffer charbuffer = CharBuffer.allocate(unreadSize); ByteBuffer buf = null;/*from w w w.j a va 2 s . c om*/ while (prepareRead() != -1) { buf = currentReadChunk.readToNioBuffer(); boolean endOfInput = (prepareRead() == -1); CoderResult result = decoder.decode(buf, charbuffer, endOfInput); if (endOfInput) { if (!result.isUnderflow()) { result.throwException(); } } } CoderResult result = decoder.flush(charbuffer); if (buf.hasRemaining()) { throw new IllegalStateException("There's a bug here, buffer wasn't read fully."); } if (!result.isUnderflow()) { result.throwException(); } charbuffer.flip(); String str; if (charbuffer.hasArray()) { int len = charbuffer.remaining(); char[] ch = charbuffer.array(); if (len != ch.length) { ch = ArrayUtils.subarray(ch, 0, len); } str = StringCharArrayAccessor.createString(ch); } else { str = charbuffer.toString(); } return str; } return null; }
From source file:org.codelabor.example.remoting.message.services.MessageAdapterServiceImpl.java
public void call(HeaderDTO inputHeaderDTO, DataDTO inputDataDTO, HeaderDTO outputHeaderDTO, DataDTO outputDataDTO) throws Exception { // stnd_tlg_thwh_len KsfcHeaderDTO ksfcInputHeaderDTO = (KsfcHeaderDTO) inputHeaderDTO; int stndTlgThwhLen = ksfcInputHeaderDTO.getLength() + inputDataDTO.toBytes().length; ksfcInputHeaderDTO.getSystemHeaderDTO().setStndTlgThwhLen(stndTlgThwhLen); // tlg_dscd/*from w w w . java 2 s.c o m*/ ksfcInputHeaderDTO.getSystemHeaderDTO().setTlgDscd("S"); // itn_incd ksfcInputHeaderDTO.getSystemHeaderDTO().setItnIncd("KSF"); // sys_dscd ksfcInputHeaderDTO.getSystemHeaderDTO().setSysDscd("UA"); // tr_id String nextId = idGenerationService.getNextStringId(); String pid = nextId.substring(3, 11); ksfcInputHeaderDTO.getSystemHeaderDTO().setTrIdChCode(nextId.substring(0, 3)); ksfcInputHeaderDTO.getSystemHeaderDTO().setTrIdPid(pid); ksfcInputHeaderDTO.getSystemHeaderDTO().setTrIdReqDt(nextId.substring(11, 17)); ksfcInputHeaderDTO.getSystemHeaderDTO().setTrIdReqTm(nextId.substring(17, 25)); ksfcInputHeaderDTO.getSystemHeaderDTO().setTrIdSeq(nextId.substring(25, 27)); // lnkg_sno ksfcInputHeaderDTO.getSystemHeaderDTO().setLnkgSno("000"); // og_tr_id ksfcInputHeaderDTO.getSystemHeaderDTO().setOgTrId(nextId); // cd_vl_stup_dscd ksfcInputHeaderDTO.getSystemHeaderDTO().setCdVlStupDscd(0); // sync_dscd ksfcInputHeaderDTO.getSystemHeaderDTO().setSyncDscd("S"); // rsp_tpcd ksfcInputHeaderDTO.getSystemHeaderDTO().setRspTpcd(0); // tlg_pout_tpcd ksfcInputHeaderDTO.getSystemHeaderDTO().setTlgPoutTpcd(0); // nxt_tr_yn ksfcInputHeaderDTO.getSystemHeaderDTO().setNxtTrYn(0); // tmnl_ip ksfcInputHeaderDTO.getSystemHeaderDTO().setTmnlIp(SecurityContextUtil.getRemoteAddress()); // tr_rqs_chnl_cd ksfcInputHeaderDTO.getSystemHeaderDTO().setTrRqsChnlCd("IBS"); // og_tr_rqs_chnl_cd ksfcInputHeaderDTO.getSystemHeaderDTO().setOgTrRqsChnlCd("IBS"); // tr_prcs_rsl_cd ksfcInputHeaderDTO.getSystemHeaderDTO().setTrPrcsRslCd(0); // og_tr_cd ksfcInputHeaderDTO.getSystemHeaderDTO().setOgTrCd(nextId); // hnd_empno ksfcInputHeaderDTO.getTransactionHeaderDTO().setHndEmpno("Z9001"); // lgn_yn // ksfcInputHeaderDTO.getTransactionHeaderDTO().setLgnYn(BooleanUtils.toInteger(SecurityContextUtil.isAuthenticated())); ksfcInputHeaderDTO.getTransactionHeaderDTO().setLgnYn(1); // clsn_bf_af_dscd ksfcInputHeaderDTO.getTransactionHeaderDTO().setClsnBfAfDscd("0"); // iccd_rdr_inp_yn ksfcInputHeaderDTO.getTransactionHeaderDTO().setIccdRdrInpYn("N"); // pinpd_inp_yn ksfcInputHeaderDTO.getTransactionHeaderDTO().setPinpdInpYn("N"); // bkbk_prtr_inp_yn ksfcInputHeaderDTO.getTransactionHeaderDTO().setBkbkPrtrInpYn("N"); // rspr_aprv_tr_obj_yn ksfcInputHeaderDTO.getTransactionHeaderDTO().setRsprAprvTrObjYn("0"); // cnc_tlg_dscd ksfcInputHeaderDTO.getTransactionHeaderDTO().setCncTlgDscd(0); // tlg_tr_tpcd ksfcInputHeaderDTO.getTransactionHeaderDTO().setTlgTrTpcd(0); byte[] inputHeaderBytes = inputHeaderDTO.toBytes(); byte[] inputDataBytes = inputDataDTO.toBytes(); byte[] inputMessageBytes = ArrayUtils.addAll(inputHeaderBytes, inputDataBytes); String inputMessage = new String(inputMessageBytes, charsetName); String outputMessage = socketAdapterService.send(inputMessage); if (log.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("input message: ").append(inputMessage); log.debug(sb.toString()); sb = new StringBuilder(); sb.append("output message: ").append(outputMessage); log.debug(sb.toString()); } byte[] outputMessageBytes = outputMessage.getBytes(charsetName); byte[] outputHeaderBytes = ArrayUtils.subarray(outputMessageBytes, 0, outputHeaderDTO.getLength()); byte[] outputDataBytes = ArrayUtils.subarray(outputMessageBytes, outputHeaderDTO.getLength(), outputMessageBytes.length); outputHeaderDTO.fromBytes(outputHeaderBytes); if (!outputHeaderDTO.isError()) { outputDataDTO.fromBytes(outputDataBytes); } }
From source file:org.collectionspace.chain.pathtrie.TrieNode.java
private boolean call_here(String[] path, int off, Object pay) throws Exception { for (int i = path.length - off; i > -1; i--) { // ??? A little help? TrieMethod m = values.get(i);/*w w w. ja v a 2 s . c om*/ if (m != null) { m.run(pay, (String[]) ArrayUtils.subarray(path, off, path.length)); return true; } } return false; }
From source file:org.datanucleus.store.hbase.fieldmanager.FetchFieldManager.java
private UUID fetchUUIDInternal(AbstractMemberMetaData mmd, byte[] bytes) { if (bytes == null) { // Handle missing field String dflt = HBaseUtils.getDefaultValueForMember(mmd); return dflt != null ? UUID.fromString(dflt) : null; }/* w w w . j a v a 2s.co m*/ if (mmd.isSerialized()) { ByteArrayInputStream bis = null; ObjectInputStream ois = null; try { bis = new ByteArrayInputStream(bytes); ois = new ObjectInputStream(bis); return UUID.class.cast(ois.readObject()); } catch (ClassNotFoundException e) { throw new NucleusException(e.getMessage(), e); } catch (IOException e) { throw new NucleusException(e.getMessage(), e); } finally { IOUtils.closeStream(ois); IOUtils.closeStream(bis); } } else { if (bytes.length == 16) { // serialized as bytes long upper = Bytes.toLong(bytes); long lower = Bytes.toLong(ArrayUtils.subarray(bytes, 8, 16)); return new UUID(upper, lower); } else { final String value = new String(bytes, Charsets.UTF_8); return UUID.fromString(value); } } }
From source file:org.diffkit.util.DKStringUtil.java
public static String unquote(String target_, Quote kind_) { DKValidate.notNull(kind_);/* ww w . j ava 2 s. c om*/ if (target_ == null) return null; if (target_.length() < 2) return target_; char[] chars = target_.toCharArray(); if (!((chars[0] == kind_._character) && (chars[chars.length - 1] == kind_._character))) return target_; return new String(ArrayUtils.subarray(chars, 1, chars.length - 1)); }
From source file:org.dragonet.net.ClientChunkManager.java
/** * Send a single chunk to the client/*from w ww . j av a 2 s.c o m*/ * * @param chunkX The chunk X coordinate * @param chunkZ The chunk Z coordinate */ private synchronized void sendChunk(int chunkX, int chunkZ) { try { GlowChunkSnapshot chunk = this.getSession().getPlayer().getWorld().getChunkAt(chunkX, chunkZ) .getChunkSnapshot(); ByteArrayOutputStream totalData = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(totalData); if (writer.getEndianness() == PEBinaryUtils.BIG_ENDIAN) { writer.switchEndianness(); } writer.writeInt(chunkX); writer.writeInt(chunkZ); for (int x = 0; x < 16; x++) { for (int z = 0; z < 16; z++) { for (int y = 0; y < 128; y++) { writer.writeByte((byte) (this.getSession().getTranslator() .translateBlockToPE(chunk.getBlockTypeId(x, y, z)) & 0xFF)); } } } writer.write(new byte[16384]); for (int i = 0; i < 16384; i++) { writer.writeByte((byte) 0xF0); } for (int i = 0; i < 16384; i++) { writer.writeByte((byte) 0x11); } for (int i = 0; i < 256; i++) { writer.writeByte((byte) 0x00); } for (int i = 0; i < 256; i++) { writer.writeByte((byte) 0x00); writer.writeByte((byte) 0x85); writer.writeByte((byte) 0xB2); writer.writeByte((byte) 0x4A); } Deflater deflater = new Deflater(2); deflater.reset(); deflater.setInput(totalData.toByteArray()); deflater.finish(); byte[] bufferDeflate = new byte[65536]; int deflatedSize = deflater.deflate(bufferDeflate); FullChunkPacket packet = new FullChunkPacket(); packet.compressedData = ArrayUtils.subarray(bufferDeflate, 0, deflatedSize); this.getSession().send(packet); } catch (IOException e) { } }
From source file:org.dragonet.net.inf.mcpe.NetworkHandler.java
private void processPacket(DatagramPacket packet) { try {//from w w w . j a v a 2 s .c om PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData())); int raknetPID = reader.readByte() & 0xFF; switch (raknetPID) { case RaknetConstants.ID_PING_OPEN_CONNECTIONS: ServerInfoPacket pkReply = new ServerInfoPacket(); pkReply.time = reader.readLong(); pkReply.serverID = serverID; pkReply.serverName = this.getManager().getServer().getServer().getName(); pkReply.encode(); this.udp.send(pkReply.getData(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1: reader.read(16); //MAGIC reader.readByte(); //RakNet Protocol short mtu = (short) ((packet.getLength() - 18) & 0xFFFF); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1); writer.write(RaknetConstants.magic); writer.writeLong(NetworkHandler.serverID); writer.writeByte((byte) 0x00); writer.writeShort(mtu); this.udp.send(bos.toByteArray(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2: reader.read(16); reader.readByte(); reader.readInt(); reader.readShort(); short clientMTU = reader.readShort(); long clientID = reader.readLong(); ByteArrayOutputStream bos8 = new ByteArrayOutputStream(); PEBinaryWriter writer8 = new PEBinaryWriter(bos8); writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2); writer8.write(RaknetConstants.magic); writer8.writeLong(NetworkHandler.serverID); writer8.writeAddress(packet.getAddress(), (short) packet.getPort()); writer8.writeShort(clientMTU); writer8.writeByte((byte) 0x00); this.send(bos8.toByteArray(), packet.getSocketAddress()); PENetworkClient session = new PENetworkClient(this, packet.getSocketAddress(), clientID, clientMTU); clients.put(packet.getSocketAddress().toString(), session); //this.server.getServer().getSessionRegistry().add(session); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { RaknetDataPacket dataPacket = new RaknetDataPacket( ArrayUtils.subarray(packet.getData(), 1, packet.getLength())); dataPacket.decode(); clients.get(getClientKey(packet.getSocketAddress())).processDataPacket(dataPacket); } break; case 0xC0: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { clients.get(getClientKey(packet.getSocketAddress())) .processACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length)); } break; case 0xA0: if (this.manager.getSessions().containsKey(getClientKey(packet.getSocketAddress()))) { clients.get(getClientKey(packet.getSocketAddress())) .processNACKPacket(ArrayUtils.subarray(packet.getData(), 1, packet.getData().length)); } break; } } catch (IOException e) { } }
From source file:org.dragonet.net.NetworkHandler.java
private void processPacket(DatagramPacket packet) { try {/*from w ww. java 2s . c o m*/ PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(packet.getData())); int raknetPID = reader.readByte() & 0xFF; switch (raknetPID) { case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_1: reader.read(16); //MAGIC reader.readByte(); //RakNet Protocol short mtu = (short) ((packet.getLength() - 18) & 0xFFFF); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PEBinaryWriter writer = new PEBinaryWriter(bos); writer.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_1); writer.write(RaknetConstants.magic); writer.writeLong(NetworkHandler.serverID); writer.writeByte((byte) 0x00); writer.writeShort(mtu); this.udp.send(bos.toByteArray(), packet.getSocketAddress()); break; case RaknetConstants.ID_OPEN_CONNECTION_REQUEST_2: reader.read(16); reader.read(5); reader.readShort(); short clientMTU = reader.readShort(); long clientID = reader.readLong(); ByteArrayOutputStream bos8 = new ByteArrayOutputStream(); PEBinaryWriter writer8 = new PEBinaryWriter(bos8); writer8.writeByte(RaknetConstants.ID_OPEN_CONNECTION_REPLY_2); writer8.write(RaknetConstants.magic); writer8.writeLong(NetworkHandler.serverID); writer8.writeShort((short) (packet.getPort() & 0xFFFF)); writer8.writeShort(clientMTU); writer8.writeByte((byte) 0x00); this.send(bos8.toByteArray(), packet.getSocketAddress()); DragonetSession session = new DragonetSession(this.server, packet.getSocketAddress(), clientID, clientMTU); this.sessions.put(packet.getSocketAddress().toString(), session); //this.server.getServer().getSessionRegistry().add(session); break; case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: if (this.sessions.containsKey(packet.getSocketAddress().toString())) { RaknetDataPacket dataPacket = new RaknetDataPacket( ArrayUtils.subarray(packet.getData(), 1, packet.getLength())); dataPacket.decode(); this.sessions.get(packet.getSocketAddress().toString()).processDataPacket(dataPacket); } break; } } catch (IOException e) { } }