<commit_before>"use strict";

angular.module('myApp.services', [])

.value('version', '0.0.1')

/***
 *      /$$$$$$  /$$$$$$$  /$$$$$$       /$$$$$$$$ /$$    /$$ /$$$$$$$$ /$$   /$$ /$$$$$$$$
 *     /$$__  $$| $$__  $$|_  $$_/      | $$_____/| $$   | $$| $$_____/| $$$ | $$|__  $$__/
 *    | $$  \ $$| $$  \ $$  | $$        | $$      | $$   | $$| $$      | $$$$| $$   | $$
 *    | $$$$$$$$| $$$$$$$/  | $$        | $$$$$   |  $$ / $$/| $$$$$   | $$ $$ $$   | $$
 *    | $$__  $$| $$____/   | $$        | $$__/    \  $$ $$/ | $$__/   | $$  $$$$   | $$
 *    | $$  | $$| $$        | $$        | $$        \  $$$/  | $$      | $$\  $$$   | $$
 *    | $$  | $$| $$       /$$$$$$      | $$$$$$$$   \  $/   | $$$$$$$$| $$ \  $$   | $$
 *    |__/  |__/|__/      |______/      |________/    \_/    |________/|__/  \__/   |__/
 *
 *
 *
 */
.constant('AUTH_EVENTS', {
	loginSuccess: 'auth-login-success',
	loginFailed: 'auth-login-failed',
	logoutSuccess: 'auth-logout-success',
	sessionTimeout: 'auth-session-timeout',
	notAuthenticated: 'auth-not-authenticated',
	notAuthorized: 'auth-not-authorized'
})

/***
 *     /$$$$$$$   /$$$$$$  /$$       /$$$$$$$$
 *    | $$__  $$ /$$__  $$| $$      | $$_____/
 *    | $$  \ $$| $$  \ $$| $$      | $$
 *    | $$$$$$$/| $$  | $$| $$      | $$$$$
 *    | $$__  $$| $$  | $$| $$      | $$__/
 *    | $$  \ $$| $$  | $$| $$      | $$
 *    | $$  | $$|  $$$$$$/| $$$$$$$$| $$$$$$$$
 *    |__/  |__/ \______/ |________/|________/
 *
 *
 *
 */
.constant('USER_ROLES', {
	all: '*',
	admin: 'admin',
	editor: 'editor',
	guest: 'guest'
})

/***
 *      /$$$$$$  /$$   /$$ /$$$$$$$$ /$$   /$$
 *     /$$__  $$| $$  | $$|__  $$__/| $$  | $$
 *    | $$  \ $$| $$  | $$   | $$   | $$  | $$
 *    | $$$$$$$$| $$  | $$   | $$   | $$$$$$$$
 *    | $$__  $$| $$  | $$   | $$   | $$__  $$
 *    | $$  | $$| $$  | $$   | $$   | $$  | $$
 *    | $$  | $$|  $$$$$$/   | $$   | $$  | $$
 *    |__/  |__/ \______/    |__/   |__/  |__/
 *
 *
 *
 */
.factory('AuthService', ['$http', '$log', 'Session', 'USER_ROLES','ServerConfig',
	function($http, $log, Session, USER_ROLES, ServerConfig) {

	return {

		login: function(credentials,success,error) {

			//build api endpoint
			// var apiEndpoint = ServerConfig.endpoint + 'auth/login', credentials;
			// $log.log('call login api:' + apiEndpoint);
			// $log.log(credentials);

			// return $http
			// 	.post(apiEndpoint)
			// 	.success(function(res) {
			// 		$log.log('resposne');
			// 		$log.log(res);
			// 		Session.create(res.id, res.userid, res.role);
			// 	}).error(error);

		},

		logout: function(){

		},

		isAuthenticated: function() {
			return !!Session.userId;
		},

		isAuthorized: function(authorizedRoles) {
			$log.log('isAuthorized role:' + authorizedRoles);
			$log.log('Session.userRole:' + Session.userRole);

			if (!angular.isArray(authorizedRoles)) {
				authorizedRoles = [authorizedRoles];
			}

			if(USER_ROLES.all == authorizedRoles){
				$log.log('access public page');
				return true;
			}else if(USER_ROLES.guest == authorizedRoles){
				return true;
			}else{
				return (this.isAuthenticated() &&
					authorizedRoles.indexOf(Session.userRole) !== -1);
			}

		}
	};

}])

/***
 *     /$$$$$$ /$$   /$$ /$$$$$$$$ /$$$$$$$$ /$$$$$$$   /$$$$$$  /$$$$$$$$ /$$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$
 *    |_  $$_/| $$$ | $$|__  $$__/| $$_____/| $$__  $$ /$$__  $$| $$_____/| $$__  $$|__  $$__//$$__  $$| $$__  $$
 *      | $$  | $$$$| $$   | $$   | $$      | $$  \ $$| $$  \__/| $$      | $$  \ $$   | $$  | $$  \ $$| $$  \ $$
 *      | $$  | $$ $$ $$   | $$   | $$$$$   | $$$$$$$/| $$      | $$$$$   | $$$$$$$/   | $$  | $$  | $$| $$$$$$$/
 *      | $$  | $$  $$$$   | $$   | $$__/   | $$__  $$| $$      | $$__/   | $$____/    | $$  | $$  | $$| $$__  $$
 *      | $$  | $$\  $$$   | $$   | $$      | $$  \ $$| $$    $$| $$      | $$         | $$  | $$  | $$| $$  \ $$
 *     /$$$$$$| $$ \  $$   | $$   | $$$$$$$$| $$  | $$|  $$$$$$/| $$$$$$$$| $$         | $$  |  $$$$$$/| $$  | $$
 *    |______/|__/  \__/   |__/   |________/|__/  |__/ \______/ |________/|__/         |__/   \______/ |__/  |__/
 *
 *
 *
 *
 *
 *
 */
/*
 * Simple auth interceptor
 * It can be ehanced with this great github repo
 * 'https://github.com/witoldsz/angular-http-auth/blob/master/src/http-auth-interceptor.js'
 *
 */

.factory('AuthInterceptor', function($rootScope, $q, AUTH_EVENTS) {

	/*
	401 Unauthorized — The user is not logged in
	403 Forbidden — The user is logged in but isn’t allowed access
	419 Authentication Timeout (non standard) — Session has expired
	440 Login Timeout (Microsoft only) — Session has expired
	*/
	return {
		responseError: function(response) {
			if (response.status === 401) {
				$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated,
					response);
			}
			if (response.status === 403) {
				$rootScope.$broadcast(AUTH_EVENTS.notAuthorized,
					response);
			}
			if (response.status === 419 || response.status === 440) {
				$rootScope.$broadcast(AUTH_EVENTS.sessionTimeout,
					response);
			}
			return $q.reject(response);
		}
	};
})

/***
 *      /$$$$$$  /$$$$$$$$  /$$$$$$   /$$$$$$  /$$$$$$  /$$$$$$  /$$   /$$
 *     /$$__  $$| $$_____/ /$$__  $$ /$$__  $$|_  $$_/ /$$__  $$| $$$ | $$
 *    | $$  \__/| $$      | $$  \__/| $$  \__/  | $$  | $$  \ $$| $$$$| $$
 *    |  $$$$$$ | $$$$$   |  $$$$$$ |  $$$$$$   | $$  | $$  | $$| $$ $$ $$
 *     \____  $$| $$__/    \____  $$ \____  $$  | $$  | $$  | $$| $$  $$$$
 *     /$$  \ $$| $$       /$$  \ $$ /$$  \ $$  | $$  | $$  | $$| $$\  $$$
 *    |  $$$$$$/| $$$$$$$$|  $$$$$$/|  $$$$$$/ /$$$$$$|  $$$$$$/| $$ \  $$
 *     \______/ |________/ \______/  \______/ |______/ \______/ |__/  \__/
 *
 *
 *
 */
//session store
.service('Session', function() {

	var sessionObj = this;

	var sessionId = null;
	var userId = null;
	var userRole = null;

	sessionObj.create = function(sessionId, userId, userRole) {
		sessionId = sessionId;
		userId = userId;
		userRole = userRole;
	};
	sessionObj.destroy = function() {
		sessionId = null;
		userId = null;
		userRole = null;
	};
	sessionObj.getSession = function(){
		return {
			sessionId : sessionId,
			userid: userId,
			userRole: userRole
		}
	};

	return sessionObj;
})

/***
 *      /$$$$$$   /$$$$$$  /$$   /$$ /$$$$$$$$ /$$$$$$  /$$$$$$
 *     /$$__  $$ /$$__  $$| $$$ | $$| $$_____/|_  $$_/ /$$__  $$
 *    | $$  \__/| $$  \ $$| $$$$| $$| $$        | $$  | $$  \__/
 *    | $$      | $$  | $$| $$ $$ $$| $$$$$     | $$  | $$ /$$$$
 *    | $$      | $$  | $$| $$  $$$$| $$__/     | $$  | $$|_  $$
 *    | $$    $$| $$  | $$| $$\  $$$| $$        | $$  | $$  \ $$
 *    |  $$$$$$/|  $$$$$$/| $$ \  $$| $$       /$$$$$$|  $$$$$$/
 *     \______/  \______/ |__/  \__/|__/      |______/ \______/
 *
 *
 *
 */

.service('ServerConfig', function($location) {

    var serverConfig = this;

    var project = $location.absUrl().split('/')[3],
        project = project.search("#") > 0 ? project : '';

    serverConfig.protocal = $location.protocol();
    serverConfig.project = project;
    serverConfig.host = $location.host();
    serverConfig.port = $location.port();
    serverConfig.endpoint =
        serverConfig.protocal + '://' + serverConfig.host + (serverConfig.port == '80' || serverConfig.port == '443' ? '' : serverConfig.port) + (serverConfig.project == '' ? '' : '/' + serverConfig.project) + '/';
    //"http://acer.iangel.tw/";

    //分頁設定
    serverConfig.itemPerPage = 5;
    serverConfig.limitMaxPageSize = 5;

    return serverConfig;
})

.factory('ServerConfigFile', function($resource) {
	return $resource('config.json', {}, {
		getData: {
			method: 'GET',
			isArray: false
		}
	});
});

<commit_msg> 寫死api<commit_after>"use strict";

angular.module('myApp.services', [])

.value('version', '0.0.1')

/***
 *      /$$$$$$  /$$$$$$$  /$$$$$$       /$$$$$$$$ /$$    /$$ /$$$$$$$$ /$$   /$$ /$$$$$$$$
 *     /$$__  $$| $$__  $$|_  $$_/      | $$_____/| $$   | $$| $$_____/| $$$ | $$|__  $$__/
 *    | $$  \ $$| $$  \ $$  | $$        | $$      | $$   | $$| $$      | $$$$| $$   | $$
 *    | $$$$$$$$| $$$$$$$/  | $$        | $$$$$   |  $$ / $$/| $$$$$   | $$ $$ $$   | $$
 *    | $$__  $$| $$____/   | $$        | $$__/    \  $$ $$/ | $$__/   | $$  $$$$   | $$
 *    | $$  | $$| $$        | $$        | $$        \  $$$/  | $$      | $$\  $$$   | $$
 *    | $$  | $$| $$       /$$$$$$      | $$$$$$$$   \  $/   | $$$$$$$$| $$ \  $$   | $$
 *    |__/  |__/|__/      |______/      |________/    \_/    |________/|__/  \__/   |__/
 *
 *
 *
 */
.constant('AUTH_EVENTS', {
	loginSuccess: 'auth-login-success',
	loginFailed: 'auth-login-failed',
	logoutSuccess: 'auth-logout-success',
	sessionTimeout: 'auth-session-timeout',
	notAuthenticated: 'auth-not-authenticated',
	notAuthorized: 'auth-not-authorized'
})

/***
 *     /$$$$$$$   /$$$$$$  /$$       /$$$$$$$$
 *    | $$__  $$ /$$__  $$| $$      | $$_____/
 *    | $$  \ $$| $$  \ $$| $$      | $$
 *    | $$$$$$$/| $$  | $$| $$      | $$$$$
 *    | $$__  $$| $$  | $$| $$      | $$__/
 *    | $$  \ $$| $$  | $$| $$      | $$
 *    | $$  | $$|  $$$$$$/| $$$$$$$$| $$$$$$$$
 *    |__/  |__/ \______/ |________/|________/
 *
 *
 *
 */
.constant('USER_ROLES', {
	all: '*',
	admin: 'admin',
	editor: 'editor',
	guest: 'guest'
})

/***
 *      /$$$$$$  /$$   /$$ /$$$$$$$$ /$$   /$$
 *     /$$__  $$| $$  | $$|__  $$__/| $$  | $$
 *    | $$  \ $$| $$  | $$   | $$   | $$  | $$
 *    | $$$$$$$$| $$  | $$   | $$   | $$$$$$$$
 *    | $$__  $$| $$  | $$   | $$   | $$__  $$
 *    | $$  | $$| $$  | $$   | $$   | $$  | $$
 *    | $$  | $$|  $$$$$$/   | $$   | $$  | $$
 *    |__/  |__/ \______/    |__/   |__/  |__/
 *
 *
 *
 */
.factory('AuthService', ['$http', '$log', 'Session', 'USER_ROLES','ServerConfig',
	function($http, $log, Session, USER_ROLES, ServerConfig) {

	return {

		login: function(credentials,success,error) {

			//build api endpoint
			// var apiEndpoint = ServerConfig.endpoint + 'auth/login', credentials;
			// $log.log('call login api:' + apiEndpoint);
			// $log.log(credentials);

			// return $http
			// 	.post(apiEndpoint)
			// 	.success(function(res) {
			// 		$log.log('resposne');
			// 		$log.log(res);
			// 		Session.create(res.id, res.userid, res.role);
			// 	}).error(error);

		},

		logout: function(){

		},

		isAuthenticated: function() {
			return !!Session.userId;
		},

		isAuthorized: function(authorizedRoles) {
			$log.log('isAuthorized role:' + authorizedRoles);
			$log.log('Session.userRole:' + Session.userRole);

			if (!angular.isArray(authorizedRoles)) {
				authorizedRoles = [authorizedRoles];
			}

			if(USER_ROLES.all == authorizedRoles){
				$log.log('access public page');
				return true;
			}else if(USER_ROLES.guest == authorizedRoles){
				return true;
			}else{
				return (this.isAuthenticated() &&
					authorizedRoles.indexOf(Session.userRole) !== -1);
			}

		}
	};

}])

/***
 *     /$$$$$$ /$$   /$$ /$$$$$$$$ /$$$$$$$$ /$$$$$$$   /$$$$$$  /$$$$$$$$ /$$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$
 *    |_  $$_/| $$$ | $$|__  $$__/| $$_____/| $$__  $$ /$$__  $$| $$_____/| $$__  $$|__  $$__//$$__  $$| $$__  $$
 *      | $$  | $$$$| $$   | $$   | $$      | $$  \ $$| $$  \__/| $$      | $$  \ $$   | $$  | $$  \ $$| $$  \ $$
 *      | $$  | $$ $$ $$   | $$   | $$$$$   | $$$$$$$/| $$      | $$$$$   | $$$$$$$/   | $$  | $$  | $$| $$$$$$$/
 *      | $$  | $$  $$$$   | $$   | $$__/   | $$__  $$| $$      | $$__/   | $$____/    | $$  | $$  | $$| $$__  $$
 *      | $$  | $$\  $$$   | $$   | $$      | $$  \ $$| $$    $$| $$      | $$         | $$  | $$  | $$| $$  \ $$
 *     /$$$$$$| $$ \  $$   | $$   | $$$$$$$$| $$  | $$|  $$$$$$/| $$$$$$$$| $$         | $$  |  $$$$$$/| $$  | $$
 *    |______/|__/  \__/   |__/   |________/|__/  |__/ \______/ |________/|__/         |__/   \______/ |__/  |__/
 *
 *
 *
 *
 *
 *
 */
/*
 * Simple auth interceptor
 * It can be ehanced with this great github repo
 * 'https://github.com/witoldsz/angular-http-auth/blob/master/src/http-auth-interceptor.js'
 *
 */

.factory('AuthInterceptor', function($rootScope, $q, AUTH_EVENTS) {

	/*
	401 Unauthorized — The user is not logged in
	403 Forbidden — The user is logged in but isn’t allowed access
	419 Authentication Timeout (non standard) — Session has expired
	440 Login Timeout (Microsoft only) — Session has expired
	*/
	return {
		responseError: function(response) {
			if (response.status === 401) {
				$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated,
					response);
			}
			if (response.status === 403) {
				$rootScope.$broadcast(AUTH_EVENTS.notAuthorized,
					response);
			}
			if (response.status === 419 || response.status === 440) {
				$rootScope.$broadcast(AUTH_EVENTS.sessionTimeout,
					response);
			}
			return $q.reject(response);
		}
	};
})

/***
 *      /$$$$$$  /$$$$$$$$  /$$$$$$   /$$$$$$  /$$$$$$  /$$$$$$  /$$   /$$
 *     /$$__  $$| $$_____/ /$$__  $$ /$$__  $$|_  $$_/ /$$__  $$| $$$ | $$
 *    | $$  \__/| $$      | $$  \__/| $$  \__/  | $$  | $$  \ $$| $$$$| $$
 *    |  $$$$$$ | $$$$$   |  $$$$$$ |  $$$$$$   | $$  | $$  | $$| $$ $$ $$
 *     \____  $$| $$__/    \____  $$ \____  $$  | $$  | $$  | $$| $$  $$$$
 *     /$$  \ $$| $$       /$$  \ $$ /$$  \ $$  | $$  | $$  | $$| $$\  $$$
 *    |  $$$$$$/| $$$$$$$$|  $$$$$$/|  $$$$$$/ /$$$$$$|  $$$$$$/| $$ \  $$
 *     \______/ |________/ \______/  \______/ |______/ \______/ |__/  \__/
 *
 *
 *
 */
//session store
.service('Session', function() {

	var sessionObj = this;

	var sessionId = null;
	var userId = null;
	var userRole = null;

	sessionObj.create = function(sessionId, userId, userRole) {
		sessionId = sessionId;
		userId = userId;
		userRole = userRole;
	};
	sessionObj.destroy = function() {
		sessionId = null;
		userId = null;
		userRole = null;
	};
	sessionObj.getSession = function(){
		return {
			sessionId : sessionId,
			userid: userId,
			userRole: userRole
		}
	};

	return sessionObj;
})

/***
 *      /$$$$$$   /$$$$$$  /$$   /$$ /$$$$$$$$ /$$$$$$  /$$$$$$
 *     /$$__  $$ /$$__  $$| $$$ | $$| $$_____/|_  $$_/ /$$__  $$
 *    | $$  \__/| $$  \ $$| $$$$| $$| $$        | $$  | $$  \__/
 *    | $$      | $$  | $$| $$ $$ $$| $$$$$     | $$  | $$ /$$$$
 *    | $$      | $$  | $$| $$  $$$$| $$__/     | $$  | $$|_  $$
 *    | $$    $$| $$  | $$| $$\  $$$| $$        | $$  | $$  \ $$
 *    |  $$$$$$/|  $$$$$$/| $$ \  $$| $$       /$$$$$$|  $$$$$$/
 *     \______/  \______/ |__/  \__/|__/      |______/ \______/
 *
 *
 *
 */

.service('ServerConfig', function($location) {
	// var project = $location.absUrl().split('/')[3],
	// 	project = project.search("#") > 0 ? project : '';
	// return JSON.parse(angular.toJson({
	// 	site: {
	// 		protocal: $location.protocol(),
	// 		server: $location.host(),
	// 		project: project,
	// 		port: $location.port(),
	// 		endpoint: $location.protocol()
	// 			+ '://' + $location.host()
	// 			+ ($location.port() == '80' || $location.port() == '443' ? '' : $location.port())
	// 			+ (project == '' ? '' : '/' + project) + '/#',
	// 		draggable: true,
	// 		sort: 'nmst',
	// 		orders: '1010',
	// 	}
	// }));

	var serverConfig = this;
	serverConfig.endpoint = "http://10.10.11.130:1880/editor/";
	return serverConfig;
})

.factory('ServerConfigFile', function($resource) {
	return $resource('config.json', {}, {
		getData: {
			method: 'GET',
			isArray: false
		}
	});
});

<|endoftext|>


<commit_before>'use strict';
import React from 'react';

import createReactClass from 'create-react-class';

import ConnectFold from '../components/connect-fold';

import YoutubeEmbed from '../components/youtube-player';

/*
 * create-react-class provides a drop-in replacement for the outdated React.createClass,
 * see https://reactjs.org/docs/react-without-es6.html
 * Please modernize this code using functional components and hooks!
 */
var Donate = createReactClass({
  displayName: 'Donate',

  propTypes: {},

  render: function () {
    return (

Donate now to OpenAQ!

                      Help support our mission to achieve clean air through air
                      quality data and community. Donate below or directly with{' '}

                        DAF

                      .

                        We are a registered 501(c)(3). If US-based, your
                        donation is tax deductible.

                        If you contribute through a DAF, please{' '}
                        send us an email
                        so we can update the campaign total!

                <YoutubeEmbed embedId="J47SsCH0bi0" />

Your donation helps support...

                    Key programs and initiatives like our Community Ambassador
                    Program, a 10-month Program designed to train local leaders
                    on open data and tools to aid their work to fight air
                    pollution.

                    Development of new tools and enhancements to the OpenAQ
                    platform to improve access and usability.

                    Integration of new data sources and technologies to the
                    OpenAQ platform to improve coverage and transparency of
                    global air quality data.

                    Ongoing administrative as well as platform maintenance costs
                    to ensure the data and tools are available free of charge.

Community Ambassador Program

                    Funding helps support programs like OpenAQ’s Community
                    Ambassador program, training inspiring community leaders
                    like Farah Kazi, a dedicated air quality advocate in
                    Maharashtra, India. Farah is participating in OpenAQ’s
                    10-month Ambassador Program, a program designed to train
                    local leaders on open data and leadership to fight air
                    pollution in their communities.

                      Meet all the ambassadors and learn more

                        “It's been a great three months since
                        I joined the OpenAQ Ambassador Program. I have been
                        connected to and have been learning from leaders from
                        across the world that are fighting air inequality from
                        within their communities. OpenAQ through it's
                        centralized data platform provides access to open air
                        quality data from around the globe. It's so much
                        easier now to compare air quality between cities and
                        even countries.”

- Farah Kazi

                  Wear a cool OpenAQ t-shirt that helps us fight air inequality!

                    This June 2021, in honor of World Environment Day, we would
                    like to celebrate the OpenAQ Community and support efforts
                    to fight air inequality by releasing some new OpenAQ swag
                    available for a limited time only! Your purchase will help
                    support our work in democratizing access to air quality data
                    to enable community action to fight air pollution. Please
                    join us in wearing OpenAQ shirts and spreading the word of
                    #CleanAirforAll!

                      View options

We are an open book

                    For more information about how funds are used check out our
                    990 form and the{' '}

                      FAQs page

                    .

                      Download 2020 Form 990

2020

Form 990

          <ConnectFold />

    );
  },
});

module.exports = Donate;
<commit_msg>update donate video<commit_after>'use strict';
import React from 'react';

import createReactClass from 'create-react-class';

import ConnectFold from '../components/connect-fold';

import YoutubeEmbed from '../components/youtube-player';

/*
 * create-react-class provides a drop-in replacement for the outdated React.createClass,
 * see https://reactjs.org/docs/react-without-es6.html
 * Please modernize this code using functional components and hooks!
 */
var Donate = createReactClass({
  displayName: 'Donate',

  propTypes: {},

  render: function () {
    return (

Donate now to OpenAQ!

                      Help support our mission to achieve clean air through air
                      quality data and community. Donate below or directly with{' '}

                        DAF

                      .

                        We are a registered 501(c)(3). If US-based, your
                        donation is tax deductible.

                        If you contribute through a DAF, please{' '}
                        send us an email
                        so we can update the campaign total!

                <YoutubeEmbed embedId="FntU6TXpb2g" />

Your donation helps support...

                    Key programs and initiatives like our Community Ambassador
                    Program, a 10-month Program designed to train local leaders
                    on open data and tools to aid their work to fight air
                    pollution.

                    Development of new tools and enhancements to the OpenAQ
                    platform to improve access and usability.

                    Integration of new data sources and technologies to the
                    OpenAQ platform to improve coverage and transparency of
                    global air quality data.

                    Ongoing administrative as well as platform maintenance costs
                    to ensure the data and tools are available free of charge.

Community Ambassador Program

                    Funding helps support programs like OpenAQ’s Community
                    Ambassador program, training inspiring community leaders
                    like Farah Kazi, a dedicated air quality advocate in
                    Maharashtra, India. Farah is participating in OpenAQ’s
                    10-month Ambassador Program, a program designed to train
                    local leaders on open data and leadership to fight air
                    pollution in their communities.

                      Meet all the ambassadors and learn more

                        “It's been a great three months since
                        I joined the OpenAQ Ambassador Program. I have been
                        connected to and have been learning from leaders from
                        across the world that are fighting air inequality from
                        within their communities. OpenAQ through it's
                        centralized data platform provides access to open air
                        quality data from around the globe. It's so much
                        easier now to compare air quality between cities and
                        even countries.”

- Farah Kazi

                  Wear a cool OpenAQ t-shirt that helps us fight air inequality!

                    This June 2021, in honor of World Environment Day, we would
                    like to celebrate the OpenAQ Community and support efforts
                    to fight air inequality by releasing some new OpenAQ swag
                    available for a limited time only! Your purchase will help
                    support our work in democratizing access to air quality data
                    to enable community action to fight air pollution. Please
                    join us in wearing OpenAQ shirts and spreading the word of
                    #CleanAirforAll!

                      View options

We are an open book

                    For more information about how funds are used check out our
                    990 form and the{' '}

                      FAQs page

                    .

                      Download 2020 Form 990

2020

Form 990

          <ConnectFold />

    );
  },
});

module.exports = Donate;
<|endoftext|>


<commit_before>/*
  SignalStore will keep track of all signals triggered. It keeps an array of signals with
  actions and mutations related to that signal. It will also track any async signals processing. The SignalStore
  is able to reset state and travel to a "specific point in time" by playing back the signals up to a certain
  signal.
*/
var utils = require('./../../utils.js')

module.exports = function SignalStore () {
  return function (module, controller) {
    var signals = []
    var isRemembering = false
    var currentIndex = signals.length - 1
    var hasRememberedInitial = false

    var asyncActionsRunning = []

    var addAsyncAction = function (action) {
      asyncActionsRunning.push(action)
    }

    var removeAsyncAction = function (action) {
      asyncActionsRunning.splice(asyncActionsRunning.indexOf(action), 1)
    }

    var addSignal = function (signal) {
      if (utils.isDeveloping() && !isRemembering) {
        if (asyncActionsRunning.length) {
          var currentAction = asyncActionsRunning[asyncActionsRunning.length - 1]
          currentAction.signals = currentAction.signals || []
          currentAction.signals.push(signal)
        } else {
          currentIndex++
          signals.push(signal)
        }
      }
    }

    var services = {
      // This is used when loading up the app and producing the last known state
      rememberNow: function () {
        if (!signals.length) {
          return
        }

        currentIndex = signals.length - 1
        this.remember(currentIndex)
      },

      // Will reset the SignalStore
      reset: function () {
        if (!isRemembering) {
          signals = []

          currentIndex = -1

          controller.emit('reset')
        }
      },

      rememberInitial: function (index) {
        // Both router and debugger might try to do initial remembering
        if (hasRememberedInitial) {
          return
        }

        hasRememberedInitial = true
        this.remember(index)
      },

      remember: function (index) {
        // Flag that we are remembering
        isRemembering = true
        controller.emit('reset')

        // If going back to initial state, just return and update
        if (index === -1) {
          currentIndex = index
          isRemembering = false
        } else {
          // Start from beginning
          currentIndex = -1

          // Go through signals
          try {
            for (var x = 0; x <= index; x++) {
              var signal = signals[x]
              if (!signal) {
                break
              }

              // Trigger signal and then set what has become the current signal
              var signalMethodPath = signal.name.split('.').reduce(function (signals, key) {
                return signals[key]
              }, controller.getSignals())
              signalMethodPath(signal.input, {
                branches: signal.branches
              })
              currentIndex = x
            }
          } catch (e) {
            console.log(e)
            console.warn('CEREBRAL - There was an error remembering state, it has been reset')
            this.reset()
          }
        }

        controller.emit('change')
        isRemembering = false
      },

      removeRunningSignals: function () {
        for (var x = 0; x < signals.length; x++) {
          if (signals[x].isExecuting) {
            signals.splice(x, 1)
            x--
          }
        }
      },

      getSignals: function () {
        return signals
      },

      setSignals: function (newSignals) {
        signals = signals.concat(newSignals)
      },

      isExecutingAsync: function () {
        return !!asyncActionsRunning.length
      },

      isRemembering: function () {
        return isRemembering
      },

      getCurrentIndex: function () {
        return currentIndex
      }
    }

    module.services(services)
    controller.getStore = function getStore () {
      console.warn('Cerebral: controller.getStore() method is deprecated.')
      return services
    }

    controller.on('signalStart', function (args) {
      var signal = args.signal

      if (isRemembering && currentIndex !== -1 && currentIndex < signals.length - 1) {
        signal.preventSignalRun()
        console.warn('Cerebral - Looking in the past, ignored signal ' + signal.name)
      }

      addSignal(signal)
    })
    controller.on('actionStart', function (args) {
      var action = args.action
      if (action.isAsync) addAsyncAction(args.action)
    })
    controller.on('actionEnd', function (args) {
      var action = args.action
      if (action.isAsync) removeAsyncAction(args.action)
    })
  }
}
<commit_msg>fix(signalStore): use correct condition to prevent signal run while looking into past<commit_after>/*
  SignalStore will keep track of all signals triggered. It keeps an array of signals with
  actions and mutations related to that signal. It will also track any async signals processing. The SignalStore
  is able to reset state and travel to a "specific point in time" by playing back the signals up to a certain
  signal.
*/
var utils = require('./../../utils.js')

module.exports = function SignalStore () {
  return function (module, controller) {
    var signals = []
    var isRemembering = false
    var currentIndex = signals.length - 1
    var hasRememberedInitial = false

    var asyncActionsRunning = []

    var addAsyncAction = function (action) {
      asyncActionsRunning.push(action)
    }

    var removeAsyncAction = function (action) {
      asyncActionsRunning.splice(asyncActionsRunning.indexOf(action), 1)
    }

    var addSignal = function (signal) {
      if (utils.isDeveloping() && !isRemembering) {
        if (asyncActionsRunning.length) {
          var currentAction = asyncActionsRunning[asyncActionsRunning.length - 1]
          currentAction.signals = currentAction.signals || []
          currentAction.signals.push(signal)
        } else {
          currentIndex++
          signals.push(signal)
        }
      }
    }

    var services = {
      // This is used when loading up the app and producing the last known state
      rememberNow: function () {
        if (!signals.length) {
          return
        }

        currentIndex = signals.length - 1
        this.remember(currentIndex)
      },

      // Will reset the SignalStore
      reset: function () {
        if (!isRemembering) {
          signals = []

          currentIndex = -1

          controller.emit('reset')
        }
      },

      rememberInitial: function (index) {
        // Both router and debugger might try to do initial remembering
        if (hasRememberedInitial) {
          return
        }

        hasRememberedInitial = true
        this.remember(index)
      },

      remember: function (index) {
        // Flag that we are remembering
        isRemembering = true
        controller.emit('reset')

        // If going back to initial state, just return and update
        if (index === -1) {
          currentIndex = index
          isRemembering = false
        } else {
          // Start from beginning
          currentIndex = -1

          // Go through signals
          try {
            for (var x = 0; x <= index; x++) {
              var signal = signals[x]
              if (!signal) {
                break
              }

              // Trigger signal and then set what has become the current signal
              var signalMethodPath = signal.name.split('.').reduce(function (signals, key) {
                return signals[key]
              }, controller.getSignals())
              signalMethodPath(signal.input, {
                branches: signal.branches
              })
              currentIndex = x
            }
          } catch (e) {
            console.log(e)
            console.warn('CEREBRAL - There was an error remembering state, it has been reset')
            this.reset()
          }
        }

        controller.emit('change')
        isRemembering = false
      },

      removeRunningSignals: function () {
        for (var x = 0; x < signals.length; x++) {
          if (signals[x].isExecuting) {
            signals.splice(x, 1)
            x--
          }
        }
      },

      getSignals: function () {
        return signals
      },

      setSignals: function (newSignals) {
        signals = signals.concat(newSignals)
      },

      isExecutingAsync: function () {
        return !!asyncActionsRunning.length
      },

      isRemembering: function () {
        return isRemembering
      },

      getCurrentIndex: function () {
        return currentIndex
      }
    }

    module.services(services)
    controller.getStore = function getStore () {
      console.warn('Cerebral: controller.getStore() method is deprecated.')
      return services
    }

    controller.on('signalStart', function (args) {
      var signal = args.signal

      if (!isRemembering && currentIndex !== -1 && currentIndex < signals.length - 1) {
        signal.preventSignalRun()
        console.warn('Cerebral - Looking in the past, ignored signal ' + signal.name)
      }

      addSignal(signal)
    })
    controller.on('actionStart', function (args) {
      var action = args.action
      if (action.isAsync) addAsyncAction(args.action)
    })
    controller.on('actionEnd', function (args) {
      var action = args.action
      if (action.isAsync) removeAsyncAction(args.action)
    })
  }
}
<|endoftext|>


<commit_before>
(function() {
    'use strict';

    angular
        .module('app.bricks', [])
        .service('BrickService', BrickService);

    BrickService.$inject = ["$q"]
    function BrickService($q) {
        var preBrick = [
            storage.refFromURL('gs://remin-f1785.appspot.com/1.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/2.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/3.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/4.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/5.jpg')
        ];
        var service = this;

        service.getBricks = getBricks;

        return service;

        function getBricks () {
            console.log('BrickService.getBricks');
            return init();

        }

        function init() {
            var qUrls = [];
            preBrick.forEach(function (preUrl) {
                qUrls.push(preUrl.getDownloadURL());
            });
            return $q.all(qUrls);
        }
    }

})();<commit_msg>uploadBrick function<commit_after>
(function() {
    'use strict';

    angular
        .module('app.bricks', [])
        .service('BrickService', BrickService);

    BrickService.$inject = ["$q"]
    function BrickService($q) {
        var preBrick = [
            storage.refFromURL('gs://remin-f1785.appspot.com/1.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/2.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/3.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/4.jpg'),
            storage.refFromURL('gs://remin-f1785.appspot.com/5.jpg')
        ];
        var service = this;

        service.getBricks = getBricks;
        service.uploadBrick = uploadBrick;

        return service;

        function getBricks () {
            console.log('BrickService.getBricks');
            return init();

        }

        function uploadBrick(file){
            console.log("Uploading file, ", file);

            var uploadTask = storageRef.child('images/' + file.name).put(file);
            // uploadTask.on('state_changed', function(snapshot){
            //     // Observe state change events such as progress, pause, and resume
            //     // See below for more detail
            // }, function(error) {
            //     // Handle unsuccessful uploads
            //     console.log("Upload error, ", error);
            // }, function(s) {
            //     console.log("Uploadsuccess, ", s);
            //     // Handle successful uploads on complete
            //     // For instance, get the download URL: https://firebasestorage.googleapis.com/...
            //     var downloadURL = uploadTask.snapshot.downloadURL;
            // });
        }

        function init() {
            var qUrls = [];
            preBrick.forEach(function (preUrl) {
                qUrls.push(preUrl.getDownloadURL());
            });
            return $q.all(qUrls);
        }
    }

})();<|endoftext|>


<commit_before>window.templates || (window.templates = {});

templates.network_options_main = function(clearing_cache, caching, tracking, headers)
{
  var checked = true;
  return ["div",
          ["button", "Clear cache", "handler", "network-options-clear-cache"],
          clearing_cache ? ["span", "CLEARING"] : [],
          ["hr"],
          ["div", "Caching behaviour:",
           ["br"],
           ["label", "Standard browser caching behaviour",
            ["input", "type", "radio",
             "name", "network-options-caching",
             "value", "default",
             "handler", "network-options-toggle-caching",
             caching == "default" ? "checked" : "non-checked", "true"
            ]],

           ["br"],
           ["label", "Disable all caching",
            ["input", "type", "radio",
             "name", "network-options-caching",
             "value", "disabled",
             "handler", "network-options-toggle-caching",
             caching == "disabled" ? "checked" : "non-checked", "true"
            ]]
          ],
          ["hr"],
          ["div", "Content tracking behaviour:",
           ["br"],
           ["label", "Don't track content (default)",
            ["input", "type", "radio",
             "name", "network-options-track-bodies",
             "value", "notrack",
             "handler", "network-options-toggle-body-tracking",
             tracking == "notrack" ? "checked" : "non-checked", "true"
            ]],

           ["br"],
           ["label", "Track content (affects speed/memory)",
            ["input", "type", "radio",
             "name", "network-options-track-bodies",
             "value", "track",
             "handler", "network-options-toggle-body-tracking",
             tracking == "track" ? "checked" : "non-checked", "true"
            ]]
          ],

          /*
          ["hr"],
          ["fieldset", ["legend", "Global header rewrites"],
           templates.network_options_header_table(headers)
          ],
          */
          "class", "padding network-options"
         ];
};

templates.network_options_header_table = function(headers)
{
  var fun = function(header) {
      return ["tr",
               ["td", "DEL"],
               ["td", "ON"],
               ["td", ["input", "", "value", header.name]],
               ["td", ["input", "", "value", header.value]]
             ];
  };

  var tpl = ["table",
              ["tr",
                ["th", "X"], ["th", "Y"], ["th", "Name"], ["th", "Value"]],
                headers.map(fun)
            ];
  return tpl;
};

templates.network_request_crafter_main = function(url, request, response)
{
  return ["div",
          ["div",
           ["label", "URL:", ["input", "type", "text",
                              "value", url || "",
                              "handler", "request-crafter-url-change"
                             ]
           ],
           ["textarea", request]
          ],
          ["button", "Send request", "handler", "request-crafter-send"],
          ["hr"],
          ["div", ["pre", ["code", response]]],
          "class", "padding request-crafter"
         ];
};

templates.network_log_main = function(ctx, graphwidth)
{
  return [
    ["div",
     ["div",
      ["div", templates.network_log_url_list(ctx), "id", "left-side-content"],
      ["div",
       ["div", templates.network_log_graph(ctx, graphwidth),
        "id", "right-side-content"
       ],
       "id", "right-side-container",
      ],
      "id", "main-scroll-content",
     ],
     "class", "network-log",
     "id", "main-scroll-container",
    ],
    ["div", ["div", "id", "scrollbar"], "id", "scrollbar-container"]
  ];
}

templates.network_log_details = function(ctx, selected)
{
  return  [
    ["div", templates.network_log_url_list(ctx, selected),
     "class", "network-details-url-list"
    ],
    ["div", templates.network_log_request_detail(ctx, selected),
     "class", "network-details-request"
    ]
  ]
}

templates.network_log_request_detail = function(ctx, selected)
{
  var req = ctx.get_resource(selected);
  return [
    ["button", "X", "handler", "close-request-detail"],
    ["table",
     ["tr", ["th", "URL:"], ["td", req.url]],
     ["tr", ["th", "Method:"], ["td", req.method || "-"]],
     ["tr", ["th", "Status:"], ["td", String(req.responsecode || "-")]],
     "class", "resource-detail"
    ],
    ["hr"],
    ["h2", "Request details"],
    templates.network_header_table(req.request_headers),
    ["hr"],
    ["h2", "Response details"],
    templates.network_header_table(req.response_headers),
    ["hr"],
    ["h2", "Body"],
    templates.network_response_body(req)
  ]
}

templates.network_response_body = function(req)
{
  if (!req.responsebody)
  {
    return ["div",
            "Response body not tracked. To always fetch response bodies, toggle the response body option on the \"network options\" tab. To retrieve only this body, click the button.",
            ["button",
             "Get response body",
             "data-resource-id", String(req.id),
             "handler", "get-response-body"
             ]
            ]
  }
  else
  {
    var bodytpl;
    if (["script", "markup", "css", "text"].indexOf(req.type) != -1)
    {
      bodytpl = ["code", ["pre", req.responsebody.content.stringData]];
    }
    else if (req.type == "image")
    {
      bodytpl = ["img", "src", req.responsebody.content.stringData];
    }
    else
    {
      bodytpl = ["span", "not able to show data of type " + req.mime];
    }

    return ["div",
            bodytpl,
            "class", "response-body-content"
           ];
  }
}

templates.network_header_table = function(headers)
{
  if (!headers)
  {
    return ["table", ["tr", ["td", "No headers"]]];
  }

  var rowfun = function(header)
  {
    return ["tr",
            ["th", header.name],
            ["td", header.value]
           ]
  }

  var headers = headers.slice(0); // copy so we can sort withouth nuking original
  headers.sort(function(a, b) {
    if (a.name>b.name) { return 1 }
    else if (b.name>a.name) { return -1 }
    else { return 0 }
  });
  return ["table", headers.map(rowfun),
          "class", "header-list"];
}

templates.network_log_main_table = function(ctx)
{
  return [
    ["div", templates.network_log_url_list(ctx),
     "class", "resourcelist"
    ],
    ["div", templates.network_log_url_list(ctx),
     "class", "timeline"]
  ]
}

templates.network_log_url_list = function(ctx, selected)
{
  var itemfun = function(res) {
    return ["li", templates.network_request_icon(res), ["span", res.url],
            "handler", "select-network-request",
            "data-resource-id", String(res.id),
            "class", selected===res.id ? "selected" : ""
           ]
  }
  return ["ol", ctx.resources.map(itemfun),
          "class", "network-log-url-list"];
}

templates.network_request_icon = function(request)
{
  return ["span", "class", "resource-icon resource-type-" + request.type];
}

templates.network_log_graph = function(ctx, width)
{
  width = width;
  var rowheight = 23;
  var height = ctx.resources.length * rowheight;

  var gradients = templates.gradient_defs();
  var background = templates.network_log_background(ctx, rowheight);
  var bars = templates.graph_bars(ctx, width, rowheight);
  var grid = templates.grid_lines(ctx, width, height);

  var tpl = ["svg:svg",
             gradients,
             background,
             bars,
             grid,
             //'viewBox', '0 0 ' + 3000 + 'px ' + 500 +'px',
             "xmlns", "http://www.w3.org/2000/svg",
             "class", "resource-graph"];

    return tpl;
}

templates.graph_bars = function(ctx, width, height)
{
  var bars = [];
  var basetime = ctx.get_starttime();
  var duration = ctx.get_duration();
  duration = Math.ceil(duration / 1000) * 1000

  for (var n=0, req; req=ctx.resources[n]; n++)
  {
    var bar = templates.request_bar(n, req, basetime, duration, width, height);
    bars.push(bar);
  }
  return bars;
}

templates.request_bar = function(index, request, basetime, totaltime, contwidth, lineheight)
{
  var y = lineheight * index;
  var barheight = 12;
  var bary = y + (lineheight / 2) - (barheight / 2);
  var multiplier = contwidth / totaltime;

  if (!request.duration) {
    // fixme: request not done, so emit something saner here.
    return [];
  }

  var start = request.starttime;

  var reqwidth = request.duration

  var resstart = start+10//entry.requestfinished.time;
  var reswidth = 30; // reqwidth - (resstart - reqstart);

  var texture = "gradient-" + (request.type || "unknown");

  var tpl = [
    ["rect", "x", String((start-basetime)*multiplier), "y", String(bary),
     "width", String(reqwidth*multiplier), "height", String(barheight),
             "rx", "4", "ry", "4",
             "fill", "#dfdfdf", "stroke", "#969696", "stroke-width", "1.0"],

      ["rect", "x", String((resstart-basetime)*multiplier), "y", String(bary),
             "width", String(reswidth*multiplier), "height", String(barheight),
             "rx", "4", "ry", "4",
             "fill", "url(#" + texture + ")", "stroke", "#939393", "stroke-width", "1.0"]

  ];
  return tpl;
};

templates.grid_lines = function(ctx, width, height)
{
  var ret = [];
  var millis = ctx.get_duration();
  millis = Math.ceil(millis / 1000) * 1000
  var secondwidth = width / (millis / 1000);
  var multiplier = width / millis;

  // Thresholds for whether or not to render grid for every 100 and 500ms.
  // The number is how many pixels per second. So if every second is
  // alloted more than 200px, render the 100ms bars
  const THRESH_100MS = 200;
  const THRESH_500MS = 100;

  ret.push(["line",
            "x1", "0",
            "y1", "0",
            "x2", "0",
            "y2", String(height),
            "stroke", "black",
            "stroke-width", "1",
           ]);

  for (var n=100; n<millis; n+=100)
  {
    var color = null;
    if (!(n % 1000))
    {
      color = "black";
    }
    else if (secondwidth > THRESH_500MS && !(n % 500))
    {
      color = "gray";
    }
    else if (secondwidth > THRESH_100MS && !(n % 100))
    {
      color = "silver";
    }

    if (color) {
      ret.push(["line",
                "x1", String(n*multiplier),
                "y1", "0",
                "x2", String(n*multiplier),
                "y2", String(height),
                "stroke", color,
                "stroke-width", "1.0",
                "opacity", "1.0"
      ]);
    }
  }

  return ret;
};

templates.gradient_defs = function()
{
  return ["defs",
          templates.gradient("image", "#F1B5B5", "#F1B5B5", "#F1B5B5", "#ffffff"),
          templates.gradient("script", "#FAEFBB","#FAEFBB","#FAEFBB", "#ffffff"),
          templates.gradient("css", "#C4D9F5", "#C4D9F5", "#C4D9F5", "#ffffff"),
          templates.gradient("markup", "#f2f9ff", "#e5eeff", "#d9e2ff", "#e5e9ff"),
          templates.gradient("unknown", "#E6E6E6", "#E6E6E6", "#E6E6E6", "#ffffff")
         ];
};

templates.gradient = function(id, c1, c2, c3, c4)
{
  return ["linearGradient",
          ["stop", "offset", "5%", "stop-color", c1],
          ["stop", "offset", "50%", "stop-color", c2],
          ["stop", "offset", "50%", "stop-color", c3],
          ["stop", "offset", "100%", "stop-color", c4],
          "x1", "0",
          "x2", "0",
          "y1", "0",
          "y2", "100%",
          "id", "gradient-" + id
         ];
};

templates.network_log_background = function(ctx, lineheight)
{
  var cnt = ctx.resources.length;
  var tpls = [];
  while (cnt--)
  {
    tpls.push(["rect", "x", "0",
                       "y", String(cnt*lineheight),
                       "width", "100%",
                       "height", String(lineheight),
                       "stroke-width", "0", "fill", (cnt%2 ?  "#f2f2f2" : "white")]);
  }
  return tpls;
};
<commit_msg>Updating colors for the network graph bars.<commit_after>window.templates || (window.templates = {});

templates.network_options_main = function(clearing_cache, caching, tracking, headers)
{
  var checked = true;
  return ["div",
          ["button", "Clear cache", "handler", "network-options-clear-cache"],
          clearing_cache ? ["span", "CLEARING"] : [],
          ["hr"],
          ["div", "Caching behaviour:",
           ["br"],
           ["label", "Standard browser caching behaviour",
            ["input", "type", "radio",
             "name", "network-options-caching",
             "value", "default",
             "handler", "network-options-toggle-caching",
             caching == "default" ? "checked" : "non-checked", "true"
            ]],

           ["br"],
           ["label", "Disable all caching",
            ["input", "type", "radio",
             "name", "network-options-caching",
             "value", "disabled",
             "handler", "network-options-toggle-caching",
             caching == "disabled" ? "checked" : "non-checked", "true"
            ]]
          ],
          ["hr"],
          ["div", "Content tracking behaviour:",
           ["br"],
           ["label", "Don't track content (default)",
            ["input", "type", "radio",
             "name", "network-options-track-bodies",
             "value", "notrack",
             "handler", "network-options-toggle-body-tracking",
             tracking == "notrack" ? "checked" : "non-checked", "true"
            ]],

           ["br"],
           ["label", "Track content (affects speed/memory)",
            ["input", "type", "radio",
             "name", "network-options-track-bodies",
             "value", "track",
             "handler", "network-options-toggle-body-tracking",
             tracking == "track" ? "checked" : "non-checked", "true"
            ]]
          ],

          /*
          ["hr"],
          ["fieldset", ["legend", "Global header rewrites"],
           templates.network_options_header_table(headers)
          ],
          */
          "class", "padding network-options"
         ];
};

templates.network_options_header_table = function(headers)
{
  var fun = function(header) {
      return ["tr",
               ["td", "DEL"],
               ["td", "ON"],
               ["td", ["input", "", "value", header.name]],
               ["td", ["input", "", "value", header.value]]
             ];
  };

  var tpl = ["table",
              ["tr",
                ["th", "X"], ["th", "Y"], ["th", "Name"], ["th", "Value"]],
                headers.map(fun)
            ];
  return tpl;
};

templates.network_request_crafter_main = function(url, request, response)
{
  return ["div",
          ["div",
           ["label", "URL:", ["input", "type", "text",
                              "value", url || "",
                              "handler", "request-crafter-url-change"
                             ]
           ],
           ["textarea", request]
          ],
          ["button", "Send request", "handler", "request-crafter-send"],
          ["hr"],
          ["div", ["pre", ["code", response]]],
          "class", "padding request-crafter"
         ];
};

templates.network_log_main = function(ctx, graphwidth)
{
  return [
    ["div",
     ["div",
      ["div", templates.network_log_url_list(ctx), "id", "left-side-content"],
      ["div",
       ["div", templates.network_log_graph(ctx, graphwidth),
        "id", "right-side-content"
       ],
       "id", "right-side-container",
      ],
      "id", "main-scroll-content",
     ],
     "class", "network-log",
     "id", "main-scroll-container",
    ],
    ["div", ["div", "id", "scrollbar"], "id", "scrollbar-container"]
  ];
}

templates.network_log_details = function(ctx, selected)
{
  return  [
    ["div", templates.network_log_url_list(ctx, selected),
     "class", "network-details-url-list"
    ],
    ["div", templates.network_log_request_detail(ctx, selected),
     "class", "network-details-request"
    ]
  ]
}

templates.network_log_request_detail = function(ctx, selected)
{
  var req = ctx.get_resource(selected);
  return [
    ["button", "X", "handler", "close-request-detail"],
    ["table",
     ["tr", ["th", "URL:"], ["td", req.url]],
     ["tr", ["th", "Method:"], ["td", req.method || "-"]],
     ["tr", ["th", "Status:"], ["td", String(req.responsecode || "-")]],
     "class", "resource-detail"
    ],
    ["hr"],
    ["h2", "Request details"],
    templates.network_header_table(req.request_headers),
    ["hr"],
    ["h2", "Response details"],
    templates.network_header_table(req.response_headers),
    ["hr"],
    ["h2", "Body"],
    templates.network_response_body(req)
  ]
}

templates.network_response_body = function(req)
{
  if (!req.responsebody)
  {
    return ["div",
            "Response body not tracked. To always fetch response bodies, toggle the response body option on the \"network options\" tab. To retrieve only this body, click the button.",
            ["button",
             "Get response body",
             "data-resource-id", String(req.id),
             "handler", "get-response-body"
             ]
            ]
  }
  else
  {
    var bodytpl;
    if (["script", "markup", "css", "text"].indexOf(req.type) != -1)
    {
      bodytpl = ["code", ["pre", req.responsebody.content.stringData]];
    }
    else if (req.type == "image")
    {
      bodytpl = ["img", "src", req.responsebody.content.stringData];
    }
    else
    {
      bodytpl = ["span", "not able to show data of type " + req.mime];
    }

    return ["div",
            bodytpl,
            "class", "response-body-content"
           ];
  }
}

templates.network_header_table = function(headers)
{
  if (!headers)
  {
    return ["table", ["tr", ["td", "No headers"]]];
  }

  var rowfun = function(header)
  {
    return ["tr",
            ["th", header.name],
            ["td", header.value]
           ]
  }

  var headers = headers.slice(0); // copy so we can sort withouth nuking original
  headers.sort(function(a, b) {
    if (a.name>b.name) { return 1 }
    else if (b.name>a.name) { return -1 }
    else { return 0 }
  });
  return ["table", headers.map(rowfun),
          "class", "header-list"];
}

templates.network_log_main_table = function(ctx)
{
  return [
    ["div", templates.network_log_url_list(ctx),
     "class", "resourcelist"
    ],
    ["div", templates.network_log_url_list(ctx),
     "class", "timeline"]
  ]
}

templates.network_log_url_list = function(ctx, selected)
{
  var itemfun = function(res) {
    return ["li", templates.network_request_icon(res), ["span", res.url],
            "handler", "select-network-request",
            "data-resource-id", String(res.id),
            "class", selected===res.id ? "selected" : ""
           ]
  }
  return ["ol", ctx.resources.map(itemfun),
          "class", "network-log-url-list"];
}

templates.network_request_icon = function(request)
{
  return ["span", "class", "resource-icon resource-type-" + request.type];
}

templates.network_log_graph = function(ctx, width)
{
  width = width;
  var rowheight = 23;
  var height = ctx.resources.length * rowheight;

  var gradients = templates.gradient_defs();
  var background = templates.network_log_background(ctx, rowheight);
  var bars = templates.graph_bars(ctx, width, rowheight);
  var grid = templates.grid_lines(ctx, width, height);

  var tpl = ["svg:svg",
             gradients,
             background,
             bars,
             grid,
             //'viewBox', '0 0 ' + 3000 + 'px ' + 500 +'px',
             "xmlns", "http://www.w3.org/2000/svg",
             "class", "resource-graph"];

    return tpl;
}

templates.graph_bars = function(ctx, width, height)
{
  var bars = [];
  var basetime = ctx.get_starttime();
  var duration = ctx.get_duration();
  duration = Math.ceil(duration / 1000) * 1000

  for (var n=0, req; req=ctx.resources[n]; n++)
  {
    var bar = templates.request_bar(n, req, basetime, duration, width, height);
    bars.push(bar);
  }
  return bars;
}

templates.request_bar = function(index, request, basetime, totaltime, contwidth, lineheight)
{
  var y = lineheight * index;
  var barheight = 12;
  var bary = y + (lineheight / 2) - (barheight / 2);
  var multiplier = contwidth / totaltime;

  if (!request.duration) {
    // fixme: request not done, so emit something saner here.
    return [];
  }

  var start = request.starttime;

  var reqwidth = request.duration

  var resstart = start+10//entry.requestfinished.time;
  var reswidth = 30; // reqwidth - (resstart - reqstart);

  var texture = "gradient-" + (request.type || "unknown");

  var tpl = [
    ["rect", "x", String((start-basetime)*multiplier), "y", String(bary),
     "width", String(reqwidth*multiplier), "height", String(barheight),
             "rx", "4", "ry", "4",
             "fill", "#dfdfdf", "stroke", "#969696", "stroke-width", "1.0"],

      ["rect", "x", String((resstart-basetime)*multiplier), "y", String(bary),
             "width", String(reswidth*multiplier), "height", String(barheight),
             "rx", "4", "ry", "4",
             "fill", "url(#" + texture + ")", "stroke", "#333333", "stroke-width", "1.0"]

  ];
  return tpl;
};

templates.grid_lines = function(ctx, width, height)
{
  var ret = [];
  var millis = ctx.get_duration();
  millis = Math.ceil(millis / 1000) * 1000
  var secondwidth = width / (millis / 1000);
  var multiplier = width / millis;

  // Thresholds for whether or not to render grid for every 100 and 500ms.
  // The number is how many pixels per second. So if every second is
  // alloted more than 200px, render the 100ms bars
  const THRESH_100MS = 200;
  const THRESH_500MS = 100;

  ret.push(["line",
            "x1", "0",
            "y1", "0",
            "x2", "0",
            "y2", String(height),
            "stroke", "black",
            "stroke-width", "1",
           ]);

  for (var n=100; n<millis; n+=100)
  {
    var color = null;
    if (!(n % 1000))
    {
      color = "black";
    }
    else if (secondwidth > THRESH_500MS && !(n % 500))
    {
      color = "gray";
    }
    else if (secondwidth > THRESH_100MS && !(n % 100))
    {
      color = "silver";
    }

    if (color) {
      ret.push(["line",
                "x1", String(n*multiplier),
                "y1", "0",
                "x2", String(n*multiplier),
                "y2", String(height),
                "stroke", color,
                "stroke-width", "1.0",
                "opacity", "1.0"
      ]);
    }
  }

  return ret;
};

templates.gradient_defs = function()
{
  return ["defs",
          templates.gradient("image", "#ff7c7c", "#cb1313", "#b40000", "#c42222"),
          templates.gradient("script", "#ffffeb","#e2dd9a","#c6bf7a", "#d1cd95"),
          templates.gradient("css", "#e6ffff", "#91c4ff", "#71a6f0", "#8eb8f3"),
          templates.gradient("markup", "#d9deff", "#7c85b9", "#6972a6", "#8088b4"),
          templates.gradient("unknown", "#ffffff", "#c0c0c0", "#aaaaaa", "#b8b8b8")
         ];
};

templates.gradient = function(id, c1, c2, c3, c4)
{
  return ["linearGradient",
          ["stop", "offset", "5%", "stop-color", c1],
          ["stop", "offset", "49%", "stop-color", c2],
          ["stop", "offset", "50%", "stop-color", c3],
          ["stop", "offset", "100%", "stop-color", c4],
          "x1", "0",
          "x2", "0",
          "y1", "0",
          "y2", "100%",
          "id", "gradient-" + id
         ];
};

templates.network_log_background = function(ctx, lineheight)
{
  var cnt = ctx.resources.length;
  var tpls = [];
  while (cnt--)
  {
    tpls.push(["rect", "x", "0",
                       "y", String(cnt*lineheight),
                       "width", "100%",
                       "height", String(lineheight),
                       "stroke-width", "0", "fill", (cnt%2 ?  "#f2f2f2" : "white")]);
  }
  return tpls;
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { Col, Label, Panel } from 'react-bootstrap'

const labelStyle = {
  marginRight: '5px'
}

const humanType = {
  'text': 'Text',
  'category': 'Category',
  'checkbox': 'True/False',
  'date': 'Date/Time',
  'location': 'Latitude and Longitude',
  'number': 'Number'
}

const ColumnCard = ({item, idx}) => {
  return (
    <Col md={12} key={idx}>
      <Panel header={
item.name
} className={'descriptionPanel'}>

 {item.description}

        Field type: {humanType[item.type]}
        API name: {item.key}
      </Panel>
    </Col>
  )
}

const ColumnList = ({list}) => {
  let keys = Object.keys(list)
  let listItems = keys.map((key, idx) => {
    return <ColumnCard item={list[key]} idx />
  })

  return (

      {listItems}

  )
}

ColumnList.propTypes = {
  list: PropTypes.object.isRequired
}

export default ColumnList
<commit_msg>fix titles<commit_after>import React, { PropTypes } from 'react'
import { Col, Label, Panel } from 'react-bootstrap'

const labelStyle = {
  marginRight: '5px'
}

const humanType = {
  'text': 'Text',
  'category': 'Category',
  'checkbox': 'True/False',
  'date': 'Date/Time',
  'location': 'Latitude and Longitude',
  'number': 'Number'
}

const ColumnCard = ({item, idx}) => {
  return (
    <Col md={12} key={idx}>
      <Panel header={
{item.name}
} className={'descriptionPanel'}>

 {item.description}

        Field type: {humanType[item.type]}
        API name: {item.key}
      </Panel>
    </Col>
  )
}

const ColumnList = ({list}) => {
  let keys = Object.keys(list)
  let listItems = keys.map((key, idx) => {
    return <ColumnCard item={list[key]} idx />
  })

  return (

      {listItems}

  )
}

ColumnList.propTypes = {
  list: PropTypes.object.isRequired
}

export default ColumnList
<|endoftext|>


<commit_before>/**
 * TODO: [Description]
 * @author Greg Rozmarynowycz <greg@thunderlab.net>
 */
'use strict';
const IOEvent = require('event-types').IOEvent;
const EventTarget = require('eventtarget');

function networkEntityFactory(Connection, $q, SimpleSocket) {

    class NetworkEntity extends EventTarget {

        constructor(id) {
            super();
            this.id = id;
        }

        getId() {
            return this.id;
        }

        reconstruct(params) {

        }

        sync(params) {
            Object.assign(this, params);
        }

        static registerType(type) {
            NetworkEntity.types.set(type.name, type);
            NetworkEntity.entities.set(type.name, new Map());
        }

        /**
         * Retrieve a network entity constructor based on name
         * @param typeName
         * @returns {undefined|V|V}
         */
        static getType(typeName) {
            if(NetworkEntity.types.has(typeName) === false) {
                throw new ReferenceError(`Type ${typeName} is not a valid network entity`);
            }

            return NetworkEntity.types.get(typeName);
        }

        /**
         * Returns a network entity identified by type and id
         * @param type {class}
         * @param id {string}
         * @returns {Promise<NetworkEntity>}
         */
        static getById(type, id) {
            if(!type || typeof id !== 'string') {
                throw new Error(`Network entities must be identified by both type and name`);
            }

            if(NetworkEntity.localEntityExists(type, id) === true) {
                return $q.when(NetworkEntity.entities.get(type.name).get(id));
            } else {
                return Connection.getSocket().request(IOEvent.syncNetworkEntity, {type: type.name, id: id})
                    .then(NetworkEntity.reconstruct);
            }
        }

        static localEntityExists(type, id) {
            return NetworkEntity.entities.get(type.name).has(id);
        }

        /**
         * Parses a response to rebuild a network entity
         * @param data
         * @returns {NetworkEntity}
         */
        static reconstruct(data) {
            const type = NetworkEntity.getType(data.type);
            let entity = null;
            if(NetworkEntity.localEntityExists(type, data.id) === true) {
                entity = NetworkEntity.entities.get(type.name).get(data.id);
                entity.sync(data.params);
            } else {
                entity = new type(data.params);
                NetworkEntity.entities.get(type.name).set(data.id, entity);
            }

            return entity;
        }
    }

    NetworkEntity.types = new Map();
    NetworkEntity.entities = new Map();

    Connection.ready().then(socket => {
        socket.get().on(IOEvent.syncNetworkEntity, NetworkEntity.reconstruct);
    });

    return NetworkEntity;
}

module.exports = networkEntityFactory;<commit_msg>add constructor types to client network entity<commit_after>/**
 * TODO: [Description]
 * @author Greg Rozmarynowycz <greg@thunderlab.net>
 */
'use strict';
const IOEvent = require('event-types').IOEvent;
const EventTarget = require('eventtarget');

function networkEntityFactory(Connection, $q, SimpleSocket) {

    class NetworkEntity extends EventTarget {

        constructor(id) {
            super();
            this.id = id;
        }

        getId() {
            return this.id;
        }

        reconstruct(params) {

        }

        sync(params) {
            Object.assign(this, params);
        }

        static registerType(type) {
            let baseType = type;
            NetworkEntity.lookupTypes.forEach(candidateType => {
                if(type.prototype instanceof candidateType) {
                    baseType = candidateType;
                }
            });

            NetworkEntity.constructorTypes.set(type.name, type);
            NetworkEntity.lookupTypes.set(type.name, baseType);
            if(baseType === type) {
                NetworkEntity.entities.set(type.name, new Map());
            }
        }

        static getConstructorType(typeName) {
            let resolvedType = typeName;
            if(NetworkEntity.constructorTypes.has(typeName) === false) {
                if (NetworkEntity.constructorTypes.has('Client' + typeName)) {
                    resolvedType = 'Client' + typeName;
                } else {
                    throw new ReferenceError(`Type ${typeName} is not a valid network entity constructor type`);
                }
            }

            return NetworkEntity.constructorTypes.get(resolvedType);
        }

        /**
         * Retrieve a network entity constructor based on name
         * @param typeName
         * @returns {undefined|V|V}
         */
        static getLookupType(typeName) {
            let resolvedType = typeName;
            if(NetworkEntity.lookupTypes.has(typeName) === false) {
                if (NetworkEntity.lookupTypes.has('Client' + typeName)) {
                    resolvedType = 'Client' + typeName;
                } else {
                    throw new ReferenceError(`Type ${typeName} is not a valid network entity lookup type`);
                }
            }

            return NetworkEntity.lookupTypes.get(resolvedType);
        }

        /**
         * Returns a network entity identified by type and id
         * @param type {class}
         * @param id {string}
         * @returns {Promise<NetworkEntity>}
         */
        static getById(type, id) {
            if(!type || typeof id !== 'string') {
                throw new Error(`Network entities must be identified by both type and name`);
            }

            if(NetworkEntity.localEntityExists(type, id) === true) {
                return $q.when(NetworkEntity.entities.get(type.name).get(id));
            } else {
                const serverType = type.name.replace('Client', '');
                return Connection.getSocket().request(IOEvent.syncNetworkEntity, {type: serverType, id: id})
                    .then(NetworkEntity.reconstruct);
            }
        }

        static localEntityExists(type, id) {
            return NetworkEntity.entities.get(type.name).has(id);
        }

        /**
         * Parses a response to rebuild a network entity
         * @param data
         * @returns {NetworkEntity}
         */
        static reconstruct(data) {
            const type = NetworkEntity.getLookupType(data.type);
            let entity = null;
            if(NetworkEntity.localEntityExists(type, data.id) === true) {
                entity = NetworkEntity.entities.get(type.name).get(data.id);
                entity.sync(data.params);
            } else {
                const ctorType = NetworkEntity.getConstructorType(data.type);
                entity = new ctorType(data.params);
                entity.sync(data.params);
                NetworkEntity.entities.get(type.name).set(data.id, entity);
            }

            return entity;
        }
    }

    NetworkEntity.lookupTypes      = new Map(); // Mapping of types to use for entity look ups
    NetworkEntity.constructorTypes = new Map(); // Types to use when reconstructing entities
    NetworkEntity.entities         = new Map(); // Collection of all synced entities

    Connection.ready().then(socket => {
        socket.get().on(IOEvent.syncNetworkEntity, NetworkEntity.reconstruct);
    });

    return NetworkEntity;
}

module.exports = networkEntityFactory;<|endoftext|>


<commit_before>"use strict";
//# sourceMappingURL=ng2-scrollimate.interface.js.map<commit_msg>Delete ng2-scrollimate.interface.js<commit_after><|endoftext|>


<commit_before>import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';

const styles = StyleSheet.create({
  root: {
    height: 1,
    backgroundColor: colors.grey,
    opacity: 0.5,
  },

  shadow: {
    backgroundColor: colors.greyOpacity,
    ...Platform.select({
      ios: {
        shadowOpacity: 0.8,
        shadowRadius: 4,
        shadowOffset: {
          height: 0,
          width: 0,
        },
      },
      android: {
        elevation: 0.3,
      },
    }),
  },
  opacity: {
    opacity: 0.3,
  },
});

export default styles;
<commit_msg>Very small shadow change<commit_after>import { Platform, StyleSheet } from 'react-native';
import { colors } from '../../styles';

const styles = StyleSheet.create({
  root: {
    height: 1,
    backgroundColor: colors.grey,
    opacity: 0.5,
  },
  shadow: {
    backgroundColor: colors.greyOpacity,
    ...Platform.select({
      ios: {
        shadowOpacity: 0.9,
        shadowRadius: 4,
        shadowOffset: {
          height: 0,
          width: 0,
        },
      },
      android: {
        elevation: 0.3,
      },
    }),
  },
  opacity: {
    opacity: 0.3,
  },
});

export default styles;
<|endoftext|>


<commit_before>import React from "react";
import { autobind } from "core-decorators";
import { substruct, compose, eq, get } from "../../fp";
import StakePoolsList from "./List";
import StakePoolsAddForm from "./AddForm";
import stakePools from "../../connectors/stakePools";

@autobind
class StakePools extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isAdding: false,
      apiKey: "",
      selectedUnconfigured: this.props.unconfiguredStakePools[0]
    };
  }

  render() {
    return this.getIsAdding() ? (
      <StakePoolsAddForm
        {...{
          ...this.props,
          ...this.state,
          selectedUnconfigured: this.getSelectedUnconfigured(),
          ...substruct({
            onChangeApiKey: null,
            onSaveStakePool: null,
            onSetStakePoolInfo: null,
            onChangeSelectedUnconfigured: null,
            onCancelPassphraseRequest: null,
            onCancelAddStakePool: null
          }, this),
          onSetStakePoolInfo: this.onSetStakePoolInfo
        }}
      />
    ) : (
      <StakePoolsList
        {...{
          ...this.props,
          ...substruct({
            onShowAddStakePool: null
          }, this)
        }}
      />
    );
  }

  getIsAdding() {
    return this.state.isAdding || this.props.configuredStakePools.length <= 0;
  }

  getSelectedUnconfigured() {
    const pool = this.state.selectedUnconfigured;
    return pool
      ? this.props.unconfiguredStakePools.find(compose(eq(pool.Host), get("Host")))
      : null;
  }

  onChangeSelectedUnconfigured(selectedUnconfigured) {
    this.setState({ selectedUnconfigured });
  }

  onShowAddStakePool() {
    this.setState({ isAdding: false });
  }

  onChangeApiKey(apiKey) {
    this.setState({ apiKey });
  }

  onSaveStakePool() {
    this.state.apiKey ? this.setState({ isRequestingPassphrase: true }) : null;
  }

  onCancelPassphraseRequest() {
    this.setState({ isRequestingPassphrase: false });
  }

  onCancelAddStakePool() {
    const { onHideStakePoolConfig } = this.props;
    this.setState({ isAdding: false });
    onHideStakePoolConfig && onHideStakePoolConfig();
  }

  onSetStakePoolInfo(privpass) {
    const { apiKey } = this.state;
    const onSetInfo = this.props.onSetStakePoolInfo;
    apiKey ? (onSetInfo && onSetInfo(privpass, this.getSelectedUnconfigured().Host, apiKey, 0)) : null;
  }
}

export default stakePools(StakePools);
<commit_msg>Fix to allow adding of more stakepools (#721)<commit_after>import React from "react";
import { autobind } from "core-decorators";
import { substruct, compose, eq, get } from "../../fp";
import StakePoolsList from "./List";
import StakePoolsAddForm from "./AddForm";
import stakePools from "../../connectors/stakePools";

@autobind
class StakePools extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isAdding: false,
      apiKey: "",
      selectedUnconfigured: this.props.unconfiguredStakePools[0]
    };
  }

  render() {
    return this.getIsAdding() ? (
      <StakePoolsAddForm
        {...{
          ...this.props,
          ...this.state,
          selectedUnconfigured: this.getSelectedUnconfigured(),
          ...substruct({
            onChangeApiKey: null,
            onSaveStakePool: null,
            onSetStakePoolInfo: null,
            onChangeSelectedUnconfigured: null,
            onCancelPassphraseRequest: null,
            onCancelAddStakePool: null
          }, this),
          onSetStakePoolInfo: this.onSetStakePoolInfo
        }}
      />
    ) : (
      <StakePoolsList
        {...{
          ...this.props,
          ...substruct({
            onShowAddStakePool: null
          }, this)
        }}
      />
    );
  }

  getIsAdding() {
    return this.state.isAdding || this.props.configuredStakePools.length <= 0;
  }

  getSelectedUnconfigured() {
    const pool = this.state.selectedUnconfigured;
    return pool
      ? this.props.unconfiguredStakePools.find(compose(eq(pool.Host), get("Host")))
      : null;
  }

  onChangeSelectedUnconfigured(selectedUnconfigured) {
    this.setState({ selectedUnconfigured });
  }

  onShowAddStakePool() {
    this.setState({ isAdding: true });
  }

  onChangeApiKey(apiKey) {
    this.setState({ apiKey });
  }

  onSaveStakePool() {
    this.state.apiKey ? this.setState({ isRequestingPassphrase: true }) : null;
  }

  onCancelPassphraseRequest() {
    this.setState({ isRequestingPassphrase: false });
  }

  onCancelAddStakePool() {
    const { onHideStakePoolConfig } = this.props;
    this.setState({ isAdding: false });
    onHideStakePoolConfig && onHideStakePoolConfig();
  }

  onSetStakePoolInfo(privpass) {
    const { apiKey } = this.state;
    const onSetInfo = this.props.onSetStakePoolInfo;
    apiKey ? (onSetInfo && onSetInfo(privpass, this.getSelectedUnconfigured().Host, apiKey, 0)) : null;
  }
}

export default stakePools(StakePools);
<|endoftext|>


<commit_before>// adopted from: is-data-descriptor <https://github.com/jonschlinkert/is-data-descriptor>
// Copyright (c) 2015, Jon Schlinkert. (MIT)

var hasOwn = require('./hasOwn')
var kind   = require('../lang/kind')

function isDataDescriptor (obj, prop) {
  if (kind.safe(obj) !== 'object') return false

  if (typeof prop === 'string') {
    var val = Object.getOwnPropertyDescriptor(obj, prop)
    if (!('value' in val) && !('writable' in val)) return false

    return typeof val !== 'undefined'
  }

  // I am being anal here. I require all properties to be present
  // if only an object is being passed. this check is primarily for
  // lang/defineProp -- a wrapper for Object.defineProperty
  if (isDescriptorProp('configurable')
    && isDescriptorProp('enumerable')
    && (isDescriptorProp('writable') || hasOwn(obj, 'value'))
  ) return true

  return false

  function isDescriptorProp (prop) {
    return hasOwn(obj, prop) && typeof obj[prop] === 'boolean'
  }
}

module.exports = isDataDescriptor
<commit_msg>lint object/is-descriptor-data<commit_after>// adopted from: is-data-descriptor <https://github.com/jonschlinkert/is-data-descriptor>
// Copyright (c) 2015, Jon Schlinkert. (MIT)

var hasOwn = require('./hasOwn')
var kind   = require('../lang/kind')

function isDataDescriptor (obj, prop) {
  if (kind.safe(obj) !== 'object') return false

  if (typeof prop === 'string') {
    var val = Object.getOwnPropertyDescriptor(obj, prop)
    if (!('value' in val) && !('writable' in val)) return false

    return typeof val !== 'undefined'
  }

  // I am being anal here. I require all properties to be present
  // if only an object is being passed. this check is primarily for
  // lang/defineProp -- a wrapper for Object.defineProperty
  if (isDescriptorProp('configurable')
    && isDescriptorProp('enumerable')
    && (isDescriptorProp('writable') || hasOwn(obj, 'value'))
  ) return true

  return false

  function isDescriptorProp (prop) {
    return hasOwn(obj, prop) && typeof obj[prop] === 'boolean'
  }
}

module.exports = isDataDescriptor
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Component.extend({
    tagName: 'document-creator',
    classNames: 'document-creator',
    documentTitle: null,
    isCreating: false,

    actions: {
      createDocument: function () {
        this.createDocument();
      },
    },

    createDocument: function () {
      var title = this.get('documentTitle').trim(),
        component = this;

      this.set('isCreating', true);

      console.log('creating document...');
      return this.get('documentSource').createManually(title).then(function (doc) {
        component.sendAction('documentCreated', doc);
        component.set('isCreating', false);
      }, function (error) {
        component.set('isCreating', false);
      });
    }
});
<commit_msg>Removed debug console.log call<commit_after>import Ember from 'ember';

export default Ember.Component.extend({
    tagName: 'document-creator',
    classNames: 'document-creator',
    documentTitle: null,
    isCreating: false,

    actions: {
      createDocument: function () {
        this.createDocument();
      },
    },

    createDocument: function () {
      var title = this.get('documentTitle').trim(),
        component = this;

      this.set('isCreating', true);

      return this.get('documentSource').createManually(title).then(function (doc) {
        component.sendAction('documentCreated', doc);
        component.set('isCreating', false);
      }, function (error) {
        component.set('isCreating', false);
      });
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router';

export class Nav extends React.Component { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    boards: React.PropTypes.object.isRequired,
  };

  render() {
    return (

            {this.props.boards.map((board, i) => (
              <Link
                to={`/boards/${board.id}`}
                className="nav-item is-tab is-hidden-mobile"
                activeClassName="is_active"
                key={i}
              >
                {board.name}
              </Link>
            ))}

    );
  }
}

export default connect(
  (state) => ({
    boards: state.get('app').get('boards'),
  }),
  (dispatch) => bindActionCreators({
    //
  }, dispatch)
)(Nav);
<commit_msg>is-active fix<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router';

export class Nav extends React.Component { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    boards: React.PropTypes.object.isRequired,
  };

  render() {
    return (

            {this.props.boards.map((board, i) => (
              <Link
                to={`/boards/${board.id}`}
                className="nav-item is-tab is-hidden-mobile"
                activeClassName="is-active"
                key={i}
              >
                {board.name}
              </Link>
            ))}

    );
  }
}

export default connect(
  (state) => ({
    boards: state.get('app').get('boards'),
  }),
  (dispatch) => bindActionCreators({
    //
  }, dispatch)
)(Nav);
<|endoftext|>


<commit_before>export { Base };

//import * as FloatValue from "../../Unpacker/FloatValue.js";
//import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as Weights from "../../Unpacker/Weights.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import * as Depthwise from "./Depthwise.js"; //avg pooling
import * as Pointwise from "./Pointwise.js"; //_ConstantWhenPassThrough

//!!! ...unfinished... (2022/05/14)
// Q: Perhaps, let pointwise1 become squeeze and excitation before depthwise.
// A: It may not be possible because input and output channel count may be different.

//!!! ...unfinished... (2022/05/15)
// Fo half copy and pass-through, the squeeze and excitation should also pass-through
// (i.e filter = 0, bias = 1) (compare to pass-through for addition operation: filter = 1, bias = 0)
//
// pointwiseSE's filterValueAdjusted = undoDepthwiseActivationEscapingScale * filterValue
//
// pointwise2's filterValueAdjusted = undoDepthwiseActivationEscapingScale * undoPointwiseSEActivationEscapingScale * filterValue
//
//
//
// o should undo previous activation escaping scale
// o when pass-through, filter = 0, bias = 1 (not: filter 1, bias 0)
// o even if there is pass-through, it is not necessary to activation escaping scale.
// o The bounds array set of output (which is input multiplied by squeeze-and-excitation) should include squeeze-and-excitation.
//   However, the activation escaping scale should be the same as input's activation escaping scale.
//   So that the next operation (e.g. pointwise2) could restore the correct input (with squeeze-and-excitation) 。
//
// PASS_THROUGH_STYLE_FILTER_1_BIAS_0_ACTIVATION_ESCAPING
// PASS_THROUGH_STYLE_FILTER_0_BIAS_1_ACTIVATION_NO_ESCAPING

//!!! ...unfinished... (2022/05/08) Add squeeze and excitation before pointwise.
// globale avg pooling - pointwise - pointwise - multiplyToInput
// And the, the original pointwise

//!!! ...unfinished... (2022/05/09) What if:
// pointwise1 ( bias, activation )
// depthwise ( channelMultipler > 1, bias / no bias, activation / no activation )
// pointwiseSE ( bias, activation )
// pointwise2 ( bias, activation )
//
// pointwise1 - depthwise - pointwiseSE - multiply - pointwise2
//                        \-------------/
//
// No global average pooloing.
//
//
//
//

/**
 *
 */
class Pointwise_SqueezeExcitation extends Pointwise_Base {

//!!! ...unfinished... (2022/05/08)

  /**
   */
  constructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount,

//!!! ...unfinished... (2022/05/08) squeeze channel count? ratio?

    ) {

    super(
      inputChannelCount, outputChannelCount, bBias, nActivationId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount );
  }

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @param {Array} arrayTemp_forInterleave_asGrouptTwo
   *   A temporary array for placing the original elements temporarily. Provide this array could reduce memory re-allocation
   * and improve performance when doing Interleave_asGrouptTwo.
   *
   * @return {boolean} Return true, if succeeded.
   */
  init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo ) {

//!!! ...unfinished... (2022/05/08)

  }

//!!! ...unfinished... (2022/05/15) should deletel sub pointwise.boundsArraySet

}
<commit_msg>Update SqueezeExcitation.js<commit_after>export { Base };

//import * as FloatValue from "../Unpacker/FloatValue.js";
//import * as ValueDesc from "../Unpacker/ValueDesc.js";
//import * as Weights from "../Unpacker/Weights.js";
import * as BoundsArraySet from "./BoundsArraySet.js";
import * as Depthwise from "./Depthwise.js"; //avg pooling
import * as Pointwise from "./Pointwise.js"; //_ConstantWhenPassThrough

//!!! ...unfinished... (2022/05/14)
// Q: Perhaps, let pointwise1 become squeeze and excitation before depthwise.
// A: It may not be possible because input and output channel count may be different.

//!!! ...unfinished... (2022/05/15)
// Fo half copy and pass-through, the squeeze and excitation should also pass-through
// (i.e filter = 0, bias = 1) (compare to pass-through for addition operation: filter = 1, bias = 0)
//
// pointwiseSE's filterValueAdjusted = undoDepthwiseActivationEscapingScale * filterValue
//
// pointwise2's filterValueAdjusted = undoDepthwiseActivationEscapingScale * undoPointwiseSEActivationEscapingScale * filterValue
//
//
//
// o should undo previous activation escaping scale
// o when pass-through, filter = 0, bias = 1 (not: filter 1, bias 0)
// o even if there is pass-through, it is not necessary to activation escaping scale.
// o The bounds array set of output (which is input multiplied by squeeze-and-excitation) should include squeeze-and-excitation.
//   However, the activation escaping scale should be the same as input's activation escaping scale.
//   So that the next operation (e.g. pointwise2) could restore the correct input (with squeeze-and-excitation) 。
//
// PASS_THROUGH_STYLE_FILTER_1_BIAS_0_ACTIVATION_ESCAPING
// PASS_THROUGH_STYLE_FILTER_0_BIAS_1_ACTIVATION_NO_ESCAPING

//!!! ...unfinished... (2022/05/08) Add squeeze and excitation before pointwise.
// globale avg pooling - pointwise - pointwise - multiplyToInput
// And the, the original pointwise

//!!! ...unfinished... (2022/05/09) What if:
// pointwise1 ( bias, activation )
// depthwise ( channelMultipler > 1, bias / no bias, activation / no activation )
// pointwiseSE ( bias, activation )
// pointwise2 ( bias, activation )
//
// pointwise1 - depthwise - pointwiseSE - multiply - pointwise2
//                        \-------------/
//
// No global average pooloing.
//
//
//
//

/**
 *
 */
class Pointwise_SqueezeExcitation extends Pointwise_Base {

//!!! ...unfinished... (2022/05/08)

  /**
   */
  constructor(
    inputChannelCount, outputChannelCount, bBias, nActivationId,
    nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount,

//!!! ...unfinished... (2022/05/08) squeeze channel count? ratio?

    ) {

    super(
      inputChannelCount, outputChannelCount, bBias, nActivationId,
      nHigherHalfDifferent, inputChannelCount_lowerHalf, outputChannelCount_lowerHalf, channelShuffler_outputGroupCount );
  }

  /**
   * @param {Float32Array} inputFloat32Array
   *   A Float32Array whose values will be interpreted as weights.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray
   *   The element value bounds (per channel) of input. Usually, it is The .output of the previous convolution-bias-activation value bounds
   * set of this pointwise convolution. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @param {Array} arrayTemp_forInterleave_asGrouptTwo
   *   A temporary array for placing the original elements temporarily. Provide this array could reduce memory re-allocation
   * and improve performance when doing Interleave_asGrouptTwo.
   *
   * @return {boolean} Return true, if succeeded.
   */
  init( inputFloat32Array, byteOffsetBegin, inputScaleBoundsArray, arrayTemp_forInterleave_asGrouptTwo ) {

//!!! ...unfinished... (2022/05/08)

  }

//!!! ...unfinished... (2022/05/15) should deletel sub pointwise.boundsArraySet

}
<|endoftext|>


<commit_before>// ==UserScript==
// @name       js_lib_booster
// @namespace  http://gubnota.ru/
// @version    0.1
// @description  Replace Google CDN with my jquery libs
// @copyright  2014+, Vladislav Muravyev
// @grant          none
// @icon http://gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/fb.ico
// @run-at document-start
// ==/UserScript==
// itteration across DOM elems http://callmenick.com/2014/03/10/javascript-foreach-loop/
// http://localhost/p/cdn/jquery/
window.onload = function(){
[].slice.call(document.getElementsByTagName('script')).forEach(function(el,i){
    if (el.src && el.src.match('/yandex.st/') ){
        if ( el.src.match('/1.')) {
        var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-1.11.2.min.js';
        }
        else if ( el.src.match('/2.')){
        var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-2.1.3.min.js';
        }
    }
    if (el.src && el.src.match('/ajax.googleapis.com/') ){
    if (el.src && ( el.src.match('/jquery.') || el.src.match('/jquery/') || el.src.match('/jquery-'))){
    if ( el.src.match('/1.') || el.src.match('1.6') || el.src.match('1.7') || el.src.match('1.8') || el.src.match('1.9') || el.src.match('1.10'))
    var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-1.11.2.min.js';
    else if ( el.src.match('/2.') || el.src.match('2.0') || el.src.match('2.1') || el.src.match('2.2') || el.src.match('2.3'))
    var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-2.1.3.min.js';
    }
    var new_el = document.createElement('script'); new_el.src = replace;
    var parent = el.parentElement;
    }
    if (typeof replace !='undefined'){
    var new_el = document.createElement('script'); new_el.src = replace;
    var parent = el.parentElement;
//  var new2_el = document.createElement('script');
       new_el.src = replace;
    var parent = el.parentElement;
  parent.removeChild(el);
  parent.appendChild(new_el);
//  alert(el.src+' '+new_el.src);
// parent.replaceChild(new_el, el);
            }

});
};

/*
var script = document.createElement('script');
script.src = 'http://localhost/';
document.getElementsByTagName('head')[0].appendChild(script);
*/<commit_msg>rearrangment<commit_after>// ==UserScript==
// @name       js_lib_booster
// @namespace  http://gubnota.ru/
// @version    0.1
// @description  Replace Google CDN with my jquery libs
// @copyright  2014+, Vladislav Muravyev
// @grant          none
// @icon http://gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/g.png
// @run-at document-start
// ==/UserScript==
// itteration across DOM elems http://callmenick.com/2014/03/10/javascript-foreach-loop/
// http://localhost/p/cdn/jquery/
window.onload = function(){
[].slice.call(document.getElementsByTagName('script')).forEach(function(el,i){
    if (el.src && el.src.match('/yandex.st/') ){
        if ( el.src.match('/1.')) {
        var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-1.11.2.min.js';
        }
        else if ( el.src.match('/2.')){
        var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-2.1.3.min.js';
        }
    }
    if (el.src && el.src.match('/ajax.googleapis.com/') ){
    if (el.src && ( el.src.match('/jquery.') || el.src.match('/jquery/') || el.src.match('/jquery-'))){
    if ( el.src.match('/1.') || el.src.match('1.6') || el.src.match('1.7') || el.src.match('1.8') || el.src.match('1.9') || el.src.match('1.10'))
    var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-1.11.2.min.js';
    else if ( el.src.match('/2.') || el.src.match('2.0') || el.src.match('2.1') || el.src.match('2.2') || el.src.match('2.3'))
    var replace = 'gubnota.github.io/fenki_js_helpers/plugin/monkey/js_lib_booster/jquery-2.1.3.min.js';
    }
    var new_el = document.createElement('script'); new_el.src = replace;
    var parent = el.parentElement;
    }
    if (typeof replace !='undefined'){
    var new_el = document.createElement('script'); new_el.src = replace;
    var parent = el.parentElement;
//  var new2_el = document.createElement('script');
       new_el.src = replace;
    var parent = el.parentElement;
  parent.removeChild(el);
  parent.appendChild(new_el);
//  alert(el.src+' '+new_el.src);
// parent.replaceChild(new_el, el);
            }

});
};

/*
var script = document.createElement('script');
script.src = 'http://localhost/';
document.getElementsByTagName('head')[0].appendChild(script);
*/<|endoftext|>


<commit_before>/**
 * Patterns autoscale - scale elements to fit available space
 *
 * Copyright 2012 Humberto Sermeno
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "jquery.browser",
    "pat-base",
    "pat-registry",
    "pat-parser"
], function($, dummy, Base, registry, Parser) {
    var parser = new Parser("auto-scale");
    parser.addArgument("method", "scale", ["scale", "zoom"]);
    parser.addArgument("min-width", 0);
    parser.addArgument("max-width", 1000000);

    return Base.extend({
        name: "autoscale",
        trigger: ".pat-auto-scale",
        force_method: null,

        init: function($el, opts) {
            this.options = parser.parse(this.$el, opts);
            if (this.force_method !== null) {
                this.options.method = this.force_method;
            }
            this._setup().scale();
            return this.$el;
        },

        _setup: function() {
            if ($.browser.mozilla) {
                // See https://bugzilla.mozilla.org/show_bug.cgi?id=390936
                this.force_method = "scale";
            } else if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
                this.force_method = "zoom";
            }
            $(window).on("resize.autoscale",
                _.debounce(this.scale.bind(this), 250, true)
            );
            $(document).on("pat-update.autoscale", _.debounce(this.scale.bind(this), 250));
            return this;
        },

        scale: function() {
            var available_space, scale;

            if (this.$el[0].tagName.toLowerCase() === "body") {
                available_space = $(window).width();
            } else {
                available_space = this.$el.parent().outerWidth();
            }
            available_space = Math.min(available_space, this.options.maxWidth);
            available_space = Math.max(available_space, this.options.minWidth);
            scale = available_space/this.$el.outerWidth();

            switch (this.options.method) {
                case "scale":
                    this.$el.css("transform", "scale(" + scale + ")");
                    break;
                case "zoom":
                    this.$el.css("zoom", scale);
                    break;
            }
            this.$el.addClass("scaled");
            return this;
        }
    });
});
<commit_msg>wrap scaled element in div to allow proper content pushing. Fixes #430<commit_after>/**
 * Patterns autoscale - scale elements to fit available space
 *
 * Copyright 2012 Humberto Sermeno
 * Copyright 2013 Simplon B.V. - Wichert Akkerman
 */
define([
    "jquery",
    "jquery.browser",
    "pat-base",
    "pat-registry",
    "pat-parser"
], function($, dummy, Base, registry, Parser) {
    var parser = new Parser("auto-scale");
    parser.addArgument("method", "scale", ["scale", "zoom"]);
    parser.addArgument("min-width", 0);
    parser.addArgument("max-width", 1000000);

    return Base.extend({
        name: "autoscale",
        trigger: ".pat-auto-scale",
        force_method: null,

        init: function($el, opts) {
            this.options = parser.parse(this.$el, opts);
            if (this.force_method !== null) {
                this.options.method = this.force_method;
            }
            this._setup().scale();
            return this.$el;
        },

        _setup: function() {
            if ($.browser.mozilla) {
                // See https://bugzilla.mozilla.org/show_bug.cgi?id=390936
                this.force_method = "scale";
            } else if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
                this.force_method = "zoom";
            }
            $(window).on("resize.autoscale",
                _.debounce(this.scale.bind(this), 250, true)
            );
            $(document).on("pat-update.autoscale", _.debounce(this.scale.bind(this), 250));
            return this;
        },

        scale: function() {
            var available_space, scale, scaled_height, scaled_width;

            if (this.$el[0].tagName.toLowerCase() === "body") {
                available_space = $(window).width();
            } else {
                available_space = this.$el.parent().outerWidth();
            }
            available_space = Math.min(available_space, this.options.maxWidth);
            available_space = Math.max(available_space, this.options.minWidth);
            scale = available_space/this.$el.outerWidth();
            scaled_height = this.$el.outerHeight() * scale;
            scaled_width = this.$el.outerWidth() * scale;

            switch (this.options.method) {
                case "scale":
                    this.$el.css("transform", "scale(" + scale + ")");
                    this.$el.wrap("

");
                    this.$el.parent().height(scaled_height).width(scaled_width);
                    break;
                case "zoom":
                    this.$el.css("zoom", scale);
                    break;
            }
            this.$el.addClass("scaled");
            return this;
        }
    });
});
<|endoftext|>