text:
import sys
import os
import socket
import struct
import select
import time
import threading
import argparse
import netifaces

from adb import adb_commands
from adb import common

deviceAddresses = []

def ip2int(addr):
    return struct.unpack("!I", socket.inet_aton(addr))[0]

def int2ip(addr):
    return socket.inet_ntoa(struct.pack("!I", addr))

def connect_with_adb(ipaddr,port):
    global deviceAddresses
    device_serial = '%s:%d' % (ipaddr,port)
    cnt = 0
    while cnt < 5:
        try:
            connection = adb_commands.AdbCommands.ConnectDevice(serial=device_serial)
        except:
            #print 'discover_tcp: connection error to', device_serial
            pass
        else:
            if 'hostname.txt' in connection.Shell('ls /mnt/sdcard/'):
                name = connection.Shell('cat /mnt/sdcard/hostname.txt').strip()
                connection.Close()
                print 'discover_tcp: ', ipaddr, name
                deviceAddresses[ipaddr] = name
                return
            else:
                print 'discover_tcp: ', ipaddr, " /mnt/sdcard/hostname.txt not found"
                deviceAddresses[ipaddr] =  ipaddr
                return
        cnt = cnt+1

def open_adb_socket(dest_addr,port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setblocking(0)
    sock.connect_ex((dest_addr,port))
    return sock

# non-Darwin version
def do_work_poll(start, end, port, get_hostname):
    print "scanning "+int2ip(start)+" to "+int2ip(end)
    connected = []
    total = end-start

    READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
    READ_WRITE = READ_ONLY | select.POLLOUT
    poller = select.poll()

    while (start <= end):
        fd_map = {}
        while (start <= end):
            try:
                s = open_adb_socket(int2ip(start),port)
            except:
                break
            else:
                fd_map[s.fileno()] = (start,s)
                start = start+1
                poller.register(s, READ_WRITE)
        time.sleep(0.2)
        events = poller.poll(0.1)
        for fd,flag in events:
            (addr,sock) = fd_map[fd]
            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) == 0:
                print 'ADDCON', fd, int2ip(addr)
                connected.append(int2ip(addr))
        for fd,t in fd_map.iteritems():
            poller.unregister(t[1])
            t[1].close()
        sys.stdout.write("\r%d/%d" % (total-(end-start),total))
        sys.stdout.flush()
    print
    if get_hostname:
        for c in connected:
            connect_with_adb(c,port)

# Darwin version
def do_work_kqueue(start, end, port, get_hostname):
    print "kqueue scanning "+int2ip(start)+" to "+int2ip(end)
    connected = []
    total = end-start

    while (start <= end):
        kq = select.kqueue()
        fd_map = {}
        kevents = []
        while (start <= end):
            try:
                s = open_adb_socket(int2ip(start),port)
            except:
                break
            else:
                fd_map[s.fileno()] = (start,s)
                start = start+1
                kevents.append(select.kevent(s,filter=select.KQ_FILTER_WRITE))
        kq.control(kevents,0,0)
        time.sleep(0.2)
        for k in kq.control([],len(kevents),0.1):
            w = fd_map[k.ident][1]
            addr = fd_map[w.fileno()][0]
            if w.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) == 0:
                print 'ADDCON2', k.ident, w.fileno(), int2ip(addr), fd_map[w.fileno()]
                connected.append(int2ip(addr))
        for fd,t in fd_map.iteritems():
            t[1].close()
        sys.stdout.write("\r%d/%d" % (total-(end-start),total))
        sys.stdout.flush()
    print
    if get_hostname:
        for c in connected:
            connect_with_adb(c,port)

argparser = argparse.ArgumentParser("Discover Zedboards on a network")
argparser.add_argument('-n', '--network', help='xxx.xxx.xxx.xxx/N')
argparser.add_argument('-p', '--port', default=5555, help='Port to probe')
argparser.add_argument('-g', '--get_hostname', default=True, help='Get hostname with adb')

def do_work(start,end,port,get_hostname):
    if sys.platform == 'darwin':
        do_work_kqueue(start,end,port,get_hostname)
    else:
        do_work_poll(start,end,port,get_hostname)

def detect_network(network=None, port=5555, get_hostname=True):
    global deviceAddresses
    deviceAddresses = {}
    if network:
        nw = network.split("/")
        start = ip2int(nw[0])
        if len(nw) != 2:
            print 'Usage: discover_tcp.py ipaddr/prefix_width'
            sys.exit(-1)
        end = start + (1 << (32-int(nw[1])) ) - 2
        do_work(start+1,end,port,get_hostname)
    else:
        for ifc in netifaces.interfaces():
            ifaddrs = netifaces.ifaddresses(ifc)
            if netifaces.AF_INET in ifaddrs.keys():
                af_inet = ifaddrs[netifaces.AF_INET]
                for i in af_inet:
                    if i.get('addr') == '127.0.0.1':
                        print 'skipping localhost'
                    else:
                        addr = ip2int(i.get('addr'))
                        netmask = ip2int(i.get('netmask'))
                        start = addr & netmask
                        end = start + (netmask ^ 0xffffffff)
                        start = start+1
                        end = end-1
                        print (int2ip(start), int2ip(end))
                        do_work(start, end,port,get_hostname)

if __name__ ==  '__main__':
    options = argparser.parse_args()
    detect_network(options.network,options.port,options.get_hostname)


text:
package com.google.j2objc.net;

import com.google.j2objc.io.AsyncPipedNSInputStreamAdapter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.CookieHandler;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/*-[
#include "NSDataInputStream.h"
#include "NSDataOutputStream.h"
#include "NSDictionaryMap.h"
#include "com/google/j2objc/net/NSErrorException.h"
#include "java/lang/Double.h"
#include "java/net/ConnectException.h"
#include "java/net/MalformedURLException.h"
#include "java/net/UnknownHostException.h"
#include "java/net/SocketTimeoutException.h"
#include "java/util/logging/Level.h"
#include "java/util/logging/Logger.h"
]-*/

/**
 * HttpURLConnection implementation for iOS, using NSURLSession.
 *
 * @author Tom Ball
 */
public class IosHttpURLConnection extends HttpURLConnection {

  /** Represents the current NSURLSessionDataTask. Guarded by nativeDataTaskLock. */
  private Object nativeDataTask; // NSURLSessionDataTask.

  /** Used to guard the release of the data task. */
  private final Object nativeDataTaskLock = new Object();

  /**
   * If chunked transfer is not enabled, the OutputStream we offer to the writer is just an,
   * NSDataOutputStream that accumulates bytes until the stream is closed.
   */
  private OutputStream nativeDataOutputStream; // NSDataOutputStream.

  /**
   * If chunked transfer is enabled, we need to give the writer an OutputStream backed by a queue,
   * and then pipe that stream to nativePipedRequestStream.
   */
  private DataEnqueuedOutputStream requestStream;

  /** The NSInputStream from AsyncPipedNSInputStreamAdapter. */
  private Object nativePipedRequestStream; // NSInputStream.

  /** An InputStream for reading the response body. Guarded by responseBodyStreamLock. */
  private DataEnqueuedInputStream responseBodyStream;

  /** Used to guard responseBodyStream. */
  private final Object responseBodyStreamLock = new Object();

  /** An InputStream for reading the error response. */
  private InputStream errorDataStream;

  private List<HeaderEntry> headers = new ArrayList<HeaderEntry>();

  // Cache response failure, so multiple requests to a bad response throw the same exception.
  private IOException responseException;

  /** Guards both responseCode and responseException and is used to block getResponse(). */
  private final Object getResponseLock = new Object();

  // Delegate to handle native security data, to avoid a direct dependency on jre_security.
  private final SecurityDataHandler securityDataHandler;

  private static final int NATIVE_PIPED_STREAM_BUFFER_SIZE = 8192;
  private static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
  private static final Map<Integer,String> RESPONSE_CODES = new HashMap<Integer,String>();

  // A case-insensitive comparator that supports a null key, so headers with
  // keys that only differ by case can be coalesced using a TreeMap.
  private static final Comparator<String> HEADER_KEY_COMPARATOR =
      new Comparator<String>() {
        @Override
        public int compare(String lhs, String rhs) {
          if (lhs == null || rhs == null) {
            if (rhs != null) {
              return -1;
            }
            if (lhs != null) {
              return 1;
            }
            return 0;
          }
          return String.CASE_INSENSITIVE_ORDER.compare(lhs, rhs);
        }
      };

  public IosHttpURLConnection(URL url) {
    this(url, null);
  }

  IosHttpURLConnection(URL url, SecurityDataHandler handler) {
    super(url);
    securityDataHandler = handler;
  }

  @Override
  public void disconnect() {
    connected = false;

    // Cancel the data task if it's still running.
    cancelDataTask();

    synchronized (responseBodyStreamLock) {
      if (responseBodyStream != null) {
        // Close the responseBodyStream from the offering side if it still exists.
        responseBodyStream.endOffering();
      }
      responseBodyStream = null;
    }

    nativeDataOutputStream = null;
    requestStream = null;
    nativePipedRequestStream = null;
    errorDataStream = null;

    // Unblock any remaining pending getResponse(), if for any reason cancelDataTask() fails.
    synchronized (getResponseLock) {
      responseException = null;
      getResponseLock.notifyAll();
    }
  }

  /**
   * Enable chunked streaming mode. The chunk length doesn't matter since NSURLSession does not give
   * us control over the chunk size.
   *
   * @param chunklen ignored.
   */
  @Override
  public void setChunkedStreamingMode(int chunklen) {
    super.setChunkedStreamingMode(chunklen);
  }

  /**
   * This method has no effect on iOS. NSURLSession only sends the Content-Length header field is
   * the HTTP request body is a data or an NSInputStream from a file (which we don't support), and
   * it always removes the Content-Length and sets Transfer-Encoding to chunked if a generic stream
   * is supplied as the request body.
   *
   * <p>The implication here is that you should never use this method. If you use this method to
   * attempt to send 5 MB of data to the OutputStream you obtain from {@link #getOutputStream()}, at
   * least 5 MB of data (if not more) will have to be allocated just to be able to send it with the
   * Content-Length field filled. Instead, call {@link #setChunkedStreamingMode(int)} and use the
   * chunked streaming mode, although this also means your server has to have chunked transfer
   * encoding support.
   *
   * @param contentLength ignored.
   */
  @Override
  public void setFixedLengthStreamingMode(long contentLength) {
    super.setFixedLengthStreamingMode(contentLength);
  }

  @Override
  public boolean usingProxy() {
    return false;
  }

  @Override
  public InputStream getInputStream() throws IOException {
    if (!doInput) {
      throw new ProtocolException("This protocol does not support input");
    }
    getResponse();
    if (responseCode >= HTTP_BAD_REQUEST) {
      throw new FileNotFoundException(url.toString());
    }
    return responseBodyStream;
  }

  @Override
  public void connect() throws IOException {
    if (responseCode != -1) {
      // Request already made.
      return;
    }

    if (responseException != null) {
      throw responseException;
    }

    if (connected) {
      return;
    }

    connected = true;

    int timeout = getReadTimeout();
    responseBodyStream = new DataEnqueuedInputStream(timeout > 0 ? timeout : -1);
    loadRequestCookies();
    makeRequest();
  }

  @Override
  public Map<String, List<String>> getHeaderFields() {
    try {
      getResponse();
      return getHeaderFieldsDoNotForceResponse();
    } catch (IOException e) {
      return Collections.emptyMap();
    }
  }

  private Map<String, List<String>> getHeaderFieldsDoNotForceResponse() {
    Map<String, List<String>> map = new TreeMap<String, List<String>>(HEADER_KEY_COMPARATOR);
    for (HeaderEntry entry : headers) {
      String k = entry.getKey();
      String v = entry.getValue();
      List<String> values = map.get(k);
      if (values == null) {
        values = new ArrayList<String>();
        map.put(k, values);
      }
      values.add(v);
    }
    return Collections.unmodifiableMap(map);
  }

  private List<HeaderEntry> getResponseHeaders() throws IOException {
    getResponse();
    return headers;
  }

  @Override
  public String getHeaderField(int pos) {
    try {
      List<HeaderEntry> headers = getResponseHeaders();
      return pos < headers.size() ? headers.get(pos).getValue() : null;
    } catch (IOException e) {
      return null;
    }
  }

  /**
   * Returns the value of the named header field.
   *
   * If called on a connection that sets the same header multiple times with
   * possibly different values, only the last value is returned.
   */
  @Override
  public String getHeaderField(String key) {
    try {
      getResponse();
      return getHeaderFieldDoNotForceResponse(key);
    } catch(IOException e) {
      return null;
    }
  }

  private String getHeaderFieldDoNotForceResponse(String key) {
    for (int i = headers.size() - 1; i >= 0; i--) {
      HeaderEntry entry = headers.get(i);
      if (key == null) {
        if (entry.getKey() == null) {
          return entry.getValue();
        }
        continue;
      }
      if (entry.getKey() != null && key.equalsIgnoreCase(entry.getKey())) {
        return entry.getValue();
      }
    }
    return null;
  }

  @Override
  public long getHeaderFieldDate(String field, long defaultValue) {
    String dateString = getHeaderField(field);
    try {
      SimpleDateFormat format = new SimpleDateFormat(HTTP_DATE_FORMAT);
      Date d = format.parse(dateString);
      return d.getTime();
    } catch (ParseException e) {
      return defaultValue;
    }
  }

  @Override
  public String getHeaderFieldKey(int posn) {
    try {
      List<HeaderEntry> headers = getResponseHeaders();
      return posn < headers.size() ? headers.get(posn).getKey() : null;
    } catch (IOException e) {
      return null;
    }
  }

  @Override
  public int getHeaderFieldInt(String field, int defaultValue) {
    String intString = getHeaderField(field);
    try {
      return Integer.parseInt(intString);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
  }

  @Override
  public long getHeaderFieldLong(String field, long defaultValue) {
    String longString = getHeaderField(field);
    return headerValueToLong(longString, defaultValue);
  }

  private long getHeaderFieldLongDoNotForceResponse(String field, long defaultValue) {
    String longString = getHeaderFieldDoNotForceResponse(field);
    return headerValueToLong(longString, defaultValue);
  }

  private long headerValueToLong(String value, long defaultValue) {
    try {
      return Long.parseLong(value);
    } catch (NumberFormatException e) {
      return defaultValue;
    }
  }

  @Override
  public final Map<String, List<String>> getRequestProperties() {
    if (connected) {
      throw new IllegalStateException(
          "Cannot access request header fields after connection is set");
    }
    return getHeaderFieldsDoNotForceResponse();
  }

  @Override
  public void setRequestProperty(String field, String newValue) {
    if (connected) {
      throw new IllegalStateException("Cannot set request property after connection is made");
    }
    if (field == null) {
      throw new NullPointerException("field == null");
    }
    setHeader(field, newValue);
  }

  @Override
  public void addRequestProperty(String field, String newValue) {
    if (connected) {
      throw new IllegalStateException("Cannot add request property after connection is made");
    }
    if (field == null) {
      throw new NullPointerException("field == null");
    }
    addHeader(field, newValue);
  }

  @Override
  public String getRequestProperty(String field) {
    if (field == null) {
      return null;
    }
    return getHeaderFieldDoNotForceResponse(field);
  }

  @Override
  public InputStream getErrorStream() {
    return errorDataStream;
  }

  @Override
  public long getIfModifiedSince() {
    return getHeaderFieldLongDoNotForceResponse("If-Modified-Since", 0L);
  }

  @Override
  public void setIfModifiedSince(long newValue) {
    super.setIfModifiedSince(newValue);
    if (ifModifiedSince != 0) {
      SimpleDateFormat format = new SimpleDateFormat(HTTP_DATE_FORMAT);
      String dateString = format.format(new Date(ifModifiedSince));
      setHeader("If-Modified-Since", dateString);
    } else {
      removeHeader("If-Modified-Since");
    }
  }

  @Override
  public OutputStream getOutputStream() throws IOException {
    if (connected) {
      throw new IllegalStateException("Cannot get output stream after connection is made");
    }

    // If {@link java.net.HttpURLConnection#setChunkedStreamingMode(int)} is ever called to enable
    // chunked streaming mode, create a queue-backed OutputStream and pipe that to a native
    // NSInputStream, which we can then use as the HTTP request body stream.
    if (chunkLength > 0) {
      if (requestStream == null) {
        int timeout = getReadTimeout();
        requestStream = new DataEnqueuedOutputStream(timeout > 0 ? timeout : -1);
      }

      if (nativePipedRequestStream == null) {
        nativePipedRequestStream =
            AsyncPipedNSInputStreamAdapter.create(requestStream, NATIVE_PIPED_STREAM_BUFFER_SIZE);
      }
      connect();
      return requestStream;
    } else {
      if (nativeDataOutputStream == null) {
        nativeDataOutputStream = createNativeDataOutputStream();
      }
      return nativeDataOutputStream;
    }
  }

  private native OutputStream createNativeDataOutputStream() /*-[
    return (JavaIoOutputStream *) [NSDataOutputStream stream];
  ]-*/;

  private void getResponse() throws IOException {
    if (responseCode != -1) {
      // Request already made.
      return;
    }

    connect();
    synchronized (getResponseLock) {
      if (responseCode == -1 && responseException == null) {
        try {
          // There are three places where getResponseLock.notifyAll() is called: in disconnect(), in
          // the native -URLSession:dataTask:didReceiveResponse:, and in the native
          // -URLSession:task:didCompleteWithError:. The call in disconnect() is just a clean-up
          // step, where as -URLSession:dataTask:didReceiveResponse: is called only if the
          // connection is made and an HTTP response code is received. If a non-server error occurs
          // (such as lost connection), -URLSession:task:didCompleteWithError: will be called and an
          // exception will be set there. So the only condition we are waiting for here is if both
          // responseCode and responseExecption are not set.
          getResponseLock.wait();
        } catch (InterruptedException e) {
          // Ignored.
        }
      }
    }
    if (responseException != null) {
      throw responseException;
    }
    saveResponseCookies();
  }

  /**
   * Add any cookies for this URI to the request headers.
   */
  private void loadRequestCookies() throws IOException {
    CookieHandler cookieHandler = CookieHandler.getDefault();
    if (cookieHandler != null) {
      try {
        URI uri = getURL().toURI();
        Map<String, List<String>> cookieHeaders =
            cookieHandler.get(uri, getHeaderFieldsDoNotForceResponse());
        for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
          String key = entry.getKey();
          if (("Cookie".equalsIgnoreCase(key)
              || "Cookie2".equalsIgnoreCase(key))
              && !entry.getValue().isEmpty()) {
            List<String> cookies = entry.getValue();
            StringBuilder sb = new StringBuilder();
            for (int i = 0, size = cookies.size(); i < size; i++) {
              if (i > 0) {
                sb.append("; ");
              }
              sb.append(cookies.get(i));
            }
            setHeader(key, sb.toString());
          }
        }
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }
    }
  }

  /**
   * Store any returned cookies.
   */
  private void saveResponseCookies() throws IOException {
    CookieHandler cookieHandler = CookieHandler.getDefault();
    if (cookieHandler != null) {
      try {
        URI uri = getURL().toURI();
        cookieHandler.put(uri, getHeaderFieldsDoNotForceResponse());
      } catch (URISyntaxException e) {
        throw new IOException(e);
      }
    }
  }

  @Override
  public int getResponseCode() throws IOException {
    getResponse();
    return responseCode;
  }

  private native void makeRequest() throws IOException /*-[
    @autoreleasepool {

      NSMutableURLRequest *request =
          [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self->url_ toExternalForm]]];
      request.HTTPShouldHandleCookies = false;
      request.cachePolicy = self->useCaches_ ?
          NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData;
      int readTimeout = [self getReadTimeout];
      request.timeoutInterval = readTimeout > 0 ? (readTimeout / 1000.0) : JavaLangDouble_MAX_VALUE;
      int n = [self->headers_ size];
      for (int i = 0; i < n; i++) {
        ComGoogleJ2objcNetIosHttpURLConnection_HeaderEntry *entry = [self->headers_ getWithInt:i];
        if (entry->key_) {
          [request setValue:[entry getValue] forHTTPHeaderField:entry->key_];
        }
      }

      if (self->doOutput_) {
        if ([self->method_ isEqualToString:@"GET"]) {
          self->method_ = @"POST";  // GET doesn't support output, so assume POST.
        } else if (![self->method_ isEqualToString:@"POST"] &&
                   ![self->method_ isEqualToString:@"PUT"] &&
                   ![self->method_ isEqualToString:@"PATCH"]) {
          NSString *errMsg =
              [NSString stringWithFormat:@"%@ does not support writing", self->method_];
          self->responseException_ = [[JavaNetProtocolException alloc] initWithNSString:errMsg];
          @throw self->responseException_;
        }

        if (self->nativeDataOutputStream_) {
          // Use the accumululated data as the request body.
          request.HTTPBody = [(NSDataOutputStream *) self->nativeDataOutputStream_ data];
        } else if (self->nativePipedRequestStream_) {
          // Use the piped NSInputStream as the request stream.
          request.HTTPBodyStream = self->nativePipedRequestStream_;
        }
      }
      request.HTTPMethod = self->method_;

      NSURLSessionConfiguration *sessionConfiguration =
          [NSURLSessionConfiguration defaultSessionConfiguration];
      NSURLSession *session =
          [NSURLSession sessionWithConfiguration:sessionConfiguration
                                        delegate:(id<NSURLSessionDataDelegate>)self
                                   delegateQueue:nil];
      NSURLSessionTask *task = [session dataTaskWithRequest:request];
      [task resume];
      JreStrongAssign(&self->nativeDataTask_, task);
      [session finishTasksAndInvalidate];
    }
  ]-*/;

  /*
   * NSURLSessionDataDelegate method: initial reply received.
   */
  /*-[
  - (void)URLSession:(NSURLSession *)session
            dataTask:(NSURLSessionDataTask *)dataTask
  didReceiveResponse:(NSURLResponse *)urlResponse
   completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    if (urlResponse && ![urlResponse isKindOfClass:[NSHTTPURLResponse class]]) {
      @throw AUTORELEASE(([[JavaLangAssertionError alloc]
                           initWithId:[NSString stringWithFormat:@"Unknown class %@",
                               NSStringFromClass([urlResponse class])]]));
    }
    NSHTTPURLResponse *response = (NSHTTPURLResponse *) urlResponse;
    int responseCode = (int) response.statusCode;
    JavaNetHttpURLConnection_set_responseMessage_(self,
        ComGoogleJ2objcNetIosHttpURLConnection_getResponseStatusTextWithInt_(responseCode));

    // Clear request headers to make room for the response headers.
    [self->headers_ clear];

    // The HttpURLConnection headerFields map uses a null key for Status-Line.
    NSString *statusLine = [NSString stringWithFormat:@"HTTP/1.1 %d %@", responseCode,
        self->responseMessage_];
    ComGoogleJ2objcNetIosHttpURLConnection_addHeaderWithNSString_withNSString_(
        self, nil, statusLine);

    // Copy remaining response headers.
    [response.allHeaderFields enumerateKeysAndObjectsUsingBlock:
        ^(id key, id value, BOOL *stop) {
      ComGoogleJ2objcNetIosHttpURLConnection_addHeaderWithNSString_withNSString_(self, key, value);
    }];

    if (response.statusCode >= JavaNetHttpURLConnection_HTTP_BAD_REQUEST) {
      // Make errorDataStream an alias to responseBodyStream. Since getInputStream() throws an
      // exception when status code >= HTTP_BAD_REQUEST, it is guaranteed that responseBodyStream
      // can only mean error stream going forward.
      JreStrongAssign(&self->errorDataStream_, self->responseBodyStream_);
    }

    completionHandler(NSURLSessionResponseAllow);

    // Since the original request might have been redirected, we might need to
    // update the URL to the redirected URL.
    JavaNetURLConnection_set_url_(
        self, create_JavaNetURL_initWithNSString_(response.URL.absoluteString));

    // Unblock getResponse().
    @synchronized(getResponseLock_) {
      self->responseCode_ = responseCode;
      [self->getResponseLock_ java_notifyAll];
    }
  }
  ]-*/

  /*
   * NSURLSessionDataDelegate method: data received.
   */
  /*-[
  - (void)URLSession:(NSURLSession *)session
            dataTask:(NSURLSessionDataTask *)dataTask
      didReceiveData:(NSData *)data {
    @synchronized(responseBodyStreamLock_) {
      [self->responseBodyStream_ offerDataWithByteArray:[IOSByteArray arrayWithNSData:data]];
    }
  }
  ]-*/

  /*
   * NSURLSessionDataDelegate method: should we store the response in the cache.
   */
  /*-[
  - (void)URLSession:(NSURLSession *)session
            dataTask:(NSURLSessionDataTask *)dataTask
   willCacheResponse:(NSCachedURLResponse *)proposedResponse
   completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
    completionHandler( self->useCaches_ ? proposedResponse : nil );
  }
  ]-*/

  /*
   * NSURLSessionDelegate method: task completed.
   */
  /*-[
  - (void)URLSession:(NSURLSession *)session
                task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
    JavaIoIOException *responseException = nil;
    if (error) {
      NSString *url = [self->url_ description];  // Use original URL in any error text.
      if ([[error domain] isEqualToString:@"NSURLErrorDomain"]) {
        switch ([error code]) {
          case NSURLErrorBadURL:
            responseException = create_JavaNetMalformedURLException_initWithNSString_(url);
            break;
          case NSURLErrorCannotConnectToHost:
            responseException =
                create_JavaNetConnectException_initWithNSString_([error description]);
            break;
          case NSURLErrorSecureConnectionFailed:
            responseException = RETAIN_(
                ComGoogleJ2objcNetIosHttpURLConnection_secureConnectionExceptionWithNSString_
                    ([error description]));
            break;
          case NSURLErrorCannotFindHost:
            responseException = create_JavaNetUnknownHostException_initWithNSString_(url);
            break;
          case NSURLErrorTimedOut:
            responseException = create_JavaNetSocketTimeoutException_initWithNSString_(url);
            break;
        }
      }
      if (!responseException) {
        responseException = create_JavaIoIOException_initWithNSString_([error description]);
      }
      ComGoogleJ2objcNetNSErrorException *cause =
          create_ComGoogleJ2objcNetNSErrorException_initWithId_(error);
      [responseException initCauseWithJavaLangThrowable:cause];
    }

    @synchronized(responseBodyStreamLock_) {
      if (!responseException) {
        // No error, close the responseBodyStream.
        [self->responseBodyStream_ endOffering];
      } else {
        // Close responseBodyStream with the exception so that subsequent calls to read() cause the
        // same exception to be thrown.
        [self->responseBodyStream_ endOfferingWithJavaIoIOException:responseException];
      }
    }

    // Set nativeDataTask to null.
    @synchronized(nativeDataTaskLock_) {
      JreStrongAssign(&self->nativeDataTask_, nil);
    }

    // Unblock getResponse() and set responseException. This call to notifyAll() is needed because
    // -URLSession:dataTask:didReceiveResponse: may not be called if a non-server error (such as
    // lost connection) occurs.
    @synchronized(getResponseLock_) {
      JreStrongAssign(&self->responseException_, responseException);
      [self->getResponseLock_ java_notifyAll];
    }
  }
  ]-*/

  /*
   * NSURLSessionDelegate method: session completed.
   */
  /*-[
  - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
    if (error) {
      // Cannot return error since this happened on another thread and the task
      // finished, so just log it.
      ComGoogleJ2objcNetNSErrorException *exception =
          create_ComGoogleJ2objcNetNSErrorException_initWithId_(error);
      JavaUtilLoggingLogger *logger = JavaUtilLoggingLogger_getLoggerWithNSString_(
          [[self java_getClass] getName]);
      [logger logWithJavaUtilLoggingLevel:JreLoadStatic(JavaUtilLoggingLevel, SEVERE)
                             withNSString:@"session invalidated with error"
                    withJavaLangThrowable:exception];
    }
  }
  ]-*/

  /**
   * Returns an SSLException if that class is linked into the application,
   * otherwise IOException.
   */
  private static IOException secureConnectionException(String description) {
    try {
      Class<?> sslExceptionClass = Class.forName("javax.net.ssl.SSLException");
      Constructor<?> constructor = sslExceptionClass.getConstructor(String.class);
      return (IOException) constructor.newInstance(description);
    } catch (ClassNotFoundException e) {
      return new IOException(description);
    } catch (Exception e) {
      throw new AssertionError("unexpected exception", e);
    }
  }

  /*-[
  - (void)URLSession:(NSURLSession *)session
                task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
          newRequest:(NSURLRequest *)request
   completionHandler:(void (^)(NSURLRequest *))completionHandler {
    if (self->instanceFollowRedirects_
        && [response.URL.scheme isEqualToString:request.URL.scheme]) {
      completionHandler(request);
    } else {
      completionHandler(nil);
    }
  }
  ]-*/

  private void addHeader(String k, String v) {
    if (k != null && (k.equalsIgnoreCase("Set-Cookie") || k.equalsIgnoreCase("Set-Cookie2"))) {
      CookieSplitter cs = new CookieSplitter(v);
      while (cs.hasNext()) {
        headers.add(new HeaderEntry(k, cs.next()));
      }
    } else {
      headers.add(new HeaderEntry(k, v));
    }
  }

  private void removeHeader(String k) {
    Iterator<HeaderEntry> iter = headers.iterator();
    while (iter.hasNext()) {
      HeaderEntry entry = iter.next();
      if (entry.key == k) {
        iter.remove();
        return;
      }
    }
  }

  private void setHeader(String k, String v) {
    for (HeaderEntry entry : headers) {
      if (entry.key == k || (entry.key != null && k != null && k.equalsIgnoreCase(entry.key))) {
        headers.remove(entry);
        break;
      }
    }
    headers.add(new HeaderEntry(k, v));
  }

  private static class HeaderEntry implements Map.Entry<String, String> {
    private final String key;
    private final String value;

    HeaderEntry(String k, String v) {
      this.key = k;
      this.value = v;
    }

    @Override
    public String getKey() {
      return key;
    }

    @Override
    public String getValue() {
      return value;
    }

    @Override
    public String setValue(String object) {
      throw new AssertionError("mutable method called on immutable class");
    }
  }

  private static String getResponseStatusText(int responseCode) {
    return RESPONSE_CODES.get(responseCode);
  }

  /** Cancels the native data task. */
  private native void cancelDataTask() /*-[
    @synchronized (self->nativeDataTaskLock_) {
      // Safe to do even if self->nativeDataTask_ is already nil.
      [(NSURLSessionDataTask *)self->nativeDataTask_ cancel];
      JreStrongAssign(&self->nativeDataTask_, nil);
    }
  ]-*/;

  /**
   * Splits a string with one or more cookies separated with a comma. Since
   * some attribute values can also have commas, like the expires date field,
   * this does a look ahead to detect where it's a separator or not.
   */
  private static class CookieSplitter {
    String s;
    char[] buf;
    int pos;

    CookieSplitter(String s) {
      this.s = s;
      buf = s.toCharArray();
      pos = 0;
    }

    boolean hasNext() {
      return pos < buf.length;
    }

    String next() {
      int start = pos;
      while (skipSpace()) {
        if (buf[pos] == ',') {
          int lastComma = pos++;
          skipSpace();
          int nextStart = pos;
          while (pos < buf.length && buf[pos] != '=' && buf[pos] != ';' && buf[pos] != ',') {
            pos++;
          }
          if (pos < buf.length && buf[pos] == '=') {
            // pos is inside the next cookie, so back up and return it.
            pos = nextStart;
            return s.substring(start, lastComma);
          }
          pos = lastComma;
        }
        pos++;
      }
      return s.substring(start);
    }

    // Skip whitespace, returning true if there are more chars to read.
    private boolean skipSpace() {
      while (pos < buf.length && Character.isWhitespace(buf[pos])) {
        pos++;
      }
      return pos < buf.length;
    }
  }

  static {
    RESPONSE_CODES.put(100, "Continue");
    RESPONSE_CODES.put(101, "Switching Protocols");
    RESPONSE_CODES.put(102, "Processing");
    RESPONSE_CODES.put(HTTP_OK, "OK");
    RESPONSE_CODES.put(HTTP_CREATED, "Created");
    RESPONSE_CODES.put(HTTP_ACCEPTED, "Accepted");
    RESPONSE_CODES.put(HTTP_NOT_AUTHORITATIVE, "Non Authoritative Information");
    RESPONSE_CODES.put(HTTP_NO_CONTENT, "No Content");
    RESPONSE_CODES.put(HTTP_RESET, "Reset Content");
    RESPONSE_CODES.put(HTTP_PARTIAL, "Partial Content");
    RESPONSE_CODES.put(207, "Multi-Status");
    RESPONSE_CODES.put(HTTP_MULT_CHOICE, "Multiple Choices");
    RESPONSE_CODES.put(HTTP_MOVED_PERM, "Moved Permanently");
    RESPONSE_CODES.put(HTTP_MOVED_TEMP, "Moved Temporarily");
    RESPONSE_CODES.put(HTTP_SEE_OTHER, "See Other");
    RESPONSE_CODES.put(HTTP_NOT_MODIFIED, "Not Modified");
    RESPONSE_CODES.put(HTTP_USE_PROXY, "Use Proxy");
    RESPONSE_CODES.put(307, "Temporary Redirect");
    RESPONSE_CODES.put(HTTP_BAD_REQUEST, "Bad Request");
    RESPONSE_CODES.put(HTTP_UNAUTHORIZED, "Unauthorized");
    RESPONSE_CODES.put(HTTP_PAYMENT_REQUIRED, "Payment Required");
    RESPONSE_CODES.put(HTTP_FORBIDDEN, "Forbidden");
    RESPONSE_CODES.put(HTTP_NOT_FOUND, "Not Found");
    RESPONSE_CODES.put(HTTP_BAD_METHOD, "Method Not Allowed");
    RESPONSE_CODES.put(HTTP_NOT_ACCEPTABLE, "Not Acceptable");
    RESPONSE_CODES.put(HTTP_PROXY_AUTH, "Proxy Authentication Required");
    RESPONSE_CODES.put(HTTP_CLIENT_TIMEOUT, "Request Timeout");
    RESPONSE_CODES.put(HTTP_CONFLICT, "Conflict");
    RESPONSE_CODES.put(HTTP_GONE, "Gone");
    RESPONSE_CODES.put(HTTP_LENGTH_REQUIRED, "Length Required");
    RESPONSE_CODES.put(HTTP_PRECON_FAILED, "Precondition Failed");
    RESPONSE_CODES.put(HTTP_ENTITY_TOO_LARGE, "Request Too Long");
    RESPONSE_CODES.put(HTTP_REQ_TOO_LONG, "Request-URI Too Long");
    RESPONSE_CODES.put(HTTP_UNSUPPORTED_TYPE, "Unsupported Media Type");
    RESPONSE_CODES.put(416, "Requested Range Not Satisfiable");
    RESPONSE_CODES.put(417, "Expectation Failed");
    RESPONSE_CODES.put(418, "Unprocessable Entity");
    RESPONSE_CODES.put(419, "Insufficient Space On Resource");
    RESPONSE_CODES.put(420, "Method Failure");
    RESPONSE_CODES.put(423, "Locked");
    RESPONSE_CODES.put(424, "Failed Dependency");
    RESPONSE_CODES.put(HTTP_INTERNAL_ERROR, "Internal Server Error");
    RESPONSE_CODES.put(HTTP_NOT_IMPLEMENTED, "Not Implemented");
    RESPONSE_CODES.put(HTTP_BAD_GATEWAY, "Bad Gateway");
    RESPONSE_CODES.put(HTTP_UNAVAILABLE, "Service Unavailable");
    RESPONSE_CODES.put(HTTP_GATEWAY_TIMEOUT, "Gateway Timeout");
    RESPONSE_CODES.put(HTTP_VERSION, "Http Version Not Supported");
    RESPONSE_CODES.put(507, "Insufficient Storage");
  }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Includeme of SACRUD
"""

CONFIG_MODELS = 'pyramid_sacrud.models'
CONFIG_DASHBOARD_ROW_LEN = 'pyramid_sacrud.dashboard_row_len'

def includeme(config):
    config.include('.includes')
    config.scan('.views')


text:
namespace Series.Core
{
    public abstract class Series
    {
        public abstract int Calculate(int number);
    }
}


text:
package org.camunda.bpm.extension.reactor.spring.listener;

import org.camunda.bpm.engine.delegate.DelegateCaseExecution;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.extension.reactor.bus.CamundaEventBus;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class AbstractListenerTestHelper {

  @Autowired
  protected CamundaEventBus camundaEventBus;

  public static DelegateTask delegateTask() {
    return delegateTask("task1", "process:1:1", "create");
  }

  public static DelegateTask delegateTask(String taskName, String processDefinitionId, String eventName) {
    final DelegateTask task = mock(DelegateTask.class, RETURNS_DEEP_STUBS);
    when(task.getBpmnModelElementInstance().getElementType().getTypeName()).thenReturn("userTask");

    when(task.getTaskDefinitionKey()).thenReturn(taskName);
    when(task.getProcessDefinitionId()).thenReturn(processDefinitionId);
    when(task.getEventName()).thenReturn(eventName);

    return task;
  }

  public static DelegateExecution delegateExecution() {
    final DelegateExecution execution = mock(DelegateExecution.class, RETURNS_DEEP_STUBS);

    when(execution.getBpmnModelElementInstance().getElementType().getTypeName()).thenReturn("serviceTask");
    when(execution.getProcessDefinitionId()).thenReturn("process:1:1");
    when(execution.getEventName()).thenReturn("start");
    when(execution.getCurrentActivityId()).thenReturn("service1");

    return execution;
  }

  public static DelegateCaseExecution delegateCaseExecution() {
    final DelegateCaseExecution execution = mock(DelegateCaseExecution.class, RETURNS_DEEP_STUBS);

    when(execution.getCmmnModelElementInstance().getElementType().getTypeName()).thenReturn("serviceTask");
    when(execution.getCaseDefinitionId()).thenReturn("process:1:1");
    when(execution.getEventName()).thenReturn("start");
    when(execution.getActivityId()).thenReturn("service1");

    return execution;
  }

}


text:
title: MySQLSchema::schemata — Core Library
package: lib
packageTitle: Core Library
layout: default
className: MySQLSchema
type: method
---

# MySQLSchema::schemata

## Synopsis

public function MySQLSchema::schemata($dbName)

## Parameters

      Name
      Direction
      Type
      Description

      $dbName


text:
 package com.indeed.flamdex.lucene;

import com.google.common.collect.Lists;
import com.indeed.flamdex.query.BooleanOp;
import com.indeed.flamdex.query.Query;
import com.indeed.flamdex.query.Term;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreRangeQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.RangeQuery;
import org.apache.lucene.search.TermQuery;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author jsgroth
 */
public final class LuceneQueryTranslator {
    private LuceneQueryTranslator() {}

    public static Query rewrite(org.apache.lucene.search.Query q, Set<String> intFields) {
        if (q instanceof TermQuery) {
            return rewrite((TermQuery)q, intFields);
        } else if (q instanceof BooleanQuery) {
            return rewrite((BooleanQuery)q, intFields);
        } else if (q instanceof RangeQuery) {
            return rewrite((RangeQuery)q, intFields);
        } else if (q instanceof ConstantScoreRangeQuery) {
            return rewrite((ConstantScoreRangeQuery)q, intFields);
        } else if (q instanceof PrefixQuery) {
            return rewrite((PrefixQuery)q, intFields);
        } else if (q instanceof PhraseQuery) {
            return rewrite((PhraseQuery)q, intFields);
        }
        throw new IllegalArgumentException("unsupported lucene query type: " + q.getClass().getSimpleName());
    }

    public static Query rewrite(PrefixQuery pq, Set<String> intFields) {
        if (intFields.contains(pq.getPrefix().field())) {
            // not really sure what to do here, for now just treat it as an inequality query
            return Query.newRangeQuery(pq.getPrefix().field(), Long.parseLong(pq.getPrefix().text()), Long.MAX_VALUE, true);
        } else {
            final String prefix = pq.getPrefix().text();
            final String endTerm = prefix.substring(0, prefix.length() - 1) + ((char)((prefix.charAt(prefix.length() - 1) + 1)));
            return Query.newRangeQuery(pq.getPrefix().field(), prefix, endTerm, false);
        }
    }

    public static Query rewrite(BooleanQuery bq, Set<String> intFields) {
        boolean hasMust = false;
        boolean hasMustNot = false;
        for (final BooleanClause clause : bq.getClauses()) {
            if (clause.getOccur() == BooleanClause.Occur.MUST) {
                hasMust = true;
            } else if (clause.getOccur() == BooleanClause.Occur.MUST_NOT) {
                hasMustNot = true;
            }
        }

        if (hasMustNot) {
            final List<Query> nots = Lists.newArrayList();
            final List<Query> other = Lists.newArrayList();
            for (final BooleanClause clause : bq.getClauses()) {
                if (clause.getOccur() == BooleanClause.Occur.MUST_NOT) {
                    final Query query = rewrite(clause.getQuery(), intFields);
                    nots.add(query);
                } else if (clause.getOccur() == BooleanClause.Occur.MUST ||
                        (clause.getOccur() == BooleanClause.Occur.SHOULD && !hasMust)) {
                    final Query query = rewrite(clause.getQuery(), intFields);
                    other.add(query);
                }
            }

            final Query notQuery = Query.newBooleanQuery(BooleanOp.NOT, nots);
            if (other.isEmpty()) {
                return notQuery;
            } else {
                return Query.newBooleanQuery(BooleanOp.AND, Arrays.asList(Query.newBooleanQuery(hasMust ? BooleanOp.AND : BooleanOp.OR, other), notQuery));
            }
        } else {
            final List<Query> operands = Lists.newArrayList();
            for (final BooleanClause clause : bq.getClauses()) {
                if (clause.getOccur() == BooleanClause.Occur.MUST || (clause.getOccur() == BooleanClause.Occur.SHOULD && !hasMust)) {
                    final Query query = rewrite(clause.getQuery(), intFields);
                    operands.add(query);
                }
            }
            return Query.newBooleanQuery(hasMust ? BooleanOp.AND : BooleanOp.OR, operands);
        }
    }

    public static Query rewrite(TermQuery tq, Set<String> intFields) {
        final Term term = rewriteTerm(tq.getTerm(), intFields);
        return Query.newTermQuery(term);
    }

    private static Term rewriteTerm(org.apache.lucene.index.Term lTerm, Set<String> intFields) {
        final String field = lTerm.field();
        final Term term;
        if (intFields.contains(field)) {
            term = new Term(field, true, Long.parseLong(lTerm.text()), "");
        } else {
            String termText = lTerm.text();
            term = new Term(field, false, 0, termText);
        }
        return term;
    }

    public static Query rewrite(RangeQuery rq, Set<String> intFields) {
        final Term startTerm = rewriteTerm(rq.getLowerTerm(), intFields);
        final Term endTerm = rewriteTerm(rq.getUpperTerm(), intFields);
        return Query.newRangeQuery(startTerm, endTerm, rq.isInclusive());
    }

    public static Query rewrite(ConstantScoreRangeQuery rq, Set<String> intFields) {
        final Term startTerm = rewriteTerm(new org.apache.lucene.index.Term(rq.getField(), rq.getLowerVal()), intFields);
        final Term endTerm = rewriteTerm(new org.apache.lucene.index.Term(rq.getField(), rq.getUpperVal()), intFields);
        return Query.newRangeQuery(startTerm, endTerm, rq.includesUpper());
    }

    public static Query rewrite(PhraseQuery pq, Set<String> intFields) {
        final List<Query> termQueries = Lists.newArrayListWithCapacity(pq.getTerms().length);
        for (final org.apache.lucene.index.Term term : pq.getTerms()) {
            termQueries.add(Query.newTermQuery(rewriteTerm(term, intFields)));
        }
        return Query.newBooleanQuery(BooleanOp.AND, termQueries);
    }
}


text:
<?php

use Silex\Application;
use Silex\Provider\TwigServiceProvider;
use Bt51\Silex\Provider\GoogleAnalyticsServiceProvider\GoogleAnalyticsServiceProvider;

$app = new Application();

$app->register(TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/views'
));

$app->register(new GoogleAnalyticsServiceProvider(),
			   array('ga.configuration' => array('code' => 'UA-XXXXX-X')));

$app->get('/', function () use ($app) {
    return $app['twig']->render('test.html.twig');
});


text:
package api

import (
	"github.com/projectcalico/libcalico-go/lib/api/unversioned"
)

// Profile contains the details a security profile resource.  A profile is set of security rules
// to apply on an endpoint.  An endpoint (either a host endpoint or an endpoint on a workload) can
// reference zero or more profiles.  The profile rules are applied directly to the endpoint *after*
// the selector-based security policy has been applied, and in the order the profiles are declared on the
// endpoint.
type Profile struct {
	unversioned.TypeMetadata
	Metadata ProfileMetadata `json:"metadata,omitempty"`
	Spec     ProfileSpec     `json:"spec,omitempty"`
}

// ProfileMetadata contains the metadata for a security Profile resource.
type ProfileMetadata struct {
	unversioned.ObjectMetadata

	// The name of the endpoint.
	Name string `json:"name,omitempty" validate:"omitempty,namespacedname"`

	// A list of tags that are applied to each endpoint that references this profile.
	Tags []string `json:"tags,omitempty" validate:"omitempty,dive,tag"`

	// The labels to apply to each endpoint that references this profile.  It is expected
	// that many endpoints share the same labels. For example, they could be used to label all
	// "production" workloads with "deployment=prod" so that security policy can be applied
	// to production workloads.
	Labels map[string]string `json:"labels,omitempty" validate:"omitempty,labels"`
}

// ProfileSpec contains the specification for a security Profile resource.
type ProfileSpec struct {
	// The ordered set of ingress rules.  Each rule contains a set of packet match criteria and
	// a corresponding action to apply.
	IngressRules []Rule `json:"ingress,omitempty" validate:"omitempty,dive"`

	// The ordered set of egress rules.  Each rule contains a set of packet match criteria and
	// a corresponding action to apply.
	EgressRules []Rule `json:"egress,omitempty" validate:"omitempty,dive"`
}

// NewProfile creates a new (zeroed) Profile struct with the TypeMetadata initialised to the current
// version.
func NewProfile() *Profile {
	return &Profile{
		TypeMetadata: unversioned.TypeMetadata{
			Kind:       "profile",
			APIVersion: unversioned.VersionCurrent,
		},
	}
}

// A ProfileList contains a list of security Profile resources.  List types are returned from List()
// enumerations on the client interface.
type ProfileList struct {
	unversioned.TypeMetadata
	Metadata unversioned.ListMetadata `json:"metadata,omitempty"`
	Items    []Profile                `json:"items" validate:"dive,omitempty"`
}

// NewProfile creates a new (zeroed) Profile struct with the TypeMetadata initialised to the current
// version.
func NewProfileList() *ProfileList {
	return &ProfileList{
		TypeMetadata: unversioned.TypeMetadata{
			Kind:       "profileList",
			APIVersion: unversioned.VersionCurrent,
		},
	}
}


text:
package org.apache.accumulo.core.util;

import java.util.Date;

import org.apache.log4j.Logger;

public class LoggingRunnable implements Runnable {
  private Runnable runnable;
  private Logger log;

  public LoggingRunnable(Logger log, Runnable r) {
    this.runnable = r;
    this.log = log;
  }

  public void run() {
    try {
      runnable.run();
    } catch (Throwable t) {
      try {
        log.error("Thread \"" + Thread.currentThread().getName() + "\" died " + t.getMessage(), t);
      } catch (Throwable t2) {
        // maybe the logging system is screwed up OR there is a bug in the exception, like t.getMessage() throws a NPE
        System.err.println("ERROR " + new Date() + " Failed to log message about thread death " + t2.getMessage());
        t2.printStackTrace();

        // try to print original exception
        System.err.println("ERROR " + new Date() + " Exception that failed to log : " + t.getMessage());
        t.printStackTrace();
      }
    }
  }
}


text:
<?php
// Connection Component Binding
Doctrine_Manager::getInstance()->bindComponent('ChecksumResults', 'doctrine');

/**
 * BaseChecksumResults
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property string $result_code
 * @property string $result_description
 * @property Doctrine_Collection $MostRecentChecksums
 * @property Doctrine_Collection $ChecksumHistorys
 *
 * @method string              getResultCode()          Returns the current record's "result_code" value
 * @method string              getResultDescription()   Returns the current record's "result_description" value
 * @method Doctrine_Collection getMostRecentChecksums() Returns the current record's "MostRecentChecksums" collection
 * @method Doctrine_Collection getChecksumHistorys()    Returns the current record's "ChecksumHistorys" collection
 * @method ChecksumResults     setResultCode()          Sets the current record's "result_code" value
 * @method ChecksumResults     setResultDescription()   Sets the current record's "result_description" value
 * @method ChecksumResults     setMostRecentChecksums() Sets the current record's "MostRecentChecksums" collection
 * @method ChecksumResults     setChecksumHistorys()    Sets the current record's "ChecksumHistorys" collection
 *
 * @package    dspace
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseChecksumResults extends BaseDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('public.checksum_results');
        $this->hasColumn('result_code', 'string', null, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'primary' => true,
             'length' => '',
             ));
        $this->hasColumn('result_description', 'string', null, array(
             'type' => 'string',
             'fixed' => 0,
             'unsigned' => false,
             'notnull' => false,
             'primary' => false,
             'length' => '',
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasMany('MostRecentChecksum as MostRecentChecksums', array(
             'local' => 'result_code',
             'foreign' => 'result'));

        $this->hasMany('ChecksumHistory as ChecksumHistorys', array(
             'local' => 'result_code',
             'foreign' => 'result'));
    }
}


text:
extern WXDLLIMPEXP_DATA_CORE(const char) wxFileSelectorDefaultWildcardStr[];

typedef struct _GtkFileChooser GtkFileChooser;

// [GTK] current problems:
// All methods(e.g. SetFilename(), SetPath(), etc) which change the state of
// the control result in events fired, such events should be suppressed.
// ------
// Sometimes a selection event(with 0 files) is fired before
// wxEVT_FILECTRL_FOLDERCHANGED, unfortunately this can hardly be detected!

// A wx wrapper for any Gtk object implementing the interface GtkFileChooser

class WXDLLIMPEXP_CORE wxGtkFileChooser
{
public:
    wxGtkFileChooser() { m_ignoreNextFilterEvent = false; }

    void SetWidget(GtkFileChooser *w);

    wxString GetPath() const;
    void GetPaths( wxArrayString& paths ) const;
    wxString GetDirectory() const;
    wxString GetFilename() const;
    void GetFilenames( wxArrayString& files ) const;
    int GetFilterIndex() const;

    bool SetPath( const wxString& path );
    bool SetDirectory( const wxString& dir );
    void SetWildcard( const wxString& wildCard );
    void SetFilterIndex( int filterIndex );

    bool HasFilterChoice() const;

    bool ShouldIgnoreNextFilterEvent() const { return m_ignoreNextFilterEvent; }

    wxString GetCurrentWildCard() const
       { return m_wildcards[GetFilterIndex()]; }

private:
    GtkFileChooser *m_widget;
    // First wildcard in filter, to be used when the user
    // saves a file without giving an extension.
    wxArrayString   m_wildcards;

    // If true, ignore the next event because it was generated by us and not
    // the user.
    bool m_ignoreNextFilterEvent;
};

#if wxUSE_FILECTRL

class WXDLLIMPEXP_CORE wxGtkFileCtrl: public wxControl,
            public wxFileCtrlBase
{
public:
    wxGtkFileCtrl () { Init(); }

    wxGtkFileCtrl ( wxWindow *parent,
                    wxWindowID id,
                    const wxString& defaultDirectory = wxEmptyString,
                    const wxString& defaultFilename = wxEmptyString,
                    const wxString& wildCard = wxFileSelectorDefaultWildcardStr,
                    long style = wxFC_DEFAULT_STYLE,
                    const wxPoint& pos = wxDefaultPosition,
                    const wxSize& size = wxDefaultSize,
                    const wxString& name = wxFileCtrlNameStr )
    {
        Init();
        Create( parent, id, defaultDirectory, defaultFilename, wildCard, style, pos, size, name );
    }

    virtual ~wxGtkFileCtrl();

    bool Create( wxWindow *parent,
                 wxWindowID id,
                 const wxString& defaultDirectory = wxEmptyString,
                 const wxString& defaultFileName = wxEmptyString,
                 const wxString& wildCard = wxFileSelectorDefaultWildcardStr,
                 long style = wxFC_DEFAULT_STYLE,
                 const wxPoint& pos = wxDefaultPosition,
                 const wxSize& size = wxDefaultSize,
                 const wxString& name = wxFileCtrlNameStr );

    virtual void SetWildcard( const wxString& wildCard ) wxOVERRIDE;
    virtual void SetFilterIndex( int filterIndex ) wxOVERRIDE;
    virtual bool SetDirectory( const wxString& dir ) wxOVERRIDE;
    virtual bool SetFilename( const wxString& name ) wxOVERRIDE;
    virtual bool SetPath( const wxString& path ) wxOVERRIDE;

    virtual wxString GetFilename() const wxOVERRIDE;
    virtual wxString GetDirectory() const wxOVERRIDE;
    virtual wxString GetWildcard() const wxOVERRIDE { return this->m_wildCard; }
    virtual wxString GetPath() const wxOVERRIDE;
    virtual void GetPaths( wxArrayString& paths ) const wxOVERRIDE;
    virtual void GetFilenames( wxArrayString& files ) const wxOVERRIDE;
    virtual int GetFilterIndex() const wxOVERRIDE { return m_fc.GetFilterIndex(); }

    virtual bool HasMultipleFileSelection() const wxOVERRIDE { return HasFlag( wxFC_MULTIPLE ); }
    virtual void ShowHidden(bool show) wxOVERRIDE;

    virtual bool HasFilterChoice() const
        { return m_fc.HasFilterChoice(); }

    // Implementation only from now on.
    bool GTKShouldIgnoreNextFilterEvent() const
        { return m_fc.ShouldIgnoreNextFilterEvent(); }

    bool    m_checkNextSelEvent;
    bool    m_ignoreNextFolderChangeEvent;

protected:
    GtkFileChooser     *m_fcWidget;
    wxGtkFileChooser    m_fc;
    wxString            m_wildCard;

private:
    void Init();

    DECLARE_DYNAMIC_CLASS( wxGtkFileCtrl )
};

#endif // wxUSE_FILECTRL

#endif // _WX_GTK_FILECTRL_H_


text:
<?php

namespace PharIo\Manifest;

use PharIo\Version\Version;
use PharIo\Version\Exception as VersionException;
use PharIo\Version\VersionConstraintParser;

class ManifestDocumentMapper {
    /**
     * @param ManifestDocument $document
     *
     * @returns Manifest
     *
     * @throws ManifestDocumentMapperException
     */
    public function map(ManifestDocument $document) {
        try {
            $contains          = $document->getContainsElement();
            $type              = $this->mapType($contains);
            $copyright         = $this->mapCopyright($document->getCopyrightElement());
            $requirements      = $this->mapRequirements($document->getRequiresElement());
            $bundledComponents = $this->mapBundledComponents($document);

            return new Manifest(
                new ApplicationName($contains->getName()),
                new Version($contains->getVersion()),
                $type,
                $copyright,
                $requirements,
                $bundledComponents
            );
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException($e->getMessage(), $e->getCode(), $e);
        } catch (Exception $e) {
            throw new ManifestDocumentMapperException($e->getMessage(), $e->getCode(), $e);
        }
    }

    /**
     * @param ContainsElement $contains
     *
     * @return Type
     *
     * @throws ManifestDocumentMapperException
     */
    private function mapType(ContainsElement $contains) {
        switch ($contains->getType()) {
            case 'application':
                return Type::application();
            case 'library':
                return Type::library();
            case 'extension':
                return $this->mapExtension($contains->getExtensionElement());
        }

        throw new ManifestDocumentMapperException(
            sprintf('Unsupported type %s', $contains->getType())
        );
    }

    /**
     * @param CopyrightElement $copyright
     *
     * @return CopyrightInformation
     *
     * @throws InvalidUrlException
     * @throws InvalidEmailException
     */
    private function mapCopyright(CopyrightElement $copyright) {
        $authors = new AuthorCollection();

        foreach($copyright->getAuthorElements() as $authorElement) {
            $authors->add(
                new Author(
                    $authorElement->getName(),
                    new Email($authorElement->getEmail())
                )
            );
        }

        $licenseElement = $copyright->getLicenseElement();
        $license        = new License(
            $licenseElement->getType(),
            new Url($licenseElement->getUrl())
        );

        return new CopyrightInformation(
            $authors,
            $license
        );
    }

    /**
     * @param RequiresElement $requires
     *
     * @return RequirementCollection
     *
     * @throws ManifestDocumentMapperException
     */
    private function mapRequirements(RequiresElement $requires) {
        $collection = new RequirementCollection();
        $phpElement = $requires->getPHPElement();
        $parser     = new VersionConstraintParser;

        try {
            $versionConstraint = $parser->parse($phpElement->getVersion());
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException(
                sprintf('Unsupported version constraint - %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }

        $collection->add(
            new PhpVersionRequirement(
                $versionConstraint
            )
        );

        if (!$phpElement->hasExtElements()) {
            return $collection;
        }

        foreach($phpElement->getExtElements() as $extElement) {
            $collection->add(
                new PhpExtensionRequirement($extElement->getName())
            );
        }

        return $collection;
    }

    /**
     * @param ManifestDocument $document
     *
     * @return BundledComponentCollection
     */
    private function mapBundledComponents(ManifestDocument $document) {
        $collection = new BundledComponentCollection();

        if (!$document->hasBundlesElement()) {
            return $collection;
        }

        foreach($document->getBundlesElement()->getComponentElements() as $componentElement) {
            $collection->add(
                new BundledComponent(
                    $componentElement->getName(),
                    new Version(
                        $componentElement->getVersion()
                    )
                )
            );
        }

        return $collection;
    }

    /**
     * @param ExtensionElement $extension
     *
     * @return Extension
     *
     * @throws ManifestDocumentMapperException
     */
    private function mapExtension(ExtensionElement $extension) {
        try {
            $parser            = new VersionConstraintParser;
            $versionConstraint = $parser->parse($extension->getCompatible());

            return Type::extension(
                new ApplicationName($extension->getFor()),
                $versionConstraint
            );
        } catch (VersionException $e) {
            throw new ManifestDocumentMapperException(
                sprintf('Unsupported version constraint - %s', $e->getMessage()),
                $e->getCode(),
                $e
            );
        }
    }
}


text:
package aqa.variable;

import aqa.InterpreterException;
import aqa.value.StringValue;
import aqa.value.IntegerValue;
import aqa.value.NullValue;
import aqa.value.ValueBase;
import aqa.value.Value;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;

/**
 *
 * @author martinhart
 */
public class VariableTest {

    private Variable subject;

    @Before
    public void setUp() {
        subject = new Variable("Variable1");
    }

    @Test
    public void constructorSuppliesName() {
        assertEquals("Variable1", subject.getName());
    }

    @Test
    public void testConstructorSetsName() {
        subject = new Variable("wibble");
        assertEquals("wibble", subject.getName());
    }

    @Test
    public void whenCreatedItHasNullValue() {
        assertEquals(true, subject.getValue() instanceof NullValue);
    }

    @Test
    public void notConstantByDefault() {
        assertEquals(false, subject.isConstant());
    }

    @Test
    public void ifConstantCanStillAssignFirstValue() throws Exception {
        Value sv = new StubValue();
        subject.makeConstant();
        subject.setValue(sv);
        assertEquals(sv, subject.getValue());
    }

    @Test
    public void canChangeValueOfNonConstantVariable() throws Exception {
        Value v1 = new StubValue();
        Value v2 = new StubValue();
        subject.setValue(v1);
        subject.setValue(v2);
        assertEquals(v2, subject.getValue());
        assertNotEquals(v1, subject.getValue());
    }

    @Test(expected=Exception.class)
    public void cannotChangeValueOfConstantVariable() throws Exception {
        Value v1 = new StubValue();
        Value v2 = new StubValue();
        subject.makeConstant();
        subject.setValue(v1);
        subject.setValue(v2);
    }

    private class StubValue extends ValueBase {

        public StubValue() {
            super("StubValue");
        }

        @Override
        public String inspect() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public String output() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public int compare(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public boolean equal(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value add(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value subtract(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value multiply(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value divide(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value div(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Value mod(Value other) throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public IntegerValue length() throws InterpreterException {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public Object getValue() {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }
}


text:
package it.redhat.demo.event;

public class EventContent {

	private String content;

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "EventContent [content=" + content + "]";
	}

}


text:
package com.communote.server.core.database.config;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.hibernate.dialect.function.SQLFunction;

import com.communote.server.api.core.config.database.DatabaseConfiguration;
import com.communote.server.core.database.hibernate.C3P0DataSourceConnectionProvider;
import com.communote.server.core.database.hibernate.StandardLikeFulltextFunction;

/**
 * DatabaseConfiguration without fulltext support. The HQL fulltext function will be translated to a
 * standard LIKE query.
 *
 * @author Communote GmbH - http://www.communote.com/
 *
 */
public class StandardDatabaseConfiguration implements DatabaseConfiguration {

    /**
     * Name of a System property which can hold the full qualified class name of a
     * org.hibernate.connection.ConnectionProvider
     */
    public static final String COMMUNOTE_CONNECTION_PROVIDER_CLASS = "communote.connectionProviderClass";

    /**
     * Get the class name of the org.hibernate.connection.ConnectionProvider to use. This
     * implementation will return the value of the system property
     * {@value #COMMUNOTE_CONNECTION_PROVIDER_CLASS} or C3P0DataSourceConnectionProvider if the
     * property is not set.
     *
     * @return the full qualified class name of the connection provider
     */
    @Override
    public String getConnectionProviderClassName() {
        String connectionProviderName = System.getProperty(COMMUNOTE_CONNECTION_PROVIDER_CLASS);
        if (StringUtils.isBlank(connectionProviderName)) {
            connectionProviderName = C3P0DataSourceConnectionProvider.class.getName();

        }

        return connectionProviderName;
    }

    @Override
    public SQLFunction getDatepartSQLFunction() {
        // not supported
        return null;
    }

    /**
     * {@inheritDoc}
     *
     * Evaluates to the % syntax
     */
    @Override
    public String getFulltextParameterValue(String pattern, MatchMode matchMode,
            boolean doNotUseFulltext) {
        return matchMode.toMatchString(pattern);
    }

    /**
     * {@inheritDoc}
     *
     * Evaluates to the % syntax
     */
    @Override
    public final String getFulltextParameterValue(String pattern,
            org.hibernate.criterion.MatchMode matchMode) {
        return this.getFulltextParameterValue(pattern, matchMode, false);
    }

    /**
     * {@inheritDoc}
     *
     * The like function will be returned
     */
    @Override
    public SQLFunction getFulltextSQLFunction() {
        return new StandardLikeFulltextFunction();
    }

    @Override
    public boolean isExtendSubselectsWithOuterConditions() {
        return false;
    }

    /**
     * @return always returns false
     */
    @Override
    public boolean isUseFulltextFeature() {
        return false;
    }

}


text:
/**
 * Created by Chris, Z on 6/8/2016 2:45 PM.
 */
import $ from "jquery";
$("body").html("Hello");

//require("babel-polyfill");
//console.log(`small-bird: ${require("./src/images/small-bird.jpg").substr(0, 100)}...`);
//console.log(`big-bird: ${require("./src/images/big-bird.jpg")}`);
//require("./src/css/style.scss");
//
//let fibonacci = require("./src/js/es6.fibonacci.js"), arr = [];
//for (let v of fibonacci) {
//    if (v > 1000) break;
//    arr.push(v);
//}
//console.log(`Fibonacci: ${arr.join(", ")}`);
//
////document.write(require("./src/html/webpack.html"));
//console.dir(`jQuery Version: ${require("jquery").fn.jquery}`);


text:
<?php

namespace Map\Http\Controllers;

use Map\Auth\Authenticator;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Views\Twig;

class AuthController
{
    /**
     * @var Twig
     */
    private $twig;

    /**
     * @var LDAPAuthenticator
     */
    private $auth;

    /**
     * AuthController constructor.
     * @param Twig $twig
     * @param Authenticator $auth
     */
    public function __construct(Twig $twig, Authenticator $auth)
    {
        $this->twig = $twig;
        $this->auth = $auth;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function getLogin(Request $request, Response $response)
    {
        return $this->twig->render($response, 'auth/login.twig');
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return static
     */
    public function postLogin(Request $request, Response $response)
    {
        $auth = $this->auth->attempt($request->getParam('username'), $request->getParam('password'));

        if (!$auth) {
            return $response->withRedirect('/login');
        }

        return $response->withRedirect('/');
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return static
     */
    public function getLogout(Request $request, Response $response)
    {
        $this->auth->logout();

        return $response->withRedirect('/');
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Biatorella simplex var. herpes Norman

### Remarks
null


text:
use strict;
use warnings;

use LWP::Simple;
use JSON	qw(from_json);
use Getopt::Long;
use File::Basename;
use Cwd;

my $JAVA_PATH = "/usr/bin/java";
my $VERSION_URL = "https://s3.amazonaws.com/Minecraft.Download/versions/versions.json";
my $DOWNLOAD_URL = "https://s3.amazonaws.com/Minecraft.Download/versions/%s/minecraft_server.%s.jar";
my $USAGE = "usage: %s [options] <server jar> [<java opts> [<server opts>]]\n";

sub usage {
	my ($rv) = @_;
	printf $USAGE, $0;

	if (defined $rv) {
		exit $rv;
	} else {
		exit 1;
	}
}

sub check_latest {
	my $decoded = from_json(get($VERSION_URL));
	my $latest = $decoded->{'latest'};
	return $latest->{'release'};
}

sub check_for_server {
	my ($dir, $version) = @_;
	my $filename = $dir . "/minecraft_server.${version}.jar";
	return (-e $filename);
}

sub download_server {
	my ($dir, $version) = @_;
	my $url = sprintf($DOWNLOAD_URL, $version, $version);
	printf "%s\n", $url;
	mkdir $dir;
	my $download_path = $dir . "/minecraft_server.${version}.jar";
	my $symlink = $dir . "/minecraft_server.jar";

	getstore($url, $download_path)
		or die("Failed to download server.");
	symlink $download_path, $symlink
		or die("Failed to create symlink to new server file.");

	return $download_path;
}

sub run_server {
	my ($j_opts, $s_opts, $jar, $dir) = @_;
	my $command = "${JAVA_PATH} ${j_opts} -jar ${jar} ${s_opts}";
	chdir($dir);
	print $command . "\n";
	exec($command) or die("Failed to start server.");
}

usage unless defined $ARGV[0];

my $jar_file = $ARGV[0];
my $java_opts = $ARGV[1];
my $server_opts = $ARGV[2];

my $server_dir = dirname($jar_file);

print "Checking for server file...\n";
my $latest = &check_latest;
print "Latest version: ${latest}\n";
my $server_exists = check_for_server($server_dir, $latest);

unless ($server_exists) {
	print "Downloading latest server...\n";
	download_server($server_dir, $latest);
}

$java_opts = "" unless defined $java_opts;
$server_opts = "" unless defined $server_opts;

printf "Java options: %s\n", $java_opts;
printf "Server options: %s\n", $server_opts;

run_server($java_opts, $server_opts, $jar_file, $server_dir);


text:
define([
		"dojo/_base/lang",
		"dojo/_base/declare",
		"dojo/_base/Color",
		"../../RectangularGauge",
		"../../LinearScaler",
		"../../RectangularScale",
		"../../RectangularValueIndicator",
		"../DefaultPropertiesMixin"
	],
	function(lang, declare, Color, RectangularGauge, LinearScaler, RectangularScale, RectangularValueIndicator, DefaultPropertiesMixin){
		return declare("dojox.dgauges.components.black.HorizontalLinearGauge", [RectangularGauge, DefaultPropertiesMixin], {
			// summary:
			//		A horizontal gauge widget.

			// borderColor: Object|Array|int
			//		The border color. Default is "#000000".
			borderColor: "#000000",
			// fillColor: Object|Array|int
			//		The background color. Default is "#000000".
			fillColor: "#000000",
			// indicatorColor: Object|Array|int
			//		The indicator fill color. Default is "#A4A4A4".
			indicatorColor: "#A4A4A4",
			constructor: function(){
				// Base colors
				this.borderColor = new Color(this.borderColor);
				this.fillColor = new Color(this.fillColor);
				this.indicatorColor = new Color(this.indicatorColor);

				this.addElement("background", lang.hitch(this, this.drawBackground));

				// Scaler
				var scaler = new LinearScaler();

				// Scale
				var scale = new RectangularScale();
				scale.set("scaler", scaler);
				scale.set("labelPosition", "leading");
				scale.set("paddingLeft", 30);
				scale.set("paddingRight", 30);
				scale.set("paddingTop", 34);
				scale.set("labelGap", 8);
				scale.set("font", {
					family: "Helvetica",
					weight: "bold",
					size: "7pt",
					color: "#CECECE"
				});
				scale.set("tickShapeFunc", function(group, scale, tick){
					return group.createCircle({
						r: tick.isMinor ? 0.5 : 3
					}).setFill("#CECECE");
				});
				this.addElement("scale", scale);

				var indicator = new RectangularValueIndicator();
				indicator.set("interactionArea", "gauge");
				indicator.set("value", scaler.minimum);
				indicator.set("paddingTop", 30);
				indicator.set("indicatorShapeFunc", lang.hitch(this, function(group, indicator){
					return group.createPolyline([0, 0, -10, -20, 10, -20, 0, 0]).setFill(this.indicatorColor).setStroke({
						color: [70, 70, 70],
						width: 1,
						style: "Solid",
						cap: "butt",
						join: 20.0
					});

				}));
				scale.addIndicator("indicator", indicator);
			},

			drawBackground: function(g, w, h){
				// summary:
				//		Draws the background shape of the gauge.
				// g: dojox/gfx/Group
				//		The group used to draw the background.
				// w: Number
				//		The width of the gauge.
				// h: Number
				//		The height of the gauge.
				// tags:
				//		protected
				g.createRect({
					x: 0,
					y: 0,
					width: w,
					height: 50,
					r: 15
				}).setFill(this.borderColor);
				g.createRect({
					x: 4,
					y: 4,
					width: w - 8,
					height: 42,
					r: 12
				}).setFill({
					type: "linear",
					x1: 0,
					y1: 50,
					x2: 0,
					y2: 30,
					colors: [
						{offset: 0, color: [100,100,100]},
						{offset: 1, color: this.fillColor}
					]
				});
				g.createPath().moveTo(4, 25).vLineTo(14).smoothCurveTo(4, 4, 18, 4).hLineTo(w - 16).smoothCurveTo(w - 4, 4, w - 4, 16).closePath().setFill({
					type: "linear",
					x1: 0,
					y1: 0,
					x2: 0,
					y2: 20,
					colors: [
						{offset: 0, color: [150,150,150]},
						{offset: 1, color: this.fillColor}
					]
				});
				g.createPath().moveTo(4, 25).vLineTo(14).smoothCurveTo(4, 4, 18, 4).hLineTo(w - 16).smoothCurveTo(w - 4, 4, w - 4, 16).closePath().setFill([255,255,255,0.05]);
			}
		});
	}
);


text:
require 'mkmf'

LIBDIR = RbConfig::CONFIG['libdir']
INCLUDEDIR = RbConfig::CONFIG['includedir']

HEADER_DIRS = [
  # Search /opt/local (Mac source install)
  '/opt/local/include',

  # Search /usr/local (Source install)
  '/usr/local/include',

  # Check the ruby install locations
  INCLUDEDIR
]

LIB_DIRS = [
  # Search /opt/local (Mac source install)
  '/opt/local/lib',

  # Search /usr/local (Source install)
  '/usr/local/lib',

  # Check the ruby install locations
  LIBDIR
]

windows = RUBY_PLATFORM =~ /mingw|mswin/

grpc_root = File.expand_path(File.join(File.dirname(__FILE__), '../../../..'))

grpc_config = ENV['GRPC_CONFIG'] || 'opt'

if ENV.key?('GRPC_LIB_DIR')
  grpc_lib_dir = File.join(grpc_root, ENV['GRPC_LIB_DIR'])
else
  grpc_lib_dir = File.join(grpc_root, 'libs', grpc_config)
end

ENV['MACOSX_DEPLOYMENT_TARGET'] = '10.7'

unless File.exist?(File.join(grpc_lib_dir, 'libgrpc.a')) or windows
  ENV['AR'] = RbConfig::CONFIG['AR'] + ' rcs'
  ENV['CC'] = RbConfig::CONFIG['CC']
  ENV['LD'] = ENV['CC']

  ENV['AR'] = 'libtool -o' if RUBY_PLATFORM =~ /darwin/

  ENV['EMBED_OPENSSL'] = 'true'
  ENV['EMBED_ZLIB'] = 'true'
  ENV['ARCH_FLAGS'] = RbConfig::CONFIG['ARCH_FLAG']
  ENV['ARCH_FLAGS'] = '-arch i386 -arch x86_64' if RUBY_PLATFORM =~ /darwin/
  ENV['CFLAGS'] = '-DGPR_BACKWARDS_COMPATIBILITY_MODE'

  output_dir = File.expand_path(RbConfig::CONFIG['topdir'])
  grpc_lib_dir = File.join(output_dir, 'libs', grpc_config)
  ENV['BUILDDIR'] = output_dir

  puts 'Building internal gRPC into ' + grpc_lib_dir
  system("make -j -C #{grpc_root} #{grpc_lib_dir}/libgrpc.a CONFIG=#{grpc_config}")
  exit 1 unless $? == 0
end

$CFLAGS << ' -I' + File.join(grpc_root, 'include')
$LDFLAGS << ' ' + File.join(grpc_lib_dir, 'libgrpc.a') unless windows
if grpc_config == 'gcov'
  $CFLAGS << ' -O0 -fprofile-arcs -ftest-coverage'
  $LDFLAGS << ' -fprofile-arcs -ftest-coverage -rdynamic'
end

$LDFLAGS << ' -Wl,-wrap,memcpy' if RUBY_PLATFORM =~ /linux/
$LDFLAGS << ' -static' if windows

$CFLAGS << ' -std=c99 '
$CFLAGS << ' -Wall '
$CFLAGS << ' -Wextra '
$CFLAGS << ' -pedantic '
$CFLAGS << ' -Werror '
$CFLAGS << ' -Wno-format '

output = File.join('grpc', 'grpc_c')
puts 'Generating Makefile for ' + output
create_makefile(output)

strip_tool = RbConfig::CONFIG['STRIP']
strip_tool = 'strip -x' if RUBY_PLATFORM =~ /darwin/

if grpc_config == 'opt'
  File.open('Makefile.new', 'w') do |o|
    o.puts 'hijack: all strip'
    o.puts
    File.foreach('Makefile') do |i|
      o.puts i
    end
    o.puts
    o.puts 'strip:'
    o.puts "\t$(ECHO) Stripping $(DLLIB)"
    o.puts "\t$(Q) #{strip_tool} $(DLLIB)"
  end
  File.rename('Makefile.new', 'Makefile')
end


text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Path = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

// Based on https://github.com/joyent/node/blob/41e53e557992a7d552a8e23de035f9463da25c99/lib/path.js

// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
  // if the path tries to go above the root, `up` ends up > 0
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last = parts[i];
    if (last === '.') {
      parts.splice(i, 1);
    } else if (last === '..') {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }

  // if the path is allowed to go above the root, restore leading ..s
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift('..');
    }
  }

  return parts;
}

// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
      /^(\/?)([\s\S]+\/(?!$)|\/)?((?:\.{1,2}$|[\s\S]+?)?(\.[^.\/]*)?)$/;
var splitPath = function(filename) {
  var result = splitPathRe.exec(filename);
  return [result[1] || '', result[2] || '', result[3] || '', result[4] || ''];
};

// path.resolve([from ...], to)
function resolve() {
  var resolvedPath = '',
      resolvedAbsolute = false;

  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    // XXXfiler: we don't have process.cwd() so we use '/' as a fallback
    var path = (i >= 0) ? arguments[i] : '/';

    // Skip empty and invalid entries
    if (typeof path !== 'string' || !path) {
      continue;
    }

    resolvedPath = path + '/' + resolvedPath;
    resolvedAbsolute = path.charAt(0) === '/';
  }

  // At this point the path should be resolved to a full absolute path, but
  // handle relative paths to be safe (might happen when process.cwd() fails)

  // Normalize the path
  resolvedPath = normalizeArray(resolvedPath.split('/').filter(function(p) {
    return !!p;
  }), !resolvedAbsolute).join('/');

  return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
}

// path.normalize(path)
function normalize(path) {
  var isAbsolute = path.charAt(0) === '/',
      trailingSlash = path.substr(-1) === '/';

  // Normalize the path
  path = normalizeArray(path.split('/').filter(function(p) {
    return !!p;
  }), !isAbsolute).join('/');

  if (!path && !isAbsolute) {
    path = '.';
  }
  /*
   if (path && trailingSlash) {
   path += '/';
   }
   */

  return (isAbsolute ? '/' : '') + path;
}

function join() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return normalize(paths.filter(function(p, index) {
    return p && typeof p === 'string';
  }).join('/'));
}

// path.relative(from, to)
function relative(from, to) {
  from = resolve(from).substr(1);
  to = resolve(to).substr(1);

  function trim(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== '') break;
    }

    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== '') break;
    }

    if (start > end) return [];
    return arr.slice(start, end - start + 1);
  }

  var fromParts = trim(from.split('/'));
  var toParts = trim(to.split('/'));

  var length = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length;
  for (var i = 0; i < length; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }

  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push('..');
  }

  outputParts = outputParts.concat(toParts.slice(samePartsLength));

  return outputParts.join('/');
}

function dirname(path) {
  var result = splitPath(path),
      root = result[0],
      dir = result[1];

  if (!root && !dir) {
    // No dirname whatsoever
    return '.';
  }

  if (dir) {
    // It has a dirname, strip trailing slash
    dir = dir.substr(0, dir.length - 1);
  }

  return root + dir;
}

function basename(path, ext) {
  var f = splitPath(path)[2];
  // TODO: make this comparison case-insensitive on windows?
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  // XXXfiler: node.js just does `return f`
  return f === "" ? "/" : f;
}

function extname(path) {
  return splitPath(path)[3];
}

function isAbsolute(path) {
  if(path.charAt(0) === '/') {
    return true;
  }
  return false;
}

function isNull(path) {
  if (('' + path).indexOf('\u0000') !== -1) {
    return true;
  }
  return false;
}

// Make sure we don't double-add a trailing slash (e.g., '/' -> '//')
function addTrailing(path) {
  return path.replace(/\/*$/, '/');
}

// Deal with multiple slashes at the end, one, or none
// and make sure we don't return the empty string.
function removeTrailing(path) {
  path = path.replace(/\/*$/, '');
  return path === '' ? '/' : path;
}

// XXXfiler: we don't support path.exists() or path.existsSync(), which
// are deprecated, and need a FileSystem instance to work. Use fs.stat().

module.exports = {
  normalize: normalize,
  resolve: resolve,
  join: join,
  relative: relative,
  sep: '/',
  delimiter: ':',
  dirname: dirname,
  basename: basename,
  extname: extname,
  isAbsolute: isAbsolute,
  isNull: isNull,
  // Non-node but useful...
  addTrailing: addTrailing,
  removeTrailing: removeTrailing
};

},{}]},{},[1])(1)
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.rndm.todo"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="de.rndm.todo.activities.DashboardActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="de.rndm.todo.activities.DetailActivity"
            android:label="@string/title_activity_detail" >
        </activity>
        <activity
                android:name="de.rndm.todo.activities.ContactActivity"
                android:label="@string/title_activity_contact" >
        </activity>
    </application>

</manifest>


text:
package com.google.gerrit.httpd;

import com.google.gerrit.server.account.AccountManager;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;

import java.io.IOException;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Singleton
class HttpLogoutServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  private final Provider<WebSession> webSession;
  private final Provider<String> urlProvider;
  private final String logoutUrl;

  @Inject
  HttpLogoutServlet(final AuthConfig authConfig,
      final Provider<WebSession> webSession,
      @CanonicalWebUrl @Nullable final Provider<String> urlProvider,
      final AccountManager accountManager) {
    this.webSession = webSession;
    this.urlProvider = urlProvider;
    this.logoutUrl = authConfig.getLogoutURL();
  }

  @Override
  protected void doGet(final HttpServletRequest req,
      final HttpServletResponse rsp) throws IOException {
    webSession.get().logout();
    if (logoutUrl != null) {
      rsp.sendRedirect(logoutUrl);
    } else {
      rsp.sendRedirect(urlProvider.get());
    }
  }
}


text:
/*
  index.js

  Express routes for our application
*/

'use strict';

const router     = require('express').Router();
const SensorData = require('../model/sensor-data.js');
const moment     = require('moment');

// DeviceManager provides a platform-independent interface to our hardware devices
// so we can install and run this application on different platforms.
//
const DeviceManager = require('../devices/device-manager.js');
const deviceManager = DeviceManager.instance();

// GET live sensor data
//
router.get('/sensors/live', (req, res) =>
  deviceManager.readSensors()
    .then((data) => res.status(200).send(data))
    .catch((err) => res.status(500).send(err)));

// GET sensor history data
//
router.get('/sensors/history/:startDate?/:endDate?', (req, res) => {

  let query = { deviceId : process.env.PI_WEATHER_STATION_DEVICE_ID };

  var start_date = req.params.startDate;
  if (!start_date) {
    start_date = '1970-01-01T00:00';
  } else {
    if(!moment(start_date, moment.ISO_8601).isValid()) {
          return res.status(400).send('Invalid ISO 8601 startDate');
    }
  }
  var end_date = req.params.endDate;
  if (!end_date) {
    end_date = new Date();
  } else {
    if(!moment(end_date, moment.ISO_8601).isValid()) {
      return res.status(400).send('Invalid ISO 8601 startDate');
    }
  }

  query.timestamp = {'$gte' : start_date, '$lte' : end_date };

  SensorData.find(query)
            .select('-_id -__v -deviceId') // Keep it clean for the caller. Could also {select : false} in the SensorData schema definition.
            .exec((err, docs) => err ? res.status(500).send(err) : res.status(200).send(docs));
});

// GET GPS location, timezone, other associated data
//
router.get('/location', (req, res) =>
  deviceManager.locationDetails()
    .then((data) => res.status(200).send(data))
    .catch((err) => res.status(500).send(err)));

module.exports = router;


text:
define([
    'modules/room/module'
], function (module) {
    'use strict';

    module.controller('modules/room/components/rcu/rcu', [
        '$scope',
        '$modal',
        'modules.manageui.factories.tableParameter',
        'app.services.httpService',
        'app.services.ajaxService',
        'app.services.popupService',
        function ($scope, $modal, tableParameter, httpService, ajaxService, popupService) {
            var me = this;

            this.current = null;

            this.floorParams = {
                floorid: null
            };

            this.timeTable = new tableParameter({
                url: '/rcuSettime/findRunTimeRcu',
                data: me.floorParams
            });

            // this.paramTable = new tableParameter({
            //     url: '/rcuSetparam/findRcuSetparam',
            //     data: me.floorParams
            // });

            // this.paramTable = new tableParameter({
            //     url: '/rcuSetparam/findRcuSetparam',
            //     data: me.floorParams
            // });

            this.upgrade = function () {

            };

            this.reset = function () {
                $modal
                    .open({
                        templateUrl: 'modules/room/components/rcu/reset.html'
                    });
            };

            this.select = function (floor) {
                me.current = floor;
                me.floorParams.floorid = floor.id;
                me.timeTable.reload();
                //me.paramTable.reload();
            };
        }
    ]);
});


text:
class RDoc::Markup::Rule < Struct.new :weight

  ##
  # Calls #accept_rule on +visitor+

  def accept visitor
    visitor.accept_rule self
  end

  def pretty_print q # :nodoc:
    q.group 2, '[rule:', ']' do
      q.pp weight
    end
  end

end


text:
package com.adobe.testing.s3mock.dto;

import static com.adobe.testing.s3mock.dto.CopySource.DELIMITER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;

import java.util.UUID;
import org.junit.jupiter.api.Test;

/**
 * Verifies parsing behaviour from {@link CopySource}.
 */
public class CopySourceTest {

  private static final String BUCKET = UUID.randomUUID().toString();
  private static final String KEY = UUID.randomUUID().toString();
  private static final String VALID_COPY_SOURCE = BUCKET + DELIMITER + KEY;

  @Test
  public void fromPrefixedCopySourceString() {
    final CopySource copySource = new CopySource(DELIMITER + VALID_COPY_SOURCE);

    assertThat(copySource.getBucket()).isEqualTo(BUCKET);
    assertThat(copySource.getKey()).isEqualTo(KEY);
  }

  @Test
  public void fromCopySourceString() {
    final CopySource copySource = new CopySource(VALID_COPY_SOURCE);

    assertThat(copySource.getBucket()).isEqualTo(BUCKET);
    assertThat(copySource.getKey()).isEqualTo(KEY);
  }

  @Test
  public void invalidCopySource() {
    Throwable thrown = catchThrowable(() -> new CopySource(UUID.randomUUID().toString()));
    assertThat(thrown).isInstanceOf(IllegalArgumentException.class);
  }

  @Test
  public void nullCopySource() {
    Throwable thrown = catchThrowable(() -> new CopySource(null));
    assertThat(thrown).isInstanceOf(NullPointerException.class);
  }
}


text:
PEGASUS_USING_PEGASUS;

extern "C" PEGASUS_EXPORT ProviderManager * PegasusCreateProviderManager(const String & providerManagerName)
{
    if(String::equalNoCase(providerManagerName, "INTERNAL"))
    {
        return(new InternalProviderManager());
    }

    return(0);
}


text:
static md5_state_t state[MAX_SLOTS];
static bool active = false;

void DebugDSPSetActive(bool activate) {
    active = activate;
    if(active) {
        for(int i=0;i<MAX_SLOTS;++i) {
            md5_init(state+i);
        }
    }
}

void DebugDSP(int slot, float value) {
    if(active) {
        assert(slot < MAX_SLOTS);
        md5_append(state+slot, (md5_byte_t*)&value, sizeof(float));
    }
}

bool DebugDSPCheck(int slot, const char* expected) {
    assert(slot < MAX_SLOTS);

    md5_byte_t digest[16];
    md5_finish(state+slot, digest);

    char digestStr[33];
    for(int i=0;i<16;++i) {
        sprintf(digestStr+2*i, "%02x", digest[i]);
    }

    if(strcmp(digestStr, expected)) {
        printf("Debug hash %s does not match expected hash %s\n", digestStr, expected);
        return false;
    }
    return true;
}