text:
/*
   Direct call to ProcessCommandOptions() to process an array of
   options minus the command argument.  This is the function that
   actually splits up the argument array into separate operation
   group calls.

   Compile with ImageMagick-devlop installed...

     gcc -lMagickWand -lMagickCore cli_process.c -o cli_process

   Compile and run directly in Source Directory...

     IM_PROG=api_examples/cli_process
     gcc -I`pwd` -LMagickWand/.libs -LMagickCore/.libs \
       -lMagickWand -lMagickCore  $IM_PROG.c -o $IM_PROG

     sh magick.sh    $IM_PROG

*/
#include <stdio.h>
#include "MagickCore/studio.h"
#include "MagickWand/MagickWand.h"

int main(int argc, char **argv)
{
  MagickCLI
    *cli_wand;

  int arg_count;
  char *args[] = { "-size", "100x100", "xc:red",
                   "(", "rose:", "-rotate", "-90", ")",
                   "+append", "show:", NULL };

  for(arg_count = 0; args[arg_count] != (char *)NULL; arg_count++);

  MagickCoreGenesis(argv[0],MagickFalse);
  cli_wand = AcquireMagickCLI((ImageInfo *)NULL,(ExceptionInfo *)NULL);

  ProcessCommandOptions(cli_wand, arg_count, args, 0, MagickCommandOptionFlags);

  /* Note use of 'True' to report all exceptions - including non-fatals */
  if ( CLICatchException(cli_wand,MagickTrue) != MagickFalse )
    fprintf(stderr, "Major Error Detected\n");

  cli_wand = DestroyMagickCLI(cli_wand);
  MagickCoreTerminus();
}


text:
"use strict"

var url = require("url")
var fs = require("fs")
var uuid = require("node-uuid")

class Setup{

  constructor(mscp){
    this.mscp = mscp
    this.init();
  }

  reload(){
    this.init();
  }

  init(){
    if(fs.existsSync("./setup.json"))
      this.setup = JSON.parse(fs.readFileSync("./setup.json", "utf-8"))
    else
      this.setup = {}
  }

  async handleJSONRequest(req, res){
    var data = req.body;
    if(data === undefined || (Object.keys(data).length === 0 && data.constructor === Object))
      data = req.query;

    if(data === undefined){
      res.end("Invalid request!");
      return;
    }

    var apiPath = url.parse(req.url).pathname.substring(1);
    let def = null;
    let serveName = null;
    let arg = null;

    res.writeHead(200, {'Content-Type':'application/json'});

    let response = undefined;
    switch(apiPath.toLowerCase()){

      // -------------------------
      //        SERVERS
      // -------------------------

      case "add-server":
      case "refresh-server":
        switch(data.type){
          case "http":
            if(!data.url.startsWith("http"))
              data.url = "http://" + data.url;

          case "websocket-server":
            var definition = await this.getServerDefinition(data)
            if(definition != null){
              data.name = definition.name;
            }
            break;

          case "websocket-client":
            if(!data.name){
              data.name = "Client";
            }
            break;
        }

        if(data.namespace){
            if(data.namespace.toLowerCase() == 'client' || data.namespace.toLowerCase() == 'server' || data.namespace.toLowerCase() == 'mscp'){
              data.namespace = data.namespace+'2';
            }
        }

        if(this.setup.servers === undefined)
          this.setup.servers = []

        if(apiPath.toLowerCase() == "add-server"){
          data.id = uuid.v4()
          this.setup.servers.push(data)
        } else {
          for(let i = 0; i < this.setup.servers.length; i++){
            if(this.setup.servers[i].id === data.id){
              this.setup.servers[i] = data;
            }
          }
        }

        await this.updateDependencyToServer();

        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "update-server":
        if(data.id !== undefined){
          for(let i = 0; i < this.setup.servers.length; i++){
            if(this.setup.servers[i].id === data.id){
              this.setup.servers[i].name = data.name;
              this.setup.servers[i].namespace = data.namespace;
              this.setup.servers[i].enabled = data.enabled;
              this.setup.servers[i].websocket = data.websocket;
              this.setup.servers[i].accesskey = data.accesskey;
              this.setup.servers[i].forwardAccessKey = data.forwardAccessKey;
            }
          }
          await this.updateDependencyToServer();
          fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        }
        break;

      case "get-servers":
        response = this.setup.servers
        break;

      case "get-server-definition":
        if(data.id !== undefined){
          var definition = await this.getServerDefinition(data)
          if(definition != null)
            response = definition
          else
            response = {error: "Could not get definition from server"}
        }
        break;

      case "get-servers-with-status":
        let serverStatus = []
        let promises = []
        if(this.setup.servers !== undefined){
          for(let i = 0; i < this.setup.servers.length; i++){
            promises.push(new Promise(async (r) => {
              var definition = await this.getServerDefinition(this.setup.servers[i])
              r(definition)
            }))
          }

          for(let i = 0; i < promises.length; i++){
            let definition = await promises[i];
            serverStatus[i] = JSON.parse(JSON.stringify(this.setup.servers[i]));
            serverStatus[i].running = definition != null && definition["name"] !== undefined;
          }
        }

        response = serverStatus
        break;

      case "log":
        response = []
        break;

      case "remove-server":
        if(data.id !== undefined){
          for(let i = 0; i < this.setup.servers.length; i++){
            if(this.setup.servers[i].id === data.id){
              this.setup.servers.splice(i, 1)
              await this.updateDependencyToServer();
              fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
            }
          }
        }
        response = {}
        break;

      // -------------------------
      //        DEPENDENCIES
      // -------------------------
      case "get-dependencies":
        def = await this.readDefinition()
        let deps = def.dependencies !== undefined ? def.dependencies : []
        deps = JSON.parse(JSON.stringify(deps))
        if(this.setup.dependencyToServer == undefined)
          this.setup.dependencyToServer = {}
        for(let d of deps){
          let server = this.setup.dependencyToServer[(d.namespace?d.namespace+".":"")+d.name]
          if(server){
            for(let i = 0; i < (this.setup.servers || []).length; i++){
              if(this.setup.servers[i].id === server.id){
                d.serverId = server.id
                d.serverName = this.setup.servers[i].name
              }
            }
          }
        }
        response = deps
        break;

      case "remove-dependency":
        if(data && typeof data.name !== undefined && data.name != ""){
          def = await this.readDefinition()
          let deps = def.dependencies !== undefined ? def.dependencies : []
          if(this.setup.dependencyToServer == undefined)
            this.setup.dependencyToServer = {}
          for(let i = 0; i < deps.length; i++){
            if(deps[i].name == data.name && deps[i].namespace == data.namespace){
              this.setup.dependencyToServer[(deps[i].namespace?deps[i].namespace+".":"")+deps[i].name] = undefined
              deps.splice(i, 1)
            }
          }
          def.dependencies = deps;
          await this.writeDefinition(def);
          await this.writeSetup()
          response = {}
        }
        break;

      case "update-dependency":
        if(data && typeof data.name !== undefined && data.name != ""){
          def = await this.readDefinition()
          let deps = def.dependencies !== undefined ? def.dependencies : []
          for(let i = 0; i < deps.length; i++){
            if(deps[i].name == data.name && (deps[i].namespace == data.namespace || deps[i].namespace == data.oldNamespace)){
              deps[i].namespace = data.namespace
            }
          }
          def.dependencies = deps;
          await this.writeDefinition(def);
          await this.writeSetup()
          response = {}
        }
        break;

      case "add-all-server-func-as-dep":
        response = {error: "Not implemented"}
        break;

      case "add-server-func-as-dep":
        if(data && data.func && typeof data.func.name !== undefined && data.func.name != ""){
          let dep = data.func;

          def = await this.readDefinition()
          let deps = def.dependencies !== undefined ? def.dependencies : []
          if(this.setup.dependencyToServer == undefined)
            this.setup.dependencyToServer = {}
          let alreadyExists = false
          for(let i = 0; i < deps.length; i++){
            if(deps[i].name == dep.name && deps[i].namespace == data.serverNamespace){
              deps[i] = dep;
              alreadyExists = true;
            }
          }
          if(!alreadyExists){
            this.setup.dependencyToServer[(data.serverNamespace?data.serverNamespace+".":"")+dep.name] = {id: data.serverId, method: dep.name, namespace: dep.namespace}
            dep.namespace = data.serverNamespace;
            deps.push(dep);
          }
          def.dependencies = deps;
          await this.writeDefinition(def);
          await this.writeSetup()
        }
        break;

      // -------------------------
      //        BASIC
      // -------------------------
      case "set-basic-info":
        def = await this.readDefinition()

        if(typeof data.name === "string" && data.name !== "" && data.name != def.name){
          def.name = data.name
          await this.writeDefinition(def);
        }

        if(typeof data.http_port === "string" || typeof data.http_port === "number"){
          let port = parseInt(data.http_port)
          if(port > 0 && port <= 65535 && port != this.setup.http_port){
            this.setup.http_port = port
          }
        }

        if(typeof data.https_port === "string" || typeof data.https_port === "number"){
          let port = parseInt(data.https_port)
          if(port > 0 && port <= 65535 && port != this.setup.https_port){
            this.setup.https_port = port
          }
        }

        if(typeof data.enableHTTP === "boolean")
          this.setup.enableHTTP = data.enableHTTP

        if(typeof data.enableHTTPS === "boolean")
          this.setup.enableHTTPS = data.enableHTTPS

        if(typeof data.https_key === "string")
          this.setup.https_key = data.https_key

        if(typeof data.https_cert === "string")
          this.setup.https_cert = data.https_cert

        if(typeof data.https_ca === "string")
          this.setup.https_ca = data.https_ca

        if(typeof data.api_access_scheme === "string")
          this.setup.api_access_scheme = data.api_access_scheme

        if(typeof data.manage_access_scheme === "string")
          this.setup.manage_access_scheme = data.manage_access_scheme

        if(typeof data.static_access_scheme === "string")
          this.setup.static_access_scheme = data.static_access_scheme

        if(typeof data.attemptAPIOnUnresolvedPaths === "boolean")
          this.setup.attemptAPIOnUnresolvedPaths = data.attemptAPIOnUnresolvedPaths

        await this.writeSetup()

        response = {}
        break;

      case "get-basic-info":
        def = await this.readDefinition()
        response = {
          name: def.name,
          http_port: this.setup.http_port || this.setup.port || 8080,
          https_port: this.setup.https_port || 443,
          enableHTTP: this.setup.enableHTTP || true,
          enableHTTPS: this.setup.enableHTTPS || false,
          https_key: this.setup.https_key || "",
          https_cert: this.setup.https_cert || "",
          https_ca: this.setup.https_ca || "",
          api_access_scheme: this.setup.api_access_scheme || "full_access",
          manage_access_scheme: this.setup.manage_access_scheme || "full_access",
          static_access_scheme: this.setup.static_access_scheme || "full_access",
          attemptAPIOnUnresolvedPaths: this.setup.static_access_scheme || false
        }
        break;

      // -------------------------
      //        SERVE
      // -------------------------
      case "get-serve":
        def = await this.readDefinition()
        response = def.serve !== undefined ? def.serve : []
        break;

      case "add-serve":
        if(data && typeof data.name !== undefined && data.name != ""){
          if(data.args === undefined)
            data.args = []

          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          let alreadyExists = false
          for(let i = 0; i < serve.length; i++){
            if(serve[i].name == data.name && serve[i].namespace == data.namespace){
              serve[i] = data;
              alreadyExists = true;
            }
          }
          if(!alreadyExists){
            serve.push(data);
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        break;

      case "remove-serve":
        if(data && typeof data.name !== undefined && data.name != ""){
          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          for(let i = 0; i < serve.length; i++){
            if(serve[i].name == data.name && serve[i].namespace == data.namespace){
              serve.splice(i, 1)
            }
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        break;

      case "update-serve":
        if(data && typeof data.name !== undefined && data.name != ""){
          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          for(let i = 0; i < serve.length; i++){
            if((serve[i].name == data.name || serve[i].name == data.oldName) && (serve[i].namespace == data.namespace || serve[i].namespace == data.oldNamespace)){
              serve[i].name = data.name;
              serve[i].title = data.title;
              serve[i].description = data.description;
              serve[i].returntype = data.returntype;
              serve[i].namespace = data.namespace;
              serve[i].default = data.default;
            }
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        break;

      // -------------------------
      //    SERVE ARGUMENTS
      // -------------------------
      case "get-serve-arguments":
        def = await this.readDefinition()
        if(def.serve !== undefined){
          for(let f of def.serve){
            if(f.name == data.name && (!data.namespace || data.namespace == f.namespace)){
              response = f.args != undefined ? f.args : []
            }
          }
        } else {
          response = []
        }
        break;

      case "add-serve-argument":
        serveName = data.servename
        arg = data.record
        if(arg && typeof arg.name !== undefined && arg.name != ""){
          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          let alreadyExists = false
          for(let i = 0; i < serve.length; i++){
            if(serve[i].name == serveName && (!data.servenamespace || data.servenamespace == serve[i].namespace)){
              if(serve[i].args === undefined)
                serve[i].args = [];

              for(let a = 0; a < serve[i].args.length; a++){
                if(typeof serve[i].args[a] === "string")
                  serve[i].args[a] = {name: serve[i].args[a]};

                if(serve[i].args[a].name == arg.name)
                  alreadyExists = true;
              }
              if(!alreadyExists){
                serve[i].args.push(arg);
              }
            }
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        break;

      case "remove-serve-argument":
        serveName = data.servename
        arg = data.record
        //try{
        if(arg && typeof arg.name !== undefined && arg.name != ""){
          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          let alreadyExists = false
          for(let i = 0; i < serve.length; i++){
            if(serve[i].name == serveName && serve[i].args !== undefined && (!data.servenamespace || data.servenamespace == serve[i].namespace)){
              for(let a = 0; a < serve[i].args.length; a++){
                if(typeof serve[i].args[a] === "string")
                  serve[i].args[a] = {name: serve[i].args[a]};

                if(serve[i].args[a].name == arg.name)
                  serve[i].args.splice(a, 1)
              }
            }
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        //} catch(err){console.log(err)}
        break;

      case "update-serve-argument":
        serveName = data.servename
        arg = data.record
        if(arg && typeof arg.name !== undefined && arg.name != ""){
          def = await this.readDefinition()
          let serve = def.serve !== undefined ? def.serve : []
          let alreadyExists = false
          for(let i = 0; i < serve.length; i++){
            if(serve[i].name == serveName && serve[i].args !== undefined && (!data.servenamespace || data.servenamespace == serve[i].namespace)){
              for(let a = 0; a < serve[i].args.length; a++){
                if(serve[i].args[a].name == arg.name || serve[i].args[a].name == arg.oldName){
                  serve[i].args[a].name = arg.name;
                  serve[i].args[a].title = arg.title;
                  serve[i].args[a].type = arg.type;
                  serve[i].args[a].required = arg.required;
                  serve[i].args[a].description = arg.description;
                }
              }
            }
          }
          def.serve = serve;
          await this.writeDefinition(def);
        }
        break;

      // -------------------------
      //        FORWARDS
      // -------------------------
      case "get-forwards":
        response = this.setup.forwards !== undefined ? this.setup.forwards : []
        response = response.map((f) => {
          f.serverName = this.setup.servers.find((s) => s.id == f.server || s.name == f.server).name
          f.localnamespace = this.setup.servers.find((s) => s.id == f.server || s.name == f.server).namespace
          return f;
        })
        break;

      case "add-forward":
        if(data && data.server !== undefined && data.server != "" && data.function !== undefined && data.function != ""){
          if(this.setup.forwards === undefined)
            this.setup.forwards = []

          let alreadyExists = false
          for(let i = 0; i < this.setup.forwards.length; i++){
            if(this.setup.forwards[i].server == data.server && this.setup.forwards[i].function == data.function && (!this.setup.forwards[i].namespace || this.setup.forwards[i].namespace == data.namespace)){
              alreadyExists = true;
              break;
            }
          }
          if(!alreadyExists){
            this.setup.forwards.push(data);
          }
          await this.writeSetup()
        }
        break;

      case "remove-forward":
        if(data && data.server !== undefined && data.server != "" && data.function !== undefined && data.function != ""){
          for(let i = 0; i < this.setup.forwards.length; i++){
            if(this.setup.forwards[i].server == data.server && this.setup.forwards[i].function == data.function && (!this.setup.forwards[i].namespace || this.setup.forwards[i].namespace == data.namespace)){
              this.setup.forwards.splice(i, 1)
            }
          }
          await this.writeSetup()
        }
        break;

      case "update-forward":
        if(data && data.server !== undefined && data.server != "" && data.function !== undefined && data.function != ""){
          for(let i = 0; i < this.setup.forwards.length; i++){
            if(this.setup.forwards[i].server == data.server && this.setup.forwards[i].function == data.function && (!this.setup.forwards[i].namespace || this.setup.forwards[i].namespace == data.namespace)){
              this.setup.forwards[i].forwardAccessKey = data.forwardAccessKey;
            }
          }
          await this.writeSetup()
        }
        break;

      // -------------------------
      //        SECURITY
      // -------------------------
      case "get-access-rules":
        response = this.setup.accessRules || []
        break;

      case "add-access-rule":
        data.id = uuid.v4()

        if(this.setup.accessRules === undefined)
          this.setup.accessRules = []

        this.setup.accessRules.push(data)
        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "remove-access-rule":
        for(let i = 0; i < this.setup.accessRules.length; i++){
          if(this.setup.accessRules[i].id === data.id){
            this.setup.accessRules.splice(i, 1);
          }
        }
        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "update-access-rule":
        for(let i = 0; i < this.setup.accessRules.length; i++){
          if(this.setup.accessRules[i].id === data.id){
            this.setup.accessRules[i].area = data.area;
            this.setup.accessRules[i].description = data.description;
            this.setup.accessRules[i].ip = data.ip;
            this.setup.accessRules[i].default_permission = data.default_permission;
            this.setup.accessRules[i].require_access_key = data.require_access_key;
          }
        }
        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "get-access-sub-rules":
        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            response = a.subRules || [];
            break;
          }
        }
        break;

      case "add-access-sub-rule":
        data.id = uuid.v4()
        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            if(a.subRules === undefined)
              a.subRules = []
            a.subRules.push(data.rule)
            break;
          }
        }

        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "remove-access-sub-rule":
        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            if(a.subRules === undefined)
              a.subRules = []

            for(let i = 0; i < a.subRules.length; i++){
              if(a.subRules[i].path == data.path && a.subRules[i].parameters == data.parameters){
                a.subRules.splice(i, 1)
                break;
              }
            }
            break;
          }
        }
        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "get-access-keys":
        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            response = a.accessKeys || [];
            break;
          }
        }
        break;

      case "add-access-key":
        data.id = uuid.v4()
        if(data.rule.key == "")
          data.rule.key = uuid.v4()

        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            if(a.accessKeys === undefined)
              a.accessKeys = []
            a.accessKeys.push(data.rule)
            break;
          }
        }

        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      case "remove-access-key":
        for(let a of this.setup.accessRules){
          if(a.id == data.accessId){
            if(a.accessKeys === undefined)
              a.accessKeys = []

            for(let i = 0; i < a.accessKeys.length; i++){
              if(a.accessKeys[i].description == data.description && a.accessKeys[i].key == data.key){
                a.accessKeys.splice(i, 1)
                break;
              }
            }
            break;
          }
        }
        fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), ()=>null)
        response = {}
        break;

      // -------------------------
      //      Forward setup
      // -------------------------
      case "forward-to-server":
        if(data.server !== undefined && data.command !== undefined){
          let url = null;
          for(let i = 0; i < this.setup.servers.length; i++){
            if(this.setup.servers[i].id === data.server){
              url = this.setup.servers[i].url;
              break;
            }
          }
          if(url !== null){
            response = (await this.mscp._request({
              url: url + "/mscpapi/" + data.command,
              method: "POST",
              headers: {
                  "content-type": "application/json",
              },
              json: data.data
            }))
            response = JSON.parse(response)
          } else {
            response = {error: "Unknown server ID"}
          }
        } else {
          response = {error: "Invalid arguments"}
        }
        break;

      default:
        res.end(JSON.stringify({error: "Unknown setup API", path: apiPath}));
    }
    res.end(JSON.stringify(response != undefined ? response : {error: "Unknown server error", path: apiPath}));
  }

  async getServerDefinition(server){
    try{
      return await this.mscp.client.connectionManager.call(server, "")
    } catch(err){console.log(err)}
    return null;
  }
  async readDefinition(){
    try
    {
      return JSON.parse(await new Promise(r => fs.readFile("./definition.json", "utf-8", (err, data)=>r(data))))
    } catch(err){}
    return {}
  }
  async writeDefinition(def){
    try
    {
      await new Promise(r => fs.writeFile("./definition.json", JSON.stringify(def, null, 2), (err)=>r()));
    } catch(err){}
  }
  async writeSetup(def){
    try
    {
      await new Promise(r => fs.writeFile("./setup.json", JSON.stringify(this.setup, null, 2), (err)=>r()));
    } catch(err){}
  }

  async updateDependencyToServer(){
    let def = await this.readDefinition()
    let deps = def.dependencies !== undefined ? def.dependencies : []
    deps = JSON.parse(JSON.stringify(deps))
    if(this.setup.dependencyToServer == undefined)
      this.setup.dependencyToServer = {}

    for(let d of deps){
      let server = this.setup.dependencyToServer[(d.namespace?d.namespace+".":"")+d.name]
      if(server){
        let found = false;
        for(let i = 0; i < (this.setup.servers || []).length; i++){
          if(this.setup.servers[i].id === server.id){
            //d.serverId = server.id
            //d.serverName = this.setup.servers[i].name
            found = true;
          }
        }
        if(!found){
          delete this.setup.dependencyToServer[(d.namespace?d.namespace+".":"")+d.name];
          server = null;
        }
      }

      if(!server){
        for(let i = 0; i < (this.setup.servers || []).length; i++){
          let s = this.setup.servers[i];
          if(s.namespace != d.namespace)
            continue;

          let serverDef = await this.getServerDefinition(s)
          if(!serverDef){
            console.log("Could not get definition from server: " + s.name)
            continue;
          }

          for(let serv of serverDef.serve){
            if(serv.name == d.name){
              this.setup.dependencyToServer[(d.namespace?d.namespace+".":"")+d.name] = {id: s.id, method: serv.name, namespace: serv.namespace}
            }
          }
        }
      }
    }
  }

}

module.exports = Setup

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('topics', '0095_auto_20200603_2208'),
    ]

    operations = [
        migrations.AddField(
            model_name='programmingchallenge',
            name='testing_examples',
            field=models.TextField(default=''),
        ),
    ]


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Philippe Tillet, Sergey Lisitsyn, Viktor Gal, Fernando Iglesias,
 *          Bjoern Esser, Soeren Sonnenburg, Saurabh Goyal
 */

#ifndef _NEAREST_CENTROID_H__
#define _NEAREST_CENTROID_H__

#include <shogun/lib/config.h>

#include <shogun/lib/common.h>
#include <shogun/io/SGIO.h>
#include <shogun/features/Features.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/distance/Distance.h>
#include <shogun/machine/DistanceMachine.h>

namespace shogun
{

class DistanceMachine;

/** @brief Class NearestCentroid, an implementation of Nearest Shrunk Centroid classifier
 *
 * To define how close examples are
 * NearestCentroid requires a Distance object to work with (e.g., EuclideanDistance ).
 */

class NearestCentroid : public DistanceMachine{

public:

	/** problem type */
	MACHINE_PROBLEM_TYPE(PT_MULTICLASS);

	/**
	 * Default constructor
	 */
	NearestCentroid();

	/** constructor
	 *
	 * @param distance distance
	 * @param trainlab labels for training
	 */
	NearestCentroid(const std::shared_ptr<Distance>& distance, const std::shared_ptr<Labels>& trainlab);

	/** Destructor
	 */
	virtual ~NearestCentroid();

	/** Set shrinking constant
	 *
	 * @param shrinking to be set
	 */
	void set_shrinking(float64_t shrinking) {
		m_shrinking = shrinking ;
	}

	/** Get shrinking constant
	 *
	 * @return value of the shrinking constant
	 */
	float64_t get_shrinking() const{
		return m_shrinking;
	}

	/** Get the centroids
	 *
	 * @return Matrix containing the centroids
	 */
	std::shared_ptr<DenseFeatures<float64_t>> get_centroids() const{
		return m_centroids;
	}

	/** Returns the name of the SGSerializable instance.
	 *
	 * @return name of the SGSerializable
	 */
	virtual const char* get_name() const { return "NearestCentroid"; }

protected:
	/** train Nearest Centroid classifier
	 *
	 * @param data training data (parameter can be avoided if distance or
	 * kernel-based classifiers are used and distance/kernels are
	 * initialized with train data)
	 *
	 * @return whether training was successful
	 */
	virtual bool train_machine(std::shared_ptr<Features> data=NULL);

	/** Stores feature data of underlying model.
	 *
	 * Sets centroids as lhs
	 */

private:
	void init();

protected:
	///	number of classes (i.e. number of values labels can take)
	int32_t m_num_classes;

	///	Shrinking parameter
	float64_t m_shrinking;

	///	The centroids of the trained features
	std::shared_ptr<DenseFeatures<float64_t>> m_centroids;

	///	Tells if the classifier has been trained or not
	bool m_is_trained;
};

}

#endif


text:
package org.apache.ignite.tests.p2p;

import org.apache.ignite.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.compute.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.resources.*;
import org.jetbrains.annotations.*;

import java.util.*;

/**
 * Test task for {@code GridCacheDeploymentSelfTest}.
 */
public class CacheDeploymentTestTask3 extends ComputeTaskAdapter<T2<ClusterNode, String>, Object> {
    /** {@inheritDoc} */
    @Override public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid,
        @Nullable T2<ClusterNode, String> tup) {
        final String val = tup.getValue();

        return F.asMap(
                new ComputeJobAdapter() {
                    @IgniteInstanceResource
                    private Ignite ignite;

                    @Override public Object execute() {
                        X.println("Executing CacheDeploymentTestTask3 job on node " +
                                ignite.cluster().localNode().id());

                        ignite.<String, CacheDeploymentTestValue>cache(null).put(val,
                                new CacheDeploymentTestValue());

                        return null;
                    }
                },
                tup.get1()
        );
    }

    /** {@inheritDoc} */
    @Nullable @Override public Object reduce(List<ComputeJobResult> results) {
        return null;
    }
}


text:
I am ZnUTF8Encoder, a concrete subclass of ZnCharacterEncoder.
I implement the variable length UTF-8 encoding and decoding of Unicode according to RFC 3629.

Part of Zinc HTTP Components.


text: from .forest_classifier import ForestClassifier


text:
<?php

namespace DTS\eBaySDK\BulkDataExchange\Types\Test;

use DTS\eBaySDK\BulkDataExchange\Types\DeleteRecurringJobRequest;

class DeleteRecurringJobRequestTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new DeleteRecurringJobRequest();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\BulkDataExchange\Types\DeleteRecurringJobRequest', $this->obj);
    }

    public function testExtendsBaseServiceRequest()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\BulkDataExchange\Types\BaseServiceRequest', $this->obj);
    }
}


text:
package org.dasein.cloud.cloudstack;

import java.util.ArrayList;
import java.util.List;

/**
 * Description
 *
Created by stas: 24/09/2014 11:52

 *
 * @author Stas Maksimov
 * @version 2014.08 initial version
 * @since 2014.08
 */
public final class Iterables {

    public static <T> List<T> toList(Iterable<T> iterable) {
        if( iterable == null ) {
            return null;
        }
        if( iterable instanceof List ) {
            return (List<T>) iterable;
        } else {
            List<T> list = new ArrayList<T>();
            for( T item : iterable) {
                list.add(item);
            }
            return list;
        }
    }

}


text:
<?php include('about_header.php') ?>

 <a href="<?php echo base_url() ?>"> Home  WHATSAPP ORDER

ORDER ON WHATSAPP

Take Time to place order on website? Don't worry, we shall deliver your list of grocery stuff  after receiving it on whatsapp.
First Sign up on www.keryana.com and you will be given an acc. no.
Then make a list of grocery stuff and text it or snap it & send it to us on Whatsapp with your acc. no. mentioned on the list.
 You will get value of order shortly.

 Confirm your order now at 0331 68 67000 and get your order delivered to your doorstep.

<?php include('about_footer.php'); ?>


text:
var helpers = require('helpers'),
    redis = require('redis').saveClient,
    sys = require('sys');

/* Don't be fooled about max_usage. While we do set it initially, it's nothing
   but a flag - the real usage counter is in redis in counter:<aid> and the only
   way to read-access that is by calling Alias.prototype.use() (or set use to true
   when callind findById())

   use() in turn will use redis' DECR operation on the counter.

   This makes sure, considering that DECR is atomic, that even under high load
   no mail can slip in :-)
 */
var Alias = function(aid) {
  this.aid = aid || null,
  this.valid_from = null,
  this.valid_until = null,
  this.max_usage = null
}
helpers.extend(Alias.prototype, (function(){
  function dv(ad, m) {
    var d = null;
    if (ad.hasOwnProperty(m)) {
      d = new Date(Date.parse(ad[m]));
      if (!d) {
        throw new Error(m + ' provided but invalid');
      }
    }
    return d;
  }

  function validate(ad) {
    if (ad.days){
      ad.days = Math.min(60, ad.days);
      var d = new Date();
      d.setDate(d.getDate() + parseInt(ad.days, 10));
      this.valid_until = d;
    }else{
      this.valid_from = dv(ad, 'valid-from');
      this.valid_until = dv(ad, 'valid-until');
    }
    this.target = null;
    this.max_usage = parseInt(ad['max-usage'], 10);
    if (isNaN(this.max_usage)) this.max_usage = null;
    if (this.max_usage) this.max_usage = Math.min(100, this.max_usage);

    if (ad.hasOwnProperty('target')) {
      // we require a "raw" email address, so no comments or anything
      // also, I'm not even trying to be clever here. If it looks like
      // not-at@notdot.notdot, it's probably a valid email address
      if (ad.target.match(/^[^@]+@[^.@]+\.[^@.][^@]+$/))
        this.target = ad.target
    }
    if (!this.target) {
      throw new Error("Target missing or invalid");
    }
  }
  return {
    setInfo: function(ad) {
      validate.apply(this, arguments);
    },
    use: function(callback){
      var pdate = null;

      // node currently can't parse the output of its JSON serialized dates :-)
      function fixJSONDate(s){
        return s.replace(/\.[0-9]+Z$/, ' UTC').replace(/(\d)T(\d)/, "$1 $2");
      }

      if (!this.aid){
        callback(true);
        return;
      }

      if (this.valid_from && Date.parse(fixJSONDate(this.valid_from)) > new Date()){
        callback(false);
        return; // no further checks
      }
      if (this.valid_until && Date.parse(fixJSONDate(this.valid_until)) < new Date()){
        callback(false);
        return; // no further checks
      }

      if (!this.max_usage){
        callback(true);
      }else{
        var alias = this;
        redis.decr('counter:' + alias.aid, function(data){
          var c = parseInt(""+data, 10);
          callback(!isNaN(c) && (c >= 0));
        });
      }
    }
  };
}()));

(function() {
  var ids = 0;
  var UUID = require("uuid").UUID;

  var AliasProvider = (function(){
    function getNextId(callback) {
      var len = 3, c = "";
      redis.get('admin:keylength', function(data){
        len = data || len;
        var uuidg = function uuidg() {
          len++;
          var id = UUID.uuid(len);
          redis.setnx('reservations:' + id, 'reserved', function(data) {
            if (parseInt(""+data, 10) == 0) {
              redis.set('admin:keylength', len, function(data){
                uuidg();
              });
            }
            callback(id);
          });
        }();
      });
    }
    return {
      findById: function(id, use, callback) {
        if (callback) {
          redis.get('aliases:' + id, function(data) {
            if (!data) {
              callback(null);
              return;
            }
            helpers.extend(ad = new Alias(), JSON.parse(""+data));

            if (use){
              ad.use(function(valid){
                callback(valid ? ad : null);
              })
            }else{
              if (ad.max_usage){
                redis.get('counter:'+ad.aid, function(data){
                  var cb =  (parseInt(data, 10) > 0) ? ad : null;
                  callback(cb);
                });
              }else{
                callback(ad);
              }
            }
          });
        }
      },
      getNew: function() {
        return new Alias();
      },
      save: function(alias, callback) {
        if (!alias.aid) {
          alias.updatekey = UUID.uuid();
          getNextId(function(id) {
            alias.aid = id;
            redis.set('aliases:' + id, JSON.stringify(alias), function(data) {
              if (alias.max_usage){
                redis.set('counter:' + id, alias.max_usage,  function(data){
                  callback(alias.aid);
                })
              }else{
                callback(alias.aid);
              }
            });
          });
        }
      }
    }
  }());

  exports.AliasProvider = AliasProvider;
})();


text:
package org.apache.causeway.security.authentication.standard;

import java.util.Collections;
import java.util.Optional;

import org.junit.jupiter.api.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.apache.causeway.applib.exceptions.unrecoverable.NoAuthenticatorException;
import org.apache.causeway.core.security._testing.InteractionService_forTesting;
import org.apache.causeway.core.security.authentication.AuthenticationRequestPassword;
import org.apache.causeway.core.security.authentication.manager.AuthenticationManager;
import org.apache.causeway.core.security.authentication.standard.RandomCodeGeneratorDefault;
import org.apache.causeway.security.AuthenticatorsForTesting;

import lombok.val;

class AuthenticationManager_authenticators_Test {

    private AuthenticationManager authenticationManager;

    @Test
    public void shouldNotBeAbleToAuthenticateWithNoAuthenticators() throws Exception {

        assertThrows(NoAuthenticatorException.class, ()->{

            authenticationManager = new AuthenticationManager(
                    Collections.emptyList(),
                    new InteractionService_forTesting(),
                    new RandomCodeGeneratorDefault(),
                    Optional.empty(),
                    Collections.emptyList());
            authenticationManager.authenticate(new AuthenticationRequestPassword("foo", "bar"));

        });
    }

    @Test
    public void shouldBeAbleToUseAuthenticators() throws Exception {

        val auth = AuthenticatorsForTesting.authenticatorAllwaysValid();

        authenticationManager = new AuthenticationManager(
                Collections.singletonList(auth),
                new InteractionService_forTesting(),
                new RandomCodeGeneratorDefault(),
                Optional.empty(),
                Collections.emptyList());
        assertThat(authenticationManager.getAuthenticators().size(), is(1));
        assertThat(authenticationManager.getAuthenticators().getElseFail(0), is(sameInstance(auth)));
    }

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

	<servlet>
		<servlet-name>oam</servlet-name>
		<servlet-class>org.cipango.example.OamServlet</servlet-class>
	</servlet>

	<servlet>
		<servlet-name>ClickToDialHttpServlet</servlet-name>
		<servlet-class>org.cipango.example.ClickToDialHttpServlet</servlet-class>
	</servlet>

   <servlet-mapping>
		<servlet-name>oam</servlet-name>
		<url-pattern>/oam</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>ClickToDialHttpServlet</servlet-name>
		<url-pattern>/call</url-pattern>
	</servlet-mapping>
</web-app>


text:
(function() {
  'use strict';

  angular.module('todoApp').service('authenticationService', function($http, $log, $rootScope, $q, appUrl, storageService, appEvents) {

    var KEY_TOKEN = '$AUTH_TOKEN';
    var USER_ID = '$AUTH_USER_ID';
    var authenticateUrl = appUrl.api + 'authentication/authenticate';

    var setRootScopeAuthentication = function(isAuthenticated) {
      $rootScope.isAuthenticated = isAuthenticated === true;
      $rootScope.$broadcast(appEvents.USER_AUTH_CHANGED);
    };

    /**
     * Remove the current token from storageService.
     */
    var invalidateToken = function() {
      storageService.remove(KEY_TOKEN);
    };

    var authenticate = function(username, password) {
      var deferred = $q.defer();

      $http.post(authenticateUrl, { username: username, password: password })
        .then(function(response) {
          var data = response.data;
          if (!data.success) {
            data.message = 'Usuário e/ou senha inválidos.';
          }
          else {
            storageService.set(KEY_TOKEN, data.token);
            storageService.set(USER_ID, data.id);
            setRootScopeAuthentication(true);
          }

          deferred.resolve(data);
        }, function(err) {
          deferred.reject(err);
        });

      return deferred.promise;
    };

    var checkCurrentAuthentication = function() {
      if (storageService.get(KEY_TOKEN)) {
        return true;
      }
      else {
        return false;
      }
    };

    var reAuthenticate = function() {

    };

    /**
     * Removes the current authentication token.
     */
    var removeAuthentication = function() {
      invalidateToken();
      setRootScopeAuthentication(false);

      return $q.when();
    };

    return {
      removeAuthentication: removeAuthentication,
      authenticate: authenticate,
      checkCurrentAuthentication: checkCurrentAuthentication,
      reAuthenticate: reAuthenticate,
    };
  });
})();


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta property="og:title" content="WebGL Setup and Installation" />
<meta property="og:type" content="website" />
<meta property="og:image" content="http://webglfundamentals.org/webgl/lessons/resources/webglfundamentals.jpg" />
<meta property="og:description" content="How to do WebGL development" />
<meta property="og:url" content="http://webglfundamentals.org/webgl/lessons/webgl-setup-and-installation.html" />

<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@greggman" />
<meta name="twitter:creator" content="@greggman" />
<meta name="twitter:domain" content="webglfundamentals.org" />
<meta name="twitter:title" content="WebGL Setup and Installation" />
<meta name="twitter:url" content="http://webglfundamentals.org/webgl/lessons/webgl-setup-and-installation.html" />
<meta name="twitter:description" content="How to do WebGL development" />
<meta name="twitter:image:src" content="http://webglfundamentals.org/webgl/lessons/resources/webglfundamentals.jpg" />

<title>WebGL Setup and Installation</title>
<link href="/webgl/lessons/resources/webglfundamentals-icon.png" rel="shortcut icon" type="image/png">
<link rel="stylesheet" href="/webgl/lessons/resources/base.css" type="text/css" />
<link rel="stylesheet" href="/webgl/lessons/resources/lesson.css" type="text/css" />

WebGLFundamentals.org

WebGL Setup and Installation

Techincally you don't need anything other than a web browser to do WebGL
development. Go to jsfiddle.net or jsbin.com
or codepen.io and just start applying the lessons here.

On all of them you can reference external scripts by adding a <script src="..."></script>
tag pair if you want to use external scripts.

Still, there are limits. WebGL has stronger restrictions than Canvas2D for loading images
which means you can't easily access images from around the web for your WebGL work.
On top of that it's just faster to work with everything local.

Let's assume you want to run and edit the samples on this site. The first thing you should
do is download the site. You can download it here.

Unzip the files into some folder.

Using a small simple easy Web Server

Next up you should install a small web server. I know "web server" sounds scary but the truth is web
servers are actually extremely simple.

If you're on Chrome here's a simple solution.
Here's a small chrome extension that's a web server

Just point it at the folder where you unzipped the files and click one of the web server URLs.

If you're not on chrome or if you don't want to use the extension another way is to use node.js.
Download it, install it, then open a command prompt / console / terminal window. If you're on Windows the installer
will add a special "Node Command Prompt" so use that.

Then install the http-server by typing

npm -g install http-server

If you're on OSX use

sudo npm -g install http-server

Once you've done that type

http-server path/to/folder/where/you/unzipped/files

It should print something like

Then in your browser go to http://localhost:8080.

If you don't specify a path then http-server will server the current folder.

Using your Browsers Developer Tools

Most browser have extensive developer tools built in.

Docs for Chrome's are here,
Firefox's are here.

Learn how to use them. If nothing else always check the JavaScript console. If there is an issue it will often have
an error message. Read the error message closely and you should get a clue where the issue is.

WebGL Helpers

There are various WebGL Inspectors / Helpers. Here's one for Chrome.

Firefox also has a similar one.
It needs to be enabled in about:flags and might required the Firefox Developer Edition.

They may or may not be helpful. Most of them are designed for animated samples and will capture a frame
and let you see all the WebGL calls that made that frame. That's great if you already have something
working or if you had something working and it broke. But it's not so great if your issue is during
initialization which they don't catch or if you're not using animation, as in drawing something every frame.
Still they can be very useful. I'll often click on a draw call, and check the uniforms. If I see a
bunch of NaN (NaN = Not a Number) then I can usually track down the code that set that uniform and
find the bug.

Inspect the Code

Also always remember you can inspect the code. You can usually just pick view source

Even if you can't right click a page or if the source is in a separate file
you can always view the source in the devtools

Get Started

Hopefully that helps you get started. Now back to the lessons.

Questions? Ask on stackoverflow.

Issue/Bug? Create an issue on github.

        Please enable JavaScript to view the comments powered by Disqus.
        comments powered by Disqus

        <select id="language">
</select>

Fundamentals

WebGL Fundamentals

WebGL How It Works

WebGL Shaders and GLSL

Image Processing

WebGL Image Processing

WebGL Image Processing Continued

2D translation, rotation, scale, matrix math

WebGL 2D Translation

WebGL 2D Rotation

WebGL 2D Scale

WebGL 2D Matrices

3D

WebGL - Orthographic 3D

WebGL 3D Perspective

WebGL 3D - Cameras

Lighting

WebGL 3D - Directional Lighting

WebGL 3D - Point Lighting

Structure and Organization

WebGL - Less Code, More Fun

WebGL - Drawing Multiple Things

WebGL - Scene Graphs

Techniques

2D

WebGL 2D - DrawImage

WebGL 2D - Matrix Stack

Text

WebGL Text - HTML

WebGL Text - Canvas 2D

WebGL Text - Using a Texture

WebGL Text - Using a Glyph Texture

Misc

WebGL Setup And Installation

WebGL Boilerplate

WebGL Resizing the Canvas

WebGL - Animation

WebGL 3D - Textures

WebGL Using 2 or More Textures

WebGL and Alpha

WebGL - 2D vs 3D libraries

WebGL - Anti-Patterns

Helper API Docs

TWGL, A tiny WebGL helper library

github


text:
package io.shrtr.lambda;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.amazonaws.services.lambda.runtime.Context;
import com.google.common.base.Optional;

import io.shrtr.server.Persister;
import io.shrtr.server.TestUtils;

public class PutURLTest {

	private final String input = "https://www.google.com";

	@Before
	public void setUp() {
		TestUtils.setupShortUrlTable();
	}

	@After
	public void tearDown() {
		TestUtils.deleteShortUrlTable();
	}

	private Context createContext() {
		TestContext ctx = new TestContext();
		ctx.setFunctionName("GetURL");
		return ctx;
	}

	@Test
	public void testPutURL() throws Exception {
		Persister dps = TestUtils.dynamoDbLocalPersister();

		PutURL handler = new PutURL(dps);
		Context ctx = createContext();

		String shortened = handler.handleRequest(input, ctx);
		assertEquals("50328aa4", shortened);
		Optional<String> fromDynamo = dps.getMapping(shortened);
		assertTrue(fromDynamo.isPresent());
		assertEquals(input, fromDynamo.get());
	}

}


text:
<!DOCTYPE html>
<html>
<!--
Copyright 2008 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by an Apache 2.0 License.
See the COPYING file for details.
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.testing.ExpectedFailures</title>
<script src="../base.js"></script>
<script>
  goog.require('goog.testing.ExpectedFailures');
  goog.require('goog.testing.jsunit');
</script>
</head>
<body>
<script type="text/javascript">
  var count, expectedFailures, lastLevel, lastMessage;

  // Stub out the logger.
  goog.testing.ExpectedFailures.prototype.logger_.log = function(level,
      message) {
    lastLevel = level;
    lastMessage = message;
    count++;
  };

  function setUp() {
    expectedFailures = new goog.testing.ExpectedFailures();
    count = 0;
    lastLevel = lastMessage = '';
  }

  // Individual test methods.

  function testNoExpectedFailure() {
    expectedFailures.handleTearDown()
  }

  function testPreventExpectedFailure() {
    expectedFailures.expectFailureFor(true);

    expectedFailures.handleException(new goog.testing.JsUnitException('', ''));
    assertEquals('Should have logged a message', 1, count);
    assertEquals('Should have logged an info message',
        goog.debug.Logger.Level.INFO, lastLevel);
    assertContains('Should log a suppression message',
        'Suppressing test failure', lastMessage);

    expectedFailures.handleTearDown();
    assertEquals('Should not have logged another message', 1, count);
  }

  function testDoNotPreventException() {
    var ex = 'exception';
    try {
      expectedFailures.expectFailureFor(false);
      expectedFailures.handleException(ex);
      fail('Should have rethrown exception');
    } catch (e) {
      assertEquals('Should rethrow same exepction', e, ex);
    }
  }

  function testExpectedFailureDidNotOccur() {
    expectedFailures.expectFailureFor(true);

    expectedFailures.handleTearDown();
    assertEquals('Should have logged a message', 1, count);
    assertEquals('Should have logged a warning',
        goog.debug.Logger.Level.WARNING, lastLevel);
    assertContains('Should log a suppression message',
        'Expected a test failure', lastMessage);
  }

  function testRun() {
    expectedFailures.expectFailureFor(true);

    expectedFailures.run(function() {
      fail('Expected failure');
    });

    assertEquals('Should have logged a message', 1, count);
    assertEquals('Should have logged an info message',
        goog.debug.Logger.Level.INFO, lastLevel);
    assertContains('Should log a suppression message',
        'Suppressing test failure', lastMessage);

    expectedFailures.handleTearDown();
    assertEquals('Should not have logged another message', 1, count);
  }

  function testRunStrict() {
    expectedFailures.expectFailureFor(true);

    try {
      expectedFailures.run(function() {
        // Doesn't fail!
      });

      fail('Should have thrown exception');
    } catch (ex) {
      assertEquals(ex.message, 'Call to fail()\n' +
          'Expected a test failure in \'testRunStrict\' but the test passed.');
    }
  }

  function testRunLenient() {
    expectedFailures.expectFailureFor(true);

    expectedFailures.run(function() {
      // Doesn't fail!
    }, true);
    expectedFailures.handleTearDown();
    assertEquals('Should have logged a message', 1, count);
    assertEquals('Should have logged a warning',
        goog.debug.Logger.Level.WARNING, lastLevel);
    assertContains('Should log a suppression message',
        'Expected a test failure', lastMessage);
  }

</script>
</body>
</html>


text:
#include <aws/core/client/AWSError.h>
#include <aws/serverlessrepo/ServerlessApplicationRepositoryErrorMarshaller.h>
#include <aws/serverlessrepo/ServerlessApplicationRepositoryErrors.h>

using namespace Aws::Client;
using namespace Aws::ServerlessApplicationRepository;

AWSError<CoreErrors> ServerlessApplicationRepositoryErrorMarshaller::FindErrorByName(const char* errorName) const
{
  AWSError<CoreErrors> error = ServerlessApplicationRepositoryErrorMapper::GetErrorForName(errorName);
  if(error.GetErrorType() != CoreErrors::UNKNOWN)
  {
    return error;
  }

  return AWSErrorMarshaller::FindErrorByName(errorName);
}


text:
<?php

declare(strict_types=1);

namespace Bitrix24\SDK\Services\CRM\Deal\Service;

use Bitrix24\SDK\Core\Exceptions\BaseException;
use Bitrix24\SDK\Core\Exceptions\TransportException;
use Bitrix24\SDK\Core\Result\AddedItemResult;
use Bitrix24\SDK\Core\Result\DeletedItemResult;
use Bitrix24\SDK\Core\Result\FieldsResult;
use Bitrix24\SDK\Core\Result\UpdatedItemResult;
use Bitrix24\SDK\Services\AbstractService;
use Bitrix24\SDK\Services\CRM\Deal\Result\DealContactItemsResult;

/**
 * Class DealContact
 *
 * @package Bitrix24\SDK\Services\CRM\Deal\Service
 */
class DealContact extends AbstractService
{
    /**
     * Adds contact to specified deal.
     *
     * @link https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_add.php
     *
     * @param int  $dealId
     * @param int  $contactId
     * @param bool $isPrimary
     * @param int  $sort
     *
     * @return AddedItemResult
     * @throws TransportException
     * @throws BaseException
     */
    public function add(int $dealId, int $contactId, bool $isPrimary, int $sort = 100): AddedItemResult
    {
        return new AddedItemResult(
            $this->core->call(
                'crm.deal.contact.add',
                [
                    'id'     => $dealId,
                    'fields' => [
                        'CONTACT_ID' => $contactId,
                        'IS_PRIMARY' => $isPrimary,
                        'SORT'       => $sort,
                    ],
                ]
            )
        );
    }

    /**
     * Returns field descriptions for the deal-contact link used by methods of family crm.deal.contact.*
     *
     * @link  https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_fields.php
     * @return FieldsResult
     * @throws BaseException
     * @throws TransportException
     */
    public function fields(): FieldsResult
    {
        return new FieldsResult($this->core->call('crm.deal.contact.fields'));
    }

    /**
     * Returns a set of contacts, associated with the specified deal.
     *
     * @link https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_items_get.php
     *
     * @param int $dealId
     *
     * @return DealContactItemsResult
     * @throws BaseException
     * @throws TransportException
     */
    public function itemsGet(int $dealId): DealContactItemsResult
    {
        return new DealContactItemsResult(
            $this->core->call(
                'crm.deal.contact.items.get',
                [
                    'id' => $dealId,
                ]
            )
        );
    }

    /**
     * Clears a set of contacts, associated with the specified deal.
     *
     * @link https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_items_delete.php
     *
     * @param int $dealId
     *
     * @return DeletedItemResult
     * @throws BaseException
     * @throws TransportException
     */
    public function itemsDelete(int $dealId): DeletedItemResult
    {
        return new DeletedItemResult(
            $this->core->call(
                'crm.deal.contact.items.delete',
                [
                    'id' => $dealId,
                ]
            )
        );
    }

    /**
     * Set a set of contacts, associated with the specified seal.
     *
     * @link https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_items_set.php
     *
     * @param int $dealId
     * @param array<int, array{
     *   CONTACT_ID: int,
     *   SORT: int,
     *   IS_PRIMARY: string,
     *   }> $contactItems
     *
     * @return UpdatedItemResult
     * @throws BaseException
     * @throws TransportException
     */
    public function itemsSet(int $dealId, array $contactItems): UpdatedItemResult
    {
        return new UpdatedItemResult(
            $this->core->call(
                'crm.deal.contact.items.set',
                [
                    'id'    => $dealId,
                    'items' => $contactItems,
                ]
            )
        );
    }

    /**
     * Deletes contact from a specified deal
     *
     * @link https://training.bitrix24.com/rest_help/crm/deals/crm_deal_contact_delete.php
     *
     * @param int $dealId
     * @param int $contactId
     *
     * @return DeletedItemResult
     * @throws BaseException
     * @throws TransportException
     */
    public function delete(int $dealId, int $contactId): DeletedItemResult
    {
        return new DeletedItemResult(
            $this->core->call(
                'crm.deal.contact.delete',
                [
                    'id'     => $dealId,
                    'fields' => [
                        'CONTACT_ID' => $contactId,
                    ],
                ]
            )
        );
    }
}


text:
/*
 * decaffeinate suggestions:
 * DS102: Remove unnecessary code created because of implicit returns
 * DS202: Simplify dynamic range loops
 * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
 */
const _ = require("lodash");
const Promise = require("es6-promise");
const timegrunt = require("time-grunt");
const fs = require("fs");
const path = require("path");
const webpackConfig = require("./webpack.config");
const webpackTestConfig = require("./webpack.test.config");

module.exports = function(grunt) {
  timegrunt(grunt);
  grunt.initConfig({
    pkg: grunt.file.readJSON("package.json"),
    htmlhint: {
      app: {
        options: {
          "tag-pair": true,
          "id-unique": true,
          "src-not-empty": true
        },
        src: ["public/index.html", "frontend/views/**/*.html"]
      }
    },
    webpack: {
      keepalive: false,
      options: {
        stats: (process.env.WEBPACK_ENV || "development") === "development"
      },
      app: webpackConfig,
      test: webpackTestConfig
    },
    eslint: {
      app: ["frontend/**/*.js"]
    },
    karma: {
      unit: {
        configFile: "karma.config.js"
      }
    },
    watch: {
      html: {
        files: ["public/index.html", "frontend/views/**/*.html"],
        tasks: ["htmlhint", "build:js", "test:js"]
      },
      js: {
        files: ["frontend/**/*.js"],
        tasks: ["build:js", "test:js"]
      },
      sass: {
        files: "frontend/scss/**/*.scss",
        tasks: ["sass", "build:js", "test:js"]
      },
      ruby: {
        files: [
          ".rubocop*.yml",
          "app.rb",
          "db/**/*.rb",
          "server/**/*.rb",
          "server/tests/**/*.phantom.js",
          "server/views/js.json",
          "Rakefile",
          "config.ru"
        ],
        tasks: ["bgShell:pumaRestart", "bgShell:rake"]
      }
    },
    bgShell: {
      pumaRestart: {
        cmd: "touch tmp/restart.txt",
        fail: true
      },
      rake: {
        cmd: `rm -f ${__dirname}/test.db && bundle exec rake`,
        fail: true,
        execOpts: {
          env: _.assign(_.cloneDeep(process.env), {
            LOG_LEVEL: "error",
            RACK_ENV: "test",
            COVERALLS_NOISY: "true"
          })
        }
      },
      shotgun: {
        cmd: `bundle exec puma config.ru -p ${process.env.PORT || 3001}`,
        bg: true
      }
    }
  });
  grunt.registerTask(
    "karma-simplecov-format",
    "transform karma coverage json into simplecov format",
    function() {
      const coverInFile = path.join(__dirname, "coverage", ".frontend.json");
      const coverOutFile = path.join(__dirname, "coverage", ".resultset.json");
      const done = this.async();
      const coverOut = new Promise(function(resolve, reject) {
        // https://github.com/colszowka/simplecov
        // { "Prog": { "coverage": { "file-path": [1,3,null,0] }, "timestamp": 1491185211 } }
        return fs.readFile(coverOutFile, "utf8", function(err, data) {
          if (err) {
            if (err.code === "ENOENT") {
              return resolve({});
            } else {
              return reject(err);
            }
          } else {
            return resolve(JSON.parse(data));
          }
        });
      });
      const coverIn = new Promise(function(resolve, reject) {
        // https://github.com/gotwarlost/istanbul
        // { "file-path": { "path": "file-path", "l": {"1": 3, "4": 0 } }
        return fs.readFile(coverInFile, "utf8", function(err, data) {
          if (err) {
            return reject(err);
          } else {
            let coverage;
            const covered = {};
            const object = JSON.parse(data);
            for (let file in object) {
              coverage = object[file];
              const knownLines = _.keys(coverage.l).sort((a, b) => +a - +b);
              const lastLine = +knownLines[knownLines.length - 1]; // 1-based index
              const results = new Array(lastLine);
              for (
                let i = 0, end = lastLine - 1, asc = 0 <= end;
                asc ? i <= end : i >= end;
                asc ? i++ : i--
              ) {
                results[i] = coverage.l[+i + 1];
                if (results[i] === undefined) {
                  results[i] = null;
                }
              }
              covered[file] = results;
            }
            return resolve({
              Karma: {
                timestamp: new Date().getTime() / 1000,
                coverage: covered
              }
            });
          }
        });
      });
      return Promise.all([coverIn, coverOut])
        .then(function(results) {
          const simplecov = results[1];
          simplecov.Karma = results[0].Karma;
          return fs.writeFile(
            coverOutFile,
            JSON.stringify(simplecov, null, " "),
            function(err) {
              if (err) {
                grunt.log.error("Failed to merge coverage info.");
                grunt.log.error(err);
                return done(false);
              } else {
                grunt.log.writeln("Merged coverage info.");
                return done();
              }
            }
          );
        })
        .catch(function(reason) {
          grunt.log.error("Failed to discern coverage info.");
          grunt.log.error(reason);
          return done(false);
        });
    }
  );

  grunt.loadNpmTasks("grunt-karma");
  grunt.loadNpmTasks("grunt-eslint");
  grunt.loadNpmTasks("grunt-contrib-watch");
  grunt.loadNpmTasks("grunt-htmlhint");
  grunt.loadNpmTasks("grunt-bg-shell");
  grunt.loadNpmTasks("grunt-webpack");
  grunt.registerTask("build:js", [
    "htmlhint",
    "eslint",
    "webpack:app",
    "webpack:test"
  ]);
  grunt.registerTask("build", ["build:js"]);
  grunt.registerTask("test:js", [
    "karma",
    "karma-simplecov-format",
    "bgShell:rake"
  ]);
  grunt.registerTask("test:server", ["bgShell:rake"]);
  grunt.registerTask("test", ["test:js", "test:server"]);
  grunt.registerTask("dist", ["build:js"]);
  return grunt.registerTask("default", [
    "build:js",
    "bgShell:shotgun",
    "watch"
  ]);
};


text:
<?php

class EF_Event_Options {

	public static $theme_options_group = 'event_framework';

	private static $theme_options = NULL;

	public function __construct() {
		add_action( 'wp_ajax_save_theme_options', array( $this, 'save_theme_options' ) );
		add_action( 'wp_head', array( __CLASS__, 'generate_css_rules' ), 88 );
	}

	public function save_theme_options() {
		if( isset( $_POST['data'] ) ) {
			$theme_options = apply_filters( 'ef_save_options_filter' , $_POST['data'] );
			$this->update_theme_options( $theme_options );
		}

		die();
	}

	private function update_theme_options( $theme_options ) {
		update_option( self::$theme_options_group , $theme_options );
	}

	public static function get_theme_options( $force = false ) {
		// Fetch DB only if the value isn't set or force is triggered
		if ( $force || is_null( self::$theme_options ) ) {
			// Read the DB options
			$db_options = get_option( self::$theme_options_group, array() );
			$theme_options = array();

			if ( empty( $db_options ) ) {
				return array();
			}
			// Convert the DB options to a more readable format
			foreach( $db_options['theme_options'] as $index => $data ) {
				if( false !== strpos( $data['name'], 'eventframework[' ) ) {
					// Strip the eventframework[...] wrapper
					$option_name = substr( $data['name'], 15, strlen( $data['name'] ) - 16 );

					// Regroup arrays if there is another level of depth
					if ( false !== strpos( $option_name , '][' ) ) {
						$option_fields = explode( '][' , $option_name );
						$theme_options[ $option_fields[0] ][ $option_fields[1] ] = $data['value'];
					} else {
						// Take care of simple fields, non-arrays
						$theme_options[ $option_name ] = $data['value'];
					}

				}
			}

			self::$theme_options = apply_filters( 'ef_get_theme_options_filter', $theme_options );
		}

		return self::$theme_options;
	}

	public static function get_theme_option( $option_name ) {
		$theme_options = self::get_theme_options();

		if ( ! isset( $theme_options[ $option_name ] ) ) {
			return '';
		}

		return $theme_options[ $option_name ];
	}

	public static function generate_css_rules() {

		if ( is_admin() ) {
			return;
		}

		$theme_options = self::get_theme_options();

		$all_fields = self::get_all_registered_panel_fields();

		$css_rules = array();
		foreach ( $all_fields as $field ) {
			if ( ! is_null( $field->selector ) ) {
				$css = array();

				// Merge old rules assigned to the same selector if any
				if ( ! empty( $css_rules[ $field->selector ] ) ) {
					$css = $css_rules[ $field->selector ];
				}

				$css_rules[ $field->selector ] = array_merge( $css, $field->get_css_rules() );
			}
		}

		echo '<style type="text/css">';
		foreach ( $css_rules as $selector => $rules_list ) {
			$rules = '';
			foreach ( $rules_list as $rule => $value ) {
				$rules .= sprintf( '%s: %s;', $rule, $value );
			}
			printf( '%s { %s } ', $selector, $rules );
		}
		echo '</style>';
	}

	/**
	 * Get all registered fields in a panel, flat model
	 *
	 * @param string $panel panel name
	 */
	public static function get_all_registered_panel_fields( $panel = 'theme_options' ) {
		global $ef_panel_manager;

		$all_fields = array();

		$theme_options = $ef_panel_manager->get_panel( $panel );

		$tabs = $theme_options->get_tabs();

		foreach( $tabs as $tab ) {
			$tab_fields = $tab->get_fields();
			$all_fields = array_merge( $all_fields, $tab_fields );
		}

		return apply_filters( 'ef_filter_all_fields_array', $all_fields );
	}
}

new EF_Event_Options();


text:
from datetime import datetime, timedelta
from django.core.management import BaseCommand

from corehq.apps.saved_reports.models import ReportNotification

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('domains', nargs='+')
        parser.add_argument('-F', '--forward', action='store_true')

    def handle(self, domains, forward=False, *args, **kwargs):
        for domain in domains:
            print(f'processing domain: {domain}')
            reports = get_reports_by_domain(domain)

            for report in reports:
                previous_hour = report.hour
                report = adjust_report(report, forward)
                report.save()
                print(f'Updated hour on report {report._id} from {previous_hour} to {report.hour}')

def get_reports_by_domain(domain):
    key = [domain]
    reports = ReportNotification.view('reportconfig/user_notifications',
        reduce=False, include_docs=True, startkey=key, endkey=key + [{}])
    return reports

DAYS_IN_WEEK = 7

def adjust_report(report, forward=False):
    day = report.day + 1 if report.interval == 'weekly' else report.day  # account for 0-indexed days
    trigger_time = datetime.now().replace(hour=report.hour, minute=report.minute, day=day)

    if forward:
        trigger_time += timedelta(hours=1)
    else:
        trigger_time -= timedelta(hours=1)

    report.hour = trigger_time.hour
    if report.interval == 'weekly':
        report.day = (trigger_time.day - 1) % DAYS_IN_WEEK
    elif report.interval == 'monthly':
        report.day = trigger_time.day

    return report


text:
print '==> downloading dataset'

-- Here we download dataset files.

-- Note: files were converted from their original Matlab format
-- to Torch's internal format using the mattorch package. The
-- mattorch package allows 1-to-1 conversion between Torch and Matlab
-- files.

-- The SVHN dataset contains 3 files:
--    + train: training data
--    + test:  test data
--    + extra: extra training data

tar = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/svhn.t7.tgz'

if not paths.dirp('housenumbers') then
   os.execute('wget ' .. tar)
   os.execute('tar xvf ' .. paths.basename(tar))
end

train_file = 'housenumbers/train_32x32.t7'
test_file = 'housenumbers/test_32x32.t7'
extra_file = 'housenumbers/extra_32x32.t7'

----------------------------------------------------------------------
print '==> loading dataset'

-- We load the dataset from disk, and re-arrange it to be compatible
-- with Torch's representation. Matlab uses a column-major representation,
-- Torch is row-major, so we just have to transpose the data.

-- Note: the data, in X, is 4-d: the 1st dim indexes the samples, the 2nd
-- dim indexes the color channels (RGB), and the last two dims index the
-- height and width of the samples.

loaded = torch.load(train_file,'ascii')
trainData = {
   data = loaded.X:transpose(3,4),
   labels = loaded.y[1],
   size = function() return trsize end
}

loaded = torch.load(extra_file,'ascii')
extraTrainData = {
   data = loaded.X:transpose(3,4),
   labels = loaded.y[1],
   size = function() return trsize end
}

loaded = torch.load(test_file,'ascii')
testData = {
   data = loaded.X:transpose(3,4),
   labels = loaded.y[1],
   size = function() return tesize end
}

trainData.data=trainData.data:float():div(256)
--train_mean=trainData.data:mean(1)
--train_std=trainData.data:std()
--print(train_mean)
--print('train std'..train_std)
--trainData.data:add(-train_mean:expandAs(trainData.data)):mul(1/train_std)

testData.data=testData.data:float():div(256)
--test_mean=testData.data:mean(1)
--test_std=testData.data:std()
--print(test_mean)
--print('test std'..test_std)
--testData.data:add(-test_mean:expandAs(testData.data)):mul(1/test_std)

set={}
set.trainData=trainData
set.testData=testData
torch.save('svhn_div256.dat',set)
----------------------------------------------------------------------
print '==> visualizing data'

-- Visualization is quite easy, using itorch.image().
if itorch then
   print('training data:')
   itorch.image(trainData.data[{ {1,256} }])
   print('extra training data:')
   itorch.image(extraTrainData.data[{ {1,256} }])
   print('test data:')
   itorch.image(testData.data[{ {1,256} }])
end


text:
package demo.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * ClassName:DateTimeUtil
 * 类描述:   日期工具类
 * 操作人:wangshuang
 * 操作时间:2015-5-26 下午05:52:42
 *
 * @version 1.0
 */
public class DateTimeUtil {

    public static final String PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static String getDateTimeByHour(long time) {
        DateFormat formatHour = new SimpleDateFormat("yyyyMMddHH");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        return formatHour.format(c.getTime());
    }

    public static String getDateTimeByDay(long time) {
        DateFormat formatHour = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        return formatHour.format(c.getTime());
    }

    public static String getDateTime(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        return format.format(c.getTime());
    }

    public static String getDateTime(long time, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        return format.format(c.getTime());
    }

    public static long add(long time, int field, int amount) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        c.add(field, amount);

        return c.getTimeInMillis();
    }

    public static long parse(String dateTime, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        try {
            Date date = format.parse(dateTime);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;

    }

    public static long currentTimeByHour() {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTimeInMillis();
    }

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

    public static long getDateByDay(long time) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        return c.getTimeInMillis();
    }

}


text:
<?php
$query = siteorigin_widget_post_selector_process_query( $instance['posts'] );
$the_query = new WP_Query( $query );
?>

<?php if($the_query->have_posts()) : ?>

		<?php echo $args['before_title'] . esc_html($instance['title']) . $args['after_title'] ?>

		<a href="#" class="sow-carousel-next" title="<?php esc_attr_e('Next', 'siteorigin-widgets') ?>">
		<a href="#" class="sow-carousel-previous" title="<?php esc_attr_e('Previous', 'siteorigin-widgets') ?>">

	<div class="sow-carousel-wrapper"
		data-query="<?php echo esc_attr(json_encode( $query )) ?>"
		data-ajax-url="<?php echo esc_url( admin_url('admin-ajax.php') ) ?>"
		>

			<?php while($the_query->have_posts()) : $the_query->the_post(); ?>

						<?php if( has_post_thumbnail() ) : $img = wp_get_attachment_image_src(get_post_thumbnail_id(), 'sow-carousel-default'); ?>
							<a href="<?php the_permalink() ?>" style="background-image: url(<?php echo esc_url($img[0]) ?>)">

						<?php else : ?>
							<a href="<?php the_permalink() ?>" class="sow-carousel-default-thumbnail">
						<?php endif; ?>

<a href="<?php the_permalink() ?>"><?php the_title() ?>

			<?php endwhile; wp_reset_postdata(); ?>

<?php endif; ?>


text:
Overview
========

.. role:: usertype
    :class: usertype

The scripts in this directory perform tasks intended to stand up a full VistA
instance in a fresh RHEL based or Ubuntu based Linux environment.

Vagrant Integration
===================

Vagrant has been integrated for GTM/Ubuntu. Goto the Scripts/Install/Ubuntu
directory and type "vagrant up" to provision a new Virtual Machine (VM) running
Ubuntu 12.04 LTS and GTM 6.x automatically. This procedure also performs a
"dashboard" build which runs the current OSEHRA testing suite for VistA and
submits it to the dashboard_. This will take over an hour to complete.

Bootstrapping
=============

The bootstrap scripts install basic packages require for VistA to function and
update the distro to the latest version.

RHEL:

.. parsed-literal::

    ~/Development/VistA$ :usertype:`Scripts/Install/RHEL/bootstrapRHELserver.sh`

Ubuntu:

.. parsed-literal::
    ~/Development/VistA$ :usertype:`sudo Scripts/Install/Ubuntu/bootstrapUbuntuserver.sh`

Install M environment
=====================

There are scripts for Intersystems Caché and Fidelity Information Systems GT.M
included in the Cache and GTM folders respectively.

Since each M implementation requires different steps to prepare the environment
the steps will vary slightly.

GT.M
----

You must change into the GTM directory (Scripts/Install/GTM) before running the
scripts.

    1. sudo install.sh
    2. sudo createVistaInstance.sh

Caché
-----

This is currently a work in progress. The scripts function but makes lots of
assumptions about the environment. Customization of these scripts will be
required for them to work.

Change into the Cache directory (Scripts/Install/Cache) before running the
scripts.

    1. createDaemonAccount.sh
    2. configureFirewall.sh
    3. install.sh

Repository Directory Layout
===========================

* Scripts/Install/Cache - Contains all scripts specific to the Caché M
  environment

    * etc/init.d - init scripts specific to Caché

* Scripts/Install/Common - Contains all scripts not specific to any M
  environment

* Scripts/Install/Dashboard - Scripts for submitting to the OSEHRA Dashboard

    * Scripts are experimental quality

* Scripts/Install/GTM - Contains all scripts specific to the GT.M M environment

    * etc/init.d - init script to start VistA upon system boot
    * etc/xinetd.d - scripts for RPC broker and VistALink
    * bin - scripts for VistA services

* Scripts/Install/RHEL - Contains all scripts specific to RHEL based Linux
  distros

    * CentOS is the primary platform used by developers for testing

* Scripts/Install/Ubuntu - Contains all scripts specific to Ubuntu based Linux
  distros

    * Ubuntu 12.04 LTS is the primary platform used by developers for testing

VistA Directory Layout
======================

GT.M
----

$instance is the name of the VistA environment being installed. Currently
hard-coded to FOIA

* /home/$instance - Root directory for VistA environment

    * bin - Scripts specific to this VistA environment

        * prog.sh - Programmer mode script. Dumps user to $instance>
        * tied.sh - Regular user script. Forces user into ^ZU

    * etc - Configuration files for VistA environment

        * db.gde - Script to create GT.M Global Directory
        * env - Setup environment variables for this VistA environment
        * xinetd.d - Scripts copied from Scripts/Install/GTM/xinetd.d directory
        * init.d - Scripts copied from Scripts/Install/GTM/etc/init.d directory

    * log - Setup as the GT.M log directory and contains logs from xinetd
      scripts

    * lib - stores symlinks to any libraries used by this installation

    * r - Routines from source VistA distribution

    * r/$gtmver - Stores object files per GT.M version

    * tmp - Used for VistA temp files

    * g - contains the GT.M .gld and .dat for the VistA environment

    * j - contains the journals for the VistA environment

Caché
-----

This is a work in progress. The goal is to use similar structures for GT.M and
Caché where appropriate.

* /opt/$instance - Root directory for the VistA environment $instance is
  hard-coded to cacheprod for now.

    * bin - Scripts specific to this VistA environment

        * prog.sh - Programmer mode script. Dumps user to $namespace>
        * tied.sh - Regular user script. Forces user into ^ZU

    * etc - Configuration files for VistA environment

        * xinetd.d - Scripts copied from common folder in the repository
        * init.d - Scripts copied from Cache/etc/init.d in the repository

    * log - contains logs from xinetd scripts

    * $cachever - Example $cachever: 2011.1.2.701. Used to store items specific
      to a Caché version

        * g - contains the CACHE.DAT for the VistA environment
        * j - contains the journals for the VistA environment

.. _dashboard: http://code.osehra.org/CDash/index.php?project=Open+Source+EHR


text:
JoinChannelCommand::JoinChannelCommand(
		IRequestResponseManagerPtr responseManager,
		core::IDisplayerPtr displayer,
		core::IQueueHandlerPtr queueHandler,
		core::ClientDataPtr clientData)
	: _responseManager(responseManager),
	  _displayer(displayer),
	  _queueHandler(queueHandler),
	  _clientData(clientData)
{

}

JoinChannelCommand::~JoinChannelCommand()
{

}

void JoinChannelCommand::handle(std::string input)
{
	if (_clientData->Id < 1)
	{
		_displayer->displayLine("You must be connected first");
		return;
	}

	auto tokens = core::utils::tokenize(input, " \t");

	auto countOfParams = core::utils::getTokensCount(tokens);

	if (countOfParams != 1)
	{
		_displayer->displayLine("Invalid count of parameters, see #help");
		return;
	}

	_responseManager->registerResponseType(_clientData->RequestId ,getResponseCommand());

	rapidjson::Document document;
	document.SetObject();

	document.AddMember("request", "join_channel", document.GetAllocator());

	_clientData->Channel = *tokens.begin();

	document.AddMember("channel_name", rapidjson::Value().SetString(tokens.begin()->c_str(), tokens.begin()->length()), document.GetAllocator());
	document.AddMember("request_id",  rapidjson::Value().SetInt(_clientData->RequestId++), document.GetAllocator());
	document.AddMember("user_id",  rapidjson::Value().SetInt(_clientData->Id), document.GetAllocator());

	rapidjson::StringBuffer buffer;
	rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
	document.Accept(writer);

	_queueHandler->send(1, std::string(buffer.GetString()));
}

void JoinChannelCommand::handleResponse(rapidjson::Document& response)
{
	if(!core::utils::checkFields(response, {"status", "channel_created"}))
	{
		_displayer->displayLine("Some field are missing [join channel response]");
		return;
	}

	if (std::string("OK").compare(response["status"].GetString()) == 0)
	{
		_displayer->displayLine(core::utils::format(
					{"You successfully join channel %1% %2%",
					_clientData->Channel,
					response["channel_created"].GetBool() ? "(You create that channel)" : "" }));
	}
	else
	{
		_clientData->Channel = "";
		_displayer->displayLine("Error in message from server [join channel]");
	}
}

std::string JoinChannelCommand::getCommand()
{
	return "#join";
}

std::string JoinChannelCommand::getResponseCommand()
{
	return "#join_response";
}

std::string JoinChannelCommand::getInfo()
{
	return "#join <channelName> [joins <channelName> (if not exists, create channel with provided <channelName>)]";
}


text:
[![Join the chat at https://gitter.im/angular/angular-cli](https://badges.gitter.im/angular/angular-cli.svg)](https://gitter.im/angular/angular-cli?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![Build Status][travis-badge]][travis-badge-url]
[![Dependency Status][david-badge]][david-badge-url]
[![devDependency Status][david-dev-badge]][david-dev-badge-url]
[![npm][npm-badge]][npm-badge-url]

Prototype of a CLI for Angular 2 applications based on the [ember-cli](http://www.ember-cli.com/) project.

## Note

This project is very much still a work in progress.

We still have a long way before getting out of our alpha stage.
If you wish to collaborate while the project is still young, check out [our issue list](https://github.com/angular/angular-cli/issues).

## Prerequisites

The generated project has dependencies that require **Node 4 or greater**.

## Table of Contents

* [Installation](#installation)
* [Usage](#usage)
* [Generating a New Project](#generating-and-serving-an-angular2-project-via-a-development-server)
* [Generating Components, Directives, Pipes and Services](#generating-other-scaffolds)
* [Generating a Route](#generating-a-route)
* [Creating a Build](#creating-a-build)
* [Running Unit Tests](#running-unit-tests)
* [Running End-to-End Tests](#running-end-to-end-tests)
* [Deploying the App via GitHub Pages](#deploying-the-app-via-github-pages)
* [Support for offline applications](#support-for-offline-applications)
* [Commands autocompletion](#commands-autocompletion)
* [Known Issues](#known-issues)

## Installation

**BEFORE YOU INSTALL:** please read the [prerequisites](#prerequisites)
```bash
npm install -g angular-cli
```

## Usage

```bash
ng --help
```

### Generating and serving an Angular2 project via a development server

```bash
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
```
Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

You can configure the default HTTP port and the one used by the LiveReload server with two command-line options :

```bash
ng serve --port 4201 --live-reload-port 49153
```

### Generating other scaffolds

You can use the `ng generate` (or just `ng g`) command to generate Angular components:

```bash
ng generate component my-new-component
ng g component my-new-component # using the alias

# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
```
You can find all possible blueprints in the table below:

Scaffold  | Usage
---       | ---
Component | `ng g component my-new-component`
Directive | `ng g directive my-new-directive`
Pipe      | `ng g pipe my-new-pipe`
Service   | `ng g service my-new-service`

### Generating a route

You can generate a new route by with the following command (note the singular
used in `hero`):

```bash
ng generate route hero
```

This will create a folder with a routable component (`hero-root.component.ts`)
with two sub-routes. The file structure will be as follows:

```
...
|-- app
|   |-- hero
|   |   |-- hero-detail.component.html
|   |   |-- hero-detail.component.css
|   |   |-- hero-detail.component.spec.ts
|   |   |-- hero-detail.component.ts
|   |   |-- hero-list.component.html
|   |   |-- hero-list.component.css
|   |   |-- hero-list.component.spec.ts
|   |   |-- hero-list.component.ts
|   |   |-- hero-root.component.spec.ts
|   |   |-- hero-root.component.ts
|   |   |-- hero.service.spec.ts
|   |   |-- hero.service.ts
|   |-- ...
|-- app.ts
...
```

Afterwards to use the new route open your main app component, import
`hero-root.component.ts` and add it in the route config:

```
@RouteConfig([
  {path:'/hero/...', name: 'HeroRoot', component: HeroRoot}
])
```

Visiting `http://localhost:4200/hero` will show the hero list.

### Creating a build

```bash
ng build
```

The build artifacts will be stored in the `dist/` directory.

### Running unit tests

```bash
ng test
```

Tests will execute after a build is executed via [Karma](http://karma-runner.github.io/0.13/index.html)

If run with the watch argument `--watch` (shorthand `-w`) builds will run when source files have changed
and tests will run after each successful build

### Running end-to-end tests

```bash
ng e2e
```

Before running the tests make sure you are serving the app via `ng serve`.

End-to-end tests are ran via [Protractor](https://angular.github.io/protractor/).

### Deploying the app via GitHub Pages

The CLI currently comes bundled with [angular-cli-github-pages addon](https://github.com/IgorMinar/angular-cli-github-pages).

This means that you can deploy your apps quickly via:

```
git commit -a -m "final tweaks before deployment - what could go wrong?"
ng github-pages:deploy
```

Checkout [angular-cli-github-pages addon](https://github.com/IgorMinar/angular-cli-github-pages) docs for more info.

### Linting and formatting code

You can lint or format your app code by running `ng lint` or `ng format` respectively.
This will use the `lint`/`format` npm script that in generated projects uses `tslint`/`clang-format`.

You can modify the these scripts in `package.json` to run whatever tool you prefer.

### Formatting code

You can format your app code by running `ng format`.
This will use the `format` npm script that in generated projects uses `clang-format`.

You can modify the `format` script in `package.json` to run whatever formatting tool
you prefer and `ng format` will still run it.

### Support for offline applications

By default a file `manifest.appcache` will be generated which lists all files included in
a project's output, along with SHA1 hashes of all file contents. This file can be used
directly as an AppCache manifest (for now, `index.html` must be manually edited to set this up).

The manifest is also annotated for use with `angular2-service-worker`. Some manual operations
are currently required to enable this usage. The package must be installed, and `worker.js`
manually copied into the project `src` directory:

```bash
npm install angular2-service-worker
cp node_modules/angular2-service-worker/dist/worker.js src/
```

 Then, the commented snippet in `index.html` must be uncommented to register the worker script
 as a service worker.

### Commands autocompletion

To turn on auto completion use the following commands:

For bash:
```bash
ng completion >> ~/.bashrc
source ~/.bashrc
```

For zsh:
```bash
ng completion >> ~/.zshrc
source ~/.zshrc
```

Windows users using gitbash:
```bash
ng completion >> ~/.bash_profile
source ~/.bash_profile
```

## Known issues

This project is currently a prototype so there are many known issues. Just to mention a few:

- All blueprints/scaffolds are in TypeScript only, in the future blueprints in all dialects officially supported by Angular will be available.
- On Windows you need to run the `build` and `serve` commands with Admin permissions, otherwise the performance is not good.
- [Protractor](https://angular.github.io/protractor/) integration is missing.
- The initial installation as well as `ng new` take too long because of lots of npm dependencies.
- Many existing ember addons are not compatible with Angular apps built via angular-cli.
- When you `ng serve` remember that the generated project has dependencies that require **Node 4 or greater**.

## Development Hints for hacking on angular-cli

### Working with master

```bash
git clone https://github.com/angular/angular-cli.git
cd angular-cli
npm link
```

`npm link` is very similar to `npm install -g` except that instead of downloading the package
from the repo, the just cloned `angular-cli/` folder becomes the global package.
Any changes to the files in the `angular-cli/` folder will immediately affect the global `angular-cli` package,
allowing you to quickly test any changes you make to the cli project.

Now you can use `angular-cli` via the command line:

```bash
ng new foo
cd foo
npm link angular-cli
ng server
```

`npm link angular-cli` is needed because by default the globally installed `angular-cli` just loads
the local `angular-cli` from the project which was fetched remotely from npm.
`npm link angular-cli` symlinks the global `angular-cli` package to the local `angular-cli` package.
Now the `angular-cli` you cloned before is in three places:
The folder you cloned it into, npm's folder where it stores global packages and the `angular-cli` project you just created.

Please read the official [npm-link documentation](https://www.npmjs.org/doc/cli/npm-link.html)
and the [npm-link cheatsheet](http://browsenpm.org/help#linkinganynpmpackagelocally) for more information.

## License

MIT

[travis-badge]: https://travis-ci.org/angular/angular-cli.svg?branch=master
[travis-badge-url]: https://travis-ci.org/angular/angular-cli
[david-badge]: https://david-dm.org/angular/angular-cli.svg
[david-badge-url]: https://david-dm.org/angular/angular-cli
[david-dev-badge]: https://david-dm.org/angular/angular-cli/dev-status.svg
[david-dev-badge-url]: https://david-dm.org/angular/angular-cli#info=devDependencies
[npm-badge]: https://img.shields.io/npm/v/angular-cli.svg
[npm-badge-url]: https://www.npmjs.com/package/angular-cli