@Override public boolean process(TProtocol in, TProtocol out) throws TException { TMessage msg = in.readMessageBegin(); String name = msg.name; int idx = name.indexOf('.'); if (idx != -1) { name = name.substring(idx + 1); } TDynamicFunction f = descManager.getFunction(name); if (f == null) throw new TException("unknow function '" + name + "'"); Reader reader = new Reader(f.getManager()); Xdom param = reader.readStruct(f.getParamStruct(), in); in.readMessageEnd(); if (!f.isOneway()) { XdomMap rep; TDynamicField retf = f.getReturnStruct().getField("success"); if (retf.getTypeValue() != TType.VOID) { Xdom ret = handle(name, param); rep = new XdomMap(); rep.put("success", ret); } else { rep = new XdomMap(); } TMessage repmsg = new TMessage(name, TMessageType.REPLY, msg.seqid); out.writeMessageBegin(repmsg); Writer writer = new Writer(f.getManager()); writer.writeStruct(f.getReturnStruct(), rep, out); out.writeMessageEnd(); out.getTransport().flush(); } return true; }
public static void main(String args[]) { Reader reader = new Reader(4, "ivanthefool.txt"); System.out.println("------------------"); System.out.println("Chunked Text Below"); System.out.println("------------------"); reader.printStoryInChunks(); }
/** * @param job Calculates each partition weight based on the undirected graph for comparison. If * static partitioning is applied then skipping will be applied here. */ public static void initializePartitionsWeight() { ArrayList<String> neighbours; long pw = 0, me, other; for (int i = 0; i < partitionsNames.size(); i++) { String currentPartition = partitionsNames.get(i); me = partitionsSizes.get(currentPartition); neighbours = new ArrayList<String>(); pw = me * me; for (int j = 0; j < partitionsNames.size(); j++) { other = partitionsSizes.get(partitionsNames.get(j)); if (currentPartition.startsWith("G")) { String otherPartition = partitionsNames.get(j); int myRow = Reader.getRow(currentPartition); int myCol = Reader.getCol(currentPartition); int otherRow = Reader.getRow(otherPartition); int otherCol = Reader.getCol(otherPartition); if ((((myRow != myCol) && (myCol >= otherRow)) || ((otherRow != otherCol) && (otherCol >= myRow))) // new || otherPartition.equals(currentPartition)) continue; // verified } neighbours.add(partitionsNames.get(j)); pw += me * other; } partitionsWeights.put(currentPartition, pw); undirectedGraph.put(currentPartition, neighbours); } }
/** @see EntityInput#readKeyObject */ public Object readKeyObject(Format format) { /* Create and read the object using the given key format. */ Reader reader = format.getReader(); Object o = reader.newInstance(this, rawAccess); return reader.readObject(o, this, rawAccess); }
public ReadOperation( String operationName, Reader<?> reader, OutputReceiver[] receivers, String counterPrefix, String systemStageName, CounterSet.AddCounterMutator addCounterMutator, StateSampler stateSampler) { super( operationName, receivers, counterPrefix, addCounterMutator, stateSampler, reader.getStateSamplerStateKind()); this.reader = reader; this.byteCount = addCounterMutator.addCounter( Counter.longs(bytesCounterName(counterPrefix, operationName), SUM)); reader.addObserver(new ReaderObserver()); reader.setStateSamplerAndOperationName(stateSampler, operationName); this.totalParallelismCounter = addCounterMutator.addCounter( Counter.doubles(totalParallelismCounterName(systemStageName), SUM)); // Set only when a task is started or split. totalParallelismCounter.resetToValue(boundParallelism(reader.getTotalParallelism())); this.remainingParallelismCounter = addCounterMutator.addCounter( Counter.doubles(remainingParallelismCounterName(systemStageName), SUM)); }
public void run() { try { providerSocket = new ServerSocket(port, 10); providerSocket.setSoTimeout(5000); while (!stopServer) { try { connection = providerSocket.accept(); } catch (SocketTimeoutException e) { log.info("........Socket is timed out.........."); continue; } Reader reader = new Reader(); reader.connectionReceived = this.connection; new Thread(reader).start(); } } catch (IOException ioException) { ioException.printStackTrace(); } finally { try { providerSocket.close(); } catch (Exception e) { } } log.info("Closing connection"); }
public void printFileInfo() throws Exception { System.out.println("Reader: " + m_reader); System.out.println("# Rows: " + m_reader.getNumberOfRows()); System.out.println("# Types in the file: " + m_types.size()); for (int i = 0; i < m_types.size(); i++) { System.out.println("Type " + i + ": " + m_types.get(i).getKind()); } System.out.println("Compression: " + m_reader.getCompression()); if (m_reader.getCompression() != CompressionKind.NONE) { System.out.println("Compression size: " + m_reader.getCompressionSize()); } m_oi = (StructObjectInspector) m_reader.getObjectInspector(); System.out.println("object inspector type category: " + m_oi.getCategory()); System.out.println("object inspector type name : " + m_oi.getTypeName()); System.out.println("Number of columns in the table: " + m_fields.size()); // Print the type info: for (int i = 0; i < m_fields.size(); i++) { System.out.println("Column " + i + " name: " + m_fields.get(i).getFieldName()); ObjectInspector lv_foi = m_fields.get(i).getFieldObjectInspector(); System.out.println("Column " + i + " type category: " + lv_foi.getCategory()); System.out.println("Column " + i + " type name: " + lv_foi.getTypeName()); } }
// YUVオブジェクトのバイナリデータを読み込み、マーカーを検知 public void readYUV( final byte[] data, int dataWidth, int dataHeight, int left, int top, int width, int height, boolean reserversion) { final LuminanceSource source = new PlanarYUVLuminanceSource( data, dataWidth, dataHeight, left, top, width, height, reserversion); final BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source)); // final Reader reader = new MultiFormatReader(); final Reader reader = new QRCodeReader(); try { // 結果をゲット mQRResult.setResultData(reader.decode(binaryBitmap)); mFoundFlag = true; } // 見つからなかった! catch (NotFoundException ex) { ex.printStackTrace(); mFoundFlag = false; } catch (ChecksumException ex) { ex.printStackTrace(); mFoundFlag = false; } catch (FormatException ex) { ex.printStackTrace(); mFoundFlag = false; } }
@Override public void run(String... arg0) throws Exception { dictionary.set("java", "object oriented"); /*dictionary.set("linux", "rulez"); dictionary.set("mac", "beutifull"); dictionary.set("solaris", "old but gold"); dictionary.set("red hat", "new and fit"); dictionary.set("debian", "just old");*/ Writer writer = new Writer(dictionary, "Mr. Writer"); Reader reader1 = new Reader(dictionary, "Mrs Reader 1"); Reader reader2 = new Reader(dictionary, "Mrs Reader 2"); Reader reader3 = new Reader(dictionary, "Mrs Reader 3"); Reader reader4 = new Reader(dictionary, "Mrs Reader 4"); Reader reader5 = new Reader(dictionary, "Mrs Reader 5"); log.info("Inciando thread de writer"); writer.setPriority(Thread.MAX_PRIORITY); writer.start(); log.info("Inciando thread de reader Mrs Reader 1"); reader1.start(); log.info("Inciando thread de reader Mrs Reader 2"); reader2.start(); log.info("Inciando thread de reader Mrs Reader 3"); reader3.start(); log.info("Inciando thread de reader Mrs Reader 4"); reader4.start(); log.info("Inciando thread de reader Mrs Reader 5"); reader5.start(); }
@Override public void sendLLRPMessageToAllReaders(byte[] message) throws RemoteException, LLRPRuntimeException { for (Reader reader : readers.values()) { reader.send(message); } }
public Pair<Long, Long> copyMessageInbox(long messageId) { Reader reader = readerFor(getMessage(messageId)); SmsMessageRecord record = reader.getNext(); ContentValues contentValues = new ContentValues(); contentValues.put(TYPE, (record.getType() & ~Types.BASE_TYPE_MASK) | Types.BASE_INBOX_TYPE); contentValues.put(ADDRESS, record.getIndividualRecipient().getNumber()); contentValues.put(ADDRESS_DEVICE_ID, record.getRecipientDeviceId()); contentValues.put(DATE_RECEIVED, System.currentTimeMillis()); contentValues.put(DATE_SENT, record.getDateSent()); contentValues.put(PROTOCOL, 31337); contentValues.put(READ, 0); contentValues.put(BODY, record.getBody().getBody()); contentValues.put(THREAD_ID, record.getThreadId()); SQLiteDatabase db = databaseHelper.getWritableDatabase(); long newMessageId = db.insert(TABLE_NAME, null, contentValues); DatabaseFactory.getThreadDatabase(context).update(record.getThreadId(), true); notifyConversationListeners(record.getThreadId()); jobManager.add(new TrimThreadJob(context, record.getThreadId())); reader.close(); return new Pair<>(newMessageId, record.getThreadId()); }
@Override public void reset() { if (readers != null) { for (Reader reader : readers) { reader.reset(); } } }
public void disconnect() { try { reader.destroy(); writer.destroy(); socket.close(); reader.destroy(); } catch (Exception e) { } }
@Test public void mmapThreadTest() throws IOException, InterruptedException, ExecutionException { Reader reader = new Reader(ReaderTest.getFile("MaxMind-DB-test-decoder.mmdb")); try { MultiThreadedTest.threadTest(reader); } finally { reader.close(); } }
@RequestMapping(method = RequestMethod.POST, value = "/charge") @ResponseBody public Charge charge(HttpServletRequest request) { // 获取请求body中的参数 JSONObject params = Tools.getParams(request); // 文章的标识 String articleId = params.getString("articleId"); // 付款读者的标识 String wechat = params.getString("wgateid"); // 付款的渠道 String channel = params.getString("channel"); // 当前页面的URL String url = params.getString("url"); // 付款的金额 int amount = params.getInt("amount"); // 获取请求的IP地址 String ip = Tools.getIP(request); Deal deal = new Deal(wechat, articleId); deal.setDealPayment(amount); deal.setClientIp(ip); if (dealService.queryDealRecord(deal).getResponseCode() == ResponseCode.RESPONSE_NULL) { ResultData createMessage = dealService.createDealRecord(deal); if (createMessage.getResponseCode() == ResponseCode.RESPONSE_OK) { logger.debug("Insert a deal record successfully."); } else { logger.debug("Fail to insert a deal record."); return null; } } // 设置订单的ID String orderNo = deal.getDealId(); // 根据文章的标识查询文章的信息 Article article = new Article(); article.setArticleId(articleId); article = (Article) articleService.queryArticle(article).getData(); Reader reader = new Reader(); if (!StringUtils.isEmpty(wechat)) { reader.setReaderWechat(wechat); ResultData readerExistMessage = readerService.queryReader(reader); if (readerExistMessage.getResponseCode() == ResponseCode.RESPONSE_NULL) { readerService.createReader(reader); } else if (readerExistMessage.getResponseCode() == ResponseCode.RESPONSE_ERROR) { return null; } } ChargeForm form = new ChargeForm(orderNo, article, reader, channel, amount, ip, url); ResultData result = dealService.charge(form); Charge charge = (Charge) result.getData(); logger.debug(charge.toString()); return charge; }
@Override public void undefine(String readerName) throws RemoteException, LLRPRuntimeException { if (!containsReader(readerName)) { throw new LLRPRuntimeException("Reader '" + readerName + "' does not exist."); } Reader reader = readers.remove(readerName); reader.disconnect(); commit(); }
@Override public Object newInstance(EntityInput input, boolean rawAccess) { Reader reader = proxyFormat.getReader(); if (rawAccess) { return reader.newInstance(null, true); } else { PersistentProxy proxy = (PersistentProxy) reader.newInstance(null, false); proxy = (PersistentProxy) reader.readObject(proxy, input, false); return proxy.convertProxy(); } }
public int openFile() throws Exception { m_reader = OrcFile.createReader(m_file_path, OrcFile.readerOptions(m_conf)); m_types = m_reader.getTypes(); m_oi = (StructObjectInspector) m_reader.getObjectInspector(); m_fields = m_oi.getAllStructFieldRefs(); m_rr = m_reader.rows(); return 0; }
public static void readTag(Reader r) throws Exception { epcToReadDataMap = new ConcurrentHashMap<String, TagRecord>(); // Create Reader object, connecting to physical device try { // add tag listener r.addReadListener(readListener); // search for tags in the background r.startReading(); } catch (Exception re) { throw re; } }
public int getData(Reader r) { try { System.out.println(r.getName() + " has entered with data = " + data + "."); try { r.sleep(500); } catch (InterruptedException ex) { } return data; } finally { System.out.println(r.getName() + " has exited with data = " + data + "."); } }
private Result decodeInternal(BinaryBitmap image) throws NotFoundException { if (readers != null) { for (Reader reader : readers) { try { return reader.decode(image, hints); } catch (ReaderException re) { // continue } } } throw NotFoundException.getNotFoundInstance(); }
public int read(int timeout) throws IOException { if ((reader == null) || !reader.isAlive()) reader = new Reader(); try { reader.join(timeout); } catch (InterruptedException e) { throw new IOException("read was interrupted", e); } handleException(); if (read == null) throw new TimeoutException(); return read; }
public void importFile() { try { Reader r; Vm.showWait(true); r = new FileReader(file); parse(r); r.close(); Vm.showWait(false); } catch (Exception e) { // Vm.debug(e.toString()); Vm.showWait(false); } }
private void testReadWrite(Random rng, Writer wr) throws InterruptedException { ArrayBlockingQueue<byte[]> q = newQueue(); InputStream is = create(q); wr.init(q); wr.start(); Reader rd = new Reader(rng, is); rd.run(); wr.join(); Assert.assertNull(wr.exn); Assert.assertNull(rd.exn); System.out.printf("sums %x -> %x\n", wr.getSum(), rd.getSum()); Assert.assertEquals(wr.getSum(), rd.getSum()); }
/** Scan tag */ public static Hashtable scanTag(Reader in) throws IOException { Hashtable atts = new Hashtable(); skipSpace(in); while (c >= 0 && c != '>') { String att = scanIdentifier(in); String val = ""; skipSpace(in); if (c == '=') { int quote = -1; c = in.read(); skipSpace(in); if ((c == '\'') || (c == '\"')) { quote = c; c = in.read(); } StringBuffer buf = new StringBuffer(); while ((c > 0) && (((quote < 0) && (c != ' ') && (c != '\t') && (c != '\n') && (c != '\r') && (c != '>')) || ((quote >= 0) && (c != quote)))) { buf.append((char) c); c = in.read(); } if (c == quote) { c = in.read(); } skipSpace(in); val = buf.toString(); } // statusMsgStream.println("PUT " + att + " = '" + val + "'"); if (!val.equals("")) { atts.put(att.toLowerCase(j86.java.util.Locale.ENGLISH), val); } while (true) { if ((c == '>') || (c < 0) || ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || (c == '_')) break; c = in.read(); } // skipSpace(in); } return atts; }
public static void main(String[] args) { String datFile = args[0]; String dstFile = args[1]; String ansFile = args[2]; String data = reader.getString(datFile); String[] lines = data.split("\n"); int p = Integer.valueOf(lines[0]); int n = Integer.valueOf(lines[1]); int[] polynomial = new int[n + 1]; String[] coefficients = lines[2].split(" "); for (int i = 0; i < coefficients.length; i++) polynomial[n - i] = Integer.valueOf(coefficients[i]); polynomial = Polynomial.clear(polynomial); String sigma = reader.getString(dstFile); int s = Integer.valueOf(sigma); int ml = 0; int[][] minimals = new int[2 * s][]; for (int i = 1; i < s; i++) { int[] pol = Polynomial.field(MinimalPolynomial.findPolynomial(polynomial, i, p), p); int[] min = MinimalPolynomial.findMinimal(pol, polynomial, p); minimals[ml] = min; ml++; } Set<List<Integer>> clean = removeDuplicates(minimals, ml); int[] result = {1}; for (List<Integer> a : clean) { int[] t = toArray(a); result = Polynomial.field(Polynomial.multiply(result, t), p); } StringBuilder res = new StringBuilder(); res.append(p); res.append("\n"); res.append(new Double(Math.pow(p, n)).intValue() - 1); res.append("\n"); for (int i = result.length - 1; i >= -(Math.pow(p, n) - 1 - result.length); i--) { if (i < 0) res.append("0"); else res.append(result[i]); res.append(" "); } res.append("\n"); writer.writeString(ansFile, res.toString()); }
public static void main(String args[]) throws Exception { Reader in = new Reader(); PrintWriter out = new PrintWriter(System.out, true); int t = in.nextInt(); while (t-- != 0) { Long a = in.nextLong(); Long b = in.nextLong(); Long c = in.nextLong(); long ans = ((a * a) - (2 * b)); out.println(ans); } }
/** * Find the key range for bucket files. * * @param reader the reader * @param options the options for reading with * @throws IOException */ private void discoverKeyBounds(Reader reader, Reader.Options options) throws IOException { RecordIdentifier[] keyIndex = OrcRecordUpdater.parseKeyIndex(reader); long offset = options.getOffset(); long maxOffset = options.getMaxOffset(); int firstStripe = 0; int stripeCount = 0; boolean isTail = true; List<StripeInformation> stripes = reader.getStripes(); for (StripeInformation stripe : stripes) { if (offset > stripe.getOffset()) { firstStripe += 1; } else if (maxOffset > stripe.getOffset()) { stripeCount += 1; } else { isTail = false; break; } } if (firstStripe != 0) { minKey = keyIndex[firstStripe - 1]; } if (!isTail) { maxKey = keyIndex[firstStripe + stripeCount - 1]; } }
public void run() { final ZLTextHyperlink hyperlink = Reader.getTextView().getCurrentHyperlink(); if (hyperlink != null) { switch (hyperlink.Type) { case FBHyperlinkType.EXTERNAL: openInBrowser(hyperlink.Id); break; case FBHyperlinkType.INTERNAL: Reader.tryOpenFootnote(hyperlink.Id); break; } return; } DictionaryUtil.openWordInDictionary(myBaseActivity, Reader.getTextView().getSelectedText()); }
@Override public void init(String remoteHost, int remotePort, InputStream in, OutputStream out) throws TransportException { connInfo = new ConnInfo(remoteHost, remotePort, in, out); try { log.info("Client identity string: {}", clientID); connInfo.out.write((clientID + "\r\n").getBytes(IOUtils.UTF8)); connInfo.out.flush(); // Read server's ID final Buffer.PlainBuffer buf = new Buffer.PlainBuffer(); while ((serverID = readIdentification(buf)).isEmpty()) { int b = connInfo.in.read(); if (b == -1) throw new TransportException("Server closed connection during identification exchange"); buf.putByte((byte) b); } log.info("Server identity string: {}", serverID); } catch (IOException e) { throw new TransportException(e); } reader.start(); }