text:
<?php

require_once (__DIR__ . "/../model/config.php");
//require once is used to find files out of the origin file, like a library
$username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, "password", FILTER_SANITIZE_STRING);
//email password and username strings

$salt = "$5$" . "rounds=5000$" . uniqid(mt_rand(), true) . "$";
//makes the password crypt random
$hashedPassword = crypt($password, $salt);
//makes the password crypt
$query = $_SESSION["connection"]->query("INSERT INTO users SET "
        . "email = '',"
        . "username = '$username',"
        . "password = '$hashedPassword',"
        . "salt = '$salt' ");

$_SESSION["name"] = $username;

//query for insert into users
if ($query) {
    //need this for Ajax on index.php
    echo "true";
}
//echo for succesfully created user
else {
    echo "<p>" . $_SESSION["connection"]->error . "</p>";
}
//echo for error in created user


text:
FROM haproxy:1.5
MAINTAINER Muhammed Uluyol <uluyol@google.com>

RUN apt-get update && apt-get install -y dnsutils

ADD proxy.conf.insecure.in /proxy.conf.in
ADD run_proxy.sh /usr/bin/run_proxy

RUN chown root:users /usr/bin/run_proxy
RUN chmod 755 /usr/bin/run_proxy

CMD ["/usr/bin/run_proxy"]

redpajama_set_name: RedPajamaGithub


text:
VRL.TheTimeline = function (docWidth, docHeight, extraSpaces) {
	"use strict";
	// default settings
	var margin = {
		top : 0,
		bottom : 10,
		left : 10,
		right : 10
	};

	var padding = {
		top : 10,
		bottom : 10,
		left : 0,
		right : 5
	};

	var width = docWidth - margin.left - margin.right - extraSpaces;
	var height = 70;

	var contextHeight = height - 20;
	var contextHeightPadding = 5;
	var areaSpace = 40;

	var theData;
	var theSensorData = [];

	var noOfData = 0;
	var noOfSensorData = 0;

	var timelineBarHeight = 20; //timelineHeight / noOfData;

	//The total time range
	var startTimeRange = 0;
	var endTimeRange = 0;

	//
	var theBrush = d3.svg.brush();
	var theRange = d3.svg.brush();

	var xDomain = [];
	var xContext = 1;

	var eachDataHeight = 0;

	var yContextArr = [];
	var yContextArrIndex = {};

	var availableWidth;

	//##############################################
	//For Observer Pattern

	var subject = new Subject();

	timeline.addObserver = function addObserver(newObserver) {
		subject.observe(newObserver);
	};

	timeline.removeObserver = function removeObserver(deleteObserver) {
		subject.unobserve(deleteObserver);
	};

	timeline.handlesUpdated = function fetchRange() {
		// notify our observers of the stock change
		subject.notify(theRange, "timeline");
	};
	//##############################################

	var context;
	var container;

	function timeline(selection) {
		selection.each(function (data) {
			log("timeL: timeline");
			//var data = selection;

			theData = data;

			noOfData = theData.length;
			log("timeL: noOfData = " + noOfData);
			//calculateTimeRange(data);

			container = d3.select(this);
			var svg = container.append('svg')
				.attr('width', width + margin.left + margin.right)
				.attr('height', height + margin.top + margin.bottom);

			availableWidth = width - padding.left - padding.right;
			var availableHeight = height - padding.top - padding.bottom;

			//### collecting all the sensor data in one place
			for(var i = 0; i < noOfData; i++) {
				if(theData[i].dataType() == 2) {
					theSensorData.push(theData[i]);
					yContextArrIndex["" + i] = (theSensorData.length - 1) ;
				}
			}
			noOfSensorData = theSensorData.length;

			xContext = d3.time.scale().range([0, availableWidth]); //for context
			var yContext = d3.scale.linear().range([contextHeight, 0 + contextHeightPadding]);
			var xAxisContext = d3.svg.axis().scale(xContext).orient('bottom');//.tickFormat(d3.time.format("%X"));

			svg.append('defs').append('clipPath')
								.attr('id', 'clip')
								.append('rect')
								.attr('width', availableWidth)
								.attr('height', height - areaSpace);

			var wrap = svg.append('g')
				.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

			context = wrap.append('g')
				.attr('class', 'context')
				.attr('transform', 'translate(' + padding.left + ',' + (padding.top) + ')');

			//Generate lines for the linecharts
			function lineG(d) {
				//log("timeL: val " +  JSON.stringify(d)  )
				var lineGen = d3.svg.line()
						.x(function(d) {
							return xContext(new Date(d.timestamp - 0));
						})
						.y(function(d) {
							//var val = contextHeight/no * i;
							log("val " +  JSON.stringify(d)  )
							return yContext(0);
						});

				return lineGen;
			}

			//domain
			data.forEach(function (d) {
				d = d.data();
				//log("d = " + d);
				d.map(function(dd) {
					//log("dd = " + dd.timestamp);
					xDomain.push(new Date(dd.timestamp - 0).getTime());
				});

			});

			//log("timeL: xDomain size = " + xDomain.length);

			//### Calculating the start and the end timeline among the data ###
			var startValue = xDomain[0] - 0;
			var startIndex = 0;
			var endValue   = xDomain[xDomain.length - 1] - 0;
			var endIndex = xDomain.length - 1;
			for(var i = 0; i < xDomain.length; i++) {
				if(xDomain[i] < startValue) {
					startValue = xDomain[i];
					startIndex = i;
				}
				if(xDomain[i] > endValue) {
					endValue = xDomain[i];
					endIndex = i;
				}
			}
			var temp = xDomain[0];
			xDomain[0] = startValue;
			xDomain[startIndex] = temp;

			temp = xDomain[xDomain.length - 1];
			xDomain[xDomain.length - 1] = endValue;
			xDomain[endIndex] = temp;

			//log("timeL: start date :" + xDomain[0]);
			//log("timeL: Stop date  :" + xDomain[xDomain.length - 1]);

			if(xDomain[0] + (1000*60*60*24) > xDomain[xDomain.length - 1]) {
				log("timeL: range smaller than a day");
				//put hourly ticks for the x-axis
				xAxisContext.tickFormat(d3.time.format("%X"));

			}
			//###

			//yValues
			var yValues = [];
			data.forEach(function (d) {
				d = d.data();
				//log("d = " + d);
				d.map(function(dd) {
					//log("dd = " + dd.timestamp);
					//xDomain.push(new Date(dd.timestamp - 0));
					yValues.push(dd.value - 0);
				});

			});
			//log("yValues : " + yValues);

			var yMax = d3.max(yValues);
			//var yMax = d3.max(data.map(function(d) { return d[1]; } )); //for array of data

			//log("yMax = " + yMax);

			xContext.domain(d3.extent(xDomain));
			yContext.domain([0, contextHeight]);

			//### for drawing the lines based on the data
			var no = noOfData;
			var h = contextHeight - contextHeightPadding - 5;
				h = h/no;
			var hy = h;	//h  for height of the lines
						//hy for 'y' coordinate for each line
			//draw the data as straight lines

			if(h > 20) {
				h = 20;
			}

			eachDataHeight = h; //so that it can be used later for highlighting

			//### to keep all the figures inside this
			context.append("g")
					.attr("id", "timelineObjectContainer");

			for(var i = 0; i < noOfData; i++) {
				var start, end

				//find the next 'y' for a new line and fix the gap between them
				hy = i * h +  h/2 + i * 2;

				start = data[i].data();
				//log(start);
				if(start.length > 0) {
					//### Nominal Data
					start = start[0].timestamp - 0 ;

					start = xContext(start);
					//log("data: " + data[i].dataType());

					end = data[i].data();
					end = end[end.length - 1].timestamp - 0 ;
					end = xContext(end);
						//log("line end: " + end);
						//log("xContext = " + xContext.domain());
						//log("yContext" + yContext());
					if(data[i].dataType() == 0) {
						//if Nominal data

						var d = data[i].data();
						d.map(function(dd, index) {

							context.select("#timelineObjectContainer")
								.append('line')
									.attr("id", "TcircleNominal" + i + "-" + index)
									.attr('class', 'nominal theNominalTick' + i + ' dataElement data' + i )
									.attr("x1", xContext(dd.timestamp))
									.attr("y1", yContext(hy))
									.attr("x2", xContext(dd.timestamp) + 3)
									.attr("y2", yContext(hy))
									.attr('stroke', data[i].style.dataColor()) //based on the index
									.attr('stroke-width', h)
									.attr('fill', 'none');
						});

					}
					else if(data[i].dataType() == 1) {
					//### Ordinal Data

						var d = data[i].data();
						d.map(function(dd, index) {

							context.select("#timelineObjectContainer")
								.append('line')
									.attr("id", "TcircleOrdinal" + i + "-" + index)
									.attr('class', 'ordinal dataElement data' + i  + " ordinal" + i + "-"  + dd.value )
									.attr("x1", xContext(dd.timestamp))
									.attr("y1", yContext(hy))
									.attr("y2", yContext(hy))
									.attr("x2", xContext(dd.timestamp) + 3)
									.attr('stroke', data[i].styles[dd.value]) //based on the index
									.attr('stroke-width', h)
									.attr('fill', 'none');
						});

					}
					else if(data[i].dataType() == 2) {
						//if sensor data
						context.select("#timelineObjectContainer")
							.append('line')
								.attr("id", "Tline" + (yContextArrIndex["" + i] - 0))
								.attr('class', 'dataElement data' + i )
								.attr("x1", start)
								.attr("y1", yContext(hy))
								.attr("x2", end)
								.attr("y2", yContext(hy))
								.attr('stroke', data[i].style.dataColor())
								.attr('stroke-width', h)
								.attr('fill', 'none');
					}
					else if(data[i].dataType() == 3) {
						//if GPS data
						//log("GPS data drawn. index is " + "TlineGPS" +  i )
						context.select("#timelineObjectContainer")
							.append('line')
								.attr("id", "TlineGPS" +  i)
								.attr('class', 'dataElement data' + i )
								.attr("x1", start)
								.attr("y1", yContext(hy))
								.attr("x2", end)
								.attr("y2", yContext(hy))
								.attr('stroke', data[i].style.dataColor())
								.attr('stroke-width', h)
								.attr('fill', 'none');
					}
				}

			}

			context.append('g')
					.attr('class', 'x axis')
					.attr('transform', 'translate(0,' + contextHeight + ')')
					.call(xAxisContext);

		//-----------------------------------------------------------------

			var startDate = new Date(xDomain[0] - 0);
			var lastDate = new Date(xDomain[xDomain.length - 1] - 0);

			theBrush = d3.svg.brush()
									.x(xContext)
									.extent([startDate, lastDate])
									.on('brush', timeline.brushed);

			context.append('g')
					.attr('class', 'x brush')
					.call(theBrush);

			//show the charts
			timeline.brushed();
			//brushed();

			//### Don't allow the brushing from background and single click context switch
			context.select(".background")
							.on("mousedown.brush", timeline.nobrush)
							.on("touchstart.brush", timeline.nobrush);

			context.selectAll("rect")
						.attr('y', contextHeightPadding - 2)
						.attr("height", contextHeight - contextHeightPadding + 20);

			//### the handles configuration
			context.selectAll(".resize").append("rect")
											.attr('class', 'timeRangeHandle')
											.attr("width", '5px')
											.attr("height", contextHeight + 25)
											.classed("border");

		});

		return timeline;
	}

	// Expose Public Variables

	timeline.margin = function (_) {
		if (!arguments.length)
			return margin;
		margin.top = typeof _.top !== 'undefined' ? _.top : margin.top;
		margin.right = typeof _.right !== 'undefined' ? _.right : margin.right;
		margin.left = typeof _.left !== 'undefined' ? _.left : margin.left;
		margin.bottom = typeof _.bottom !== 'undefined' ? _.bottom : margin.bottom;
		return timeline;
	};

	timeline.padding = function (_) {
		if (!arguments.length)
			return padding;
		padding.top = typeof _.top !== 'undefined' ? _.top : padding.top;
		padding.right = typeof _.right !== 'undefined' ? _.right : padding.right;
		padding.left = typeof _.left !== 'undefined' ? _.left : padding.left;
		padding.bottom = typeof _.bottom !== 'undefined' ? _.bottom : padding.bottom;
		return timeline;
	};

	timeline.width = function (_) {
		if (!arguments.length)
			return width;
		width = _;
		return timeline;
	};

	timeline.height = function (_) {
		if (!arguments.length)
			return height;
		height = _;
		return timeline;
	};

	timeline.contextHeight = function (_) {
		if (!arguments.length)
			return contextHeight;
		contextHeight = _;
		return timeline;
	};

	timeline.areaSpace = function (_) {
		if (!arguments.length)
			return areaSpace;
		areaSpace = _;
		return timeline;
	};

	//##############################################
	timeline.timelineBarHeight = function (_) {
		if (!arguments.length)
			return timelineBarHeight;
		timelineBarHeight = _;
		return timeline;
	};
//#######################################################
			timeline.brushed = function() {
				//log("extent: " + theBrush.extent());
				//log(new Date(startTimeRange) + " : " + new Date(endTimeRange))
				//xContext.domain(theBrush.empty() ? xContext.domain() : theBrush.extent());
				theRange = theBrush.extent();

				var startD = new Date(theRange[0]).getTime();
				var endD = new Date(theRange[1]).getTime();

				//don't go smaller than 1 seconds
				if(endD < (startD + 1000)){

					endD = startD + 1000;
					theRange[1] = new Date(endD);

					context.select('.brush').call(theBrush.extent(theRange));
				}

				for(var i = 0; i < noOfData; i++) {
					//context.select('.line').attr('d', lineGen(data[0].data())); //lineContext //show the context line
				}

				//timeline.changeHandles();

				subject.notify(theRange, "timeline");//notifying all the observers about the change in range
			};

			timeline.changeHandles = function(){
				//xContext.domain(theBrush.empty() ? xContext.domain() : theBrush.extent());
				//context.select('class', 'x brush').call(theBrush);
				//log(theRange)
				//context.select('class', 'x brush')
				context.select('.brush').call(theBrush.extent(theRange));
				//log(context.select('.brush'));
					//;
			};

			timeline.nobrush = function(a, b, c) {
				//to stop the brushing from the chart background
				//log('Brushing from background diabled')
				d3.event.stopPropagation()
			};

			function calculateTimeRange(data){
				//log("calculating time range");

				var start, end;
				if(data.length >= 1) {
					start = data[0].data();
					start = start[0].timestamp - 0;
					//log("start: " + start);

					end = data[0].data();
					end = end[end.length - 1].timestamp - 0;

					startTimeRange = start;
					endTimeRange = end;
					//log("end: " + end);
				}
				if(data.length > 1) {
					for(var i = 1; i < data.length; i++) {
						var s = data[i].data();
						s = s[0].timestamp - 0;

						var e = data[i].data();
						e = e[e.length - 1].timestamp - 0;

						if(s < start) {
							startTimeRange = s;
						}
						if(e > end) {
							endTimeRange = e;
						}
					}

					//log("timeline:   Start: " + new Date(startTimeRange) + " and End : " + new Date(endTimeRange) );
				}
			}

			//#######################################################
	timeline.reload = function(data) {

		xDomain = [];
		theSensorData = [];
		yContextArr = [];
		yContextArrIndex = {};

		container.selectAll("*").remove();
		d3.select('#TimeLineDIV').html("");
		d3.select('#TimeLineDIV')
						.datum(data)
						.call(timeline);
	};

	//### the handle was updated
	timeline.update = function (range, caller, dataObject) {
		//log("theBrush : " + theBrush.extent());
		//log("before " + theBrush.extent());

		//### when the item was highlighted in Focus chart
		if(caller == "itemHighlighted") {
			var str = dataObject.substring(0, 4);
			log(dataObject)
			if(str == "circ") {
				context.select("#T" + dataObject)
									.attr("fill-opacity", 1)
									.attr('stroke-width', function() {
										this.parentNode.appendChild(this);
										return eachDataHeight + 10;
									});
			}
			else if(str == "line") {
				var lineStr = dataObject.substring(0,5);
				context.select("#T" + lineStr )
								.attr("fill-opacity", 0.5)
								.attr('stroke-width', function(){
									this.parentNode.appendChild(this);
									return eachDataHeight + 6;
								});
			}
		}
		else if(caller == "itemHighlightedOut") {
			var str = dataObject.substring(0, 4);

			if(str == "circ") {
				context.select("#T" + dataObject)
								.attr("fill-opacity", 1)
								.attr('stroke-width', eachDataHeight);
			}
			else if(str == "line") {
				var lineStr = dataObject.substring(0,5);
				context.select("#T" + lineStr )
								.attr("fill-opacity", 1)
								.attr('stroke-width', eachDataHeight);
			}
		}
		else {
			theRange = range;
			theBrush.extent(range);
			//log("t: range = " + range);

			//log("after  " + theBrush.extent());
			if(theBrush.extent() != null) {
				timeline.changeHandles();
			}
		}
	}

	//### hide Data
	timeline.hideData = function(index) {
		context.selectAll(".data" + index).attr("visibility", "hidden");
	};

	//### show Data
	timeline.showData = function(index) {
		context.selectAll(".data" + index).attr("visibility", "visible");
	};

	//### change color of the data
	timeline.changeColor = function(dataToChangeIndex, color) {
		//log("data " + dataToChangeIndex + " color " + color);

		//log(theData[dataToChangeIndex].dataType())

		if(theData[dataToChangeIndex].dataType() == 0) {
			//### Nominal Notes

			context.selectAll(".theNominalTick" + dataToChangeIndex)
							.attr("stroke", color)
							.attr("fill", color);
		}
		else if(theData[dataToChangeIndex].dataType() == 1) {
			//### Ordinal Values
			var dataInfo = theData[dataToChangeIndex].dataInfo();
			var noOfKeys = Object.keys(dataInfo).length;

			var plus = 0,
				minus = 0;
			var gradientColors = [];
			var moreLuminance = [];
			var lessLuminance = [];

			var inc;
			if(noOfKeys % 2 == 0) {
				if(noOfKeys > 1) {
					inc = 100 / noOfKeys;
				}
				else {
					inc = 50;
				}
			}
			else {
				if(noOfKeys > 1) {
					inc =  100 / (noOfKeys - 1);
				}
				else {
					inc = 50;
				}
			}

			for(var i = 0; i < noOfKeys - 1; i++) {
				if(i % 2 == 0) {
					plus += inc;
					moreLuminance.push(ColorLuminance(color, (plus/100)));
				}
				else {
					minus -= inc;
					lessLuminance.push(ColorLuminance(color, (minus/100)));
				}
			}

			for(var j = moreLuminance.length - 1; j >= 0; j-- ) {
				gradientColors.push(moreLuminance[j]);
			}
			gradientColors.push(color);
			for(var j = 0; j < lessLuminance.length; j++ ) {
				gradientColors.push(lessLuminance[j]);
			}

			for(var j = 0; j < gradientColors.length; j++ ) {
				context.selectAll(".ordinal" + dataToChangeIndex + "-"   + j)
						.attr("stroke", gradientColors[j])
						.attr("fill", gradientColors[j]);
			}

		}
		else if(theData[dataToChangeIndex].dataType() == 2) {
			//### Sensor data
			context.select("#Tline" + (yContextArrIndex["" + dataToChangeIndex] - 0))
							.attr("stroke", color);
		}
		else if(theData[dataToChangeIndex].dataType() == 3) {
			//### GPS data
			context.select("#TlineGPS" + dataToChangeIndex)
							.attr("stroke", color);
		}

	};

	return timeline;
};


text:
package fr.polytech.ihm.controller;

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

/**
 * Created by Pierre on 03/03/2017.
 */
public class EmailController {

    @FXML
    private TextField emailField;
    @FXML
    private TextArea textField;

    public void sendEmail(){
        String email ="Email : "+emailField.getText() +"\n" + "Contenu : "+ textField.getText();
        System.out.println(email);
    }

}


text:
..
      All Rights Reserved.

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

Running Cinder API under Apache
===============================

Files
-----
Copy the file etc/cinder/api-httpd.conf to the appropriate location for your Apache server, most likely:

``/etc/httpd/conf.d/cinder_wsgi.conf``

Update this file to match your system configuration (for example, some distributions put httpd logs in the apache2 directory and some in the httpd directory).
Create the directory /var/www/cgi-bin/cinder/. You can either hard or soft link the file cinder/wsgi/wsgi.py to be osapi_volume under the /var/www/cgi-bin/cinder/ directory. For a distribution appropriate place, it should probably be copied to:

``/usr/share/openstack/cinder/httpd/cinder.py``

Cinder's primary configuration file (etc/cinder.conf) and the PasteDeploy configuration file (etc/cinder-paste.ini) must be readable to httpd in one of the default locations described in Configuring Cinder.

Access Control
--------------

If you are running with Linux kernel security module enabled (for example SELinux or AppArmor), make sure that the configuration file has the appropriate context to access the linked file.


text:
package com.zegoggles.smssync.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.zegoggles.smssync.preferences.Preferences;
import com.zegoggles.smssync.service.BackupJobs;

import static com.zegoggles.smssync.App.LOCAL_LOGV;
import static com.zegoggles.smssync.App.TAG;

public class BackupBroadcastReceiver extends BroadcastReceiver {
    public static final String BACKUP_ACTION = "com.zegoggles.smssync.BACKUP";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (LOCAL_LOGV) Log.v(TAG, "onReceive(" + context + "," + intent + ")");

        if (BACKUP_ACTION.equals(intent.getAction())) {
            backupRequested(context, intent);
        }
    }

    private void backupRequested(Context context, Intent intent) {
        if (new Preferences(context).isAllow3rdPartyIntegration()) {
            Log.d(TAG, "backup requested via broadcast intent");
            new BackupJobs(context).scheduleImmediate();
        } else {
            Log.d(TAG, "backup requested via broadcast intent but ignored");
        }
    }
}


text:
"""Authentication for HTTP component."""

import base64
import hmac
import logging

from aiohttp import hdrs
from aiohttp.web import middleware
import jwt

from homeassistant.core import callback
from homeassistant.const import HTTP_HEADER_HA_AUTH
from homeassistant.auth.providers import legacy_api_password
from homeassistant.auth.util import generate_secret
from homeassistant.util import dt as dt_util

from .const import KEY_AUTHENTICATED, KEY_REAL_IP

DATA_API_PASSWORD = 'api_password'
DATA_SIGN_SECRET = 'http.auth.sign_secret'
SIGN_QUERY_PARAM = 'authSig'

_LOGGER = logging.getLogger(__name__)

@callback
def async_sign_path(hass, refresh_token_id, path, expiration):
    """Sign a path for temporary access without auth header."""
    secret = hass.data.get(DATA_SIGN_SECRET)

    if secret is None:
        secret = hass.data[DATA_SIGN_SECRET] = generate_secret()

    now = dt_util.utcnow()
    return "{}?{}={}".format(path, SIGN_QUERY_PARAM, jwt.encode({
        'iss': refresh_token_id,
        'path': path,
        'iat': now,
        'exp': now + expiration,
    }, secret, algorithm='HS256').decode())

@callback
def setup_auth(app, trusted_networks, api_password):
    """Create auth middleware for the app."""
    old_auth_warning = set()

    @middleware
    async def auth_middleware(request, handler):
        """Authenticate as middleware."""
        authenticated = False

        if (HTTP_HEADER_HA_AUTH in request.headers or
                DATA_API_PASSWORD in request.query):
            if request.path not in old_auth_warning:
                _LOGGER.log(
                    logging.INFO if api_password else logging.WARNING,
                    'You need to use a bearer token to access %s from %s',
                    request.path, request[KEY_REAL_IP])
                old_auth_warning.add(request.path)

        if (hdrs.AUTHORIZATION in request.headers and
                await async_validate_auth_header(request, api_password)):
            # it included both use_auth and api_password Basic auth
            authenticated = True

        # We first start with a string check to avoid parsing query params
        # for every request.
        elif (request.method == "GET" and SIGN_QUERY_PARAM in request.query and
              await async_validate_signed_request(request)):
            authenticated = True

        elif (api_password and HTTP_HEADER_HA_AUTH in request.headers and
              hmac.compare_digest(
                  api_password.encode('utf-8'),
                  request.headers[HTTP_HEADER_HA_AUTH].encode('utf-8'))):
            # A valid auth header has been set
            authenticated = True
            request['hass_user'] = await legacy_api_password.async_get_user(
                app['hass'])

        elif (api_password and DATA_API_PASSWORD in request.query and
              hmac.compare_digest(
                  api_password.encode('utf-8'),
                  request.query[DATA_API_PASSWORD].encode('utf-8'))):
            authenticated = True
            request['hass_user'] = await legacy_api_password.async_get_user(
                app['hass'])

        elif _is_trusted_ip(request, trusted_networks):
            users = await app['hass'].auth.async_get_users()
            for user in users:
                if user.is_owner:
                    request['hass_user'] = user
                    break
            authenticated = True

        request[KEY_AUTHENTICATED] = authenticated
        return await handler(request)

    app.middlewares.append(auth_middleware)

def _is_trusted_ip(request, trusted_networks):
    """Test if request is from a trusted ip."""
    ip_addr = request[KEY_REAL_IP]

    return any(
        ip_addr in trusted_network for trusted_network
        in trusted_networks)

def validate_password(request, api_password):
    """Test if password is valid."""
    return hmac.compare_digest(
        api_password.encode('utf-8'),
        request.app['hass'].http.api_password.encode('utf-8'))

async def async_validate_auth_header(request, api_password=None):
    """
    Test authorization header against access token.

    Basic auth_type is legacy code, should be removed with api_password.
    """
    if hdrs.AUTHORIZATION not in request.headers:
        return False

    try:
        auth_type, auth_val = \
            request.headers.get(hdrs.AUTHORIZATION).split(' ', 1)
    except ValueError:
        # If no space in authorization header
        return False

    hass = request.app['hass']

    if auth_type == 'Bearer':
        refresh_token = await hass.auth.async_validate_access_token(auth_val)
        if refresh_token is None:
            return False

        request['hass_refresh_token'] = refresh_token
        request['hass_user'] = refresh_token.user
        return True

    if auth_type == 'Basic' and api_password is not None:
        decoded = base64.b64decode(auth_val).decode('utf-8')
        try:
            username, password = decoded.split(':', 1)
        except ValueError:
            # If no ':' in decoded
            return False

        if username != 'homeassistant':
            return False

        if not hmac.compare_digest(api_password.encode('utf-8'),
                                   password.encode('utf-8')):
            return False

        request['hass_user'] = await legacy_api_password.async_get_user(hass)
        return True

    return False

async def async_validate_signed_request(request):
    """Validate a signed request."""
    hass = request.app['hass']
    secret = hass.data.get(DATA_SIGN_SECRET)

    if secret is None:
        return False

    signature = request.query.get(SIGN_QUERY_PARAM)

    if signature is None:
        return False

    try:
        claims = jwt.decode(
            signature,
            secret,
            algorithms=['HS256'],
            options={'verify_iss': False}
        )
    except jwt.InvalidTokenError:
        return False

    if claims['path'] != request.path:
        return False

    refresh_token = await hass.auth.async_get_refresh_token(claims['iss'])

    if refresh_token is None:
        return False

    request['hass_refresh_token'] = refresh_token
    request['hass_user'] = refresh_token.user

    return True


text:
CC = elm make
PACKAGE = elm package
INSTALL = install
SRC = src
TEST = test
OPEN = open
NODE = node
BASH = bash

PACKAGE_FLAGS = -y

BUILD_DIR = build
RESOURCES_DIR = resources

all: package/install clean compile

compile: matrix

Matrix = Matrix
Matrix.js = $(BUILD_DIR)/$(Matrix).js
Matrix.elm = $(SRC)/$(Matrix).elm
matrix: $(Matrix.js)
$(Matrix.js): $(Matrix.elm)
	$(CC) --output $(Matrix.js) $(Matrix.elm)

clean:
	rm -rf $(BUILD_DIR)

package/install:
	$(PACKAGE) $(INSTALL) $(PACKAGE_FLAGS)

#### TEST ####################

TestRunner.elm = test/TestRunner.elm
Test.html = $(BUILD_DIR)/test.html
test: $(Test.html)
$(Test.html): $(TestRunner.elm)
	$(CC) $(TestRunner.elm) --output $(Test.html)

test/open: clean test
	$(OPEN) $(Test.html)


text:
package com.doctusoft.dataops;

import java.util.*;
import java.util.function.*;

import static java.util.Objects.*;

public final class JoinOperator<K> {

    public static <K> JoinOperator<K> from(Comparator<K> comparator) {
        return new JoinOperator<>(comparator);
    }

    public static <K extends Comparable<? super K>> JoinOperator<K> natural() {
        return NATURAL_OPERATOR;
    }

    public static <K extends Comparable<? super K>> JoinOperator<K> forClass(Class<K> keyClass) {
        return NATURAL_OPERATOR;
    }

    private final Comparator<? super K> keyOrder;

    private JoinOperator(Comparator<? super K> keyOrder) {
        this.keyOrder = requireNonNull(keyOrder);
    }

    public <L, R> void join(Entries<K, L> leftEntries, Entries<K, R> rightEntries, JoinConsumer<L, R, K> consumer) {
        Side<L> left = new Side<>(leftEntries);
        Side<R> right = new Side<>(rightEntries);
        K actualKey = null;
        while (left.hasNext() || right.hasNext()) {
            int c = compareNullsLast(left.nextKey, right.nextKey);
            if (c <= 0) {
                actualKey = left.nextKey;
                left.forward();
            }
            if (c >= 0) {
                actualKey = right.nextKey;
                right.forward();
            }
            consumer.accept(left.actualValue, right.actualValue, actualKey);
            left.actualValue = null;
            right.actualValue = null;
        }
    }

    public <L, G extends Collection<L>, R> void joinGroupLeft(Entries<K, L> leftEntries,
        Supplier<? extends G> leftCollectionSupplier, Entries<K, R> rightEntries, JoinConsumer<G, R, K> consumer) {
        join(new EntryGroups<>(leftEntries, leftCollectionSupplier, this::keyEquals), rightEntries, consumer);
    }

    public <L, R, G extends Collection<R>> void joinGroupRight(Entries<K, L> leftEntries, Entries<K, R> rightEntries,
        Supplier<? extends G> rightCollectionSupplier, JoinConsumer<L, G, K> consumer) {
        join(leftEntries, new EntryGroups<>(rightEntries, rightCollectionSupplier, this::keyEquals), consumer);
    }

    public <L, GL extends Collection<L>, R, GR extends Collection<R>> void joinGroupBoth(
        Entries<K, L> leftEntries, Supplier<? extends GL> leftCollectionSupplier,
        Entries<K, R> rightEntries, Supplier<? extends GR> rightCollectionSupplier,
        JoinConsumer<GL, GR, K> consumer) {
        join(
            new EntryGroups<>(leftEntries, leftCollectionSupplier, this::keyEquals),
            new EntryGroups<>(rightEntries, rightCollectionSupplier, this::keyEquals),
            consumer);
    }

    private boolean keyEquals(K left, K right) {
        return left == right || keyOrder.compare(left, right) == 0;
    }

    private int compareNullsLast(K left, K right) {
        if (left == right) {
            return 0;
        }
        if (left == null) {
            return 1;
        }
        if (right == null) {
            return -1;
        }
        return keyOrder.compare(left, right);
    }

    @SuppressWarnings("rawtypes")
    private static final JoinOperator NATURAL_OPERATOR = new JoinOperator<>(Comparator.naturalOrder());

    private final class Side<V> {

        private final Entries<K, V> entries;
        private final LookbackFilter<K> keyOrderValidator;

        private K nextKey;
        private V nextValue;
        private V actualValue;

        private Side(Entries<K, V> entries) {
            this.entries = requireNonNull(entries);
            this.keyOrderValidator = LookbackFilter.strictlyMonotone(keyOrder);
            forward();
        }

        public boolean hasNext() {
            return nextKey != null;
        }

        public void forward() {
            validateKeyOrder();
            if (!entries.next(this::acceptNext)) {
                store(null, null);
            }
        }

        private void acceptNext(K key, V value) {
            store(key, value);
        }

        private void validateKeyOrder() {
            if (nextKey != null && !keyOrderValidator.test(nextKey)) {
                K lastKey = keyOrderValidator.getLastAccepted();
                throw new IllegalArgumentException("keyOrder violated: " + lastKey + ", " + nextKey);
            }
        }

        private void store(K key, V value) {
            actualValue = nextValue;
            nextValue = value;
            nextKey = key;
        }

    }

}


text:
/**
 * IoSL-INav routes/users
 * SNET TU Berlin
 * using PIazza code base
 *
 * Users specific endpoints
 */

/* Variables and configurations. */

var express = require('express');

var config = require('./../config');
var controller = require('./../controllers/users');

var router = express();

/* Param middleware. */

/* If given, add group ID to request. */
router.param('gid', function(req, res, next, gid) {
	req.groupID = gid;
	next();
});

/* If given, add requested (other) user ID to request. */
router.param('uid', function(req, res, next, uid) {
	req.otherUserID = uid;
	next();
});

/* Routes concerning everything around users. */

router.route('/me')
	.all(config.authenticate)
	.get(controller.getCurrentUser)
	.put(controller.updateCurrentUser)
	.delete(controller.deleteCurrentUser);

router.route('/me/location')
	.all(config.authenticate)
	.put(controller.updateLocation)
	.delete(controller.deleteLocation);

router.route('/me/groups')
	.all(config.authenticate)
	.get(controller.getGroupsForUser)
	.post(controller.addGroupForUser);

router.route('/me/groups/:gid')
	.all(config.authenticate)
	.get(controller.getGroupForUser)
	.put(controller.updateGroupForUser)
	.delete(controller.deleteGroupForUser);

router.route('/me/groups/:gid/users')
	.post(config.authenticate, controller.addUserToGroup);

router.route('/me/groups/:gid/users/:uid')
	.delete(config.authenticate, controller.deleteUserFromGroup);

/* Export router with described routes. */
module.exports = router;


text:
var GetJSON = (function (url, optionalEvent, headers) {
  var doneEvent = optionalEvent ? new Event(optionalEvent) : null;

  function GetJ(_url, _cb){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', _url);
    if(headers) {
      for (var property in headers) {
        if (headers.hasOwnProperty(property)) {
          xhr.setRequestHeader(property, headers[property]);
        }
      }
    }
    xhr.send();
    xhr.onload = function() {
      var resp = xhr.responseText;
      if (typeof _cb === 'function') { _cb(resp); }
      if (doneEvent) { window.dispatchEvent(doneEvent); }
    };
  }

  var done = function(cb){
    new GetJ(url, cb);
  };
  return { done: done };
});

module.exports = GetJSON;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<TITLE>Q Light Controller Plus - Virtual Console Cue List</TITLE>

<link href="style.css" rel="stylesheet" type="text/css" />

 Virtual Console Cue List

A Cue List provides a list of Functions that
you can step through with a single keyboard key. The Cue List is designed for
theatrical performances where the lighting operator needs only to follow the script
and toggle the next cue as the performance goes on.

The first column on the Cue List displays the step (cue) number that runs from 1 to
infinity and beyond .
The second column shows the individual Function
name that has been assigned to that particular cue.

Please note that only Chasers
can be assigned to a Cue List, for the simple reason that the Chaser
is the only function with a duration. Since any other Function can be added
as a step to a Chaser with the Chaser Editor,
it is simple to create the desired Cues by mixing Scenes,
Collections, and so on...

Configuration

Cue Lists can be configured with the object properties button
 found in the toolbar or
by double clicking on the Cue List widget.

   Cue list name

   Set the friendly name of the Cue List. The name appears as the Cue List's
   second column title.

   Cue list

   This panel allows the user to select the Chaser
   to associate with the Cue List.

   Associate a Chaser with the Cue List using
   the Select Function dialog.

   Remove the selected Chaser from the Cue List.

   Playback

   You can select the key that you want to use to start/stop the selected step (cue) in the Cue List
   with this option. The key combination is shown in the text field; if the
   field is empty, there is no key combination currently attached to the Cue List.

   Next cue

   You can select the key that you want to use to skip to the next step (cue) in the Cue List
   with this option. The key combination is shown on the text field; if the
   field is empty, there is no key combination currently attached to the Cue List.

   Previous cue

   You can select the key that you want to use to skip to the previous step (cue) in the Cue List
   with this option. The key combination is shown on the text field; if the
   field is empty, there is no key combination currently attached to the Cue List.

   Crossfade

   You can select external input for the two crossfaders.

Operate mode

When switching QLC+ to Operate Mode, the Cue List will
become active, allowing the selection of the desired steps included in the associated Chaser.

Four buttons are displayed at the bottom of the Cue List widget:

  Start/stop the replay of the Cue List from the currently selected step

  Go back to the previous step in the Cue List, which will then be replayed.
  When the top is reached, the previous step will be the last step of the Cue List

  Go to the next step in the Cue List, which will then be replayed.
  When reaching the bottom, the next step will be the first of the Cue List

  When clicked, this button will open/close a side panel showing two sliders for controlling crossfade.

Pressing ENTER key will start the selected step.

Crossfade

  There are two faders that can be used to manually control crossfade between two consecutive steps.

  Each slider is connected to a Cue List step and to help to understand their purpose we'll call them
  "current step" and "next step" sliders.

  The label at the bottom of each slider will show
  the number of the step that the slider is controlling and a colour to show the status of that step.

  The checkbox at the top will link the sliders together to facilitate crossfading between steps.

  When the Cue list is running the sliders control the intensity of the
  associated steps, overriding their Fade In and Fade Out speeds and so allowing manual control
  of the transition.

  The slider for the current step has a blue label. This will be at 100% when the replay of the Cue List is started.

  The slider for the next step has an orange label and will be at 0% when the replay of the Cue List is started.

  The intensities of both steps can be adjusted by moving the corresponding slider.

  However, after both sliders have been moved to the opposite ends of their travel, the following changes take place:

  The orange next step label changes to blue (slider at 100%). This indicates that the old next step has become the new current step.

  The blue current step label changes to orange and the number of the step is increased by 2 (slider at 0%). So this slider now controls the step which comes after the
  old next step.

Hint

When a step is added to a Chaser using the Chaser Editor, the default
duration is set to 0.

To avoid the steps in the Cue List looping frantically without any result, set the duration
of your steps, either by double clicking on the duration field or by using the
Speed Dial widget

Note that if you need scenes that you're going to crossfade manually with the
Cue List widget, you probably will want to set the duration of the steps to "infinite" (∞) using the Speed Dial widget. This can be
enabled in the Chaser Editor by clicking on the  button.


text:
var React = require('react/addons'),
    mui = require("material-ui"),
    injectTapEventPlugin = require('react-tap-event-plugin');

injectTapEventPlugin();

window.mui = mui;

require("./js/highlight.pak.js")

window.React = React;

//css

require("./styles/default.css")

//images
var googleMapImage = require("./images/googleMap.png");
   reactListViewImage = require("./images/reactListView.png"),
   reactTreeViewImage = require("./images/reactTreeView.png"),
   materialuiImage = require("./images/mui.png"),
   reactTableImage = require("./images/reactTable.png"),
   bottomTearImage = require("./images/bottom-tear.svg"),
   reactTagsInputImage = require("./images/reactTagsInput.png"),
   reactSelectImage = require("./images/reactSelect.png"),
   reactInfiniteImage = require("./images/reactInfinite.png"),
   reactGeomIconImage = require("./images/reactGeomIcon.png"),
   spinnerImage = require("./images/spinner.png"),
   reactPopoverImage = require("./images/reactPopover.png");

window.googleMapImage = googleMapImage;
window.bottomTearImage = bottomTearImage;
window.reactInfiniteImage = reactInfiniteImage;
window.reactTagsInputImage = reactTagsInputImage;
window.reactListViewImage = reactListViewImage;
window.reactTableImage = reactTableImage;
window.spinnerImage = spinnerImage;
window.reactPopoverImage = reactPopoverImage;
window.reactGeomIconImage = reactGeomIconImage;
window.materialuiImage = materialuiImage;
window.reactTreeViewImage = reactTreeViewImage;
window.reactSelectImage = reactSelectImage;


text:
ballin-sansa
============

freezing-octo-dangerzone


text:
/*

  DEBUG CHILDREN
  Docs: http://tachyons.io/docs/debug/

  Just add the debug class to any element to see outlines on its
  children.

*/

.debug * { outline: 1px solid gold; }
.debug-white * { outline: 1px solid white; }
.debug-black * { outline: 1px solid black; }


text:
package datastore

import (
	"fmt"
	"strings"

	"context"

	"github.com/speedland/go/lazy"
	"github.com/speedland/go/x/xlog"
	"google.golang.org/appengine/datastore"
)

// Query is a struct to build a query to datastore.
type Query struct {
	kind        string
	ancestor    lazy.Value
	projects    []string
	keysOnly    bool
	orders      []*order
	filters     []*filter
	startCursor lazy.Value
	endCursor   lazy.Value
	limit       lazy.Value
	offset      lazy.Value
	loggerKey   string
}

// NewQuery returns a new *Query for `kind`
func NewQuery(kind string, loggerKey string) *Query {
	return &Query{
		kind:      kind,
		loggerKey: loggerKey,
	}
}

// Ancestor sets the ancestor filter
func (q *Query) Ancestor(a lazy.Value) *Query {
	q.ancestor = a
	return q
}

// KeysOnly sets the query to fetch only keys.
func (q *Query) KeysOnly(t bool) *Query {
	q.keysOnly = t
	return q
}

// Eq sets the "=" filter on the `name` field.
func (q *Query) Eq(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeEq,
		Value: value,
	})
	return q
}

// Lt sets the `<` filter on the `name` field.
func (q *Query) Lt(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeLt,
		Value: value,
	})
	return q
}

// Le sets the `<=` filter on the `name` field.
func (q *Query) Le(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeLe,
		Value: value,
	})
	return q
}

// Gt sets the `>` filter on the `name` field.
func (q *Query) Gt(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeGt,
		Value: value,
	})
	return q
}

// Ge sets the `>=` filter on the `name` field.
func (q *Query) Ge(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeGe,
		Value: value,
	})
	return q
}

// Ne sets the `!=` filter on the `name` field.
func (q *Query) Ne(name string, value lazy.Value) *Query {
	q.filters = append(q.filters, &filter{
		Name:  name,
		Type:  filterTypeNe,
		Value: value,
	})
	return q
}

// Asc specifies ascending order on the given filed.
func (q *Query) Asc(name string) *Query {
	q.orders = append(q.orders, &order{
		Name: name,
		Type: orderTypeAsc,
	})
	return q
}

// Desc specifies descending order on the given filed.
func (q *Query) Desc(name string) *Query {
	q.orders = append(q.orders, &order{
		Name: name,
		Type: orderTypeDesc,
	})
	return q
}

// Limit sets the limit
func (q *Query) Limit(value lazy.Value) *Query {
	q.limit = value
	return q
}

// Start sets the start cursor
func (q *Query) Start(value lazy.Value) *Query {
	q.startCursor = value
	return q
}

// End sets the end cursor
func (q *Query) End(value lazy.Value) *Query {
	q.endCursor = value
	return q
}

type order struct {
	Name string
	Type orderType
}

type orderType string

const (
	orderTypeAsc  orderType = ""
	orderTypeDesc           = "-"
)

type filter struct {
	Name  string
	Type  filterType
	Value lazy.Value
}

type filterType string

const (
	filterTypeEq filterType = "="
	filterTypeLe            = "<="
	filterTypeLt            = "<"
	filterTypeGe            = ">="
	filterTypeGt            = ">"
	filterTypeNe            = "!="
)

// FilterValueOmit is a value to omit the filter.
//
//     q.Eq("FieladName", lazy.LazyFunc(func(ctx) lazy.Value {
//         v, ok :=  ctx.Value("filterValue").(string)
//         if ok {
//             return v;
//         }
//         return query.FilterValueOmit
//     }))
//
// This means if 'filterValue' does not present in the context nor a int value,
// FieldName filter is not be applied in the query q.
var FilterValueOmit = lazy.Value(nil)

// GetAll fills the query result into dst and returns corresponding *datastore.Key
func (q *Query) GetAll(ctx context.Context, dst interface{}) ([]*datastore.Key, error) {
	query, err := q.prepare(ctx)
	if err != nil {
		return nil, err
	}
	return query.GetAll(ctx, dst)
}

// Run runs a query and returns *datastore.Iterator
func (q *Query) Run(ctx context.Context) (*datastore.Iterator, error) {
	query, err := q.prepare(ctx)
	if err != nil {
		return nil, err
	}
	return query.Run(ctx), nil
}

// Count returns a count
func (q *Query) Count(ctx context.Context) (int, error) {
	query, err := q.prepare(ctx)
	if err != nil {
		return 0, err
	}
	return query.Count(ctx)
}

func (q *Query) prepare(ctx context.Context) (*datastore.Query, error) {
	ctx, logger := xlog.WithContextAndKey(ctx, "", q.loggerKey)
	var buff []string
	query := datastore.NewQuery(q.kind)

	if q.projects != nil {
		query = query.Project(q.projects...)
		buff = append(buff, fmt.Sprintf("Projects: %v", q.projects))
	}

	if q.ancestor != nil {
		v, err := q.ancestor.Eval(ctx)
		if err != nil {
			return nil, fmt.Errorf("ancestor field error: %v", err)
		}
		if vv, ok := v.(*datastore.Key); ok {
			query = query.Ancestor(vv)
			buff = append(buff, fmt.Sprintf("Ancestor: %v", vv))
		}
	}

	if q.filters != nil {
		var s []string
		for _, f := range q.filters {
			val, err := f.Value.Eval(ctx)
			if err != nil {
				return nil, fmt.Errorf("%s filter error: %v", f.Name, err)
			}
			if val != FilterValueOmit {
				query = query.Filter(
					fmt.Sprintf("%s %s", f.Name, f.Type),
					val,
				)
				s = append(s, fmt.Sprintf("%s %s %s", f.Name, f.Type, val))
			}
		}
		buff = append(buff, fmt.Sprintf("Filter: %v", strings.Join(s, " AND ")))
	}

	if q.orders != nil {
		var s []string
		for _, o := range q.orders {
			order := fmt.Sprintf("%s%s", o.Type, o.Name)
			query = query.Order(
				fmt.Sprintf(order),
			)
			s = append(s, order)
		}
		buff = append(buff, fmt.Sprintf("Order: %v", strings.Join(s, " ")))
	}

	if q.limit != nil {
		v, err := q.limit.Eval(ctx)
		if err != nil {
			return nil, fmt.Errorf("limit error: %v", err)
		}
		if vv, ok := v.(int); ok {
			query = query.Limit(vv)
			buff = append(buff, fmt.Sprintf("Limit: %d", vv))
		}
	}

	if q.startCursor != nil {
		v, err := q.startCursor.Eval(ctx)
		if err != nil {
			return nil, fmt.Errorf("start cursor error: %v", err)
		}
		if str := fmt.Sprintf("%s", v); str != "" {
			if vv, err := datastore.DecodeCursor(str); err == nil {
				query = query.Start(vv)
				buff = append(buff, fmt.Sprintf("Start: %s", vv))
			}
		}
	}

	if q.endCursor != nil {
		v, err := q.endCursor.Eval(ctx)
		if err != nil {
			return nil, fmt.Errorf("end cursor error: %v", err)
		}
		if str := fmt.Sprintf("%s", v); str != "" {
			if vv, err := datastore.DecodeCursor(str); err == nil {
				query = query.End(vv)
				buff = append(buff, fmt.Sprintf("End: %s", vv))
			}
		}
	}

	if q.keysOnly {
		query = query.KeysOnly()
		buff = append(buff, "KeysOnly: true")
	}

	logger.Debug(func(p *xlog.Printer) {
		p.Printf("Query: Kind=%s\n", q.kind)
		for _, line := range buff {
			p.Printf("\t%s\n", line)
		}
	})
	return query, nil
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ad8f0b86/css/bootstrap.css" rel="stylesheet">
<link href="./assets/f07207ee/solarized_light.css" rel="stylesheet">
<link href="./assets/67e76fc4/style.css" rel="stylesheet">

    <title>Dificultades Encontradas y Soluciones Aplicadas - Dificultades Encontradas y Soluciones Aplicadas - Guía de We 'r' Gamers</title>

<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w130-collapse">Toggle navigation

</button>Guía de We 'r' Gamers

Class reference

Guide

    <input id="searchbox" type="text" class="form-control" placeholder="Search">

Descripción General del Proyecto
Funcionalidad Principal de la Aplicación
Objetivos Generales
Repositorio en GitHub
Documentación

Instrucciones de instalación y despliegue
En local
En la nube

Catálogo de Requisitos
Definición Detallada
Cuadro Resumen

Manual Básico de Usuario
Manual

Decisiones Adoptadas y su Justificación
Decisiones Adoptadas y su Justificación

Dificultades Encontradas y Soluciones Aplicadas
Dificultades Encontradas y Soluciones Aplicadas

Diagramas
De Clases
De Estructura Lógica de Datos

Glosario de Términos
Glosario de Términos

Conclusiones
Conclusiones

Anexos
Prueba del seis
Validación
Compatibilidad del diseño con navegadores

Dificultades Encontradas y Soluciones Aplicadas ¶

Navbar generado de Yii2 ¶

El navbar con clases de bootstrap que genera Yii2 es poco flexible y da
muchos problemas en cuanto quieres hacer algo que no sea muy común o que algún
componente sea responsive, por lo que he optado por no usar el widget e
implementarlo yo.

Chat en tiempo real y funcionando en heroku ¶

El chat con lo visto en clase era imposible hacerlo en tiempo real, por
lo que investigué maneras de hacerlo y aprendí un poco de node.js y socket.io,
con lo que además conseguí implementar alguna funcionalidad más típica de los
chats.

Para que el chat funcionase en heroku necesitaba arrancar una aplicación en
node.js y escuchar por un puerto, primero me hice una aplicación de chat de
prueba con yii2 y node.js e intenté subirlo en un mismo dyno, una vez conseguido
intenté arrancar la aplicación de node.js en el mismo dyno con un buidpack
que permitía ejecutar varios comandos por dyno, pero no sirvió para nada porque
heroku sólo deja un puerto abierto por aplicación y necesitaba dos, uno para el
proyecto y otro para la aplicación en node.js. Al final opté por hacer una
aplicación aparte en heroku llamada jomari-listener para el chat.

Al ser una aplicación aparte y recibir peticiones desde un dominio distinto
al que pertenece tuve que habilitar las CORS (Cross Origin HTTP Request) ya que
por razones de seguridad, los exploradores restringen las solicitudes HTTP de
origen cruzado iniciadas dentro de un script.

Page generated on Mon, 12 Jun 2017 14:23:24 +0000

    Powered by Yii Framework


text:
from buildtest.config import load_settings
from buildtest.menu.build import discover_buildspecs, resolve_testdirectory, build_phase
from buildtest.menu.buildspec import parse_buildspecs

tagname = ["tutorials"]
print(f"Searching by tagname: {tagname}")
included_bp, excluded_bp = discover_buildspecs(tags=tagname)
print(f"discovered_buildspec: {included_bp} \n\n")

configuration = load_settings()
testdir = resolve_testdirectory(configuration)
builders = parse_buildspecs(included_bp, testdir, printTable=True)

build_phase(builders, printTable=True)


text:
import cv2
import numpy as np
import math

class SingleTileAffineRenderer:

    def __init__(self, img_path, width, height, compute_mask=False, compute_distances=True):
        self.img_path = img_path
        self.width = width
        self.height = height
        self.transform_matrix = np.eye(3)[:2]
        self.compute_mask = compute_mask
        self.mask = None
        self.compute_distances = compute_distances
        self.weights = None
        self.update_img_transformed_corners_and_bbox()

        # Save for caching
        self.already_rendered = False

    def add_transformation(self, transform_matrix):
        assert(transform_matrix.shape == (2, 3))
        self.transform_matrix = np.dot(np.vstack((transform_matrix, [0., 0., 1.])), np.vstack((self.transform_matrix, [0., 0., 1.])))[:2]
        self.update_img_transformed_corners_and_bbox()

        # Remove any rendering
        self.already_rendered = False
        self.img = None

    def get_start_point(self):
        return (self.bbox[0], self.bbox[2])

    def get_bbox(self):
        return self.bbox

#    def contains_point(self, p):
#        """Return True if the point is inside the image boundaries (bounding polygon)."""

    def get_min_distance(self, points):
        """Returns a list of minimal distances between each of the given points and any of the image boundaries (bounding polygon).
           Assumes that the given points are inside the bounding polygon."""
        #assert(p.shape == (2,))
        # Get the normals of each line, and compute the distance between the point and the normal
        # Based on method 2 (but for 2D) from: http://www.qc.edu.hk/math/Advanced%20Level/Point_to_line.htm
        denominators = [np.linalg.norm(self.corners[i] - self.corners[(i + 1) % len(self.corners)]) for i in range(len(self.corners))]
        self_normals = get_normals(self.corners)
        if points.shape == (2,): # A single point
            dist = np.min([np.linalg.norm(np.dot(n, points - c)) / denom
                        for c, n, denom in zip(self.corners, self_normals, denominators)])
            return dist
        else: # multiple points
            dists = [np.min([np.linalg.norm(np.dot(n, p - c)) / denom
                        for c, n, denom in zip(self.corners, self_normals, denominators)])
                            for p in points]
            return dists

    def is_overlapping(self, other_tile):
        """Uses Separating Axes Theorem (http://www.dyn4j.org/2010/01/sat/) in order to decide
           whether the the current transformed tile and the other transformed tile are overlapping"""
        # Fetch the normals of each tile
        self_normals = get_normals(self.corners)
        other_normals = get_normals(other_tile.corners)
        # Check all edges of self against the normals of the other tile
        if not check_normals_side(self.corners, self_normals, other_tile.corners):
            return True
        # Check all edges of the other tile against the normals of self
        if not check_normals_side(other_tile.corners, other_normals, self.corners):
            return True
        return False

    def render(self):
        """Returns the rendered image (after transformation), and the start point of the image in global coordinates"""
        if self.already_rendered:
            return self.img, np.array([self.bbox[0], self.bbox[1]])

        img = cv2.imread(self.img_path, 0)
        adjusted_transform = self.transform_matrix[:2].copy()
        adjusted_transform[0][2] -= self.bbox[0]
        adjusted_transform[1][2] -= self.bbox[2]

        self.img = cv2.warpAffine(img, adjusted_transform, self.shape, flags=cv2.INTER_AREA)
        self.already_rendered = True
        if self.compute_mask:
            mask_img = np.ones(img.shape)
            self.mask = cv2.warpAffine(mask_img, adjusted_transform, self.shape, flags=cv2.INTER_AREA)
            self.mask[self.mask > 0] = 1
        if self.compute_distances:
            # The initial weights for each pixel is the minimum from the image boundary
            grid = np.mgrid[0:self.height, 0:self.width]
            weights_img = np.minimum(
                                np.minimum(grid[0], self.height - 1 - grid[0]),
                                np.minimum(grid[1], self.width - 1 - grid[1])
                            ).astype(np.float32)
            self.weights = cv2.warpAffine(weights_img, adjusted_transform, self.shape, flags=cv2.INTER_AREA)
        # Returns the transformed image and the start point
        return self.img, (self.bbox[0], self.bbox[2])

    def fetch_mask(self):
        assert(self.compute_mask)

        if not self.already_rendered:
            self.render()

        return self.mask, (self.bbox[0], self.bbox[2])

    def crop(self, from_x, from_y, to_x, to_y):
        """Returns the cropped image, its starting point, and the cropped mask (if the mask was computed).
           The given coordinates are specified using world coordinates."""
        # find the overlapping area of the given coordinates and the transformed tile
        overlapping_area = [max(from_x, self.bbox[0]), min(to_x, self.bbox[1]), max(from_y, self.bbox[2]), min(to_y, self.bbox[3])]
        overlapping_width = overlapping_area[1] - overlapping_area[0] + 1
        overlapping_height = overlapping_area[3] - overlapping_area[2] + 1
        if overlapping_width <= 0 or overlapping_height <= 0:
            # No overlap between the area and the tile
            return None, None, None

        cropped_mask = None
        # Make sure the image was rendered
        self.render()
        cropped_img = self.img[overlapping_area[2] - self.bbox[2]:overlapping_area[3] - self.bbox[2] + 1,
                               overlapping_area[0] - self.bbox[0]:overlapping_area[1] - self.bbox[0] + 1]
        if self.compute_mask:
            cropped_mask = self.mask[overlapping_area[2] - self.bbox[2]:overlapping_area[3] - self.bbox[2] + 1,
                                     overlapping_area[0] - self.bbox[0]:overlapping_area[1] - self.bbox[0] + 1]
        # Take only the parts that are overlapping
        return cropped_img, (overlapping_area[0], overlapping_area[2]), cropped_mask

    def crop_with_distances(self, from_x, from_y, to_x, to_y):
        """Returns the cropped image, its starting point, and the cropped image L1 distances of each pixel inside the image from the edge
           of the rendered image (if the mask was computed).
           The given coordinates are specified using world coordinates."""
        # find the overlapping area of the given coordinates and the transformed tile
        overlapping_area = [max(from_x, self.bbox[0]), min(to_x, self.bbox[1]), max(from_y, self.bbox[2]), min(to_y, self.bbox[3])]
        overlapping_width = overlapping_area[1] - overlapping_area[0] + 1
        overlapping_height = overlapping_area[3] - overlapping_area[2] + 1
        if overlapping_width <= 0 or overlapping_height <= 0:
            # No overlap between the area and the tile
            return None, None, None

        cropped_distances = None
        # Make sure the image was rendered
        self.render()
        cropped_img = self.img[overlapping_area[2] - self.bbox[2]:overlapping_area[3] - self.bbox[2] + 1,
                               overlapping_area[0] - self.bbox[0]:overlapping_area[1] - self.bbox[0] + 1]
#        if self.compute_mask:
#            cropped_mask = self.mask[overlapping_area[2] - self.bbox[2]:overlapping_area[3] - self.bbox[2] + 1,
#                                     overlapping_area[0] - self.bbox[0]:overlapping_area[1] - self.bbox[0] + 1]
#            # find for each row where is the first and last one
#            rows_ones = find_per_row_first_last_one(cropped_mask)
#            cols_ones = find_per_row_first_last_one(cropped_mask.T)
#            # fill the weights matrix according to the distance of each pixel from it's row and col values
#            grid = np.mgrid[0:cropped_mask.shape[0], 0:cropped_mask.shape[1]]
#            cropped_distances = np.minimum(
#                                    np.minimum(np.abs(grid[0] - cols_ones[:, 0]), np.abs(grid[0] - cols_ones[:, 1])),
#                                    np.minimum(np.abs(grid[1].T - rows_ones[:, 0].T).T, np.abs(grid[1].T - rows_ones[:, 1].T).T)
#                                )
#            # Filter only the weights that are on the mask (using elementwise multiplication)
#            cropped_distances = cropped_distances * cropped_mask

        if self.compute_distances:
            cropped_distances = self.weights[overlapping_area[2] - self.bbox[2]:overlapping_area[3] - self.bbox[2] + 1,
                                             overlapping_area[0] - self.bbox[0]:overlapping_area[1] - self.bbox[0] + 1]

        # Take only the parts that are overlapping
        return cropped_img, (overlapping_area[0], overlapping_area[2]), cropped_distances

    # Helper methods (shouldn't be used from the outside)
    def update_img_transformed_corners_and_bbox(self):
        pts = np.array([[0., 0.], [self.width - 1, 0.], [self.width - 1, self.height - 1], [0., self.height - 1]])
        self.corners = np.dot(self.transform_matrix[:2,:2], pts.T).T + np.asarray(self.transform_matrix.T[2][:2]).reshape((1, 2))
        min_XY = np.min(self.corners, axis=0)
        max_XY = np.max(self.corners, axis=0)
        # Rounding to avoid float precision errors due to representation
        self.bbox = [int(math.floor(round(min_XY[0], 5))), int(math.ceil(round(max_XY[0], 5))), int(math.floor(round(min_XY[1], 5))), int(math.ceil(round(max_XY[1], 5)))]
        #self.bbox = [int(min_XY[0] + math.copysign(0.5, min_XY[0])), int(max_XY[0] + math.copysign(0.5, max_XY[1])), int(min_XY[1] + math.copysign(0.5, min_XY[1])), int(max_XY[1] + math.copysign(0.5, max_XY[1]))]
        self.shape = (self.bbox[1] - self.bbox[0] + 1, self.bbox[3] - self.bbox[2] + 1)

def get_normals(corners):
    """Given a polygon corners list, returns a list of non-normalized normals for each edge"""
    edges = [(corners[i] - corners[(i + 1) % len(corners)]) for i in range(len(corners))]
    normals = [(-e[1], e[0]) for e in edges]
    return normals

def check_normals_side(corners1, normals1, corners2):
    """Checks if all corners2 appear on one side of polygon1"""
    assert(len(corners1) == len(normals1))
    for c, n in zip(corners1, normals1):
        signs2 = [np.sign(np.dot(n, p - c)) for p in corners2]
        signs2 = [s for s in signs2 if abs(s - 0.) > 0.0001] # remove all +-0.
        if np.any(signs2 != signs2[0]):
            return False
    return True

def find_per_row_first_last_one(arr):
    """Given a 2D array (of only 1's in a quadrangle shape, and 0's), for each row find the first and the last occurrance of 1.
       Returns a 2D array with the same number of rows as arr, and 2 columns with the column-indices
       of the first and last one. If a row has only 0's, -1 will be returned on both indices"""
    res = np.full((arr.shape[0], 2), -1, dtype=np.int16)
    # take the first and last column of arr, and find all 1's
    arr_T = arr.T
    first_col_non_zero = np.nonzero(arr_T[0])
    last_col_non_zero = np.nonzero(arr_T[-1])
    for r in first_col_non_zero[0]:
        res[r, 0] = 0
    for r in last_col_non_zero[0]:
        res[r, 1] = arr.shape[1] - 1
    # Now find the positions where the value changes in the middle of the matrix using np.diff
    nonzero = np.nonzero(np.diff(arr))
    # nonzero contents for each row, r:
    #   if nonzero doesn't have a row with r, the row has the same value (either 0 or 1)
    #   if nonzero has a single row with r, the row changes the value once (either from 0 to 1 or from 1 to 0)
    #   if nonzero has row r twice, the row changes both from 0 to 1 and then from 1 to 0
    for r, c in zip(*nonzero):
        if res[r, 0] > -1:
            # already updated the left value, or there is a single change from 1 to 0
            res[r, 1] = c
        else:
            res[r, 0] = c + 1
    return res


text:
package device

import (
	"fmt"
	"path/filepath"
	"strconv"
	"strings"
	"sync"

	deviceConfig "github.com/lxc/lxd/lxd/device/config"
	"github.com/lxc/lxd/lxd/instance"
	"github.com/lxc/lxd/lxd/state"
	log "github.com/lxc/lxd/shared/log15"
	"github.com/lxc/lxd/shared/logger"
)

// USBEvent represents the properties of a USB device uevent.
type USBEvent struct {
	Action string

	Vendor  string
	Product string

	Path        string
	Major       uint32
	Minor       uint32
	UeventParts []string
	UeventLen   int
}

// usbHandlers stores the event handler callbacks for USB events.
var usbHandlers = map[string]func(USBEvent) (*deviceConfig.RunConfig, error){}

// usbMutex controls access to the usbHandlers map.
var usbMutex sync.Mutex

// usbRegisterHandler registers a handler function to be called whenever a USB device event occurs.
func usbRegisterHandler(inst instance.Instance, deviceName string, handler func(USBEvent) (*deviceConfig.RunConfig, error)) {
	usbMutex.Lock()
	defer usbMutex.Unlock()

	// Null delimited string of project name, instance name and device name.
	key := fmt.Sprintf("%s\000%s\000%s", inst.Project(), inst.Name(), deviceName)
	usbHandlers[key] = handler
}

// usbUnregisterHandler removes a registered USB handler function for a device.
func usbUnregisterHandler(inst instance.Instance, deviceName string) {
	usbMutex.Lock()
	defer usbMutex.Unlock()

	// Null delimited string of project name, instance name and device name.
	key := fmt.Sprintf("%s\000%s\000%s", inst.Project(), inst.Name(), deviceName)
	delete(usbHandlers, key)
}

// USBRunHandlers executes any handlers registered for USB events.
func USBRunHandlers(state *state.State, event *USBEvent) {
	usbMutex.Lock()
	defer usbMutex.Unlock()

	for key, hook := range usbHandlers {
		keyParts := strings.SplitN(key, "\000", 3)
		projectName := keyParts[0]
		instanceName := keyParts[1]
		deviceName := keyParts[2]

		if hook == nil {
			delete(usbHandlers, key)
			continue
		}

		runConf, err := hook(*event)
		if err != nil {
			logger.Error("USB event hook failed", log.Ctx{"err": err, "project": projectName, "instance": instanceName, "device": deviceName})
			continue
		}

		// If runConf supplied, load instance and call its USB event handler function so
		// any instance specific device actions can occur.
		if runConf != nil {
			instance, err := instance.LoadByProjectAndName(state, projectName, instanceName)
			if err != nil {
				logger.Error("USB event loading instance failed", log.Ctx{"err": err, "project": projectName, "instance": instanceName, "device": deviceName})
				continue
			}

			err = instance.DeviceEventHandler(runConf)
			if err != nil {
				logger.Error("USB event instance handler failed", log.Ctx{"err": err, "project": projectName, "instance": instanceName, "device": deviceName})
				continue
			}
		}
	}
}

// USBNewEvent instantiates a new USBEvent struct.
func USBNewEvent(action string, vendor string, product string, major string, minor string, busnum string, devnum string, devname string, ueventParts []string, ueventLen int) (USBEvent, error) {
	majorInt, err := strconv.ParseUint(major, 10, 32)
	if err != nil {
		return USBEvent{}, err
	}

	minorInt, err := strconv.ParseUint(minor, 10, 32)
	if err != nil {
		return USBEvent{}, err
	}

	path := devname
	if devname == "" {
		busnumInt, err := strconv.Atoi(busnum)
		if err != nil {
			return USBEvent{}, err
		}

		devnumInt, err := strconv.Atoi(devnum)
		if err != nil {
			return USBEvent{}, err
		}
		path = fmt.Sprintf("/dev/bus/usb/%03d/%03d", busnumInt, devnumInt)
	} else {
		if !filepath.IsAbs(devname) {
			path = fmt.Sprintf("/dev/%s", devname)
		}
	}

	return USBEvent{
		action,
		vendor,
		product,
		path,
		uint32(majorInt),
		uint32(minorInt),
		ueventParts,
		ueventLen,
	}, nil
}


text:
function Export-PortGroupNicTeaming {
<#
.SYNOPSIS
  Creates a csv file with VMware vNetwork Portgroup to vmnic relationship and vSW/vPG properties
.DESCRIPTION
  Creates a csv file with VMware vNetwork Portgroup to vmnic relationship and vSW/vPG properties
.NOTES
  Release 1.5
  Robert Ebneth
  July, 12th, 2017
.LINK
  http://github.com/rebneth/RobertEbneth.VMware.vSphere.Reporting
.PARAMETER Cluster
  Selects only ESXi servers from this vSphere Cluster. If nothing is specified,
  all vSphere Clusters will be taken.
.PARAMETER Filename
  The path and filename of the CSV file to use when exporting
  DEFAULT: $($env:USERPROFILE)\vSwitch_portgroup_nicteaming_and_shaping_$(get-date -f yyyy-MM-dd-HH-mm-ss).csv
.EXAMPLE
  Export-PortGroupNicTeaming -FILENAME d:\vm_vSW_vPG_NicTeaming.csv
#>

[CmdletBinding()]
 param(
    [Parameter(Mandatory = $False, ValueFromPipeline=$true, Position = 0)]
    [Alias("c")]
    [string]$CLUSTER,
    [Parameter(Mandatory = $false, Position = 1)]
    [alias("f")]
    [string]$FILENAME = "$($env:USERPROFILE)\vSwitch_portgroup_nicteaming_and_shaping_$(get-date -f yyyy-MM-dd-HH-mm-ss).csv"
)

Begin {
    # Check and if not loaded add Powershell core module
    if ( !(Get-Module -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) ) {
        Import-Module VMware.VimAutomation.Core
    }
    if ( !(Get-Module -Name VMware.VimAutomation.Vds -ErrorAction SilentlyContinue) ) {
        Import-Module VMware.VimAutomation.Vds
    }
    # We need the common function CheckFilePathAndCreate
    Get-Command "CheckFilePathAndCreate" -errorAction SilentlyContinue | Out-Null
    if ( $? -eq $false) {
        Write-Error "Function CheckFilePathAndCreate is missing."
        break
    }
	$OUTPUTFILENAME = CheckFilePathAndCreate "$FILENAME"
    $report = @()
} ### End Begin

Process {

    ########
    # Main #
    ########

    # If we do not get Cluster from Input, we take them all from vCenter
	If ( !$Cluster ) {
		$Cluster_to_process = (Get-Cluster | Select Name).Name | Sort}
	  else {
		$Cluster_to_process = $CLUSTER
	}

	foreach ( $Cluster in $Cluster_to_process ) {
 	$status = Get-Cluster $Cluster
    If ( $? -eq $false ) {
		Write-Host "Error: Required Cluster $($Cluster) does not exist." -ForegroundColor Red
		break
    }

    foreach ( $VMHost in (Get-Cluster -Name $Cluster | Get-VMHost | Sort Name)) {
        Write-Host "Collecting Virtual Networking information for ESXi host $($VMHost.Name)..."
		$esxi_
        $vNicTab = @{}
		$VMHost.ExtensionData.Config.Network.Vnic | %{ $vNicTab.Add($_.Portgroup,$_)}
        foreach($vsw in (Get-VirtualSwitch -VMHost $VMHost)){
            $VSWprops = "" | Select Cluster, ESXiHost, vSwitch, Portgroup, VLAN, ActiveNIC, StandbyNIC, Device, Mac, DHCP, IP, SubnetMask, MTU, AllowPromiscuous, MacChanges, ForgedTransmits, TsoEnabled, Policy, NotifySwitches, RollingOrder, ShapingEnabled, AverageBandwidth, PeakBandwidth, BurstSize
			$VSWprops.Cluster = $Cluster
			$VSWprops.ESXiHost = $($VMHost.Name)
			$VSWprops.vSwitch = $vsw
			$VSWprops.PortGroup = "vSwitch Settings"
            if ($vsw.extensiondata.spec.policy.Nicteaming.NicOrder.ActiveNic) {
                $VSWprops.ActiveNIC = [string]::Join(',',$vsw.extensiondata.spec.policy.Nicteaming.NicOrder.ActiveNic)}
            if ($vsw.extensiondata.spec.policy.Nicteaming.NicOrder.StandbyNic) {
                $VSWprops.StandbyNIC = [string]::Join(',',$vsw.extensiondata.spec.policy.Nicteaming.NicOrder.StandbyNic)}
            $VSWprops.MTU = $vsw.Mtu
            $VSWprops.AllowPromiscuous = $vsw.extensiondata.Spec.Policy.Security.AllowPromiscuous
            $VSWprops.MacChanges = $vsw.extensiondata.Spec.Policy.Security.MacChanges
            $VSWprops.ForgedTransmits = $vsw.extensiondata.Spec.Policy.Security.ForgedTransmits
            $VSWprops.Policy = $vsw.extensiondata.Spec.Policy.Nicteaming.Policy
			$VSWprops.NotifySwitches = $vsw.extensiondata.Spec.Policy.Nicteaming.NotifySwitches
			$VSWprops.RollingOrder = $vsw.extensiondata.Spec.Policy.Nicteaming.RollingOrder
            $VSWprops.ShapingEnabled = $vsw.ExtensionData.Spec.Policy.ShapingPolicy.ShapingEnabled
            $VSWprops.AverageBandwidth = $vsw.ExtensionData.Spec.Policy.ShapingPolicy.AverageBandwidth
            $VSWprops.PeakBandwidth = $vsw.ExtensionData.Spec.Policy.ShapingPolicy.PeakBandwidth
            $VSWprops.BurstSize = $vsw.ExtensionData.Spec.Policy.ShapingPolicy.BurstSize
            $report += $VSWprops
			foreach($pg in (Get-VirtualPortGroup -VirtualSwitch $vsw)){
				$PGprops = "" | Select Cluster, ESXiHost, vSwitch, Portgroup, VLAN, Setting, ActiveNIC, StandbyNIC, Device, Mac, DHCP, IP, SubnetMask, MTU, AllowPromiscuous, MacChanges, ForgedTransmits, TsoEnabled, Policy, NotifySwitches, RollingOrder, ShapingEnabled, AverageBandwidth, PeakBandwidth, BurstSize
				$PGprops.Cluster = $Cluster
				$PGprops.ESXiHost = $($VMHost.Name)
				$PGprops.vSwitch = $vsw
				$PGprops.PortGroup = $pg.Name
				$PGprops.VLAN = $pg.VLanId
                if ($pg.extensiondata.spec.policy.Nicteaming.NicOrder.ActiveNic) {
                    $PGprops.ActiveNIC = [string]::Join(',',$pg.extensiondata.spec.policy.Nicteaming.NicOrder.ActiveNic)}
                if ($pg.extensiondata.spec.policy.Nicteaming.NicOrder.StandbyNic) {
                    $PGprops.StandbyNIC = [string]::Join(',',$pg.extensiondata.spec.policy.Nicteaming.NicOrder.StandbyNic)}
				if ($vNicTab.ContainsKey($pg.Name)) {
                    $PGprops.Device = $vNicTab[$pg.Name].Device
                    $PGprops.Mac = $vNicTab[$pg.Name].Spec.Mac
                    $PGprops.Dhcp = $vNicTab[$pg.Name].Spec.Ip.Dhcp
                    $PGprops.IP = $vNicTab[$pg.Name].Spec.Ip.IpAddress
                    $PGprops.SubnetMask = $vNicTab[$pg.Name].Spec.Ip.SubnetMask
                    $PGprops.MTU = $vNicTab[$pg.Name].Spec.Mtu
                }
                $PGprops.AllowPromiscuous = $pg.extensiondata.Spec.Policy.Security.AllowPromiscuous
                $PGprops.MacChanges = $pg.extensiondata.Spec.Policy.Security.MacChanges
                $PGprops.ForgedTransmits =$pg.extensiondata.Spec.Policy.Security.ForgedTransmits
                $PGprops.Policy = $pg.extensiondata.Spec.Policy.Nicteaming.Policy
                $PGprops.TsoEnabled = $pg.extensiondata.Spec.TsoEnabled
                $PGprops.ShapingEnabled = $pg.extensiondata.Spec.Policy.ShapingPolicy.Enabled
                $PGprops.AverageBandwidth = $pg.extensiondata.Spec.Policy.ShapingPolicy.AverageBandwidth
                $PGprops.PeakBandwidth = $pg.extensiondata.Spec.Policy.ShapingPolicy.PeakBandwidth
                $PGprops.BurstSize = $pg.extensiondata.Spec.Policy.ShapingPolicy.BurstSize
				$PGprops.NotifySwitches = $pg.extensiondata.Spec.Policy.Nicteaming.NotifySwitches
				$PGprops.RollingOrder = $pg.extensiondata.Spec.Policy.Nicteaming.RollingOrder
                $report += $PGprops
			} ### End Foreach Portgroup
		} ### End Foreach vSwitch
    } ### End foreach esxi host
} ### End foreach cluster

} ### End Process

    End {
    $report | Export-csv -Delimiter ";" $OUTPUTFILENAME -noTypeInformation
	Write-Host "Writing Outputfile $($OUTPUTFILENAME)..."
    $report | ft -AutoSize
} ### End End

} ### End Function
# SIG # Begin signature block
# MIIFmgYJKoZIhvcNAQcCoIIFizCCBYcCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU9T6yNRwHd+jUiJXcZ8MF/II3
# P6GgggMmMIIDIjCCAgqgAwIBAgIQPWSBWJqOxopPvpSTqq3wczANBgkqhkiG9w0B
# AQUFADApMScwJQYDVQQDDB5Sb2JlcnRFYm5ldGhJVFN5c3RlbUNvbnN1bHRpbmcw
# HhcNMTcwMjA0MTI0NjQ5WhcNMjIwMjA1MTI0NjQ5WjApMScwJQYDVQQDDB5Sb2Jl
# cnRFYm5ldGhJVFN5c3RlbUNvbnN1bHRpbmcwggEiMA0GCSqGSIb3DQEBAQUAA4IB
# DwAwggEKAoIBAQCdqdh2MLNnST7h2crQ7CeJG9zXfPv14TF5v/ZaO8yLmYkJVsz1
# tBFU5E1aWhTM/fk0bQo0Qa4xt7OtcJOXf83RgoFvo4Or2ab+pKSy3dy8GQ5sFpOt
# NsvLECxycUV/X/qpmOF4P5f4kHlWisr9R6xs1Svf9ToktE82VXQ/jgEoiAvmUuio
# bLLpx7/i6ii4dkMdT+y7eE7fhVsfvS1FqDLStB7xyNMRDlGiITN8kh9kE63bMQ1P
# yaCBpDegi/wIFdsgoSMki3iEBkiyF+5TklatPh25XY7x3hCiQbgs64ElDrjv4k/e
# WJKyiow3jmtzWdD+xQJKT/eqND5jHF9VMqLNAgMBAAGjRjBEMBMGA1UdJQQMMAoG
# CCsGAQUFBwMDMA4GA1UdDwEB/wQEAwIHgDAdBgNVHQ4EFgQUXJLKHJBzYZdTDg9Z
# QMC1/OLMbxUwDQYJKoZIhvcNAQEFBQADggEBAGcRyu0x3vL01a2+GYU1n2KGuef/
# 5jhbgXaYCDm0HNnwVcA6f1vEgFqkh4P03/7kYag9GZRL21l25Lo/plPqgnPjcYwj
# 5YFzcZaCi+NILzCLUIWUtJR1Z2jxlOlYcXyiGCjzgEnfu3fdJLDNI6RffnInnBpZ
# WdEI8F6HnkXHDBfmNIU+Tn1znURXBf3qzmUFsg1mr5IDrF75E27v4SZC7HMEbAmh
# 107gq05QGvADv38WcltjK1usKRxIyleipWjAgAoFd0OtrI6FIto5OwwqJxHR/wV7
# rgJ3xDQYC7g6DP6F0xYxqPdMAr4FYZ0ADc2WsIEKMIq//Qg0rN1WxBCJC/QxggHe
# MIIB2gIBATA9MCkxJzAlBgNVBAMMHlJvYmVydEVibmV0aElUU3lzdGVtQ29uc3Vs
# dGluZwIQPWSBWJqOxopPvpSTqq3wczAJBgUrDgMCGgUAoHgwGAYKKwYBBAGCNwIB
# DDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEE
# AYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUpkvU/lSURv1P
# UMW8agkuTAZtUq4wDQYJKoZIhvcNAQEBBQAEggEASdmlahvSeif/jVeDrXrRSloG
# DoD0RfgQV3VdSm7IzwCVclJ/zxzH+b7MZj0hWMTPCjpxIAC2dpp12d/ysq1TW8AS
# vX7ht+K+/9DA7GdyW6Ey/aYkTL4XLYVrVyo96j4RgSqQBqw9p3S9gAGxOv6QSYpS
# rVZVmc37JMm3wJ7KW8S5huEInaf+MGr3CCV//ublMrA/zi9IsDiHlIqNUNBkd4nf
# 9k5oA7LeZcFF4FgB6IaIfQ458N6bNHSP8fAOAr55g8KZOMADFJmPs5CXAL0uE5hG
# JXQg1LlywjvseDLyU8EZgtIfCvke0sL088QMsKX+IYzfFmpfu4jtDdV7bH8mkQ==
# SIG # End signature block


text:
from __future__ import absolute_import

import itertools

import nose

from climin import GradientDescent

from .losses import Quadratic, LogisticRegression, Rosenbrock
from .common import continuation

def test_gd_quadratic():
    obj = Quadratic()
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9)
    for i, info in enumerate(opt):
        if i > 500:
            break
    assert obj.solved(), 'did not find solution'

@nose.tools.nottest
def test_gd_rosen():
    obj = Rosenbrock()
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9)
    for i, info in enumerate(opt):
        if i > 5000:
            break
    assert ((1 - obj.pars) < 0.01).all(), 'did not find solution'

def test_gd_lr():
    obj = LogisticRegression()
    args = itertools.repeat(((obj.X, obj.Z), {}))
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9, args=args)
    for i, info in enumerate(opt):
        if i > 500:
            break
    assert obj.solved(), 'did not find solution'

def test_gd_quadratic_nesterov():
    obj = Quadratic()
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9,
        momentum_type='nesterov')
    for i, info in enumerate(opt):
        if i > 500:
            break
    assert obj.solved(), 'did not find solution'

@nose.tools.nottest
def test_gd_rosen_nesterov():
    obj = Rosenbrock()
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9,
        momentum_type='nesterov')
    for i, info in enumerate(opt):
        if i > 5000:
            break
    assert ((1 - obj.pars) < 0.01).all(), 'did not find solution'

def test_gd_lr_nesterov():
    obj = LogisticRegression()
    args = itertools.repeat(((obj.X, obj.Z), {}))
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9,
        momentum_type='nesterov',
        args=args)
    for i, info in enumerate(opt):
        if i > 500:
            break
    assert obj.solved(), 'did not find solution'

def test_gd_continue():
    obj = LogisticRegression(n_inpt=2, n_classes=2)
    args = itertools.repeat(((obj.X, obj.Z), {}))
    opt = GradientDescent(
        obj.pars, obj.fprime, step_rate=0.01, momentum=.9,
        momentum_type='nesterov',
        args=args)

    continuation(opt)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using REvolution.Core.Generator;

namespace REvolution.Core.Syntax.Nodes
{
    public class One : Node
    {
        public override NodeType Type
        {
            get { return NodeType.One; }
        }

        private char _character;

        public char Character
        {
            get { return _character; }
        }

        public One(NodeParent parent, Token token)
            : base(parent)
        {
            Tokens.Add(token);
            _character = token.ReadChar();
        }

        public override string GenerateContent(GenerateContext context)
        {
            StringBuilder builder = new StringBuilder();
            if (context == null || context.Mode == GenerateMode.SingleLine)
                builder.Append(Tokens[0].Text);
            else
            {
                string esc = CharUtils.EscapeWhiteSpace(Tokens[0].Text[0]);
                if (esc == null)
                    builder.Append(Tokens[0].Text);
                else
                    builder.Append(esc);
            }
            return builder.ToString();
        }
    }
}


text:
import os

# inspect.signature is only available in Python 3. funcsigs.signature is
# a backport.
try:
    import inspect
    signature = inspect.signature
except AttributeError:
    import funcsigs
    signature = funcsigs.signature

from copy import copy
from functools import wraps

from airflow.exceptions import AirflowException

def apply_defaults(func):
    """
    Function decorator that Looks for an argument named "default_args", and
    fills the unspecified arguments from it.

    Since python2.* isn't clear about which arguments are missing when
    calling a function, and that this can be quite confusing with multi-level
    inheritance and argument defaults, this decorator also alerts with
    specific information about the missing arguments.
    """
    @wraps(func)
    def wrapper(*args, **kwargs):
        if len(args) > 1:
            raise AirflowException(
                "Use keyword arguments when initializing operators")
        dag_args = {}
        dag_params = {}
        import airflow.models
        if kwargs.get('dag', None) or airflow.models._CONTEXT_MANAGER_DAG:
            dag = kwargs.get('dag', None) or airflow.models._CONTEXT_MANAGER_DAG
            dag_args = copy(dag.default_args) or {}
            dag_params = copy(dag.params) or {}

        params = {}
        if 'params' in kwargs:
            params = kwargs['params']
        dag_params.update(params)

        default_args = {}
        if 'default_args' in kwargs:
            default_args = kwargs['default_args']
            if 'params' in default_args:
                dag_params.update(default_args['params'])
                del default_args['params']

        dag_args.update(default_args)
        default_args = dag_args

        sig = signature(func)
        non_optional_args = [
            name for (name, param) in sig.parameters.items()
            if param.default == param.empty and
            param.name != 'self' and
            param.kind not in (param.VAR_POSITIONAL, param.VAR_KEYWORD)]
        for arg in sig.parameters:
            if arg in default_args and arg not in kwargs:
                kwargs[arg] = default_args[arg]
        missing_args = list(set(non_optional_args) - set(kwargs))
        if missing_args:
            msg = "Argument {0} is required".format(missing_args)
            raise AirflowException(msg)

        kwargs['params'] = dag_params

        result = func(*args, **kwargs)
        return result
    return wrapper

if 'BUILDING_AIRFLOW_DOCS' in os.environ:
    # Monkey patch hook to get good function headers while building docs
    apply_defaults = lambda x: x


text:
"""
Base functionality for nova daemons - gradually being replaced with twistd.py.
"""

import logging
import logging.handlers
import os
import signal
import sys
import time

from nova import vendor
import daemon
from daemon import pidlockfile

from nova import flags

FLAGS = flags.FLAGS
flags.DEFINE_bool('daemonize', False, 'daemonize this process')
# NOTE(termie): right now I am defaulting to using syslog when we daemonize
#               it may be better to do something else -shrug-
# NOTE(Devin): I think we should let each process have its own log file
#              and put it in /var/logs/nova/(appname).log
#              This makes debugging much easier and cuts down on sys log
#              clutter.
flags.DEFINE_bool('use_syslog', True, 'output to syslog when daemonizing')
flags.DEFINE_string('logfile', None, 'log file to output to')
flags.DEFINE_string('pidfile', None, 'pid file to output to')
flags.DEFINE_string('working_directory', './', 'working directory...')

def stop(pidfile):
    """
    Stop the daemon
    """
    # Get the pid from the pidfile
    try:
        pf = file(pidfile,'r')
        pid = int(pf.read().strip())
        pf.close()
    except IOError:
        pid = None

    if not pid:
        message = "pidfile %s does not exist. Daemon not running?\n"
        sys.stderr.write(message % pidfile)
        return # not an error in a restart

    # Try killing the daemon process
    try:
        while 1:
            os.kill(pid, signal.SIGTERM)
            time.sleep(0.1)
    except OSError, err:
        err = str(err)
        if err.find("No such process") > 0:
            if os.path.exists(pidfile):
                os.remove(pidfile)
        else:
            print str(err)
            sys.exit(1)

def serve(name, main):
    argv = FLAGS(sys.argv)

    if not FLAGS.pidfile:
        FLAGS.pidfile = '%s.pid' % name

    logging.debug("Full set of FLAGS: \n\n\n" )
    for flag in FLAGS:
        logging.debug("%s : %s" % (flag, FLAGS.get(flag, None) ))

    action = 'start'
    if len(argv) > 1:
        action = argv.pop()

    if action == 'stop':
        stop(FLAGS.pidfile)
        sys.exit()
    elif action == 'restart':
        stop(FLAGS.pidfile)
    elif action == 'start':
        pass
    else:
        print 'usage: %s [options] [start|stop|restart]' % argv[0]
        sys.exit(1)

    logging.getLogger('amqplib').setLevel(logging.WARN)
    if FLAGS.daemonize:
        logger = logging.getLogger()
        formatter = logging.Formatter(
                name + '(%(name)s): %(levelname)s %(message)s')
        if FLAGS.use_syslog and not FLAGS.logfile:
            syslog = logging.handlers.SysLogHandler(address='/dev/log')
            syslog.setFormatter(formatter)
            logger.addHandler(syslog)
        else:
            if not FLAGS.logfile:
                FLAGS.logfile = '%s.log' % name
            logfile = logging.handlers.FileHandler(FLAGS.logfile)
            logfile.setFormatter(formatter)
            logger.addHandler(logfile)
        stdin, stdout, stderr = None, None, None
    else:
        stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr

    if FLAGS.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.getLogger().setLevel(logging.WARNING)

    with daemon.DaemonContext(
            detach_process=FLAGS.daemonize,
            working_directory=FLAGS.working_directory,
            pidfile=pidlockfile.TimeoutPIDLockFile(FLAGS.pidfile,
                                                   acquire_timeout=1,
                                                   threaded=False),
            stdin=stdin,
            stdout=stdout,
            stderr=stderr
            ):
        main(argv)


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yiic message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE, this file must be saved in UTF-8 encoding.
 */
return array (
    '*unknown*' => '',
    '--choose--' => '',
    '--no--' => '',
    '0.5' => '',
    'Id' => '',
    'http://yupe.ru' => '',
    'team@yupe.ru' => '',
    'yupe team' => '',
    'Alias' => '',
    'This section describes category management' => '',
    'You are adding translate in to {lang}!' => '',
    'Do you really want to remove category?' => '',
    'Directory "{dir}" is available for write! {link}' => '',
    'Create category' => '',
    'Create category and close' => '',
    'Create category and continue' => '',
    'Add translate in to {lang}' => '',
    'Create' => '',
    'Record was created!' => '',
    'Bad characters in {attribute} field' => '',
    'Page was not found!' => '',
    'Change settings' => '',
    'Image' => '',
    'Find category' => '',
    'File uploading catalog (relatively Yii::app()->getModule("yupe")->uploadPath)' => '',
    'Categories' => '',
    'Categories - show' => '',
    'Categories - edit' => '',
    'Categories - manage' => '',
    'Categories/Sections' => '',
    'Category' => '',
    'Categories - create' => '',
    'Category was changed!' => '',
    'Short description' => '',
    'Module for categories/sections management' => '',
    'On moderation' => '',
    'Title' => '',
    'Bad request. Please don\'t use similar requests anymore' => '',
    'Description' => '',
    'Published' => '',
    'Find category' => '',
    'Fields with' => '',
    'Menu items order' => '',
    'Show category' => '',
    'View category' => '',
    'Change' => '',
    'Change category' => '',
    'Change translation in to {lang}' => '',
    'Parent' => '',
    'Save category and close' => '',
    'Save category and continue' => '',
    'Categories list' => '',
    'Status' => '',
    'Structure' => '',
    'Remove category' => '',
    'Manage' => '',
    'Category manage' => '',
    'Targeting category was not found!' => '',
    'Draft' => '',
    'Language' => '',
    'Language was not found!' => '',
    'create' => '',
    'are required' => '',
    'manage' => '',
	'Select {field}' => '',
);


text:
<?php

/* //////////////////////
   /     Shortcodes    /
   ///////////////////// */

//Create a login form shortcode that redirect to the homepage
function login_form_redirect_shortcode(){
  return do_shortcode('[login_form redirect="'. home_url() . '"]');
}

//Create the logout link shortcode
function logout_link_shortcode() {
	return wp_logout_url( home_url() );
}

//Create the profile name shortcode
function profile_name_shortcode(){
    $user=wp_get_current_user();
    $name=$user->user_firstname;
    return $name;
}

//Add the shortcodes
function my_add_shortcodes() {
	add_shortcode( 'logout-link', 'logout_link_shortcode' );
	add_shortcode('profile-name', 'profile_name_shortcode');
  add_shortcode( 'login-form-redirect', 'login_form_redirect_shortcode' );
}
add_action( 'init', 'my_add_shortcodes' );


text:
set -e

curl -X post localhost:5000/predict -d '["bedtime! why did u have to leave?"]' -H "Content-Type: application/json"