text:
Watson Developer Cloud Nodejs Client - Alpha
============================================

[![Join the chat at https://gitter.im/watson-developer-cloud/nodejs-wrapper](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/watson-developer-cloud/nodejs-wrapper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Wrapper to use the [Watson Developer Cloud][wdc] services. A collection of REST APIs and SDKs that use cognitive computing to solve complex problems.

## Table of Contents
  * [Watson Developer Cloud Nodejs Client - Alpha](#watson-developer-cloud-nodejs-client---alpha)
    * [Questions](#questions)
    * [Installation](#installation)
    * [Usage](#usage)
    * [Getting the Service Credentials](#getting-the-service-credentials)
    * [IBM Watson Services](#ibm-watson-services)
      * [Concept Expansion](#concept-expansion)
      * [Concept Insights](#concept-insights)
      * [Language Identification](#language-identification)
      * [Machine Translation](#machine-translation)
      * [Message Resonance](#message-resonance)
      * [Personality Insights](#personality-insights)
      * [Question and Answer](#question-and-answer)
      * [Relationship Extraction](#relationship-extraction)
      * [Speech to Text](#speech-to-text)
      * [Text to Speech](#text-to-speech)
      * [Tradeoff Analytics](#tradeoff-analytics)
      * [Visual Recognition](#visual-recognition)
    * [Running in Bluemix](#running-in-bluemix)
    * [Debug](#debug)
    * [Tests](#tests)
    * [Open Source @ IBM](#open-source--ibm)
    * [License](#license)
    * [Contributing](#contributing)

## Alpha
This is an **Alpha release** of the `watson-developer-cloud` [npm][npm_link] module. Features might be changed in backward-incompatible ways and is not recommended for production use.

## Questions

If you are having difficulties using the APIs or have a question about the IBM Watson Services, please ask a question on [dW Answers](https://developer.ibm.com/answers/questions/ask/?topics=watson) or [Stack Overflow](http://stackoverflow.com/questions/ask?tags=ibm-watson).

## Installation

```sh
$ npm install watson-developer-cloud-alpha --save
```

## Usage

The examples below assume you already have service credentials. If not, you will have to create and bind the service in [Bluemix][bluemix]. See the [Getting Started][getting_started] page for more details.

If you are running your application in Bluemix, you don't need to specify the credentials, the wrapper will get them for you by looking at the `VCAP_SERVICES`

### Getting the Service Credentials
The credentials for the services are stored in the [VCAP_SERVICES][vcap_environment] environment variable. In order to get them you need to first create and bind the service to your application.

There are two ways to get the credentials, you can use Bluemix to access your app and view the `VCAP_SERVICES` there or you can run:

```sh
$ cf env <application-name>
```

Example output:
```sh
  System-Provided:
  {
  "VCAP_SERVICES": {
    "visual_recognition": [{
        "credentials": {
          "password": "<password>",
          "url": "<url>",
          "username": "<username>"
        },
      "label": "visual_recognition",
      "name": "visual-recognition-service",
      "plan": "free"
   }]
  }
  }
```

You need to copy `username`, `password`.

## IBM Watson Services
The Watson Developer Cloud offers a variety of services for building cognitive apps.

### Concept Expansion
Example: Map euphemisms or colloquial terms to more commonly understood phrases using the [Concept Expansion][concept_expansion] service.

```javascript
var watson = require('watson-developer-cloud-alpha');

var concept_expansion = watson.concept_expansion({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});
var params = {
  seeds: ['motrin','tylenol','aspirin'],
  dataset: 'mtsamples',
  label: 'medications'
};
concept_expansion.expand(params, function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
```

### Concept Insights
Example: Use the [Concept Insights][concept_insights] to identify words in the text that correspond to concepts in a Wikipedia graph.
```js
var watson = require('watson-developer-cloud-alpha');

var concept_insights = watson.concept_insights({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
  user: 'wikipedia',
  graph: 'en-20120601',
  text: 'IBM Watson won the Jeopardy television show hosted by Alex Trebek'
};

// Retrieve the concepts for input text
concept_insights.annotateText(params, function(err, response) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(response, null, 2));
});
```

### Language Identification
Example: Identify a language using the [Language Identification][language_identification] service.

```javascript
var watson = require('watson-developer-cloud-alpha');

var language_identification = watson.language_identification({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

language_identification.identify({
  text: 'The language identification service takes text input and identifies the language used.' }, function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
```

### Machine Translation
Example: Translate text from one language to another using the [Machine Translation][machine_translation] service.

```javascript
var watson = require('watson-developer-cloud-alpha');

var machine_translation = watson.machine_translation({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

machine_translation.translate({
  text: 'A sentence must have a verb', from : 'enus', to: 'eses' },
  function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
```

### Message Resonance
Example: Get resonance information for individual words in a sentence from the [Message Resonance][message_resonance] service.

```js
var watson = require('watson-developer-cloud-alpha');
var message_resonance = watson.message_resonance({
  username:'<username>',
  password:'<password>',
  version:'v1'
});

message_resonance.resonance({ text: 'IBM Watson Developer Cloud', dataset: 1 }, function(err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});
```

### Personality Insights
Example: Analyze text and get a personality profile using the [Personality Insights][personality_insights] service.

```javascript
var watson = require('watson-developer-cloud-alpha');

var personality_insights = watson.personality_insights({
  username: '<username>',
  password: '<password>',
  version: 'v2'
});

personality_insights.profile({
  text: 'type more than 100 unique words here...' },
  function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
```
**Node:** Don't forget to update the `text` variable!

### Question and Answer
Example: Ask a healthcare-related question to the [Question and Answer][question_and_answer] service.

```js
var watson = require('watson-developer-cloud-alpha');
var question_and_answer_healthcare = watson.question_and_answer({
  username: '<username>',
  password: '<password>',
  version: 'v1',
  dataset: 'healthcare' /* The dataset can be specified when creating the service or when calling it */
});

question_and_answer_healthcare.ask({ text: 'What is HIV?'}, function (err, response) {
  if (err)
    console.log('error:', err);
  else
    console.log(JSON.stringify(response, null, 2));
});
```

### Relationship Extraction
Example: Analyze an English news article and get the relationships between sentence components (nouns, verbs, subjects, objects, etc.) using the [Relationship Extraction][relationship_extraction] service.

```javascript
var watson = require('watson-developer-cloud-alpha');

var relationship_extraction = watson.relationship_extraction({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

relationship_extraction.extract({
  text: 'IBM Watson developer cloud', dataset: 'ie-en-news' },
  function (err, response) {
    if (err)
      console.log('error:', err);
    else
      console.log(JSON.stringify(response, null, 2));
});
```

### Speech to Text
Example: Use the [Speech to Text][speech_to_text] to recognize the text from a wav file.

```js
var watson = require('watson-developer-cloud-alpha');
var request = require('request');

var speech_to_text = watson.speech_to_text({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
  // From file
  audio: request('http://speech-to-text-demo.mybluemix.net/audio/sample1.wav'),
  content_type: 'audio/l16; rate=44100'
};

speech_to_text.recognize(params, function(err, res) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(res, null, 2));
});
```

### Text to Speech
Example: Use the [Text to Speech][text_to_speech] to synthesize text into a wav file.

```js
var watson = require('watson-developer-cloud-alpha');
var fs = require('fs');

var text_to_speech = watson.text_to_speech({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
    text: 'Hello from IBM Watson',
    voice: 'VoiceEnUsMichael', // optional voice
    accept: 'audio/wav'
};

// pipe the synthesized text to a file
text_to_speech.synthesize(params).pipe(fs.createWriteStream('output.wav'));
```

### Tradeoff Analytics
Example: Use the [Tradeoff Analytics][tradeoff_analytics] to find the best phone that minimize price and weight and maximize screen size.

```js
var watson = require('watson-developer-cloud-alpha');

var tradeoff_analytics = watson.tradeoff_analytics({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
  'subject': 'phone',
  'columns': [{
    'key': 'price',
    'full_name': 'Price (Eur)',
    'type': 'NUMERIC',
    'is_objective': true,
    'goal': 'MIN'
  }, {
    'key': 'RAM',
    'full_name': 'RAM (MB)',
    'type': 'NUMERIC',
    'is_objective': false,
    'goal': 'MAX'
  }, {
    'key': 'weight',
    'full_name': 'Weight (gr)',
    'type': 'NUMERIC',
    'is_objective': true,
    'goal': 'MIN'
  }],
  'options': [{
    'key': ' 1',
    'name': 'Samsung Galaxy S4 White',
    'values': {
      'weight': 130,
      'price': 239,
      'RAM': 2048
    }
  }, {
    'key': '2',
    'name': 'Samsung Galaxy S4 Black',
    'values': {
      'weight': 130,
      'price': 240,
      'RAM': 2048
    }
  }, {
    'key': '3',
    'name': 'Samsung Galaxy S3 White',
    'values': {
      'weight': 133,
      'price': 79,
      'RAM': 2048
    }
  }]
};

tradeoff_analytics.dilemmas(params, function(err, res) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(res, null, 2));
});
```

### Visual Recognition
Example: Use the [Visual Recognition][visual_recognition] service to recognize the picture below.

<img src="http://visual-recognition-demo.mybluemix.net/images/horses.jpg" width="150" height="150" />

```js
var watson = require('watson-developer-cloud-alpha');
var request = require('request');

var visual_recognition = watson.visual_recognition({
  username: '<username>',
  password: '<password>',
  version: 'v1'
});

var params = {
  image_file: request('http://visual-recognition-demo.mybluemix.net/images/horses.jpg')
};
visual_recognition.recognize(params, function(err, res) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(res, 'labels', 2));
});
```

## Running in Bluemix
By default the wrapper will try to use the Bluemix `VCAP_SERVICES` to get the credentials for a given service. You can avoid this by using: `use_vcap_services`.

```javascript
var watson = require('watson-developer-cloud-alpha');

var concept_expansion = watson.concept_expansion({
  version: 'v1',
  use_vcap_services: false
});
```
The example above will fail because you did not provide a username and password and the wrapper will not look into Bluemix for those values.

## Debug
This wrapper relies in the `request` npm module writted by [mikeal][mikeal_github] to call the Watson Services. In order to debug add 'request' to the `NODE_DEBUG`:

```sh
$ NODE_DEBUG='request' app.js
```
where `app.js` is your nodejs file

## Tests
Running all the tests:
```sh
$ npm test
```

Running a specific test:
```sh
$ mocha -g '<test name>'
```

## Open Source @ IBM
[Find more open source projects on the IBM Github Page](http://ibm.github.io/)

## License

This library is licensed under Apache 2.0. Full license text is
available in [COPYING](https://github.com/watson-developer-cloud/nodejs-wrapper-alpha/blob/master/LICENSE).

## Contributing
See [CONTRIBUTING](https://github.com/watson-developer-cloud/nodejs-wrapper-alpha/blob/master/CONTRIBUTING.md).

[question_and_answer]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/qaapi/
[message_resonance]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/mrapi/
[personality_insights]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/personality-insights/
[language_identification]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/lidapi/
[machine_translation]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/mtapi/
[concept_expansion]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/glimpseapi/
[relationship_extraction]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/sireapi/
[visual_recognition]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/visual-recognition/
[text_to_speech]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/text-to-speech/
[speech_to_text]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/speech-to-text/
[concept_insights]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/concept-insights/
[tradeoff_analytics]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/tradeoff-analytics/

[getting_started]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/getstarted.html
[wdc]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/
[vcap_environment]: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/index.html#EnvVars
[bluemix]: https://console.ng.bluemix.net
[npm_link]: https://www.npmjs.com/package/watson-developer-cloud
[mikeal_github]: https://github.com/request/request


text:
/* global site_logo_header_classes */
/**
 * JS for handling the "Display Header Text" setting's realtime preview.
 */
(function($){
	var api = wp.customize,
		$classes = site_logo_header_classes;

	api( 'site_logo_header_text', function( value ) {
		value.bind( function( to ) {
			if ( true === to ) {
				$( $classes ).css({
					'position': 'static',
					'clip': 'auto'
				});
			} else {
				$( $classes ).css({
					'position': 'absolute',
					'clip': 'rect(1px 1px 1px 1px)'
				});
			}
		});
	});
})(jQuery);

redpajama_set_name: RedPajamaGithub


text:
package edu.harvard.mcb.leschziner.manage;

import java.util.UUID;

import org.vertx.java.core.json.DecodeException;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;

import edu.harvard.mcb.leschziner.classify.DistributedClassifier;
import edu.harvard.mcb.leschziner.classify.PCAClassifier;
import edu.harvard.mcb.leschziner.event.Checkpoint;
import edu.harvard.mcb.leschziner.event.checkpoint.ClassifierLoadCheckpoint;
import edu.harvard.mcb.leschziner.event.checkpoint.ClassifierRunCheckpoint;
import edu.harvard.mcb.leschziner.load.ClassUploader;
import edu.harvard.mcb.leschziner.load.ImageDownloader;
import edu.harvard.mcb.leschziner.particlefilter.Binner;
import edu.harvard.mcb.leschziner.particlefilter.CircularMask;
import edu.harvard.mcb.leschziner.particlefilter.LowPassFilter;
import edu.harvard.mcb.leschziner.particlegenerator.RotationGenerator;
import edu.harvard.mcb.leschziner.particlegenerator.ShiftGenerator;
import edu.harvard.mcb.leschziner.particlesource.DistributedParticlePicker;
import edu.harvard.mcb.leschziner.particlesource.DoGParticlePicker;
import edu.harvard.mcb.leschziner.pipe.ParticleFilteringPipe;
import edu.harvard.mcb.leschziner.pipe.ParticleGeneratingPipe;

/**
 * An agent responsible for all the elements of a particular pipeline
 *
 * @author spartango
 *
 */
public class PipelineGuardian {
    private final UUID                uuid;

    // Pipeline stages

    private ImageDownloader           downloader;
    private DistributedParticlePicker picker;
    private ParticleFilteringPipe     filter;
    private ParticleGeneratingPipe    generator;
    private DistributedClassifier     classifier;
    private ClassUploader             uploader;

    // Checkpoints
    private Checkpoint                loaderCheckpoint;
    private Checkpoint                pickerCheckpoint;
    private Checkpoint                filterCheckpoint;
    private Checkpoint                generatorCheckpoint;
    private ClassifierLoadCheckpoint  classifierCheckpoint;
    private ClassifierRunCheckpoint   uploadCheckpoint;

    public PipelineGuardian() {
        uuid = UUID.randomUUID();
    }

    /**
     *
     * @param parameters
     * @return
     */
    public boolean initialize(String parameters) {
        try {
            JsonObject json = new JsonObject(parameters);

            // Check for the appropriate sections (validation)
            if (validateParameters(json)) {
                System.out.println("[Guardian "
                                   + this.uuid.toString()
                                   + "]: Building pipeline");
                // Images
                JsonArray images = json.getArray("images");
                // Build an ImageLoader
                initLoader(images);

                // Picker
                JsonObject pickerParams = json.getObject("picker");
                // Build a Picker
                initPicker(pickerParams);

                // Filters
                JsonObject filterParams = json.getObject("filter");
                // Build a filter pipe
                initFilterPipe(filterParams);

                // Generation
                JsonObject generationParams = json.getObject("generation");
                // Build a generator pipe
                initGeneratorPipe(generationParams);

                // Classification
                JsonObject classifierParams = json.getObject("classifier");
                // Build a classifier
                initClassifier(classifierParams);

                // Check that everything got built
                if (pipelineBuilt()) {
                    System.out.println("[Guardian "
                                       + this.uuid.toString()
                                       + "]: Starting pipeline");
                    // Wire the pipes together
                    linkPipes();

                    // Place the checkpoints between stages
                    linkCheckpoints();

                    // Start the loader
                    downloader.start();
                    return true;
                }

            }
        } catch (DecodeException e) {
            System.err.println("["
                               + this.getClass().getSimpleName()
                               + "]: Failed to decode body");
        }
        return false;

    }

    private void linkCheckpoints() {
        loaderCheckpoint.setEventSource(downloader);
        loaderCheckpoint.addDependent(pickerCheckpoint);
        pickerCheckpoint.setEventSource(picker);
        pickerCheckpoint.addDependent(filterCheckpoint);
        filterCheckpoint.setEventSource(filter);
        filterCheckpoint.addDependent(generatorCheckpoint);
        generatorCheckpoint.setEventSource(generator);
        generatorCheckpoint.addDependent(classifierCheckpoint);
        classifierCheckpoint.setEventSource(classifier);
        classifierCheckpoint.addDependent(uploadCheckpoint);
        uploadCheckpoint.setEventSource(classifier);
    }

    private void linkPipes() {
        picker.addParticleSource(downloader);
        filter.addParticleSource(picker);
        generator.addParticleSource(filter);
        classifier.addParticleSource(generator);
    }

    private static boolean validatePickerParams(JsonObject pickerParams) {
        return pickerParams.getInteger("particleSize") != null
               && pickerParams.getInteger("particleEpsilon") != null
               && pickerParams.getInteger("boxSize") != null
               && pickerParams.getInteger("firstFilter") != null
               && pickerParams.getInteger("secondFilter") != null
               && pickerParams.getInteger("threshold") != null;
    }

    private void initPicker(JsonObject pickerParams) {
        if (validatePickerParams(pickerParams)) {
            picker = new DoGParticlePicker(pickerParams.getInteger("particleSize"),
                                           pickerParams.getInteger("particleEpsilon"),
                                           pickerParams.getInteger("firstFilter"),
                                           pickerParams.getInteger("secondFilter"),
                                           pickerParams.getInteger("threshold"),
                                           pickerParams.getInteger("boxSize"));
            pickerCheckpoint = new Checkpoint();
        }

    }

    private static boolean validateGeneratorParams(JsonObject generatorParams) {
        return generatorParams.getNumber("rotationAngle") != null;
    }

    private void initGeneratorPipe(JsonObject generationParams) {
        if (validateGeneratorParams(generationParams)) {
            generator = new ParticleGeneratingPipe();
            generatorCheckpoint = new Checkpoint();
            // Rotation generator (if needed)
            double rotationAngle = generationParams.getNumber("rotationAngle")
                                                   .doubleValue();
            if (rotationAngle > 0) {
                generator.addStage(new RotationGenerator(rotationAngle));
            }

            // Shift generator (if needed)
            Integer shiftDistance = generationParams.getInteger("shiftDistance");
            Integer shiftIncrement = generationParams.getInteger("shiftIncrement");

            if (shiftDistance != null
                && shiftIncrement != null
                && shiftDistance > 0
                && shiftIncrement > 0) {
                generator.addStage(new ShiftGenerator(shiftDistance,
                                                      shiftIncrement));
            }
        }
    }

    private static boolean validateFilterParams(JsonObject filterParams) {
        return filterParams.getInteger("maskSize") != null
               && filterParams.getInteger("lowPassFilter") != null
               && filterParams.getInteger("binning") != null;
    }

    private void initFilterPipe(JsonObject filterParams) {
        if (validateFilterParams(filterParams)) {
            filter = new ParticleFilteringPipe();
            filterCheckpoint = new Checkpoint();
            // Circular Mask
            filter.addStage(new CircularMask(filterParams.getInteger("maskSize")));

            // Low Pass Filter (if needed)
            int lowPassFilter = filterParams.getInteger("lowPassFilter");
            if (lowPassFilter > 1) {
                filter.addStage(new LowPassFilter(lowPassFilter));
            }
            // Binner (if needed)
            int binning = filterParams.getInteger("binning");
            if (binning > 1) {
                filter.addStage(new Binner(binning));
            }
        }
    }

    private static boolean
            validateClassifierParams(JsonObject classifierParams) {
        return classifierParams.getNumber("classAccuracy") != null
               && classifierParams.getInteger("classCount") != null
               && classifierParams.getInteger("principalComponents") != null;
    }

    private void initClassifier(JsonObject classifierParams) {
        if (validateClassifierParams(classifierParams)) {
            classifier = new PCAClassifier(classifierParams.getInteger("principalComponents"),
                                           classifierParams.getInteger("classCount"),
                                           classifierParams.getNumber("classAccuracy")
                                                           .doubleValue());
            classifierCheckpoint = new ClassifierLoadCheckpoint(classifier);
            uploader = new ClassUploader(classifier, "EMPApp", this.getUUID()
                                                                   .toString());
            uploadCheckpoint = new ClassifierRunCheckpoint(uploader, classifier);
        }
    }

    private void initLoader(JsonArray images) {
        downloader = new ImageDownloader();
        loaderCheckpoint = new Checkpoint();
        for (Object o : images) {
            // Hope this is a real string? else we'll choke later
            downloader.addImagePath(o.toString());
        }
        loaderCheckpoint.setExpectedCompletions(images.size());
    }

    public String getStatusJSON() {
        JsonObject status = new JsonObject();

        JsonObject loaderStatus = new JsonObject();
        loaderStatus.putNumber("progress", loaderCheckpoint.getCompletions());
        loaderStatus.putNumber("expected",
                               loaderCheckpoint.getExpectedCompletions());
        loaderStatus.putNumber("output", loaderCheckpoint.getTotalOutput());
        loaderStatus.putNumber("runtime", loaderCheckpoint.getTotalRuntime());
        loaderStatus.putNumber("errors", loaderCheckpoint.getErrorCount());
        loaderStatus.putBoolean("done", loaderCheckpoint.isReached());
        status.putObject("loader", loaderStatus);

        JsonObject pickerStatus = new JsonObject();
        pickerStatus.putNumber("progress", pickerCheckpoint.getCompletions());
        pickerStatus.putNumber("output", pickerCheckpoint.getTotalOutput());
        pickerStatus.putNumber("runtime", pickerCheckpoint.getTotalRuntime());
        pickerStatus.putNumber("expected",
                               pickerCheckpoint.getExpectedCompletions());
        pickerStatus.putNumber("errors", pickerCheckpoint.getErrorCount());
        pickerStatus.putBoolean("done", pickerCheckpoint.isReached());

        status.putObject("picker", pickerStatus);

        JsonObject filterStatus = new JsonObject();
        filterStatus.putNumber("progress", filterCheckpoint.getCompletions());
        filterStatus.putNumber("output", filterCheckpoint.getTotalOutput());
        filterStatus.putNumber("runtime", filterCheckpoint.getTotalRuntime());
        filterStatus.putNumber("expected",
                               filterCheckpoint.getExpectedCompletions());
        filterStatus.putNumber("errors", filterCheckpoint.getErrorCount());
        filterStatus.putBoolean("done", filterCheckpoint.isReached());

        status.putObject("filter", filterStatus);

        JsonObject generatorStatus = new JsonObject();
        generatorStatus.putNumber("progress",
                                  generatorCheckpoint.getCompletions());
        generatorStatus.putNumber("expected",
                                  generatorCheckpoint.getExpectedCompletions());
        generatorStatus.putNumber("errors", generatorCheckpoint.getErrorCount());
        generatorStatus.putNumber("runtime",
                                  generatorCheckpoint.getTotalRuntime());
        generatorStatus.putNumber("output",
                                  generatorCheckpoint.getTotalOutput());
        generatorStatus.putBoolean("done", generatorCheckpoint.isReached());

        status.putObject("generation", generatorStatus);

        JsonObject classifierStatus = new JsonObject();
        classifierStatus.putNumber("progress",
                                   classifierCheckpoint.getCompletions());
        classifierStatus.putNumber("expected",
                                   classifierCheckpoint.getExpectedCompletions());
        classifierStatus.putNumber("errors",
                                   classifierCheckpoint.getErrorCount());
        classifierStatus.putBoolean("loaded", classifierCheckpoint.isReached());
        classifierStatus.putNumber("runtime",
                                   uploadCheckpoint.getTotalRuntime());
        classifierStatus.putBoolean("classified", uploadCheckpoint.isReached());
        classifierStatus.putBoolean("done", uploadCheckpoint.hasUploaded());
        status.putObject("classifier", classifierStatus);
        return status.encode();
    }

    public String getResultsJSON() {
        if (uploadCheckpoint.hasUploaded())
            return uploader.getResultsJson();
        else
            return null;
    }

    public UUID getUUID() {
        return uuid;
    }

    private static boolean validateParameters(JsonObject json) {
        return json.getArray("images") != null
               && json.getObject("picker") != null
               && json.getObject("filter") != null
               && json.getObject("generation") != null
               && json.getObject("classifier") != null;
    }

    private boolean pipelineBuilt() {
        return downloader != null
               && picker != null
               && filter != null
               && generator != null
               && classifier != null;
    }

    public void destroy() {
        // TODO Auto-generated method stub
        classifier.clearClasses();
    }

}


text:
using System;
using NUnit.Framework;

namespace L4p.Common.NUnits
{
    public static class AssertIt
    {
        public static void Fails(TestDelegate action)
        {
            try
            {
                action();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            Assert.That(() => {}, Throws.Exception);
        }

        public static void Succeeds(TestDelegate action)
        {
            Assert.That(action, Throws.Nothing);
        }
    }
}


text:
layout: post
title: "The More The Better?"
date: 2017-01-09
comments: true
categories: da
keywords: "da mondays, the effect of large sample on models, large sample size, model quality"
published: true
share: true
ads: true

---

A lot of my clients think more data lead to more accurate models, but this may not be true. Here's why.

* Noise in the predictors or the response are also likely to increase as more data are collected, and hence reduce any positive impact of the large sample on model quality.
* The law of diminishing returns. Beyond a certain point, more of the same data from the same population won't improve models by much.
* More data lead to more computational burden and cost.

Instead of collecting more data, it's often better to collect different data. In other words, increase P (number of predictors) instead of N (sample size).


text:
package actor.salt

import akka.actor._
import akka.event.LoggingReceive
import com.qianmi.bugatti.actors.SpiritCommand

import scala.concurrent.duration._
import scala.language.postfixOps

/**
 * Created by mind on 8/1/14.
 */
case class Reconnect(path: String)
case object ConnectStoped
case class Connected()

class SpiritActor(startPath: String) extends Actor with ActorLogging {
  import context._
  var path = startPath

  sendIdentifyRequest()

  def sendIdentifyRequest(): Unit = {
    context.actorSelection(path) ! Identify(path)
  }

  def receive = identifying

  def identifying: Actor.Receive = LoggingReceive {
    case ActorIdentity(idPath, Some(actor)) => {
      if (idPath == path) {
        context.watch(actor)
        context.become(active(actor))
      } else {
        context.stop(actor)
        context.system.scheduler.scheduleOnce(3.seconds, self, ReceiveTimeout)
      }
    }
    case ActorIdentity(idPath, None) => {
      context.system.scheduler.scheduleOnce(3.seconds, self, ReceiveTimeout)
    }
    case Reconnect(newPath)          => path = newPath
    case ReceiveTimeout              => sendIdentifyRequest()
    case Connected                   => sender ! false
    case _                           => {
      sender ! ConnectStoped
      log.warning("Not ready yet")
    }
  }

  def active(actor: ActorRef): Actor.Receive = LoggingReceive {
    case sc: SpiritCommand => {
      actor forward  sc
    }

    case Reconnect(newPath) => {
      context.children.foreach { child =>
        child ! ConnectStoped
      }

      path = newPath
      sendIdentifyRequest()
      context.become(identifying)
    }

    case Connected => sender ! true

    case Terminated(`actor`) => {
      context.children.foreach { child =>
        child ! ConnectStoped
      }

      sendIdentifyRequest()
      context.become(identifying)
    }
    case ReceiveTimeout => log.warning("ReceiveTimeout")//      ignore

    case x => log.warning(s"Unknown message $x")
  }
}


text:
/**************************************************************
 *	Arc curve
 **************************************************************/

THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

	THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
};

THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;


text:
const { expectRedux, storeSpy } = require("expect-redux");
const { configureStore } = require("./store");

const storeForTest = () => configureStore([storeSpy]);

const effect = dispatch => {
  dispatch({ type: "REQUEST_STARTED" });

  return fetch("/api/count").then(result => {
    if (result.ok) {
      return result.json().then(jsonBody => {
        dispatch({
          type: "REQUEST_SUCCESS",
          payload: jsonBody.count
        });
      });
    }
  });
};

describe("service", () => {
  it("retrieves the current count", () => {
    const store = storeForTest();

    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      json: jest.fn().mockResolvedValue({ count: 42 })
    });

    store.dispatch(effect);

    return expectRedux(store)
      .toDispatchAnAction()
      .matching({
        type: "REQUEST_SUCCESS",
        payload: 42
      });
  });
});


text:
body {
  background: url(images/imagem-login.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  color:white;
}
h1{
	color: white;

}


text:
require "rails_helper"

describe CaseFilter::CaseRetentionDeadlineFilter do
  before(:all) do
    DbHousekeeping.clean
      @offender_sar_retention_2018 = create(:offender_sar_complaint, :closed, :with_retention_schedule, planned_destruction_date: Time.new(2018, 5, 15))
      @offender_sar_retention_2020 = create(:offender_sar_case, :closed, :with_retention_schedule, planned_destruction_date: Time.new(2020, 5, 15))
  end

  after(:all) do
    DbHousekeeping.clean
  end

  let(:user) { find_or_create(:branston_user) }
  let(:filter) { described_class.new search_query, user, Case::Base.joins(:retention_schedule) }

  describe '#available_choices' do
    let(:search_query) { create :search_query }

    it 'contains the choices for the filter' do
      available_choices = Timecop.freeze(Time.new(2018, 5, 15)) { filter.available_choices }

      expect(
        available_choices
      ).to eq({
        :due => {:from => "{\"day\":\"01\",\"month\":\"01\",\"year\":\"2000\"}", :to => "{\"day\":\"15\",\"month\":\"05\",\"year\":\"2018\"}"},
        :one_month => {:from => "{\"day\":\"16\",\"month\":\"05\",\"year\":\"2018\"}", :to => "{\"day\":\"15\",\"month\":\"06\",\"year\":\"2018\"}"},
        :two_months => {:from => "{\"day\":\"16\",\"month\":\"06\",\"year\":\"2018\"}", :to => "{\"day\":\"15\",\"month\":\"07\",\"year\":\"2018\"}"},
        :three_months => {:from => "{\"day\":\"16\",\"month\":\"07\",\"year\":\"2018\"}", :to => "{\"day\":\"15\",\"month\":\"08\",\"year\":\"2018\"}"},
        :four_months => {:from => "{\"day\":\"16\",\"month\":\"08\",\"year\":\"2018\"}", :to => "{\"day\":\"15\",\"month\":\"09\",\"year\":\"2018\"}"}
      })
    end
  end

  describe '#applied?' do
    subject { filter }

    context 'no planned_destruction_date present' do
      let(:search_query) { create :search_query }
      it { should_not be_applied }
    end

    context 'both from and to planned_destruction_date present' do
      let(:search_query) { create :search_query, planned_destruction_date_from: Date.today, planned_destruction_date_to: Date.today }
      it { should be_applied }
    end

    context 'only planned_destruction_date_from present' do
      let(:search_query) { create :search_query, planned_destruction_date_from: Date.today }
      it { should_not be_applied }
    end

    context 'only planned_destruction_date_to present' do
      let(:search_query) { create :search_query, planned_destruction_date_to: Date.today }
      it { should_not be_applied }
    end
  end

  describe '#call' do
    context 'no cases with deadline in date range' do
      let(:search_query) { create :search_query,
                                  planned_destruction_date_from: Date.new(2017, 12, 4),
                                  planned_destruction_date_to: Date.new(2018, 01, 15) }

      it 'returns an empty collection' do
        expect(filter.call).to eq([])
      end
    end

    context 'there are cases within the deadline' do
      let(:search_query) { create :search_query,
                                  planned_destruction_date_from: Date.new(2018, 01, 01),
                                  planned_destruction_date_to: Date.new(2021, 01, 01) }

      it 'returns all the cases in the range' do
        expect(filter.call).to eq([@offender_sar_retention_2018, @offender_sar_retention_2020])
      end
    end

    context 'there are some cases within the deadline, not all' do
      let(:search_query) { create :search_query,
                                  planned_destruction_date_from: Date.new(2019, 01, 01),
                                  planned_destruction_date_to: Date.new(2021, 01, 01) }

      it 'returns only the cases in the range' do
        expect(filter.call).to eq([@offender_sar_retention_2020])
      end
    end
  end

  describe '#crumbs' do
    context 'filter not enabled' do
      let(:search_query) { create :search_query, planned_destruction_date_from: nil, planned_destruction_date_to: nil }

      it 'returns no crumbs' do
        expect(filter.crumbs).to be_empty
      end
    end

    context 'from and to date selected' do
      let(:search_query)  { create :search_query,
                                   planned_destruction_date_from: Date.new(2017, 12, 4),
                                   planned_destruction_date_to: Date.new(2017, 12, 25) }

      it 'returns a single crumb' do
        expect(filter.crumbs).to have(1).items
      end

      it 'uses the from and to dates in the crumb text' do
        expect(filter.crumbs[0].first).to eq 'Destruction due 4 Dec 2017 - 25 Dec 2017'
      end

      describe 'params that will be submitted when clicking on the crumb' do
        subject { filter.crumbs[0].second }

        it { should eq 'planned_destruction_date_from' => '',
                       'planned_destruction_date_to' => '',
                       'parent_id' => search_query.id }
      end
    end
  end
end


text:
import csv
import os
import sys
import math

if len(sys.argv) != 4:
	print "splitData.py input.csv outputDir n-folds"

inputDir = sys.argv[1]
outputDir = sys.argv[2]
n = int(sys.argv[3])

dataSet = open(inputDir, 'r')
dataSetReader = csv.reader(dataSet, dialect='excel')

header = dataSetReader.next()

records = []
for row in dataSetReader:
	records.append(row[0])

templates = list(set(records))
numTemplates = len(templates)

print numTemplates
dataSet.seek(0)
dataSetReader.next()

partitionSize = int(math.floor(5749 / int(n)))

for i in range(n):
	dataSet.seek(0)
	dataSetReader.next()

	output = open(outputDir + "/train%d.csv" % i, 'w')
	writer = csv.writer(output, dialect='excel')
	writer.writerow(header)

	if i == (n-1):
		for row in dataSetReader:
			if int(row[0]) >= i*partitionSize:
				writer.writerow(row)

	else:
		for row in dataSetReader:
			if (int(row[0])>= i*partitionSize) & (int(row[0]) < (i+1)*partitionSize):
				writer.writerow(row)

	output.close()

dataSet.close()


text:
import re
import bottle
import config
import database

from bottle import request
from bottle import redirect
from bottle import response

from services.engine import themeservice
from services.engine import engineservice
from services.installer import installservice

def starter(callback):
	def wrapper(*args, **kwargs):
		passthrough = False

		passthroughExtensions = (".html", ".xml", "txt")
		passthroughPaths = ("/resources", "/views", "/static", "/theme/static")

		test1 = [ext for ext in passthroughExtensions if ext in request.path]
		test2 = [p for p in passthroughPaths if request.path.startswith(p)]
		passthrough = (len(test1) > 0 or len(test2) > 0)

		#
		# Connect to our database
		#
		if len(config.ENVIRONMENT["DB_HOST"]):
			database.connect(
				engine   = "mysql",
				host     = config.ENVIRONMENT["DB_HOST"],
				port     = config.ENVIRONMENT["DB_PORT"],
				database = config.ENVIRONMENT["DB_NAME"],
				user     = config.ENVIRONMENT["DB_USER"],
				password = config.ENVIRONMENT["DB_PASSWORD"]
			)

		#
		# Get the current theme and add framework paths
		#
		if installservice.isEngineInstalled():
			request.themeName = themeservice.getThemeName()
			themeservice.addThemeToTemplatePath(themeName=request.themeName)

		if not passthrough:
			if not installservice.isEngineInstalled() and not request.path.startswith("/install"):
				redirect("/install")

			#
			# Setup session and environment stuff
			#
			request.session = request.environ.get("beaker.session")
			request.all = dict(list(request.query.items()) + list(request.forms.items()))

			if installservice.isEngineInstalled():
				request.timezone = engineservice.getBlogTimezone()
				config.TIMEZONE = request.timezone
			else:
				config.TIMEZONE = "UTC"

			#
			# Finally call the the next method in the chain
			#
			body = callback(*args, **kwargs)
			database.disconnect()

			return body

		else:
			body = callback(*args, **kwargs)
			database.disconnect()

			return body

	return wrapper


text:
'use strict';

const projectManager = require('./lib/projectManager');

module.exports = {

	/**
	 * Creates test-project.
	 * @param {string} src
	 * @param {string|Array<string>} globCopyParams
	 * @param {string|Array<string>} globSymlinkParams
	 * @param {string} destination
	 */
	build(src, globCopyParams, globSymlinkParams, destination) {
		projectManager.create(src, globCopyParams, globSymlinkParams, destination);
	},

	/**
	 * Runs test creation
	 * @param {string} source
	 * @param {string} destination
	 */
	create(source, destination) {
		this.build(source, [
			'**',
			'!node_modules*/**',
			'!test*/**',
			'!public*/**',
			'!scriptsc*/**',
			'!configs*/**',
			'!lib*/**',
			'!l10n*/**',
			'!processes.json',
			'!routes.js',
			'!gemini*/**'
		], [
			'node_modules',
			'lib',
			'scripts',
			'configs',
			'l10n',
			'gemini'
		], destination);
	}
};


text:
/*
 * The following macro invocations define error codes returned by various cg
 * API functions.
 *
 * The macros have the form :
 *
 *   CG_ERROR_MACRO(code, enum_name, message)
 *
 *     code      : The integer error code associated with the error.
 *     enum_name : The name of enumerant of the error code in the API.
 *     message   : A description string associated with the error.
 *
 */

CG_ERROR_MACRO(0,
               CG_NO_ERROR,
               "No error has occurred.")

CG_ERROR_MACRO(1,
               CG_COMPILER_ERROR,
               "The compile returned an error.")

CG_ERROR_MACRO(2,
               CG_INVALID_PARAMETER_ERROR,
               "The parameter used is invalid.")

CG_ERROR_MACRO(3,
               CG_INVALID_PROFILE_ERROR,
               "The profile is not supported.")

CG_ERROR_MACRO(4,
               CG_PROGRAM_LOAD_ERROR,
               "The program could not load.")

CG_ERROR_MACRO(5,
               CG_PROGRAM_BIND_ERROR,
               "The program could not bind.")

CG_ERROR_MACRO(6,
               CG_PROGRAM_NOT_LOADED_ERROR,
               "The program must be loaded before this operation may be used.")

CG_ERROR_MACRO(7,
               CG_UNSUPPORTED_GL_EXTENSION_ERROR,
               "An unsupported GL extension was required to perform this operation.")

CG_ERROR_MACRO(8,
               CG_INVALID_VALUE_TYPE_ERROR,
               "An unknown value type was assigned to a parameter.")

CG_ERROR_MACRO(9,
               CG_NOT_MATRIX_PARAM_ERROR,
               "The parameter is not of matrix type.")

CG_ERROR_MACRO(10,
               CG_INVALID_ENUMERANT_ERROR,
               "The enumerant parameter has an invalid value.")

CG_ERROR_MACRO(11,
               CG_NOT_4x4_MATRIX_ERROR,
               "The parameter must be a 4x4 matrix type.")

CG_ERROR_MACRO(12,
               CG_FILE_READ_ERROR,
               "The file could not be read.")

CG_ERROR_MACRO(13,
               CG_FILE_WRITE_ERROR,
               "The file could not be written.")

CG_ERROR_MACRO(14,
               CG_NVPARSE_ERROR,
               "nvparse could not successfully parse the output from the Cg "
               "compiler backend.")

CG_ERROR_MACRO(15,
               CG_MEMORY_ALLOC_ERROR,
               "Memory allocation failed.")

CG_ERROR_MACRO(16,
               CG_INVALID_CONTEXT_HANDLE_ERROR,
               "Invalid context handle.")

CG_ERROR_MACRO(17,
               CG_INVALID_PROGRAM_HANDLE_ERROR,
               "Invalid program handle.")

CG_ERROR_MACRO(18,
               CG_INVALID_PARAM_HANDLE_ERROR,
               "Invalid parameter handle.")

CG_ERROR_MACRO(19,
               CG_UNKNOWN_PROFILE_ERROR,
               "The specified profile is unknown.")

CG_ERROR_MACRO(20,
               CG_VAR_ARG_ERROR,
               "The variable arguments were specified incorrectly.")

CG_ERROR_MACRO(21,
               CG_INVALID_DIMENSION_ERROR,
               "The dimension value is invalid.")

CG_ERROR_MACRO(22,
               CG_ARRAY_PARAM_ERROR,
               "The parameter must be an array.")

CG_ERROR_MACRO(23,
               CG_OUT_OF_ARRAY_BOUNDS_ERROR,
               "Index into the array is out of bounds.")

CG_ERROR_MACRO(24,
               CG_CONFLICTING_TYPES_ERROR,
               "A type being added to the context conflicts with an "
               "existing type.")

CG_ERROR_MACRO(25,
               CG_CONFLICTING_PARAMETER_TYPES_ERROR,
               "The parameters being bound have conflicting types.")

CG_ERROR_MACRO(26,
               CG_PARAMETER_IS_NOT_SHARED_ERROR,
               "The parameter must be global.")

CG_ERROR_MACRO(27,
               CG_INVALID_PARAMETER_VARIABILITY_ERROR,
               "The parameter could not be changed to the given variability.")

CG_ERROR_MACRO(28,
               CG_CANNOT_DESTROY_PARAMETER_ERROR,
               "Cannot destroy the parameter.  It is bound to other parameters "
               "or is not a root parameter.")

CG_ERROR_MACRO(29,
               CG_NOT_ROOT_PARAMETER_ERROR,
               "The parameter is not a root parameter.")

CG_ERROR_MACRO(30,
               CG_PARAMETERS_DO_NOT_MATCH_ERROR,
               "The two parameters being bound do not match.")

CG_ERROR_MACRO(31,
               CG_IS_NOT_PROGRAM_PARAMETER_ERROR,
               "The parameter is not a program parameter.")

CG_ERROR_MACRO(32,
               CG_INVALID_PARAMETER_TYPE_ERROR,
               "The type of the parameter is invalid.")

CG_ERROR_MACRO(33,
               CG_PARAMETER_IS_NOT_RESIZABLE_ARRAY_ERROR,
               "The parameter must be a resizable array.")

CG_ERROR_MACRO(34,
               CG_INVALID_SIZE_ERROR,
               "The size value is invalid.")

CG_ERROR_MACRO(35,
               CG_BIND_CREATES_CYCLE_ERROR,
               "Cannot bind the given parameters.  Binding will form a cycle.")

CG_ERROR_MACRO(36,
               CG_ARRAY_TYPES_DO_NOT_MATCH_ERROR,
               "Cannot bind the given parameters.  Array types do not match.")

CG_ERROR_MACRO(37,
               CG_ARRAY_DIMENSIONS_DO_NOT_MATCH_ERROR,
               "Cannot bind the given parameters.  "
               "Array dimensions do not match.")

CG_ERROR_MACRO(38,
               CG_ARRAY_HAS_WRONG_DIMENSION_ERROR,
               "The array has the wrong dimension.")

CG_ERROR_MACRO(39,
               CG_TYPE_IS_NOT_DEFINED_IN_PROGRAM_ERROR,
               "Connecting the parameters failed because The type of the "
               "source parameter is not defined within the given program "
               "or does not match the type with the same name in the program.")

CG_ERROR_MACRO(40,
               CG_INVALID_EFFECT_HANDLE_ERROR,
               "Invalid effect handle.")

CG_ERROR_MACRO(41,
               CG_INVALID_STATE_HANDLE_ERROR,
               "Invalid state handle.")

CG_ERROR_MACRO(42,
               CG_INVALID_STATE_ASSIGNMENT_HANDLE_ERROR,
               "Invalid stateassignment handle.")

CG_ERROR_MACRO(43,
               CG_INVALID_PASS_HANDLE_ERROR,
               "Invalid pass handle.")

CG_ERROR_MACRO(44,
               CG_INVALID_ANNOTATION_HANDLE_ERROR,
               "Invalid annotation handle.")

CG_ERROR_MACRO(45,
               CG_INVALID_TECHNIQUE_HANDLE_ERROR,
               "Invalid technique handle.")

// Do not use this!  Use CG_INVALID_PARAM_HANDLE_ERROR instead.
CG_ERROR_MACRO(46,
               CG_INVALID_PARAMETER_HANDLE_ERROR,
               "Invalid parameter handle.")

CG_ERROR_MACRO(47,
               CG_STATE_ASSIGNMENT_TYPE_MISMATCH_ERROR,
               "Operation is not valid for this type of stateassignment.")

CG_ERROR_MACRO(48,
               CG_INVALID_FUNCTION_HANDLE_ERROR,
               "Invalid function handle.")

CG_ERROR_MACRO(49,
               CG_INVALID_TECHNIQUE_ERROR,
               "Technique did not pass validation.")

CG_ERROR_MACRO(50,
               CG_INVALID_POINTER_ERROR,
               "The supplied pointer is NULL.")

CG_ERROR_MACRO(51,
               CG_NOT_ENOUGH_DATA_ERROR,
               "Not enough data was provided.")

CG_ERROR_MACRO(52,
               CG_NON_NUMERIC_PARAMETER_ERROR,
               "The parameter is not of a numeric type.")

CG_ERROR_MACRO(53,
               CG_ARRAY_SIZE_MISMATCH_ERROR,
               "The specified array sizes are not compatible with the given array.")

CG_ERROR_MACRO(54,
               CG_CANNOT_SET_NON_UNIFORM_PARAMETER_ERROR,
               "Cannot set the value of a non-uniform parameter.")

CG_ERROR_MACRO(55,
               CG_DUPLICATE_NAME_ERROR,
               "This name is already in use.")

#undef CG_ERROR_MACRO


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

<title>GenreController</title>
<meta name="date" content="2016-04-27">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

limmen.controllers

Class GenreController

java.lang.Object

limmen.controllers.GenreController

@RestController
 @CrossOrigin
 @RequestMapping(value="/resources/genres")
public class GenreController
extends java.lang.Object

RestController for the resource pointed by the url: /resources/genres*

Author:

Kim Hammar on 2016-03-22.

Constructor Summary

Constructors

Constructor and Description

GenreController(GenreService genreService)

Method to be injected by the Spring container.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

org.springframework.http.HttpEntity<GenreRepresentation>
createNewGenre(Genre genre)

Method to handle HTTP POST-requests for /resources/genres

org.springframework.http.HttpEntity<GenreRepresentation>
deleteGenre(int genreId)

Method to handle HTTP DELETE-requests for /resources/genres/{genreId}

org.springframework.http.HttpEntity<GenresArrayRepresentation>
getAllGenres(java.lang.String genreId,
            java.lang.String name,
            java.lang.String sort)

Method to handle HTTP GET-requests for /resources/genres

org.springframework.http.HttpEntity<GenreRepresentation>
getGenre(int genreId)

Method to handle HTTP GET-requests for /resources/genres/{genreId}

org.springframework.http.HttpEntity<GenreRepresentation>
updateGenre(int genreId,
           Genre genre)

Method to handle HTTP PUT-requests for /resources/genres/{genreId}

org.springframework.http.HttpEntity<GenresArrayRepresentation>
updateGenres(java.util.List<Genre> putGenres)

Method to handle PUT-requests for /resources/genres

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

GenreController

@Inject
public GenreController(GenreService genreService)

Method to be injected by the Spring container. Initializes the service.

Parameters:

genreService - service that handles genre-data.

Method Detail

getAllGenres

@CrossOrigin
 @RequestMapping(value="",
                method=GET,
                produces="application/json")
public org.springframework.http.HttpEntity<GenresArrayRepresentation> getAllGenres(@RequestParam(name="genreId",required=false)
                                                                                java.lang.String genreId,
                                                                                @RequestParam(name="name",required=false)
                                                                                java.lang.String name,
                                                                                @RequestParam(name="sort",required=false)
                                                                                java.lang.String sort)
                                                                                throws SortException

Method to handle HTTP GET-requests for /resources/genres

Returns:

HTTP-response, JSON array of genres

Throws:

SortException

getGenre

@CrossOrigin
 @RequestMapping(value="/{genreId}",
                method=GET,
                produces="application/json")
public org.springframework.http.HttpEntity<GenreRepresentation> getGenre(@PathVariable
                                                                                int genreId)

Method to handle HTTP GET-requests for /resources/genres/{genreId}

Parameters:

genreId - id of the genre.

Returns:

HTTP-response, JSON representation of the genre

createNewGenre

@CrossOrigin
 @RequestMapping(value="",
                method=POST,
                produces="application/json",
                consumes="application/json")
public org.springframework.http.HttpEntity<GenreRepresentation> createNewGenre(@RequestBody
                                                                                Genre genre)

Method to handle HTTP POST-requests for /resources/genres

Parameters:

genre - posted genre data

Returns:

HTTP-response, JSON representation of the created genre

updateGenre

@CrossOrigin
 @RequestMapping(value="/{genreId}",
                method=PUT,
                produces="application/json",
                consumes="application/json")
public org.springframework.http.HttpEntity<GenreRepresentation> updateGenre(@PathVariable
                                                                                int genreId,
                                                                                @RequestBody
                                                                                Genre genre)

Method to handle HTTP PUT-requests for /resources/genres/{genreId}

Parameters:

genreId - id of the genre

genre - put genre data

Returns:

HTTP-Response, JSON representation of the updated genre representation

updateGenres

@CrossOrigin
 @RequestMapping(value="",
                method=PUT,
                produces="application/json",
                consumes="application/json")
public org.springframework.http.HttpEntity<GenresArrayRepresentation> updateGenres(@RequestBody
                                                                                java.util.List<Genre> putGenres)

Method to handle PUT-requests for /resources/genres

Parameters:

putGenres -

Returns:

HTTP-Response, JSON representation of the updated genres resource

deleteGenre

@CrossOrigin
 @RequestMapping(value="/{genreId}",
                method=DELETE,
                produces="application/json")
public org.springframework.http.HttpEntity<GenreRepresentation> deleteGenre(@PathVariable
                                                                                int genreId)

Method to handle HTTP DELETE-requests for /resources/genres/{genreId}

Parameters:

genreId - id of the genre

Returns:

HTTP-Response, JSON representation of the deleted genre.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.jitsi.impl.androidcertdialog;

import net.java.sip.communicator.service.certificate.*;
import net.java.sip.communicator.util.*;

import org.osgi.framework.*;

/**
 * Activator of <tt>VerifyCertificateDialogService</tt> Android implementation.
 *
 * @author Pawel Domas
 */
public class CertificateDialogActivator
    extends SimpleServiceActivator<CertificateDialogServiceImpl>
{
    /**
     * Creates new instance of CertificateDialogActivator.
     */
    public CertificateDialogActivator()
    {
        super(VerifyCertificateDialogService.class,
              "Android verify certificate service");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected CertificateDialogServiceImpl createServiceImpl()
    {
        impl = new CertificateDialogServiceImpl();
        return impl;
    }

    /**
     * Cached instance of service impl.
     */
    public static CertificateDialogServiceImpl impl;

    /**
     * Gets the <tt>VerifyCertDialog</tt> for given <tt>requestId</tt>.
     *
     * @param requestId identifier of the request managed by
     *                  <tt>CertificateDialogServiceImpl</tt>.
     *
     * @return <tt>VerifyCertDialog</tt> for given <tt>requestId</tt> or
     *         <tt>null</tt> if service has been shutdown.
     */
    public static VerifyCertDialog getDialog(Long requestId)
    {
        if(impl != null)
        {
            return impl.retrieveDialog(requestId);
        }
        else
        {
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void stop(BundleContext bundleContext)
            throws Exception
    {
        super.stop(bundleContext);

        // Clears service reference
        impl = null;
    }
}


text:
<?php

use JsonRPC\ProcedureHandler;

require_once __DIR__.'/../vendor/autoload.php';

class A
{
    public function getAll($p1, $p2, $p3 = 4)
    {
        return $p1 + $p2 + $p3;
    }
}

class B
{
    public function getAll($p1)
    {
        return $p1 + 2;
    }
}

class ClassWithBeforeMethod
{
    private $foobar = '';

    public function before($procedure)
    {
        $this->foobar = $procedure;
    }

    public function myProcedure()
    {
        return $this->foobar;
    }
}

class ProcedureHandlerTest extends PHPUnit_Framework_TestCase
{
    public function testProcedureNotFound()
    {
        $this->setExpectedException('BadFunctionCallException');
        $handler = new ProcedureHandler;
        $handler->executeProcedure('a');
    }

    public function testCallbackNotFound()
    {
        $this->setExpectedException('BadFunctionCallException');
        $handler = new ProcedureHandler;
        $handler->withCallback('b', function() {});
        $handler->executeProcedure('a');
    }

    public function testClassNotFound()
    {
        $this->setExpectedException('BadFunctionCallException');
        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllTasks', 'c', 'getAll');
        $handler->executeProcedure('getAllTasks');
    }

    public function testMethodNotFound()
    {
        $this->setExpectedException('BadFunctionCallException');
        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllTasks', 'A', 'getNothing');
        $handler->executeProcedure('getAllTasks');
    }

    public function testIsPositionalArguments()
    {
        $handler = new ProcedureHandler;
        $this->assertFalse($handler->isPositionalArguments(
            array('a' => 'b', 'c' => 'd')
        ));

        $handler = new ProcedureHandler;
        $this->assertTrue($handler->isPositionalArguments(
            array('a', 'b', 'c')
        ));
    }

    public function testBindNamedArguments()
    {
        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllA', 'A', 'getAll');
        $handler->withClassAndMethod('getAllB', 'B', 'getAll');
        $handler->withClassAndMethod('getAllC', new B, 'getAll');
        $this->assertEquals(6, $handler->executeProcedure('getAllA', array('p2' => 4, 'p1' => -2)));
        $this->assertEquals(10, $handler->executeProcedure('getAllA', array('p2' => 4, 'p3' => 8, 'p1' => -2)));
        $this->assertEquals(6, $handler->executeProcedure('getAllB', array('p1' => 4)));
        $this->assertEquals(5, $handler->executeProcedure('getAllC', array('p1' => 3)));
    }

    public function testBindPositionalArguments()
    {
        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllA', 'A', 'getAll');
        $handler->withClassAndMethod('getAllB', 'B', 'getAll');
        $this->assertEquals(6, $handler->executeProcedure('getAllA', array(4, -2)));
        $this->assertEquals(2, $handler->executeProcedure('getAllA', array(4, 0, -2)));
        $this->assertEquals(4, $handler->executeProcedure('getAllB', array(2)));
    }

    public function testRegisterNamedArguments()
    {
        $handler = new ProcedureHandler;
        $handler->withCallback('getAllA', function($p1, $p2, $p3 = 4) {
            return $p1 + $p2 + $p3;
        });

        $this->assertEquals(6, $handler->executeProcedure('getAllA', array('p2' => 4, 'p1' => -2)));
        $this->assertEquals(10, $handler->executeProcedure('getAllA', array('p2' => 4, 'p3' => 8, 'p1' => -2)));
    }

    public function testRegisterPositionalArguments()
    {
        $handler = new ProcedureHandler;
        $handler->withCallback('getAllA', function($p1, $p2, $p3 = 4) {
            return $p1 + $p2 + $p3;
        });

        $this->assertEquals(6, $handler->executeProcedure('getAllA', array(4, -2)));
        $this->assertEquals(2, $handler->executeProcedure('getAllA', array(4, 0, -2)));
    }

    public function testTooManyArguments()
    {
        $this->setExpectedException('InvalidArgumentException');

        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllC', new B, 'getAll');
        $handler->executeProcedure('getAllC', array('p1' => 3, 'p2' => 5));
    }

    public function testNotEnoughArguments()
    {
        $this->setExpectedException('InvalidArgumentException');

        $handler = new ProcedureHandler;
        $handler->withClassAndMethod('getAllC', new B, 'getAll');
        $handler->executeProcedure('getAllC');
    }

    public function testBeforeMethod()
    {
        $handler = new ProcedureHandler;
        $handler->withObject(new ClassWithBeforeMethod);
        $handler->withBeforeMethod('before');
        $this->assertEquals('myProcedure', $handler->executeProcedure('myProcedure'));
    }
}


text:
/* get text from all divs of class messages */
$('.messages').each(function () {
    toast_text = $(this).text();
    if (toast_text != ""){
        Materialize.toast(toast_text, 10000);
    }
});


text:
package com.ywl5320.adviewpager;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import adutils.AdViewpagerUtil;

public class MainActivity extends AppCompatActivity {

    private ViewPager viewpager;
    private LinearLayout lydots;
    private TextView tvtxt;
    private String[] urls;
    private AdViewpagerUtil adViewpagerUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        lydots = (LinearLayout) findViewById(R.id.ly_dots);
        tvtxt = (TextView) findViewById(R.id.tv_txt);

        urls = new String[5];
        urls[0] = "http://imgsrc.baidu.com/forum/pic/item/4bed2e738bd4b31c2958c52c87d6277f9f2ff8c5.jpg";
        urls[1] = "http://ww1.sinaimg.cn/mw600/b4ece975tw1e33ep5rqfmj.jpg";
        urls[2] = "http://img2.duitang.com/uploads/item/201204/22/20120422200645_TUrrj.thumb.600_0.jpeg";
        urls[3] = "http://www.laozu.com/d/file/news/baguaquwen/2014-12-25/2e8381506499688a412dff83047c2db2.jpg";
        urls[4] = "http://www.haofanben.com/uploads/allimg/140625/0951046053-0.jpg";

        adViewpagerUtil = new AdViewpagerUtil(this, viewpager, lydots, 8, 4, urls);
        adViewpagerUtil.initVps();
        adViewpagerUtil.setOnAdItemClickListener(new AdViewpagerUtil.OnAdItemClickListener() {
            @Override
            public void onItemClick(View v, int flag) {
                Toast.makeText(MainActivity.this, "flag:" + flag, Toast.LENGTH_SHORT).show();
            }
        });
        adViewpagerUtil.setOnAdPageChangeListener(new AdViewpagerUtil.OnAdPageChangeListener() {
            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                if(arg0 == 0)
                    arg0 = 1;
                if(arg0 == urls.length + 1)
                {
                    arg0 = urls.length;
                }
                tvtxt.setText("第" + arg0 + "张");
            }
        });
    }
}


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011 Bucknell University
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Tiago G. Rodrigues (tgr002@bucknell.edu)
 */

#include "ns3/log.h"
#include "ns3/string.h"
#include "ns3/boolean.h"

#include "data-collection-object.h"

namespace ns3 {

NS_LOG_COMPONENT_DEFINE ("DataCollectionObject");

NS_OBJECT_ENSURE_REGISTERED (DataCollectionObject);

TypeId
DataCollectionObject::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::DataCollectionObject")
    .SetParent<Object> ()
    .SetGroupName ("Stats")
    .AddConstructor<DataCollectionObject> ()
    .AddAttribute ( "Name",
                    "Object's name",
                    StringValue ("unnamed"), MakeStringAccessor (&DataCollectionObject::GetName, &DataCollectionObject::SetName), MakeStringChecker ())
    .AddAttribute ( "Enabled",
                    "Object's enabled status",
                    BooleanValue (true), MakeBooleanAccessor (&DataCollectionObject::m_enabled), MakeBooleanChecker ())
  ;
  return tid;
}

DataCollectionObject::DataCollectionObject ()
{
}

DataCollectionObject::~DataCollectionObject ()
{
  NS_LOG_FUNCTION (this);
}

bool
DataCollectionObject::IsEnabled (void) const
{
  return m_enabled;
}

std::string
DataCollectionObject::GetName (void) const
{
  return m_name;
}

void
DataCollectionObject::SetName (std::string name)
{
  NS_LOG_FUNCTION (this << name);
  for (size_t pos = name.find (" "); pos != std::string::npos; pos = name.find (" ", pos + 1, 1))
    {
      name[pos] = '_';
    }

  m_name = name;
}

void
DataCollectionObject::Enable (void)
{
  NS_LOG_FUNCTION (this);
  m_enabled = true;
}

void
DataCollectionObject::Disable (void)
{
  NS_LOG_FUNCTION (this);
  m_enabled = false;
}

} // namespace ns3


text:
import traceback
import sys
import os
import cherrypy
import htpc
import urllib2
import gzip
import socket
from json import loads, dumps
import logging
import cookielib
from StringIO import StringIO
from cherrypy.lib.auth2 import require

class Deluge:

    cookieJar = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))

    def __init__(self):
        self.logger = logging.getLogger('modules.deluge')
        htpc.MODULES.append({
            'name': 'Deluge',
            'id': 'deluge',
            'test': htpc.WEBDIR + 'deluge/ping',
            'fields': [
                {'type': 'bool', 'label': 'Enable', 'name': 'deluge_enable'},
                {'type': 'text', 'label': 'Menu name', 'name': 'deluge_name'},
                {'type': 'text', 'label': 'IP / Host *', 'name': 'deluge_host'},
                {'type': 'text', 'label': 'Port *', 'name': 'deluge_port'},
                {'type': 'bool', 'label': 'Use SSL', 'name': 'deluge_ssl'},
                {'type': 'text', 'label': 'Basepath', 'name': 'deluge_basepath'},
                {'type': 'password', 'label': 'Password', 'name': 'deluge_password'}
        ]})

    @cherrypy.expose()
    @require()
    def index(self):
        return htpc.LOOKUP.get_template('deluge.html').render(scriptname='deluge')

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def connected(self):
        return self.fetch('web.connected')

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def connect(self,hostid):
        return self.fetch('web.connect',[hostid])

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def get_hosts(self):
        return self.fetch('web.get_hosts')

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def queue(self):
        fields = ['progress','is_finished','ratio','name','download_payload_rate','upload_payload_rate','eta','state','hash','total_size']
        return self.fetch('core.get_torrents_status', [[],fields])

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def stats(self):
        fields = ["payload_download_rate","payload_upload_rate"]
        return self.fetch('core.get_session_status',[fields])

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def start(self, torrentId):
        torrents = [torrentId]
        return self.fetch('core.resume_torrent', [torrents])

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def stop(self, torrentId):
        torrents = [torrentId]
        return self.fetch('core.pause_torrent',[torrents])

    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def remove(self, torrentId, removeData):
        removeDataBool = bool(int(removeData));
        return self.fetch('core.remove_torrent', [torrentId,removeDataBool])

    # Wrapper to access the Deluge Api
    # If the first call fails, there probably is no valid Session ID so we try it again
    def fetch(self, method, arguments=[]):
        """ Do request to Deluge api """
        self.logger.debug("Request deluge method: "+method)

        # format post data
        data = {'id':1,'method': method,'params':arguments}

        response = self.read_data(data)
        self.logger.debug ("response is %s" %response)
        if response and response['error']:
            self.auth()
            response = self.read_data(data)
            self.logger.debug ("response is %s" %response)
        return response

    def auth(self):
        self.read_data({"method": "auth.login","params": [htpc.settings.get('deluge_password', '')],"id": 1})

    def read_data(self,data):
        try:
            self.logger.debug("Read data from server")

            host = htpc.settings.get('deluge_host', '')
            port = str(htpc.settings.get('deluge_port', ''))

            host = htpc.settings.get('deluge_host', '')
            port = str(htpc.settings.get('deluge_port', ''))
            deluge_basepath = str(htpc.settings.get('deluge_basepath', ''))
            ssl = 's' if htpc.settings.get('deluge_ssl') else ''

            url = 'http' + ssl + '://' +  host + ':' + str(port) + deluge_basepath + '/json'

            post_data = dumps(data)
            buf = StringIO( self.opener.open(url, post_data,1).read())
            f = gzip.GzipFile(fileobj=buf)
            response = loads(f.read())
            self.logger.debug ("response for %s is %s" %(data,response))
            return response
        except urllib2.URLError:
            self.logger.error ("can't connect with %s" %data)
            return {'result':{},'error':"can't connect with %s" %data}
        except socket.timeout:
            self.logger.error ("timeout when connect with %s" %data)
            return {'result':{},'error':"can't connect with %s" %data}


text:
<link rel="stylesheet" href="blink.css" type="text/css" media="screen">

<blink>
  Look at me!
</blink>

  To use, just include the blink.css stylesheet! Just use the blink tag, and it blinks!


text:
Audiopile

        <button ng-click="toggleSignup()" class="login">Signup</button>
        <button ng-click="toggleLogin()" class="login">Login</button>

Upload uncompressed audio in any format

Automatic audio transcoding and normalization

Backup source files, stream lower resolution mp3

Collaborate and share audio with your group

    <form ng-show="showLogin" name="loginForm" class="login-form">
      <fieldset>
        <legend>Login</legend>

          <input ng-focus="loginError = '';" name="email" ng-field ng-model="user.email" placeholder="email" type="email" ng-pattern="/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/" ng-model-options="{ updateOn: 'blur' }" required focus-if="showLogin">

            Required!
            Not valid email!

          <input type="password" name="password" ng-model="user.password" placeholder="password" ng-focus="loginError = '';"  my-enter="login()" required />

            Required!

          <button class="button-primary" ng-click="login()" ng-disabled="loginForm.$invalid">Login</button>

            {{loginError}}

        </fieldset>
      </form>

    <form ng-show="showSignup" name="signupForm" class="login-form">
      <fieldset>
        <legend>Signup</legend>

            <input ng-focus="signupError = '';" name="email" ng-field ng-model="user.email" placeholder="email" type="email" ng-pattern="/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/" ng-model-options="{ updateOn: 'blur' }" required focus-if="showSignup"/>

              Required!
              Not valid email!

            <input ng-focus="signupError = '';" type="password" name="passwordConfirm" ng-model="newPassword" placeholder="confirm password" my-enter="signup(newPassword)" ng-minlength="8" />

              Required!
              Not valid email!

            <input type="password" name="password" ng-model="user.password" placeholder="password" ng-focus="signupError = '';" required />

              Required!

            <button ng-click="signup(newPassword)" ng-disabled="signupForm.$invalid || confirm">Signup</button>

              {{signupError}}

        </fieldset>
      </form>

AudioPile


text:
RESOURCE = ./resource
BIN = ./bin
SRC = ./src
DESTDIR = /opt/skype_unofficial_client
SHARE_APPS_DIR = /usr/share/applications
SHARE_APPS_FILE = $(SHARE_APPS_DIR)/skype-desktop.desktop
SYS_BIN_DIR = /usr/bin
SYS_BIN_FILE = $(SYS_BIN_DIR)/skype-desktop
PREFIX =

linux_x64: create_bin create_link_to_lib_if_exists create_desktop_shortcut copy_source
	mkdir -p $(PREFIX)$(DESTDIR) || echo "Skip"
	cp -p -f -R $(BIN)/linux_x64/* $(PREFIX)$(DESTDIR)/
	chmod +x $(PREFIX)$(DESTDIR)/skype

linux_x86: create_bin create_link_to_lib_if_exists create_desktop_shortcut copy_source
	mkdir -p $(PREFIX)$(DESTDIR) || echo "Skip"
	cp -p -f -R $(BIN)/linux_x86/* $(PREFIX)$(DESTDIR)/
	chmod +x $(PREFIX)$(DESTDIR)/skype

copy_source:
	mkdir -p $(PREFIX)$(DESTDIR)/js || echo "Skip"
	cp -p -f $(SRC)/package.json $(PREFIX)$(DESTDIR)/
	cp -p -f $(SRC)/skype.html $(PREFIX)$(DESTDIR)/
	cp -p -f -R $(SRC)/js/* $(PREFIX)$(DESTDIR)/js
	cp -p -f -R $(RESOURCE)/skypeweb/* $(PREFIX)$(DESTDIR)/

create_bin:
	mkdir -p $(PREFIX)$(DESTDIR) || echo "Skip"
	mkdir -p $(PREFIX)$(SYS_BIN_DIR) || echo "Skip"
	echo '#!/bin/sh' > $(PREFIX)$(SYS_BIN_FILE)
	echo "cd $(PREFIX)$(DESTDIR)" >> $(PREFIX)$(SYS_BIN_FILE)
	echo './skype --enable-spell-checking' >> $(PREFIX)$(SYS_BIN_FILE)
	chmod +x $(PREFIX)$(SYS_BIN_FILE)

create_desktop_shortcut:
	mkdir -p $(PREFIX)$(SHARE_APPS_DIR) || echo "Skip"
	echo "[Desktop Entry]" > $(PREFIX)$(SHARE_APPS_FILE)
	echo "Version=1.0" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Type=Application" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Name=Skype" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Comment=An unofficial client of Skype for Linux, running on top of Node Webkit." >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Icon=$(PREFIX)/opt/skype_unofficial_client/skype.png" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Exec=$(PREFIX)/opt/skype_unofficial_client/skype --enable-spell-checking %U" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "StartupWMClass=crx_monljlleikpphbhopghghdbggidfahha" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "NoDisplay=false" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Categories=Network;" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "StartupNotify=false" >> $(PREFIX)$(SHARE_APPS_FILE)
	echo "Terminal=false" >> $(PREFIX)$(SHARE_APPS_FILE)

create_link_to_lib_if_exists:
	mkdir -p $(PREFIX)$(DESTDIR) || echo "Skip"
	if [ -d /opt/google/chrome/PepperFlash ] && [ ! -d $(PREFIX)$(DESTDIR)/PepperFlash ]; then ln -s /opt/google/chrome/PepperFlash $(PREFIX)$(DESTDIR)/PepperFlash; fi
	if [ -d ~/.config/chromium/PepperFlash ] && [ ! -d $(PREFIX)$(DESTDIR)/PepperFlash ]; then ln -s ~/.config/chromium/PepperFlash $(PREFIX)$(DESTDIR)/PepperFlash; fi
	if [ -d /usr/lib/PepperFlash ] && [ ! -d $(PREFIX)$(DESTDIR)/PepperFlash ]; then ln -s /usr/lib/PepperFlash $(PREFIX)$(DESTDIR)/PepperFlash; fi


text:
@implementation AppDelegate (AppService)

+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

-(UIViewController *)getCurrentVC{

    UIViewController *result = nil;

    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }

    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;

    return result;
}

-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];

    if ([superVC isKindOfClass:[UITabBarController class]]) {

        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;

        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {

            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {

            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}

@end


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Acqinfo" do
  it "should be present" do
    @ead.archdesc.acqinfo.should be_a_kind_of(Eadsax::Acqinfo)
  end
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>DocStrap Source: utils/lifecycle.js</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.cosmo.css">

			DocStrap

					Modules

							base

							base/chains

							document/binder

							document/collector

							document/cursor

							document/document

							document/probe

							document/schema

							events/bussable

							events/signalable

							strings/format

							utils/construct

							utils/logger

					Classes

							base

							base/chains

							document/document

							document/collector~ACollector

							document/collector~CollectorBase

							document/collector~OCollector

							document/cursor~Cursor

							document/probe.queryOperators

							document/probe.updateOperators

							events/signalable~Signal

					Mixins

							document/schema

							events/bussable

							events/signalable

Source: utils/lifecycle.js

"use strict";
/**
 * @fileOverview Tools to integrate and compose objects
 * @module utils/construct
 */
var sys = require( "lodash" );
var dcl = require( "dcl" );
/**
 * Mixes one thing into another
 * @param {function|object} Source The thing to mixin into the `target`. This can
 * be an object or a class. If a class, `Source` is added to `target`'s prototype.
 * @param target
 * @returns {*}
 */
exports.mix = function ( Source, target ) {
//	if ( sys.isFunction( target ) ) {
//		return dcl( [target, Source], {} );
//	} else {
//		var instance
//		instance = new Source();
//		return sys.extend( target, instance );
//	}
};

exports.safeMix = function ( C, obj ) {
	if ( sys.isFunction( obj ) ) {
		return dcl( [obj, C], {} );
	} else {
		var instance = new C();
		return sys.defaults( obj, instance );
	}
};

exports.extend = function ( roots, def ) {
	return dcl( roots, def );
};

exports.use = function ( C, exp ) {
	exp.mix = sys.partial( exports.mix, C );
	exp.safeMix = sys.partial( exports.safeMix, C );
	exp.extend = function ( roots, def ) {
		if ( arguments.length === 1 ) {
			return exports.extend( C, def );
		} else {
			if ( sys.isArray( roots ) ) {
				roots.push( C );
			} else {
				roots = [roots, C];
			}
			return exports.extend( roots, def );
		}
	};
};

		DocStrap Copyright © 2012-2014 The contributors to the JSDoc3 and DocStrap projects.

		Documentation generated by JSDoc 3.3.0-alpha9
		on Fri Jul 18th 2014 using the DocStrap template.