code
stringlengths
73
34.1k
label
stringclasses
1 value
public static List<String> readLines(File file, Charset charset) throws IOException { // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return readLines( file, charset, new LineProcessor<List...
java
@CanIgnoreReturnValue // some processors won't return a useful result public static <T> T readBytes(File file, ByteProcessor<T> processor) throws IOException { return asByteSource(file).read(processor); }
java
static Expression decomposeCondition(Expression e, HsqlArrayList conditions) { if (e == null) { return Expression.EXPR_TRUE; } Expression arg1 = e.getLeftNode(); Expression arg2 = e.getRightNode(); int type = e.getType...
java
void assignToLists() { int lastOuterIndex = -1; for (int i = 0; i < rangeVariables.length; i++) { if (rangeVariables[i].isLeftJoin || rangeVariables[i].isRightJoin) { lastOuterIndex = i; } if (lastOuterIndex == i) { ...
java
void assignToLists(Expression e, HsqlArrayList[] expressionLists, int first) { set.clear(); e.collectRangeVariables(rangeVariables, set); int index = rangeVarSet.getLargestIndex(set); // condition is independent of tables if no range variable is found if...
java
void assignToRangeVariables() { for (int i = 0; i < rangeVariables.length; i++) { boolean isOuter = rangeVariables[i].isLeftJoin || rangeVariables[i].isRightJoin; if (isOuter) { assignToRangeVariable(rangeVariables[i], i, ...
java
void setInConditionsAsTables() { for (int i = rangeVariables.length - 1; i >= 0; i--) { RangeVariable rangeVar = rangeVariables[i]; Expression in = inExpressions[i]; if (in != null) { Index index = rangeVar.rangeTable.getIndexForColumn( ...
java
public static LargeBlockTask getStoreTask(BlockId blockId, ByteBuffer block) { return new LargeBlockTask() { @Override public LargeBlockResponse call() throws Exception { Exception theException = null; try { LargeBlockManager.getInstanc...
java
public static LargeBlockTask getReleaseTask(BlockId blockId) { return new LargeBlockTask() { @Override public LargeBlockResponse call() throws Exception { Exception theException = null; try { LargeBlockManager.getInstance().releaseBlock...
java
public static LargeBlockTask getLoadTask(BlockId blockId, ByteBuffer block) { return new LargeBlockTask() { @Override public LargeBlockResponse call() throws Exception { Exception theException = null; try { LargeBlockManager.getInstance...
java
public static <T, U> Pair<T, U> of(T x, U y) { return new Pair<T, U>(x, y); }
java
public static Routine newRoutine(Method method) { Routine routine = new Routine(SchemaObject.FUNCTION); int offset = 0; Class[] params = method.getParameterTypes(); String className = method.getDeclaringClass().getName(); StringBuffer sb =...
java
public ByteBuffer saveToBuffer(InstanceId instId) throws IOException { if (instId == null) { throw new IOException("Null instance ID."); } if (m_serData == null) { throw new IOException("Uninitialized hashinator snapshot data."); } // Assu...
java
public InstanceId restoreFromBuffer(ByteBuffer buf) throws IOException { buf.rewind(); // Assumes config data is the last field. int dataSize = buf.remaining() - OFFSET_DATA; if (dataSize <= 0) { throw new IOException("Hashinator snapshot data is too small.")...
java
public void restoreFromFile(File file) throws IOException { byte[] rawData = new byte[(int) file.length()]; ByteBuffer bufData = null; FileInputStream fis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); dis = new DataInputStr...
java
public static File createFileForSchema(String ddlText) throws IOException { File temp = File.createTempFile("literalschema", ".sql"); temp.deleteOnExit(); FileWriter out = new FileWriter(temp); out.write(ddlText); out.close(); return temp; }
java
public void addLiteralSchema(String ddlText) throws IOException { File temp = createFileForSchema(ddlText); addSchema(URLEncoder.encode(temp.getAbsolutePath(), "UTF-8")); }
java
public void addStmtProcedure(String name, String sql, String partitionInfoString) { addProcedures(new ProcedureInfo(new String[0], name, sql, ProcedurePartitionData.fromPartitionInfoString(partitionInfoString))); }
java
public static byte[] hexStringToByteArray(String s) throws IOException { int l = s.length(); byte[] data = new byte[l / 2 + (l % 2)]; int n, b = 0; boolean high = true; int i = 0; for (int j = 0; j < l; j++) { char c = s...
java
public static BitMap sqlBitStringToBitMap(String s) throws IOException { int l = s.length(); int n; int bitIndex = 0; BitMap map = new BitMap(l); for (int j = 0; j < l; j++) { char c = s.charAt(j); if (c == ' ') { continue;...
java
public static String byteArrayToBitString(byte[] bytes, int bitCount) { char[] s = new char[bitCount]; for (int j = 0; j < bitCount; j++) { byte b = bytes[j / 8]; s[j] = BitMap.isSet(b, j % 8) ? '1' : '0'; } return new...
java
public static String byteArrayToSQLBitString(byte[] bytes, int bitCount) { char[] s = new char[bitCount + 3]; s[0] = 'B'; s[1] = '\''; int pos = 2; for (int j = 0; j < bitCount; j++) { byte b = bytes[j / 8]; s[pos++] = BitMap.isSet(b, j % 8) ? '1' ...
java
public static void writeHexBytes(byte[] o, int from, byte[] b) { int len = b.length; for (int i = 0; i < len; i++) { int c = ((int) b[i]) & 0xff; o[from++] = HEXBYTES[c >> 4 & 0xf]; o[from++] = HEXBYTES[c & 0xf]; } }
java
public static int stringToUTFBytes(String str, HsqlByteArrayOutputStream out) { int strlen = str.length(); int c, count = 0; if (out.count + strlen + 8 > out.buffer.length) { out.ensureRoom(strlen + 8); } char[] a...
java
public static String inputStreamToString(InputStream x, String encoding) throws IOException { InputStreamReader in = new InputStreamReader(x, encoding); StringWriter writer = new StringWriter(); int blocksize = 8 * 1024; char[] buffer ...
java
static int count(final String s, final char c) { int pos = 0; int count = 0; if (s != null) { while ((pos = s.indexOf(c, pos)) > -1) { count++; pos++; } } return count; }
java
public static void registerLog4jMBeans() throws JMException { if (Boolean.getBoolean("zookeeper.jmx.log4j.disable") == true) { return; } MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // Create and Register the top level Log4J MBean HierarchyD...
java
public void create(final String path, byte data[], List<ACL> acl, CreateMode createMode, StringCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath, createMode.isSequential()); final String serverPath = prependCh...
java
public void delete(final String path, int version, VoidCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath; // maintain semantics even in chroot case // specifically - ...
java
public void setData(final String path, byte data[], int version, StatCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new Requ...
java
public void getACL(final String path, Stat stat, ACLCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setTyp...
java
public void setACL(final String path, List<ACL> acl, int version, StatCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new Req...
java
public void sync(final String path, VoidCallback cb, Object ctx) { verbotenThreadCheck(); final String clientPath = path; PathUtils.validatePath(clientPath); final String serverPath = prependChroot(clientPath); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.Op...
java
@Override public final boolean callProcedureWithTimeout( ProcedureCallback callback, int batchTimeout, String procName, Object... parameters) throws IOException, NoConnectionsException { //Time unit doesn't matter in this case since the...
java
private Object[] getUpdateCatalogParams(File catalogPath, File deploymentPath) throws IOException { Object[] params = new Object[2]; if (catalogPath != null) { params[0] = ClientUtils.fileToBytes(catalogPath); } else { params[0] = null; } if (d...
java
@Override public void close() throws InterruptedException { if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new RuntimeException("Can't invoke backpressureBarrier from within the client callback thread " + " without deadlocking the client library"); ...
java
public boolean backpressureBarrier(final long start, long timeoutNanos) throws InterruptedException { if (m_isShutdown) { return false; } if (m_blessedThreadIds.contains(Thread.currentThread().getId())) { throw new RuntimeException("Can't invoke backpressureBarrier from w...
java
public Object[] readData(Type[] colTypes) throws IOException, HsqlException { int l = colTypes.length; Object[] data = new Object[l]; Object o; Type type; for (int i = 0; i < l; i++) { if (checkNull()) { continue; } ...
java
public static int matchGenreDescription(String description) { if (description != null && description.length() > 0) { for (int i = 0; i < ID3v1Genres.GENRES.length; i++) { if (ID3v1Genres.GENRES[i].equalsIgnoreCase(description)) { return i; } } } return -1; }
java
private int measureSize(int specType, int contentSize, int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = Math.max(contentSize, specSize); } ...
java
private void initSuffixMargin() { int defSuffixLRMargin = Utils.dp2px(mContext, DEFAULT_SUFFIX_LR_MARGIN); boolean isSuffixLRMarginNull = true; if (mSuffixLRMargin >= 0) { isSuffixLRMarginNull = false; } if (isShowDay && mSuffixDayTextWidth > 0) { if (mS...
java
public int getAllContentWidth() { float width = getAllContentWidthBase(mTimeTextWidth); if (!isConvertDaysToHours && isShowDay) { if (isDayLargeNinetyNine) { Rect rect = new Rect(); String tempDay = String.valueOf(mDay); mTimeTextPaint.getText...
java
private float initTimeTextBaselineAndTimeBgTopPadding(int viewHeight, int viewPaddingTop, int viewPaddingBottom, int contentAllHeight) { float topPaddingSize; if (viewPaddingTop == viewPaddingBottom) { // center topPaddingSize = (viewHeight - contentAllHeight) / 2; } else...
java
public int filterRGB(int pX, int pY, int pARGB) { // Get color components int r = pARGB >> 16 & 0xFF; int g = pARGB >> 8 & 0xFF; int b = pARGB & 0xFF; // Scale to new contrast r = LUT[r]; g = LUT[g]; b = LUT[b]; // Return ARGB pixel, l...
java
protected static String buildTimestamp(final Calendar pCalendar) { if (pCalendar == null) { return CALENDAR_IS_NULL_ERROR_MESSAGE; } // The timestamp format StringBuilder timestamp = new StringBuilder(); //timestamp.append(DateUtil.getMonthName(new Integer(pCalendar.get(Calendar.MO...
java
public static long roundToHour(final long pTime, final TimeZone pTimeZone) { int offset = pTimeZone.getOffset(pTime); return ((pTime / HOUR) * HOUR) - offset; }
java
public static long roundToDay(final long pTime, final TimeZone pTimeZone) { int offset = pTimeZone.getOffset(pTime); return (((pTime + offset) / DAY) * DAY) - offset; }
java
private PropertyConverter getConverterForType(Class pType) { Object converter; Class cl = pType; // Loop until we find a suitable converter do { // Have a match, return converter if ((converter = getInstance().converters.get(cl)) != null) { ...
java
public Object toObject(String pString, Class pType, String pFormat) throws ConversionException { if (pString == null) { return null; } if (pType == null) { throw new MissingTypeException(); } // Get converter PropertyConver...
java
public static void merge(List<File> inputFiles, File outputFile) throws IOException { ImageOutputStream output = null; try { output = ImageIO.createImageOutputStream(outputFile); for (File file : inputFiles) { ImageInputStream input = null; try { ...
java
public static List<File> split(File inputFile, File outputDirectory) throws IOException { ImageInputStream input = null; List<File> outputFiles = new ArrayList<>(); try { input = ImageIO.createImageInputStream(inputFile); List<TIFFPage> pages = getPages(input); ...
java
public static String getStats() { long total = sCacheHit + sCacheMiss + sCacheUn; double hit = ((double) sCacheHit / (double) total) * 100.0; double miss = ((double) sCacheMiss / (double) total) * 100.0; double un = ((double) sCacheUn / (double) total) * 100.0; // Default ...
java
private Object[] readIdentities(Class pObjClass, Hashtable pMapping, Hashtable pWhere, ObjectMapper pOM) throws SQLException { sCacheUn++; // Build SQL query string if (pWhere == null) pWhere = new Hashtable(); String[] ...
java
public Object readObject(DatabaseReadable pReadable) throws SQLException { return readObject(pReadable.getId(), pReadable.getClass(), pReadable.getMapping()); }
java
public Object readObject(Object pId, Class pObjClass, Hashtable pMapping) throws SQLException { return readObject(pId, pObjClass, pMapping, null); }
java
public Object[] readObjects(DatabaseReadable pReadable) throws SQLException { return readObjects(pReadable.getClass(), pReadable.getMapping(), null); }
java
private void setPropertyValue(Object pObj, String pProperty, Object pValue) { Method m = null; Class[] cl = {pValue.getClass()}; try { //Util.setPropertyValue(pObj, pProperty, pValue); // Find method m...
java
private Object getPropertyValue(Object pObj, String pProperty) { Method m = null; Class[] cl = new Class[0]; try { //return Util.getPropertyValue(pObj, pProperty); // Find method m = pObj.getClass(). getMethod("get" + String...
java
private void setChildObjects(Object pParent, ObjectMapper pOM) throws SQLException { if (pOM == null) { throw new NullPointerException("ObjectMapper in readChildObjects " + "cannot be null!!"); } for (Enumeration keys = pOM.m...
java
private String buildWhereClause(String[] pKeys, Hashtable pMapping) { StringBuilder sqlBuf = new StringBuilder(); for (int i = 0; i < pKeys.length; i++) { String column = (String) pMapping.get(pKeys[i]); sqlBuf.append(" AND "); sqlBuf.append(column); ...
java
public static Properties loadMapping(Class pClass) { try { return SystemUtil.loadProperties(pClass); } catch (FileNotFoundException fnf) { // System.err... err... System.err.println("ERROR: " + fnf.getMessage()); } catch (IOExcept...
java
protected Class getType(String pType) { Class cl = (Class) mTypes.get(pType); if (cl == null) { // throw new NoSuchTypeException(); } return cl; }
java
protected Object getObject(String pType) /*throws XxxException*/ { // Get class Class cl = getType(pType); // Return the new instance (requires empty public constructor) try { return cl.newInstance(); } catch (Exception e) { // throw new XxxException(e); ...
java
protected void checkBounds(int index) throws IOException { assertInput(); if (index < getMinIndex()) { throw new IndexOutOfBoundsException("index < minIndex"); } int numImages = getNumImages(false); if (numImages != -1 && index >= numImages) { throw new I...
java
protected static boolean hasExplicitDestination(final ImageReadParam pParam) { return pParam != null && ( pParam.getDestination() != null || pParam.getDestinationType() != null || !ORIGIN.equals(pParam.getDestinationOffset()) ...
java
public BufferedImage getImage() throws IOException { if (image == null) { // No content, no image if (bufferedOut == null) { return null; } // Read from the byte buffer InputStream byteStream = bufferedOut.createInputStream(); ...
java
private static QTDecompressor getDecompressor(final ImageDesc pDescription) { for (QTDecompressor decompressor : sDecompressors) { if (decompressor.canDecompress(pDescription)) { return decompressor; } } return null; }
java
public static BufferedImage decompress(final ImageInputStream pStream) throws IOException { ImageDesc description = ImageDesc.read(pStream); if (PICTImageReader.DEBUG) { System.out.println(description); } QTDecompressor decompressor = getDecompressor(description); ...
java
protected boolean trigger(ServletRequest pRequest) { boolean trigger = false; if (pRequest instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) pRequest; String accept = getAcceptedFormats(request); String originalFormat = getServl...
java
private static String findBestFormat(Map<String, Float> pFormatQuality) { String acceptable = null; float acceptQuality = 0.0f; for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) { float qValue = entry.getValue(); if (qValue > acceptQuality) { ...
java
private void adjustQualityFromAccept(Map<String, Float> pFormatQuality, HttpServletRequest pRequest) { // Multiply all q factors with qs factors // No q=.. should be interpreted as q=1.0 // Apache does some extras; if both explicit types and wildcards // (without qaulity factor) ar...
java
private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) { // NOTE: The values are all made-up. May need tuning. // If pImage.getColorModel() instanceof IndexColorModel // JPEG qs*=0.6 // If NOT binary or 2 color index // ...
java
private static void adjustQuality(Map<String, Float> pFormatQuality, String pFormat, float pFactor) { Float oldValue = pFormatQuality.get(pFormat); if (oldValue != null) { pFormatQuality.put(pFormat, oldValue * pFactor); //System.out.println("New vallue after multiplying with...
java
private float getKnownFormatQuality(String pFormat) { for (int i = 0; i < sKnownFormats.length; i++) { if (pFormat.equals(sKnownFormats[i])) { return knownFormatQuality[i]; } } return 0.1f; }
java
public void write(final byte pBytes[], final int pOff, final int pLen) throws IOException { out.write(pBytes, pOff, pLen); }
java
public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException { if (reachedEOF) { return -1; } // TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream... while (buffer.hasRemaining()) { in...
java
private float[] LABtoXYZ(float L, float a, float b, float[] xyzResult) { // Significant speedup: Removing Math.pow float y = (L + 16.0f) / 116.0f; float y3 = y * y * y; // Math.pow(y, 3.0); float x = (a / 500.0f) + y; float x3 = x * x * x; // Math.pow(x, 3.0); float z = y...
java
public Object toObject(final String pString, final Class pType, final String pFormat) throws ConversionException { if (StringUtil.isEmpty(pString)) { return null; } try { if (pType.equals(BigInteger.class)) { return new BigInteger(pString); // No f...
java
public void setPenSize(Dimension2D pSize) { penSize.setSize(pSize); graphics.setStroke(getStroke(penSize)); }
java
protected void setupForFill(final Pattern pPattern) { graphics.setPaint(pPattern); graphics.setComposite(getCompositeFor(QuickDraw.PAT_COPY)); }
java
private static Arc2D.Double toArc(final Rectangle2D pRectangle, int pStartAngle, int pArcAngle, final boolean pClosed) { return new Arc2D.Double(pRectangle, 90 - pStartAngle, -pArcAngle, pClosed ? Arc2D.PIE : Arc2D.OPEN); }
java
public void drawString(String pString) { setupForText(); graphics.drawString(pString, (float) getPenPosition().getX(), (float) getPenPosition().getY()); }
java
public static Dimension readDimension(final DataInput pStream) throws IOException { int h = pStream.readShort(); int v = pStream.readShort(); return new Dimension(h, v); }
java
public static String readStr31(final DataInput pStream) throws IOException { String text = readPascalString(pStream); int length = 31 - text.length(); if (length < 0) { throw new IOException("String length exceeds maximum (31): " + text.length()); } pStream.skipBytes(...
java
public static String readPascalString(final DataInput pStream) throws IOException { // Get as many bytes as indicated by byte count int length = pStream.readUnsignedByte(); byte[] bytes = new byte[length]; pStream.readFully(bytes, 0, length); return new String(bytes, ENCODING);...
java
protected void doFilterImpl(ServletRequest pRequest, ServletResponse pResponse, FilterChain pChain) throws IOException, ServletException { // TODO: Max size configuration, to avoid DOS attacks? OutOfMemory // Size parameters int width = ServletUtil.getIntParameter(pRequest, sizeWidthParam, ...
java
public void setTimeout(int pTimeout) { if (pTimeout < 0) { // Must be positive throw new IllegalArgumentException("Timeout must be positive."); } timeout = pTimeout; if (socket != null) { try { socket.setSoTimeout(pTimeout); } ...
java
public synchronized InputStream getInputStream() throws IOException { if (!connected) { connect(); } // Nothing to return if (responseCode == HTTP_NOT_FOUND) { throw new FileNotFoundException(url.toString()); } int length; if (inputStream...
java
private void connect(final URL pURL, PasswordAuthentication pAuth, String pAuthType, int pRetries) throws IOException { // Find correct port final int port = (pURL.getPort() > 0) ? pURL.getPort() : HTTP_DEFAULT_PORT; // Create socket if we don't have one ...
java
private Socket createSocket(final URL pURL, final int pPort, int pConnectTimeout) throws IOException { Socket socket; final Object current = this; SocketConnector connector; Thread t = new Thread(connector = new SocketConnector() { private IOException mConnectException = nul...
java
private static void writeRequestHeaders(OutputStream pOut, URL pURL, String pMethod, Properties pProps, boolean pUsingProxy, PasswordAuthentication pAuth, String pAuthType) { PrintWriter out = new PrintWriter(pOut, true); // autoFlush if (!pUsingProxy) { ...
java
private static int findEndOfHeader(byte[] pBytes, int pEnd) { byte[] header = HTTP_HEADER_END.getBytes(); // Normal condition, check all bytes for (int i = 0; i < pEnd - 4; i++) { // Need 4 bytes to match if ((pBytes[i] == header[0]) && (pBytes[i + 1] == header[1]) && (pBytes[i + 2...
java
private static InputStream detatchResponseHeader(BufferedInputStream pIS) throws IOException { // Store header in byte array ByteArrayOutputStream bytes = new ByteArrayOutputStream(); pIS.mark(BUF_SIZE); byte[] buffer = new byte[BUF_SIZE]; int length; int headerEnd; ...
java
private static Properties parseHeaderFields(String[] pHeaders) { Properties headers = new Properties(); // Get header information int split; String field; String value; for (String header : pHeaders) { //System.err.println(pHeaders[i]); if ((spli...
java
private static String[] parseResponseHeader(InputStream pIS) throws IOException { List<String> headers = new ArrayList<String>(); // Wrap Stream in Reader BufferedReader in = new BufferedReader(new InputStreamReader(pIS)); // Get response status String header; while ((...
java
public int filterRGB(int pX, int pY, int pARGB) { // Get color components int r = pARGB >> 16 & 0xFF; int g = pARGB >> 8 & 0xFF; int b = pARGB & 0xFF; // ITU standard: Gray scale=(222*Red+707*Green+71*Blue)/1000 int gray = (222 * r + 707 * g + 71 * b) / 10...
java
public final int decode(final InputStream stream, final ByteBuffer buffer) throws IOException { // TODO: Allow decoding < row.length at a time and get rid of this assertion... if (buffer.capacity() < row.length) { throw new AssertionError("This decoder needs a buffer.capacity() of at least o...
java
public void init() throws ServletException { // Get the name of the upload directory. String uploadDirParam = getInitParameter("uploadDir"); if (!StringUtil.isEmpty(uploadDirParam)) { try { URL uploadDirURL = getServletContext().getResource(uploadDirParam); ...
java
private static boolean copyDir(File pFrom, File pTo, boolean pOverWrite) throws IOException { if (pTo.exists() && !pTo.isDirectory()) { throw new IOException("A directory may only be copied to another directory, not to a file"); } pTo.mkdirs(); // mkdir? boolean allOkay...
java
public static boolean copy(InputStream pFrom, OutputStream pTo) throws IOException { Validate.notNull(pFrom, "from"); Validate.notNull(pTo, "to"); // TODO: Consider using file channels for faster copy where possible // Use buffer size two times byte array, to avoid i/o bottleneck...
java