text:
/**
 *  This file is part of ytd2
 *
 *  ytd2 is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  ytd2 is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  You should have received a copy of the GNU General Public License
 *  along with ytd2.
 *  If not, see <http://www.gnu.org/licenses/>.
 */
package zsk;

import java.io.BufferedReader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileNotFoundException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
// necessary external libraries
// http://hc.apache.org/downloads.cgi -> httpcomponents-core-4.2.2-bin, httpcomponents-client-4.2.2-bin
// plus corresponding sources as Source Attachment within the Eclipse Project Properties
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
//import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
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.cookie.CookieOrigin;
//import org.apache.http.cookie.CookieSpec;
//import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
//import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

/**
 * http://www.youtube.com/watch?v=9QFK1cLhytY					Javatar and .NOT
 * http://www.youtube.com/watch?v=Mt7zsortIXs				 	1080p "Lady Java"
 * http://www.youtube.com/watch?v=WowZLe95WDY					Tom Petty And the Heartbreakers - Learning to Fly (with lyrics)
 * http://www.youtube.com/watch?v=86OfBExGSE0					URZ 720p
 * http://www.youtube.com/watch?v=cNOP2t9FObw 					Blade 360 - 480
 * http://www.youtube.com/watch?v=HvQBrM_i8bU					MZ 1000 Street Fighter
 * http://www.youtube.com/watch?v=yVpbFMhOAwE					How Linx is build
 * http://www.youtube.com/watch?v=4XpnKHJAok8					Tech Talk: Linus Torvalds on git
 *
 * ODOT http://sourceforge.net/p/ytd2/bugs/7/ http://www.youtube.com/watch?v=fRVVzXnRsUQ   uses RTMPE (http://en.wikipedia.org/wiki/Protected_Streaming), which ytd2 cannot download atm
 *
 */
public class YTDownloadThread extends Thread {

	boolean bNODOWNLOAD;

	static int iThreadcount = 0;

	public static int getiThreadcount() {
		return iThreadcount;
	}

	int iThreadNo = YTDownloadThread.iThreadcount++; // every download thread get its own number
	private static YTDEventDispatcher eventDispatcher = new YTDEventDispatcher(); // notify changes
	public static YTDEventDispatcher getEventDispatcher() {
		return eventDispatcher;
	}

	final String ssourcecodeurl = "http://";
	final String ssourcecodeuri = "[a-zA-Z0-9%&=\\.]";

	String sURL = null;				// main URL (youtube start web page)
	String sTitle = null;			// will be used as filename

	String sVideoURL = null;		// one video web resource
	Vector<YTURL> vNextVideoURL = new Vector<YTURL>();	// list of URLs from webpage source
	String sFileName = null;		// contains the absolute filename
	//CookieStore bcs = null;			// contains cookies after first HTTP GET
	boolean bisinterrupted = false; // basically the same as Thread.isInterrupted()
	int iRecursionCount = -1;		// counted in downloadone() for the 3 webrequest to one video

	String 				sContentType = null;
	BufferedReader		textreader = null;
	BufferedInputStream binaryreader = null;
	HttpGet				httpget = null;
	HttpClient			httpclient = null;
	HttpHost			proxy = null;
	HttpHost			target = null;
	HttpContext			localContext = null;
    HttpResponse		response = null;

	public YTDownloadThread() {
		super();
		String sv = "thread started: ".concat(this.getMyName());
		debugoutput(sv);
	} // YTDownloadThread()

	boolean downloadone(String sURL) {
		boolean rc = false;
		boolean rc204 = false;
		boolean rc302 = false;

		this.iRecursionCount++;

		// stop recursion
		try {
			if (sURL.equals("")) return(false);
		} catch (NullPointerException npe) {
			return(false);
		}
		if (JFCMainClient.getbQuitrequested()) return(false); // try to get information about application shutdown

		debugoutput("start.");

		// TODO GUI option for proxy?
		// http://wiki.squid-cache.org/ConfigExamples/DynamicContent/YouTube
		// using local squid to save download time for tests

		try {
			// determine http_proxy environment variable
			if (!this.getProxy().equals("")) {

				String sproxy = JFCMainClient.sproxy.toLowerCase().replaceFirst("http://", "") ;
				this.proxy = new HttpHost( sproxy.replaceFirst(":(.*)", ""), Integer.parseInt( sproxy.replaceFirst("(.*):", "")), "http");

				SchemeRegistry supportedSchemes = new SchemeRegistry();
				supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
				supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

				HttpParams params = new BasicHttpParams();
				HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(params, "UTF-8");
				HttpProtocolParams.setUseExpectContinue(params, true);

				ClientConnectionManager ccm = new PoolingClientConnectionManager(supportedSchemes);

				// with proxy
				this.httpclient = new DefaultHttpClient(ccm, params);
				this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, this.proxy);
				this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
			} else {
				// without proxy
				this.httpclient = new DefaultHttpClient();
				this.httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
			}
			this.httpget = new HttpGet( getURI(sURL) );
			if (sURL.toLowerCase().startsWith("https"))
				this.target = new HttpHost( getHost(sURL), 443, "https" );
			else
				this.target = new HttpHost( getHost(sURL), 80, "http" );
		} catch (Exception e) {
			debugoutput(e.getMessage());
		}

        debugoutput("executing request: ".concat( this.httpget.getRequestLine().toString()) );
        debugoutput("uri: ".concat( this.httpget.getURI().toString()) );
        debugoutput("host: ".concat( this.target.getHostName() ));
        debugoutput("using proxy: ".concat( this.getProxy() ));

        // we dont need cookies at all because the download runs even without it (like my wget does) - in fact it blocks downloading videos from different webpages, because we do not handle the bcs for every URL (downloading of one video with different resolutions does work)
        /*
        this.localContext = new BasicHttpContext();
        if (this.bcs == null) this.bcs = new BasicCookieStore(); // make cookies persistent, otherwise they would be stored in a HttpContext but get lost after calling org.apache.http.impl.client.AbstractHttpClient.execute(HttpHost target, HttpRequest request, HttpContext context)
		((DefaultHttpClient) httpclient).setCookieStore(this.bcs); // cast to AbstractHttpclient would be best match because DefaultHttpClass is a subclass of AbstractHttpClient
		*/

        // TODO maybe we save the video IDs+res that were downloaded to avoid downloading the same video again?

		try {
			this.response = this.httpclient.execute(this.target,this.httpget,this.localContext);
		} catch (ClientProtocolException cpe) {
			debugoutput(cpe.getMessage());
		} catch (UnknownHostException uhe) {
			output((JFCMainClient.isgerman()?"Fehler bei der Verbindung zu: ":"error connecting to: ").concat(uhe.getMessage()));
			debugoutput(uhe.getMessage());
		} catch (IOException ioe) {
			debugoutput(ioe.getMessage());
		} catch (IllegalStateException ise) {
			debugoutput(ise.getMessage());
		}

		/*
		CookieOrigin cookieOrigin = (CookieOrigin) localContext.getAttribute( ClientContext.COOKIE_ORIGIN);
		CookieSpec cookieSpec = (CookieSpec) localContext.getAttribute( ClientContext.COOKIE_SPEC);
		CookieStore cookieStore = (CookieStore) localContext.getAttribute( ClientContext.COOKIE_STORE) ;
		try { debugoutput("HTTP Cookie store: ".concat( cookieStore.getCookies().toString( )));
		} catch (NullPointerException npe) {} // useless if we don't set our own CookieStore before calling httpclient.execute
		try {
			debugoutput("HTTP Cookie origin: ".concat(cookieOrigin.toString()));
			debugoutput("HTTP Cookie spec used: ".concat(cookieSpec.toString()));
			debugoutput("HTTP Cookie store (persistent): ".concat(this.bcs.getCookies().toString()));
		} catch (NullPointerException npe) {
		}
		*/

		try {
			debugoutput("HTTP response status line:".concat( this.response.getStatusLine().toString()) );
			//for (int i = 0; i < response.getAllHeaders().length; i++) {
			//	debugoutput(response.getAllHeaders()[i].getName().concat("=").concat(response.getAllHeaders()[i].getValue()));
			//}

			// abort if HTTP response code is != 200, != 302 and !=204 - wrong URL?
			if (!(rc = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)200(.*)")) &
					!(rc204 = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)204(.*)")) &
					!(rc302 = this.response.getStatusLine().toString().toLowerCase().matches("^(http)(.*)302(.*)"))) {
				debugoutput(this.response.getStatusLine().toString().concat(" ").concat(sURL));
				output(this.response.getStatusLine().toString().concat(" \"").concat(this.sTitle).concat("\""));
				return(rc & rc204 & rc302);
			}
			if (rc204) {
				debugoutput("last response code==204 - download: ".concat(this.vNextVideoURL.get(0).getsYTID()));
				rc = downloadone(this.vNextVideoURL.get(0).getsURL());
				return(rc);
			}
			if (rc302)
				debugoutput("location from HTTP Header: ".concat(this.response.getFirstHeader("Location").toString()));

		} catch (NullPointerException npe) {
			// if an IllegalStateException was catched while calling httpclient.execute(httpget) a NPE is caught here because
			// response.getStatusLine() == null
			this.sVideoURL = null;
		}

		HttpEntity entity = null;
        try {
            entity = this.response.getEntity();
        } catch (NullPointerException npe) {
        }

        // try to read HTTP response body
        if (entity != null) {
			try {
				if (this.response.getFirstHeader("Content-Type").getValue().toLowerCase().matches("^text/html(.*)"))
					this.textreader = new BufferedReader(new InputStreamReader(entity.getContent()));
				else
					this.binaryreader = new BufferedInputStream( entity.getContent());
			} catch (IllegalStateException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
            try {
            	// test if we got a webpage
            	this.sContentType = this.response.getFirstHeader("Content-Type").getValue().toLowerCase();
            	if (this.sContentType.matches("^text/html(.*)")) {
            		rc = savetextdata();
            	// test if we got the binary content
            	} else if (this.sContentType.matches("video/(.)*")) {
            		if (JFCMainClient.getbNODOWNLOAD())
            			reportheaderinfo();
            		else
            			savebinarydata();
            	} else { // content-type is not video/
            		rc = false;
            		this.sVideoURL = null;
            	}
            } catch (IOException ex) {
                try {
					throw ex;
				} catch (IOException e) {
					e.printStackTrace();
				}
            } catch (RuntimeException ex) {
                try {
					throw ex;
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        } //if (entity != null)

       	this.httpclient.getConnectionManager().shutdown();

        debugoutput("done: ".concat(sURL));
        if (this.sVideoURL==null)
        	this.sVideoURL=""; // to prevent NPE

        if (!this.sVideoURL.matches(JFCMainClient.szURLREGEX)) {
        	// no more recursion - html source hase been read
        	// test !rc than video could not downloaded because of some error (like wrong protocol or restriction)
        	if (!rc) {
        		debugoutput("cannot download video - URL does not seem to be valid or could not be found: ".concat(this.sURL));
        		output(JFCMainClient.isgerman()?"es gab ein Problem die Video URL zu finden! evt. wegen Landesinschränkung?!":"there was a problem getting the video URL! perhaps not allowed in your country?!");
        		output((JFCMainClient.isgerman()?"erwäge die URL dem Autor mitzuteilen!":"consider reporting the URL to author! - ").concat(this.sURL));
        		this.sVideoURL = null;
        	}
        } else {
        	// enter recursion - download video resource
        	debugoutput("try to download video from URL: ".concat(this.sVideoURL));
        	rc = downloadone(this.sVideoURL);
        }
        this.sVideoURL = null;

    	return(rc);

	} // downloadone()

	void reportheaderinfo() {
		if (JFCMainClient.getbDEBUG()) {
			debugoutput("");
			debugoutput("NO-DOWNLOAD mode active (ndl on)");
			debugoutput("all HTTP header fields:");
			for (int i = 0; i < this.response.getAllHeaders().length; i++) {
				debugoutput(this.response.getAllHeaders()[i].getName().concat("=").concat(this.response.getAllHeaders()[i].getValue()));
			}
			debugoutput("filename would be: ".concat(this.getTitle()).concat(".").concat(this.response.getFirstHeader("Content-Type").getValue().replaceFirst("video/", "").replaceAll("x-", ""))); // title contains just filename, no path
		} else {
			Long iFileSize = Long.parseLong(this.response.getFirstHeader("Content-Length").getValue());
			output("");
			output("NO-DOWNLOAD active (ndl on)");
			output("some HTTP header fields:");
			output("content-type: ".concat( this.response.getFirstHeader("Content-Type").getValue()) );
			output("content-length: ".concat(iFileSize.toString()).concat(" Bytes").concat(" ~ ").concat(Long.toString((iFileSize/1024)).concat(" KiB")).concat(" ~ ").concat(Long.toString((iFileSize/1024/1024)).concat(" MiB")) );
			if (JFCMainClient.getbNODOWNLOAD())
				output((JFCMainClient.isgerman()?"Dateiname würde sein: ":"filename would be: ").concat(this.getTitle().concat(".").concat(this.response.getFirstHeader("Content-Type").getValue().replaceFirst("video/", "").replaceAll("x-", "")))); // title contains just filename, no path
		}
		this.sVideoURL = null;
	} // reportheaderinfo()

	private int addMPEG_HD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;
		// try 3D HD first if 3D is selected
		if (JFCMainClient.get3Dbuttonstate())
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("84"),this.sURL,"3D")); // mpeg 3D full HD

		// if SDS is on reverse order! - 720p before 1080p for HD and so on
		if (!JFCMainClient.bSaveDiskSpace) {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("37"),this.sURL)); // mpeg full HD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("22"),this.sURL)); // mpeg half HD
		} else {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("22"),this.sURL)); // mpeg half HD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("37"),this.sURL)); // mpeg full HD
		}
		return inewiindex;
	}

	private int addWBEM_HD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;
		// try 3D HD first if 3D is selected
		if (JFCMainClient.get3Dbuttonstate())
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("100"),this.sURL,"3D")); // webm 3D HD

		if (!JFCMainClient.bSaveDiskSpace) {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("46"),this.sURL)); // webm full HD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("45"),this.sURL)); // webm half HD
		} else {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("45"),this.sURL)); // webm half HD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("46"),this.sURL)); // webm full HD
		}
		return inewiindex;
	}

	private int addWBEM_SD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;
		// try 3D  first if 3D is selected
		if (JFCMainClient.get3Dbuttonstate())
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("102"),this.sURL,"3D")); // webm 3D SD

		if (!JFCMainClient.bSaveDiskSpace) {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("44"),this.sURL)); // webm SD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("43"),this.sURL)); // webm SD
		} else {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("43"),this.sURL)); // webm SD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("44"),this.sURL)); // webm SD
		}
		return inewiindex;
	}

	private int addFLV_SD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;

		if (!JFCMainClient.bSaveDiskSpace) {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("35"),this.sURL)); // flv SD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("34"),this.sURL)); // flv SD
		} else {
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("34"),this.sURL)); // flv SD
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("35"),this.sURL)); // flv SD
		}
		return inewiindex;
	}

	private int addMPEG_SD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;

		// try 3D  first if 3D is selected
		if (JFCMainClient.get3Dbuttonstate())
			this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("82"),this.sURL,"3D")); // mpeg 3D SD

		this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("18"),this.sURL)); // mpeg SD
		return inewiindex;
	}

	private int addMPEG_LD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;
		this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("36"),this.sURL)); // mpeg LD
		this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get("17"),this.sURL)); // mpeg LD
		return inewiindex;
	}
	private int addFLV_LD_Urls(int iindex, HashMap<String, String> ssourcecodevideourls) {
		int inewiindex = iindex;

		this.vNextVideoURL.add(inewiindex++, new YTURL(ssourcecodevideourls.get( "5"),this.sURL)); // flv LD
		return inewiindex;
	}

	boolean savetextdata() throws IOException {
		boolean rc = false;
		// read html lines one by one and search for java script array of video URLs
		String sline = "";
		while (sline != null) {
			sline = this.textreader.readLine();
			try {
				if (this.iRecursionCount==0 && sline.matches("(.*)\"url_encoded_fmt_stream_map\":(.*)")) {
					rc = true;
    				HashMap<String, String> ssourcecodevideourls = new HashMap<String, String>();

					sline = sline.replaceFirst(".*\"url_encoded_fmt_stream_map\": \"", "");
					sline = sline.replaceFirst("\".*", "");
					sline = sline.replace("%25","%");
					sline = sline.replace("\\u0026", "&");
					sline = sline.replace("\\", "");

					// by anonymous
					String[] ssourcecodeyturls = sline.split(",");
					debugoutput("ssourcecodeuturls.length: ".concat(Integer.toString(ssourcecodeyturls.length)));
					String sResolutions = JFCMainClient.isgerman()?"gefundene Video URL für Auflösung: ":"found video URL for resolution: ";

					for (String urlString : ssourcecodeyturls) {

						// assuming rtmpe is used for all resolutions, if found once - end download
						if (urlString.matches(".*conn=rtmpe.*")) {
							debugoutput("RTMPE found. cannot download this one!");
							output(JFCMainClient.isgerman()?"Herunterladen des Videos wegen nicht unterstütztem Protokoll (RTMPE) leider nicht möglich!":"Unable to download video due to unsupported protocol (RTMPE). sry!");
							break;
						}
						String[] fmtUrlPair = urlString.split("url=http",2);
						fmtUrlPair[1] = "url=http"+fmtUrlPair[1]+"&"+fmtUrlPair[0];
						// grep itag=xz out and use xy as hash key
						// 2013-02 itag now has up to 3 digits
						fmtUrlPair[0] = fmtUrlPair[1].substring(fmtUrlPair[1].indexOf("itag=")+5, fmtUrlPair[1].indexOf("itag=")+5+1+(fmtUrlPair[1].matches(".*itag=[0-9]{2}.*")?1:0)+(fmtUrlPair[1].matches(".*itag=[0-9]{3}.*")?1:0));
						fmtUrlPair[1] = fmtUrlPair[1].replaceFirst("url=http%3A%2F%2F", "http://");
						fmtUrlPair[1] = fmtUrlPair[1].replaceAll("%3F","?").replaceAll("%2F", "/").replaceAll("%3B",";").replaceAll("%2C",",").replaceAll("%3D","=").replaceAll("%26", "&").replaceAll("%252C", "%2C").replaceAll("sig=", "signature=").replaceAll("&s=", "&signature=").replaceAll("\\?s=", "?signature=");

						// remove duplicated &itag=xy
						if (StringUtils.countMatches(fmtUrlPair[1], "itag=")==2)
							fmtUrlPair[1] = fmtUrlPair[1].replaceFirst("itag=[0-9]{1,3}", "");

						try {
							ssourcecodevideourls.put(fmtUrlPair[0], fmtUrlPair[1]); // save that URL
							//debugoutput(String.format( "video url saved with key %s: %s",fmtUrlPair[0],ssourcecodevideourls.get(fmtUrlPair[0]) ));
							sResolutions = sResolutions.concat(
									fmtUrlPair[0].equals( "37")?"1080p mpeg, ":		// HD		type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2"
									fmtUrlPair[0].equals( "22")?"720p mpeg, ":		// HD		type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2"
									fmtUrlPair[0].equals( "84")?"1080p 3d mpeg, ":	// HD 3D	type=video/mp4;+codecs="avc1.64001F,+mp4a.40.2"
									fmtUrlPair[0].equals( "35")?"480p flv, ":		// SD		type=video/x-flv
									fmtUrlPair[0].equals( "18")?"360p mpeg, ":		// SD		type=video/mp4;+codecs="avc1.42001E,+mp4a.40.2"
									fmtUrlPair[0].equals( "34")?"360p flv, ":		// SD		type=video/x-flv
									fmtUrlPair[0].equals( "82")?"360p 3d mpeg, ":	// SD 3D	type=video/mp4;+codecs="avc1.42001E,+mp4a.40.2"
									fmtUrlPair[0].equals( "36")?"240p mpeg 3gpp, ":	// LD		type=video/3gpp;+codecs="mp4v.20.3,+mp4a.40.2"
									fmtUrlPair[0].equals( "17")?"114p mpeg 3gpp, ":	// LD		type=video/3gpp;+codecs="mp4v.20.3,+mp4a.40.2"

									fmtUrlPair[0].equals( "46")?"1080p webm, ":		// HD 		type=video/webm;+codecs="vp8.0,+vorbis"&
									fmtUrlPair[0].equals( "45")?"720p webm, ":		// HD		type=video/webm;+codecs="vp8.0,+vorbis"
									fmtUrlPair[0].equals("100")?"1080p 3d webm, ":	// HD 3D	type=video/webm;+codecs="vp8.0,+vorbis"&
									fmtUrlPair[0].equals( "44")?"480p webm, ":		// SD		type=video/webm;+codecs="vp8.0,+vorbis"
									fmtUrlPair[0].equals( "43")?"360p webm, ":		// SD		type=video/webm;+codecs="vp8.0,+vorbis"
									fmtUrlPair[0].equals("102")?"360p 3d webm, ":	// SD 3D	type=video/webm;+codecs="vp8.0,+vorbis"&
									fmtUrlPair[0].equals(  "5")?"240p flv, ":		// LD		type=video/x-flv
									"unknown resolution! (".concat(fmtUrlPair[0]).concat(")"));
						} catch (java.lang.ArrayIndexOutOfBoundsException aioobe) {
						}
					} // for

					if (JFCMainClient.frame!=null)
						output(sResolutions);
					debugoutput(sResolutions);

					int iindex;	iindex = 0;
					this.vNextVideoURL.removeAllElements();

					debugoutput("ssourcecodevideourls.length: ".concat(Integer.toString(ssourcecodevideourls.size())));
					// figure out what resolution-button is pressed now and fill list with possible URLs
					switch (JFCMainClient.getIdlbuttonstate()) {
					case 4: // HD
						// try 1080p/720p in selected format first. if it's not available than the other format will be used
						if (JFCMainClient.getBmpgbuttonstate())
							iindex=addMPEG_HD_Urls(iindex,ssourcecodevideourls);

						if (JFCMainClient.getBwebmbuttonstate())
							iindex=addWBEM_HD_Urls(iindex,ssourcecodevideourls);

						// there are no FLV HD URLs for now, so at least try mpg,wbem HD then
						iindex = addMPEG_HD_Urls(iindex, ssourcecodevideourls);
						iindex = addWBEM_HD_Urls(iindex, ssourcecodevideourls);

						//$FALL-THROUGH$
					case 2: // SD
						// try to download desired format first, if it's not available we take the other of same res
						if (JFCMainClient.getBmpgbuttonstate())
							iindex=addMPEG_SD_Urls(iindex, ssourcecodevideourls);

						if (JFCMainClient.getBwebmbuttonstate())
							iindex=addWBEM_SD_Urls(iindex,ssourcecodevideourls);

						if (JFCMainClient.getBflvbuttonstate())
							iindex=addFLV_SD_Urls(iindex, ssourcecodevideourls);

						iindex = addMPEG_SD_Urls(iindex, ssourcecodevideourls);
						iindex = addWBEM_SD_Urls(iindex, ssourcecodevideourls);
						iindex = addFLV_SD_Urls(iindex, ssourcecodevideourls);

						//$FALL-THROUGH$
					case 1:	// LD

						// TODO this.sFilenameResPart = "(LD)"; // adding LD to filename because HD-Videos are almost already named HD (?)
						if (JFCMainClient.getBmpgbuttonstate())
							iindex = addMPEG_LD_Urls(iindex, ssourcecodevideourls);

						if (JFCMainClient.getBwebmbuttonstate()) {
							// there are no wbem LD URLs for now
						}

						if (JFCMainClient.getBflvbuttonstate())
							iindex = addFLV_LD_Urls(iindex, ssourcecodevideourls);

						// we must ensure all (16) possible URLs get added to the list so that the list of URLs is never empty
						iindex = addMPEG_LD_Urls(iindex, ssourcecodevideourls);
						iindex = addFLV_LD_Urls(iindex, ssourcecodevideourls);

						break;
					default:
						//this.vNextVideoURL = null;
						this.sVideoURL = null;
						break;
					}

					// if the first 2 entries are null than there are no URLs for the selected resolution
					// strictly speaking this is only true for HD as there are only two URLs in contrast to three of SD - in this case the output will not be shown but downloading should work anyway
					if (this.vNextVideoURL.get(0).getsURL()==null && this.vNextVideoURL.get(1).getsURL()==null) {
						String smsg = JFCMainClient.isgerman()?"Video URL für ausgewählte Auflösung nicht gefunden! versuche geringere Auflösung...":"could not find video url for selected resolution! trying lower res...";
						output(smsg); debugoutput(smsg);
					}

					// remove null entries in list - we later try to download the first (index 0) and if it fails the next one (at index 1) and so on
					for (int x=this.vNextVideoURL.size()-1;x>=0;x--) {
						if (this.vNextVideoURL.get(x).getsURL()==null) this.vNextVideoURL.remove(x);
					}

					try {
						this.sVideoURL = this.vNextVideoURL.get(0).getsURL();
						debugoutput(String.format("trying this one: %s %s %s",this.vNextVideoURL.get(0).getsITAG(),this.vNextVideoURL.get(0).getsQUALITY(),this.vNextVideoURL.get(0).getsTYPE()));
					} catch (ArrayIndexOutOfBoundsException aioobe) {
					}

					this.setTitle( this.getTitle()
							.concat(JFCMainClient.isbSaveIDinFilename()?"."+this.vNextVideoURL.get(0).getsYTID():"")
							.concat(!this.vNextVideoURL.get(0).getsRESPART().equals("")?"."+this.vNextVideoURL.get(0).getsRESPART():""));

				}

				if (this.iRecursionCount==0 && sline.matches("(.*)<meta name=\"title\" content=(.*)")) {
					String stmp = sline.replaceFirst("(.*)<meta name=\"title\" content=", "").trim();
					// change html characters to their UTF8 counterpart
					stmp = UTF8.changeHTMLtoUTF8(stmp);
					stmp = stmp.replaceFirst("^\"", "").replaceFirst("\">$", "");
					this.setTitle( stmp ); // complete file name without path
				}

			} catch (NullPointerException npe) {
			}
		} // while
		return rc;
	} // savetextdata()

	void savebinarydata() throws IOException {
		FileOutputStream fos = null;
		try {
			File f; Integer idupcount = 0;
			String sdirectorychoosed;
//			try {
//				synchronized (JFCMainClient.frame.directorytextfield) {
//					sdirectorychoosed = JFCMainClient.frame.directorytextfield.getText();
//				}
//			} catch (NullPointerException npe) {
//				// for CLI-only run
//				sdirectorychoosed = JFCMainClient.shomedir;
//			}
			sdirectorychoosed=(String) JFCMainClient.config.getProperty("savefolder");

			String sfilename = this.getTitle();
    		debugoutput("title: ".concat(this.getTitle()).concat("sfilename: ").concat(sfilename));
			do {
				f = new File(sdirectorychoosed, sfilename.concat((idupcount>0?"(".concat(idupcount.toString()).concat(")"):"")).concat(".").concat(this.sContentType.replaceFirst("video/", "").replaceAll("x-", "")));
				idupcount += 1;
			} while (f.exists());
			this.setFileName(f.getAbsolutePath());

			Long iBytesReadSum = (long) 0;
			Long iPercentage = (long) -1;
			Long iBytesMax = Long.parseLong(this.response.getFirstHeader("Content-Length").getValue());
			fos = new FileOutputStream(f);

			debugoutput(String.format("writing %d bytes to: %s",iBytesMax,this.getFileName()));
			output((JFCMainClient.isgerman()?"Dateigröße von \"":"file size of \"").concat(this.getTitle()).concat("\" = ").concat(iBytesMax.toString()).concat(" Bytes").concat(" ~ ").concat(Long.toString((iBytesMax/1024)).concat(" KiB")).concat(" ~ ").concat(Long.toString((iBytesMax/1024/1024)).concat(" MiB")));

			byte[] bytes = new byte[4096];
			Integer iBytesRead = 1;
			String sOldURL = JFCMainClient.szDLSTATE.concat(this.sURL);
			String sNewURL = "";

			// adjust blocks of percentage to output - larger files are shown with smaller pieces
			Integer iblocks = 10; if (iBytesMax>20*1024*1024) iblocks=4; if (iBytesMax>32*1024*1024) iblocks=2; if (iBytesMax>56*1024*1024) iblocks=1;
			while (!this.bisinterrupted && iBytesRead>0) {
				iBytesRead = this.binaryreader.read(bytes);
				iBytesReadSum += iBytesRead;
				// drop a line every x% of the download
				if ( (((iBytesReadSum*100/iBytesMax) / iblocks) * iblocks) > iPercentage ) {
					iPercentage = (((iBytesReadSum*100/iBytesMax) / iblocks) * iblocks);
					sNewURL = JFCMainClient.szDLSTATE.concat("(").concat(Long.toString(iPercentage).concat(" %) ").concat(this.sURL));
					JFCMainClient.exchangeYTURLInList(sOldURL, sNewURL);
					sOldURL = sNewURL ;
				}
				// TODO calculate and show ETA for bigger downloads (remaining time > 60s) - every 20%?

				try {fos.write(bytes,0,iBytesRead);} catch (IndexOutOfBoundsException ioob) {}
				this.bisinterrupted = JFCMainClient.getbQuitrequested(); // try to get information about application shutdown
			} // while

			JFCMainClient.exchangeYTURLInList(sNewURL, JFCMainClient.szDLSTATE.concat(this.sURL));

			// rename files if download was interrupted before completion of download
			if (this.bisinterrupted && iBytesReadSum<iBytesMax) {
				try {
					// this part is especially for our M$-Windows users because of the different behavior of File.renameTo() in contrast to non-windows
					// see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213298  and others
					// even with Java 1.6.0_22 the renameTo() does not work directly on M$-Windows!
					fos.close();
				} catch (Exception e) {
				}
//				System.gc(); // we don't have to do this but to be sure the file handle gets released we do a thread sleep
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}

				// this part runs on *ix platforms without closing the FileOutputStream explicitly
				this.httpclient.getConnectionManager().shutdown(); // otherwise binaryreader.close() would cause the entire datastream to be transmitted
				debugoutput(String.format("download canceled. (%d)",(iBytesRead)));
				changeFileNamewith("CANCELED.");
				String smsg = "renaming unfinished file to: ".concat( this.getFileName() );
				output(smsg); debugoutput(smsg);

				// CANCELED filenames overwrite others as we do not test for CANCELED one, two...
				if (!f.renameTo(new File( this.getFileName()))) {
					smsg = "error renaming unfinished file to: ".concat( this.getFileName() );
    				output(smsg); debugoutput(smsg);
				}
			}
			debugoutput("done writing.");
		} catch (FileNotFoundException fnfe) {
			throw(fnfe)		;
		} catch (IOException ioe) {
			debugoutput("IOException");
			throw(ioe);
		} finally {
			this.sVideoURL = null;
			try {
				fos.close();
			} catch (Exception e) {
			}
            try {
				this.textreader.close();
			} catch (Exception e) {
			}
            try {
				this.binaryreader.close();
			} catch (Exception e) {
			}
		} // try
	} // savebinarydata()

	void changeFileNamewith(String string) {
		File f = null;
		Integer idupcount = 0;
		String sfilesep = System.getProperty("file.separator");
		if (sfilesep.equals("\\")) sfilesep += sfilesep; // on m$-windows we need to escape the \

		String sdirectorychoosed="";
		String[] srenfilename = this.getFileName().split(sfilesep);

		try {
			for (int i = 0; i < srenfilename.length-1; i++) {
				sdirectorychoosed += srenfilename[i].concat((i<srenfilename.length-1)?sfilesep:""); // constructing folder where file is saved now (could be changed in GUI already)
			}
		} catch (ArrayIndexOutOfBoundsException aioobe) {}

		String sfilename = srenfilename[srenfilename.length-1];
		debugoutput("changeFileNamewith() sfilename: ".concat(sfilename));
		do {
			 // filename will be prepended with a parameter string and possibly a duplicate counter
			f = new File(sdirectorychoosed, string.concat((idupcount>0?"(".concat(idupcount.toString()).concat(")"):"")).concat(sfilename));
			idupcount += 1;
		} while (f.exists());

		debugoutput("changeFileNamewith() new filename: ".concat(f.getAbsolutePath()));
		this.setFileName(f.getAbsolutePath());

	} // changeFileNamewith

	String getProxy() {
		String sproxy = JFCMainClient.sproxy;
		if (sproxy==null) return(""); else return(sproxy);
	} // getProxy()

	String getURI(String sURL) {
		String suri = "/".concat(sURL.replaceFirst(JFCMainClient.szYTHOSTREGEX, ""));
		return(suri);
	} // getURI

	String getHost(String sURL) {
		String shost = sURL.replaceFirst(JFCMainClient.szYTHOSTREGEX, "");
		shost = sURL.substring(0, sURL.length()-shost.length());
		shost = shost.toLowerCase().replaceFirst("http[s]?://", "").replaceAll("/", "");
		return(shost);
	} // gethost

	String getTitle() {
		if (this.sTitle != null) return this.sTitle; else return("");
	}

	void setTitle(String sTitle) {
		this.sTitle = sTitle;
	}

	String getFileName() {
		if (this.sFileName != null) return this.sFileName; else return("");
	}

	void setFileName(String sFileName) {
		this.sFileName = sFileName;
	}

	synchronized void debugoutput (String s) {
		if (!JFCMainClient.getbDEBUG())
			return;
		// sometimes this happens:  Exception in thread "Thread-2" java.lang.Error: Interrupted attempt to aquire write lock (on quit only)
		try {
			JFCMainClient.addTextToConsole("#DEBUG ".concat(this.getMyName()).concat(" ").concat(s));
		} catch (Exception e) {
			try { Thread.sleep(50); } catch (InterruptedException e1) {}
			try { JFCMainClient.addTextToConsole("#DEBUG ".concat(this.getMyName()).concat(" ").concat(s)); } catch (Exception e2) {}
		}
	} // debugoutput

	void output (String s) {
		if (JFCMainClient.getbDEBUG())
			return;
		JFCMainClient.addTextToConsole("#info - ".concat(s));
	} // output

	String getMyName() {
		return this.getClass().getName().concat(Integer.toString(this.iThreadNo));
	} // getMyName()

	/*public void setbDEBUG(boolean bDEBUG) {
		this.bDEBUG = bDEBUG;
	} // setbDEBUG*/

	public void run() {
		boolean bDOWNLOADOK = false;
		while (!this.bisinterrupted) {
			try {
				synchronized (JFCMainClient.dlm) {
//					debugoutput("going to sleep.");
					JFCMainClient.dlm.wait(1000); // check for new URLs (if they got pasted faster than threads removing them)
//					debugoutput("woke up ".concat(this.getClass().getName()));
					this.bisinterrupted = JFCMainClient.getbQuitrequested(); // if quit was pressed while this threads works it would not get the InterruptedException and therefore prevent application shutdown

//					debugoutput("URLs remain in list: ".concat(Integer.toString(JFCMainClient.dlm.size())));
					// running in CLI mode?
					if (JFCMainClient.frame == null) {
						if (JFCMainClient.dlm.size() == 0) {
							debugoutput(this.getMyName().concat(" ran out of work."));
							if (YTDownloadThread.iThreadcount == 0) {
								// this is the last DownloadThread so shutdown Application as well
								debugoutput("all DownloadThreads ended. shuting down ytd2.");
								JFCMainClient.shutdownAppl();
							} else {
								// this is not the last DownloadThread so shutdown this thread only
								this.bisinterrupted = true;
								debugoutput("end this thread.");
								throw new NullPointerException("end this thread.");
							}
						}
					}

					this.sURL = JFCMainClient.getfirstURLFromList();
					output((JFCMainClient.isgerman()?"versuche herunterzuladen: ":"try to download: ").concat(this.sURL));
					JFCMainClient.removeURLFromList(this.sURL);
				} // sync dlm
				if (JFCMainClient.frame != null) // only if we have a GUI window insert "downloading" text
					JFCMainClient.addYTURLToList(JFCMainClient.szDLSTATE.concat(this.sURL));

				this.bNODOWNLOAD = JFCMainClient.getbNODOWNLOAD(); // copy ndl-state because this thread should end with a complete file (and report so) even if someone switches to no-download before this thread is finished

				// download one webresource and show result
				bDOWNLOADOK = downloadone(this.sURL); this.iRecursionCount=-1;
				if (bDOWNLOADOK && !this.bNODOWNLOAD)
					output((JFCMainClient.isgerman()?"fertig heruntergeladen: ":"download complete: ").concat("\"").concat(this.getTitle()).concat("\"").concat(" to ").concat(this.getFileName()));
				else
					output((JFCMainClient.isgerman()?"Nicht heruntergeladen: ":"not downloaded: ").concat("\"").concat(this.getTitle()).concat("\"")); // not downloaded does not mean it was erroneous

				// running in CLI mode?
				if (JFCMainClient.frame == null)
					JFCMainClient.removeURLFromList(this.sURL);
				else
					JFCMainClient.removeURLFromList(JFCMainClient.szDLSTATE.concat(this.sURL));
				// notify download complete
				eventDispatcher.threadNumberChanged(JFCMainClient.dlm.size());
			} catch (InterruptedException e) {
				this.bisinterrupted = true;
			} catch (NullPointerException npe) {
//				debugoutput("npe - nothing to download?");
			} catch (Exception e) {
				e.printStackTrace();
			} // try
		} // while
		debugoutput("thread ended: ".concat(this.getMyName()));
		YTDownloadThread.iThreadcount--;
	} // run()

} // class YTDownloadThread


text:
/**
 * @private
 */
Ext.define('Ext.device.storage.Cordova', {
    alternateClassName: 'Ext.device.storage.PhoneGap',

    extend: 'Ext.device.storage.HTML5.HTML5'
});

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

@Component({
  selector: 'app-task-edit-dialog',
  templateUrl: './task-edit-dialog.component.html',
  styleUrls: ['./task-edit-dialog.component.css']
})
export class TaskEditDialogComponent implements OnInit {

    constructor(public dialogRef: MatDialogRef<TaskEditDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any) { }

    onNoClick(): void {
        this.dialogRef.close();
    }

    ngOnInit() {
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>REU Site: Incentive-Centered Design for Cyberinfrastructure</AwardTitle>
    <AwardEffectiveDate>04/01/2008</AwardEffectiveDate>
    <AwardExpirationDate>03/31/2012</AwardExpirationDate>
    <AwardAmount>286743</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      04050000
      <Directorate>
        <LongName>Direct For Social, Behav & Economic Scie</LongName>
      </Directorate>
      <Division>
        <LongName>Divn Of Social and Economic Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Fahmida N. Chowdhury</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>Intellectual Merit:<br/>This REU Site award to the University of Michigan's School of Information is dedicated to furthering undergraduate intellectual growth and preparing them for careers at the intersection of the social sciences and information technology in incentive-centered design for cyberinfrastructure. They will conduct research in some of the country's leading information laboratories. Performance of distributed and collaborative systems critically depends on interactions, yet such interactions are often ineffective and inefficient. this training will address these inefficiencies.<br/>Broader Impact:<br/>Partnerships with various organizations and with Wayne State will assist in recruitment of women, underrepresented minorities and students from institutions with limited research programs.</AbstractNarration>
    <MinAmdLetterDate>04/08/2008</MinAmdLetterDate>
    <MaxAmdLetterDate>04/08/2008</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0755147</AwardID>
    <Investigator>
      <FirstName>Jeffrey</FirstName>
      <LastName>MacKie-Mason</LastName>
      <EmailAddress>jmm@umich.edu</EmailAddress>
      <StartDate>04/08/2008</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Yan</FirstName>
      <LastName>Chen</LastName>
      <EmailAddress>yanchen@umich.edu</EmailAddress>
      <StartDate>04/08/2008</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>University of Michigan Ann Arbor</Name>
      <CityName>Ann Arbor</CityName>
      <ZipCode>481091274</ZipCode>
      <PhoneNumber>7347636438</PhoneNumber>
      <StreetAddress>3003 South State St. Room 1062</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Michigan</StateName>
      <StateCode>MI</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
package eu.the5zig.mod.server;

/**
 * Represents the result of a matched pattern.
 */
public interface IPatternResult {

	/**
	 * @return the size of the result.
	 */
	int size();

	/**
	 * Gets a matched group at the specified index.
	 *
	 * @param index the index.
	 * @return a matched group at the specified index or an empty string, in the index exceeds the total group count.
	 */
	String get(int index);

	/**
	 * Allows you to ignore the matched message.
	 *
	 * @param ignore true, if the matched message should be ignored.
	 * @since 1.0.1
	 */
	void ignoreMessage(boolean ignore);

}


text:
<?php

namespace Stitcher\Page\Adapter;

use Stitcher\Exception\InvalidCollectionAdapter;
use Stitcher\File;
use Stitcher\Page\Adapter;
use Stitcher\Configureable;
use Stitcher\Variable\VariableParser;
use Symfony\Component\Yaml\Yaml;

class CollectionAdapter implements Adapter, Configureable
{
    /** @var null */
    private static $filterId;

    /** @var array */
    private $entries = [];

    /** @var mixed */
    private $parameter;

    /** @var mixed */
    private $variable;

    /** @var \Stitcher\Variable\VariableParser */
    private $variableParser;

    public function __construct(
        array $adapterConfiguration,
        VariableParser $variableParser
    ) {
        if (! $this->isValidConfiguration($adapterConfiguration)) {
            throw InvalidCollectionAdapter::create();
        }

        $this->variable = $adapterConfiguration['variable'];
        $this->parameter = $adapterConfiguration['parameter'];
        $this->variableParser = $variableParser;
    }

    public static function make(
        array $adapterConfiguration,
        VariableParser $variableParser
    ): CollectionAdapter {
        return new self($adapterConfiguration, $variableParser);
    }

    public static function setFilterId(?string $filterId)
    {
        self::$filterId = $filterId;
    }

    public function transform(array $pageConfiguration): array
    {
        $this->entries = $this->getEntries($pageConfiguration);

        $collectionPageConfiguration = [];

        while ($entry = current($this->entries)) {
            $entryId = key($this->entries);

            if (self::$filterId !== null && self::$filterId != $entryId) {
                next($this->entries);

                continue;
            }

            foreach ($entry as $field => $value) {
                $entry[$field] = $this->variableParser->parse($value);
            }

            $entryConfiguration = $this->createEntryConfiguration(
                $pageConfiguration,
                $entryId,
                $entry
            );

            $collectionPageConfiguration[$entryConfiguration['id']] = $entryConfiguration;

            next($this->entries);
        }

        return $collectionPageConfiguration;
    }

    public function isValidConfiguration($subject): bool
    {
        return \is_array($subject) && isset($subject['variable']) && isset($subject['parameter']);
    }

    protected function getEntries($pageConfiguration): ?array
    {
        $variable = $pageConfiguration['variables'][$this->variable] ?? null;

        $entries = Yaml::parse(File::read($variable));

        foreach ($entries as $id => $data) {
            $data['id'] = $data['id'] ?? $id;

            $entries[$id] = $data;
        }

        return $entries;
    }

    protected function createEntryConfiguration(array $pageConfiguration, $entryId, $entry): array
    {
        $entryConfiguration = $pageConfiguration;

        $parsedEntryId = str_replace('{' . $this->parameter . '}', $entryId, $pageConfiguration['id']);

        $entryConfiguration['id'] = $parsedEntryId;

        $entryConfiguration['variables'][$this->variable] = $entry;

        $entryConfiguration['variables']['meta'] = array_merge(
            $entryConfiguration['variables']['meta'] ?? [],
            $this->createMetaVariable($entryConfiguration)
        );

        $entryConfiguration['variables']['_browse'] =
            $entryConfiguration['variables']['_browse']
            ?? $this->createBrowseData();

        unset($entryConfiguration['config']['collection']);

        return $entryConfiguration;
    }

    protected function createMetaVariable(array $entryConfiguration): array
    {
        $meta = [];

        if ($title = $this->getTitleMeta($entryConfiguration)) {
            $meta['title'] = $title;
        }

        if ($description = $this->getDescriptionMeta($entryConfiguration)) {
            $meta['description'] = $description;
        }

        return $meta;
    }

    protected function getTitleMeta(array $entryConfiguration): ?string
    {
        $title =
            $entryConfiguration['variables'][$this->variable]['meta']['title']
            ?? $entryConfiguration['variables'][$this->variable]['title']
            ?? null;

        return $title;
    }

    protected function getDescriptionMeta(array $entryConfiguration): ?string
    {
        $description =
            $entryConfiguration['variables'][$this->variable]['meta']['description']
            ?? $entryConfiguration['variables'][$this->variable]['description']
            ?? null;

        return $description;
    }

    protected function createBrowseData(): array
    {
        $browse = [];

        $prev = prev($this->entries);

        if (! $prev) {
            reset($this->entries);
        } else {
            $browse['prev'] = $prev;

            next($this->entries);
        }

        $next = next($this->entries);

        if ($next) {
            $browse['next'] = $next;
        }

        prev($this->entries);

        return $browse;
    }
}


text:
impac.widget.sales_aged.settings.title

      <button class="btn btn-default" ng-click="initSettings()" translate>impac.widget.sales_aged.cancel</button>
      <button class="btn btn-warning" ng-click="updateSettings()" translate>impac.widget.sales_aged.save</button>

{{'impac.widget.sales_aged.from' | translate}} {{widget.content.dates[0] | momentDate : widget.metadata.hist_parameters.period}} {{'impac.widget.sales_aged.to' | translate}} {{getLastDate() | momentDate : widget.metadata.hist_parameters.period}}

 0" class="clearfix dashed">

                  {{date}}

                  {{getTotal($index) | mnoCurrency : widget.content.currency}}

                  {{getTotal($index)}}

            {{date}}

            {{getTotal($index) | mnoCurrency : widget.content.currency}}

            {{getTotal($index)}}


text:
package improving

import scala.collection._

/** A trait representing zero.
 *
 * @author Paul Phillips (standing on the shoulders of giants)
 * @since 2.8
 */

trait Zero[+Z] {
  val zero: Z
}

object Zero {
  def apply[Z](implicit z: Zero[Z])   = z.zero
  def zero[Z](z: Z)                   = new Zero[Z] { val zero = z }

  implicit object UnitZero extends Zero[Unit] { val zero = () }
  implicit object StringZero extends Zero[String] { val zero = "" }
  implicit object BooleanZero extends Zero[Boolean] { val zero = false }
  implicit object ByteZero extends Zero[Byte] { val zero = 0.toByte }
  implicit object ShortZero extends Zero[Short] { val zero = 0.toShort }
  implicit object IntZero extends Zero[Int] { val zero = 0 }
  implicit object LongZero extends Zero[Long] { val zero = 0l }
  implicit object CharZero extends Zero[Char] { val zero = 0.toChar }
  implicit object FloatZero extends Zero[Float] { val zero = 0f }
  implicit object DoubleZero extends Zero[Double] { val zero = 0d }
  implicit object BigIntZero extends Zero[BigInt] { val zero = BigInt(0) }
  implicit object BigDecimalZero extends Zero[BigDecimal] { val zero = BigDecimal(0) }

  implicit def OptionZero[A] = zero[Option[A]](None)

  implicit def TraversableZero[A] = zero[Traversable[A]](Traversable.empty)
  implicit def IterableZero[A] = zero[Iterable[A]](Iterable.empty)
  implicit def SeqZero[A] = zero[Seq[A]](Seq.empty)
  implicit def VectorZero[A] = zero[Vector[A]](Vector.empty)

  implicit def ArrayZero[A: ClassManifest] = zero(new Array[A](0))
  implicit def ListZero[A] = zero[List[A]](Nil)
  implicit def StreamZero[A] = zero[Stream[A]](Stream.empty)

  implicit def SetZero[A] = zero[Set[A]](Set.empty)
  implicit def MapZero[A,B] = zero[Map[A,B]](Map.empty)
}


text:
#pragma once

#include <thread>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <memory>

using atomic_int = std::atomic<int>;

using ThreadID = std::thread::id;

// Mutual exclusion
using Mutex = std::mutex;
using OwnerLock = std::recursive_mutex;

// Synchronization
using CondLock = std::condition_variable_any;

using ScopeLock = std::lock_guard<Mutex>;
using ScopeOwnerLock = std::lock_guard<OwnerLock>;

// Number of available cores
inline unsigned int GetNumCores()
{
	return std::thread::hardware_concurrency();
}

// Wrapper around C++11 threads that makes them nicer to use
class Thread
{
	std::thread* ActualThread;

protected:
	void Yield( unsigned int TimesToYield = 1 );

public:
	Thread();
	Thread( Thread& T ) = delete;
	~Thread();

	/** The function that runs in the thread */
	virtual void Main() = 0;
	void Start();
	void Join();
	ThreadID ID();

	Thread& operator=( Thread& T ) = delete;
};

/** Construct and start a new thread of the provided type */
template<typename ThreadType, typename... Args>
std::unique_ptr<ThreadType> CreateThread(Args&&... args)
{
	std::unique_ptr<ThreadType> NewThread(
		std::make_unique<ThreadType>(std::forward<decltype(args)>(args)...)
		);
	NewThread->Start();
	return NewThread;
}

// The current thread will sleep for the provided number of microseconds
void SleepMicro(unsigned int Microseconds);

// Used for testing thread features
class TestThread : public Thread
{
	int a, b, c;
public:
	TestThread(int a, int b, int c) : a(a), b(b), c(c) {}

	virtual void Main() override
	{
		Yield(100);
		//std::cout << "Test";
	}
};


text:
package testdata

import "strconv"

func (c Celsius) String() string {
	return strconv.Itoa(int(c))
}

func (f Fahrenheit) String() string {
	return strconv.Itoa(int(f))
}


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="js">
            <block class="Magento\Backend\Block\Template" name="decimal_attribute_edit_js" template="Part_Decimal::catalog/product/attribute/js.phtml" after="attribute_edit_js"/>
        </referenceContainer>
    </body>
</page>


text:
describe "/users/{username}/roles/subject-coordinator/schedules" do
  before do
    # The released version of NU480
    @nu480 = create_study 'NU480' do |s|
      s.planned_calendar do |cal|
        cal.epoch "Treatment" do |e|
          e.study_segment "A" do |a|
            a.period "P1", :start_day => 2, :duration => [4, :day], :repetitions => 2 do |p|
              p.activity "Rituximab", 4
              p.activity "Alcohol", 4
            end
          end
        end
      end
    end

    # The released version of ECOG170
    @ecog170 = create_study 'ECOG170' do |s|
      s.planned_calendar do |cal|
        cal.epoch "Followup" do |e|
          e.study_segment "B" do |a|
            a.period "P2", :start_day => 2, :duration => [3, :day], :repetitions => 1 do |p|
              p.activity "Lab Test", 1
              p.activity "Physical Test", 2
            end
          end
        end
      end
    end
    #create a studysites
    @studySites = [
       @studySite1 = PscTest::Fixtures.createStudySite(@nu480, northwestern),
       @studySite2 = PscTest::Fixtures.createStudySite(@ecog170, northwestern)
    ]
    @studySites.each do |ss|
       application_context['studySiteDao'].save(ss)
    end

    #approve an existing amendment
    @approve_date = PscTest.createDate(2008, 12, 20)
    @studySite1.approveAmendment(@nu480.amendment, @approve_date)
    @studySite2.approveAmendment( @ecog170.amendment, @approve_date)
    application_context['studySiteDao'].save(@studySite1)
    application_context['studySiteDao'].save(@studySite2)

    #create subject
    @subject1 = PscTest::Fixtures.createSubject("ID001", "Alan", "Boyarski", PscTest.createDate(1983, 3, 23))
    @subject2 = PscTest::Fixtures.createSubject("ID002", "Perry", "Carl", PscTest.createDate(1978, 4, 17))
    @subject3 = PscTest::Fixtures.createSubject("ID003", "Art", "Kelly", PscTest.createDate(1975, 6, 12))

    #create a study subject assignment
    @studySegment1 = @nu480.plannedCalendar.epochs.first.studySegments.first
    @studySegment2 = @ecog170.plannedCalendar.epochs.first.studySegments.first
    @studySubjectAssignments= [
      @studySubjectAssignment1 = application_context['subjectService'].assignSubject(
        @studySite1,
        Psc::Service::Presenter::Registration::Builder.new.
          subject(@subject1).first_study_segment(@studySegment1).
          date(PscTest.createDate(2008, 12, 26)).manager(erin).
          to_registration),
      @studySubjectAssignment2 = application_context['subjectService'].assignSubject(
        @studySite2,
        Psc::Service::Presenter::Registration::Builder.new.
          subject(@subject1).first_study_segment(@studySegment2).
          date(PscTest.createDate(2008, 12, 28)).manager(erin).
          to_registration),
      @studySubjectAssignment3 = application_context['subjectService'].assignSubject(
        @studySite2,
        Psc::Service::Presenter::Registration::Builder.new.
          subject(@subject2).first_study_segment(@studySegment2).
          date(PscTest.createDate(2008, 12, 28)).manager(erin).
          to_registration),
      @studySubjectAssignment4 = application_context['subjectService'].assignSubject(
        @studySite1,
        Psc::Service::Presenter::Registration::Builder.new.
          subject(@subject3).first_study_segment(@studySegment1).
          date(PscTest.createDate(2008, 12, 26)).manager(juno).
          to_registration)
    ]
    @studySubjectAssignments.each do |ssa|
      application_context['studySubjectAssignmentDao'].save(ssa)
    end
  end

  describe "GET" do
    describe "SCTB's own schedules" do
      describe "xml" do
        before do
          get "/users/erin/managed-schedules", :as => :erin
        end

        it "is successful" do
          response.status_code.should == 200
        end

        it "is XML" do
          response.content_type.should == 'text/xml'
        end

        it "has the right number of assignments" do
          response.xml_elements('//subject-assignment').should have(3).elements
        end

        it "has the right number of activities" do
          response.xml_elements('//scheduled-activity').should have(8).activities
        end
      end

      describe "json" do
        before do
          get "/users/erin/managed-schedules.json", :as => :erin
        end

        it "is successful" do
          response.status_code.should == 200
        end

        it "is XML" do
          response.content_type.should == 'application/json'
        end

        it "has the right number of activities" do
          response.json["days"].inject(0) { |sum, (_, day)| sum + day["activities"].size }.should == 8
        end

        it "[days][date][activities][each activity] contains subject name" do
          response.json["days"]['2008-12-28']['activities'][0]["subject"].should == "Alan Boyarski"
        end

        it "[study_segments] contains subject name" do
          @subjects = response.json["study_segments"].sort_by { |s| s["subject"] }
          @subjects[0]["subject"].should == "Alan Boyarski"
        end

      end

      describe "ics" do
        before do
          get "/users/erin/managed-schedules.ics", :as => :erin
        end

        it "is successful" do
          response.status_code.should == 200
        end

        it "is ICS calendar" do
          response.content_type.should == 'text/calendar'
        end

        it "has the right number of events" do
          response.calendar.events.size.should == 8
        end

        describe "event" do
          it 'has the Summary property' do
            response.calendar.events[0].summary.should == "Alan Boyarski/ECOG170/Lab Test"
          end
        end
      end
    end

    describe "collegue schedules" do
        describe "xml" do
          before do
            get "/users/juno/managed-schedules", :as => :erin
          end

          it "has the right number of assignments" do
            response.xml_elements('//subject-assignment').should have(1).elements
          end

          it "has the right number of activities" do
            response.xml_elements('//scheduled-activity').should have(4).activities
          end
        end

        describe "json" do
          before do
            get "/users/juno/managed-schedules.json", :as => :erin
          end

          it "has the right number of activities" do
            response.json["days"].inject(0) { |sum, (_, day)| sum + day["activities"].size }.should == 4
          end
        end

        describe "ics" do
          before do
            get "/users/juno/managed-schedules.ics", :as => :erin
          end

          it "has the right number of events" do
            response.calendar.events.size.should == 4
          end

          describe "event" do
            it 'has the Summary property' do
              response.calendar.events[0].summary.should == "Art Kelly/NU480/Rituximab"
            end
          end
        end
    end

    it "forbids access to schedules other than by SCTB, STA, DR" do
      get "/users/erin/managed-schedules", :as => :alice
      response.status_code.should == 403
    end

    it "404s for non-existent users" do
      get "/users/unknown/managed-schedules", :as => :erin
      response.status_code.should == 404
    end
  end
end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class PHP_ConfigReport_Runner_Cli</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

 PHP_ConfigReport_Runner_Cli

Description

					Description |
													Vars (details)
						|											Methods (details)

Command line runner

author: Jean-Marc Fontaine <jm@jmfontaine.net>

copyright: 2010-2011 Jean-Marc Fontaine <jm@jmfontaine.net>

license: BSD License

			Located in /Runner/Cli.php (line 50)

PHP_ConfigReport_Runner_Abstract
   |
   --PHP_ConfigReport_Runner_Cli

Variable Summary

			Description |
						Vars (details)
							|
									Methods (details)

					static mixed
					$_consoleInput

					static mixed
					$_consoleOutput

Method Summary

			Description |
																		Vars (details)

				|
						Methods (details)

											static void
										displayDebug
											(string $message)

											static void
										displayError
											(string $message)

											static void
										displayHelp
										()

											static void
										displayMessage
											(string $message, [string $type = 'info'])

											static void
										displayVersion
										()

											static void
										getConsoleInput
										()

											static void
										getConsoleOutput
										()

											static void
										run
										()

Variables

			Description |
										Vars (details)

										|
									Methods (details)

			static mixed
			$_consoleInput
						(line 58)

Command line argument parser

see: http://ezcomponents.org/docs/api/trunk/ConsoleTools/ezcConsoleInput.html

access: protected

			static mixed
			$_consoleOutput
						(line 66)

Object used for display in command line

see: http://ezcomponents.org/docs/api/trunk/ConsoleTools/ezcConsoleOutput.html

access: protected

Methods

			Description |
															Vars (details)
														Methods (details)

		static displayDebug (line 218)

Displays debug informations

access: public

		void

			displayDebug

					(string $message)

				string
				$message: Message to display

		static displayError (line 229)

Displays errors

access: public

		void

			displayError

					(string $message)

				string
				$message: Message to display

		static displayHelp (line 239)

Displays help informations

access: public

		void

			displayHelp

				()

		static displayMessage (line 270)

Displays messages

access: public

		void

			displayMessage

					(string $message, [string $type = 'info'])

				string
				$message: Message to display

				string
				$type: Type of the message

		static displayVersion (line 288)

Displays version informations

access: public

		void

			displayVersion

				()

		static getConsoleInput (line 297)

access: public

		void

			getConsoleInput

				()

		static getConsoleOutput (line 302)

access: public

		void

			getConsoleOutput

				()

		static run (line 73)

Main function. Sets up the environment and coordinate the work.

access: public

		void

			run

				()

		Documentation generated on Sun, 23 Jan 2011 16:23:55 +0100 by phpDocumentor 1.4.3


text:
supports
  * indiegala
  * steamgifts

updated randomly

changes massively when it is updated

:)


text:
  do {                                  \
    const tc::Error& status__ = (S);    \
    if (!status__.IsOk()) {             \
      return Error(status__.Message()); \
    }                                   \
  } while (false)

namespace tc = triton::client;
namespace cb = triton::perfanalyzer::clientbackend;
namespace ts = triton::perfanalyzer::clientbackend::torchserve;

namespace triton { namespace perfanalyzer { namespace clientbackend {
namespace torchserve {

//==============================================================================
/// TorchServeClientBackend is used to generate load on the Torchserve isntance
///
class TorchServeClientBackend : public ClientBackend {
 public:
  /// Create a torchserve client backend which can be used to interact with the
  /// server.
  /// \param url The inference server url and port.
  /// \param protocol The protocol type used.
  /// \param http_headers Map of HTTP headers. The map key/value indicates
  /// the header name/value.
  /// \param verbose Enables the verbose mode.
  /// \param client_backend Returns a new TorchServeClientBackend
  /// object.
  /// \return Error object indicating success or failure.
  static Error Create(
      const std::string& url, const ProtocolType protocol,
      std::shared_ptr<Headers> http_headers, const bool verbose,
      std::unique_ptr<ClientBackend>* client_backend);

  /// See ClientBackend::Infer()
  Error Infer(
      cb::InferResult** result, const InferOptions& options,
      const std::vector<InferInput*>& inputs,
      const std::vector<const InferRequestedOutput*>& outputs) override;

  /// See ClientBackend::ClientInferStat()
  Error ClientInferStat(InferStat* infer_stat) override;

 private:
  TorchServeClientBackend(std::shared_ptr<Headers> http_headers)
      : ClientBackend(BackendKind::TORCHSERVE), http_headers_(http_headers)
  {
  }

  void ParseInferStat(
      const tc::InferStat& torchserve_infer_stat, InferStat* infer_stat);

  std::unique_ptr<ts::HttpClient> http_client_;
  std::shared_ptr<Headers> http_headers_;
};

//==============================================================
/// TorchServeInferResult is a wrapper around InferResult object of
/// torchserve InferResult object.
///
class TorchServeInferResult : public cb::InferResult {
 public:
  explicit TorchServeInferResult(ts::InferResult* result);
  /// See InferResult::Id()
  Error Id(std::string* id) const override;
  /// See InferResult::RequestStatus()
  Error RequestStatus() const override;
  /// See InferResult::RawData()
  Error RawData(
      const std::string& output_name, const uint8_t** buf,
      size_t* byte_size) const override;

 private:
  std::unique_ptr<ts::InferResult> result_;
};

}}}}  // namespace triton::perfanalyzer::clientbackend::torchserve


text:
<?php
/**
 * Created by PhpStorm.
 * User: Exodus 4D
 * Date: 30.12.2018
 * Time: 01:09
 */

namespace Exodus4D\ESI\Lib\Stream;

use GuzzleHttp\Psr7\StreamDecoratorTrait;

class JsonStream implements JsonStreamInterface {

    // we need to "overwrite" the default Trait getContents() method
    // -> therefore we make it accessible as traitGetContents() and call it from
    // the new getContents() method
    use StreamDecoratorTrait {
        StreamDecoratorTrait::getContents as traitGetContents;
    }

    /**
     * @return mixed|string|null
     */
    public function getContents(){
        $contents = $this->traitGetContents();

        if($contents === ''){
            return null;
        }
        $decodedContents = \GuzzleHttp\json_decode($contents);

        if(json_last_error() !== JSON_ERROR_NONE){
            throw new \RuntimeException('Error trying to decode response: ' . json_last_error_msg());
        }

        return $decodedContents;
    }

    /**
     * we need to overwrite this because of Trait __toString() calls $this->Contents() which no longer returns a string
     * @return string
     */
    public function __toString(){
        try {
            if($this->isSeekable()){
                $this->seek(0);
            }
            return $this->traitGetContents();
        }catch (\Exception $e){
            // Really, PHP? https://bugs.php.net/bug.php?id=53648
            trigger_error('StreamDecorator::__toString exception: '
                . (string) $e, E_USER_ERROR);
            return '';
        }
    }
}


text:
<?php
/**
 * @package WPSEO
 */

/**
 * Represents a post's primary term
 */
class WPSEO_Primary_Term {

	/**
	 * @var string
	 */
	protected $taxonomy_name;

	/**
	 * @var int
	 */
	protected $post_ID;

	/**
	 * The taxonomy this term is part of
	 *
	 * @param string $taxonomy_name Taxonomy name for the term.
	 * @param int    $post_ID       Post ID for the term.
	 */
	public function __construct( $taxonomy_name, $post_ID ) {
		$this->taxonomy_name = $taxonomy_name;
		$this->post_ID = $post_ID;
	}

	/**
	 * Returns the primary term ID
	 *
	 * @return int|bool
	 */
	public function get_primary_term() {
		$primary_term = get_post_meta( $this->post_ID, WPSEO_Meta::$meta_prefix . 'primary_' . $this->taxonomy_name, true );

		$terms = $this->get_terms();

		if ( ! in_array( $primary_term, wp_list_pluck( $terms, 'term_id' ) ) ) {
			$primary_term = false;
		}

		// By default the first term (sorted by ID) is the primary term.
		if ( ! $primary_term ) {

			if ( ! empty( $terms ) ) {
				usort( $terms, '_usort_terms_by_ID' );
				$primary_term = array_shift( $terms );
				$primary_term = $primary_term->term_id;
			}
		}

		$primary_term = (int) $primary_term;
		return ( $primary_term ) ? ( $primary_term ) : false;
	}

	/**
	 * Sets the new primary term ID
	 *
	 * @param int $new_primary_term New primary term ID.
	 */
	public function set_primary_term( $new_primary_term ) {
		update_post_meta( $this->post_ID, WPSEO_Meta::$meta_prefix . 'primary_' . $this->taxonomy_name, $new_primary_term );
	}

	/**
	 * Get the terms for the current post ID.
	 * When $terms is not an array, set $terms to an array.
	 *
	 * @return array
	 */
	protected function get_terms() {
		$terms = get_the_terms( $this->post_ID, $this->taxonomy_name );

		if ( ! is_array( $terms ) ) {
			$terms = array();
		}

		return $terms;
	}
}


text:
package Models;

import Beans.LoggedIn;

import Util.DBConnection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author Sophia
 */
public class AllUsersModel {

    public boolean createUser (int userid, String password, int isadmin, int outletref)
    {
        Connection con;
        Statement statement = null;

        try
        {
            con = DBConnection.createConnection();
            statement = con.createStatement();

            String query = "INSERT INTO users " + "VALUES ('"+userid+"',"+password+","+isadmin+","+outletref+")";

            statement.executeUpdate(query);

            statement.close();
            con.close();

            return true;
        } catch (SQLException e) {
            System.out.println("Error Executing Query");
            e.printStackTrace();
            return false;
        }
    }

    public LoggedIn[] viewUsers(){

        Connection con;
        Statement statement = null;
        ResultSet resultSet = null;

        LoggedIn[] users = new LoggedIn[30];

        try
        {
            con = DBConnection.createConnection();
            statement = con.createStatement();
            resultSet = statement.executeQuery ("SELECT * FROM users");

            int counter = 0;

            while (resultSet.next())
            {
                LoggedIn user = new LoggedIn();
                user.setUserid(resultSet.getInt("Userid"));
                user.setIsAdmin(resultSet.getInt("IsAdmin"));
                user.setOutletRef(resultSet.getInt("OutletRef"));
                users[counter]=user;
                counter++;
            }

            LoggedIn[] usersSized = new LoggedIn[counter];

            for (int i=0; i<counter; i++){
                    usersSized[i] = users[i];
            }

            resultSet.close();
            statement.close();
            con.close();

            return usersSized;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public boolean editUser(int userid, String password, int isadmin, int outletref){

        Connection con;
        Statement statement = null;

        try
        {
            con = DBConnection.createConnection();
            statement = con.createStatement();
            String query;
            if (password!=null){
                query = "UPDATE users " + "SET Userid="+userid+", Password='"+password+"', IsAdmin="+isadmin+", OutletRef ="+outletref+" WHERE Userid ="+userid;
            }else{
                query = "UPDATE users " + "SET Userid="+userid+", IsAdmin="+isadmin+", OutletRef ="+outletref+" WHERE Userid ="+userid;
            }

            statement.executeUpdate(query);

            statement.close();
            con.close();

            return true;
        } catch (SQLException e) {
            System.out.println("Error Executing Query");
            e.printStackTrace();
            return false;
        }
    }

    public boolean deleteUser(int userid){

        Connection con;
        Statement statement = null;

        try
        {
            con = DBConnection.createConnection();
            statement = con.createStatement();
            String query = "DELETE from users WHERE Userid ="+userid;

            statement.executeUpdate(query);

            statement.close();
            con.close();

            return true;
        } catch (SQLException e) {
            System.out.println("Error Executing Deleting User.");
            e.printStackTrace();
            return false;
        }
    }
}


text: Collection of laboratory assignments from deep learning course


text:
@extends('app')

@section('content')

Delete shift from the schedule: {{ $schedule->shift->name }}

    {!! Form::open() !!}

            Are you sure you want to delete this shift from the schedule? All information including users who have signed up for this shift will be removed.

        <button type="submit" class="btn btn-danger">Delete from the Schedule</button>
        event->id }}" class="btn btn-primary">Cancel
    {!! Form::close() !!}
@endsection


text:
-include ../../run-make-fulldeps/tools.mk

# How to run this
# $ ./x.py clean
# $ ./x.py test --target thumbv6m-none-eabi,thumbv7m-none-eabi src/test/run-make

# Supported targets:
# - thumbv6m-none-eabi (Bare Cortex-M0, M0+, M1)
# - thumbv7em-none-eabi (Bare Cortex-M4, M7)
# - thumbv7em-none-eabihf (Bare Cortex-M4F, M7F, FPU, hardfloat)
# - thumbv7m-none-eabi (Bare Cortex-M3)

# only-thumb

# For cargo setting
RUSTC := $(RUSTC_ORIGINAL)
LD_LIBRARY_PATH := $(HOST_RPATH_DIR)
# We need to be outside of 'src' dir in order to run cargo
WORK_DIR := $(TMPDIR)

HERE := $(shell pwd)

CRATE := cortex-m
CRATE_URL := https://github.com/rust-embedded/cortex-m
CRATE_SHA1 := a448e9156e2cb1e556e5441fd65426952ef4b927 # 0.5.0

# Don't make lints fatal, but they need to at least warn or they break Cargo's target info parsing.
export RUSTFLAGS := --cap-lints=warn

all:
	env
	mkdir -p $(WORK_DIR)
	-cd $(WORK_DIR) && rm -rf $(CRATE)
	cd $(WORK_DIR) && bash -x $(HERE)/../git_clone_sha1.sh $(CRATE) $(CRATE_URL) $(CRATE_SHA1)
	# HACK(eddyb) sets `RUSTC_BOOTSTRAP=1` so Cargo can accept nightly features.
	# These come from the top-level Rust workspace, that this crate is not a
	# member of, but Cargo tries to load the workspace `Cargo.toml` anyway.
	cd $(WORK_DIR) && cd $(CRATE) && env RUSTC_BOOTSTRAP=1 $(BOOTSTRAP_CARGO) build --target $(TARGET) -v


text:
<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylorotwell@gmail.com>
 */

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels nice to relax.
|
*/

require __DIR__.'/../bootstrap/autoload.php';

if (! function_exists('elixir')) {
    /**
     * Get the path to a versioned Elixir file.
     *
     * @param  string  $file
     * @param  string  $buildDirectory
     * @return string
     *
     * @throws \InvalidArgumentException
     */
    function elixir($file, $buildDirectory = 'build')
    {
        static $manifest = [];
        static $manifestPath;

        if (empty($manifest) || $manifestPath !== $buildDirectory) {
            $path = public_path($buildDirectory.'/rev-manifest.json');

            if (file_exists($path)) {
                $manifest = json_decode(file_get_contents($path), true);
                $manifestPath = $buildDirectory;
            }
        }

        $file = ltrim($file, '/');

        if (isset($manifest[$file])) {
            return '/'.trim($buildDirectory.'/'.$manifest[$file], '/');
        }

        $unversioned = public_path($file);

        if (file_exists($unversioned)) {
            return '/'.trim($file, '/');
        }

        throw new InvalidArgumentException("File {$file} not defined in asset manifest.");
    }
}

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);


text:
'use strict';

var _ = require('lodash');

/**
 * class extension function
 *
 * @param {!Function} Child - constructor of child class.
 * @param {!Function} Parent - constructor of parent class.
 * @returns {Function} Child constructor
 */
var extend = function extend (Child, Parent) {
	_.extend(Child, Parent);
	Child.prototype = _.create(Parent.prototype, { constructor: Child });
	Child.__super__ = Parent.prototype;

	return Child;
};

extend.method = function extendMethod (proto, stat) {
	proto || (proto = {});

	var Child;
	var Parent = this;

	if (proto && _.has(proto, 'constructor')) {
		Child = proto.constructor;
	} else {
		Child = function () {
			return Parent.apply(this, arguments);
		};
	}

	extend(Child, Parent);

	_.extend(Child, stat);

	_.extend(Child.prototype, proto);

	return Child;
};

module.exports = extend;


text:
.timeline-status-dialog {
    display: flex;
    flex-direction: column;
    padding: 12px 16px;
    align-self: center;
    background-color: white;
    border: 1px solid lightgrey;
    box-shadow: grey 0 0 14px;
    margin-top: -1px;
}

.status-dialog-line {
    margin: 2px;
    height: 14px;
    display: flex;
    align-items: baseline;
}

.status-dialog-line .label {
    display: inline-block;
    width: 80px;
    text-align: right;
    color: #aaa;
    margin-right: 10px;
}

.timeline-status-dialog .progress .indicator-container {
    display: inline-block;
    width: 200px;
    height: 8px;
    background-color: #f4f4f4;
    display: inline-block;
    margin: 0 10px 0 0;
}

.timeline-status-dialog .progress .indicator {
    background-color: rgb(112, 166, 255);
    height: 100%;
    width: 0;
    margin: 0;
}

.timeline-status-dialog .stop-button {
    margin-top: 8px;
    height: 100%;
    align-self: center;
}


text:
X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X.  Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

### Example:
```
Input: 10
Output: 4
Explanation:
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
```

### Note:
- N  will be in range [1, 10000].

## Solution
### Intuitive Approach
For each number from 1 to N, judge the number digit by digit. Time complexity is O(N * log10 N).

### Dynamic Programming
In the brutal force, some computation for the subproblem is duplicated. For example, N = 112, 11 is already calculated before.

Though, in this problem, the execution time for DP is not faster than brute force, but in theorem it's faster.

#GOOGL

#Dynamic Programming


text:
PsiSigmoid * determine_sigmoid ( char *sigmoid ) {
	if ( !strcmp(sigmoid,"logistic") ) {
		return new PsiLogistic ();
	} else if ( !strcmp(sigmoid,"exp") ) {
		return new PsiExponential ();
	} else if ( !strcmp(sigmoid,"gauss") ) {
		return new PsiGauss ();
	} else if ( !strcmp(sigmoid,"gumbel_l") || !strcmp(sigmoid,"gumbel") || !strcmp(sigmoid,"lgumbel") ) {
		return new PsiGumbelL ();
	} else if ( !strcmp(sigmoid,"gumbel_r") || !strcmp(sigmoid,"rgumbel") ) {
		return new PsiGumbelL();
	} else if ( !strcmp(sigmoid,"cauchy") ) {
		return new PsiCauchy();
	} else {
		Rprintf ( "WARNING: no valid sigmoid!" );
		return NULL;
	}
}

PsiCore * determine_core ( char *core, const PsiSigmoid* Sigmoid, const PsiData* data ) {
	double dummy;
	if ( !strcmp(core,"ab") ) {
		return  new abCore();
	} else if ( !strncmp(core,"mw",2) ) {
		sscanf(core, "mw%lf", &dummy);
		return  new mwCore(Sigmoid->getcode(), dummy);
	} else if ( !strcmp(core,"linear") ) {
		return  new linearCore();
	} else if ( !strcmp(core,"log") ) {
		return  new logCore(data);
	} else if ( !strcmp(core,"poly") ) {
		return  new polyCore(data);
	} else if ( !strcmp(core,"weibull") ) {
		return  new weibullCore(data);
	} else {
		Rprintf ( "WARNING: no valid core!" );
		return NULL;
	}
}

PsiPrior * determine_prior ( char *prior ) {
	double prm1,prm2;
	if ( !strncmp(prior,"Beta",4) ) {
		sscanf(prior,"Beta(%lf,%lf)",&prm1,&prm2);
		return new BetaPrior(prm1,prm2);
	} else if ( !strncmp(prior,"Gamma",5) ) {
		sscanf(prior,"Gamma(%lf,%lf)",&prm1,&prm2);
		return new GammaPrior(prm1,prm2);
	} else if ( !strncmp(prior,"Gauss",5) ) {
		sscanf(prior,"Gauss(%lf,%lf)",&prm1,&prm2);
		return new GaussPrior(prm1,prm2);
	} else if ( !strncmp(prior,"Uniform",7) ) {
		sscanf(prior,"Uniform(%lf,%lf)",&prm1,&prm2);
		return new UniformPrior(prm1,prm2);
	} else {
		return new PsiPrior();
	}
}

PsiData * determine_data ( double *x, int *k, int *n, int *K, int *nafc ) {
	std::vector<double> stimulus_intensities ( *K );
	std::vector<int>    number_of_trials     ( *K );
	std::vector<int>    number_of_correct    ( *K );
	int i;

	for ( i=0; i<*K; i++ ) {
		stimulus_intensities[i] = x[i];
		number_of_trials[i]     = n[i];
		number_of_correct[i]    = k[i];
	}

	return new PsiData ( stimulus_intensities, number_of_trials, number_of_correct, *nafc );
}

void get_fitting_setup ( double *x, int *k, int *n, int *K,
		char **sigmoid, char **core, int *nafc, int *nparams, char **priors,
		PsiData** dataout, PsiPsychometric** pmfout )
{
	int i;
	*dataout = determine_data ( x, k, n, K, nafc );

	PsiSigmoid *Sigmoid = determine_sigmoid ( *sigmoid );
	if (Sigmoid==NULL) { delete *dataout; throw -1; }

	PsiCore *Core = determine_core ( *core, Sigmoid, *dataout );
	if (Core==NULL) { delete *dataout; delete Sigmoid; throw -1; }

	*pmfout = new PsiPsychometric ( *nafc, Core, Sigmoid );
	if (*nparams != (*pmfout)->getNparams() ) {
		Rprintf ( "WARNING: output vector length does not match number of parameters!" );
		delete dataout;
		delete Sigmoid;
		delete Core;
		delete *pmfout;
		throw -1;
	}

	for ( i=0; i<*nparams; i++ ) {
		(*pmfout)->setPrior ( i, determine_prior ( priors[i] ) );
	}
}

extern "C" {
////////////////////////////////////
// Functions go here
////////////////////////////////////

void mapestimate (
		double *x,        // stimulus intensities
		int *k,           // response counts of correct- (nAFC) or Yes-responses (Yes/No)
		int *n,           // numbers of trials per block
		int *K,           // number of blocks
		char **sigmoid,   // the sigmoid to be used
		char **core,      // core description
		int *nafc,        // number of alternatives in the task (a value < 2 indicates Yes/No)
		char **priors,    // priors
		int *nparams,     // number of parameters
		double *estimate, // output array for the estimated values
		double *deviance, // output: deviance
		double *Rpd,      // output: correlation between model prediction and deviance residuals
		double *Rkd       // output: correlation between block index and deviance residuals
		) {
	int i;
	PsiData * data;
	PsiPsychometric *pmf;

	try {
		get_fitting_setup ( x, k, n, K, sigmoid, core, nafc, nparams, priors, &data, &pmf );
	} catch (int) {
		return;
	}

	std::vector<double> startest = pmf->getStart ( data );
	PsiOptimizer *opt = new PsiOptimizer ( pmf, data );
	std::vector<double> est = opt->optimize ( pmf, data );
	delete opt;

	for ( i=0; i<*nparams; i++ )
		estimate[i] = est[i];

	std::vector<double> devianceresiduals ( pmf->getDevianceResiduals ( est, data ) );
	*deviance = pmf->deviance(est,data);
	*Rpd      = pmf->getRpd ( devianceresiduals, est, data );
	*Rkd      = pmf->getRkd ( devianceresiduals, data );

	delete data;
	delete pmf;

	return;
}

void performbootstrap (
		double *x,          // stimulus intensities
		int *k,             // response counts of correct- (nAFC) or Yes-responses (Yes/No)
		int *n,             // numbers of trials per block
		int *K,             // number of blocks
		char **sigmoid,     // the sigmoid to be used
		char **core,        // core description
		int *nafc,          // number of alternatives in the task (a value < 2 indicates Yes/No)
		char **priors,      // priors
		double *generating, // generating probabilites (if generating[0]==-999, non parametric bootstrap is performed)
		int *nparams,       // number of parameters
		int *nsamples,      // number of bootstrap samples to be drawn
		double *cuts,       // cuts at which the thresholds should be determined
		int *ncuts,         // number of cuts
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		int *bdata,         // output: bootstrap samples (needs to be 'reshaped')
		double *bestimates, // output: bootstrap estimates (needs to be reshaped)
		double *bdeviances, // output: deviances of the bootstrap samples
		double *bRpd,       // output: correlations between model prediction and deviance residuals for all bootstrap samples
		double *bRkd,       // output: correlations between block index and deviance residuals for all bootstrap samples
		double *bthres,     // output: thresholds of the bootstrap samples
		double *influential,// output: influence of the different blocks
		double *acc,        // output: acceleration constants
		double *bias,       // output: bias correction constants
		double *thresholdci // output: 95% confidence intervals for thresholds
		) {
	int i,j;
	PsiData * data;
	PsiPsychometric * pmf;
	std::vector<double> *start;
	bool parametric;

	try {
		get_fitting_setup ( x, k, n, K, sigmoid, core, nafc, nparams, priors, &data, &pmf );
	} catch (int) {
		return;
	}

	std::vector<double> Cuts ( *ncuts );
	for ( i=0; i<*ncuts; i++ ) Cuts[i] = cuts[i];

	if (generating[0]==-999) {
		start = NULL;
		parametric = false;
	} else {
		start = new std::vector<double> (*nparams);
		for ( i=0; i<*nparams; i++ ) {
			(*start)[i] = generating[i];
		}
		parametric = true;
	}

	BootstrapList bslist ( bootstrap (*nsamples,data,pmf,Cuts,start,true, parametric) );
	JackKnifeList jack   ( jackknifedata ( data, pmf ) );

	for ( i=0; i<*nsamples; i++ ) {
		for ( j=0; j<*K; j++ ) {
			bdata[*K*i + j] = bslist.getData(i)[j];
		}
		for ( j=0; j<*nparams; j++ ) {
			bestimates[*nparams*i + j] = bslist.getEst(i, j);
		}
		bdeviances[i] = bslist.getdeviance(i);
		bRpd[i]       = bslist.getRpd(i);
		bRkd[i]       = bslist.getRkd(i);
		for ( j=0; j<*ncuts; j++ ) {
			bthres[*ncuts*i + j] = bslist.getThres_byPos (i,j);
		}
	}
	for ( j=0; j<*ncuts; j++ ) {
		acc[j] = bslist.getAcc(j);
		bias[j] = bslist.getBias(j);
		thresholdci[3*j]   = bslist.getThres(0.025, j);
		thresholdci[3*j+1] = bslist.getThres(0.5, j);
		thresholdci[3*j+2] = bslist.getThres(0.975, j);
	}

	std::vector<double> ci_lower ( *nparams );
	std::vector<double> ci_upper ( *nparams );
	for ( j=0; j<*nparams; j++ ) {
		ci_lower[j] = bslist.getPercentile(0.025,j);
		ci_upper[j] = bslist.getPercentile(0.975,j);
	}
	for ( j=0; j<*K; j++ ) {
		influential[j] = jack.influential ( j, ci_lower, ci_upper );
	}

	delete data;
	delete pmf;
	delete start;

	return;
}

void performmcmc (
		double *x,          // stimulus intensities
		int *k,             // response counts of correct- (nAFC) or Yes-responses (Yes/No)
		int *n,             // numbers of trials per block
		int *K,             // number of blocks
		char **sigmoid,     // the sigmoid to be used
		char **core,        // core description
		int *nafc,          // number of alternatives in the task (a value < 2 indicates Yes/No)
		char **priors,      // priors
		double *proposal,   // standard deviances of the proposal distributions
		double *start,      // starting value of the sampler
		int *nparams,       // number of parameters
		int *nsamples,      // number of bootstrap samples to be drawn
		double *cuts,       // cuts at which the thresholds should be determined
		int *ncuts,         // number of cuts
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		double *mcmcestimates, // output: bootstrap estimates (needs to be reshaped)
		double *mcmcdeviances, // output: deviances of the bootstrap samples
		double *mcmcRpd,       // output: correlations between model prediction and deviance residuals for mcmc sammples
		double *mcmcRkd,       // output: correlations between block index and deviance residuals for all mcmc samples
		int *ppdata,           // output: bootstrap samples (needs to be 'reshaped')
		double *ppRpd,         // output: correlations between model prediction and deviance residuals for all bootstrap samples
		double *ppRkd,         // output: correlations between block index and deviance residuals for all bootstrap samples
		double *ppdeviances,   // output: acceleration constants
		double *logpratio      // output: logposterior ratio (for determination of influential observations)
		) {
	int i,j;
	PsiData * data;
	PsiPsychometric * pmf;

	try {
		get_fitting_setup ( x, k, n, K, sigmoid, core, nafc, nparams, priors, &data, &pmf );
	} catch (int) {
		return;
	}

	MetropolisHastings S ( pmf, data, new GaussRandom () );
	for ( i=0; i<*nparams; i++ ) S.setstepsize ( proposal[i], i );

	MCMCList mcmclist ( S.sample( *nsamples ) );

	for ( i=0; i<*nsamples; i++ ) {
		for ( j=0; j<*nparams; j++ ) {
			mcmcestimates[*nparams*i + j] = mcmclist.getEst (i, j);
		}
		mcmcdeviances[i] = mcmclist.getdeviance ( i );
		mcmcRpd[i] = mcmclist.getRpd ( i );
		mcmcRkd[i] = mcmclist.getRkd ( i );

		for ( j=0; j<*K; j++ ) {
			ppdata[*K*i + j] = mcmclist.getppData ( i, j );
		}
		ppRpd[i] = mcmclist.getppRpd ( i );
		ppRkd[i] = mcmclist.getppRkd ( i );
		ppdeviances[i] = mcmclist.getppDeviance ( i );

		for ( j=0; j<*K; j++ ) {
			logpratio[*K*i + j] = mcmclist.getlogratio ( i, j );
		}
	}
}

void getdiagnostics (
		double *x,        // stimulus intensities
		int *k,           // response counts of correct- (nAFC) or Yes-responses (Yes/No)
		int *n,           // numbers of trials per block
		int *K,           // number of blocks
		char **sigmoid,   // the sigmoid to be used
		char **core,      // core description
		int *nafc,        // number of alternatives in the task (a value < 2 indicates Yes/No)
		char **priors,    // priors
		int *nparams,     // number of parameters
		double *cuts,     // cuts at which the thresholds should be determined
		int *ncuts,       // number of cuts
		double *estimate, // array of the estimated values
		double *deviance, // output: deviance
		double *Rpd,      // output: correlation between model prediction and deviance residuals
		double *Rkd,      // output: correlation between block index and deviance residuals
		double *thres,    // output: thresholds at the respective cuts
		double *devianceresiduals // output: deviance residuals
		) {
	int i;
	PsiData * data;
	PsiPsychometric * pmf;
	std::vector<double> theta ( *nparams );
	for ( i=0; i<*nparams; i++ ) theta[i] = estimate[i];

	try {
		get_fitting_setup ( x, k, n, K, sigmoid, core, nafc, nparams, priors, &data, &pmf );
	} catch (int) {
		return;
	}

	std::vector<double> dr ( pmf->getDevianceResiduals ( theta, data ) );

	*deviance = pmf->deviance ( theta, data );
	*Rpd      = pmf->getRpd   ( dr, theta, data );
	*Rkd      = pmf->getRkd   ( dr, data );

	for ( i=0; i<*K; i++ ) {
		devianceresiduals[i] = dr[i];
	}

	for ( i=0; i<*ncuts; i++ ) {
		thres[i] = pmf->getThres ( theta, cuts[i] );
	}

	delete data;
	delete pmf;

	return;
}

void pmfevaluate (
		double *x,        // x values at which the psychometric function should be evaluated
		int *lenx,        // length of x
		double *params,   // parameter values
		int *nparams,  // number of parameters
		char **sigmoid,   // the sigmoid to be used
		char **core,      // core description
		int *nafc,        // number of alternatives in the task (a value < 2 indicates Yes/No)
		double *Fx        // output: output of the psychometric function
		) {
	int i;
	std::vector<double> xx ( 2 );
	std::vector<int> kk ( 2 );
	std::vector<int> nn ( 2 );
	PsiData * dummydata = new PsiData ( xx, kk, nn, *nafc );
	PsiPsychometric * pmf;
	std::vector<double> theta ( *nparams );
	for ( i=0; i<*nparams; i++ ) theta[i] = params[i];

	PsiSigmoid *Sigmoid = determine_sigmoid ( *sigmoid );
	PsiCore *   Core    = determine_core ( *core, Sigmoid, dummydata );
	delete dummydata;
	pmf = new PsiPsychometric ( *nafc, Core, Sigmoid );

	for ( i=0; i<*lenx; i++  ) {
		Fx[i] = pmf->evaluate ( x[i], theta );
	}

	delete pmf;

	return;
}

// Some more?
}