text:
// The MIT License (MIT)
//
// Copyright (c) 2016 Nelson Corrêa V. Júnior
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.Threading.Tasks;

namespace EnjoyCQRS.EventSource.Storage
{
    /// <summary>
    /// Represents an abstraction where an instance of <see cref="Aggregate"/> will be persisted.
    /// </summary>
    public interface IRepository
    {
        /// <summary>
        /// Retrieves an <typeparam name="TAggregate"></typeparam> based on your unique identifier property.
        /// </summary>
        /// <typeparam name="TAggregate"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        Task<TAggregate> GetByIdAsync<TAggregate>(Guid id) where TAggregate : Aggregate, new();

        /// <summary>
        /// Add an instance of <typeparam name="TAggregate"></typeparam> in repository.
        /// </summary>
        /// <typeparam name="TAggregate"></typeparam>
        /// <param name="aggregate"></param>
        Task AddAsync<TAggregate>(TAggregate aggregate) where TAggregate : Aggregate;
    }
}


text:
//
//  SRHubservable.h
//  SignalR
//
//  Created by Alex Billingsley on 11/4/11.
//  Copyright (c) 2011 DyKnow LLC. (http://dyknow.com/)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
//  documentation files (the "Software"), to deal in the Software without restriction, including without limitation
//  the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
//  to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of
//  the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
//  THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
//  CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
//  DEALINGS IN THE SOFTWARE.
//

#import <Foundation/Foundation.h>
#import "SRHubProxyInterface.h"

@class SRSubscription;

/**
 * An `SRHubservable` object provides interface for adding Subscriptions to an SRHubProxy
 */
@interface SRHubservable : NSObject

///-------------------------------
/// @name Properties
///-------------------------------

/**
 * An `NSString` object representing the name of the subscription event
 */
@property (strong, nonatomic, readonly) NSString *eventName;

/**
 * An `SRHubProxy` object representing the Hub to be observed
 */
@property (strong, nonatomic, readonly) id <SRHubProxyInterface> proxy;

///-------------------------------
/// @name Initializing an SRHubservable Object
///-------------------------------

/**
 * A convenience method for initWithProxy:(SRHubProxy *)proxy eventName:(NSString *)eventName;
 *
 *
 *  SRHubservable *observable = [SRHubservable observe:myHub event:@"myEvent"];
 *
 *
 * @param proxy the `SRHubProxy` object representing the Hub to be observed
 * @param eventName the `NSString` object representing the name of the subscription event
 * @return an `SRHubservable` object
 */
+ (instancetype)observe:(id <SRHubProxyInterface>)proxy event:(NSString *)eventName;

/**
 * Initializes a new `SRHubservable` object
 *
 *
 *  SRHubservable *observable = [SRHubservable observe:myHub event:@"myEvent"];
 *
 *
 * @param proxy the `SRHubProxy` object representing the Hub to be observed
 * @param eventName the `NSString` object representing the name of the subscription event
 * @return an `SRHubservable` object
 */
- (instancetype)initWithProxy:(id <SRHubProxyInterface>)proxy eventName:(NSString *)eventName;

///-------------------------------
/// @name Adding Subscriptions
///-------------------------------

/**
 * Adds a new Subscription to the underlying proxy for eventName
 *
 * @param object The receiver to perform selector on
 * @param selector A selector identifying the message to send.
 * @return the `SRSubscription` object created
 */
- (SRSubscription *)subscribe:(NSObject *)object selector:(SEL)selector;

@end

redpajama_set_name: RedPajamaGithub


text:
local M = {}

function M:init()
	print("test contract transfer init")
end

function M:start()
	print("test contract transfer start")
	transfer_from_contract_to_address('A', 'ALP', 50)
    return 123
end

return M


text:
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Startkicker.Api.Startup))]

namespace Startkicker.Api
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
package org.drooms.impl;

import org.assertj.core.api.Assertions;
import org.drooms.api.Node;
import org.drooms.api.Playground;
import org.junit.Test;

import java.util.List;

public class DefaultPlaygroundTest {

    @Test
    public void testGoodPlayground() {
        final Playground p = new DefaultGame().buildPlayground("test",
                this.getClass().getResourceAsStream("good_playground.txt"));
        Assertions.assertThat(p.getWidth()).isEqualTo(4);
        Assertions.assertThat(p.getHeight()).isEqualTo(5);
        final List<Node> startingPositions = p.getStartingPositions();
        Assertions.assertThat(startingPositions).hasSize(2);
    }

    @Test(expected = IllegalStateException.class)
    public void testBadPortal1() {
        new DefaultGame().buildPlayground("test", this.getClass().getResourceAsStream("playground_multiportal.txt"));
    }

    @Test(expected = IllegalStateException.class)
    public void testBadPortal2() {
        new DefaultGame().buildPlayground("test",
                this.getClass().getResourceAsStream("playground_unfinished_portal.txt"));
    }
}


text:
#include "UnaryXInverseGate.h"

void UnaryXInverseGate::forward(){

    // Compute local gradient
    dinput_a = -1.f/(input_a*input_a);
    // Compute forward pass
    output = 1.f/(input_a);
}

void UnaryXInverseGate::backward(){

    // Chain rule
    gradout_a = grad_input * dinput_a;
}


text:
Certbot Roles
=============

To setup a certbot account::

    - host: localhost
      become: true
      roles:
        - certbot/register

To link a letsencrypt certificate and its key::

    - host: localhost
      become: true
      roles:
        - role: certbot/link
          certs:
            - example.com

The certificate will available at `/etc/ssl/certs/example.com.crt`,
and its key at `/etc/ssl/private/example.com.key`.

See aws/certbot role.

Variables
---------

``certbot_path_certs``
  Defaults to ``/etc/letsencrypt/live/``
``certbot_ext_key``
  Defaults to ``/privkey.pem``
``certbot_ext_pem``
  Defaults to ``/fullchain.pem``

Dependencies
------------

- apt
- net
- ssl
- system


text:
fieldset {
  padding: 0;
  margin: 0;
  border: 0;
}
legend {
  display: block;
  width: 100%;
  padding: 0;
  margin-bottom: 20px;
  font-size: 21px;
  line-height: inherit;
  color: #333333;
  border: 0;
  border-bottom: 1px solid #e5e5e5;
}
label {
  display: inline-block;
  margin-bottom: 5px;
  font-weight: bold;
}
input[type="search"] {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
  margin: 4px 0 0;
  margin-top: 1px \9;
  /* IE8-9 */
  line-height: normal;
}
input[type="file"] {
  display: block;
}
select[multiple],
select[size] {
  height: auto;
}
select optgroup {
  font-size: inherit;
  font-style: inherit;
  font-family: inherit;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
  outline: thin dotted #333;
  outline: 5px auto -webkit-focus-ring-color;
  outline-offset: -2px;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  height: auto;
}
output {
  display: block;
  padding-top: 7px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555555;
  vertical-align: middle;
}
.form-control:-moz-placeholder {
  color: #999999;
}
.form-control::-moz-placeholder {
  color: #999999;
}
.form-control:-ms-input-placeholder {
  color: #999999;
}
.form-control::-webkit-input-placeholder {
  color: #999999;
}
.form-control {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.428571429;
  color: #555555;
  vertical-align: middle;
  background-color: #ffffff;
  background-image: none;
  border: 1px solid #cccccc;
  border-radius: 4px;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
  border-color: #66afe9;
  outline: 0;
  -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
  box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
  cursor: not-allowed;
  background-color: #eeeeee;
}
textarea.form-control {
  height: auto;
}
.form-group {
  margin-bottom: 15px;
}
.radio,
.checkbox {
  display: block;
  min-height: 20px;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-left: 20px;
  vertical-align: middle;
}
.radio label,
.checkbox label {
  display: inline;
  margin-bottom: 0;
  font-weight: normal;
  cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
  float: left;
  margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
  margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
  display: inline-block;
  padding-left: 20px;
  margin-bottom: 0;
  vertical-align: middle;
  font-weight: normal;
  cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
  margin-top: 0;
  margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
.radio[disabled],
.radio-inline[disabled],
.checkbox[disabled],
.checkbox-inline[disabled],
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"],
fieldset[disabled] .radio,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox,
fieldset[disabled] .checkbox-inline {
  cursor: not-allowed;
}
.input-sm {
  height: 30px;
  padding: 5px 10px;
  font-size: 12px;
  line-height: 1.5;
  border-radius: 3px;
}
select.input-sm {
  height: 30px;
  line-height: 30px;
}
textarea.input-sm {
  height: auto;
}
.input-lg {
  height: 45px;
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 6px;
}
select.input-lg {
  height: 45px;
  line-height: 45px;
}
textarea.input-lg {
  height: auto;
}
.has-warning .help-block,
.has-warning .control-label {
  color: #c09853;
}
.has-warning .form-control {
  border-color: #c09853;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-warning .input-group-addon {
  color: #c09853;
  border-color: #c09853;
  background-color: #fcf8e3;
}
.has-error .help-block,
.has-error .control-label {
  color: #b94a48;
}
.has-error .form-control {
  border-color: #b94a48;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-error .input-group-addon {
  color: #b94a48;
  border-color: #b94a48;
  background-color: #f2dede;
}
.has-success .help-block,
.has-success .control-label {
  color: #468847;
}
.has-success .form-control {
  border-color: #468847;
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-success .input-group-addon {
  color: #468847;
  border-color: #468847;
  background-color: #dff0d8;
}
.form-control-static {
  margin-bottom: 0;
}
.help-block {
  display: block;
  margin-top: 5px;
  margin-bottom: 10px;
  color: #737373;
}
@media (min-width: 768px) {
  .form-inline .form-group {
    display: inline-block;
    margin-bottom: 0;
    vertical-align: middle;
  }
  .form-inline .form-control {
    display: inline-block;
  }
  .form-inline .radio,
  .form-inline .checkbox {
    display: inline-block;
    margin-top: 0;
    margin-bottom: 0;
    padding-left: 0;
  }
  .form-inline .radio input[type="radio"],
  .form-inline .checkbox input[type="checkbox"] {
    float: none;
    margin-left: 0;
  }
}
.form-horizontal .control-label,
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
  margin-top: 0;
  margin-bottom: 0;
  padding-top: 7px;
}
.form-horizontal .form-group {
  margin-left: -15px;
  margin-right: -15px;
}
.form-horizontal .form-group:before,
.form-horizontal .form-group:after {
  content: " ";
  display: table;
}
.form-horizontal .form-group:after {
  clear: both;
}
.form-horizontal .form-group:before,
.form-horizontal .form-group:after {
  content: " ";
  display: table;
}
.form-horizontal .form-group:after {
  clear: both;
}
.form-horizontal .form-control-static {
  padding-top: 7px;
}
@media (min-width: 768px) {
  .form-horizontal .control-label {
    text-align: right;
  }
}


text:
package opennlp.tools.cmdline.parser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import opennlp.tools.cmdline.BasicCmdLineTool;
import opennlp.tools.cmdline.CLI;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.PerformanceMonitor;
import opennlp.tools.cmdline.SystemInputStreamFactory;
import opennlp.tools.parser.AbstractBottomUpParser;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Span;

public final class ParserTool extends BasicCmdLineTool {

  public String getShortDescription() {
    return "performs full syntactic parsing";
  }

  public String getHelp() {
    return "Usage: " + CLI.CMD + " " + getName() + " [-bs n -ap n -k n] model < sentences \n"
            + "-bs n: Use a beam size of n.\n"
            + "-ap f: Advance outcomes in with at least f% of the probability mass.\n"
            + "-k n: Show the top n parses.  This will also display their log-probablities.";
  }
  private static Pattern untokenizedParenPattern1 = Pattern.compile("([^ ])([({)}])");
  private static Pattern untokenizedParenPattern2 = Pattern.compile("([({)}])([^ ])");

  public static Parse[] parseLine(String line, opennlp.tools.parser.Parser parser, int numParses) {
    line = untokenizedParenPattern1.matcher(line).replaceAll("$1 $2");
    line = untokenizedParenPattern2.matcher(line).replaceAll("$1 $2");
    StringTokenizer str = new StringTokenizer(line);
    StringBuilder sb = new StringBuilder();
    List<String> tokens = new ArrayList<String>();
    while (str.hasMoreTokens()) {
      String tok = str.nextToken();
      tokens.add(tok);
      sb.append(tok).append(" ");
    }
    String text = sb.substring(0, sb.length() - 1);
    Parse p = new Parse(text, new Span(0, text.length()), AbstractBottomUpParser.INC_NODE, 0, 0);
    int start = 0;
    int i = 0;
    for (Iterator<String> ti = tokens.iterator(); ti.hasNext(); i++) {
      String tok = ti.next();
      p.insert(new Parse(text, new Span(start, start + tok.length()), AbstractBottomUpParser.TOK_NODE, 0, i));
      start += tok.length() + 1;
    }
    Parse[] parses;
    if (numParses == 1) {
      parses = new Parse[]{parser.parse(p)};
    } else {
      parses = parser.parse(p, numParses);
    }
    return parses;
  }

  public void run(String[] args) {

    if (args.length < 1) {
      System.out.println(getHelp());
    } else {

      ParserModel model = new ParserModelLoader().load(new File(args[args.length - 1]));

      Integer beamSize = CmdLineUtil.getIntParameter("-bs", args);
      if (beamSize == null) {
        beamSize = AbstractBottomUpParser.defaultBeamSize;
      }

      Integer numParses = CmdLineUtil.getIntParameter("-k", args);
      boolean showTopK;
      if (numParses == null) {
        numParses = 1;
        showTopK = false;
      } else {
        showTopK = true;
      }

      Double advancePercentage = CmdLineUtil.getDoubleParameter("-ap", args);

      if (advancePercentage == null) {
        advancePercentage = AbstractBottomUpParser.defaultAdvancePercentage;
      }

      opennlp.tools.parser.Parser parser =
              ParserFactory.create(model, beamSize, advancePercentage);

      ObjectStream<String> lineStream = null;
      PerformanceMonitor perfMon = null;
      try {
        lineStream = new PlainTextByLineStream(new SystemInputStreamFactory(), SystemInputStreamFactory.encoding());
        perfMon = new PerformanceMonitor(System.err, "sent");
        perfMon.start();
        String line;
        while ((line = lineStream.read()) != null) {
          if (line.trim().length() == 0) {
            System.out.println();
          } else {
            Parse[] parses = parseLine(line, parser, numParses);

            for (int pi = 0, pn = parses.length; pi < pn; pi++) {
              if (showTopK) {
                System.out.print(pi + " " + parses[pi].getProb() + " ");
              }

              parses[pi].show();

              perfMon.incrementCounter();
            }
          }
        }
      } catch (IOException e) {
        CmdLineUtil.handleStdinIoError(e);
      }

      perfMon.stopAndPrintFinalResult();
    }
  }
}


text:
Gradient Update Algorithm
--------------------------------------

.. toctree::
  :maxdepth: 1

  parameter_average.md


text:
package br.com.novaroma.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.novaroma.controller.Vehicle_Controller;

/**
 * Servlet implementation class Vehicle_Delete
 */
@WebServlet("/Vehicle_Delete")
public class Vehicle_Delete extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Vehicle_Controller vehicleController;

    public Vehicle_Delete() {
        super();
    }

	public void init() throws ServletException {
		this.vehicleController = new Vehicle_Controller();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String placa = request.getParameter("plaque_vehicle");

		String status = vehicleController.deleteVehicle(placa);

		if (status.equals("OK")) {
			response.sendRedirect("jsp/vehicles.jsp");
		} else {
			request.setAttribute("status", status);
			request.getRequestDispatcher("jsp/errorPage.jsp").forward(request, response);
		}
	}

}


text:
require "spec_helper"

describe IdobataIncommingWebhook::Client do
  let(:dummy_webhook_uri) { "https://idobata.io/hook/custom/dummy" }

  describe "#initialize" do
    context "without IDOBATA_WEBHOOK_URI" do
      before do
        allow(ENV).to receive(:[]).with("IDOBATA_WEBHOOK_URI").and_return nil
      end

      it "raises RuntimeError" do
        expect { described_class.new }.to raise_error RuntimeError
      end
    end

    context "with IDOBATA_WEBHOOK_URI" do
      before do
        allow(ENV).to receive(:[]).with("IDOBATA_WEBHOOK_URI").and_return dummy_webhook_uri
      end

      let(:uri) { described_class.new.instance_variable_get(:@uri) }

      it "has @uri instance variable" do
        expect(uri).to_not eq nil
      end
    end
  end

  describe "#submit" do
    before do
      allow(ENV).to receive(:[]).with("IDOBATA_WEBHOOK_URI").and_return dummy_webhook_uri
    end

    subject { described_class.new }

    it "has a method #submit" do
      is_expected.to respond_to(:submit)
    end
  end

  describe "#submit_html" do
    before do
      allow(ENV).to receive(:[]).with("IDOBATA_WEBHOOK_URI").and_return dummy_webhook_uri
    end

    subject { described_class.new }

    it "has a method #submit_html" do
      is_expected.to respond_to(:submit_html)
    end
  end
end


text:
// Change default favicon
var icon = document.querySelector('link[rel="shortcut icon"]');

icon.href = 'http://i.imgur.com/b5xPkrH.png';


text:
package org.sagebionetworks.repo.model.jdo;

import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_OWNER_TYPE;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_OWNER;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_RESOURCE_ACCESS_TYPE_ID;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_ACCESS_CONTROL_LIST;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_RESOURCE_ACCESS;
import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_RESOURCE_ACCESS_TYPE;

public class AuthorizationSqlUtil {

	public static final String AUTHORIZATION_SQL_TABLES =
			TABLE_ACCESS_CONTROL_LIST+" acl, "+
			TABLE_RESOURCE_ACCESS+" ra, "+
			TABLE_RESOURCE_ACCESS_TYPE+" at ";

	public static final String AUTHORIZATION_SQL_JOIN =
		    " acl."+COL_ACL_ID+"=ra."+COL_RESOURCE_ACCESS_OWNER+
		    " and at."+COL_RESOURCE_ACCESS_TYPE_ID+"=ra."+COL_RESOURCE_ACCESS_ID;

	/**
	 * The bind variable used to set the access type for authorization filters.
	 */
	public static final String ACCESS_TYPE_BIND_VAR = "type";
	public static final String RESOURCE_ID_BIND_VAR = "resourceId";
	public static final String PRINCIPAL_IDS_BIND_VAR = "principalIds";
	public static final String RESOURCE_TYPE_BIND_VAR = COL_ACL_OWNER_TYPE;

	/**
	 * The bind variable prefix used for group ID for the authorization SQL.
	 */
	public static final String BIND_VAR_PREFIX = "g";

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TheParkingLot.Models;
using TheParkingLot.Services;

namespace TheParkingLot
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // add AppSettings
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Cookies.ApplicationCookie.LoginPath = "/Account/Login"; })
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.AddAuthorization(options => options.AddPolicy("Administrator", policy => policy.RequireRole("Administrator")));

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "areaRoute",
                    template: "{area:exists}/{controller}/{action}",
                    defaults: new { controller = "Rounds", action = "Index" });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}


text:
// THIS SOURCE CODE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND, AND ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR NON INFRINGEMENT. THE USER ASSUMES ALL LIABILITY AND RESPONSIBILITY FOR USE OF THIS SOURCE CODE, AND NEITHER THE AUTHOR NOR JMLR, NOR JMLR'S PUBLISHERS AND DISTRIBUTORS, WILL BE LIABLE FOR DAMAGES OF ANY KIND RESULTING FROM ITS USE. Without lim- iting the generality of the foregoing, neither the author, nor JMLR, nor JMLR's publishers and distributors, warrant that the Source Code will be error-free, will operate without interruption, or will meet the needs of the user.
//
// --------------------------------------------------------------------------
//
// Copyright 2011 Stephen Piccolo
//
// This file is part of ML-Flex.
//
// ML-Flex is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ML-Flex 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 ML-Flex. If not, see <http://www.gnu.org/licenses/>.

// This line is required by Java to specify which package contains the code
package mlflex.dataprocessors;

// These import statements allow us to use other Java classes besides this one
import mlflex.core.DataInstanceCollection;
import mlflex.core.DataValues;
import mlflex.helper.MathUtilities;
import java.util.Random;

/** This class represents a trivial example of how to create a data processor. */
public class ExampleDataProcessor extends AbstractDataProcessor
{
    /** This method is used to parse/generate raw data that will be input into ML-Flex. In this example, random values for three data points and ten data instances are generated. The random values are continuous values. */
    @Override
    protected void ParseInputData() throws Exception
    {
        // Specify the names of the data points that will be used
        String[] dataPoints = new String[] {"DataPoint1", "DataPoint2", "DataPoint3"};

        // Specify the IDs of the data instances that will be used
        String[] instanceIDs = new String[] {"Instance1", "Instance2", "Instance3", "Instance4", "Instance5", "Instance6", "Instance7", "Instance8", "Instance9", "Instance10"};

        // Loop through the data points
        for (String dataPoint : dataPoints)
            // Loop through the instances
            for (String instanceID : instanceIDs)
                // Save a raw data point using the combination of data point and instance ID
                SaveRawDataPoint(dataPoint, instanceID, String.valueOf(new Random().nextDouble()));
    }

    /** After the raw data are processed and stored, various transformations can be applied to the data before it is used for machine-learning analyses. Implementing this method is one way to perform such transformations. In this example, the values are transformed to the log-2 scale. */
    @Override
    protected DataInstanceCollection TransformInstances(DataInstanceCollection rawInstances) throws Exception
    {
        // Loop through the data instances
        for (DataValues instance : rawInstances)
            // Loop through the data points for each instance
            for (String dataPoint : instance.GetDataPointNames())
            {
                // Retrieve the raw value
                String rawValue = instance.GetDataPointValue(dataPoint);

                // Convert the raw value to a numeric value
                double numericValue = Double.valueOf(rawValue);

                // Perform a log-2 transformation
                double transformedValue = MathUtilities.Log2(numericValue);

                // Update the values in the collection
                instance.UpdateDataPoint(dataPoint, String.valueOf(transformedValue));
            }

        // Return the collection of data in transformed form
        return rawInstances;
    }
}


text:
require 'spec_helper'

describe Uber::Client do
  before :each do
    @client = Uber::Client.new('WOBR2u2P1Uajsf67MCf_m_EQ-eRwluKCwRu-o624')

    @start_location = Uber::Location.new(37.646480, -121.871801)
    @end_location = Uber::Location.new(37.637349, -121.891317)
  end

  it 'should get the products' do
    products = @client.products '37', '-122'
    puts products.inspect
  end

  it 'should get accurate price estimates' do
    estimates = @client.estimate_prices(@start_location, @end_location)
    puts estimates.inspect
  end
end


text:
#ifndef SHARE_VM_OOPS_INSTANCEREFKLASS_HPP
#define SHARE_VM_OOPS_INSTANCEREFKLASS_HPP

#include "oops/instanceKlass.hpp"

// An instanceRefKlass is a specialized instanceKlass for Java
// classes that are subclasses of java/lang/ref/Reference.
//
// These classes are used to implement soft/weak/final/phantom
// references and finalization, and need special treatment by the
// garbage collector.
//
// During GC discovered reference objects are added (chained) to one
// of the four lists below, depending on the type of reference.
// The linked occurs through the next field in class java/lang/ref/Reference.
//
// Afterwards, the discovered references are processed in decreasing
// order of reachability. Reference objects eligible for notification
// are linked to the static pending_list in class java/lang/ref/Reference,
// and the pending list lock object in the same class is notified.

class instanceRefKlass: public instanceKlass {
 public:
  // Type testing
  bool oop_is_instanceRef() const             { return true; }

  // Casting from klassOop
  static instanceRefKlass* cast(klassOop k) {
    assert(k->klass_part()->oop_is_instanceRef(), "cast to instanceRefKlass");
    return (instanceRefKlass*) k->klass_part();
  }

  // allocation
  DEFINE_ALLOCATE_PERMANENT(instanceRefKlass);

  // Garbage collection
  int  oop_adjust_pointers(oop obj);
  void oop_follow_contents(oop obj);

  // Parallel Scavenge and Parallel Old
  PARALLEL_GC_DECLS

  int oop_oop_iterate(oop obj, OopClosure* blk) {
    return oop_oop_iterate_v(obj, blk);
  }
  int oop_oop_iterate_m(oop obj, OopClosure* blk, MemRegion mr) {
    return oop_oop_iterate_v_m(obj, blk, mr);
  }

#define InstanceRefKlass_OOP_OOP_ITERATE_DECL(OopClosureType, nv_suffix)                \
  int oop_oop_iterate##nv_suffix(oop obj, OopClosureType* blk);                         \
  int oop_oop_iterate##nv_suffix##_m(oop obj, OopClosureType* blk, MemRegion mr);

  ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_DECL)
  ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_DECL)

#ifndef SERIALGC
#define InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix)      \
  int oop_oop_iterate_backwards##nv_suffix(oop obj, OopClosureType* blk);

  ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
  ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
#endif // !SERIALGC

  static void release_and_notify_pending_list_lock(BasicLock *pending_list_basic_lock);
  static void acquire_pending_list_lock(BasicLock *pending_list_basic_lock);
  static bool owns_pending_list_lock(JavaThread* thread);

  // Update non-static oop maps so 'referent', 'nextPending' and
  // 'discovered' will look like non-oops
  static void update_nonstatic_oop_maps(klassOop k);

 public:
  // Verification
  void oop_verify_on(oop obj, outputStream* st);
};

#endif // SHARE_VM_OOPS_INSTANCEREFKLASS_HPP


text:
using DragonSpark.Model.Selection;
using System;
using System.Threading.Tasks;

namespace DragonSpark.Model.Operations;

sealed class OperationSelect<TIn, TOut> : ISelect<ValueTask<TIn>, ValueTask<TOut>>
{
	readonly Func<TIn, TOut> _select;
	readonly bool            _capture;

	public OperationSelect(Func<TIn, TOut> select, bool capture = false)
	{
		_select  = select;
		_capture = capture;
	}

	public async ValueTask<TOut> Get(ValueTask<TIn> parameter)
	{
		if (parameter.IsCompletedSuccessfully)
		{
			return _select(parameter.Result);
		}

		var input  = await parameter.ConfigureAwait(_capture);
		var result = _select(input);
		return result;
	}
}

sealed class OperationSelect<T> : ISelect<ValueTask<T>, ValueTask>
{
	readonly Func<T, ValueTask> _select;
	readonly bool               _capture;

	public OperationSelect(Func<T, ValueTask> select, bool capture = false)
	{
		_select  = select;
		_capture = capture;
	}

	public async ValueTask Get(ValueTask<T> parameter)
	{
		var input = parameter.IsCompletedSuccessfully ? parameter.Result : await parameter.ConfigureAwait(_capture);
		await _select(input).ConfigureAwait(_capture);
	}
}


text:
using base::android::AttachCurrentThread;
using base::android::ScopedJavaLocalRef;

namespace weblayer {

NewTabCallbackProxy::NewTabCallbackProxy(JNIEnv* env, jobject obj, TabImpl* tab)
    : tab_(tab), java_impl_(env, obj) {
  DCHECK(!tab_->has_new_tab_delegate());
  tab_->SetNewTabDelegate(this);
}

NewTabCallbackProxy::~NewTabCallbackProxy() {
  tab_->SetNewTabDelegate(nullptr);
}

void NewTabCallbackProxy::OnNewTab(std::unique_ptr<Tab> tab, NewTabType type) {
  JNIEnv* env = AttachCurrentThread();
  // The Java side takes ownership of Tab.
  TRACE_EVENT0("weblayer", "Java_NewTabCallbackProxy_onNewTab");
  Java_NewTabCallbackProxy_onNewTab(env, java_impl_,
                                    reinterpret_cast<jlong>(tab.release()),
                                    static_cast<int>(type));
}

void NewTabCallbackProxy::CloseTab() {
  Java_NewTabCallbackProxy_onCloseTab(AttachCurrentThread(), java_impl_);
}

static jlong JNI_NewTabCallbackProxy_CreateNewTabCallbackProxy(
    JNIEnv* env,
    const base::android::JavaParamRef<jobject>& proxy,
    jlong tab) {
  return reinterpret_cast<jlong>(
      new NewTabCallbackProxy(env, proxy, reinterpret_cast<TabImpl*>(tab)));
}

static void JNI_NewTabCallbackProxy_DeleteNewTabCallbackProxy(JNIEnv* env,
                                                              jlong proxy) {
  delete reinterpret_cast<NewTabCallbackProxy*>(proxy);
}

}  // namespace weblayer


text:
/*global window */

var todos = todos || {};

(function (todos, localStorage, KEY) {
	'use strict';

	/*-- private members -------------------------------*/

	var tasks;

	// model uses localStorage as the underlying data store
	// this creates a poor man's localStorage polyfill
	localStorage = localStorage || (function () {
		var storage = {};
		return {
			getItem: function (key) {
				return storage[key];
			},
			setItem: function (key, value) {
				storage[key] = value;
			}
		};
	})();

	function create(title, completed) {
		return {
			// fast, compact, non-repeating, unique ID: e.g., 'c2wwu0vz.pz4zpvi'
			id: (new Date().getTime() + Math.random()).toString(36),
			title: title,
			completed: !!completed
		};
	}

	function find(id) {
		return tasks.filter(function (task) {
			return task.id === id;
		})[0];
	}

	function save() {
		// if doesn't support JSON then will be directly stored in polyfill
		var value = typeof JSON !== 'undefined' ? JSON.stringify(tasks) : tasks;
		localStorage.setItem(KEY, value);
	}

	// initialize storage
	var value = localStorage.getItem(KEY);
	if (value) {
		// if doesn't support JSON then will be directly stored in polyfill
		tasks = typeof JSON !== 'undefined' ? JSON.parse(value) : value;
	} else {
		tasks = [];
	}

	function filterTasks(filter) {
		if (filter === 'completed' || filter === 'active') {
			var completed = filter === 'completed';
			return tasks.filter(function (task) {
				return task.completed === completed;
			});
		}
		return tasks;
	}

	function calcStats(filter) {
		var stats = {
			total: tasks.length,

			completed: tasks.filter(function (task) {
					return task.completed;
				}).length,

			filter: filter || ''
		};

		stats.active = stats.total - stats.completed;

		return stats;
	}

	/*-- export public interface -------------------------------*/

	todos.model = {
		viewData: function (filter) {
			return {
				tasks: filterTasks(filter),
				stats: calcStats(filter)
			};
		},

		add: function (title) {
			var task = create(title, false);

			tasks.push(task);
			save();

			return task;
		},

		find: find,

		edit: function (id, title) {
			(find(id) || {}).title = title;

			save();
		},

		// toggle completion of task
		toggle: function (id, completed) {
			(find(id) || {}).completed = completed;

			save();
		},

		// toggle completion of all tasks
		toggleAll: function (completed) {
			tasks.forEach(function (task) {
				task.completed = completed;
			});

			save();
		},

		remove: function (id) {
			// traverse in reverse for removals
			for (var i = tasks.length - 1; i >= 0; i--) {
				if (tasks[i].id === id) {
					tasks.splice(i, 1);
				}
			}

			save();
		},

		expunge: function () {
			// traverse in reverse for removals
			for (var i = tasks.length - 1; i >= 0; i--) {
				if (tasks[i].completed) {
					tasks.splice(i, 1);
				}
			}

			save();
		}
	};
})(todos, window.localStorage, 'todos-duel');


text:
import os

os.system('cls')
cel = raw_input("What is the temp in Celsius?")

convert = float(cel) * 9
convert = convert / 5
fahr = convert + 32

os.system('cls')
print cel , "Celsius"
print fahr , "Fahrenheit"


text:
using CircuitBreaker;
using System;

namespace CircuitBreakerUT
{
    /// <summary>
    /// My web server's circuit
    /// </summary>
    public class MyWebServerCircuit : AbstractCircuit
    {
        public MyWebServerCircuit(TimeSpan? timespan) : base(timespan)
        {
            base.Description = "Test...";
        }
    }
}


text:
package me.hatter.tools.resourceproxy.jsspserver.filter.impl;

import me.hatter.tools.resourceproxy.httpobjects.objects.HttpRequest;
import me.hatter.tools.resourceproxy.httpobjects.objects.HttpResponse;
import me.hatter.tools.resourceproxy.jsspserver.filter.ResourceFilter;
import me.hatter.tools.resourceproxy.jsspserver.filter.ResourceFilterChain;
import me.hatter.tools.resourceproxy.jsspserver.util.ContentTypes;
import me.hatter.tools.resourceproxy.jsspserver.util.HttpConstants;

public class Default404Filter implements ResourceFilter {

    public static final Default404Filter INSTANCE = new Default404Filter();

    @Override
    public HttpResponse filter(HttpRequest request, ResourceFilterChain chain) {
        // this is the last filter
        HttpResponse response = new HttpResponse();
        response.setContentType(ContentTypes.PLAIN_CONTENT_TYPE);
        response.setCharset(ContentTypes.UTF8_CHARSET);
        response.setStatus(HttpConstants.STATUS_NOT_FOUND);
        response.setStatusMessage("Resource not found");
        response.getHeaderMap().set(ContentTypes.CONTENT_TYPE, ContentTypes.PLAIN_AND_UTF8);
        response.setString("Resource not found: " + request.getUri().getPath());
        return response;
    }
}


text:
$(document).on("pageshow", "#logout-page", function(){
	$.mobile.changePage(domain()+"/index", {transition: "none", reloadPage: true});
});


text:
#include "jni.h"
#include "core_jni_helpers.h"

#include "GraphicsJNI.h"
#include "ScopedPrimitiveArray.h"
#include "SkTypeface.h"
#include "TypefaceImpl.h"
#include <android_runtime/android_util_AssetManager.h>
#include <androidfw/AssetManager.h>

using namespace android;

static jlong Typeface_createFromTypeface(JNIEnv* env, jobject, jlong familyHandle, jint style) {
    TypefaceImpl* family = reinterpret_cast<TypefaceImpl*>(familyHandle);
    TypefaceImpl* face = TypefaceImpl_createFromTypeface(family, (SkTypeface::Style)style);
    // TODO: the following logic shouldn't be necessary, the above should always succeed.
    // Try to find the closest matching font, using the standard heuristic
    if (NULL == face) {
        face = TypefaceImpl_createFromTypeface(family, (SkTypeface::Style)(style ^ SkTypeface::kItalic));
    }
    for (int i = 0; NULL == face && i < 4; i++) {
        face = TypefaceImpl_createFromTypeface(family, (SkTypeface::Style)i);
    }
    return reinterpret_cast<jlong>(face);
}

static jlong Typeface_createWeightAlias(JNIEnv* env, jobject, jlong familyHandle, jint weight) {
    TypefaceImpl* family = reinterpret_cast<TypefaceImpl*>(familyHandle);
    TypefaceImpl* face = TypefaceImpl_createWeightAlias(family, weight);
    return reinterpret_cast<jlong>(face);
}

static void Typeface_unref(JNIEnv* env, jobject obj, jlong faceHandle) {
    TypefaceImpl* face = reinterpret_cast<TypefaceImpl*>(faceHandle);
    TypefaceImpl_unref(face);
}

static jint Typeface_getStyle(JNIEnv* env, jobject obj, jlong faceHandle) {
    TypefaceImpl* face = reinterpret_cast<TypefaceImpl*>(faceHandle);
    return TypefaceImpl_getStyle(face);
}

static jlong Typeface_createFromArray(JNIEnv *env, jobject, jlongArray familyArray) {
    ScopedLongArrayRO families(env, familyArray);
    return reinterpret_cast<jlong>(TypefaceImpl_createFromFamilies(families.get(), families.size()));
}

static void Typeface_setDefault(JNIEnv *env, jobject, jlong faceHandle) {
    TypefaceImpl* face = reinterpret_cast<TypefaceImpl*>(faceHandle);
    return TypefaceImpl_setDefault(face);
}

///////////////////////////////////////////////////////////////////////////////

static JNINativeMethod gTypefaceMethods[] = {
    { "nativeCreateFromTypeface", "(JI)J", (void*)Typeface_createFromTypeface },
    { "nativeCreateWeightAlias",  "(JI)J", (void*)Typeface_createWeightAlias },
    { "nativeUnref",              "(J)V",  (void*)Typeface_unref },
    { "nativeGetStyle",           "(J)I",  (void*)Typeface_getStyle },
    { "nativeCreateFromArray",    "([J)J",
                                           (void*)Typeface_createFromArray },
    { "nativeSetDefault",         "(J)V",   (void*)Typeface_setDefault },
};

int register_android_graphics_Typeface(JNIEnv* env)
{
    return RegisterMethodsOrDie(env, "android/graphics/Typeface", gTypefaceMethods,
                                NELEM(gTypefaceMethods));
}


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

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

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package matrix.distributionPolicy

Interface Summary

Interface
Description

TaskSplitPolicy

This interface defines the protocol for implementing strategies
 to decide in how many task an arithmetic operation should be divided into.

Class Summary

Class
Description

TaskSplitPolicyMode

This class defines the PARALLEL_FACTOR based on the mode sparseness of the rows and the number of physical cores.

TaskSplitPolicyRowSparseness

This class defines the PARALLEL_FACTOR based on the average sparseness of the rows and
 the number of physical cores.

TaskSplitPolicyST

This class defines the PARALLEL_FACTOR based on the number of physical cores, and the average sparseness of the rows and its Standard Deviation.

TaskSplitPolicyStatic

This strategy is defined by a constant value equal to Configuration.CLUSTER_PHYSICAL_CORES * Configuration.GRANULARITY_FACTOR.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
ansible-drush
========

Ansible role for installing Drush

License
-------

Apache v2


text:
package apple.mlcompute;

import apple.NSObject;
import apple.foundation.NSArray;
import apple.foundation.NSDictionary;
import apple.foundation.NSError;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSSet;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCBlock;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

/**
 * MLCInferenceGraph
 *

 * An inference graph created from one or more MLCGraph objects
 * plus additional layers added directly to the inference graph.
 */
@Generated
@Library("MLCompute")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class MLCInferenceGraph extends MLCGraph {
    static {
        NatJ.register();
    }

    @Generated
    protected MLCInferenceGraph(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    /**
     * Add the list of inputs to the inference graph
     *
     * @param inputs The inputs
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("addInputs:")
    public native boolean addInputs(NSDictionary<String, ? extends MLCTensor> inputs);

    /**
     * Add the list of inputs to the inference graph
     *

     * Each input, loss label or label weights tensor is identified by a NSString.
     * When the inference graph is executed, this NSString is used to identify which data object
     * should be as input data for each tensor whose device memory needs to be updated
     * before the graph is executed.
     *
     * @param inputs           The inputs
     * @param lossLabels       The loss label inputs
     * @param lossLabelWeights The loss label weights
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("addInputs:lossLabels:lossLabelWeights:")
    public native boolean addInputsLossLabelsLossLabelWeights(NSDictionary<String, ? extends MLCTensor> inputs,
            NSDictionary<String, ? extends MLCTensor> lossLabels,
            NSDictionary<String, ? extends MLCTensor> lossLabelWeights);

    /**
     * Add the list of outputs to the inference graph
     *
     * @param outputs The outputs
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("addOutputs:")
    public native boolean addOutputs(NSDictionary<String, ? extends MLCTensor> outputs);

    @Generated
    @Owned
    @Selector("alloc")
    public static native MLCInferenceGraph alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native MLCInferenceGraph allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    /**
     * Compile the training graph for a device.
     *
     * @param options The compiler options to use when compiling the training graph
     * @param device  The MLCDevice object
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("compileWithOptions:device:")
    public native boolean compileWithOptionsDevice(long options, MLCDevice device);

    /**
     * Compile the inference graph for a device.
     *

     * Specifying the list of constant tensors when we compile the graph allows MLCompute to perform additional
     * optimizations at compile time.
     *
     * @param options          The compiler options to use when compiling the inference graph
     * @param device           The MLCDevice object
     * @param inputTensors     The list of input tensors that are constants
     * @param inputTensorsData The tensor data to be used with these constant input tensors
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("compileWithOptions:device:inputTensors:inputTensorsData:")
    public native boolean compileWithOptionsDeviceInputTensorsInputTensorsData(long options, MLCDevice device,
            NSDictionary<String, ? extends MLCTensor> inputTensors,
            NSDictionary<String, ? extends MLCTensorData> inputTensorsData);

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    /**
     * [@property] The device memory size used by the inference graph
     *

     * Returns the total size in bytes of device memory used by all intermediate tensors in the inference graph
     *
     * @return A NSUInteger value
     */
    @Generated
    @Selector("deviceMemorySize")
    @NUInt
    public native long deviceMemorySize();

    /**
     * Execute the inference graph with given input data
     *

     * Execute the inference graph given input data.
     * If MLCExecutionOptionsSynchronous is specified in 'options', this method returns after the graph has been
     * executed.
     * Otherwise, this method returns after the graph has been queued for execution. The completion handler is called
     * after the graph has finished execution.
     *
     * @param inputsData        The data objects to use for inputs
     * @param batchSize         The batch size to use. For a graph where batch size changes between layers this value
     *                          must be 0.
     * @param options           The execution options
     * @param completionHandler The completion handler
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("executeWithInputsData:batchSize:options:completionHandler:")
    public native boolean executeWithInputsDataBatchSizeOptionsCompletionHandler(
            NSDictionary<String, ? extends MLCTensorData> inputsData, @NUInt long batchSize, long options,
            @ObjCBlock(name = "call_executeWithInputsDataBatchSizeOptionsCompletionHandler") Block_executeWithInputsDataBatchSizeOptionsCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_executeWithInputsDataBatchSizeOptionsCompletionHandler {
        @Generated
        void call_executeWithInputsDataBatchSizeOptionsCompletionHandler(MLCTensor resultTensor, NSError error,
                double executionTime);
    }

    /**
     * Execute the inference graph with given input data
     *

     * Execute the inference graph given input data.
     * If MLCExecutionOptionsSynchronous is specified in 'options', this method returns after the graph has been
     * executed.
     * Otherwise, this method returns after the graph has been queued for execution. The completion handler is called
     * after the graph has finished execution.
     *
     * @param inputsData           The data objects to use for inputs
     * @param lossLabelsData       The data objects to use for loss labels
     * @param lossLabelWeightsData The data objects to use for loss label weights
     * @param batchSize            The batch size to use. For a graph where batch size changes between layers this value
     *                             must be 0.
     * @param options              The execution options
     * @param completionHandler    The completion handler
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("executeWithInputsData:lossLabelsData:lossLabelWeightsData:batchSize:options:completionHandler:")
    public native boolean executeWithInputsDataLossLabelsDataLossLabelWeightsDataBatchSizeOptionsCompletionHandler(
            NSDictionary<String, ? extends MLCTensorData> inputsData,
            NSDictionary<String, ? extends MLCTensorData> lossLabelsData,
            NSDictionary<String, ? extends MLCTensorData> lossLabelWeightsData, @NUInt long batchSize, long options,
            @ObjCBlock(name = "call_executeWithInputsDataLossLabelsDataLossLabelWeightsDataBatchSizeOptionsCompletionHandler") Block_executeWithInputsDataLossLabelsDataLossLabelWeightsDataBatchSizeOptionsCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_executeWithInputsDataLossLabelsDataLossLabelWeightsDataBatchSizeOptionsCompletionHandler {
        @Generated
        void call_executeWithInputsDataLossLabelsDataLossLabelWeightsDataBatchSizeOptionsCompletionHandler(
                MLCTensor resultTensor, NSError error, double executionTime);
    }

    /**
     * Execute the inference graph with given input data
     *

     * Execute the inference graph given input data.
     * If MLCExecutionOptionsSynchronous is specified in 'options', this method returns after the graph has been
     * executed.
     * Otherwise, this method returns after the graph has been queued for execution. The completion handler is called
     * after the graph has finished execution.
     *
     * @param inputsData           The data objects to use for inputs
     * @param lossLabelsData       The data objects to use for loss labels
     * @param lossLabelWeightsData The data objects to use for loss label weights
     * @param outputsData          The data objects to use for outputs
     * @param batchSize            The batch size to use. For a graph where batch size changes between layers this value
     *                             must be 0.
     * @param options              The execution options
     * @param completionHandler    The completion handler
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("executeWithInputsData:lossLabelsData:lossLabelWeightsData:outputsData:batchSize:options:completionHandler:")
    public native boolean executeWithInputsDataLossLabelsDataLossLabelWeightsDataOutputsDataBatchSizeOptionsCompletionHandler(
            NSDictionary<String, ? extends MLCTensorData> inputsData,
            NSDictionary<String, ? extends MLCTensorData> lossLabelsData,
            NSDictionary<String, ? extends MLCTensorData> lossLabelWeightsData,
            NSDictionary<String, ? extends MLCTensorData> outputsData, @NUInt long batchSize, long options,
            @ObjCBlock(name = "call_executeWithInputsDataLossLabelsDataLossLabelWeightsDataOutputsDataBatchSizeOptionsCompletionHandler") Block_executeWithInputsDataLossLabelsDataLossLabelWeightsDataOutputsDataBatchSizeOptionsCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_executeWithInputsDataLossLabelsDataLossLabelWeightsDataOutputsDataBatchSizeOptionsCompletionHandler {
        @Generated
        void call_executeWithInputsDataLossLabelsDataLossLabelWeightsDataOutputsDataBatchSizeOptionsCompletionHandler(
                MLCTensor resultTensor, NSError error, double executionTime);
    }

    /**
     * Execute the inference graph with given input data
     *

     * Execute the inference graph given input data.
     * If MLCExecutionOptionsSynchronous is specified in 'options', this method returns after the graph has been
     * executed.
     * Otherwise, this method returns after the graph has been queued for execution. The completion handler is called
     * after the graph has finished execution.
     *
     * @param inputsData        The data objects to use for inputs
     * @param outputsData       The data objects to use for outputs
     * @param batchSize         The batch size to use. For a graph where batch size changes between layers this value
     *                          must be 0.
     * @param options           The execution options
     * @param completionHandler The completion handler
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("executeWithInputsData:outputsData:batchSize:options:completionHandler:")
    public native boolean executeWithInputsDataOutputsDataBatchSizeOptionsCompletionHandler(
            NSDictionary<String, ? extends MLCTensorData> inputsData,
            NSDictionary<String, ? extends MLCTensorData> outputsData, @NUInt long batchSize, long options,
            @ObjCBlock(name = "call_executeWithInputsDataOutputsDataBatchSizeOptionsCompletionHandler") Block_executeWithInputsDataOutputsDataBatchSizeOptionsCompletionHandler completionHandler);

    @Runtime(ObjCRuntime.class)
    @Generated
    public interface Block_executeWithInputsDataOutputsDataBatchSizeOptionsCompletionHandler {
        @Generated
        void call_executeWithInputsDataOutputsDataBatchSizeOptionsCompletionHandler(MLCTensor resultTensor,
                NSError error, double executionTime);
    }

    @Generated
    @Selector("graph")
    public static native MLCInferenceGraph graph();

    /**
     * Create an inference graph
     *
     * @param graphObjects The layers from these graph objects will be added to the training graph
     * @return A new inference graph object
     */
    @Generated
    @Selector("graphWithGraphObjects:")
    public static native MLCInferenceGraph graphWithGraphObjects(NSArray<? extends MLCGraph> graphObjects);

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("init")
    public native MLCInferenceGraph init();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    /**
     * Link mutiple inference graphs
     *

     * This is used to link subsequent inference graphs with first inference sub-graph.
     * This method should be used when we have tensors shared by one or more layers in multiple sub-graphs
     *
     * @param graphs The list of inference graphs to link
     * @return A boolean indicating success or failure
     */
    @Generated
    @Selector("linkWithGraphs:")
    public native boolean linkWithGraphs(NSArray<? extends MLCInferenceGraph> graphs);

    @Generated
    @Owned
    @Selector("new")
    public static native MLCInferenceGraph new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();
}


text:
using UnityEngine;
using System.Collections;

public class LerpPos : MonoBehaviour
{
	public float lerpRate = 1.0f;

	private Vector3 position;
	private Quaternion rotation;
	private Vector3 scale;

	private Vector3 lerpStartPos;
	private Quaternion lerpStartRot;
	private Vector3 lerpStartScale;

	private float timeDiff;
	private bool lerping = false;

	public void Start()
	{
		position = transform.position;
		rotation = transform.rotation;
		scale = transform.localScale;
	}

	public void Update()
	{
		if (lerping)
		{
			timeDiff += Time.deltaTime;

			transform.position = Vector3.Lerp(transform.position, position, timeDiff * lerpRate);
			transform.rotation = Quaternion.Lerp(transform.rotation, rotation, timeDiff * lerpRate);
			transform.localScale = Vector3.Lerp(transform.localScale, scale, timeDiff * lerpRate);

			if ((transform.position - position).sqrMagnitude < 0.001f)
			{
				ThirdPersonCamera cameraController = Camera.mainCamera.GetComponent<ThirdPersonCamera>();
				if (cameraController != null)
					cameraController.enabled = false;

				SendMessage("RestartLevel");

				lerping = false;
			}
		}
	}

	public void LerpToStartPos()
	{
		timeDiff = 0.0f;
		lerping = true;
	}
}


text:
package io.reactivesw.catalog.category.domain.service.update;

import io.reactivesw.catalog.category.application.model.action.SetSlug;
import io.reactivesw.catalog.category.domain.entity.CategoryEntity;
import io.reactivesw.catalog.category.infrastructure.util.CategoryActionUtils;
import io.reactivesw.common.model.Update;
import io.reactivesw.common.model.UpdateAction;

import org.springframework.stereotype.Service;

/**
 * Created by Davis on 16/12/29.
 */
@Service(value = CategoryActionUtils.SET_SLUG)
public class SetSlugService implements Update<CategoryEntity> {

  /**
   * update handle.
   * @param entity E
   * @param action UpdateAction
   */
  @Override
  public void handle(CategoryEntity entity, UpdateAction action) {
    SetSlug setSlug = (SetSlug) action;
    entity.setSlug(setSlug.getSlug());
  }
}


text:
package com.sparkDev.alexaciscospark;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazon.speech.slu.Intent;
import com.amazon.speech.slu.Slot;
import com.amazon.speech.speechlet.IntentRequest;
import com.amazon.speech.speechlet.LaunchRequest;
import com.amazon.speech.speechlet.Session;
import com.amazon.speech.speechlet.SessionEndedRequest;
import com.amazon.speech.speechlet.SessionStartedRequest;
import com.amazon.speech.speechlet.Speechlet;
import com.amazon.speech.speechlet.SpeechletException;
import com.amazon.speech.speechlet.SpeechletResponse;
import com.amazon.speech.ui.OutputSpeech;
import com.amazon.speech.ui.PlainTextOutputSpeech;
import com.amazon.speech.ui.Reprompt;
import com.amazon.speech.ui.SimpleCard;
import com.amazon.speech.ui.SsmlOutputSpeech;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sparkDev.alexaciscospark.api.Memberships;
import com.sparkDev.alexaciscospark.api.Messages;
import com.sparkDev.alexaciscospark.api.Rooms;
import com.sparkDev.alexaciscospark.api.Teams;
import com.sparkDev.alexaciscospark.speechHandler.MemberHandler;
import com.sparkDev.alexaciscospark.speechHandler.MessageHandler;
import com.sparkDev.alexaciscospark.speechHandler.RoomHandler;
import java.util.logging.Level;

/**
 * This sample shows how to create a simple speechlet for handling speechlet
 * requests.
 */
public class SparkySpeechlet implements Speechlet {

    private static final Logger log = LoggerFactory.getLogger(SparkySpeechlet.class);

    @Override
    public void onSessionStarted(final SessionStartedRequest request, final Session session)
            throws SpeechletException {
        log.info("onSessionStarted requestId={}, sessionId={}", request.getRequestId(),
                session.getSessionId());
        // any initialization logic goes here
    }

    @Override
    public SpeechletResponse onLaunch(final LaunchRequest request, final Session session)
            throws SpeechletException {
        log.info("onLaunch requestId={}, sessionId={}", request.getRequestId(),
                session.getSessionId());
        return getWelcomeResponse();
    }

    @Override
    public SpeechletResponse onIntent(final IntentRequest request, final Session session)
            throws SpeechletException {
        log.info("onIntent requestId={}, sessionId={}", request.getRequestId(),
                session.getSessionId());

        Intent intent = request.getIntent();
        String intentName = (intent != null) ? intent.getName() : null;

        if ("createTeamIntent".equals(intentName)) {
            log.info("inside createTeamIntent");
            return createTeam(intent, session);
        } else if ("dialogueIntent".equals(intentName)) {
            return handleDialogueRequest(intent, session);
        } else if ("createRoomIntent".equals(intentName)) {
            return RoomHandler.createRoom(intent, session);
        }else if ("addMemberToRoomIntent".equals(intentName)) {
            return MemberHandler.addMemberToRoom(intent, session);
        }
        else if ("sendMessageToRoom".equals(intentName)) {
            return MessageHandler.sendMessageToRoom(intent, session);
        } else if("sendMessageToMember".equals(intentName)){
            return MessageHandler.sendMessageToMember(intent, session);
        }
        else if ("addMemberToTeamIntent".equals(intentName)) {
            return addMemberToTeam(intent, session);
        } else if ("AMAZON.HelpIntent".equals(intentName)) {
            return getHelpResponse();
        } else {
            throw new SpeechletException("Invalid Intent");
        }

    }

    @Override
    public void onSessionEnded(final SessionEndedRequest request, final Session session)
            throws SpeechletException {
        log.info("onSessionEnded requestId={}, sessionId={}", request.getRequestId(),
                session.getSessionId());
    }

    /**
     * Creates and returns a {@code SpeechletResponse} with a welcome message.
     *
     * @return SpeechletResponse spoken and visual response for the given intent
     */
    private SpeechletResponse getWelcomeResponse() {
        String speechText = "";

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle("Cisco Spark");
        card.setContent(speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        speech.setText(speechText);

        // Create reprompt
        Reprompt reprompt = new Reprompt();
        reprompt.setOutputSpeech(speech);

        return SpeechletResponse.newAskResponse(speech, reprompt, card);
    }

    private SpeechletResponse createTeam(Intent intent, Session session) {
        String speechText = "Create Teams";
        String teamName = "";
        //if the question does not have a team in it, ask back - What is the team name
        try {
            teamName = getTeamNameFromIntent(intent);
        } catch (Exception e) {
            // invalid city. move to the dialog
            String speechOutput
                    = "What is the team name?";
            String repromptText = "Sorry, I did not get you. What is the team name?";
            // repromptText is the speechOutput
            session.setAttribute("PREVIOUS_INTENT", intent.getName());
            // repromptText is the same as the speechOutput
            return newAskResponse(speechOutput, repromptText);
        }

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle("Create Teams");
        card.setContent(speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        String response = "";
        if (teamName != null) {
            try {
                response = Teams.createTeam(teamName, session.getUser().getAccessToken());
            } catch (UnirestException ex) {
                java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        speech.setText(response);

        return SpeechletResponse.newTellResponse(speech, card);
    }

    private SpeechletResponse handleDialogueRequest(Intent intent, Session session) {
        String inputText = "";
        String previousIntent = "";
        String result = "";
        try {
            previousIntent = (String) session.getAttribute("PREVIOUS_INTENT");
            log.info("Name of previous attribute: "+previousIntent);
            if (previousIntent != null && previousIntent.equals("createTeamIntent")) {
                log.info("Handling dialogue team request..");
                inputText = getInputTextFromIntent(intent);
                try {
                    //if my previous intent was a team intent
                    result = Teams.createTeam(inputText, session.getUser().getAccessToken());
                } catch (UnirestException ex) {
                    java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
                }

            }else if (previousIntent != null && previousIntent.equals("createRoomIntent")) {
                log.info("Handling dialogue room request..");
                inputText = getInputTextFromIntent(intent);
                try {
                    //if my previous intent was a room intent
                    result = Rooms.createRoom(inputText, session.getUser().getAccessToken());
                } catch (UnirestException ex) {
                    java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
                }

            }else if (previousIntent != null && previousIntent.equals("sendMessageToRoom")) {
                log.info("Handling message to room request..");
                inputText = getInputTextFromIntent(intent);
                String roomTitle = (String) session.getAttribute("ROOM_TITLE");
                log.info("ROOM TITLE: "+ roomTitle);
                try {
                    //if my previous intent was a message to room intent
                    if(roomTitle != null){
                        result = Messages.sendMessageToRoom(inputText, roomTitle, session.getUser().getAccessToken());
                    }

                } catch (UnirestException ex) {
                    java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
                }

            }//sendMessageToMember
            else if (previousIntent != null && previousIntent.equals("sendMessageToMember")) {
                log.info("Handling message to member request..");
                inputText = getInputTextFromIntent(intent);
                String memberName = (String) session.getAttribute("MEMBER_NAME");
                 log.info("MEMBER NAME: "+ memberName);
                try {
                    //if my previous intent was a message to room intent
                    if(memberName != null){
                        result = Messages.sendMessageToMember(inputText, memberName, session.getUser().getAccessToken());
                    }

                } catch (UnirestException ex) {
                    java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            else if (previousIntent != null && previousIntent.equals("addMemberToTeamIntent")) {
                log.info("Handling message to team request..");
                inputText = getInputTextFromIntent(intent); //team name
                String memberName = (String) session.getAttribute("MEMBER_NAME");
                log.info("MEMBER NAME: "+ memberName);
                try {
                    //if my previous intent was a message to room intent
                    if(memberName != null){
                        result = Memberships.addMemberToTeam(memberName, inputText, session.getUser().getAccessToken());
                    }

                } catch (UnirestException ex) {
                    java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        } catch (Exception e) {
            String speechOutput
                    = "Sorry, I did not get it.";

            return newAskResponse(speechOutput, speechOutput);
        }

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle("Alexa Spark");
        card.setContent("Alexa Spark");
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        speech.setText(result);
        return SpeechletResponse.newTellResponse(speech, card);
    }

    private String getTeamNameFromIntent(final Intent intent) throws Exception {
        Slot teamSlot = intent.getSlot("TeamName");
        if (teamSlot == null || teamSlot.getValue() == null) {
            throw new Exception("");
        } else {
            return teamSlot.getValue();
        }
    }

     private String getInputTextFromIntent(final Intent intent) throws Exception {
        Slot inputText = intent.getSlot("InputText");
        if (inputText == null || inputText.getValue() == null) {
            throw new Exception("");
        } else {
            return inputText.getValue();
        }
    }

    /**
     * Wrapper for creating the Ask response from the input strings with plain
     * text output and reprompt speeches.
     *
     * @param stringOutput the output to be spoken
     * @param repromptText the reprompt for if the user doesn't reply or is
     * misunderstood.
     * @return SpeechletResponse the speechlet response
     */
    private SpeechletResponse newAskResponse(String stringOutput, String repromptText) {
        return newAskResponse(stringOutput, false, repromptText, false);
    }

    /**
     * Wrapper for creating the Ask response from the input strings.
     *
     * @param stringOutput the output to be spoken
     * @param isOutputSsml whether the output text is of type SSML
     * @param repromptText the reprompt for if the user doesn't reply or is
     * misunderstood.
     * @param isRepromptSsml whether the reprompt text is of type SSML
     * @return SpeechletResponse the speechlet response
     */
    private SpeechletResponse newAskResponse(String stringOutput, boolean isOutputSsml,
            String repromptText, boolean isRepromptSsml) {
        OutputSpeech outputSpeech, repromptOutputSpeech;
        if (isOutputSsml) {
            outputSpeech = new SsmlOutputSpeech();
            ((SsmlOutputSpeech) outputSpeech).setSsml(stringOutput);
        } else {
            outputSpeech = new PlainTextOutputSpeech();
            ((PlainTextOutputSpeech) outputSpeech).setText(stringOutput);
        }

        if (isRepromptSsml) {
            repromptOutputSpeech = new SsmlOutputSpeech();
            ((SsmlOutputSpeech) repromptOutputSpeech).setSsml(stringOutput);
        } else {
            repromptOutputSpeech = new PlainTextOutputSpeech();
            ((PlainTextOutputSpeech) repromptOutputSpeech).setText(repromptText);
        }

        Reprompt reprompt = new Reprompt();
        reprompt.setOutputSpeech(repromptOutputSpeech);
        return SpeechletResponse.newAskResponse(outputSpeech, reprompt);
    }

    /**
     * Creates a {@code SpeechletResponse} for the help intent.
     *
     * @return SpeechletResponse spoken and visual response for the given intent
     */
    private SpeechletResponse getHelpResponse() {
        String speechText = "You can say hello to me!";

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle("Cisco Spark");
        card.setContent(speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        speech.setText(speechText);

        // Create reprompt
        Reprompt reprompt = new Reprompt();
        reprompt.setOutputSpeech(speech);

        return SpeechletResponse.newAskResponse(speech, reprompt, card);
    }

    private SpeechletResponse createRoom(Intent intent, Session session) {
        String speechText = "Cisco Spark";
        Slot roomTitle = intent.getSlot("RoomTitle");

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle(speechText);
        card.setContent(speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        String response = "";
        if (roomTitle != null && roomTitle.getValue() != null) {
            try {
                response = Rooms.createRoom(roomTitle.getValue(), session.getUser().getAccessToken());
            } catch (UnirestException ex) {
                java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        speech.setText(response);

        return SpeechletResponse.newTellResponse(speech, card);
    }

    private SpeechletResponse addMemberToTeam(Intent intent, Session session) {
        String speechText = "Cisco Spark";
        Slot teamName = intent.getSlot("TeamName");
        Slot member = intent.getSlot("memberName");

        // Create the Simple card content.
        SimpleCard card = new SimpleCard();
        card.setTitle(speechText);
        card.setContent(speechText);

        // Create the plain text output.
        PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
        String response = "";
        if (teamName != null && teamName.getValue() != null) {
            try {
                response = Memberships.addMemberToTeam(member.getValue(), teamName.getValue(), session.getUser().getAccessToken());
            } catch (UnirestException ex) {
                java.util.logging.Logger.getLogger(SparkySpeechlet.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        speech.setText(response);

        return SpeechletResponse.newTellResponse(speech, card);
    }
}


text:
""" Setup for Config Subpackages. """

from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration

def configuration(parent_package='', top_path=None):
    """ Configuration of config subpackages. """
    config = Configuration('config', parent_package, top_path)
    config.add_data_dir('tests')
    return config

if __name__ == '__main__':
    setup(**configuration(top_path='').todict())


text:
export {translations, preferredLanguage, changeLanguage} from './translation';
export {openSidebar, closeSidebar} from './sidebar';


text:
package gov.sandia.cognition.learning.algorithm.minimization;

import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationReferences;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.evaluator.Evaluator;
import gov.sandia.cognition.learning.algorithm.minimization.line.DirectionalVectorToScalarFunction;
import gov.sandia.cognition.learning.data.DefaultInputOutputPair;
import gov.sandia.cognition.learning.data.InputOutputPair;
import gov.sandia.cognition.math.RingAccumulator;
import gov.sandia.cognition.math.matrix.Vector;
import java.util.ArrayList;

/**
 * Implementation of the Downhill Simplex minimization algorithm, also known as
 * the Nelder-Mead method.  It finds the minimum of a nonlinear function
 * without using derivative information.  In my experience, this method
 * "gives up" easily and the simplex breaks down and gets stuck on complicated
 * nonlinear manifolds.  I would recommend using Powell's method instead.
 *
 * @author Kevin R. Dixon
 * @since  2.0
 *
 */
@PublicationReferences(
    references={
        @PublicationReference(
            author={
                "William H. Press",
                "Saul A. Teukolsky",
                "William T. Vetterling",
                "Brian P. Flannery"
            },
            title="Numerical Recipes in C, Second Edition",
            type=PublicationType.Book,
            year=1992,
            pages={411,412},
            notes="Section 10.5",
            url="http://www.nrbook.com/a/bookcpdf.php"
        ),
        @PublicationReference(
            author="Wikipedia",
            title="Nelder-Mead method",
            type=PublicationType.WebPage,
            year=2008,
            url="http://en.wikipedia.org/wiki/Nelder-Mead_method"
        )
    }
)
public class FunctionMinimizerNelderMead
    extends AbstractAnytimeFunctionMinimizer<Vector, Double, Evaluator<? super Vector, Double>>
{

    /**
     * Default tolerance, {@value}
     */
    public static final double DEFAULT_TOLERANCE = 1e-3;

    /**
     * Default max iterations, {@value}
     */
    public static final int DEFAULT_MAX_ITERATIONS = 4000;

    /**
     * Creates a new instance of FunctionMinimizerNelderMead
     */
    public FunctionMinimizerNelderMead()
    {
        super( null, DEFAULT_TOLERANCE, DEFAULT_MAX_ITERATIONS );
    }

    /**
     * InputOutputPairs that define the simplex
     */
    private ArrayList<DefaultInputOutputPair<Vector,Double>> simplex;

    /**
     * A running sum of the inputs of the simplex, used for reflection
     */
    private Vector simplexInputSum;

    /**
     * Small number to keep me from dividing by zero
     */
    private static final double TINY = 1e-10;

    @Override
    protected boolean initializeAlgorithm()
    {
        Evaluator<? super Vector,Double> f = this.data;

        Vector x0 = this.getInitialGuess().clone();
        Double y0 = f.evaluate( x0 );
        InputOutputPair<Vector,Double> p0 =
            new DefaultInputOutputPair<Vector, Double>( x0, y0 );

        // Create the simplex and keep a running average of its x-axis midpoint
        this.simplex = initializeSimplex( p0, 1.0 );
        this.simplexInputSum = this.computeSimplexInputSum();

        this.result = null;

        this.lineFunction = new DirectionalVectorToScalarFunction(
            this.data, null, null );

        return true;
    }

    /**
     * Initializes the simplex about the initial point
     * @param initialPoint
     * Initial point about which to initialize the simplex
     * @param offsetValue
     * Value to use to spread out the vertices of the simplex
     * @return
     * Simplex
     */
    public ArrayList<DefaultInputOutputPair<Vector,Double>> initializeSimplex(
        InputOutputPair<Vector,Double> initialPoint,
        double offsetValue )
    {
        Vector x0 = initialPoint.getInput();
        int M = x0.getDimensionality();

        // Create the simplex and keep a running average of its x-axis midpoint
        ArrayList<DefaultInputOutputPair<Vector,Double>> localSimplex =
            new ArrayList<DefaultInputOutputPair<Vector,Double>>( M+1 );

        // Add the initial point to the simplex
        localSimplex.add( DefaultInputOutputPair.create(
            initialPoint.getInput(),
            initialPoint.getOutput()) );

        // Add the remaining M points to the simplex
        for( int i = 0; i < M; i++ )
        {
            Vector xi = x0.clone();
            xi.setElement( i, x0.getElement(i) + offsetValue );
            Double yi = this.data.evaluate( xi );
            localSimplex.add( new DefaultInputOutputPair<Vector, Double>( xi, yi ) );
        }

        return localSimplex;

    }

    @Override
    protected boolean step()
    {

        // Find the highest and lowest vertex of the simplex
        int indexLow = 0;
        DefaultInputOutputPair<Vector,Double> pLow = this.simplex.get(indexLow);
        DefaultInputOutputPair<Vector,Double> pHigh = this.simplex.get(0);
        DefaultInputOutputPair<Vector,Double> pSecondHighest = null;
        for( int i = 1; i < this.simplex.size(); i++ )
        {
            DefaultInputOutputPair<Vector,Double> pi = this.simplex.get( i );
            if( pHigh.getOutput() < pi.getOutput() )
            {
                pSecondHighest = pHigh;
                pHigh = pi;
            }
            else if( (pSecondHighest == null)
                || (pSecondHighest.getOutput() < pi.getOutput()) )
            {
                pSecondHighest = pi;
            }

            if( pLow.getOutput() > pi.getOutput() )
            {
                pLow = pi;
                indexLow = i;
            }
        }

        double fhigh = pHigh.getOutput();
        double flow = pLow.getOutput();

        // This is the termination criterion...
        // If the simplex has contracted sufficiently
        double rtol = 2.0 * Math.abs(fhigh - flow) /
            (Math.abs(fhigh) + Math.abs(flow) + TINY);
        if( rtol <= this.getTolerance() )
        {
            return false;
        }

        // Set the result as the lowest point in the simplex
        this.result = pLow;

        // Begin a new iteration. First extrapolate by a factor -1 through
        // the face of the simplex across from the high point, i.e., reflex the
        // simplex from the high point
        DefaultInputOutputPair<Vector,Double> pnew = this.pointTry( pHigh, -1.0 );

        // Gives a result better than the best point,
        // so try an additional extrapolation by a factor of 2
        if( pnew.getOutput() <= pLow.getOutput() )
        {
            pnew = this.pointTry( pHigh, 2.0 );

            // If the new point is still better than the lowest, then assign
            // it as the result
            if( pnew.getOutput() <= pLow.getOutput() )
            {
                this.result = pnew;
            }
        }

        // The reflected point is worse than the second-highest,
        // so look for an intermediate lower point, that is,
        // we'll perform a one-dimensional contraction
        else if( pnew.getOutput() >= pSecondHighest.getOutput() )
        {
            double yHighSave = pHigh.getOutput();
            pnew = this.pointTry( pHigh, 0.5 );

            // Can't seem to get rid of that high point.
            // Better contract around the lowest (best) point.
            if( pnew.getOutput() > yHighSave )
            {
                Vector xlow = pLow.getInput();
                for( int i = 0; i < this.simplex.size(); i++ )
                {
                    DefaultInputOutputPair<Vector,Double> pi = this.simplex.get(i);
                    if( i != indexLow )
                    {
                        Vector xi = pi.getInput();
                        xi.plusEquals( xlow );
                        xi.scaleEquals( 0.5 );
                        Double yi = this.data.evaluate( xi );

                        // I don't actually have to setInput here, since the
                        // scaleEquals() methods (etc) will automagically
                        // show up inside "pi", but I know I'll forget this
                        // when I look at the code in the future.
                        // So here it is.
                        pi.setInput( xi );
                        pi.setOutput( yi );
                    }

                }

                // It is more efficient to recompute the simplexInputSum from
                // scratch here, instead of tracking the change in individual
                // point coordinates
                this.simplexInputSum = this.computeSimplexInputSum();
            }

        }

        return true;
    }

    @Override
    protected void cleanupAlgorithm()
    {
    }

    /**
     * Computes the sum of input values in the simplex
     * @return
     * Sum of input values in the simplex
     */
    protected Vector computeSimplexInputSum()
    {
        RingAccumulator<Vector> simplexInputAccumulator =
            new RingAccumulator<Vector>();
        for( InputOutputPair<Vector,Double> pi : this.simplex )
        {
            simplexInputAccumulator.accumulate( pi.getInput() );
        }

        return simplexInputAccumulator.getSum();
    }

    /**
     * Function that defines the simplex growth direction
     */
    private DirectionalVectorToScalarFunction lineFunction;

    /**
     * Function that attempts to find a better point using the given
     * scale factor
     * @param pold
     * Old point to improve upon
     * @param scaleFactor
     * Scale factor to reflect/stretch/contract the about the simplex
     * @return
     * New point in the simplex
     */
    private DefaultInputOutputPair<Vector,Double> pointTry(
        DefaultInputOutputPair<Vector,Double> pold,
        double scaleFactor )
    {

        int M = this.initialGuess.getDimensionality();

        Vector xold = pold.getInput();

        // This is the midpoint of the remaining points in the simplex,
        // as if xold didn't exist
        Vector xmid = this.simplexInputSum.minus( xold );
        xmid.scaleEquals( 1.0 / M );

        // Here is the direction of the operation
        Vector direction = xold.minus( xmid );
        this.lineFunction.setDirection( direction );
        this.lineFunction.setVectorOffset( xmid );

        // Now, compute the reflected, contracted, expanded, etc. point.
        // Oddly enough, line search seems to slow things down quite a bit
        // instead of just using a brain-dead computation here.
        // Don't know why, but it hurts.
        // So, dear person reading this in the future, please feel free
        // to use line minimization here but, as you'll soon find out,
        // future person, it really does hurt.
        Vector xnew = this.lineFunction.computeVector( scaleFactor );
        double ynew = this.lineFunction.evaluate( scaleFactor );
        DefaultInputOutputPair<Vector,Double> pnew =
            new DefaultInputOutputPair<Vector, Double>( xnew, ynew );

        // If the new point is better than the original point,
        // then replace the original point with the new point.
        if( ynew < pold.getOutput() )
        {
            this.simplexInputSum.minusEquals( pold.getInput() );
            this.simplexInputSum.plusEquals( xnew );
            pold.setInput( xnew );
            pold.setOutput( ynew );
        }

        return pnew;

    }

}


text:
var Menu     = require('../../menu')
  , inherits = require('util').inherits

module.exports = DashboardMenu

function DashboardMenu(opts) {
  this.controller = opts.controller
  this.dashboard  = opts.controller.dashboard()
  this.onHide     = opts.onHide

  Menu.call(this,
    { style: opts.style
    , items:
      [ {label: "Add Chart",        onClick: "onClickAddChart"}
      , {label: "Rename Dashboard", onClick: "onClickRenameDashboard"}
      , null
      , {label: "Delete Dashboard", onClick: "onClickDeleteDashboard"}
      ]
    })
  this.el.className += " setting-menu"
}

inherits(DashboardMenu, Menu)

DashboardMenu.prototype.View({})
  .destroy(function() {
    this.onHide()
    this.controller = this.dashboard = this.onHide = null
  })

////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////

DashboardMenu.prototype.onClickAddChart        = function() { this.dashboard.newChart() }
DashboardMenu.prototype.onClickRenameDashboard = function() { this.dashboard.renameDashboard() }
DashboardMenu.prototype.onClickDeleteDashboard = function() { this.dashboard.destroyDashboard() }