text:
"""
Create of grid of scatter plots with confidence ellipses from the statecrime
dataset
"""

import matplotlib.pyplot as plt

import statsmodels.api as sm
from statsmodels.graphics.plot_grids import scatter_ellipse

data = sm.datasets.statecrime.load_pandas().data
fig = plt.figure(figsize=(8, 8))
scatter_ellipse(data, varnames=data.columns, fig=fig)
plt.show()


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.navigationToolbar.ui;

import com.intellij.util.ui.StartupUiUtil;
import org.jetbrains.annotations.ApiStatus;

/**
 * @author Konstantin Bulenkov
 */
public class NavBarUIManager {
  public static final NavBarUI COMMON = new CommonNavBarUI();
  /**
   * @deprecated will be removed in 2020.1
   */
  @ApiStatus.ScheduledForRemoval(inVersion = "2020.1")
  @Deprecated
  public static final NavBarUI AQUA = COMMON;
  public static final NavBarUI DARCULA = new DarculaNavBarUI();

  public static NavBarUI getUI() {
    if (StartupUiUtil.isUnderDarcula()) return DARCULA;
    return COMMON;
  }
}

redpajama_set_name: RedPajamaGithub


text:
install: all
	cp SLOCounter.out /usr/local/bin/SLOCounter

all: main.cpp fileparser.o
	g++ -Wall -o SLOCounter.out main.cpp fileparser.o

fileparser.o: fileparser.cpp fileparser.hpp
	g++ -Wall -o fileparser.o -c fileparser.cpp

clean:
	rm *.o


text:
import argparse
import subprocess
import os
from pathlib import Path
from copy import deepcopy
import time
parser = argparse.ArgumentParser(description='Gathers failed simulations')
parser.add_argument('-l', '--logdir', type=str, help='Search for log files in directory', default='logs')
parser.add_argument('-o', '--outdir', type=str, help='Save results in directory', default='failed')
parser.add_argument('-J', '--jobname', type=str, help='Filter by jobname', default=None)
parser.add_argument('-S', '--start', type=str, help='Consider jobs started after this date', default=None)
parser.add_argument('-E', '--end', type=str, help='Consider jobs that ended before this date', default=time.strftime('%Y-%m-%dT%H:%M:%S'))
parser.add_argument('-L', '--logscan', action='store_true', help='Scan through logs instead of using sacct')
parser.add_argument('-f', '--failfile', type=str, help='Save list of jobids with failed simulations to this file', default='failed_jobs.txt')
parser.add_argument('-r', '--resfile', type=str, help='Save results, i.e. a list of cfg-seed pairs, to this file', default='resume.job')
parser.add_argument('-u', '--user', type=str, help='Call sacct for this user', default=os.getlogin())

args = parser.parse_args()

if args.outdir:
    Path(args.outdir).mkdir(parents=True, exist_ok=True)

def getlines(file, linelist):
  return [x for i, x in enumerate(file) if i in map(int,linelist)]

# Gather job-id's that may contain failed jobs. Remember, 1 job-id can correspond to a job-array
# which may contain many simulations (seeds)
joblist = []
jobitem = {
    'jobid': None,
    'jobidraw': None,
    'jobname' : None,
    'exitcode': None,
    'outfile' : None,
}

with open("{}/{}".format(args.outdir, args.failfile), "w") as output:
    sacct_command = ["sacct","-X", "--parsable2", "--noheader", '--format=jobid,jobidraw,jobname,exitcode,state']
    if args.logscan:
        sacct_command.append("--state=oom,failed,timeout,deadline,node_fail,completed")
    else:
        sacct_command.append("--state=oom,failed,timeout,deadline,node_fail")

    sacct_command.extend(["-u", args.user])
    if args.jobname:
        sacct_command.extend(['--name',args.jobname])
    if args.start:
        sacct_command.extend(["-S", args.start])
    if args.end:
        sacct_command.extend(["-E", args.end])

    with subprocess.Popen(sacct_command,bufsize=1, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8') as p:
        for out in p.stdout:
            print(out, end='')  # process line here
            if out and not out.isspace():
                output.write(out)
                line = out.split('|')
                item = {}
                item['jobid']    = line[0]
                item['jobidraw'] = line[1]
                item['jobname'] = line[2]
                item['exitcode'] = line[3]
                item['outfile'] = '{}/{}-{}.out'.format(args.logdir,line[2], line[0]) # This needs to match the sbatch file
                joblist.append(item)

        print("Command:", ' '.join(p.args))
        if p.returncode != 0 and p.returncode != None:
            raise subprocess.CalledProcessError(p.returncode, ' '.join(p.args))

with open("{}/{}".format(args.outdir,args.resfile), "w") as resfile:
    print('Creating resume file:', resfile)
count = 0
for jobitem in joblist:
    if not os.path.isfile(jobitem['outfile']):
        raise FileNotFoundError("File does not exist: {}".format(jobitem['outfile']))

    # Found a logfile that may contain a failed simulation (or not, if doing logscan)
    with open(jobitem['outfile'], "r") as log, open("{}/{}".format(args.outdir,args.resfile), "a") as resfile:
        cfgline = None
        sequence = None
        jobfile = None
        success = set([])
        jobid   = None
        for line in log:
            if not line.startswith(('JOB ID', 'JOB FILE', 'EXIT', 'TASK ID SEQUENCE')):
                continue
            keyval = [item.strip() for item in line.split(':',1)]
            if keyval[0] == 'JOB FILE':
                jobfile = keyval[1] # Contains the array jobarray chunk file.
            if keyval[0] == 'TASK ID SEQUENCE':
                sequence = set(map(int,keyval[1].split(' ')))
            if keyval[0] == 'JOB ID':
                jobid = int(keyval[1])
            if keyval[0] == "EXIT CODE" and keyval[1] == "0":
                success.add(jobid)

        # We can now compare the ids in the task id sequence that should have run,
        # to the ones that actually suceeded.
        failed = sequence - success

        # We can now extract the config lines that should have executed
        cfglines = getlines(open(jobfile,"r"), failed)
        for cfgline in cfglines:
            print("Found failed simulation | exit {:>3} | {}".format(keyval[1],cfgline), end='')
            resfile.write("{}".format(cfgline))
            count = count + 1
#
#             if keyval[0] == 'CONFIG LINE' or keyval[0] == 'JOB FILE LINE(S)':
#                 cfgline = keyval[1]
#             if keyval[0] == "EXIT CODE" and keyval[1] != "0":
#                 if not cfgline:
#                     raise Exception('cfgline is empty')
#                 print("Found failed simulation | exit {:>3} | {}".format(keyval[1],cfgline))
#                 resfile.write("{}\n".format(cfgline))
#                 count = count + 1

print('Found {} jobids'.format(len(joblist)))
print('Found {} failed simulations'.format(count))


text:
ConvertFrom-StringData @'
    UsingGetCimInstanceToFetchDriveLetter = Using Get-CimInstance to get the drive letter of optical disk {0} in the system.
    OpticalDiskAssignedDriveLetter = The optical disk {0} is currently assigned drive letter '{1}'.
    OpticalDiskNotAssignedDriveLetter = The optical disk {0} is not currently assigned a drive letter.
    NoOpticalDiskDriveError = The optical disk {0} could not be found in the system, so this resource has nothing to do. This resource does not change the drive letter of mounted ISOs.

    AttemptingToSetDriveLetter = The optical disk {0} drive letter is '{1}', attempting to set to '{2}'.
    AttemptingToRemoveDriveLetter = The optical disk {0} drive letter is '{1}', attempting to remove it.

    DriveLetterDoesNotExistAndShouldNot = The optical disk {0} does not have a drive letter assigned. Change not required.
    DriveLetterExistsButShouldNot = The optical disk {0} is assigned the drive letter '{1}' which should be removed. Change required.
    DriverLetterExistsAndIsCorrect = The optical disk {0} is assigned the drive letter '{1}' which is correct. Change not required.
    DriveLetterAssignedToAnotherDrive = Drive letter '{0}' is already present but assigned to a another volume. Change can not proceed.
    DriverLetterExistsAndIsNotCorrect = The optical disk {0} is assigned the drive letter '{1}' but should be '{2}'. Change required.
'@


text:
namespace content {

// A BackgroundSyncContextImpl for use in unit tests, primarily to create a test
// BackgroundSyncManager.
class TestBackgroundSyncContext : public BackgroundSyncContextImpl {
 public:
  TestBackgroundSyncContext() = default;

 protected:
  ~TestBackgroundSyncContext() override = default;

  // BackgroundSyncContextImpl:
  void CreateBackgroundSyncManager(
      scoped_refptr<ServiceWorkerContextWrapper> service_worker_context,
      scoped_refptr<DevToolsBackgroundServicesContextImpl> devtools_context)
      override;

 private:
  DISALLOW_COPY_AND_ASSIGN(TestBackgroundSyncContext);
};

}  // namespace content

#endif  // CONTENT_TEST_TEST_BACKGROUND_SYNC_CONTEXT_H_


text:
package dk.brics.tajs.analysis.dom.core;

import dk.brics.tajs.analysis.InitialStateBuilder;
import dk.brics.tajs.analysis.PropVarOperations;
import dk.brics.tajs.analysis.Solver;
import dk.brics.tajs.analysis.dom.DOMObjects;
import dk.brics.tajs.analysis.dom.DOMWindow;
import dk.brics.tajs.lattice.ObjectLabel;
import dk.brics.tajs.lattice.State;
import dk.brics.tajs.lattice.Value;

import static dk.brics.tajs.analysis.dom.DOMFunctions.createDOMProperty;

/**
 * The Touch interface represents a single contact point on a touch-sensitive device.
 */
public class DOMTouch {

    public static ObjectLabel CONSTRUCTOR;

    public static ObjectLabel PROTOTYPE;

    public static ObjectLabel INSTANCES;

    public static void build(Solver.SolverInterface c) {
        State s = c.getState();
        PropVarOperations pv = c.getAnalysis().getPropVarOperations();
        CONSTRUCTOR = ObjectLabel.make(DOMObjects.TOUCH_CONSTRUCTOR, ObjectLabel.Kind.FUNCTION);
        PROTOTYPE = ObjectLabel.make(DOMObjects.TOUCH_PROTOTYPE, ObjectLabel.Kind.OBJECT);
        INSTANCES = ObjectLabel.make(DOMObjects.TOUCH_INSTANCES, ObjectLabel.Kind.OBJECT);

        // Constructor Object
        s.newObject(CONSTRUCTOR);
        pv.writePropertyWithAttributes(CONSTRUCTOR, "length", Value.makeNum(0).setAttributes(true, true, true));
        pv.writePropertyWithAttributes(CONSTRUCTOR, "prototype", Value.makeObject(PROTOTYPE).setAttributes(true, true, true));
        s.writeInternalPrototype(CONSTRUCTOR, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));
        pv.writeProperty(DOMWindow.WINDOW, "Touch", Value.makeObject(CONSTRUCTOR));

        // Prototype object.
        s.newObject(PROTOTYPE);
        s.writeInternalPrototype(PROTOTYPE, Value.makeObject(InitialStateBuilder.OBJECT_PROTOTYPE));

        // Multiplied object
        s.newObject(INSTANCES);
        s.writeInternalPrototype(INSTANCES, Value.makeObject(PROTOTYPE));

         /*
         * Properties.
         */
        createDOMProperty(PROTOTYPE, "identifier", Value.makeAnyStr().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "screenX", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "screenY", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "clientX", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "clientY", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "pageX", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "pageY", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "radiusX", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "radiusY", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "rotationAngle", Value.makeAnyNum().setReadOnly(), c);
        createDOMProperty(PROTOTYPE, "force", Value.makeAnyNum().setReadOnly(), c);

        INSTANCES = INSTANCES.makeSingleton().makeSummary();
    }

}


text:
@interface ViewController : UIViewController{

	IBOutlet UIImageView *yourImage;
	IBOutlet UIImageView *aiImage;
	IBOutlet UILabel *result;
	IBOutlet UIView *viewBackground;
	IBOutlet UILabel *aiScore;
	IBOutlet UILabel *yourScore;
}
- (IBAction)rock:(id)sender;
- (IBAction)paper:(id)sender;
- (IBAction)scissors:(id)sender;

@end


text:
import { NgRedux } from 'ng2-redux';
import { WhmService, WhModel } from './../wh.service';
import {
  inject,
  TestBed
} from '@angular/core/testing';
import { Component } from '@angular/core';
import {
  BaseRequestOptions,
  ConnectionBackend,
  Http
} from '@angular/http';
import { MockBackend } from '@angular/http/testing';

// Load the implementations that should be tested
import { AppState } from '../app.service';
import { HomeComponent } from './home.component';

xdescribe('Home', () => {
  // provide our implementations or mocks to the dependency injector
  beforeEach(() => TestBed.configureTestingModule({
    providers: [
      BaseRequestOptions,
      MockBackend,
      {
        provide: Http,
        useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
          return new Http(backend, defaultOptions);
        },
        deps: [MockBackend, BaseRequestOptions]
      },
      WhmService, WhModel,
      NgRedux,
      HomeComponent
    ]
  }));

  it('should log ngOnInit', inject([ HomeComponent, WhModel, NgRedux ],
      (home: HomeComponent, _whm: WhmService, _ngRedux: NgRedux<any>) => {
    spyOn(console, 'log');
    expect(console.log).not.toHaveBeenCalled();

    home.ngOnInit();
    expect(console.log).toHaveBeenCalled();
  }));

});


text:
package com.sap.webi.sample;

import com.sap.webi.sample.model.InfoObject;

/**
 * Test Web Intelligence RESTful API (Raylight) using CXF Web Client API (Apache CXF Specific).
 *
 * @author Anthony MÜLLER
 */
public class GetData {

	private final static String BI4_API_ROOT_URL = "http://localhost:6405/biprws";

	private final static String FORMATTING_SAMPLE_CUID = "AQtkbbSqN4NOj3ydf.Sw1lY";

	private final static String USER = "Administrator";
	private final static String PASSWORD = "Password1";

	public static void main(String[] args) {

		final BI4EndPoint bi4 = new BI4EndPoint(BI4_API_ROOT_URL);
		bi4.logon(USER, PASSWORD);

		// Get data from a dataprovider and print it out
		String dpData = getDataFromDataProvider(
			bi4.getLogonToken(), 		// a valid logon token
			FORMATTING_SAMPLE_CUID, 	// a Webi document CUID
			"DP1", 						// a dataprovider id
			0,							// a flow id
			"xml"						// an output format (txt or xml). default is txt.
		);
		System.out.println(dpData);

		// Get data from a report part and print it out
		String rpData = getDataFromReportPart(
			bi4.getLogonToken(), 		// a valid logon token
			FORMATTING_SAMPLE_CUID, 	// a Webi document CUID
			3, 							// a report id
			13,							// a element id
			"xml"						// an output format (json or xml). default is json.
		);
		System.out.println(rpData);

		bi4.logoff();
	}

	/**
	 * Get data from a data provider.
	 *
	 * @param logonToken
	 * @param documentCuid
	 * @param dpId
	 * @param flowId
	 * @param format
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromDataProvider(String logonToken, String documentCuid, String dpId, int flowId, String format) {

		final BI4EndPoint bi4 = new BI4EndPoint(BI4_API_ROOT_URL);
		bi4.setLogonToken(logonToken);

		// Get Webi document SI_ID from CUID
		InfoObject document = bi4.getInfoObject(documentCuid);

		// Data from dataprovider
		String data;
		if("xml".equalsIgnoreCase(format)) {
			data = bi4.flowXml(document.getId(), dpId, flowId);
		} else {
			data = bi4.flowTxt(document.getId(), dpId, flowId);
		}

		return data;
	}

	/**
	 * Get data from a report part.
	 *
	 * @param logonToken
	 * @param documentCuid
	 * @param reportId
	 * @param elementId
	 * @param format
	 * @return
	 * @throws Exception
	 */
	public static String getDataFromReportPart(String logonToken, String documentCuid, int reportId, int elementId, String format) {

		final BI4EndPoint bi4 = new BI4EndPoint(BI4_API_ROOT_URL);
		bi4.setLogonToken(logonToken);

		// Get Webi document SI_ID from CUID
		InfoObject document = bi4.getInfoObject(documentCuid);

		// Data from report part
		String data;
		if("xml".equalsIgnoreCase(format)) {
			data = bi4.datasetXml(document.getId(), reportId, elementId);
		} else {
			data = bi4.datasetJson(document.getId(), reportId, elementId);
		}

		return data;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>controllers.discussion</title>
<meta name="date" content="2016-02-18">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

controllers.discussion

Classes

CommentController

DiscussionController

LikeController

routes

routes.javascript


text:
> **The entire internet in your palm (tree).**
> A fast, framework-agnostic partial system for old-skool page generation with NodeJS.

 - Individually cache separate parts (partials) of your page and then automatically stitch them back together
 - Put partials in partials in partials - it's partials all the way down!
 - Partials can output anything! Strings, arrays, objects, XML nodes, [:turtle: turtles](https://en.wikipedia.org/wiki/Turtles_all_the_way_down), [:squirrel: jQuery](http://i.stack.imgur.com/sGhaO.gif), whatever.

## find it on npm

```
npm install trea --save
```

> N.B. trea currently only works on Node 6 or later, due to its use of generators and ES2015 features.

## get started

In trea, everything is a partial - your pages, page sections, section sections, etc. You create a partial by creating a class that extends trea's `Partial` class:

```js
let Partial = require('trea').Partial;

class NicePartial extends Partial {
    // lolwut
}
```

Each partial has an 'output' - the information that the partial generates. A partials output can be anything - a string, number, object, etc. To output data from a partial, implement the `_generate` method:

```js
class HelloPartial extends Partial {
    _generate() {
        return 'Hello world!';
    }
}
```

The output of the partial can now be gotten by calling the `generate` method on an instance of the class:

```js
let hello = new HelloPartial();
hello.generate().then(x => console.log(x)); // 'Hello world!'
hello.generate().then(x => console.log(x)); // 'Hello world!'
```

(Notice that the `_generate` method defined before isn't being called, but instead the code is calling a `generate` method provided by the Partial class)

See how the `generate` method is called twice? Well, as the code below shows, the `_generate` implemented previously is actually only called once:

```js
class SideEffectPartial extends Partial {
    _generate() {
        console.log('Hey, I was called');
        return '💡';
    }
}

let sideEffect = new SideEffectPartial();
sideEffect.generate().then(x => console.log(x)); // 'Hey, I was called' then '💡'
sideEffect.generate().then(x => console.log(x)); // '💡'
```

This behaviour is intended, and it's important to the way trea works. As a result, you should keep so-called '[side effects](http://programmers.stackexchange.com/questions/40297/what-is-a-side-effect)' out of your `_generate` method (except for some important exceptions, which we'll have a look at soon). If you need to do something every time `generate` is called, implement the `_act` method:

```js
class SideEffectAgainPartial extends Partial {
    _act() {
        console.log('Hey, I was called');
    }
    _generate() {
        return '💡';
    }
}

let sideEffectAgain = new SideEffectAgainPartial();
sideEffectAgain.generate().then(x => console.log(x)); // 'Hey, I was called' then '💡'
sideEffectAgain.generate().then(x => console.log(x)); // 'Hey, I was called' then '💡'
```

This may seem a bit pointless, but now is when we bring all of these together, with the `_needsUpdate` method. This method is called every time `generate` is called, and allows trea to determine whether the partial output should be re-generated (i.e whether `_generate` should be run again). For example, check this out:

```js
class BigOperationPartial extends Partial {
    constructor(val) {
        this.val = val;
        this._oldVal = val;
    }

    _needsUpdate() {
        let update = this.val !== this._oldVal;
        this._oldVal = this.val;
        return update;
    }

    _generate() {
        console.log('Regenerating...');
        return JSON.stringify(this.val); // or some other expensive operation
    }
}

let bigOperation = new BigOperationPartial({ hello: 'wassup' });
bigOperation.generate().then(x => console.log(x)); // 'Regenerating...' then '{"hello": "wassup"}'
bigOperation.generate().then(x => console.log(x)); // '{"hello": "wassup"}'
bigOperation.val = { hello: 'goodbye' }; // change the value we're using
bigOperation.generate().then(x => console.log(x)); // 'Regenerating...' then '{"hello": "goodbye"}'
bigOperation.generate().then(x => console.log(x)); // '{"hello": "goodbye"}'
```

Alright, now we're getting somewhere - but this is all still just a memoization system, and one that can be easily simplified with less code. But now we're getting to the point where trea really becomes useful: partials within partials. Check this out:

```js
class TwoBigOperationsPartial extends Partial {
    constructor(op1, op2) {
        this.requires('op1', op1);
        this.requires('op2', op2);
    }
    _generate(partial) {
        return partial('op1') + " " + partial('op2');
    }
}

let bigOp1 = new BigOperationPartial({ hello: 'wassup' });
let bigOp2 = new BigOperationPartial({ hello: 'goodbye' });
let twoBigOperations = new TwoBigOperationsPartial(bigOp1, bigOp2);
twoBigOperations.generate().then(x => console.log(x)); // 'Regenerating...' twice, then '{"hello": "wassup"} {"hello": "goodbye"}'
bigOp1.val = { hello: 'bonjour' };
twoBigOperations.generate().then(x => console.log(x)); // 'Regenerating...' once, then '{"hello": "bonjour"} {"hello": "goodbye"}'
```

Notice here how only the partials that need to be regenerated are - in the first case, all three of the partials are generated, but in the second case only two must be (`bigOp1` and its container, `twoBigOperations`). This is where trea comes in handy for websites - by splitting dynamic parts (e.g. parts that are generated from a database) into partials, a website can be made very efficient.

### faqs

**I know the most recent update time for my page, but don't want to implement a bunch of logic to detect if I need to regenerate a partial. What can I do?**

Great question, and luckily, trea has a solution for you. A date passed as the first parameter to `generate` will be passed to your `_needsUpdate` method, as well as any sub-partials. If no date is provided, the last time that the partial has been generated will be used - this allows you to easily find if a partial has changed since the last time it was generated.

**What about pages that have parameters (e.g. GET parameters) passed to them that change their value though?**

I'm glad you asked that! In order to handle this, trea has a feature called 'partial parameters'. Any kind of value (string, number, object, etc, as long as it is JSON serializable) passed as a second parameter to the `generate` method will provided the partial's `_needsUpdate` and `_generate` methods, and will also filter down to any sub-partials. Partials are cached based on this value, so using a different value will cause the partial to be generated with that value.

**What if my page generation is asynchronous?**

trea supports promises through-and-through, so you can return them from literally anything... Need to check your database for changes during `_needsUpdate`? Return a promise. Need to fetch some data from a file to `_generate` the partial? Return a promise.

**What if my partial needs to do some initialization?**

trea allows you to define an asynchronous `_init` method. When the `init` method provided by the Partial class is called, that partial, as well as any sub-partials, will be initialized. If a sub-partial is required after a partial has been initialized, the sub-partial will be initialized straight away.

### get your ejs on

trea includes a super-simple EJS partial wrapper to make getting started easy (note: this will probably be moved to a separate package in the near future). Check it out:

**EJSPage.js**
```js
let path = require('path');
let EJSPartial = require('trea').EJSPartial;
let partials = require('./partials');

class EJSPagePartial extends EJSPartial {
    constructor(db) {
        super();
        this.db = db;
        this.path = path.join(__dirname, 'template.ejs');
        this.partials = partials;
    }
    _init() {
        return super(this.db);
    }
    _generate(partial) {
        return super(partial, {
            username: 'cpdt',
            avatarPath: '/images/user/cpdt.png'
        });
    }
}
```
**template.ejs**
```ejs
<p>Hello there <%= username %>.</p>
<img src="<%= avatarPath %>" />
<%- partial('infobox') %>
```

EJSPartial expects your object to have a `path` property that points to the EJS file to load, and a `partials` property that contains a list of partials to be accessible from inside your template. It will then automatically detect calls to `partial(...)` in your HTML, and require these in your partial.

Parameters passed to EJSPartial's `_init` function (like what is done in the example above) will be passed into the constructors of each sub-partial when they are created. An object passed to EJSPartial's `_generate` function will be used as the scope for the template.

## documentation

### `Partial`

#### `#_act(...params: *): undefined|Promise<>`

A method that can be implemented by partial classes, performing operations that should be done on every generation. `...params` are the parameters passed to `#generate`, other than the first two.

This method is called before both `#_needsUpdate` and `#_generate` when starting partial generation, and if a promise is returned, partial generation for the partial instance will be paused until it is completed (note that `#_act` can potentially run twice at the same time if two different partial parameters are used).

#### `#_generate(partial(name: string): *, param: *): *|Promise<*>`

A method that should be implemented by a partial class, returning the content of the partial. The content of sub-partials that have been registered with `#requires` can be accessed by calling the `partial` function parameter with the partial's name. The partial parameter provided to `#generate` (or provided to a parents `#generate`) can be accessed as `param`.

This method is called after both `#_act` and `#_needsUpdate`, and will only be called if there is no version of the partial stored with the specified `param`, if `#_needsUpdate` returns a truthy value, or if a sub-partial needs to be updated.

#### `#_init(): undefined|Promise<>`

A method that can be implemented by partial classes, performing operations to initialise the partial. Initialisation can only be done once on each partial instance, and will be done as soon as the `init` method is called on this partial or one of the partials parents. If a sub-partial is childed to a partial that has already initialised, the sub-partial will be initialised immediately.

Any operations done on the partial (e.g. generation) while the partial is initialising will wait for initialisation to complete before proceeding.

#### `#_needsUpdate(since: Date, param: *): bool|Promise<bool>`

A method that can be implemented by partial classes, specifying whether the partial should update by returning a truthy or falsey value (or a promise that resolves to either). `since` is either the date passed to `#generate` (or a parents `#generate`) as the first parameter, the last time the partial with the provided parameter was generated, or the creation time if it has not yet been generated. `param` is the partial parameter provided to `#generate` (or a parents `#generate`) as the second parameter.

This method is called after `#_act` but before `#_generate`, and will not be called if no cached version of the partial exists (as the partial must generate in that case).

#### `#generate(since: Date?, param: string = 'default', ...actParams): Promise<*>`

Returns a promise that resolves to the value of the partial. If the partial, or any of its sub-partials, specify that they need to update, this will occur. If the partial is currently being generated, the returned promise will be that of the previous generation.

`param` can be used to provide a value to the partials `_generate` function, and can be any JSON-stringifiable value. Partials are cached based on their `param` value, so using a different value will result in the partial being generated again.

`actParams` are provided to the `_act` method.

#### `#genTime(param: string = 'default'): Date`

Returns the generation time of the current version of the partial with the provided partial parameter. If the partial has not yet been generated, the creation time of the partial instance will be used instead.

#### `#init(): Promise<>`

Runs the `_init` method of the partial and any sub-partials. If the partial has already been initialised or is currently in the process of initialing, nothing will happen.

#### `#needsUpdate(since: Date?, param: string = 'default'): Promise<bool>`

Returns a promise that resolves to a truthy or falsey value, representing whether the partial needs to be regenerated. Note that this includes checking sub-partials, but does not check to see if the partial has been generated yet.

`since` will be passed to the `#_needsUpdate` method, or, if not provided, the previous generation time of the partial will be used.

For speed, the result of `#needsUpdate` is memoized - this means that checks will only actually be run once for each `#generate` call (calling `#generate` clears the memoization). This memoization will only take place if the provided `since` date is the same.

#### `#requires(name: string, partial: Partial): Promise<>`

Specifies that the partial uses a sub-partial. The name provided is then used in `#_generate` when calling the `partial` function parameter. Since the partial initialisation process also initialises all sub-partials registered, if a sub-partial is registered _after_ the parent partial has initialisated, the sub-partial will be initialised straight away. The returned promise resolves when this completes, or when the parent partial completes initialisation if it has not yet completed.

A `TypeError` will be thrown if the provided partial does not have a `#_generate` method.

## license

Licensed under the MIT license, included in the LICENSE file.


text:
'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	errorHandler = require('../errors.server.controller.js'),
	mongoose = require('mongoose'),
	passport = require('passport'),
	User = mongoose.model('User');

/**
 * Update user details
 */
exports.update = function(req, res) {
	// Init Variables
	var user = req.user;
	var message = null;

	// For security measurement we remove the roles from the req.body object
	delete req.body.roles;

	if (user) {
		// Merge existing user
		user = _.extend(user, req.body);
		user.updated = Date.now();
		user.displayName = user.firstName + ' ' + user.lastName;

		user.save(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				req.login(user, function(err) {
					if (err) {
						res.status(400).send(err);
					} else {
						res.json(user);
					}
				});
			}
		});
	} else {
		res.status(400).send({
			message: 'User is not signed in'
		});
	}
};

exports.search = function(req, res){
	var searchedUser = req.userName;
  if(req.user){
    return User.find({username: req.body.userName}, function(err, user){
    	console.log(req.body.userName);
    	console.log(user);
    	res.send(user);
    });
  } else {

    return res.status(400).send({
      message: 'User is not signed in'
    });
  }
};

exports.add = function(req, res){
	var addedUser = req.userName;
	if(req.user){
    return User.find({_id: req.user._id}, function(err, user){
    	user[0].friendsList.push(req.body.userName);
    	console.log(user[0].friendsList);
    	console.log(user[0]);
    	User.update({_id: req.user._id}, {friendsList: user[0].friendsList}, {upsert: true}, function(err, item) {
        res.send();
      });
    });
  } else {

    return res.status(400).send({
      message: 'User is not signed in'
    });
  }
};

exports.retrieveFriends = function(req, res){
	var addedUser = req.userName;
	if(req.user){
    return User.find({_id: req.user._id}, function(err, user){
    	console.log('user: '+ user[0]);
    	console.log('loading friends list for user: '+ user[0].friendsList);
        res.send(user[0].friendsList);
      });
  } else {

    return res.status(400).send({
      message: 'User is not signed in'
    });
  }
};

/**
 * Send User
 */
exports.me = function(req, res) {
	res.json(req.user || null);
};


text:
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>

<!-- Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

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

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<section id="LDAPserver-for-user-authentication">
  <title>Using an LDAP Server for User Authentication</title>
  <para>&PRODUCT; supports authentication through a Lightweight Directory Access Protocol (LDAP)
    server, such as Microsoft Active Directory or ApacheDS. You can add LDAP associations to
    &PRODUCT; so users can log in by using credentials based on your existing authentication scheme.
    Additionally, the simplified LDAP authentication mechanism in &PRODUCT; 4.3 allows you to import
    users directly from the configured LDAP Group. LDAP users are authenticated without creating
    individual users in &PRODUCT;.</para>
  <para>To use LDAP for authentication of &PRODUCT; users, you must do the following steps:</para>
  <orderedlist>
    <listitem>
      <para>Add a working LDAP server.</para>
      <para>See <xref linkend="ldap-config"/>.</para>
    </listitem>
    <listitem>
      <para>Configure the LDAP attributes.</para>
      <para>See <xref linkend="ldap-param"/>.</para>
    </listitem>
    <listitem>
      <para>Import users from the LDAP group.</para>
      <para>See <xref linkend="ldap-provision"/>.</para>
    </listitem>
    <listitem>
      <para>To confirm authentication, log in to &PRODUCT; UI as one of the LDAP user you have
        imported.</para>
    </listitem>
  </orderedlist>
  <xi:include href="ldap-config.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>
  <xi:include href="ldap-user-add.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>
</section>