<commit_before>app.service('corporations', function($http) {
  this.information = function(){
    return [
          {
            id: 1,
            title: 'CreativeAI',
            description: 'This post-modernist ad agency uses the latest in artifical intelligence to develop highly-targeted messages to reach consumers. They are experts at manipulating culture and human emotion to convince people to do horrible things. The only humans CreativeAI hires are "data scientists"; all of their other employees are algorithms.',
            industries: "Public Relations, Advertising, Entertainment",
            pro_quote: "[The noises from video compression] are more beautiful to me than most things deliberately made by humans.--Loren Schmidt, Human Co-Founder",
            anti_quote: "CreativeAI's work is...decent. Not as good as a human, of course. But the corporations don't care about quality. They care about cost. And a computer is much cheaper than a human.---Argyros Naevius, former journalist",
            favorite_policy: "Transperancy Mandate",
            alignment: "left"
          },
          {
            id: 2,
            title: 'Vanguard',
            description: "A left-wing organization dedicated to leading a People's Revolution to overthrow capitalism. To raise funds for its lofty goal, Vanguard sells its 'espionage' and 'security' services to the other corporations. Vanguard has been linked to many high-profile assassinations of corporate executives...all of them paid for by other corporate executives.",
            pro_quote: "Remember that we do not want our sons and daughters to live in this cursed hell. We will fight for their sake.---Dori Iodocus, CEO",
            anti_quote: "It is cliche to point out that the Vanguard leadership lives in skyscrapers and mansions while their employees are dirt-poor, expendable cannon fooder. But at least the Vanguard leadership recognizes the irony and pretends to cry about it.---Argyros Naevius, former journalist",
            favorite_policy: "E-Democracy",
            industries: "Corporate Espionage, Military",
            alignment: "left"
          },
          {
            id: 3,
            title: 'Centaurs Incorporated',
            description: "Humans who have decided to 'upgrade' themselves by merging with their machines, turning into a weird hybrid of 'artifical intelligence' and 'natural intelligence'. They are the workforce that are responsible for manufacturing most of the goods that the other corporations repackage and sell to other people. They are strong advocates for uplifting other people to the 'next stage of human evolution', and will happily kidnap and brainwash those who refuses upliftment.",
            pro_quote: "I am unable to see why if AI becomes effective and productive it would result in anything other than an age of practical abundance.--friendsie, Vice-President of Marketing",
            anti_quote: "In the past, we humans used technology. Now, technology uses us, and is using us for some greater, unfathomable purpose.---Yamato Izz al-Din, former Centaur employee",
            favorite_policy: "Basic Income",
            industries: "Industrial Automation, Research and Development"
            alignment: "libertarian"
          },
          {
            id: 4,
            title: "Baudrillard Associates",
            description: "An alliance of rogue financial traders and bankers who had given up pretending to comply with arbitrary government regulations and appeasing corrupt financial regulators. The white collar crime may be boring, but the pay is more than worth it. Currently the most popular corporation in the city, due to their reluctance to use violence to settle disputes.",
            industries: "Financial Services, Investment Banking, Accounting",
            anti_quote: "There is no evidence that the Baudrillard Associates even *exists*. Either the leadership has hidden themselves very well, or these bankers invented up the organization just to give themselves an excuse to do what they always wanted to do.---Tadeo Waldobert, Police Officer",
            pro_quote: "When the government treats the law as a pliable instrument to be used creatively, it tends to encourage citizens to treat it the same way. ... [The corporations] treated the law as a game to be played, a puzzle to be solved as aggressively as possible, rather than a moral obligation. THE JUSTICE DEPARTMENT DOES TOO.---Matt Levine, Senior Vice President of Public Relations",
            favorite_policy: "Deregulation",
            alignment: "libertarian"
          },
          {
            id: 5,
            title: "PAGAD",
            description: "The 'People Against Gangsterism and Drugs' movement had its roots in the chaotic violence in 1990s South Africa. It has since spread throughout the world as an anti-globalization political force. Members of PAGAD use car bombings, intimidation, and extortion in its eternal crusade against corporate crime, in the hopes of bringing sanity to an often insane world. Despite its supposedly secular nature, PAGAD has attracted its fair share of religious zealots.",
            industries: "Security & Investigations, Law Enforcement",
            favorite_policy: "Vigilante Legalization",
            anti_quote: "They believe they can go against the law if it means ridding the area of a drug dealer or gangster. How are they any better than the criminals when they resort to criminal tactics?---John Davids, South African Civilian",
            pro_quote: "If you do not mobilise yourselves, no one will do it for you. Drugs and gangsterism is destroying our society and everyone is affected.---Haroun Orrie, PAGAD spokesperson",
            alignment: "rightist"
          },
          {
            id: 6,
            title: "Room 39",
            description: "A criminal organization that was founded in the late 1970s with explicit purpose of securing funding for the North Korean dictatorship, through the use of criminal activities such as drug smuggling and weapons trafficking.  After the fall of the North Korean dictatorship, Room 39 went 'legit' in return for legal immunity for its previous crimes. Room 39 is slowly and gradually adjusting to the capitalist system.",
            pro_quote: "Ideologies are like clothing; when one is worn out, it's time to buy a new one.---Ji-Hun Yeong-Ho, Room 39 agent",
            anti_quote: "It's a mockery of our laws that a criminal gang is able to freely reinvent themselves as a honorable corporation. And they probably haven't given up on the crime yet.---Argyros Naevius, former journalist",
            favorite_policy: "Slush Fund",
            industries: "Pharmaceuticals, Weapon Production",
            alignment: "rightist"
          },
          {
            id: 7,
            title: "Singularity LLC",
            description: "Radical political activists who (after being repeatedly disappointed at the failure of human politicans and regulators to solve problems) are attempting to build an Artifical General Intelligence that will control human society. They sometimes rent their experiments as 'consultants' to the other corporations to help raise revenue.",
            pro_quote: "People are superstitios [sic] about self-modifying code because once you employ this for solving usual engineering problems, you will often find it to be difficult to trace down the reasons for your program's behavior and that the ability of a program to modify itself can be exploited to gain access / information by people / other programs they not allowed to have. However, if these aren't problematic, then any Lisp or Prolog is a safe bet. Something that speaks to broader audience: Python, JavaScript, Lua.---wvxvw, Singularity LLC employee",
            anti_quote: "Humans *don't* agree on how to run our society! Why should we trust a computer to know any better?---Bassam Petru, lawyer",
            favorite_policy: "Algorithmic Law",
            industries: "Consulting, Life Coaching",
            alignment: "libertarian"
          },
          {
            id: 8,
            title: "VHEMT",
            description: "A radical environmentalist organization founded in the early 1990s by Les U. Knight, VHEMT stands for the 'Voluntary Human Extiniction Movement'. As society has grown more dystopian, many people have began supporting VHEMT as the best way to increase global  welfare, declaring that the death of humanity is the only sensible choice in a insensible world.",
            pro_quote: "Q: Is this another one of those suicide cults? A: Seems as if our entire industralized civilization is one big suicide cult. ... [V]oluntary human extiniction offers a healthy cure to humanity's collective death wish.---VHEMT Q&A"
            anti_quote: "The logic is as absurd as it's unassailable. Yes, indeed, if there are no more children, there will be no more child tragedies. Or child triumphs, for that matter, or much reason to think childless humanity will spend its dying days as serenely as Knight predicts. ---Brian Bethune, journalist"
            industries: "Environmental Services",
            alignment: "left"
          },
          {
            id: 9,
            title: "Liberal Crime Squad"
            description: "A leftist terrorist group that previously wanted to establish an 'Elite Liberal Utopia'. The leadership soon realized that it would be far easier to plug people into a 'simulation' of an Elite Liberal utopia instead. They now adopt a policy of utter hedonism, and only leave the VR sims to raise funds and preach their agenda to the masses.",
            pro_quote: "Only by abandoning 'Conservative Reality' can humanity be awakened to its True Liberal Nature and be able to enjoy happy, productive lives.---Chris Horsa, Liberal Crime Squad Founder",
            anti_quote: "The LCS agents sleep soundly in their virtual pods, and dream of fighting their war against Conservative society. But I notice that they never really dream what happens after they win.---Leobwin Sansone, former LCS employee",
            industries: "Virtual Reality",
            alignment: "left"
          },
          {
            id: 10,
            title: "Daemon Hunters",
            description: "Wackos and conspiracy theorists who believe that they are living in a computer simulation ('MMO') controlled by cruel daemons ('players'). These daemons regularly pay 'subscription fees' for the chance to beat up and cruelly torture 'NPCs' (us). The Demon Hunters seek to purge the daemonic element from human society, but have a hard time distingushing between the NPCs and the daemons.",
            pro_quote: "Friend or foe? Paranoia imperative. Galaxy purely casual, individualism is a statistical anomaly - Nada is an error. Trust Nada? Trust you?---Priest Entity Nada, CTO of Daemon Hunters",
            anti_quote: "If I was a daemon, the first thing I'd do is to create a faction to grief other daemons. Read between the lines.---Argyros Naevius, former journalist",
            alignment: "right"
          }
        ]
  }
  })
// Other Corps To Add?

// Uber/On-Demand Startups?
// Conservative Crime Squad?
// Social Media?
// "Weyland Corps" could be an interesting addition, and it would introduce the standard 'evil corp' back into the picture, since most of the corps here seem to make more sense as rebellious scum than as multitrillion-dollar megacorps. (Weyland appears to be a pro-"human supremacy" organization that does care for the environment and believe mankind to be like gods.) The biggest hurdle for Weyland Corps is two-folds
// One...the existence of the Daemon Hunters already mean you have a faction dedicated to interacting with 'extraterrestial entities' (the Demons), although the Daemon Hunters 'officially' wants to purge demons, not use them as weaponry.
// Two...the Weyland Corps' techno-utopianism is already reflected in Cenaturs Incorporated and Singularility LLC, and actually made more explicit. Their environmentalism is radicalized in the form of VHEMT. In the dystopian world of The Regulator, the Weylands are just too...conventional. Too boring.

// Peter Weyland's speech: http://lybio.net/peter-weylands-2023-ted-talk/people/
// Even though Peter believed mankind to be god, in the movie Prometheus, he had to beg to the Creators themselves...gods who are theorized to have made mankind solely as breeding vessels for the greatest biological weapons ever...the Xenomorphs

// Possible 'Enemy Faction' To Include If Tyranny is too High
// If so, provide hints that the HFSE exist in the Lore before launching them
// I like this faction but it appears to be a non-violent version of PAGAD,
// so it can't really be used
// {
//   id: 11,
//   title: "Human Flesh Search Engine",
//   description: "Established in the early 21st century as a loose-knit collection of Chinese vigilantes seeking to punish corruption and immorality through public shaming and doxxing, it has since absorbed other crowd-sourced intelligence gathering entities to become a major international force. The HFSE uses harrassment and death threats to push the vague and shifting views of the Internet mob, and tends to target both the strong and the weak fairly equally.",
//   pro_quote: "Righteousness is one of the five virtues in the Confucian tradition. With the convenience of the internet, and in the case of non-responsive law, the righteous people took matters into their own hands.---Xujun Eberlein, Chinese-American writer",
//   anti_quote: "The human-flesh search has unimaginable power. First it was a lot of phone calls every day. Then people painted red characters on his parents’ froxnt door, which said things like, ‘You caused your wife’s suicide, so you should pay.’---Zhang Yanfeng, lawyer representing Wang Fei, a husband accused of cheating on his wife. Wang Fei went into hiding to evade the HFSE",
//   alignment: "right?"
// }

// The HFSE is a place that you can periodically monitor to check people's opinions about you. If you engage in too much tyranny, the HFSE will turn against you, and you will go against their wrath (which includes threatening attacks as well as stronger Corporations.)
// When you start the game, you log onto the HFSE to get your job.<commit_msg>Finally found a good industry for Daemon Hunters<commit_after>app.service('corporations', function($http) {
  this.information = function(){
    return [
          {
            id: 1,
            title: 'CreativeAI',
            description: 'This post-modernist ad agency uses the latest in artifical intelligence to develop highly-targeted messages to reach consumers. They are experts at manipulating culture and human emotion to convince people to do horrible things. The only humans CreativeAI hires are "data scientists"; all of their other employees are algorithms.',
            industries: "Public Relations, Advertising, Entertainment",
            pro_quote: "[The noises from video compression] are more beautiful to me than most things deliberately made by humans.--Loren Schmidt, Human Co-Founder",
            anti_quote: "CreativeAI's work is...decent. Not as good as a human, of course. But the corporations don't care about quality. They care about cost. And a computer is much cheaper than a human.---Argyros Naevius, former journalist",
            favorite_policy: "Transperancy Mandate",
            alignment: "left"
          },
          {
            id: 2,
            title: 'Vanguard',
            description: "A left-wing organization dedicated to leading a People's Revolution to overthrow capitalism. To raise funds for its lofty goal, Vanguard sells its 'espionage' and 'security' services to the other corporations. Vanguard has been linked to many high-profile assassinations of corporate executives...all of them paid for by other corporate executives.",
            pro_quote: "Remember that we do not want our sons and daughters to live in this cursed hell. We will fight for their sake.---Dori Iodocus, CEO",
            anti_quote: "It is cliche to point out that the Vanguard leadership lives in skyscrapers and mansions while their employees are dirt-poor, expendable cannon fooder. But at least the Vanguard leadership recognizes the irony and pretends to cry about it.---Argyros Naevius, former journalist",
            favorite_policy: "E-Democracy",
            industries: "Corporate Espionage, Military",
            alignment: "left"
          },
          {
            id: 3,
            title: 'Centaurs Incorporated',
            description: "Humans who have decided to 'upgrade' themselves by merging with their machines, turning into a weird hybrid of 'artifical intelligence' and 'natural intelligence'. They are the workforce that are responsible for manufacturing most of the goods that the other corporations repackage and sell to other people. They are strong advocates for uplifting other people to the 'next stage of human evolution', and will happily kidnap and brainwash those who refuses upliftment.",
            pro_quote: "I am unable to see why if AI becomes effective and productive it would result in anything other than an age of practical abundance.--friendsie, Vice-President of Marketing",
            anti_quote: "In the past, we humans used technology. Now, technology uses us, and is using us for some greater, unfathomable purpose.---Yamato Izz al-Din, former Centaur employee",
            favorite_policy: "Basic Income",
            industries: "Industrial Automation, Research and Development"
            alignment: "libertarian"
          },
          {
            id: 4,
            title: "Baudrillard Associates",
            description: "An alliance of rogue financial traders and bankers who had given up pretending to comply with arbitrary government regulations and appeasing corrupt financial regulators. The white collar crime may be boring, but the pay is more than worth it. Currently the most popular corporation in the city, due to their reluctance to use violence to settle disputes.",
            industries: "Financial Services, Investment Banking, Accounting",
            anti_quote: "There is no evidence that the Baudrillard Associates even *exists*. Either the leadership has hidden themselves very well, or these bankers invented up the organization just to give themselves an excuse to do what they always wanted to do.---Tadeo Waldobert, Police Officer",
            pro_quote: "When the government treats the law as a pliable instrument to be used creatively, it tends to encourage citizens to treat it the same way. ... [The corporations] treated the law as a game to be played, a puzzle to be solved as aggressively as possible, rather than a moral obligation. THE JUSTICE DEPARTMENT DOES TOO.---Matt Levine, Senior Vice President of Public Relations",
            favorite_policy: "Deregulation",
            alignment: "libertarian"
          },
          {
            id: 5,
            title: "PAGAD",
            description: "The 'People Against Gangsterism and Drugs' movement had its roots in the chaotic violence in 1990s South Africa. It has since spread throughout the world as an anti-globalization political force. Members of PAGAD use car bombings, intimidation, and extortion in its eternal crusade against corporate crime, in the hopes of bringing sanity to an often insane world. Despite its supposedly secular nature, PAGAD has attracted its fair share of religious zealots.",
            industries: "Security & Investigations, Law Enforcement",
            favorite_policy: "Vigilante Legalization",
            anti_quote: "They believe they can go against the law if it means ridding the area of a drug dealer or gangster. How are they any better than the criminals when they resort to criminal tactics?---John Davids, South African Civilian",
            pro_quote: "If you do not mobilise yourselves, no one will do it for you. Drugs and gangsterism is destroying our society and everyone is affected.---Haroun Orrie, PAGAD spokesperson",
            alignment: "rightist"
          },
          {
            id: 6,
            title: "Room 39",
            description: "A criminal organization that was founded in the late 1970s with explicit purpose of securing funding for the North Korean dictatorship, through the use of criminal activities such as drug smuggling and weapons trafficking.  After the fall of the North Korean dictatorship, Room 39 went 'legit' in return for legal immunity for its previous crimes. Room 39 is slowly and gradually adjusting to the capitalist system.",
            pro_quote: "Ideologies are like clothing; when one is worn out, it's time to buy a new one.---Ji-Hun Yeong-Ho, Room 39 agent",
            anti_quote: "It's a mockery of our laws that a criminal gang is able to freely reinvent themselves as a honorable corporation. And they probably haven't given up on the crime yet.---Argyros Naevius, former journalist",
            favorite_policy: "Slush Fund",
            industries: "Pharmaceuticals, Weapon Production",
            alignment: "rightist"
          },
          {
            id: 7,
            title: "Singularity LLC",
            description: "Radical political activists who (after being repeatedly disappointed at the failure of human politicans and regulators to solve problems) are attempting to build an Artifical General Intelligence that will control human society. They sometimes rent their experiments as 'consultants' to the other corporations to help raise revenue.",
            pro_quote: "People are superstitios [sic] about self-modifying code because once you employ this for solving usual engineering problems, you will often find it to be difficult to trace down the reasons for your program's behavior and that the ability of a program to modify itself can be exploited to gain access / information by people / other programs they not allowed to have. However, if these aren't problematic, then any Lisp or Prolog is a safe bet. Something that speaks to broader audience: Python, JavaScript, Lua.---wvxvw, Singularity LLC employee",
            anti_quote: "Humans *don't* agree on how to run our society! Why should we trust a computer to know any better?---Bassam Petru, lawyer",
            favorite_policy: "Algorithmic Law",
            industries: "Consulting, Life Coaching",
            alignment: "libertarian"
          },
          {
            id: 8,
            title: "VHEMT",
            description: "A radical environmentalist organization founded in the early 1990s by Les U. Knight, VHEMT stands for the 'Voluntary Human Extiniction Movement'. As society has grown more dystopian, many people have began supporting VHEMT as the best way to increase global  welfare, declaring that the death of humanity is the only sensible choice in a insensible world.",
            pro_quote: "Q: Is this another one of those suicide cults? A: Seems as if our entire industralized civilization is one big suicide cult. ... [V]oluntary human extiniction offers a healthy cure to humanity's collective death wish.---VHEMT Q&A"
            anti_quote: "The logic is as absurd as it's unassailable. Yes, indeed, if there are no more children, there will be no more child tragedies. Or child triumphs, for that matter, or much reason to think childless humanity will spend its dying days as serenely as Knight predicts. ---Brian Bethune, journalist"
            industries: "Environmental Services",
            alignment: "left"
          },
          {
            id: 9,
            title: "Liberal Crime Squad"
            description: "A leftist terrorist group that previously wanted to establish an 'Elite Liberal Utopia'. The leadership soon realized that it would be far easier to plug people into a 'simulation' of an Elite Liberal utopia instead. They now adopt a policy of utter hedonism, and only leave the VR sims to raise funds and preach their agenda to the masses.",
            pro_quote: "Only by abandoning 'Conservative Reality' can humanity be awakened to its True Liberal Nature and be able to enjoy happy, productive lives.---Chris Horsa, Liberal Crime Squad Founder",
            anti_quote: "The LCS agents sleep soundly in their virtual pods, and dream of fighting their war against Conservative society. But I notice that they never really dream what happens after they win.---Leobwin Sansone, former LCS employee",
            industries: "Virtual Reality",
            alignment: "left"
          },
          {
            id: 10,
            title: "Daemon Hunters",
            description: "Wackos and conspiracy theorists who believe that they are living in a computer simulation ('MMO') controlled by cruel daemons ('players'). These daemons regularly pay 'subscription fees' for the chance to beat up and cruelly torture 'NPCs' (us). The Demon Hunters seek to purge the daemonic element from human society, but have a hard time distingushing between the NPCs and the daemons.",
            pro_quote: "Friend or foe? Paranoia imperative. Galaxy purely casual, individualism is a statistical anomaly - Nada is an error. Trust Nada? Trust you?---Priest Entity Nada, CTO of Daemon Hunters",
            anti_quote: "If I was a daemon, the first thing I'd do is to create a faction to grief other daemons. Read between the lines.---Argyros Naevius, former journalist",
            alignment: "right",
            industries: "Space Exploration"
          }
        ]
  }
  })
// Other Corps To Add?

// Uber/On-Demand Startups?
// Conservative Crime Squad?
// Social Media?
// "Weyland Corps" could be an interesting addition, and it would introduce the standard 'evil corp' back into the picture, since most of the corps here seem to make more sense as rebellious scum than as multitrillion-dollar megacorps. (Weyland appears to be a pro-"human supremacy" organization that does care for the environment and believe mankind to be like gods.) The biggest hurdle for Weyland Corps is two-folds
// One...the existence of the Daemon Hunters already mean you have a faction dedicated to interacting with 'extraterrestial entities' (the Demons), although the Daemon Hunters 'officially' wants to purge demons, not use them as weaponry.
// Two...the Weyland Corps' techno-utopianism is already reflected in Cenaturs Incorporated and Singularility LLC, and actually made more explicit. Their environmentalism is radicalized in the form of VHEMT. In the dystopian world of The Regulator, the Weylands are just too...conventional. Too boring.

// Peter Weyland's speech: http://lybio.net/peter-weylands-2023-ted-talk/people/
// Even though Peter believed mankind to be god, in the movie Prometheus, he had to beg to the Creators themselves...gods who are theorized to have made mankind solely as breeding vessels for the greatest biological weapons ever...the Xenomorphs

// Possible 'Enemy Faction' To Include If Tyranny is too High
// If so, provide hints that the HFSE exist in the Lore before launching them
// I like this faction but it appears to be a non-violent version of PAGAD,
// so it can't really be used
// {
//   id: 11,
//   title: "Human Flesh Search Engine",
//   description: "Established in the early 21st century as a loose-knit collection of Chinese vigilantes seeking to punish corruption and immorality through public shaming and doxxing, it has since absorbed other crowd-sourced intelligence gathering entities to become a major international force. The HFSE uses harrassment and death threats to push the vague and shifting views of the Internet mob, and tends to target both the strong and the weak fairly equally.",
//   pro_quote: "Righteousness is one of the five virtues in the Confucian tradition. With the convenience of the internet, and in the case of non-responsive law, the righteous people took matters into their own hands.---Xujun Eberlein, Chinese-American writer",
//   anti_quote: "The human-flesh search has unimaginable power. First it was a lot of phone calls every day. Then people painted red characters on his parents’ froxnt door, which said things like, ‘You caused your wife’s suicide, so you should pay.’---Zhang Yanfeng, lawyer representing Wang Fei, a husband accused of cheating on his wife. Wang Fei went into hiding to evade the HFSE",
//   alignment: "right?"
// }

// The HFSE is a place that you can periodically monitor to check people's opinions about you. If you engage in too much tyranny, the HFSE will turn against you, and you will go against their wrath (which includes threatening attacks as well as stronger Corporations.)
// When you start the game, you log onto the HFSE to get your job.<|endoftext|>


<commit_before>
app.controller('createprojgrpCtrl',['$scope','$location','$routeSegment','$http', '$timeout','$sessionStorage', function($scope,$location,$routeSegment,$http, $timeout,$sessionStorage) {
	$scope.sessionToken = $sessionStorage.sessionToken;
	if($sessionStorage.isLoggedIn){
		$("#userDetails").html($sessionStorage.account.emailAddress);
	}

	Service.GetProjectList($http,
    //success
    function(data){$scope.projects =data;  }),

  $scope.submitForm = function() {

       Service.createProjectGroup($http,$scope,
    //success
    function(data){

		$scope.successTextAlert = "Your request has been sent successfully.";
		$scope.showSuccessAlert = true;
		$scope.form.name='';
		$scope.form.desc='';

},
	//error
	function(){$scope.errorTextAlert = "Error, Something gone wrong.";
$scope.showErrorAlert = true;})

    };
	// switch flag
$scope.switchBool = function(value) {
   $scope[value] = !$scope[value];
};
}]);
<commit_msg>Fix project group creation error<commit_after>
app.controller('createprojgrpCtrl',['$scope','$location','$routeSegment','$http', '$timeout','$sessionStorage', function($scope,$location,$routeSegment,$http, $timeout,$sessionStorage) {
	$scope.sessionToken = $sessionStorage.sessionToken;
	if($sessionStorage.isLoggedIn){
		$("#userDetails").html($sessionStorage.account.emailAddress);
	}

	Service.GetProjectList($http,
    //success
    function(data){$scope.projects =data;  }, function(error) {}, $scope),

  $scope.submitForm = function() {

       Service.createProjectGroup($http,$scope,
    //success
    function(data){

		$scope.successTextAlert = "Your request has been sent successfully.";
		$scope.showSuccessAlert = true;
		$scope.form.name='';
		$scope.form.desc='';

},
	//error
	function(){$scope.errorTextAlert = "Error, Something gone wrong.";
$scope.showErrorAlert = true;})

    };
	// switch flag
$scope.switchBool = function(value) {
   $scope[value] = !$scope[value];
};
}]);
<|endoftext|>


<commit_before>// Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

"use strict";

const os = require('os');
const assert = require('assert');
const http = require('http');
const https = require('https');
const url = require('url');
const debug = require('debug')('sotrade:server');
const api = require('./api.js');
const qctx = require('./qctx.js');
const promiseUtil = require('./lib/promise-util.js');

/**
 * Provides the HTTP endpoint for all client connections
 *
 * @property {object} httpServer  The associated node.js HTTP(S) server
 * @property {module:connectiondata~ConnectionData[]} clients  Full list of currently
 *                                                             active clients
 * @property {boolean} isShuttingDown  Indicates whether the serve is in shut-down mode
 * @property {int} creationTime  Unix timestamp of the object creation
 * @property {int} deadQueryCount  Total number of queries of disconnected clients
 * @property {int} connectionCount  Total number of client connections
 *
 * @public
 */
class SoTradeServer extends api.Component {
  constructor(info, requestables) {
    super({
      anonymous: true,
      description: 'Provides the HTTP endpoint for all client connections',
      depends: ['Database', 'ReadonlyStore']
    });

    this.httpServer = null;
    this.clients = [];
    this.isShuttingDown = false;
    this.creationTime = Date.now() / 1000;

    this.deadQueryCount = 0;

    this.connectionCount = 0;
    this.info = info || {};
    this.requestables = requestables;

    this.apiv1Index = JSON.stringify({
      code: 200,
      name: 'API v1 index',
      data: {
        listing: this.requestables.map(rq => {
          return {
            info: Object.assign({}, rq.options, {
              depends: undefined,
              writing: undefined,
              transactional: undefined
            })
          };
        })
      }
    });
  }

  internalServerStatistics(qctxDebug) {
    if (typeof gc === 'function') {
      gc(); // perform garbage collection, if available (e.g. via the v8 --expose-gc option)
    }

    return {
      pid: process.pid,
      hostname: os.hostname(),
      isBackgroundWorker: this.info.isBackgroundWorker,
      creationTime: this.creationTime,
      clients: this.clients.map(x => x.stats()),
      bus: this.bus.stats(),
      msgCount: this.msgCount,
      msgLZMACount: this.msgLZMACount,
      connectionCount: this.connectionCount,
      deadQueryCount: this.deadQueryCount,
      now: Date.now(),
      qcontexts: qctxDebug ? qctx.QContext.getMasterQueryContext().getStatistics(true) : null,
      readonly: this.load('ReadonlyStore').readonly,
      dbstats: this.load('Database').usageStatistics()
    };
  }

  /**
   * Set up the server for listening on HTTP
   *
   * @param {int} port  The port for this server to listen on
   */
  start(port) {
    assert.ok(port);
    debug('Start listening', port);

    const cfg = this.load('Config').config();

    if (cfg.protocol === 'https') {
      this.httpServer = https.createServer(cfg.http);
    } else {
      this.httpServer = http.createServer();
    }

    this.httpServer.on('request', (req, res) => this.handleHTTPRequest(req, res));

    return this.listen(port, cfg.wshost);
  }

  /**
   * Set up the server for listening
   *
   * @param {int} port  The port for this server to listen on
   * @param {string} host  The host to listen on
   *
   * @return {object}  A Promise fulfilled when the server is fully available
   */
  listen(port, host) {
    assert.ok(port);

    const deferred = Promise.defer();

    let listenSuccess = false;

    const listenHandler = () => {
      this.httpServer.on('error', e => this.load('PubSub').emit('error', e));

      listenSuccess = true;
      deferred.resolve();
    };

    this.httpServer.once('error', e => {
      if (listenSuccess) { // only handle pre-listen errors
        return;
      }

      this.httpServer.removeListener('listening', listenHandler);

      if (e.code !== 'EADDRINUSE') {
        return deferred.reject(e);
      }

      console.log(process.pid, 'has address in use on', port, host);
      deferred.resolve(promiseUtil.delay(500).then(() => {
        try {
          this.httpServer.close();
        } catch(e2) {
          console.warn(e2);
        }

        return this.listen(port, host);
      }));
    });

    this.httpServer.addListener('listening', listenHandler);

    process.nextTick(() => {
      debug('listening', process.pid, 'port ' + port, 'host ' + host);
      this.httpServer.listen(port, host);
    });

    return deferred.promise;
  }

  /**
   * Handles a single HTTP request in the format of standard
   * Node.js HTTP handlers.
   */
  handleHTTPRequest(req, res) {
    const defaultHeaders = {
      'Cache-Control': 'private, max-age=0, no-cache',
      'Content-Type': 'application/json; charset=utf-8'
    };

    if (req.headers['origin']) {
      Object.assign(defaultHeaders, {
        'Access-Control-Allow-Origin': req.headers['origin'],
        'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Authorization,X-Sotrade-Auth,Accept-Encoding,If-Modified-Since'
      });
    }

    debug('HTTP Request', req.method, req.url);

    const parsedURI = url.parse(req.url, true);

    if (parsedURI.pathname.match(/^\/dynamic\/files\//)) {
      // backwards compability
      parsedURI.pathname = '/api/v1' + parsedURI.pathname;
    }

    let allowedMethods = [];

    let handler = null;

    if (parsedURI.pathname.match(/^\/api\/v1/)) {
      parsedURI.pathname = parsedURI.pathname.replace(/^\/api\/v1/, '');

      if (parsedURI.pathname === '/index' || parsedURI.pathname === '/') {
        res.writeHead(200, {'Content-Type': 'application/json;charset=utf-8'});
        res.end(this.apiv1Index);
      }

      for (let rq of this.requestables) {
        if (rq.handledMethods().concat(['OPTIONS']).indexOf(req.method) === -1) {
          continue;
        }

        const uriMatch = rq.getURLMatcher().match(parsedURI.pathname);
        if (!uriMatch) {
          continue;
        }

        handler = () => rq.handleRequest(req, res, uriMatch, parsedURI, defaultHeaders); // jshint ignore:line
        allowedMethods = allowedMethods.concat(rq.handledMethods());
      }
    }

    defaultHeaders['Allow'] = allowedMethods.join(',').toUpperCase();
    defaultHeaders['Access-Control-Allow-Methods'] = allowedMethods.join(',').toUpperCase();

    if (handler !== null) {
      if (req.method !== 'OPTIONS') {
        handler();
      } else {
        defaultHeaders['Content-Type'] = 'text/plain;charset=utf-8';
        res.writeHead(200, defaultHeaders);
        res.end();
      }
    } else {
      debug('No handler for URI', parsedURI.pathname);
      res.writeHead(404, {'Content-Type': 'application/json;charset=utf-8'});
      res.end(JSON.stringify({
        code: 404,
        identifier: 'unknown-uri'
      }));
    }
  }
}

exports.Server = SoTradeServer;
<commit_msg>Move API self-documentation to /api-index<commit_after>// Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

"use strict";

const os = require('os');
const assert = require('assert');
const http = require('http');
const https = require('https');
const url = require('url');
const debug = require('debug')('sotrade:server');
const api = require('./api.js');
const qctx = require('./qctx.js');
const promiseUtil = require('./lib/promise-util.js');

/**
 * Provides the HTTP endpoint for all client connections
 *
 * @property {object} httpServer  The associated node.js HTTP(S) server
 * @property {module:connectiondata~ConnectionData[]} clients  Full list of currently
 *                                                             active clients
 * @property {boolean} isShuttingDown  Indicates whether the serve is in shut-down mode
 * @property {int} creationTime  Unix timestamp of the object creation
 * @property {int} deadQueryCount  Total number of queries of disconnected clients
 * @property {int} connectionCount  Total number of client connections
 *
 * @public
 */
class SoTradeServer extends api.Component {
  constructor(info, requestables) {
    super({
      anonymous: true,
      description: 'Provides the HTTP endpoint for all client connections',
      depends: ['Database', 'ReadonlyStore']
    });

    this.httpServer = null;
    this.clients = [];
    this.isShuttingDown = false;
    this.creationTime = Date.now() / 1000;

    this.deadQueryCount = 0;

    this.connectionCount = 0;
    this.info = info || {};
    this.requestables = requestables;

    this.apiv1Index = JSON.stringify({
      code: 200,
      name: 'API v1 index',
      data: {
        listing: this.requestables.map(rq => {
          return {
            info: Object.assign({}, rq.options, {
              depends: undefined,
              writing: undefined,
              transactional: undefined
            })
          };
        })
      }
    });
  }

  internalServerStatistics(qctxDebug) {
    if (typeof gc === 'function') {
      gc(); // perform garbage collection, if available (e.g. via the v8 --expose-gc option)
    }

    return {
      pid: process.pid,
      hostname: os.hostname(),
      isBackgroundWorker: this.info.isBackgroundWorker,
      creationTime: this.creationTime,
      clients: this.clients.map(x => x.stats()),
      bus: this.bus.stats(),
      msgCount: this.msgCount,
      msgLZMACount: this.msgLZMACount,
      connectionCount: this.connectionCount,
      deadQueryCount: this.deadQueryCount,
      now: Date.now(),
      qcontexts: qctxDebug ? qctx.QContext.getMasterQueryContext().getStatistics(true) : null,
      readonly: this.load('ReadonlyStore').readonly,
      dbstats: this.load('Database').usageStatistics()
    };
  }

  /**
   * Set up the server for listening on HTTP
   *
   * @param {int} port  The port for this server to listen on
   */
  start(port) {
    assert.ok(port);
    debug('Start listening', port);

    const cfg = this.load('Config').config();

    if (cfg.protocol === 'https') {
      this.httpServer = https.createServer(cfg.http);
    } else {
      this.httpServer = http.createServer();
    }

    this.httpServer.on('request', (req, res) => this.handleHTTPRequest(req, res));

    return this.listen(port, cfg.wshost);
  }

  /**
   * Set up the server for listening
   *
   * @param {int} port  The port for this server to listen on
   * @param {string} host  The host to listen on
   *
   * @return {object}  A Promise fulfilled when the server is fully available
   */
  listen(port, host) {
    assert.ok(port);

    const deferred = Promise.defer();

    let listenSuccess = false;

    const listenHandler = () => {
      this.httpServer.on('error', e => this.load('PubSub').emit('error', e));

      listenSuccess = true;
      deferred.resolve();
    };

    this.httpServer.once('error', e => {
      if (listenSuccess) { // only handle pre-listen errors
        return;
      }

      this.httpServer.removeListener('listening', listenHandler);

      if (e.code !== 'EADDRINUSE') {
        return deferred.reject(e);
      }

      console.log(process.pid, 'has address in use on', port, host);
      deferred.resolve(promiseUtil.delay(500).then(() => {
        try {
          this.httpServer.close();
        } catch(e2) {
          console.warn(e2);
        }

        return this.listen(port, host);
      }));
    });

    this.httpServer.addListener('listening', listenHandler);

    process.nextTick(() => {
      debug('listening', process.pid, 'port ' + port, 'host ' + host);
      this.httpServer.listen(port, host);
    });

    return deferred.promise;
  }

  /**
   * Handles a single HTTP request in the format of standard
   * Node.js HTTP handlers.
   */
  handleHTTPRequest(req, res) {
    const defaultHeaders = {
      'Cache-Control': 'private, max-age=0, no-cache',
      'Content-Type': 'application/json; charset=utf-8'
    };

    if (req.headers['origin']) {
      Object.assign(defaultHeaders, {
        'Access-Control-Allow-Origin': req.headers['origin'],
        'Access-Control-Allow-Headers': 'Content-Type,Authorization,X-Authorization,X-Sotrade-Auth,Accept-Encoding,If-Modified-Since'
      });
    }

    debug('HTTP Request', req.method, req.url);

    const parsedURI = url.parse(req.url, true);

    if (parsedURI.pathname.match(/^\/dynamic\/files\//)) {
      // backwards compability
      parsedURI.pathname = '/api/v1' + parsedURI.pathname;
    }

    let allowedMethods = [];

    let handler = null;

    if (parsedURI.pathname.match(/^\/api\/v1/)) {
      parsedURI.pathname = parsedURI.pathname.replace(/^\/api\/v1/, '');

      if (parsedURI.pathname === '/api-index' || parsedURI.pathname === '/') {
        res.writeHead(200, defaultHeaders);
        res.end(this.apiv1Index);
      }

      for (let rq of this.requestables) {
        if (rq.handledMethods().concat(['OPTIONS']).indexOf(req.method) === -1) {
          continue;
        }

        const uriMatch = rq.getURLMatcher().match(parsedURI.pathname);
        if (!uriMatch) {
          continue;
        }

        handler = () => rq.handleRequest(req, res, uriMatch, parsedURI, defaultHeaders); // jshint ignore:line
        allowedMethods = allowedMethods.concat(rq.handledMethods());
      }
    }

    defaultHeaders['Allow'] = allowedMethods.join(',').toUpperCase();
    defaultHeaders['Access-Control-Allow-Methods'] = allowedMethods.join(',').toUpperCase();

    if (handler !== null) {
      if (req.method !== 'OPTIONS') {
        handler();
      } else {
        defaultHeaders['Content-Type'] = 'text/plain;charset=utf-8';
        res.writeHead(200, defaultHeaders);
        res.end();
      }
    } else {
      debug('No handler for URI', parsedURI.pathname);
      res.writeHead(404, {'Content-Type': 'application/json;charset=utf-8'});
      res.end(JSON.stringify({
        code: 404,
        identifier: 'unknown-uri'
      }));
    }
  }
}

exports.Server = SoTradeServer;
<|endoftext|>


<commit_before>'use strict';

const index = require('config').get('elasticsearch.index');
const config = require('config').get('search');
const isNumber = require('./util/isNumber');

const fields = ['name', 'version', 'description', 'keywords', 'publisher', 'evaluation', 'score'];

class Search {
    constructor(client) {
        this.client = client;
    }

    get(value, from, size, effect, weights) {
        // Validation and defaults
        value = typeof value === 'string' ? value : '';
        from = isNumber(from) ? Number(from) : 0;
        size = isNumber(size) ? Number(size) : config.get('size');
        effect = isNumber(effect) ? Number(effect) : config.get('effect');

        weights = typeof weights === 'object' ? weights : {};
        weights = {
            quality: isNumber(weights.quality) ? Number(weights.quality) : config.get('weights.quality'),
            popularity: isNumber(weights.popularity) ? Number(weights.popularity) : config.get('weights.popularity'),
            maintenance: isNumber(weights.maintenance) ? Number(weights.maintenance) : config.get('weights.maintenance'),
        };

        // Search

        /* eslint camelcase: 0 */
        return this.client.search({
            index,
            body: {
                _source: fields,
                size,
                from,
                query: {
                    function_score: {
                        query: {
                            bool: {
                                should: [
                                    // Give boost to exact matches (phrase)
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english^4',
                                                'description.identifier_english',
                                                'keywords.identifier_english^2',
                                            ],
                                            analyzer: 'identifier',
                                            type: 'phrase',
                                            slop: 3,
                                            boost: 9,
                                        },
                                    },

                                    // Prefix exact matches
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_edge_ngram^4',
                                                'description.identifier_edge_ngram',
                                                'keywords.identifier_edge_ngram^2',
                                            ],
                                            analyzer: 'identifier',
                                            type: 'phrase',
                                            slop: 3,
                                            boost: 3,
                                        },
                                    },

                                    // Normal term match
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english_docs^4',
                                                'description.identifier_english_docs',
                                                'keywords.identifier_english_docs^2',
                                            ],
                                            type: 'cross_fields',
                                            boost: 3,
                                        },
                                    },

                                    // Normal term match with a more aggressive stemmer (not so important)
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english_aggressive_docs^4',
                                                'description.identifier_english_aggressive_docs',
                                                'keywords.identifier_english_aggressive_docs^2',
                                            ],
                                            type: 'cross_fields',
                                        },
                                    },
                                ],
                            },
                        },
                        script_score: {
                            lang: 'groovy',
                            script: 'pow(' +
                            'doc["score.detail.popularity"].value * weightPopularity + ' +
                            'doc["score.detail.quality"].value * weightQuality + ' +
                            'doc["score.detail.maintenance"].value * weightMaintenance, ' +
                            'effect)',
                            params: {
                                effect,
                                weightPopularity: weights.popularity,
                                weightQuality: weights.quality,
                                weightMaintenance: weights.maintenance,
                            },
                        },
                    },
                },
            },
        });
    }
}

module.exports = Search;
<commit_msg>Add date to fields.<commit_after>'use strict';

const index = require('config').get('elasticsearch.index');
const config = require('config').get('search');
const isNumber = require('./util/isNumber');

const fields = ['name', 'version', 'description', 'keywords', 'publisher', 'date', 'evaluation', 'score'];

class Search {
    constructor(client) {
        this.client = client;
    }

    get(value, from, size, effect, weights) {
        // Validation and defaults
        value = typeof value === 'string' ? value : '';
        from = isNumber(from) ? Number(from) : 0;
        size = isNumber(size) ? Number(size) : config.get('size');
        effect = isNumber(effect) ? Number(effect) : config.get('effect');

        weights = typeof weights === 'object' ? weights : {};
        weights = {
            quality: isNumber(weights.quality) ? Number(weights.quality) : config.get('weights.quality'),
            popularity: isNumber(weights.popularity) ? Number(weights.popularity) : config.get('weights.popularity'),
            maintenance: isNumber(weights.maintenance) ? Number(weights.maintenance) : config.get('weights.maintenance'),
        };

        // Search

        /* eslint camelcase: 0 */
        return this.client.search({
            index,
            body: {
                _source: fields,
                size,
                from,
                query: {
                    function_score: {
                        query: {
                            bool: {
                                should: [
                                    // Give boost to exact matches (phrase)
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english^4',
                                                'description.identifier_english',
                                                'keywords.identifier_english^2',
                                            ],
                                            analyzer: 'identifier',
                                            type: 'phrase',
                                            slop: 3,
                                            boost: 9,
                                        },
                                    },

                                    // Prefix exact matches
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_edge_ngram^4',
                                                'description.identifier_edge_ngram',
                                                'keywords.identifier_edge_ngram^2',
                                            ],
                                            analyzer: 'identifier',
                                            type: 'phrase',
                                            slop: 3,
                                            boost: 3,
                                        },
                                    },

                                    // Normal term match
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english_docs^4',
                                                'description.identifier_english_docs',
                                                'keywords.identifier_english_docs^2',
                                            ],
                                            type: 'cross_fields',
                                            boost: 3,
                                        },
                                    },

                                    // Normal term match with a more aggressive stemmer (not so important)
                                    {
                                        multi_match: {
                                            query: value,
                                            operator: 'and',
                                            fields: [
                                                'name.identifier_english_aggressive_docs^4',
                                                'description.identifier_english_aggressive_docs',
                                                'keywords.identifier_english_aggressive_docs^2',
                                            ],
                                            type: 'cross_fields',
                                        },
                                    },
                                ],
                            },
                        },
                        script_score: {
                            lang: 'groovy',
                            script: 'pow(' +
                            'doc["score.detail.popularity"].value * weightPopularity + ' +
                            'doc["score.detail.quality"].value * weightQuality + ' +
                            'doc["score.detail.maintenance"].value * weightMaintenance, ' +
                            'effect)',
                            params: {
                                effect,
                                weightPopularity: weights.popularity,
                                weightQuality: weights.quality,
                                weightMaintenance: weights.maintenance,
                            },
                        },
                    },
                },
            },
        });
    }
}

module.exports = Search;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @providesModule writeRelayGeneratedFile
 * @flow
 * @format
 */

'use strict';

const crypto = require('crypto');
const invariant = require('invariant');
// TODO T21875029 ../../relay-runtime/util/prettyStringify
const prettyStringify = require('prettyStringify');

import type {CodegenDirectory} from '../graphql-compiler/GraphQLCompilerPublic';
// TODO T21875029 ../../relay-runtime/util/RelayConcreteNode
import type {GeneratedNode} from 'RelayConcreteNode';

/**
 * Generate a module for the given document name/text.
 */
export type FormatModule = ({|
  moduleName: string,
  documentType: 'ConcreteBatch' | 'ConcreteFragment',
  docText: ?string,
  concreteText: string,
  flowText: ?string,
  hash: ?string,
  devTextGenerator: (objectName: string) => string,
  relayRuntimeModule: string,
|}) => string;

async function writeRelayGeneratedFile(
  codegenDir: CodegenDirectory,
  generatedNode: GeneratedNode,
  formatModule: FormatModule,
  flowText: ?string,
  persistQuery: ?(text: string) => Promise<string>,
  platform: ?string,
  relayRuntimeModule: string,
): Promise<?GeneratedNode> {
  const moduleName = generatedNode.name + '.graphql';
  const platformName = platform ? moduleName + '.' + platform : moduleName;
  const filename = platformName + '.js';
  const flowTypeName =
    generatedNode.kind === 'Batch' ? 'ConcreteBatch' : 'ConcreteFragment';
  const devOnlyProperties = {};

  let text = null;
  let hash = null;
  if (generatedNode.kind === 'Batch') {
    text = generatedNode.text;
    invariant(
      text,
      'codegen-runner: Expected query to have text before persisting.',
    );
    const oldContent = codegenDir.read(filename);
    // Hash the concrete node including the query text.
    const hasher = crypto.createHash('md5');
    hasher.update('cache-breaker-2');
    hasher.update(JSON.stringify(generatedNode));
    if (flowText) {
      hasher.update(flowText);
    }
    if (persistQuery) {
      hasher.update('persisted');
    }
    hash = hasher.digest('hex');
    if (hash === extractHash(oldContent)) {
      codegenDir.markUnchanged(filename);
      return null;
    }
    if (codegenDir.onlyValidate) {
      codegenDir.markUpdated(filename);
      return null;
    }
    if (persistQuery) {
      generatedNode = {
        ...generatedNode,
        text: null,
        id: await persistQuery(text),
      };

      devOnlyProperties.text = text;
    }
  }

  const moduleText = formatModule({
    moduleName,
    documentType: flowTypeName,
    docText: text,
    flowText,
    hash: hash ? `@relayHash ${hash}` : null,
    concreteText: prettyStringify(generatedNode),
    devTextGenerator: makeDevTextGenerator(devOnlyProperties),
    relayRuntimeModule,
  });

  codegenDir.writeFile(filename, moduleText);
  return generatedNode;
}

function makeDevTextGenerator(devOnlyProperties: Object) {
  return objectName => {
    const assignments = Object.keys(devOnlyProperties).map(key => {
      const value = devOnlyProperties[key];
      const stringifiedValue =
        value === undefined ? 'undefined' : JSON.stringify(value);

      return `  ${objectName}['${key}'] = ${stringifiedValue};`;
    });

    if (!assignments.length) {
      return '';
    }

    return `

if (__DEV__) {
${assignments.join('\n')}
}
`;
  };
}

function extractHash(text: ?string): ?string {
  if (!text) {
    return null;
  }
  if (/<<<<<|>>>>>/.test(text)) {
    // looks like a merge conflict
    return null;
  }
  const match = text.match(/@relayHash (\w{32})\b/m);
  return match && match[1];
}

module.exports = writeRelayGeneratedFile;
<commit_msg>dedupe JSON in generated files<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @providesModule writeRelayGeneratedFile
 * @flow
 * @format
 */

'use strict';

const crypto = require('crypto');
const dedupeJSONStringify = require('dedupeJSONStringify');
const invariant = require('invariant');

import type {CodegenDirectory} from '../graphql-compiler/GraphQLCompilerPublic';
// TODO T21875029 ../../relay-runtime/util/RelayConcreteNode
import type {GeneratedNode} from 'RelayConcreteNode';

/**
 * Generate a module for the given document name/text.
 */
export type FormatModule = ({|
  moduleName: string,
  documentType: 'ConcreteBatch' | 'ConcreteFragment',
  docText: ?string,
  concreteText: string,
  flowText: ?string,
  hash: ?string,
  devTextGenerator: (objectName: string) => string,
  relayRuntimeModule: string,
|}) => string;

async function writeRelayGeneratedFile(
  codegenDir: CodegenDirectory,
  generatedNode: GeneratedNode,
  formatModule: FormatModule,
  flowText: ?string,
  persistQuery: ?(text: string) => Promise<string>,
  platform: ?string,
  relayRuntimeModule: string,
): Promise<?GeneratedNode> {
  const moduleName = generatedNode.name + '.graphql';
  const platformName = platform ? moduleName + '.' + platform : moduleName;
  const filename = platformName + '.js';
  const flowTypeName =
    generatedNode.kind === 'Batch' ? 'ConcreteBatch' : 'ConcreteFragment';
  const devOnlyProperties = {};

  let text = null;
  let hash = null;
  if (generatedNode.kind === 'Batch') {
    text = generatedNode.text;
    invariant(
      text,
      'codegen-runner: Expected query to have text before persisting.',
    );
    const oldContent = codegenDir.read(filename);
    // Hash the concrete node including the query text.
    const hasher = crypto.createHash('md5');
    hasher.update('cache-breaker-3');
    hasher.update(JSON.stringify(generatedNode));
    if (flowText) {
      hasher.update(flowText);
    }
    if (persistQuery) {
      hasher.update('persisted');
    }
    hash = hasher.digest('hex');
    if (hash === extractHash(oldContent)) {
      codegenDir.markUnchanged(filename);
      return null;
    }
    if (codegenDir.onlyValidate) {
      codegenDir.markUpdated(filename);
      return null;
    }
    if (persistQuery) {
      generatedNode = {
        ...generatedNode,
        text: null,
        id: await persistQuery(text),
      };

      devOnlyProperties.text = text;
    }
  }

  const moduleText = formatModule({
    moduleName,
    documentType: flowTypeName,
    docText: text,
    flowText,
    hash: hash ? `@relayHash ${hash}` : null,
    concreteText: dedupeJSONStringify(generatedNode),
    devTextGenerator: makeDevTextGenerator(devOnlyProperties),
    relayRuntimeModule,
  });

  codegenDir.writeFile(filename, moduleText);
  return generatedNode;
}

function makeDevTextGenerator(devOnlyProperties: Object) {
  return objectName => {
    const assignments = Object.keys(devOnlyProperties).map(key => {
      const value = devOnlyProperties[key];
      const stringifiedValue =
        value === undefined ? 'undefined' : JSON.stringify(value);

      return `  ${objectName}['${key}'] = ${stringifiedValue};`;
    });

    if (!assignments.length) {
      return '';
    }

    return `

if (__DEV__) {
${assignments.join('\n')}
}
`;
  };
}

function extractHash(text: ?string): ?string {
  if (!text) {
    return null;
  }
  if (/<<<<<|>>>>>/.test(text)) {
    // looks like a merge conflict
    return null;
  }
  const match = text.match(/@relayHash (\w{32})\b/m);
  return match && match[1];
}

module.exports = writeRelayGeneratedFile;
<|endoftext|>


<commit_before>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.scss',
      'app/styles/**/*.css',
      'app/styles/components/components.scss'
    ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.rubySass({
        style: 'expanded',
        precision: 10
      })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: 'dist'
    }

  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<commit_msg>Fix to new style-system not minifying output.<commit_after>/**
 *
 *  Web Starter Kit
 *  Copyright 2014 Google Inc. All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 *
 */

'use strict';

// Include Gulp & Tools We'll Use
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
var pagespeed = require('psi');
var reload = browserSync.reload;

var AUTOPREFIXER_BROWSERS = [
  'ie >= 10',
  'ie_mob >= 10',
  'ff >= 30',
  'chrome >= 34',
  'safari >= 7',
  'opera >= 23',
  'ios >= 7',
  'android >= 4.4',
  'bb >= 10'
];

// Lint JavaScript
gulp.task('jshint', function () {
  return gulp.src('app/scripts/**/*.js')
    .pipe(reload({stream: true, once: true}))
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

// Optimize Images
gulp.task('images', function () {
  return gulp.src('app/images/**/*')
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true
    })))
    .pipe(gulp.dest('dist/images'))
    .pipe($.size({title: 'images'}));
});

// Copy All Files At The Root Level (app)
gulp.task('copy', function () {
  return gulp.src([
    'app/*',
    '!app/*.html',
    'node_modules/apache-server-configs/dist/.htaccess'
  ], {
    dot: true
  }).pipe(gulp.dest('dist'))
    .pipe($.size({title: 'copy'}));
});

// Copy Web Fonts To Dist
gulp.task('fonts', function () {
  return gulp.src(['app/fonts/**'])
    .pipe(gulp.dest('dist/fonts'))
    .pipe($.size({title: 'fonts'}));
});

// Compile and Automatically Prefix Stylesheets
gulp.task('styles', function () {
  // For best performance, don't add Sass partials to `gulp.src`
  return gulp.src([
      'app/styles/*.scss',
      'app/styles/**/*.css',
      'app/styles/components/components.scss'
    ])
    .pipe($.changed('styles', {extension: '.scss'}))
    .pipe($.rubySass({
        style: 'expanded',
        precision: 10
      })
      .on('error', console.error.bind(console))
    )
    .pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
    .pipe(gulp.dest('.tmp/styles'))
    // Concatenate And Minify Styles
    .pipe($.if('*.css', $.csso()))
    .pipe(gulp.dest('dist/styles'))
    .pipe($.size({title: 'styles'}));
});

// Scan Your HTML For Assets & Optimize Them
gulp.task('html', function () {
  var assets = $.useref.assets({searchPath: '{.tmp,app}'});

  return gulp.src('app/**/*.html')
    .pipe(assets)
    // Concatenate And Minify JavaScript
    .pipe($.if('*.js', $.uglify({preserveComments: 'some'})))
    // Remove Any Unused CSS
    // Note: If not using the Style Guide, you can delete it from
    // the next line to only include styles your project uses.
    .pipe($.if('*.css', $.uncss({
      html: [
        'app/index.html',
        'app/styleguide.html'
      ],
      // CSS Selectors for UnCSS to ignore
      ignore: [
        /.navdrawer-container.open/,
        /.app-bar.open/
      ]
    })))
    // Concatenate And Minify Styles
    // In case you are still using useref build blocks
    .pipe($.if('*.css', $.csso()))
    .pipe(assets.restore())
    .pipe($.useref())
    // Update Production Style Guide Paths
    .pipe($.replace('components/components.css', 'components/main.min.css'))
    // Minify Any HTML
    .pipe($.if('*.html', $.minifyHtml()))
    // Output Files
    .pipe(gulp.dest('dist'))
    .pipe($.size({title: 'html'}));
});

// Clean Output Directory
gulp.task('clean', del.bind(null, ['.tmp', 'dist']));

// Watch Files For Changes & Reload
gulp.task('serve', ['styles'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: ['.tmp', 'app']
    }
  });

  gulp.watch(['app/**/*.html'], reload);
  gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
  gulp.watch(['app/scripts/**/*.js'], ['jshint']);
  gulp.watch(['app/images/**/*'], reload);
});

// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], function () {
  browserSync({
    notify: false,
    // Run as an https by uncommenting 'https: true'
    // Note: this uses an unsigned certificate which on first access
    //       will present a certificate warning in the browser.
    // https: true,
    server: {
      baseDir: 'dist'
    }

  });
});

// Build Production Files, the Default Task
gulp.task('default', ['clean'], function (cb) {
  runSequence('styles', ['jshint', 'html', 'images', 'fonts', 'copy'], cb);
});

// Run PageSpeed Insights
// Update `url` below to the public URL for your site
gulp.task('pagespeed', pagespeed.bind(null, {
  // By default, we use the PageSpeed Insights
  // free (no API key) tier. You can use a Google
  // Developer API key if you have one. See
  // http://goo.gl/RkN0vE for info key: 'YOUR_API_KEY'
  url: 'https://example.com',
  strategy: 'mobile'
}));

// Load custom tasks from the `tasks` directory
try { require('require-dir')('tasks'); } catch (err) {}
<|endoftext|>


<commit_before>'use strict';
var Hapi = require('hapi');
var server = new Hapi.Server();
if( process.env.PORT ) {
  server.connection({ port: process.env.PORT });
}
else {
  server.connection({ port: 1337 });
}

// add a route
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!');
    }
});

server.route({
    method: 'GET',
    path: '/{name}',
    handler: function (request, reply) {
        reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
    }
});

// start the server
server.start(function () {
  console.log('Server running at:', server.info.uri);
});<commit_msg>Add logging to server.js'<commit_after>'use strict';
var GoodWinston = require('good-winston');
var winston = require('winston');
var Hapi = require('hapi');

// add winston logging
server.register({
register: require('good'),
  options: {
    reporters: [
      new GoodWinston({
        ops: '*',
        request: '*',
        response: '*',
        log: '*',
        error: '*'
      }, winston)
    ]
  }
}, function(err) {
  if(err) {
    return server.log(['error'],'good load error: ' + err);
  }
});

var server = new Hapi.Server();
if( process.env.PORT ) {
  server.connection({ port: process.env.PORT });
}
else {
  server.connection({ port: 1337 });
}

// add a route
server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply('Hello, world!');
    }
});

server.route({
    method: 'GET',
    path: '/{name}',
    handler: function (request, reply) {
        reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
    }
});

// start the server
server.start(function () {
  console.log('Server running at:', server.info.uri);
});<|endoftext|>


<commit_before>$(document).ready(function () {
  (function ($) {
    var template = $('#search-result-template').html(),
        resultTemplate = Handlebars.compile(template);

    var query = $('#search input[name="q"]').val();
    if (query !== '') {
      _search(query);
    }

    function _search(query) {
      var resultsDiv = $('#search-results');
      _toggleSpinner(resultsDiv);

      $.getJSON("/api/2/search", {"q": query}, function (data) {
        var results = data.results;

        resultsDiv.html('');

        for (i in results) {
          resultsDiv.append(_prepareResult(results[i]));
        }

        resultsDiv.highlight(query);
        _toggleSpinner(resultsDiv);
      });
    }

    function _toggleSpinner(element) {
      element.toggleClass('spinner');
    }

    function _prepareResult(result) {
      result['values'] = _prepareDimensionsForHandlebars(result);
      result.amount = OpenSpending.Utils.formatAmountWithCommas(result.amount, 0, result.currency)
      return resultTemplate(result);
    };

    function _prepareDimensionsForHandlebars(result) {
      var dimensions = [];

      for (dimension in result) {
        var label = result[dimension].label;
        if (dimension !== "time" && dimension !== "dataset" && label) {
          dimensions.push({ key: dimension, value: label });
        }
      }

      return dimensions;
    };
  })(jQuery);
});

<commit_msg>Display message if no data could be found for query (#478)<commit_after>$(document).ready(function () {
  (function ($) {
    var template = $('#search-result-template').html(),
        resultTemplate = Handlebars.compile(template);

    var query = $('#search input[name="q"]').val();
    if (query !== '') {
      _search(query);
    }

    function _search(query) {
      var resultsDiv = $('#search-results');
      _toggleSpinner(resultsDiv);

      $.getJSON("/api/2/search", {"q": query}, function (data) {
        _displayResults(data.results, resultsDiv);
        _toggleSpinner(resultsDiv);
      });
    }

    function _displayResults(results, element) {
      if (results.length === 0) {
        element.html('No data available for this query.');
        return;
      }

      element.html('');

      for (i in results) {
        element.append(_prepareResult(results[i]));
      }

      element.highlight(query);
    }

    function _toggleSpinner(element) {
      element.toggleClass('spinner');
    }

    function _prepareResult(result) {
      result['values'] = _prepareDimensionsForHandlebars(result);
      result.amount = OpenSpending.Utils.formatAmountWithCommas(result.amount, 0, result.currency)
      return resultTemplate(result);
    };

    function _prepareDimensionsForHandlebars(result) {
      var dimensions = [];

      for (dimension in result) {
        var label = result[dimension].label;
        if (dimension !== "time" && dimension !== "dataset" && label) {
          dimensions.push({ key: dimension, value: label });
        }
      }

      return dimensions;
    };
  })(jQuery);
});

<|endoftext|>