text:
"""
advancedTypes.py - Basic data structures not included with python
Copyright 2010  Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.

Includes:
    - CaselessDict - Case-insensitive dict
    - ProtectedDict/List/Tuple - Deeply read-only versions of these builtins
"""
from __future__ import print_function

import collections
import copy

## Template methods
def wrapMethod(methodName):
    return lambda self, *a, **k: getattr(self._data_, methodName)(*a, **k)

def protectMethod(methodName):
    return lambda self, *a, **k: protect(getattr(self._data_, methodName)(*a, **k))

class ProtectedDict(dict):
    """
    A class allowing read-only 'view' of a dict.
    The object can be treated like a normal dict, but will never modify the original dict it points to.
    Any values accessed from the dict will also be read-only.
    """

    def __init__(self, data):
        self._data_ = data

    ## List of methods to directly wrap from _data_
    wrapMethods = ['__contains__', '__eq__', '__format__', '__ge__', '__gt__', '__le__', '__len__', '__lt__',
                   '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count', 'has_key', 'iterkeys',
                   'keys', ]

    ## List of methods which wrap from _data_ but return protected results
    protectMethods = ['__getitem__', '__iter__', 'get', 'items', 'values']

    ## List of methods to disable
    disableMethods = ['__delitem__', '__setitem__', 'clear', 'pop', 'popitem', 'setdefault', 'update']

    def error(self, *args, **kargs):
        raise Exception("Can not modify read-only list.")

    ## Directly (and explicitly) wrap some methods from _data_
    ## Many of these methods can not be intercepted using __getattribute__, so they
    ## must be implemented explicitly
    for methodName in wrapMethods:
        locals()[methodName] = wrapMethod(methodName)

    ## Wrap some methods from _data_ with the results converted to protected objects
    for methodName in protectMethods:
        locals()[methodName] = protectMethod(methodName)

    ## Disable any methods that could change data in the list
    for methodName in disableMethods:
        locals()[methodName] = error

    ## Add a few extra methods.
    def copy(self):
        raise Exception("It is not safe to copy protected dicts! (instead try deepcopy, but be careful.)")

    def itervalues(self):
        for v in self._data_.values():
            yield protect(v)

    def iteritems(self):
        for k, v in self._data_.items():
            yield (k, protect(v))

    def deepcopy(self):
        return copy.deepcopy(self._data_)

    def __deepcopy__(self, memo):
        return copy.deepcopy(self._data_, memo)

class ProtectedList(collections.Sequence):
    """
    A class allowing read-only 'view' of a list or dict.
    The object can be treated like a normal list, but will never modify the original list it points to.
    Any values accessed from the list will also be read-only.

    Note: It would be nice if we could inherit from list or tuple so that isinstance checks would work.
          However, doing this causes tuple(obj) to return unprotected results (importantly, this means
          unpacking into function arguments will also fail)
    """

    def __init__(self, data):
        self._data_ = data
        # self.__mro__ = (ProtectedList, object)

    ## List of methods to directly wrap from _data_
    wrapMethods = ['__contains__', '__eq__', '__format__', '__ge__', '__gt__', '__le__', '__len__', '__lt__', '__ne__',
                   '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count', 'index']

    ## List of methods which wrap from _data_ but return protected results
    protectMethods = ['__getitem__', '__getslice__', '__mul__', '__reversed__', '__rmul__']

    ## List of methods to disable
    disableMethods = ['__delitem__', '__delslice__', '__iadd__', '__imul__', '__setitem__', '__setslice__', 'append',
                      'extend', 'insert', 'pop', 'remove', 'reverse', 'sort']

    def error(self, *args, **kargs):
        raise Exception("Can not modify read-only list.")

    ## Directly (and explicitly) wrap some methods from _data_
    ## Many of these methods can not be intercepted using __getattribute__, so they
    ## must be implemented explicitly
    for methodName in wrapMethods:
        locals()[methodName] = wrapMethod(methodName)

    ## Wrap some methods from _data_ with the results converted to protected objects
    for methodName in protectMethods:
        locals()[methodName] = protectMethod(methodName)

    ## Disable any methods that could change data in the list
    for methodName in disableMethods:
        locals()[methodName] = error

    ## Add a few extra methods.
    def __iter__(self):
        for item in self._data_:
            yield protect(item)

    def __add__(self, op):
        if isinstance(op, ProtectedList):
            return protect(self._data_.__add__(op._data_))
        elif isinstance(op, list):
            return protect(self._data_.__add__(op))
        else:
            raise TypeError("Argument must be a list.")

    def __radd__(self, op):
        if isinstance(op, ProtectedList):
            return protect(op._data_.__add__(self._data_))
        elif isinstance(op, list):
            return protect(op.__add__(self._data_))
        else:
            raise TypeError("Argument must be a list.")

    def deepcopy(self):
        return copy.deepcopy(self._data_)

    def __deepcopy__(self, memo):
        return copy.deepcopy(self._data_, memo)

    def poop(self):
        raise Exception("This is a list. It does not poop.")

class ProtectedTuple(collections.Sequence):
    """
    A class allowing read-only 'view' of a tuple.
    The object can be treated like a normal tuple, but its contents will be returned as protected objects.

    Note: It would be nice if we could inherit from list or tuple so that isinstance checks would work.
          However, doing this causes tuple(obj) to return unprotected results (importantly, this means
          unpacking into function arguments will also fail)
    """

    def __init__(self, data):
        self._data_ = data

    ## List of methods to directly wrap from _data_
    wrapMethods = ['__contains__', '__eq__', '__format__', '__ge__', '__getnewargs__', '__gt__', '__hash__', '__le__',
                   '__len__', '__lt__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__str__', 'count',
                   'index']

    ## List of methods which wrap from _data_ but return protected results
    protectMethods = ['__getitem__', '__getslice__', '__iter__', '__add__', '__mul__', '__reversed__', '__rmul__']

    ## Directly (and explicitly) wrap some methods from _data_
    ## Many of these methods can not be intercepted using __getattribute__, so they
    ## must be implemented explicitly
    for methodName in wrapMethods:
        locals()[methodName] = wrapMethod(methodName)

    ## Wrap some methods from _data_ with the results converted to protected objects
    for methodName in protectMethods:
        locals()[methodName] = protectMethod(methodName)

    ## Add a few extra methods.
    def deepcopy(self):
        return copy.deepcopy(self._data_)

    def __deepcopy__(self, memo):
        return copy.deepcopy(self._data_, memo)

def protect(obj):
    if isinstance(obj, dict):
        return ProtectedDict(obj)
    elif isinstance(obj, list):
        return ProtectedList(obj)
    elif isinstance(obj, tuple):
        return ProtectedTuple(obj)
    else:
        return obj

if __name__ == '__main__':
    d = {'x': 1, 'y': [1, 2], 'z': ({'a': 2, 'b': [3, 4], 'c': (5, 6)}, 1, 2)}
    dp = protect(d)

    l = [1, 'x', ['a', 'b'], ('c', 'd'), {'x': 1, 'y': 2}]
    lp = protect(l)

    t = (1, 'x', ['a', 'b'], ('c', 'd'), {'x': 1, 'y': 2})
    tp = protect(t)


text:
  triagens::basics::ReadUnlocker READ_UNLOCKER_VAR_B(__LINE__)(&b, __FILE__, __LINE__)

// -----------------------------------------------------------------------------
// --SECTION--                                                  class ReadLocker
// -----------------------------------------------------------------------------

namespace triagens {
  namespace basics {

////////////////////////////////////////////////////////////////////////////////
/// @brief read unlocker
///
/// A ReadUnlocker unlocks a read-write lock during its lifetime and reaquires
/// the read-lock again when it is destroyed.
////////////////////////////////////////////////////////////////////////////////

    class ReadUnlocker {
        ReadUnlocker (ReadUnlocker const&);
        ReadUnlocker& operator= (ReadUnlocker const&);

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

      public:

////////////////////////////////////////////////////////////////////////////////
/// @brief unlocks the lock
///
/// The constructors unlocks the lock, the destructors aquires a read-lock.
////////////////////////////////////////////////////////////////////////////////

        explicit
        ReadUnlocker (ReadWriteLock* readWriteLock);

////////////////////////////////////////////////////////////////////////////////
/// @brief unlocks the lock
///
/// The constructors unlocks the lock, the destructors aquires a read-lock.
////////////////////////////////////////////////////////////////////////////////

        ReadUnlocker (ReadWriteLock* readWriteLock, char const* file, int line);

////////////////////////////////////////////////////////////////////////////////
/// @brief aquires the read-lock
////////////////////////////////////////////////////////////////////////////////

        ~ReadUnlocker ();

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

      private:

////////////////////////////////////////////////////////////////////////////////
/// @brief the read-write lock
////////////////////////////////////////////////////////////////////////////////

        ReadWriteLock* _readWriteLock;

////////////////////////////////////////////////////////////////////////////////
/// @brief file
////////////////////////////////////////////////////////////////////////////////

        char const* _file;

////////////////////////////////////////////////////////////////////////////////
/// @brief line number
////////////////////////////////////////////////////////////////////////////////

        int _line;
    };
  }
}

#endif

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:

redpajama_set_name: RedPajamaGithub


text:
package gov.nih.nci.nbia.download;

import gov.nih.nci.nbia.util.NBIAIOUtils;
import gov.nih.nci.nbia.util.StringUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.net.ssl.SSLHandshakeException;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;

/**
 * This class downloads each series.
 *
 * @author lethai
 *
 */
public class LocalSeriesDownloader extends AbstractSeriesDownloader {

	/* Constructor for SeriesDownloader */
	public LocalSeriesDownloader() {

	}

	/**
	 * {@inheritDoc}
	 *
	 * <p>
	 * Do a POST to the download servlet to retrieve the image files (with
	 * authentication/authorization for non-public artifacts)
	 */
	public void runImpl() throws Exception {
		this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);

		computeTotalSize();
		URL url = new URL(serverUrl);
		System.out.println(this.seriesInstanceUid +" -- start downloading");
		this.connectAndReadFromURL(url, 0);
		System.out.println(this.seriesInstanceUid +" -- downloading complete");
	}

// /////////////////////////////////////////PRIVATE//////////////////////////////////////

	/**
	 * images already received... sent back to server for pause and resume so
	 * server wont send these again.
	 */
	private List<String> sopUidsList = new ArrayList<String>();

	private String createDirectory() {

		String localLocation = outputDirectory.getAbsolutePath()
				+ File.separator + this.collection + File.separator
				+ this.patientId + File.separator + this.studyInstanceUid
				+ File.separator + this.seriesInstanceUid;
		File f = new File(localLocation);
		try {
			int count = 0;
			boolean mkdirResult = false;
			/*
			 * Attempt to create the directory again if it fails for 3 times.
			 * The reason for this is because 3 threads are started by default,
			 * sometime the directory is not created. We think it could be
			 * thread concurrency issue with parent directories creation, but
			 * couldn't reproduce the problem.
			 */
			while (count < 3) {
				if (!f.exists()) {
					mkdirResult = f.mkdirs();
					if (mkdirResult == false) {
						System.out.println("couldnt create directory: "
							+ localLocation + " \tattempt number: "
							+ count);
						count++;
					} else {
						break;
					}
				} else {
					mkdirResult = true;
					break;
				}
			}
			if (!mkdirResult) {
				throw new RuntimeException("Could not create directory after 3 attempts: " + localLocation);
			}
		} catch (SecurityException se) {
			throw new RuntimeException(
					"SecurityException on creating directory: " + localLocation + "  " + se);
		}
		return localLocation;
	}

	private void letSleep(int attempt) {
		// Let it sleep some time when attempt is great than one already
		if (attempt >= 1 && attempt < noOfRetry) {
			Random randomGenerator = new Random();
			int randomInt = randomGenerator.nextInt(60000) + attempt * 120000;
			System.out .println(getTimeStamp () + this.seriesInstanceUid +" attempt "+ attempt +" put into sleep for " + randomInt + "millisecond");
			try {

				Thread.sleep(randomInt);
			} catch (InterruptedException ex) {
				Thread.currentThread().interrupt();
				System.out.println("awakened prematurely:" + ex.getMessage());

			}
		}
	}

	private String getTimeStamp () {
		return new Timestamp(System.currentTimeMillis()).toString();
	}

	private void connectAndReadFromURL(URL url, int attempt) throws Exception {
		System.out.println(getTimeStamp() + " attempt" + attempt + " for the series" + this.seriesInstanceUid);
		if (attempt >= noOfRetry) {
			additionalInfo.append(getTimeStamp() + " For series " + this.seriesInstanceUid +" Reached max retry (" + noOfRetry + ") attempts.\n");
			System.out.println(additionalInfo + "--attempt" + attempt +" changing to error status");
			error();
			return;
		}

		letSleep(attempt);
		System.out.println(getTimeStamp() + " After coming out from sleep for series " + seriesInstanceUid +" @ attempt" + attempt);

		TrustStrategy easyStrategy = new TrustStrategy() {
			@Override
			public boolean isTrusted(X509Certificate[] certificate,
					String authType) throws CertificateException {
				return true;
			}
		};
		// set up a TrustManager that trusts everything
		SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		Scheme httpsScheme = new Scheme("https", 443, sslsf);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(httpsScheme);
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		HttpParams httpParams = new BasicHttpParams();
		// set timeout values
		HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
		HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
		ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);
		DefaultHttpClient httpClient = new DefaultHttpClient(ccm, httpParams);

		// Additions by lrt for tcia -
		// attempt to reduce errors going through a Coyote Point Equalizer load
		// balance switch
		httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
		httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
		httpClient.getParams().setParameter("http.tcp.nodelay", true);
		httpClient.getParams() .setParameter("http.connection.stalecheck", false);
		// end lrt additions

		HttpPost httpPostMethod = new HttpPost(url.toString());
		List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
		postParams.add(new BasicNameValuePair("userId", this.userId));
		postParams.add(new BasicNameValuePair("sopUids", this.sopUids));
		postParams.add(new BasicNameValuePair("seriesUid", this.seriesInstanceUid));
		postParams.add(new BasicNameValuePair("includeAnnotation", Boolean .toString(this.includeAnnotation)));
		postParams.add(new BasicNameValuePair("hasAnnotation", Boolean .toString(this.hasAnnotation)));
		// this is ignored
		postParams.add(new BasicNameValuePair("Range", "bytes=" + downloaded + "-"));
		postParams.add(new BasicNameValuePair("password", password));

		httpPostMethod.addHeader("password", password);
		HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
			@Override
			public boolean retryRequest(IOException exception,
					int executionCount, HttpContext context) {
				if (executionCount >= noOfRetry) {
					// Do not retry if over max retry count
					System.out .println(getTimeStamp() + seriesInstanceUid +" reached max retry handler attempt," + noOfRetry + "  stop downloading");
					additionalInfo.append("Reached max retry (" + noOfRetry + ") attempts using Request handler.\n");
					return false;
				}
				if (exception instanceof NoHttpResponseException) {
					// Retry on when server dropped connection
					System.out.println("NoHttpResponseException exception- Retry if the server dropped connection on us ");
					return true;
				}
				if (exception instanceof SSLHandshakeException) {
					// Do not retry on SSL handshake exception
					System.out.println("SSLHandshakeException exception - no retry");
					return false;
				}
				if (exception instanceof java.net.SocketTimeoutException) {
					// Retry on socket timeout exception
					System.out.println(getTimeStamp() +"java.net.SocketTimeoutException exception- for series" + seriesInstanceUid  +"--attempt" + executionCount);
					additionalInfo.append(getTimeStamp() + " Request Handler attempt").append(executionCount).append(" for SocketTimeOutException \n");
					letSleep(executionCount);
					System.out.println(getTimeStamp() +" After coming out from sleep for series " + seriesInstanceUid +" @ attempt" + executionCount);
					return true;
				}
				if (exception instanceof java.net.SocketException) {
					// Retry on socket timeout exception
					System.out.println(getTimeStamp() + "java.net.SocketException - for series" + seriesInstanceUid +"--attempt" + executionCount);
					additionalInfo.append(getTimeStamp() +" Request Handler attempt").append(executionCount) .append(" for SocketException \n");
					letSleep(executionCount);
					System.out.println(getTimeStamp() +"After coming out from sleep for series " + seriesInstanceUid +" @ attempt" + executionCount);
					return true;
				}
				HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
				boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
				if (idempotent) {
					System.out.println("idempotent exception - Retry");
					// Retry if the request is considered idempotent
					return true;
				}
				return false;
			}
		};
		httpClient.setHttpRequestRetryHandler(myRetryHandler);
		UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
		httpPostMethod.setEntity(query);

		/* Connect to server. */
		try {
			HttpResponse response = httpClient.execute(httpPostMethod);
			int responseCode = response.getStatusLine().getStatusCode();
			System.out.println(getTimeStamp() +" response code: " + responseCode + "for the seriers " + this.seriesInstanceUid + "--attempt--"+ attempt);

			/* Make sure response code is in the 200 range. */
			if (responseCode / 100 != 2) {
				// additionalInfo.append("incorrect response code");
				System.out.println(getTimeStamp() +" for the seriers "+ this.seriesInstanceUid +" incorrect response code received "
						+"--attempt" + attempt);
				additionalInfo.append(getTimeStamp() + " retry attempt").append(attempt + 1).append("for incorrect response code \n");
				httpClient.getConnectionManager().shutdown();

				//it could be caused by the exclusion list is large than 1000 and result in sql execution error.
				if ( this.sopUidsList.size()>= 1000) {
					System.out.println(getTimeStamp() +" for the seriers "+ this.seriesInstanceUid +" exclusion list size="+ this.sopUidsList.size()+ " so redo whole series");
					additionalInfo.append(getTimeStamp() + "redo whole series because server internal error.");
					this.sopUidsList.clear();
					this.sopUids="";
					this.downloaded = 0;
					this.progressUpdater.bytesCopied(0);
				}
				connectAndReadFromURL(url, attempt + 1);
			}

			/*
			 * Set the size for this download if it hasn't been already set.
			 */
			if (size == -1) {
				System.out.println("no data found for the series");
				status = NO_DATA;
				stateChanged();
			}
			readFromConnection(response.getEntity().getContent());
		} catch (javax.net.ssl.SSLPeerUnverifiedException e) {
			// exclude downloading already download image.
			this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);
			System.out.println(getTimeStamp() +" SSLPeerUnverifiedException-- for series "+this.seriesInstanceUid +" @ attempt--"+ attempt);
			e.printStackTrace();
			additionalInfo.append(getTimeStamp() +" image retry attempt ").append(attempt + 1).append(" for SSLPeer Unverified Exception \n");
			connectAndReadFromURL(url, attempt + 1);
		} catch (SocketTimeoutException e) {
			// exclude downloading already download image.
			this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);
			System.out.println(getTimeStamp() +" SocketTimeoutException-- for series " + this.seriesInstanceUid +" @ attempt--"+ attempt);
			e.printStackTrace();
			additionalInfo.append(getTimeStamp() +" image retry attempt ").append(attempt + 1).append(" for Socket timeout exception \n");
			connectAndReadFromURL(url, attempt + 1);
		} catch (SocketException e) {
			// exclude downloading already download image.
			this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);
			System.out.println(getTimeStamp() +" SocketException-- for series " + this.seriesInstanceUid + " @ attempt--"+ attempt);
			e.printStackTrace();
			additionalInfo.append(getTimeStamp() +" image retry attempt ").append(attempt + 1).append(" for Socket exception \n");
			connectAndReadFromURL(url, attempt + 1);
		} catch (org.apache.http.MalformedChunkCodingException e) {
			// exclude downloading already download image.
			this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);
			System.out.println(getTimeStamp() +" MalformedChunkCodingException-- for series " + this.seriesInstanceUid +" @ attempt--"+ attempt);
			e.printStackTrace();
			additionalInfo.append(getTimeStamp() +" image retry attempt ").append(attempt + 1).append(" for MalformedChunkCodingException \n");
			connectAndReadFromURL(url, attempt + 1);
		} catch (Exception e) {
			if ((e instanceof java.net.SocketTimeoutException) || (e instanceof java.io.IOException)){
				// exclude downloading already download image.
				this.sopUids = StringUtil.encodeListEntriesWithSingleQuotes(this.sopUidsList);
				System.out.println(getTimeStamp() +" java.net.SocketTimeoutException-- for series"+this.seriesInstanceUid  + "@ attempt--"+ attempt);
				e.printStackTrace();
				additionalInfo.append(getTimeStamp() +" image retry attempt").append(attempt + 1).append(" for Socket timeout exception \n");
				connectAndReadFromURL(url, attempt + 1);
			}
			else {
				System.out.println(getTimeStamp() +"!!!!! cought exception for series "+ this.seriesInstanceUid +" @attempt--"+ attempt);
				e.printStackTrace();
			}
		}

		finally {
			httpClient.getConnectionManager().shutdown();
		}
		System.out.println("Leaving connectAndReadFromURL.........for " + this.seriesInstanceUid +" @ attempt " + attempt);
	}

	private void readFromConnection(InputStream is) throws Exception {
		String location = createDirectory();

		TarArchiveInputStream zis = new TarArchiveInputStream(is);

		int imageCnt = 0;
		// Begin lrt additions
		imageCnt = sopUidsList.size(); // needed for pause/resume, and for error
										// recovery
		int downloadedImgSize = 0;
		int downloadedAnnoSize = 0;
		// End lrt additions
		try {
			// the pause button affects this loop
			// per tar entry, will check status... which pause button could
			// change... then we will drop out of downloading.
			while (status == DOWNLOADING) {
				TarArchiveEntry tarArchiveEntry = zis.getNextTarEntry();
				if (tarArchiveEntry == null) {
					System.out.println(this.seriesInstanceUid
							+ " reaching end of file");
					status = COMPLETE;
					break;
				}
				// Begin lrt additions
				long fileSize = tarArchiveEntry.getSize();
				int startDownloaded = downloaded;
				// End lrt additions
				String sop = tarArchiveEntry.getName();
				int pos = sop.indexOf(".dcm");
				OutputStream outputStream = null;
				if (pos > 0) {
					// sopUidsList.add(sop.substring(0, pos)); - lrt moved to
					// below, after file size check
					outputStream = new FileOutputStream(location + File.separator + StringUtil.displayAsSixDigitString(imageCnt) + ".dcm");
				} else {
					outputStream = new FileOutputStream(location + File.separator + sop);
				}

				try {
					NBIAIOUtils.copy(zis, outputStream, progressUpdater);
				}
				finally {
					outputStream.flush();
					outputStream.close();
				}

				imageCnt += 1;
				// Begin lrt additions
				int bytesDownloaded = downloaded - startDownloaded;
				if (bytesDownloaded != fileSize) {
					additionalInfo.append(" file size mismatch for instance " + sop + "\n");
					System.out.println(this.seriesInstanceUid + additionalInfo);
					error();
				} else {
					if (pos > 0) { // image file
						downloadedImgSize += bytesDownloaded;
						sopUidsList.add(sop.substring(0, pos));
					} else { // annotation file
						downloadedAnnoSize += bytesDownloaded;
					}
				}
				// End lrt additions
			}
		} finally {
			org.apache.commons.io.IOUtils.closeQuietly(zis);
		}
		// Begin lrt additions
		if (status == COMPLETE) {
			if (sopUidsList.size() != Integer.valueOf(numberOfImages).intValue()) {
				additionalInfo
						.append("Number of image files mismatch. It Was supposed to be " + numberOfImages
								+ " image files but we found " + sopUidsList.size() + " at server side\n");
				System.out.println(this.seriesInstanceUid + additionalInfo);
				error();
			}
			if (downloadedImgSize != imagesSize) {
				System.out.println(this.seriesInstanceUid + " total size of image files mismatch.  Was " + downloadedImgSize+" should be "+imagesSize);
			}
			if (downloadedAnnoSize != annoSize) {
				System.out.println( this.seriesInstanceUid + " total size of annotation files mismatch.  Was " +downloadedAnnoSize+" should be "+annoSize+"\n");
			}
			/*
			 * Cannot use this sanity check, since image sizes are not always
			 * recorded correct in NBIA 5.0 - lrt else if (downloadedImgSize !=
			 * imagesSize) { System.out.println(this.seriesInstanceUid+
			 * " total size of image files mismatch.  Was "
			 * +downloadedImgSize+" should be "+imagesSize); error(); }
			 *
			 * else if (downloadedAnnoSize != annoSize) { additionalInfo.append(
			 * " total size of annotation files mismatch.  Was "
			 * +downloadedAnnoSize+" should be "+annoSize+"\n");
			 * System.out.println(this.seriesInstanceUid + additionalInfo);
			 * error(); }
			 */
		}
		// End lrt additions
	}

	// static {
	// Protocol.registerProtocol("https",
	// new Protocol("https",
	// new EasySSLProtocolSocketFactory(),
	// 443));
	// }

}


text:
/* eslint-disable no-unused-expressions */
const expect = require('chai').expect
const sinon = require('sinon')
const core = require('.')

describe('Store', () => {
  const album = [{ frequency: 3, title: 'test' }]

  let Store
  let isAlbum
  let store
  let callback

  beforeEach(() => {
    isAlbum = sinon.stub()
    isAlbum.returns(true)

    Store = core({ isAlbum })

    store = new Store()
    callback = sinon.spy()
  })

  describe('core', () => {
    describe('without isAlbum dependency', () => {
      it('should throw an error', () => {
        expect(core.bind(core, {})).to.throw('isAlbum dependency is missing')
      })
    })

    describe('with isAlbum dependency', () => {
      it('should return the Store class', () => {
        expect(core({ isAlbum })).to.be.a('function')
      })
    })
  })

  describe('constructor', () => {
    it('should create a new Store', () => {
      expect(store).to.be.an.instanceof(Store)
      expect(store.read).to.be.a('function')
      expect(store.readOneById).to.be.a('function')
      expect(store.createOne).to.be.a('function')
      expect(store.albums).to.be.an.instanceof(Array)
      expect(store.albums).to.have.lengthOf(0)
    })
  })

  describe('read', () => {
    it('should call the callback with the albums array', () => {
      store.read(callback)
      expect(callback.calledOnce).to.be.true
      expect(callback.calledWithExactly(null, [])).to.be.true
    })
  })

  describe('readOneById', () => {
    describe('with invalid id', () => {
      it('should call the callback with an error object', () => {
        store.readOneById(2, callback)
        store.readOneById(0, callback)
        store.readOneById(-1, callback)
        store.readOneById(undefined, callback)
        store.readOneById(null, callback)
        store.readOneById({}, callback)
        store.readOneById('test', callback)
        expect(callback.callCount).to.equal(7)
        expect(callback.alwaysCalledWithExactly({ err: 'invalid id' })).to.be.true
      })
    })

    describe('with valid id', () => {
      beforeEach(() => {
        store.createOne(album, () => {})
      })

      it('should call the callback with the album object', () => {
        store.readOneById(0, callback)
        expect(callback.calledOnce).to.be.true
        expect(callback.calledWithExactly(null, { id: 0, songs: album })).to.be.true
      })
    })
  })

  describe('createOne', () => {
    describe('with valid album array', () => {
      beforeEach(() => {
        store.createOne([], callback)
      })

      it('should passes the array to the album validator', () => {
        expect(isAlbum.calledOnce).to.be.true
        expect(isAlbum.calledWithExactly([])).to.be.true
      })

      it('should push the created album object to the albums array', () => {
        expect(store.albums).to.include({ id: 0, songs: [] })
      })

      it('should call the callback with the created album object', () => {
        expect(callback.calledOnce).to.be.true
        expect(callback.calledWithExactly(null, { id: 0 })).to.be.true
      })
    })

    describe('with invalid album array', () => {
      beforeEach(() => {
        isAlbum.returns(false)
        Store = core({ isAlbum })
        store = new Store()

        store.createOne([], callback)
      })

      it('should NOT push the created album to the albums array', () => {
        expect(store.albums).to.not.include({ id: 0, songs: [] })
      })

      it('should call the callback with an error object', () => {
        expect(callback.calledOnce).to.be.true
        expect(callback.calledWithExactly({ err: 'invalid data format' })).to.be.true
      })
    })
  })

  describe('create', () => {
    it('should return a new Store', () => {
      expect(Store.create).be.a('function')
      expect(Store.create()).to.be.an.instanceof(Store)
    })
  })
})


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 Actor LLC. <https://actor.im>
  -->

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="@color/selector_selected" />
        </shape>
    </item>
    <item android:state_selected="true">
        <shape android:shape="oval">
            <solid android:color="@color/selector_selected" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="oval">
            <solid android:color="@color/selector_hover" />
        </shape>
    </item>
    <item android:state_hovered="true">
        <shape android:shape="oval">
            <solid android:color="@color/selector_hover" />
        </shape>
    </item>
</selector>


text:
<img src="https://raw.githubusercontent.com/StfBauer/sp.wikitoc/master/sp.wikitoc.png" width="250" alt="SharePoint Table of Contents" style="float: left;">

jQuery extension to enhance SharePoint Wiki and publishing pages with an table of contents.

For now check out some blog posts about this plugin:

* [Revised: Table of contents for SharePoint wiki pages](http://www.n8d.at/blog/revised-table-of-contents-for-wiki-pages/)
* [How to use: Table of Contents jQuery plugin](http://www.n8d.at/blog/how-to-use-table-of-content-jquery-plugin/) - the file names have been changed in this version. Instead of sp.tableofcotents

# Global Dependencies
You must have node installed to build new minified versions of JavaScript, SASS or CSS files.
If you don't have node installed yet grab it now: [node.js
](https://nodejs.org/en/)

# Project Setup
If you have git installed you can clone this repository.

```
// Clone this repository
git git@github.com:StfBauer/sp.wiki.toc.git

// Change to the project directory
cd sp.wiki.toc

// Install all node packages to build
npm install
```

If you like to build a new minified version of the javascript and css files simply run the following command.
```
gulp dist
```
You will find the minified version in the folder ```/dist/```

# License
The MIT License (MIT)

Copyright (c) 2015 [@stfbauer](http://twitter.com/stfbauer)

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.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.parse.http Class Hierarchy (Parse 1.10.3 API)</title>
<meta name="date" content="2015-10-09">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.parse.http

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.parse.http.ParseHttpBody

com.parse.http.ParseHttpRequest

com.parse.http.ParseHttpRequest.Builder

com.parse.http.ParseHttpResponse

com.parse.http.ParseHttpResponse.Builder

Interface Hierarchy

com.parse.http.ParseNetworkInterceptor

com.parse.http.ParseNetworkInterceptor.Chain

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

com.parse.http.ParseHttpRequest.Method

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package hk.microos.tools;

import java.awt.BasicStroke;
import java.awt.geom.Ellipse2D;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import hk.microos.data.Ellipse;
import hk.microos.data.Flags;
import hk.microos.data.MyImage;
import hk.microos.data.Point_;
import hk.microos.frames.MainFrame;

public class UniversalTool {
	private UniversalTool(){}
	public static boolean inBound(double minX, double minY, double maxX, double maxY, int x, int y) {
		// System.out.format("inBound: %d %d %d %d\tXY: %d %d\n",
		// minX,minY,maxX,maxY,x,y);
		return (minX <= x && x <= maxX) && (minY <= y && y <= maxY);
	}
	public static Ellipse getTestEllipse(int f){
		double x = 100;
		double y = 100;
		Point_ mjA = new Point_(0*f+x,0*f+y);
		Point_ mjB = new Point_(8.66025403784*f+x,5*f+y);
		Point_ miC = new Point_(2.88675134595*f+x,5*f+y);
		Ellipse e = new Ellipse(mjA, mjB, miC);
		return e;
	}
	public static Ellipse2D.Double getPointOval(Point_ p, double pointWidth){
		double x = p.x; double y = p.y;
		return new Ellipse2D.Double(x-pointWidth/2, y-pointWidth/2, pointWidth, pointWidth);
	}
	public static Ellipse2D.Double getPointOval(double x, double y, double pointWidth){
		return new Ellipse2D.Double(x-pointWidth/2, y-pointWidth/2, pointWidth, pointWidth);
	}
	public static ArrayList<Double> rootQudratic(double a, double b, double c) {
		double m = b*b - 4*a*c;
		if(m>=0){
			ArrayList<Double> ret = new ArrayList<Double>();
			double r1 = (-1*b-Math.sqrt(m))/(2*a);
			double r2 = (-1*b+Math.sqrt(m))/(2*a);
			ret.add(r1);
			ret.add(r2);
			return ret;
		}else{
			System.out.println("no root!");
			return null;
		}
	}
	public static Point_ midPoint(Point_ a, Point_ b){
		return new Point_((a.x+b.x)/2, (a.y+b.y)/2);
	}
	public static double distance(Point_ a, Point_ b){
		double A2 = (a.x - b.x)*(a.x - b.x);
		double B2 = (a.y - b.y)*(a.y - b.y);
		return Math.sqrt(A2+B2);
	}

	public static boolean inBound(Point_ p, double minX, double minY, double maxX, double maxY){
		double x = p.x;
		double y = p.y;
		if( (x>=minX && x<=maxX) && (y>=minY && y<maxY)){
			return true;
		}else{
			return false;
		}

	}
	public static Point_ getInboundPoint(Point_ p, int minX, int minY, int maxX, int maxY){
		double px = p.x;
		double py = p.y;
		px = px>maxX? maxX:px;
		px = px<minX? minX:px;
		py = py>maxY? maxY:py;
		py = py<minY? minY:py;
		return new Point_(px,py);
	}
	public static BasicStroke getPreferableStroke(double distance){

		double factor = 0.03;
		double s = distance * factor;
		s = Math.min(Flags.maxStroke, s);
		s = Math.max(Flags.minStroke, s);
//		System.out.format("Distance:%.4f; S_:%s S:%s\n",distance, distance * factor, s);
		return new BasicStroke((float)s);
	}
	public static Point_ getSymmetricPoint(Point_ center, Point_ A){
		double cx = center.x;
		double cy = center.y;
		double ax = A.x;
		double ay = A.y;
		return new Point_(2*cx-ax,2*cy-ay);
	}
	public static double Pythagorean(double A, double B){
		return Math.sqrt(Math.pow(A, 2)+Math.pow(B, 2));
	}
	public static void printArray(Iterable<String> lst){
		int i = 0;
		for(String s: lst){
			System.out.println(i+": "+s);
			i++;
		}
	}
	public static String[] getPrefixAndName(String s){
		String[] sa = s.split("/");
//		System.out.println("input string "+s);
//		for(String t: sa){
//			System.out.println("\t"+t);
//		}
		String[] prefix = Arrays.copyOfRange(sa, 0, sa.length-1);
		String name = sa[sa.length-1];
		String pref = String.join("/",prefix);
		String[] ret = new String[2];
		ret[0] = pref;
		ret[1] = name;
		return ret;
	}
	public static double[] getOffset(MyImage mImg){
		double[] ret = new double[4];
		ret[0] = (mImg.w() < MainFrame.defaultScrollW) ? (MainFrame.defaultScrollW - mImg.w()) / 2 : 0;
		ret[1] = (mImg.h() < MainFrame.defaultScrollH) ? (MainFrame.defaultScrollH - mImg.h()) / 2 : 0;
		ret[2] = ret[0] + mImg.w();
		ret[3] = ret[1] + mImg.h();
		return ret;
	}
	public static MyImage getMyImageFromPathImgPair(String path, HashMap<String, MyImage> pathImgPair) {
		MyImage img = pathImgPair.get(path);
		if (img == null) {
			File f = new File(path);
			img = new MyImage(f);
			pathImgPair.put(path, img);
			return img;
		} else {
			return img;
		}
	}
}


text:
angular.module('Index')
    .controller('TestController', TestController);

TestController.$inject = ['testsService', 'socketService', '$location', 'userService', '$scope', '$timeout'];

function TestController (testService, socketService, $location, userService, $scope, $timeout) {
    var testController = this;

    testController.questions = [];
    testController.currentIndex = 0;
    socketService.delegate = testController;

    testController.minutes = 0;
    testController.seconds = 0;
    testController.onTimeout = function(){
        if(testController.seconds == 0 && testController.minutes == 0) {
            return;
        }
        if(testController.seconds == 0 && testController.minutes > 0) {
            testController.seconds = 59;
            testController.minutes--;
        } else {
            testController.seconds--;
        }
        //testController.seconds--;
        //if(testController.seconds == 59) {
        //    if(testController.minutes > 0) {
        //        testController.minutes--;
        //    }
        //}
        mytimeout = $timeout(testController.onTimeout,1000);
    };
    var mytimeout = $timeout(testController.onTimeout,1000);

    socketService.establishConnectionToSocket(function (socket) {
        socketService.startTest(testService.getCurrentTest());
    }, function (err) {

    });

    testController.showNextQuestion = function () {
        if(testController.currentIndex != (testController.questions.length - 1)) {
            testController.sendAnswerToCurrentQuestion();
            testController.downloadImageIfNeeded();
            ++testController.currentIndex;
        }
    };

    testController.showPreviousQuestion = function () {
        if(testController.currentIndex != 0) {
            testController.sendAnswerToCurrentQuestion();
            testController.downloadImageIfNeeded();
            --testController.currentIndex;
        }
    };

    testController.finishTest = function () {
        testController.sendAnswerToCurrentQuestion();
        socketService.finishTest();
    };

    testController.onTestStarted = function (socket, msg) {
        $scope.$apply(function(){
            testController.questions = msg.questions;
            for(var i = 0; i < testController.questions[i]; ++i) {
                testController.questions[i].answer = {
                    previous : ''
                };
            }
            testController.minutes = msg.minutes;
            testController.seconds = msg.seconds;
        });
        socketService.getImage(testController.questions[testController.currentIndex].idQuestion);
    };

    testController.onImageReceived = function (socket, msg) {
        $scope.$apply(function(){

            //setting of image data source property to certain question
            for(var i = 0; i < testController.questions.length; ++i) {
                if (testController.questions[i].idQuestion == msg.idQuestion) {
                    testController.questions[i].imageData = 'images/' + msg.image;
                }
            }
        });
    };

    testController.onTestFinished = function (socket, msg) {
        $scope.$apply(function(){
            $location.path('/result');
        });
    };

    testController.downloadImageIfNeeded = function () {
        if(testController.questions[testController.currentIndex].imageData == undefined) {
            socketService.getImage(testController.questions[testController.currentIndex].idQuestion);
        }
    };

    testController.sendAnswerToCurrentQuestion = function () {

        var question = testController.questions[testController.currentIndex];
        if (question.answer == undefined || question.answer.answerRequest == undefined) {
            return;
        }
        if(testController.questions[testController.currentIndex].answer.answerRequest.length < 1) {
            return;
        }

        //storing of previous request helps to reduce count of requests to server
        if(question.answer.previous == question.answer.answerRequest) {
            return;
        } else {
            question.answer.previous = question.answer.answerRequest;
        }
        testController.questions[testController.currentIndex].answer = {
            idUser: userService.getUserProfile().idUser,
            answerRequest: testController.questions[testController.currentIndex].answer.answerRequest,
            idTestHasQuestion: testController.questions[testController.currentIndex].idTestHasQuestion,
            previous : testController.questions[testController.currentIndex].answer.answerRequest
        };
        socketService.sendAnswer(testController.questions[testController.currentIndex].answer);

    }

}


text:
Rem
Rem $Header: rdbms/demo/schema/sales_history/sh_olp_c.sql /main/6 2011/12/10 19:37:28 mstasiew Exp $
Rem
Rem sh_olp_c.sql
Rem
Rem Copyright (c) 2001, 2015, Oracle and/or its affiliates.  All rights reserved.
Rem
Rem Permission is hereby granted, free of charge, to any person obtaining
Rem a copy of this software and associated documentation files (the
Rem "Software"), to deal in the Software without restriction, including
Rem without limitation the rights to use, copy, modify, merge, publish,
Rem distribute, sublicense, and/or sell copies of the Software, and to
Rem permit persons to whom the Software is furnished to do so, subject to
Rem the following conditions:
Rem
Rem The above copyright notice and this permission notice shall be
Rem included in all copies or substantial portions of the Software.
Rem
Rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
Rem EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
Rem MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
Rem NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
Rem LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
Rem OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
Rem WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Rem
Rem    NAME
Rem      sh_olp_c.sql - Create columns used by OLAP Server
Rem
Rem    DESCRIPTION
Rem      SH is the Sales History schema of the Oracle 9i Sample
Rem	   Schemas
Rem
Rem    NOTES
Rem
Rem
Rem    MODIFIED   (MM/DD/YY)
Rem      mstasiew  10/19/11 - deprecate cwm, undo ramekuma 10/13/11 change.
Rem                           Since cwm portions are removed, turn back on
Rem                           add column optimization
rem      ramekuma  10/13/11 - lrg-5729910: Turn off add column optimization for
rem                           CWM lite
rem      hyeh      08/29/02 - hyeh_mv_comschema_to_rdbms
rem      ahunold   03/16/02 - fweek_pscat_sales_mv COMPILE
rem      ahunold   09/17/01 - sh_analz.sql
rem      ahunold   05/10/01 - Time dimension attributes
rem      pfay      04/10/01 - change case
Rem      ahunold   04/05/01 - dimension names
Rem      ahunold   03/05/01 - external table, no DROPs
Rem      ahunold   02/07/01 - CMWLite
Rem      ahunold   02/01/01 - Merged ahunold_two_facts
Rem      hbaer     01/29/01 - Created
Rem

ALTER TABLE products
	ADD prod_total VARCHAR2(13)
	DEFAULT 'Product total';

ALTER TABLE customers
	ADD cust_total VARCHAR2(14)
	DEFAULT 'Customer total';

ALTER TABLE promotions
	ADD promo_total VARCHAR2(15)
	DEFAULT 'Promotion total';

ALTER TABLE channels
	ADD channel_total VARCHAR2(13)
	DEFAULT 'Channel total';

ALTER TABLE countries
	ADD country_total VARCHAR2(11)
	DEFAULT 'World total';

COMMIT;

Rem modified dimension definition to include new total column

DROP DIMENSION times_dim;

CREATE DIMENSION times_dim
   LEVEL day         IS TIMES.TIME_ID
   LEVEL month       IS TIMES.CALENDAR_MONTH_DESC
   LEVEL quarter     IS TIMES.CALENDAR_QUARTER_DESC
   LEVEL year        IS TIMES.CALENDAR_YEAR
   LEVEL fis_week    IS TIMES.WEEK_ENDING_DAY
   LEVEL fis_month   IS TIMES.FISCAL_MONTH_DESC
   LEVEL fis_quarter IS TIMES.FISCAL_QUARTER_DESC
   LEVEL fis_year    IS TIMES.FISCAL_YEAR
   HIERARCHY cal_rollup    (
             day     CHILD OF
             month   CHILD OF
             quarter CHILD OF
             year
   )
   HIERARCHY fis_rollup    (
             day         CHILD OF
             fis_week    CHILD OF
             fis_month	 CHILD OF
             fis_quarter CHILD OF
             fis_year
   )
   ATTRIBUTE day DETERMINES
	(day_number_in_week, day_name, day_number_in_month,
         calendar_week_number)
   ATTRIBUTE month DETERMINES
	(calendar_month_desc,
         calendar_month_number, calendar_month_name,
         days_in_cal_month, end_of_cal_month)
   ATTRIBUTE quarter DETERMINES
	(calendar_quarter_desc,
         calendar_quarter_number,days_in_cal_quarter,
	 end_of_cal_quarter)
   ATTRIBUTE year DETERMINES
	(calendar_year,
         days_in_cal_year, end_of_cal_year)
   ATTRIBUTE fis_week DETERMINES
	(week_ending_day,
         fiscal_week_number)
   ATTRIBUTE fis_month DETERMINES
	(fiscal_month_desc, fiscal_month_number, fiscal_month_name,
	 days_in_fis_month, end_of_fis_month)
   ATTRIBUTE fis_quarter DETERMINES
	(fiscal_quarter_desc,
         fiscal_quarter_number, days_in_fis_quarter,
	 end_of_fis_quarter)
   ATTRIBUTE fis_year DETERMINES
	(fiscal_year,
         days_in_fis_year, end_of_fis_year)
;

DROP DIMENSION customers_dim;

CREATE DIMENSION customers_dim
	LEVEL customer	IS (customers.cust_id)
	LEVEL city 	IS (customers.cust_city)
	LEVEL state 	IS (customers.cust_state_province)
	LEVEL country 	IS (countries.country_id)
	LEVEL subregion IS (countries.country_subregion)
	LEVEL region IS (countries.country_region)
	LEVEL geog_total IS (countries.country_total)
	LEVEL cust_total IS (customers.cust_total)
	HIERARCHY cust_rollup (
		customer	CHILD OF
		city 		CHILD OF
		state 		CHILD OF
                cust_total
	)
	HIERARCHY geog_rollup (
		customer	CHILD OF
		city 		CHILD OF
		state 		CHILD OF
		country 	CHILD OF
		subregion 	CHILD OF
		region          CHILD OF
                geog_total
	JOIN KEY (customers.country_id) REFERENCES country
	)
	ATTRIBUTE customer DETERMINES
	(cust_first_name, cust_last_name, cust_gender,
	 cust_marital_status, cust_year_of_birth,
	 cust_income_level, cust_credit_limit,
         cust_street_address, cust_postal_code,
         cust_main_phone_number, cust_email)
        ATTRIBUTE city DETERMINES (cust_city)
        ATTRIBUTE state DETERMINES (cust_state_province)
	ATTRIBUTE country DETERMINES (countries.country_name)
        ATTRIBUTE subregion DETERMINES (countries.country_subregion)
        ATTRIBUTE region DETERMINES (countries.country_region)
        ATTRIBUTE geog_total DETERMINES (countries.country_total)
        ATTRIBUTE cust_total DETERMINES (customers.cust_total)
;

DROP DIMENSION products_dim;

CREATE DIMENSION products_dim
	LEVEL product 		IS (products.prod_id)
 	LEVEL subcategory 	IS (products.prod_subcategory)
	LEVEL category		IS (products.prod_category)
	LEVEL prod_total	IS (products.prod_total)
	HIERARCHY prod_rollup (
		product		CHILD OF
		subcategory 	CHILD OF
		category        CHILD OF
   		prod_total
	)
	ATTRIBUTE product DETERMINES
        (products.prod_name, products.prod_desc,
         prod_weight_class, prod_unit_of_measure,
         prod_pack_size,prod_status, prod_list_price, prod_min_price)
	ATTRIBUTE subcategory DETERMINES
        (prod_subcategory, prod_subcat_desc)
	ATTRIBUTE category DETERMINES
        (prod_category, prod_cat_desc)
	ATTRIBUTE prod_total DETERMINES
        (prod_total)
;

DROP DIMENSION promotions_dim;

CREATE DIMENSION promotions_dim
	LEVEL promo 	  IS (promotions.promo_id)
	LEVEL subcategory IS (promotions.promo_subcategory)
	LEVEL category 	  IS (promotions.promo_category)
	LEVEL promo_total IS (promotions.promo_total)
	HIERARCHY promo_rollup (
		promo 		CHILD OF
		subcategory 	CHILD OF
		category	CHILD OF
		promo_total
	)
	ATTRIBUTE promo DETERMINES
        (promo_name, promo_cost,
         promo_begin_date, promo_end_date)
        ATTRIBUTE subcategory DETERMINES (promo_subcategory)
        ATTRIBUTE category DETERMINES (promo_category)
        ATTRIBUTE promo_total DETERMINES (promo_total)
;

DROP DIMENSION channels_dim;

CREATE DIMENSION channels_dim
	LEVEL channel 	   IS (channels.channel_id)
	LEVEL channel_class IS (channels.channel_class)
	LEVEL channel_total IS (channels.channel_total)
	HIERARCHY channel_rollup (
		channel		CHILD OF
		channel_class	CHILD OF
		channel_total
	)
        ATTRIBUTE channel DETERMINES (channel_desc)
        ATTRIBUTE channel_class DETERMINES (channel_class)
        ATTRIBUTE channel_total DETERMINES (channel_total)
;

set serveroutput on size 99999

COMMIT;

-- ------------------- Statistics ---------------------------

ALTER MATERIALIZED VIEW fweek_pscat_sales_mv COMPILE;
@__SUB__CWD__/sales_history/sh_analz.sql


text:
ALTER TABLE PROTOCOL_REVIEWERS ADD ( ROLODEX_ID NUMBER(12,0) NULL );
ALTER TABLE PROTOCOL_REVIEWERS MODIFY ( PERSON_ID VARCHAR2(40) NULL );

UPDATE PROTOCOL_REVIEWERS SET ROLODEX_ID=PERSON_ID, PERSON_ID = NULL WHERE NON_EMPLOYEE_FLAG = 'Y';

ALTER TABLE PROTOCOL_REVIEWERS
    ADD ( CONSTRAINT FK_PROTOCOL_REVIEWERS5
	FOREIGN KEY(ROLODEX_ID)
	REFERENCES ROLODEX(ROLODEX_ID)
	NOT DEFERRABLE INITIALLY IMMEDIATE VALIDATE );

SELECT * FROM PROTOCOL_REVIEWERS;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>HeimdalKerberos5library: The keytab handing functions</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Modules

Data Structures

The keytab handing functions

Kerberos Keytabs

See the library functions here: Heimdal Kerberos 5 keytab handling functions

Keytabs are long term key storage for servers, their equvalment of password files.

Normally the only function that useful for server are to specify what keytab to use to other core functions like krb5_rd_req() krb5_kt_resolve(), and krb5_kt_close().

Keytab names

A keytab name is on the form type:residual. The residual part is specific to each keytab-type.

When a keytab-name is resolved, the type is matched with an internal list of keytab types. If there is no matching keytab type, the default keytab is used. The current default type is FILE.

The default value can be changed in the configuration file /etc/krb5.conf by setting the variable [defaults]default_keytab_name.

The keytab types that are implemented in Heimdal are:

file store the keytab in a file, the type's name is FILE . The residual part is a filename. For compatibility with other Kerberos implemtation WRFILE and JAVA14 is also accepted. WRFILE has the same format as FILE. JAVA14 have a format that is compatible with older versions of MIT kerberos and SUN's Java based installation. They store a truncted kvno, so when the knvo excess 255, they are truncted in this format.

keytab store the keytab in a AFS keyfile (usually /usr/afs/etc/KeyFile ), the type's name is AFSKEYFILE. The residual part is a filename.

memory The keytab is stored in a memory segment. This allows sensitive and/or temporary data not to be stored on disk. The type's name is MEMORY. Each MEMORY keytab is referenced counted by and opened by the residual name, so two handles can point to the same memory area. When the last user closes using krb5_kt_close() the keytab, the keys in they keytab is memset() to zero and freed and can no longer be looked up by name.

Keytab example

This is a minimalistic version of ktutil.

int
main (int argc, char **argv)
{
    krb5_context context;
    krb5_keytab keytab;
    krb5_kt_cursor cursor;
    krb5_keytab_entry entry;
    krb5_error_code ret;
    char *principal;

    if (krb5_init_context (&context) != 0)
        errx(1, "krb5_context");

    ret = krb5_kt_default (context, &keytab);
    if (ret)
        krb5_err(context, 1, ret, "krb5_kt_default");

    ret = krb5_kt_start_seq_get(context, keytab, &cursor);
    if (ret)
        krb5_err(context, 1, ret, "krb5_kt_start_seq_get");
    while((ret = krb5_kt_next_entry(context, keytab, &entry, &cursor)) == 0){
        krb5_unparse_name(context, entry.principal, &principal);
        printf("principal: %s\n", principal);
        free(principal);
        krb5_kt_free_entry(context, &entry);
    }
    ret = krb5_kt_end_seq_get(context, keytab, &cursor);
    if (ret)
        krb5_err(context, 1, ret, "krb5_kt_end_seq_get");
    ret = krb5_kt_close(context, keytab);
    if (ret)
        krb5_err(context, 1, ret, "krb5_kt_close");
    krb5_free_context(context);
    return 0;
}

<address style="text-align: right;">
Generated on Wed Jan 11 14:07:47 2012 for HeimdalKerberos5library by  1.5.6</address>


text:
"use strict";
window.mushroom.state.play2 = {
	preload: function(){
		console.log("loading play2 state");
	},

	create: function(){
		console.log("starting play2 state");

		this.game.camera.x = 1800;
		this.redsea = mt.create("redsea");

		this.Pathway2 = mt.create("Pathway2");
		this.player=mt.create("weirdmushroom1");
		this.enemy=mt.create("evilmushroom1");
		this.enemy2=mt.create("evilmushroom2");
		this.coins2=mt.create("coins2");
		this.score=mt.create("score");
		this.timer1=mt.create("timer1");
		this.seconds = 0;
		this.timer1_count = 0;
		this.score_count = 0;

		this.Lkey = this.input.keyboard.addKey(Phaser.Keyboard.LEFT);
		this.Rkey = this.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
		this.Ukey = this.input.keyboard.addKey(Phaser.Keyboard.UP);
	},

	update: function(){
		//Increase time by one second
		this.timer1_count +=1;

		if(this.timer1_count == 60 ){
			this.seconds +=1;
			this.timer1.text = this.seconds;
			this.timer1_count = 0;
		}

		//this.game.physics.arcade.collide(this.player, this.pathway);
		this.game.physics.arcade.collide(this.player, this.Pathway2);
		this.game.physics.arcade.collide(this.player, this.enemy.self,this.restartGame, null, this);
		this.game.physics.arcade.collide(this.player, this.enemy2.self,this.restartGame, null, this);
		this.game.physics.arcade.overlap(this.player, this.coins2.self, this.destroyObject, null, this);

		this.game.camera.x = this.player.position.x - 400;
		this.game.camera.y = this.player.position.y - 300;

		if(this.enemy.body.position.y > 820){
			this.enemy.body.position.y = -100;

			this.enemy.body.position.x = 1800 + Math.random() * 1800;

			this.enemy.body.velocity.y = 0;
		}
		if(this.enemy2.body.position.y > 820){
			this.enemy2.body.position.y = -100;

			this.enemy2.body.position.x = 1800 + Math.random() * 1800;

			this.enemy2.body.velocity.y = 0;

		}

		if(this.Lkey.isDown){
			this.player.body.velocity.x -= 5;
		}

		else if(this.Rkey.isDown){
			this.player.body.velocity.x += 5;
		}
		else if (this.Ukey.isDown && this.player.body.touching.down ){
			this.player.body.velocity.y -=400;
		}
		else{
			this.player.body.velocity.x = 0;
		}
		/*if(this.score_count == 10){
			this.switchLevel();
		}*/
	},

	destroyObject: function(player,coin){
		this.score_count +=10;
		this.score.text = this.score_count;
		coin.destroy();
	},

	restartGame: function(){
		this.game.state.start("play2");
	},
		switchLevel: function(){
		this.game.state.start("play3");
	}
};


text:
Documentation on Microsoft Azure tools you may want to use during a data hackathon.

Please refer to the doc folder for additional docs


text:
var searchData=
[
  ['scatter_20plot',['Scatter Plot',['../scatterscreenshots.html',1,'']]],
  ['spectrogram_2c_20contour_20plot',['Spectrogram, Contour Plot',['../spectrogramscreenshots.html',1,'']]]
];


text:
class <%= migration_name %> < ActiveRecord::Migration
  def self.up
    create_table "<%= table_name %>", :force => true do |t|
      t.column :login,                     :string, :limit => 40
      t.column :name,                      :string, :limit => 100, :default => '', :null => true
      t.column :email,                     :string, :limit => 100
      t.column :crypted_password,          :string, :limit => 40
      t.column :salt,                      :string, :limit => 40
      t.column :created_at,                :datetime
      t.column :updated_at,                :datetime
      t.column :remember_token,            :string, :limit => 40
      t.column :remember_token_expires_at, :datetime
<% if options[:include_activation] -%>
      t.column :activation_code,           :string, :limit => 40
      t.column :activated_at,              :datetime<% end %>
<% for attribute in attributes -%>
      t.<%= attribute.type %> :<%= attribute.name %>
<% end -%>
    end
    add_index :<%= table_name %>, :login, :unique => true
  end

  def self.down
    drop_table "<%= table_name %>"
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="AppCompatResource">

    <item
        android:id="@+id/action_search"
        android:orderInCategory="80"
        android:icon="@drawable/search"
        android:title="@string/settings"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_share"
        android:actionProviderClass="android.widget.ShareActionProvider"
        android:orderInCategory="90"
        android:icon="@drawable/share"
        android:title="@string/share"
        app:showAsAction="ifRoom" />

</menu>


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Query</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Fusion 2.2">
<link rel="up" href="../algorithm.html" title="Algorithm">
<link rel="prev" href="iteration/metafunctions/for_each.html" title="for_each">
<link rel="next" href="query/functions.html" title="Functions">

Home
Libraries
People
FAQ
More

Query

Functions

Metafunctions

        The query algorithms provide support for searching and analyzing sequences.

        Header

#include <boost/fusion/algorithm/query.hpp>
#include <boost/fusion/include/query.hpp>

Copyright © 2001-2006, 2011, 2012 Joel de Guzman,
      Dan Marsden, Tobias Schwinger

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.amazonaws.services.route53domains.model;

import java.io.Serializable;

/**
 *

 * The RetrieveDomainAuthCode response includes the following element.
 *

 */
public class RetrieveDomainAuthCodeResult implements Serializable, Cloneable {

    /**
     *

     * The authorization code for the domain.
     *

     *

     * Type: String
     *

     */
    private String authCode;

    /**
     *

     * The authorization code for the domain.
     *

     *

     * Type: String
     *

     *
     * @param authCode
     *        The authorization code for the domain.

     *

     *        Type: String
     */
    public void setAuthCode(String authCode) {
        this.authCode = authCode;
    }

    /**
     *

     * The authorization code for the domain.
     *

     *

     * Type: String
     *

     *
     * @return The authorization code for the domain.

     *

     *         Type: String
     */
    public String getAuthCode() {
        return this.authCode;
    }

    /**
     *

     * The authorization code for the domain.
     *

     *

     * Type: String
     *

     *
     * @param authCode
     *        The authorization code for the domain.

     *

     *        Type: String
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public RetrieveDomainAuthCodeResult withAuthCode(String authCode) {
        setAuthCode(authCode);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getAuthCode() != null)
            sb.append("AuthCode: " + getAuthCode());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof RetrieveDomainAuthCodeResult == false)
            return false;
        RetrieveDomainAuthCodeResult other = (RetrieveDomainAuthCodeResult) obj;
        if (other.getAuthCode() == null ^ this.getAuthCode() == null)
            return false;
        if (other.getAuthCode() != null
                && other.getAuthCode().equals(this.getAuthCode()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getAuthCode() == null) ? 0 : getAuthCode().hashCode());
        return hashCode;
    }

    @Override
    public RetrieveDomainAuthCodeResult clone() {
        try {
            return (RetrieveDomainAuthCodeResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
							Inicio

							Control de Existencias

<a href="<?php URL echo ?>materiales/">Materiales

					Registrar Un material

Materiales

											Id del Material
											Tipo de elemento
											Tipo de Embalaje
											Nombre del Material
											Fecha de Ingreso
											 Descripcion Material
											Aciones

									<?php
										foreach ($materiales as $key => $value) {
											# code...
										}

									 ?>

				<button type="button" class="close" data-dismiss="modal">×</button>

Registrar Material

							<form class="form-horizontal" action="<?php echo URL; ?>materiales/addMaterial" method="POST">
								<fieldset>

										Id del Material

											<input class="input-xlarge focused" id="focusedInput " name="id_Material" type="text" value="">

										Tipo de Elemento

											<input class="input-xlarge focused" id="focusedInput " name="tipo_Elemento" type="text" value="">

										Tipo de embalaje

											<select id="selectError " name="tipo_Embalaje" data-rel="chosen">
												<option>Option 1</option>
												<option>Option 2</option>
												<option>Option 3</option>
												<option>Option 4</option>
												<option>Option 5</option>
											</select>

										Marca

											<select id="selectError1 " name="marca" data-rel="chosen">
												<option>Option 1</option>
												<option>Option 2</option>
												<option>Option 3</option>
												<option>Option 4</option>
												<option>Option 5</option>
											</select>

										Asociar Proveedor

											<select id="selectError2 " name="proveedor" data-rel="chosen">
												<option>Option 1</option>
												<option>Option 2</option>
												<option>Option 3</option>
												<option>Option 4</option>
												<option>Option 5</option>
											</select>

										 Nombre del Material

											<input class="input-xlarge focused" id="focusedInput " name="nombre_material" type="text" value="">

										Fecha de Ingreso

											<input class="input-xlarge focused" id="focusedInput " name="fecha_Ingreso" type="date" value="">

										Descripcion del Material

											<input class="input-xlarge focused" id="focusedInput  " name="descripcion" type="text" value="">

								</fieldset>
								<input type="submit" class="btn btn-primary noty " name="btn_Material" value="Aceptar" />
							</form>


text:
package BombSimulator;

import java.util.Calendar;
import java.util.Random;

/**
 * Created by civi on 22/04/16.
 */
public abstract class Simulator implements Runnable {

    protected volatile boolean stopCondition = false;
    protected Random rnd = new Random();
    private long midnight;
    private Buffer<Measurement> measurementsQueue;
    private String id;
    private String type;

    public Simulator(String id, String type, Buffer<Measurement> measurementsQueue){
        this.measurementsQueue = measurementsQueue;
        this.midnight = computeMidnightMilliseconds();
    }

    public void stopMeGently() {
        stopCondition = true;
    }

    protected void addMeasurementToQueue(double measurement){
        measurementsQueue.addNewMeasurement(new Measurement(id, type, measurement, deltaTime()));
    }

    protected void sleep(long milliseconds){
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private long computeMidnightMilliseconds(){
        Calendar c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTimeInMillis();
    }

    private long deltaTime(){
        return System.currentTimeMillis()-midnight;
    }

}


text:
<?php

namespace Doctrine\Bundle\DoctrineBundle\Tests;

use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
use Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestType;
use Doctrine\Common\Annotations\AnnotationReader;
use PHPUnit\Framework\TestCase as BaseTestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

class TestCase extends BaseTestCase
{
    public function createXmlBundleTestContainer() : ContainerBuilder
    {
        $container = new ContainerBuilder(new ParameterBag([
            'kernel.name' => 'app',
            'kernel.debug' => false,
            'kernel.bundles' => ['XmlBundle' => 'Fixtures\Bundles\XmlBundle\XmlBundle'],
            'kernel.cache_dir' => sys_get_temp_dir(),
            'kernel.environment' => 'test',
            'kernel.root_dir' => __DIR__ . '/../../../../', // src dir
            'kernel.project_dir' => __DIR__ . '/../../../../', // src dir
            'kernel.bundles_metadata' => [],
            'container.build_id' => uniqid(),
        ]));
        $container->set('annotation_reader', new AnnotationReader());

        $extension = new DoctrineExtension();
        $container->registerExtension($extension);
        $extension->load([[
            'dbal' => [
                'connections' => [
                    'default' => [
                        'driver' => 'pdo_mysql',
                        'charset' => 'UTF8',
                        'platform-service' => 'my.platform',
                    ],
                ],
                'default_connection' => 'default',
                'types' => [
                    'test' => [
                        'class' => TestType::class,
                    ],
                ],
            ], 'orm' => [
                'default_entity_manager' => 'default',
                'entity_managers' => [
                    'default' => [
                        'mappings' => [
                            'XmlBundle' => [
                                'type' => 'xml',
                                'dir' => __DIR__ . '/DependencyInjection/Fixtures/Bundles/XmlBundle/Resources/config/doctrine',
                                'prefix' => 'Fixtures\Bundles\XmlBundle\Entity',
                            ],
                        ],
                    ],
                ],
                'resolve_target_entities' => ['Symfony\Component\Security\Core\User\UserInterface' => 'stdClass'],
            ],
        ],
        ], $container);

        $container->setDefinition('my.platform', new Definition('Doctrine\DBAL\Platforms\MySqlPlatform'))->setPublic(true);

        // Register dummy cache services so we don't have to load the FrameworkExtension
        $container->setDefinition('cache.system', (new Definition(ArrayAdapter::class))->setPublic(true));
        $container->setDefinition('cache.app', (new Definition(ArrayAdapter::class))->setPublic(true));

        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
        $container->getCompilerPassConfig()->setRemovingPasses([]);
        // make all Doctrine services public, so we can fetch them in the test
        $container->getCompilerPassConfig()->addPass(new TestCaseAllPublicCompilerPass());
        $container->compile();

        return $container;
    }
}

class TestCaseAllPublicCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container) : void
    {
        foreach ($container->getDefinitions() as $id => $definition) {
            if (strpos($id, 'doctrine') === false) {
                continue;
            }

            $definition->setPublic(true);
        }

        foreach ($container->getAliases() as $id => $alias) {
            if (strpos($id, 'doctrine') === false) {
                continue;
            }

            $alias->setPublic(true);
        }
    }
}


text:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from os import listdir
import re, sys

def main(fpath):

    # Display column names and their index for reference
    ec_data = pd.read_csv(fpath, parse_dates=True , index_col=['DT'])
    if show_names == True:
        for n,i in zip(ec_data.columns.values,range(ec_data.shape[1])):
            print( str(i) + " : " + n )

    # Let just grab what we need -- SWC and NDVI
    ec_phen = ec_data.loc[:,("Sws_Con","250m_16_days_NDVI_new_smooth")]

    # Resample the hourly data to daily (although we could just do 16-day)
    ec_sampled = ec_phen.resample('D', how='mean',)
    ec_sampled.columns = ["SWC10","NDVI250X"]
    ec_filt = ec_sampled[np.isfinite(ec_sampled['NDVI250X'])]

    # Write to CSV into the Data folder
    ec_filt.to_csv(opath, sep=",")

    # Add date/time index
    ec_filt.reset_index(level=0, inplace=True)

    # Plots environmental data
    if draw_plot==True:

        fig, (ax1,ax2) = plt.subplots(2, 1, sharex=True, figsize=(9,6))
        fig.subplots_adjust(hspace=0.1)
        fig.subplots_adjust(wspace=0.1)
        plt.rcParams['text.usetex'] = False
        plt.rcParams['font.family'] = "sans-serif"
        plt.rcParams['font.sans-serif'] = "Helvetica"
        plt.rcParams['axes.labelsize'] = 12
        plt.rcParams['font.size'] = 12
        plt.rcParams['legend.fontsize'] = 9
        plt.rcParams['xtick.labelsize'] = 12
        plt.rcParams['ytick.labelsize'] = 12

        almost_black = '#262626'
        # change the tick colors also to the almost black
        plt.rcParams['ytick.color'] = almost_black
        plt.rcParams['xtick.color'] = almost_black

        # change the text colors also to the almost black
        plt.rcParams['text.color'] = almost_black

        # Change the default axis colors from black to a slightly lighter black,
        # and a little thinner (0.5 instead of 1)
        plt.rcParams['axes.edgecolor'] = almost_black
        plt.rcParams['axes.labelcolor'] = almost_black

        ax1.plot(ec_filt['DT'], ec_filt["NDVI250X"], linestyle='-', color='red')
        ax2.plot(ec_filt['DT'], ec_filt["SWC10"], linestyle='-', color='blue')
        ax1.set_ylabel(r"NDVI (-)")
        ax2.set_ylabel(r"$\theta_{10cm}$")
        ax2.set_xlabel(r"Years")

        # force zero start in range
        ax1.set_ylim(ymin=0)
        ax2.set_ylim(ymin=0)

        ax1.yaxis.major.locator.set_params(nbins=5)
        ax2.yaxis.major.locator.set_params(nbins=5)

        simpleaxis(ax1)
        simpleaxis(ax2)

        #fig.autofmt_xdate()
        fig.savefig("{0}{1}_filt.pdf".format(fig_path,site),
                    bbox_inches='tight', pad_inches=0.1)

def simpleaxis(ax):
    """ Remove the top line and right line on the plot face """
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

def get_all_site_names(ec_files):
    # list comprehensive way of getting all names in bulk
    file_name = [ re.compile('^\w+').findall(f) for f in ec_files ]
    split_name = [ re.split('_',f) for f in sum(file_name,[]) ]
    name_ver = [[ name for i,name in enumerate(sublist) if (i==3) ] \
                  for sublist in split_name ]
    return sum(name_ver,[])

def get_site_name(ec_files):
    file_name = re.compile('^\w+').findall(ec_files)
    split_name = re.split('_',file_name[0])
    return split_name[-2]

    # Get all EC files in the folder above

if __name__ == '__main__':

    # Import EC tower Dingo dataset for Sturt Plains [move this to a config file]
    out_path = "../data/"
    fig_path = "../figs/"
    search_path = out_path+"Dingo_v12/"
    show_names = False
    draw_plot = True
    out_name = "filtered"
    version = "_v12"

    # collect all files for processed eddy covariance datasets in the data folder
    natt_names = ["AdelaideRiver","AliceSprings","DalyUncleared","DryRiver", \
                  "HowardSprings","SturtPlains"]

    get_files = [ f for f in listdir(search_path) if f.endswith('.csv') ]

    grab_these = pd.Series(get_files).str.contains("|".join(natt_names))

    natt_files = pd.Series(get_files)[np.array(grab_these)]

    # for each site extract the required data
    for i_file in natt_files:
        site = get_site_name(i_file)
        print "Filtering data for site => "+ site
        opath = out_path+out_name+"_"+site+version+".csv"
        fpath = search_path+i_file
        main(fpath)


text:
package org.scalatest

import org.scalatest.prop.Checkers
import org.scalacheck._
import Arbitrary._
import Prop._
import org.scalatest.exceptions.TestFailedException
import Matchers._

class ShouldBeNullSpec extends Spec with Checkers with ReturnsNormallyThrowsAssertion {

  val nullMap: Map[Int, String] = null
  val map = Map(1 -> "one", 2 -> "two")

  object `the be (null) syntax` {

    def `should work in its basic for with or without not` {

      map should not be (null)
      map should not (be (null))
      map should (not be (null))
      map should (not (be (null)))
      nullMap should be (null)
      nullMap should (be (null))
      // null should be (null) this doesn't compile. can't do implicits on the Null type, which is fine
      // null should (be (null))
      nullMap shouldBe null
      nullMap shouldBe (null)

      val caught1 = intercept[TestFailedException] {
        map should be (null)
      }
      assert(caught1.getMessage === "Map(1 -> \"one\", 2 -> \"two\") was not null")

      val caught1b = intercept[TestFailedException] {
        map shouldBe null
      }
      assert(caught1b.getMessage === "Map(1 -> \"one\", 2 -> \"two\") was not null")

      val caught2 = intercept[TestFailedException] {
        map should (be (null))
      }
      assert(caught2.getMessage === "Map(1 -> \"one\", 2 -> \"two\") was not null")

      val caught3 = intercept[TestFailedException] {
        nullMap should not be (null)
      }
      assert(caught3.getMessage === "The reference was null")

      val caught4 = intercept[TestFailedException] {
        nullMap should not (be (null))
      }
      assert(caught4.getMessage === "The reference was null")

      val caught5 = intercept[TestFailedException] {
        nullMap should not ((be (null)))
      }
      assert(caught5.getMessage === "The reference was null")

      val caught6 = intercept[TestFailedException] {
        nullMap should be (map)
      }
      assert(caught6.getMessage === "null was not equal to Map(1 -> \"one\", 2 -> \"two\")")
    }

    def `should throw a NullPointerException if they try to short circuit with a null check first` {
      // The reason I check this is I warn that this will happen in the ShouldMatcher scaladoc
      intercept[NullPointerException] {
        nullMap should (not be (null) and contain key (7))
      }
      intercept[NullPointerException] {
        nullMap should (be (null) and contain key (7))
      }
    }

    def `should compile and run when used with and (with or without not)` {

      val caught1 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (7) and not be (null))
      }
      assert(caught1.getMessage === "Map(1 -> \"one\") did not contain key 7")

      val caught2 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (7) and not (be (null)))
      }
      assert(caught2.getMessage === "Map(1 -> \"one\") did not contain key 7")

      val caught3 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (7) and (not (be (null))))
      }
      assert(caught3.getMessage === "Map(1 -> \"one\") did not contain key 7")

      Map(1 -> "one") should (contain key (1) and not be (null))
      Map(1 -> "one") should (contain key (1) and not (be (null)))
      Map(1 -> "one") should (contain key (1) and (not (be (null))))

      val caught4 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (1) and be (null))
      }
      assert(caught4.getMessage === "Map(1 -> \"one\") contained key 1, but Map(1 -> \"one\") was not null")

      val caught5 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (1) and (be (null)))
      }
      assert(caught5.getMessage === "Map(1 -> \"one\") contained key 1, but Map(1 -> \"one\") was not null")

      val caught6 = intercept[TestFailedException] {
        Map(1 -> "one") should (be (null) and not be (null))
      }
      assert(caught6.getMessage === "Map(1 -> \"one\") was not null")

      val caught7 = intercept[TestFailedException] {
        Map(1 -> "one") should (be (null) and not (be (null)))
      }
      assert(caught7.getMessage === "Map(1 -> \"one\") was not null")

      val caught8 = intercept[TestFailedException] {
        Map(1 -> "one") should (be (null) and (not (be (null))))
      }
      assert(caught8.getMessage === "Map(1 -> \"one\") was not null")

      nullMap should (be (null) and be (null))
      nullMap should (be (null) and (be (null)))

      val caught9 = intercept[TestFailedException] {
        nullMap should (be (null) and not be (null))
      }
      assert(caught9.getMessage === "The reference was null, but the reference was null")

      val caught10 = intercept[TestFailedException] {
        nullMap should (be (null) and not (be (null)))
      }
      assert(caught10.getMessage === "The reference was null, but the reference was null")

      val caught11 = intercept[TestFailedException] {
        nullMap should (be (null) and (not (be (null))))
      }
      assert(caught11.getMessage === "The reference was null, but the reference was null")
    }

    def `should compile and run when used with or (with or without not)` {

      Map(1 -> "one") should (contain key (7) or not be (null))
      Map(1 -> "one") should (contain key (7) or not (be (null)))
      Map(1 -> "one") should (contain key (7) or (not (be (null))))

      Map(1 -> "one") should (contain key (1) or not be (null))
      Map(1 -> "one") should (contain key (1) or not (be (null)))
      Map(1 -> "one") should (contain key (1) or (not (be (null))))

      val caught4 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (7) or be (null))
      }
      assert(caught4.getMessage === "Map(1 -> \"one\") did not contain key 7, and Map(1 -> \"one\") was not null")

      val caught5 = intercept[TestFailedException] {
        Map(1 -> "one") should (contain key (7) or (be (null)))
      }
      assert(caught5.getMessage === "Map(1 -> \"one\") did not contain key 7, and Map(1 -> \"one\") was not null")

      val caught6 = intercept[TestFailedException] {
        Map(1 -> "one") should (be (null) or be (null))
      }
      assert(caught6.getMessage === "Map(1 -> \"one\") was not null, and Map(1 -> \"one\") was not null")

      val caught7 = intercept[TestFailedException] {
        Map(1 -> "one") should (be (null) or (be (null)))
      }
      assert(caught7.getMessage === "Map(1 -> \"one\") was not null, and Map(1 -> \"one\") was not null")

      nullMap should (be (null) or be (null))
      nullMap should (be (null) or (be (null)))
      nullMap should (be (null) or not be (null))
      nullMap should (be (null) or not (be (null)))
      nullMap should (be (null) or (not (be (null))))
      nullMap should (not be (null) or be (null))
      nullMap should (not (be (null)) or be (null))
    }
  }

/*
  object `the shouldBe null syntax` {

    def `should work in its basic` {
      nullMap shouldBe null

      val caught1 = intercept[TestFailedException] {
        map shouldBe null
      }
      assert(caught1.getMessage === "Map(1 -> one, 2 -> two) was not null")
    }
  }
*/
}


text:
<?PHP header("Content-Type: text/html; charset=UTF-8",true);
if(!defined('INITIALIZED'))
	exit;

$main_content .= 'Players online records on '.$config['server']['serverName'].'

Players	Date
';
$records = $SQL->query('SELECT * FROM ' . $SQL->tableName('server_record') . ' ORDER BY ' . $SQL->fieldName('record') . ' DESC LIMIT 50;')->fetchAll();
foreach($records as $i => $record)
{
	$data = date("d/m/Y, G:i:s", $record['timestamp']);
	$bgcolor = (($i % 2 == 1) ?  $config['site']['darkborder'] : $config['site']['lightborder']);
	$main_content .= '
'.$record['record'].'	'.$data.'
';
}
$main_content .= '
';


text:
package org.knopflerfish.bundle.consoletelnet;

/**
 * * The SUPGA command has no sub negotiable parameter
 */
public class TelnetCommandSupga extends TelnetCommand {

    public TelnetCommandSupga(TelnetSession ts, int commandCode,
            boolean servDO, boolean show) {
        super(ts, commandCode, servDO, show);
    }

    /**
     * Option negotiation and execution mechanism
     *
     * To follow the intentions of RFC 854, a change in status
     * is always followed by a response but if trying to enter a mode
     * that we are already in, no response is returned.
     *
     * This is essential to prevent negotiation loops.
     *
     * @param action, one of the telnet protocol basic actions DO, DONT, WILL, WONT or SE
     * @param optionCode, the option code
     * @param parameters, a string with optional parameters to the option code.
     *
     * @return a String with the response to the command.
     */
    @Override
    public String execute(int action, int optionCode, byte[] parameters) {
        // printCommand(action, optionCode, parameters);
        StringBuilder sb = new StringBuilder();

        switch (action) {
        case TCC.DO:
            if (doStatus) {
                // willing and ready, send no resonse,
                // to prevent creation of negotiation loop
            } else {
                doStatus = true;
            }
            break;

        case TCC.WILL:
            if (doStatus) {
                // willing and ready, send no resonse,
                // to prevent creation of negotiation loop
            } else {
                doStatus = true;
            }
            break;

        case TCC.DONT:
            if (doStatus) {
                sb.append(getWONT());
                doStatus = false;
                // now not willing, send no resonse,
                // to prevent creation of negotiation loop
            } else {
                doStatus = false;
            }
            break;

        case TCC.WONT:
            if (doStatus) {
                // no appropriate answer to send
                doStatus = false;
                // now not willing, send no resonse,
                // to prevent creation of negotiation loop
            } else {
                doStatus = false;
            }
            break;

        // SB .... SE, command execution, when negotiations
        // are finished and both parties have agreed

        case TCC.SE:
            if (doStatus) {

            } else { // not in right state
                sb.append(getDONT());
            }
            break;

        default:
            break;
        }
        return sb.toString();
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/esqueci_senha.css"/>
<title>Recuperar Senha</title>

        A Impacta
        Cursos
        Eventos
        Noticías
        Blog
        Contatos
		Login

		<form action="recuperarSenha" method="post">
			Recuperar senha

			 Email:

			<input type="text" name="email" id="email" size="20"/>

			 RA:

			<input type="text" name="ra_aluno" id="ra_aluno"/>

			 Nova senha:

			<input type="password" name="nova_senha" id="nova_senha">

			 Confirmação da Nova Senha:

			<input type="password" name="confirmacao_senha" id="confirmacao_senha"/>

			<button type="submit">Enviar</button>

		</form>

 © Impacta 2017. Todos os direitos reservados. Política de privacidade


text:
package ch.rasc.wamp2spring.message;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

public class HelloMessageTest extends BaseMessageTest {

	@Test
	public void serializeTest() {
		List<WampRole> roles = createRoles();
		HelloMessage helloMessage = new HelloMessage("aRealm", roles);

		assertThat(helloMessage.getCode()).isEqualTo(1);
		assertThat(helloMessage.getRealm()).isEqualTo("aRealm");
		assertThat(helloMessage.getRoles()).isEqualTo(roles);

		String json = serializeToJson(helloMessage);
		assertThat(json).isEqualTo(
				"[1,\"aRealm\",{\"roles\":{\"publisher\":{\"features\":{\"publisher_exclusion\":true}},\"subscriber\":{\"features\":{\"subscriber_blackwhite_listing\":true}}}}]");
	}

	@Test
	public void deserializeTest() throws IOException {
		String json = "[1, \"somerealm\", { \"roles\": { \"publisher\": {}, \"subscriber\": {} } }]";
		HelloMessage helloMessage = WampMessage.deserialize(getJsonFactory(),
				json.getBytes(StandardCharsets.UTF_8));
		assertThat(helloMessage.getCode()).isEqualTo(1);
		assertThat(helloMessage.getRealm()).isEqualTo("somerealm");
		assertThat(helloMessage.getRoles()).containsOnly(new WampRole("publisher"),
				new WampRole("subscriber"));

		json = "[1,\"aRealm\",{\"roles\":{\"publisher\":{\"features\":{\"publisher_exclusion\":true}},\"subscriber\":{\"features\":{\"subscriber_blackwhite_listing\":true}}}}]";
		helloMessage = WampMessage.deserialize(getJsonFactory(),
				json.getBytes(StandardCharsets.UTF_8));
		assertThat(helloMessage.getCode()).isEqualTo(1);
		assertThat(helloMessage.getRealm()).isEqualTo("aRealm");
		assertThat(helloMessage.getRoles()).containsOnlyElementsOf(createRoles());
	}

	private static List<WampRole> createRoles() {
		List<WampRole> roles = new ArrayList<>();
		WampRole publisher = new WampRole("publisher");
		publisher.addFeature("publisher_exclusion");
		roles.add(publisher);

		WampRole subscriber = new WampRole("subscriber");
		subscriber.addFeature("subscriber_blackwhite_listing");
		roles.add(subscriber);

		return roles;
	}
}


text:
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from dumprestore.archive import Archive
from dumprestore.default import default_set
from dumprestore import archive

class Command(BaseCommand):
    args = '<filename>'
    help = "Backup to the specified zip filename"

    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Usage: restore <filename>")
        if hasattr(settings, "DUMPRESTORE_SET"):
            s = settings.DUMPRESTORE_SET
        else:
            s = default_set()
        s.archive = archive.Archive.new(args[0], "r")
        if not s.before_restore():
            raise SystemExit()
        s.restore()
        s.after_restore()