text:
import injectTapEventPlugin from 'react-tap-event-plugin';

// Needed for onTouchTap
// Can go away when react 1.0 release
// Check this repo:
// https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();

let app = 'awesome';
var React = require('react');
var ReactDOM = require('react-dom');

import ThemeManager from 'material-ui/styles/themeManager';
import DarkRawTheme from 'material-ui/styles/raw-themes/dark-raw-theme';
import SliderMod from './Slider';
import Toggle from 'material-ui/Toggle';
import RaisedButton from 'material-ui/RaisedButton';

var ws;
var setters = {};

var sigFigs = function( val, min, max )
{
   var sensibility = (max-min)/5000;
   var logSensib = Math.round(Math.log10(sensibility));
   var logValue = Math.round(Math.log10(Math.abs(val)));
   if(logValue != logValue)
   {
    logValue = logSensib;
   }
   var power10 = Math.pow(10,Math.round(logSensib));

//   Math.round(val/power10)*power10)
  return val.toPrecision(Math.max(logValue-logSensib,1));
  }

var Generator = React.createClass({

  getInitialState: function()
  {
    let newMuiTheme = ThemeManager.getMuiTheme(DarkRawTheme);
    newMuiTheme.slider.handleSize = 2 * newMuiTheme.slider.handleSize;
    newMuiTheme.slider.handleSizeActive = 2 * newMuiTheme.slider.handleSizeActive;
    newMuiTheme.slider.trackSize = 2 * newMuiTheme.slider.handleSize;
    newMuiTheme.handleWhenPercentZero = newMuiTheme.handle;
    newMuiTheme.handleWhenPercentZeroAndDisabled = newMuiTheme.handleWhenDisabled;
    newMuiTheme.handleWhenPercentZeroAndFocused = newMuiTheme.handle;
    newMuiTheme.rippleWhenPercentZero = newMuiTheme.ripple;
    return {muiTheme: newMuiTheme};
  },

  childContextTypes : {
    muiTheme: React.PropTypes.object,
  },

  getChildContext() {
    return {
      muiTheme: this.state.muiTheme,
    };
  },

  render: function()
  {
    var objNodes = parseJsonToNodes(this.props.json);
    return (

              <RaisedButton style={{float:'right'}} label="REFRESH" primary={true} onTouchTap={function(){ws.send("update");}} />

              {objNodes}
);
  }

})

var Container = React.createClass({

  render: function()
  {
    var objNodes = parseJsonToNodes(this.props.json.content);
    return(

 {this.props.json.name}

{objNodes}

)
  }
});

var makeUpdateJson = function(ident,val)
{
  return {
    "type":"update",
    "content":[
      {
        id: ident,
        value: val
       }
      ]};
}

var sliderContainerStyle =
{
    overflow:"hidden",
    verticalAlign:"middle"
}

var sliderStyle =
{
  overflow:"hidden",
  margin: '0'
}

var sliderStyleStyle =
{
    marginBottom:'0.1em',
    marginTop:'0.5em'
}

var sliderValueDisplayStyle =
{
  width:"auto",
  marginRight:'0.5em',
  width:'3em',
  textAlign: 'right',
  color: DarkRawTheme.palette.borderColor,
  float: "left",
  marginTop: "0.6em"
}

var IntSlider = React.createClass({

  getInitialState: function()
  {
    var that = this;
    setters[this.props.json.id] = (function(val){that.updateState(val);});
    return {"value": this.convertValue(this.props.json.value)};
  },

  updateState: function(newValue)
  {
    this.setState({value: newValue});
  },

  handleChange: function(e,newValue)
  {
    this.updateState(newValue);
    this.communicateChange(newValue);
  },

  communicateChange: function (newValue)
  {
    var data = makeUpdateJson(this.props.json.id, newValue);
    ws.send(JSON.stringify(data));
  },

  convertValue: function(value)
  {
      return parseInt(value);
   },

  render: function()
  {
    var output = {};

      if(this.props.json.hasOwnProperty("min") && this.props.json.hasOwnProperty("max"))
      {
          var step = 1;

        var displayedValue = this.state.value;

        output = (

{displayedValue}
<SliderMod name={this.props.json.id} defaultValue={this.state.value} step={step} min={this.props.json.min} max={this.props.json.max} label={this.props.json.name} onChange={this.handleChange} value={this.state.value} style={sliderStyle} sliderStyle={sliderStyleStyle}/>
);

      }
      else
      {
        output = (this.state.value);
      }

    return (

 {this.props.json.name}

{output}

)
  }
});

var FloatSlider = React.createClass({

  getInitialState: function()
  {
    var that = this;
    setters[this.props.json.id] = (function(val){that.updateState(val);});
    return {"value": this.convertValue(this.props.json.value)};
  },

  updateState: function(newValue)
  {
    this.setState({value: newValue});
  },

  handleChange: function(e,newValue)
  {
    this.updateState(newValue);
    this.communicateChange(newValue);
  },

  communicateChange: function (newValue)
  {
    var data = makeUpdateJson(this.props.json.id, newValue);
    ws.send(JSON.stringify(data));
  },

  convertValue: function(value)
  {
     return parseFloat(value);
  },

  render: function()
  {
    var output = {};

      if(this.props.json.hasOwnProperty("min") && this.props.json.hasOwnProperty("max"))
      {
        var step = (this.props.json.max-this.props.json.min)/1000;

        var displayedValue = sigFigs(this.state.value,this.props.json.min,this.props.json.max);

        output = (

{displayedValue}
<SliderMod name={this.props.json.id} defaultValue={this.state.value} step={step} min={this.props.json.min} max={this.props.json.max} label={this.props.json.name} onChange={this.handleChange} value={this.state.value} style={sliderStyle} sliderStyle={sliderStyleStyle}/>
);

      }
      else
      {
        output = (this.state.value);
      }

    return (

 {this.props.json.name}

{output}

)
  }
});

var BoolToggle = React.createClass({

  getInitialState: function()
  {
    var that = this;
    setters[this.props.json.id] = (function(val){that.updateState(val);});
    return {"value": this.convertValue(this.props.json.value)};
  },

  updateState: function(newValue)
  {
    this.setState({value: newValue});
  },

  handleChange: function(e,newValue)
  {
    this.updateState(newValue);
    this.communicateChange(newValue);
  },

  communicateChange: function (newValue)
  {
    var data = makeUpdateJson(this.props.json.id, newValue);
    ws.send(JSON.stringify(data));
  },

  convertValue: function(value)
  {
        return Boolean(value);
  },

  render: function()
  {
    var  output = (<Toggle  name= {this.props.json.id}  defaultToggled={this.state.value}  label={this.props.json.name} labelStyle={{display:'none'}} onToggle={this.handleChange} iconStyle={{float:'right', marginTop:'0.2em'}}/>);

    return (

 {this.props.json.name}

{output}

);
  }
});

var Action = React.createClass({

  applyAction: function(e)
  {
    var data = makeUpdateJson(this.props.json.id, null);
    ws.send(JSON.stringify(data));
  },

  render: function()
  {

    return (

 {this.props.json.name}

<RaisedButton style={{float:"right"}} label="apply" secondary={true} onTouchTap={this.applyAction} />

)
  }
});

var parseJsonToNodes = function(json)
{
  if(json == null)
  {return null;}

  return json.map(function(obj)
        {

          var output = {};
            if(obj == null)
            {
                //don't do anything

            }else if (obj.type == "parameter")
            {
               switch(obj.valueType)
              {
                case 'i':
                  output = (<IntSlider key={obj.id} json={obj}/>);
                  break;
                case 'f':
                  output = (<FloatSlider key={obj.id} json={obj}/>);
                case 'd':
                  output = (<FloatSlider key={obj.id} json={obj}/>);
                  break;
                case 'b':
                  output = (<BoolToggle key={obj.id} json={obj}/>);
                  break;
                case 'a':
                  output = (<Action key={obj.id} json={obj}/>);
                  break;
                default:
                  return String(obj.name);
                  break;
              }

            } else if (obj.type == "group")
            {
              output = (<Container key={obj.id} json={obj}/>);
            }
            return output;
        });
}

var jsonTest = JSON.parse('[  {  "name" : "Param1", "type" : "parameter", "value" : 0, "valueType" : "i"  },  { "max" : 2, "min" : 0.0099999997764825821, "name" : "Param2", "type" : "parameter", "value" : 1, "valueType" : "f" }, { "max" : 2, "min" : 0.0099999997764825821, "name" : "Param3", "type" : "parameter", "value" : 1, "valueType" : "f" }, { "content" : [ { "name" : "ParamInGroup", "type" : "parameter", "value" : "hello", "valueType" : "s" }, {  "name" : "Toggle", "type" : "parameter", "value" : 1, "valueType" : "b"  }], "name" : "MyGroup", "type" : "group" }]');

var getWSUrl = function(){
  var http_url = window.location.href;
  var parts = http_url.split("/");
  if(parts[0]!="http:"){ alert("we expect the url to be of type 'http:' instead of '"+parts[0]+"'");}
  parts[0]="ws:"
  var ws_url = parts.join("/");
  return ws_url;
}

//ask through websocket for the json that will define the interface

var a = function(){
  var ws_url = getWSUrl();

  if("WebSocket" in window)
  {
    ws = new WebSocket(ws_url);

    ws.onopen = function()
    {
      ws.send("send_interface");
    }

    ws.onmessage = function(evt)
    {
      var message = JSON.parse(evt.data);

      if(message.type == "interface")
      {
        console.log(message.content);
        ReactDOM.render(<Generator json={message.content}/>,document.getElementById('example'));
      }
      else if (message.type == "update")
      {
        for(var i =0; i<message.content.length; i++)
        {
          var paramUpdate = message.content[i];
          var attrId = paramUpdate["id"];

          var fun = setters[attrId];
          if(typeof fun === "function")
          {
            var newValue = paramUpdate["value"];
            setters[attrId](newValue);
          }
          console.log(paramUpdate);
          //change state of the specified attribute
        }
      }
      else
      {
      }
    }

    ws.onclose = function()
    {
      alert("webscocket connection is closed");
    }

  }
  else
  {
    alert("Websockets are not available in this browser.");
  }
}()

//ReactDOM.render(<Generator json={jsonTest}/>,document.getElementById('example'));


text:
from heatclient.common import base
from heatclient.v1 import stacks

DEFAULT_PAGE_SIZE = 20

class Action(base.Resource):
    def __repr__(self):
        return "<Action %s>" % self._info

    def update(self, **fields):
        self.manager.update(self, **fields)

    def delete(self):
        return self.manager.delete(self)

    def data(self, **kwargs):
        return self.manager.data(self, **kwargs)

class ActionManager(stacks.StackChildManager):
    resource_class = Action

    def suspend(self, stack_id):
        """Suspend a stack."""
        body = {'suspend': None}
        self.client.post('/stacks/%s/actions' % stack_id, data=body)

    def resume(self, stack_id):
        """Resume a stack."""
        body = {'resume': None}
        self.client.post('/stacks/%s/actions' % stack_id, data=body)

    def cancel_update(self, stack_id):
        """Cancel running update of a stack."""
        body = {'cancel_update': None}
        self.client.post('/stacks/%s/actions' % stack_id, data=body)

    def cancel_without_rollback(self, stack_id):
        """Cancel running update of a stack."""
        body = {'cancel_without_rollback': None}
        self.client.post('/stacks/%s/actions' % stack_id, data=body)

    def check(self, stack_id):
        """Check a stack."""
        body = {'check': None}
        self.client.post('/stacks/%s/actions' % stack_id, data=body)

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2013 Thiago H. de Paula Figueiredo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package br.com.arsmachina.tapestry_wymeditor.mixins;

import java.util.Locale;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.Import;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.MixinAfter;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.AssetFactory;
import org.apache.tapestry5.services.ClasspathProvider;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

/**
 * Mixin that integrates WYMeditor 1.0.0b5 to Apache Tapestry 5.4+.
 *
 * @author Thiago H. de Paula Figueiredo (http://machina.com.br/thiago)
 * @see http://wymeditor.readthedocs.org/en/latest/index.html
 * @see http://wymeditor.readthedocs.org/en/latest/customizing_wymeditor/index.html
 */
@MixinAfter
@Import(library = {
		"classpath:/META-INF/assets/wymeditor/jquery-migrate.min.js",
		"classpath:/META-INF/assets/wymeditor/jquery.wymeditor.min.js",
		"classpath:/META-INF/assets/wymeditor/plugins/embed/jquery.wymeditor.embed.js",
		"classpath:/META-INF/assets/wymeditor/jquery.wymeditor.html5.js",
})
public class Wymeditor {

	/**
	 * A JSONObject containing the options to be passed to WYMeditor. If null or not provided,
	 * it automatically creates one with the lang option set to the user locale.
	 */
	@Parameter
	private JSONObject options;

	@InjectContainer
	private ClientElement clientElement;

	@Inject
	private JavaScriptSupport javaScriptSupport;

	@Inject
	@ClasspathProvider
	private AssetFactory classpathAssetFactory;

	@Inject
	private Locale locale;

	@Inject
	@Path("classpath:/META-INF/assets/wymeditor/iframe/default/wymiframe.html")
	private Asset iframeBasePath;

	/**
	 * Invokes the JavaScript initialization code.
	 */
	void afterRender(MarkupWriter writer) {

		final JSONObject jsonObject = new JSONObject("id", clientElement.getClientId());
		final String iframeUrl = iframeBasePath.toClientURL();
        options.put("iframeBasePath", iframeUrl.substring(0, iframeUrl.lastIndexOf("/") + 1));
		jsonObject.put("options", options);
		javaScriptSupport.require("wymeditor/wymeditor").with(jsonObject);

	}

	/**
	 * Creates the default value for the options parameter.
	 *
	 * @return a {@link JSONObject} with the lang option set.
	 */
	JSONObject defaultOptions() {
		return new JSONObject("lang", locale.getLanguage(), "plugins", new JSONArray("list", "resizable", "rdfa"));
	}

}


text:
import fetch from '../intra_auth'

async function _galaxy(cursus_id, campus_id, login) {
  const res = await fetch(`https://projects.intra.42.fr/project_data.json?cursus_id=${cursus_id}&campus_id=${campus_id}&login=${login}`)

  return [res.status, await res.json()]
}

export default async (req, res) => {
  const cursus_id = req.query.cursus_id
  const campus_id = req.query.campus_id
  const login = req.query.login

  if (!cursus_id) {
    return res.status(400).json({
      error: 400,
      message: 'You need to specify \'cursus_id\''
    })
  } else if (!campus_id) {
    return res.status(400).json({
      error: 400,
      message: 'You need to specify \'campus_id\''
    })
  } else if (!login) {
    return res.status(400).json({
      error: 400,
      message: 'You need to specify \'login\''
    })
  }

  const [status, galaxy] = await _galaxy(cursus_id, campus_id, login)

  res.status(status).json(galaxy)
}


text:
/* jshint node: true, esnext:true */
var http                 = require('http');
var os                   = require("os");
var cluster              = require('cluster');
var co                   = require('co');
var WebScraperController = rootRequire("web_scraper/web_scraper_controller");
var DomainConfigLoader   = rootRequire("web_scraper/domain_config_loader");
var URLRequest           = rootRequire('web_scraper/url_request');
var logger               = rootRequire('service/logger_manager');
var BeanstalkdManager    = rootRequire("service/beanstalkd_manager");
var MongoManager         = rootRequire('service/mongo_manager');
var config               = rootRequire('config');

function WebScraperProcess(pid, numberOfController,controllerAllocationIDWhiteList){
  var self = this;

  self.pid                  = pid;
  self.controllerStatusList = [];
  self.numberOfController   = numberOfController;
  self.domainConfigLoader   = new DomainConfigLoader();
  self.AllocationWhiteList  = controllerAllocationIDWhiteList;
  self.allocatedList        = null;
  // if(this.isOnDemandMode){
  //   if(config.scraper.pending_jobs_treshold <= 0){
  //     throw new Error("config.scraper.pending_jobs_treshold cannot be lower than 0");
  //   }
  //   if(config.scraper.on_demand_probe_seconds <= 0){
  //     throw new Error("config.scraper.on_demand_probe_seconds cannot be lower than 0");
  //   }

  //   var onDemandProbeSeconds = config.scraper.on_demand_probe_seconds * 1000;

  //   self.pendingJobsProbingClient = new BeanstalkdManager();
  //   self.jobProbingIntervalId = setInterval(function() {
  //     //if all controller is up, no needs to probe
  //     var numberOfUpController = self.getUpControllerCount();
  //     if(numberOfUpController == numberOfController){
  //       return;
  //     }
  //     self.pendingJobsProbingClient
  //     .lookUpTubeStat()
  //     .then(self.__onDemandManageController.bind(self));
  //   }, onDemandProbeSeconds);
  // }

}

// WebScraperProcess.prototype.__onDemandManageController = function(status){
//   var numberOfPendingJobs = status['total-jobs'] - status['cmd-delete'];
//   var numberOfControllerNeed = Math.floor( numberOfPendingJobs / config.scraper.pending_jobs_treshold );

//   for (var i = 0 ; i < this.controllerStatusList.length && numberOfControllerNeed > 0; i++) {
//     var controllerStatus = this.controllerStatusList[i];
//     if(controllerStatus.isUP === 0){
//       controllerStatus.isUP = 1;
//       controllerStatus.controller.up();
//       numberOfControllerNeed--;
//     }
//   }
// };

// WebScraperProcess.prototype.detachController = function(controllerInstance){

//   //instead of removing controller from array which is not thread safe
//   //mark the controller as down, if all controller down, then shutdown this process
//   for (var i = this.controllerStatusList.length - 1; i >= 0; i--) {
//     var controllerStatus = this.controllerStatusList[i];

//     if(controllerInstance === controllerStatus.controller){
//       controllerStatus.isUP = 0;
//     }
//   }

//   if(this.isOnDemandMode){
//     return;
//   }

//   if(this.getUpControllerCount() === 0){
//     this.down();
//   }
// };

// WebScraperProcess.prototype.getUpControllerCount = function(){
//   var upCount = 0;
//   for (var i = this.controllerStatusList.length - 1; i >= 0; i--) {
//     var controllerStatus = this.controllerStatusList[i];
//     if(controllerStatus.isUP === 1){
//       upCount++;
//     }
//   }
//   return upCount;
// };

WebScraperProcess.prototype.allocateController = co.wrap(function*(){
  var self = this;
  var loader = self.domainConfigLoader;
  var maxAllocatableController = self.numberOfController;

  logger.debug("process "+self.pid+" has "+ maxAllocatableController+ " qouta to allocate");

  yield loader.checkDomainNameIdentifierDuplicate();

  var requiredAllocationList = yield loader.getControllerAllocationList();
  var allocationWhiteList    = self.AllocationWhiteList;
  var allocatedList          = [];

  var totalAllocatedCount = 0;

  for (var i = requiredAllocationList.length - 1; i >= 0; i--) {
    var requiredAllocation = requiredAllocationList[i];

    var domainId = requiredAllocation.domainNameIdentifier;
    var numberOfRequiredController = requiredAllocation.requiredControllerCount;

    if(allocationWhiteList.indexOf(domainId) == -1){
      continue;
    }

    logger.debug("process "+self.pid+" allocating "+ numberOfRequiredController + " for "+ domainId);

    var domainConfigDetail = yield self.domainConfigLoader.findDomainConfigDetail(domainId);

    allocatedList.push(requiredAllocation);
    totalAllocatedCount += numberOfRequiredController;

    if(totalAllocatedCount > maxAllocatableController){

      throw new Error("White listed domain exceed the maximun "+ maxAllocatableController +" of controller:\n" + self.__getAllocationReportString(allocatedList));
    }

    for (var j = numberOfRequiredController - 1; j >= 0; j--) {
      var controller = new WebScraperController(
        self.pid,
        j,
        domainId,
        self.domainConfigLoader
      );
      var controllerStatus = {
        domainId : domainId,
        domainConfigDetail : domainConfigDetail,
        controller:controller,
        isUP : 0
      };
      self.controllerStatusList.push(controllerStatus);
    }
  }
  self.allocatedList = allocatedList;
  logger.debug("Web Scraper Process allocation:\n " + self.__getAllocationReportString(allocatedList));
  logger.debug("Web Scraper Process allocation qouta left:\n " + (maxAllocatableController - totalAllocatedCount));
});

WebScraperProcess.prototype.onSeriousError = function(err){
  logger.error(err);
  logger.error(err.stack);
  process.exit(1);
};

WebScraperProcess.prototype.__getAllocationReportString = function(allocatedList){
  return allocatedList.reduce(function (a, b) {
    return a + b.domainNameIdentifier + ": require " + b.requiredControllerCount + " controller(s)\n";
  },"");
};

WebScraperProcess.prototype.applyProcessGlobalSetting = function(){
  http.globalAgent.maxSockets = config.scraper.globalMaxSockets;
  //unlimit the Event Emitter
  process.setMaxListeners(0);
};

WebScraperProcess.prototype.up = function(){

    for (var i = this.controllerStatusList.length - 1; i >= 0; i--) {
      var controllerStatus = this.controllerStatusList[i];
      controllerStatus.controller.up();
      controllerStatus.isUP = 1;
    }
};

WebScraperProcess.prototype.down = function(){
  for (var i = this.controllerStatusList.length - 1; i >= 0; i--) {
      var controllerStatus = this.controllerStatusList[i];
      controllerStatus.controller.down();
  }
  process.exit(0);
};

WebScraperProcess.prototype.seedURLRequest = function(domainNameIdentifier){
  for (var i = this.controllerStatusList.length - 1; i >= 0; i--) {
    var controllerStatus = this.controllerStatusList[i];
    var domainConfigDetail = controllerStatus.domainConfigDetail;

    if(domainConfigDetail.domainNameIdentifier == domainNameIdentifier || domainNameIdentifier === undefined){
      domainConfigDetail.lazySeedURLRequest();
    }
  }
};

module.exports = WebScraperProcess;


text:
// 07. Write a program that gets a number n and after that gets more n numbers and calculates and prints
// their sum.

using System;

class NNumbersSum
{
    static void Main()
    {
        int n;
        bool isInt = false;

        Console.Write("Input how many numbers we will summarize: ");

        isInt = int.TryParse(Console.ReadLine(), out n); // Checks for valid input

        if (!isInt || n <= 0)
        {
            Console.WriteLine("Invalid input!");
            return; // Exits if not valid integer
        }

        double sum = 0;
        double number;
        bool isDouble = false;

        for (int i = 0; i < n; i++)
        {
            Console.Write("Input {0} number for summing: ", i + 1);

            isDouble = double.TryParse(Console.ReadLine(), out number); // Checks for valid input

            if (!isDouble)
            {
                Console.WriteLine("Invalid input!");
                return; // Exits if not valid double
            }

            sum += number;
        }

        Console.WriteLine("The sum is {0}", sum);
    }
}


text:
package database

import "errors"

// Errors for Storage
var (
	ErrNotFound = errors.New("key not found")
)

// StorageProcessor is a function to process one single storage entry
type StorageProcessor func(key []byte, value []byte) error

// Reader provides KV read calls
type Reader interface {
	Get(key []byte) ([]byte, error)
}

// PrefixReader provides prefixed operations
type PrefixReader interface {
	HasPrefix(prefix []byte) bool
	ProcessByPrefix(prefix []byte, proc StorageProcessor) error
	KeysByPrefix(prefix []byte) [][]byte
	FetchByPrefix(prefix []byte) [][]byte
}

// Writer provides KV update/delete calls
type Writer interface {
	Put(key []byte, value []byte) error
	Delete(key []byte) error
}

// ReaderWriter combines Reader and Writer
type ReaderWriter interface {
	Reader
	Writer
}

// Storage is an interface to KV storage
type Storage interface {
	Reader
	Writer

	PrefixReader

	CreateBatch() Batch
	OpenTransaction() (Transaction, error)

	CreateTemporary() (Storage, error)

	Open() error
	Close() error
	CompactDB() error
	Drop() error
}

// Batch provides a way to pack many writes.
type Batch interface {
	Writer

	// Write closes batch and send accumulated writes to the database
	Write() error
}

// Transaction provides isolated atomic way to perform updates.
//
// Transactions might be expensive.
// Transaction should always finish with either Discard() or Commit()
type Transaction interface {
	Reader
	Writer

	Commit() error
	Discard()
}


text:
package org.sofi.deadman.http

import akka.actor._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import org.sofi.deadman.http.api._
import org.sofi.deadman.http.server._
import org.sofi.deadman.http.router._
import org.sofi.deadman.location.NetworkLocation
import org.sofi.deadman.messages.command._
import org.sofi.deadman.messages.query._, QueryType._
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration.{ Duration, FiniteDuration }
import scala.io.Source
import scala.util.Try

object Main extends App with Server {

  // Read args
  val id = Try(args(0)).getOrElse("")
  val mode = Try(args(1)).getOrElse("")

  // Boot actor system
  val config = if (id.isEmpty) ConfigFactory.load() else ConfigFactory.load(id)
  implicit val system = ActorSystem("deadman-switch-actor-system", config.resolve())
  implicit val executionContext = system.dispatcher
  implicit val materialize = ActorMaterializer()

  // Init actor API timeout
  val duration = Duration(config.getString("request-timeout"))
  implicit val requestTimeout: Timeout = FiniteDuration(duration.length, duration.unit)

  // Activate replication endpoint
  val location = new NetworkLocation(id)

  // Start REST API server
  implicit val commandApi = new CommandApi(location.commandManager)
  implicit val queryApi = new QueryApi(location.queryManager)
  startup(new HttpRouter().routes)

  // If indicated, start interactive CLI
  if ("cli".equalsIgnoreCase(mode)) {
    system.actorOf(CommandLine.props(location.commandManager, location.queryManager).withDispatcher("dispatchers.cli"))
  }
}

private final class CommandLine(val commandManager: ActorRef, val queryManager: ActorRef) extends Actor with ActorLogging {

  def receive = {

    // Command successes and errors
    case CommandResponse(typ, msg) ⇒
      log.info("Command Response: {}", s"$typ ${msg.mkString(",")}".trim)
      prompt()

    // Query results
    case Tasks(tasks) ⇒
      if (tasks.isEmpty) {
        log.info("No tasks found")
      }
      tasks.foreach { t ⇒
        log.info(t.toString)
      }
      prompt()

    // Process CLI and send commands and/or queries
    case line: String ⇒ line.trim.split(' ').toList match {

      // Commands

      case "schedule" :: key :: agg :: ent :: ttl :: ttw :: tags ⇒
        commandManager ! ScheduleTask(key, agg, ent, Duration(ttl).toMillis, Seq(Duration(ttw).toMillis), tags)

      case "complete" :: key :: agg :: ent :: Nil ⇒
        commandManager ! CompleteTask(key, agg, ent)

      // Query scheduled tasks

      case "query" :: "aggregate" :: id :: Nil ⇒
        queryManager ! GetTasks(AGGREGATE, aggregate = Some(id))

      case "query" :: "entity" :: id :: Nil ⇒
        queryManager ! GetTasks(ENTITY, entity = Some(id))

      case "query" :: "key" :: value :: Nil ⇒
        queryManager ! GetTasks(KEY, key = Some(value))

      // Query expired tasks

      case "query" :: "aggregate" :: "expirations" :: id :: Nil ⇒
        queryManager ! GetExpirations(AGGREGATE, aggregate = Some(id))

      case "query" :: "entity" :: "expirations" :: id :: Nil ⇒
        queryManager ! GetExpirations(ENTITY, entity = Some(id))

      case "query" :: "key" :: "expirations" :: key :: window :: Nil ⇒
        queryManager ! GetByKey(key, window)

      case "query" :: "tag" :: "expirations" :: tag :: window :: Nil ⇒
        queryManager ! GetByTag(tag, window)

      // Query task warnings

      case "query" :: "aggregate" :: "warnings" :: id :: Nil ⇒
        queryManager ! GetWarnings(AGGREGATE, aggregate = Some(id))

      case "query" :: "entity" :: "warnings" :: id :: Nil ⇒
        queryManager ! GetWarnings(ENTITY, entity = Some(id))

      // Catch-all prompt

      case _ ⇒
        prompt()
    }
  }

  private val lines = Source.stdin.getLines

  def prompt(): Unit = if (lines.hasNext) {
    lines.next() match {
      case "exit" ⇒
        context.system.registerOnTermination(System.exit(0))
        val _ = context.system.terminate()
      case line ⇒ self ! line
    }
  }

  override def preStart(): Unit = prompt()
}

object CommandLine {
  def props(commandManager: ActorRef, queryManager: ActorRef): Props = Props(new CommandLine(commandManager, queryManager))
}


text: <progressbar value="listProgress" type="info"></progressbar>


text:
package sp.psl

import sp.control.DBValue
import sp.control.BusAddress
import akka.actor._
import com.codemettle.reactivemq._
import com.codemettle.reactivemq.ReActiveMQMessages._
import com.codemettle.reactivemq.model._
import org.json4s.JsonAST.JBool
import org.json4s.JsonAST.JArray
import sp.domain.logic.IDAbleLogic
import sp.system.messages._
import sp.system._
import sp.domain._
import sp.domain.Logic._

import scala.util.Try

object OperatorInstructions extends SPService {
  val specification = SPAttributes(
    "service" -> SPAttributes(
      "group"-> "psl" // to organize in gui. maybe use "hide" to hide service in gui
    ),
    "setup" -> SPAttributes(
      "busIP" -> KeyDefinition("String", List(), Some("129.16.26.22")),
      "publishTopic" -> KeyDefinition("String", List(), Some("response")),
      "subscribeTopic" -> KeyDefinition("String", List(), Some("commands"))
    ),
    "command" -> KeyDefinition("String", List("connect", "disconnect", "done"), Some("connect")),
    "doneID" -> KeyDefinition("ID", List(), Some(SPValue(ID.newID)))
  )
  val transformTuple  = (
    TransformValue("setup", _.getAs[BusSetup]("setup")),
    TransformValue("command", _.getAs[String]("command")),
    TransformValue("doneID", _.getAs[ID]("doneID"))
  )
  val transformation = transformToList(transformTuple.productIterator.toList)
  def props(eventHandler: ActorRef) = Props(classOf[OperatorInstructions], eventHandler)
}

case class BusSetup(busIP: String, publishTopic: String, subscribeTopic: String)
case class OperatorInstructionData(id: ID, colors: List[String], textMessage: String)

// Add constructor parameters if you need access to modelHandler and ServiceHandler etc
class OperatorInstructions(eventHandler: ActorRef) extends Actor with ServiceSupport {
  import context.dispatcher
  val serviceID = ID.newID
  var theBus: Option[ActorRef] = None
  var setup: Option[BusSetup] = None
  var serviceName: Option[String] = None
  var subscriptions: Map[ID, DBValue] = Map()
  var run: Boolean = false // start
  var mode: Int = 0  // notReady, ready, executing, finished

  val addressPrefix = "operatorInstructions"

  def receive = {
    case r @ Request(service, attr, ids, reqID) => {
      // Always include the following lines. Are used by the helper functions
      val replyTo = sender()
      implicit val rnr = RequestNReply(r, replyTo)

      val s = transform(OperatorInstructions.transformTuple._1)
      val command= transform(OperatorInstructions.transformTuple._2)
      val core = r.attributes.getAs[ServiceHandlerAttributes]("core").get

      println("Command: " + command)
      eventHandler ! SubscribeToSSE(self)

      command match {
        case "connect" =>
          setupBus(s, rnr)
        case "disconnect" =>
          disconnect()
        case "done" =>
          val id = transform(OperatorInstructions.transformTuple._3)
          sendDone(id)
        case _ =>
          sender ! SPError("Ill formed request");
      }
      replyTo ! Response(List(), connectedAttribute(), service, serviceID)
    }
    case ConnectionEstablished(request, c) => {
      println("OperatorInstructions connected to the bus:"+request)
      setup.foreach{ s=>
        c ! ConsumeFromTopic(s.subscribeTopic)
        theBus = Some(c)
        eventHandler ! Response(List(), connectedAttribute(), serviceName.get, serviceID)
        // ready!
        mode = 1
        sendState
      }
    }
    case ConnectionFailed(request, reason) => {
      println("Operator instruction AMQ failed:"+reason)
    }
    case r @ Response(ids, attr, service, _) if service == "OperationControl" => {
      // high level force reset...
      if(attr.getAs[Boolean]("reset").getOrElse(false)) {
        println("OperatorInstructions: High level force reset! Resetting.")
        run = false
        mode = 1
        eventHandler ! Response(List(), SPAttributes("resetOperatorInstructions"->true, "silent"->true), serviceName.get, serviceID)
      }
    }
    case mess @ AMQMessage(body, prop, headers) => {
      //println(s"new instruction on the bus!!!!!!!")
      val resp = SPAttributes.fromJson(body.toString).getOrElse(SPAttributes())

      resp.getAs[String]("command") match {
        case Some("subscribe") =>
          resp.getAs[List[DBValue]]("dbs").foreach { oi =>
            oi.map { dbv =>
              //println("dbv: " + dbv);
              dbv.address.to[BusAddress] match {
                case Some(a) => { subscriptions += (dbv.id -> dbv) }
                case _ => // skip these
              }
            }
            // reply with updated state
            sendState
          }
        case Some("write") =>
          // set variables... (only run exist. hack it)
          val newRun = for {
            db <- resp.getAs[List[DBValue]]("dbs").getOrElse(List())
            r <- db.address.to[BusAddress] if r.name == addressPrefix + ".run"
            v <- db.value.to[Boolean]
          } yield {
            v
          }

          val newP = for {
            db <- resp.getAs[List[DBValue]]("dbs").getOrElse(List())
            r <- db.address.to[BusAddress] if r.name == addressPrefix + ".brickPositions"
            v <- db.value.to[List[Brick]]
          } yield {
            v
          }

          if(newRun.nonEmpty) {
            // set run
            run = newRun.foldLeft(true)(_&&_)
            if(run) mode = 2 // run flag set, executing until we are done
            else mode = 1 // run flag reset, ready to start again
            sendState // send new state

            println("operator instructions -- new run: " + run)
            if(run && newP.nonEmpty) {
              // send instructions to ui (parameter) -- only when we start
              val p = newP.flatten
              println("operator instructions -- new parameters: " + p);
              eventHandler ! Response(List(), SPAttributes("operatorInstructions"->p, "silent"->true), serviceName.get, serviceID)
            }
          }
        case x@_ =>
          println("Unexpected " + x + " from " + body.toString)
      }
    }

    case ConnectionInterrupted(ca, x) => {
      println("Operator instr AMQ connection closed")
      setup = None
    }
    case x => {
      // println("Operator instr no match for message: "+x)
    }
  }

  def sendState = {
    val dbs = subscriptions.map { case (k,v) =>
      val value = v.address.to[BusAddress] match {
        case Some(addr) if addr.name == addressPrefix + ".run" => SPValue(run)
        case Some(addr) if addr.name == addressPrefix + ".mode" => SPValue(mode)
        case s@_ => {
          // println("op instruction subscription does not exist: " + s)
          SPValue(false)
        }
      }
      SPAttributes("id" -> k, "value" -> value)
    }.toList
    val mess = SPAttributes("dbs" -> dbs)
    sendMessage(mess)
  }

  def setupBus(s: BusSetup, rnr: RequestNReply) = {
      setup = Some(s)
      serviceName = Some(rnr.req.service)
      println(s"op instr connecting to $s")
      ReActiveMQExtension(context.system).manager ! GetConnection(s"nio://${s.busIP}:61616")
  }

  def connectedAttribute() = {
    if (setup.isEmpty)
      SPAttributes("theBus"->"Not connected") merge SPAttributes("silent"->true)
    else if (theBus.isEmpty)
      SPAttributes("theBus"->"Connecting") merge SPAttributes("silent"->true)
    else
      SPAttributes("theBus"->"Connected") merge SPAttributes("silent"->true)
  }

  def disconnect() = {
    println("op instr disconnecting from the bus")
    theBus.foreach(_ ! CloseConnection)
    this.setup = None
    this.theBus = None
  }

  def sendMessage(mess: SPAttributes) = {
    for {
      bus <- theBus
      s <- setup
    } yield {
      println(s"operator instruction sending: ${mess.toJson}")
      bus ! SendMessage(Topic(s.publishTopic), AMQMessage(mess.toJson))
    }
  }

  def sendDone(id: ID) = {
    mode = 3 // completed
    sendState
  }

  override def postStop() = {
    println("post stop, disconnect...")
    disconnect()
  }
}


text:
package com.raizlabs.android.dbflow.test.container;

import com.raizlabs.android.dbflow.structure.container.MapModel;
import com.raizlabs.android.dbflow.test.FlowTestCase;
import com.raizlabs.android.dbflow.test.structure.TestModel1;

import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 */
public class MapModelTest extends FlowTestCase {

    public void testMapModel() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("name", "test");
        MapModel<TestModel1> model1MapModel = new MapModel<TestModel1>(dataMap,TestModel1.class);
        model1MapModel.save(false);

        assertTrue(model1MapModel.exists());
        assertNotNull(model1MapModel.toModel());

        Map<String, Object> otherDataMap = new HashMap<String, Object>();
        otherDataMap.put("name", "test");
        otherDataMap.put("party_type", "club");
        otherDataMap.put("count1", 10);

        otherDataMap.put("testModel", dataMap);

        MapModel<TestModelContainerClass> testModelContainerClassMapModel = new MapModel<TestModelContainerClass>(otherDataMap, TestModelContainerClass.class);
        testModelContainerClassMapModel.save(false);

        assertTrue(testModelContainerClassMapModel.exists());
        assertNotNull(testModelContainerClassMapModel.toModel());
        assertNotNull(testModelContainerClassMapModel.toModel().testModel);
    }

}


text:
var PIXI = require('pixi.js');
require('../pixi.nativeLineGL.js');

window.PIXI = PIXI;


text:
package org.dbflute.erflute.editor.view.dialog.image;

import org.dbflute.erflute.core.dialog.AbstractDialog;
import org.dbflute.erflute.core.widgets.CompositeFactory;
import org.dbflute.erflute.core.widgets.SpinnerWithScale;
import org.dbflute.erflute.editor.model.diagram_contents.element.node.image.InsertedImage;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

public class InsertedImageDialog extends AbstractDialog {

    private SpinnerWithScale hueSpinner;
    private SpinnerWithScale saturationSpinner;
    private SpinnerWithScale brightnessSpinner;
    private SpinnerWithScale alphaSpinner;
    private Button fixAspectRatioCheckbox;
    private final InsertedImage insertedImage;
    private InsertedImage newInsertedImage;

    public InsertedImageDialog(Shell parentShell, InsertedImage insertedImage) {
        super(parentShell, 4);

        this.insertedImage = insertedImage;
    }

    @Override
    protected void initComponent(Composite composite) {
        this.hueSpinner = CompositeFactory.createSpinnerWithScale(this, composite, "label.image.hue", "", 0, 360);
        this.saturationSpinner = CompositeFactory.createSpinnerWithScale(this, composite, "label.image.saturation", -100, 100);
        this.brightnessSpinner = CompositeFactory.createSpinnerWithScale(this, composite, "label.image.brightness", -100, 100);
        this.alphaSpinner = CompositeFactory.createSpinnerWithScale(this, composite, "label.image.alpha", 0, 255);
        this.fixAspectRatioCheckbox = CompositeFactory.createCheckbox(this, composite, "label.image.fix.aspect.ratio", 3);
    }

    @Override
    protected String doValidate() {
        insertedImage.setHue(hueSpinner.getSelection());
        insertedImage.setSaturation(saturationSpinner.getSelection());
        insertedImage.setBrightness(brightnessSpinner.getSelection());
        insertedImage.setAlpha(alphaSpinner.getSelection());

        insertedImage.setFixAspectRatio(fixAspectRatioCheckbox.getSelection());

        insertedImage.setDirty();

        return null;
    }

    @Override
    protected void performOK() {
        this.newInsertedImage = new InsertedImage();
        newInsertedImage.setHue(hueSpinner.getSelection());
        newInsertedImage.setSaturation(saturationSpinner.getSelection());
        newInsertedImage.setBrightness(brightnessSpinner.getSelection());
        newInsertedImage.setAlpha(alphaSpinner.getSelection());
        newInsertedImage.setFixAspectRatio(fixAspectRatioCheckbox.getSelection());
    }

    @Override
    protected String getTitle() {
        return "dialog.title.image.information";
    }

    @Override
    protected void setupData() {
        hueSpinner.setSelection(insertedImage.getHue());
        saturationSpinner.setSelection(insertedImage.getSaturation());
        brightnessSpinner.setSelection(insertedImage.getBrightness());
        alphaSpinner.setSelection(insertedImage.getAlpha());
        fixAspectRatioCheckbox.setSelection(insertedImage.isFixAspectRatio());
    }

    public InsertedImage getNewInsertedImage() {
        return newInsertedImage;
    }
}


text:
import tempfile

tempfile.tempdir = '/I/changed/this/path'
print('gettempdir():', tempfile.gettempdir())


text:
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/util/HashMap.hpp>

template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
    namespace util
    {
typedef ::SubArray< ::java::util::Map_Entry, ::java::lang::ObjectArray > Map_EntryArray;
typedef ::SubArray< ::java::util::HashMap_Node, ::java::lang::ObjectArray, Map_EntryArray > HashMap_NodeArray;
    } // util
} // java

extern void unimplemented_(const char16_t* name);
java::util::HashMap::HashMap(const ::default_init_tag&)
    : super(*static_cast< ::default_init_tag* >(0))
{
    clinit();
}

java::util::HashMap::HashMap()
    : HashMap(*static_cast< ::default_init_tag* >(0))
{
    ctor();
}

java::util::HashMap::HashMap(int32_t initialCapacity)
    : HashMap(*static_cast< ::default_init_tag* >(0))
{
    ctor(initialCapacity);
}

java::util::HashMap::HashMap(Map* m)
    : HashMap(*static_cast< ::default_init_tag* >(0))
{
    ctor(m);
}

java::util::HashMap::HashMap(int32_t initialCapacity, float loadFactor)
    : HashMap(*static_cast< ::default_init_tag* >(0))
{
    ctor(initialCapacity, loadFactor);
}

constexpr int32_t java::util::HashMap::DEFAULT_INITIAL_CAPACITY;
constexpr float java::util::HashMap::DEFAULT_LOAD_FACTOR;
constexpr int32_t java::util::HashMap::MAXIMUM_CAPACITY;
constexpr int32_t java::util::HashMap::MIN_TREEIFY_CAPACITY;
constexpr int32_t java::util::HashMap::TREEIFY_THRESHOLD;
constexpr int32_t java::util::HashMap::UNTREEIFY_THRESHOLD;
constexpr int64_t java::util::HashMap::serialVersionUID;

void ::java::util::HashMap::ctor()
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::java::util::HashMap::ctor()");
}

void ::java::util::HashMap::ctor(int32_t initialCapacity)
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::java::util::HashMap::ctor(int32_t initialCapacity)");
}

void ::java::util::HashMap::ctor(Map* m)
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::java::util::HashMap::ctor(Map* m)");
}

void ::java::util::HashMap::ctor(int32_t initialCapacity, float loadFactor)
{ /* stub */
    /* super::ctor(); */
    unimplemented_(u"void ::java::util::HashMap::ctor(int32_t initialCapacity, float loadFactor)");
}

void java::util::HashMap::afterNodeAccess(HashMap_Node* p)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::afterNodeAccess(HashMap_Node* p)");
}

void java::util::HashMap::afterNodeInsertion(bool evict)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::afterNodeInsertion(bool evict)");
}

void java::util::HashMap::afterNodeRemoval(HashMap_Node* p)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::afterNodeRemoval(HashMap_Node* p)");
}

int32_t java::util::HashMap::capacity()
{ /* stub */
    unimplemented_(u"int32_t java::util::HashMap::capacity()");
    return 0;
}

void java::util::HashMap::clear()
{ /* stub */
    unimplemented_(u"void java::util::HashMap::clear()");
}

java::lang::Object* java::util::HashMap::clone()
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::clone()");
    return 0;
}

java::lang::Class* java::util::HashMap::comparableClassFor(::java::lang::Object* x)
{ /* stub */
    clinit();
    unimplemented_(u"java::lang::Class* java::util::HashMap::comparableClassFor(::java::lang::Object* x)");
    return 0;
}

int32_t java::util::HashMap::compareComparables(::java::lang::Class* kc, ::java::lang::Object* k, ::java::lang::Object* x)
{ /* stub */
    clinit();
    unimplemented_(u"int32_t java::util::HashMap::compareComparables(::java::lang::Class* kc, ::java::lang::Object* k, ::java::lang::Object* x)");
    return 0;
}

java::lang::Object* java::util::HashMap::compute(::java::lang::Object* key, ::java::util::function::BiFunction* remappingFunction)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::compute(::java::lang::Object* key, ::java::util::function::BiFunction* remappingFunction)");
    return 0;
}

java::lang::Object* java::util::HashMap::computeIfAbsent(::java::lang::Object* key, ::java::util::function::Function* mappingFunction)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::computeIfAbsent(::java::lang::Object* key, ::java::util::function::Function* mappingFunction)");
    return 0;
}

java::lang::Object* java::util::HashMap::computeIfPresent(::java::lang::Object* key, ::java::util::function::BiFunction* remappingFunction)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::computeIfPresent(::java::lang::Object* key, ::java::util::function::BiFunction* remappingFunction)");
    return 0;
}

bool java::util::HashMap::containsKey(::java::lang::Object* key)
{ /* stub */
    unimplemented_(u"bool java::util::HashMap::containsKey(::java::lang::Object* key)");
    return 0;
}

bool java::util::HashMap::containsValue(::java::lang::Object* value)
{ /* stub */
    unimplemented_(u"bool java::util::HashMap::containsValue(::java::lang::Object* value)");
    return 0;
}

java::util::Set* java::util::HashMap::entrySet()
{ /* stub */
    unimplemented_(u"java::util::Set* java::util::HashMap::entrySet()");
    return 0;
}

void java::util::HashMap::forEach(::java::util::function::BiConsumer* action)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::forEach(::java::util::function::BiConsumer* action)");
}

java::lang::Object* java::util::HashMap::get(::java::lang::Object* key)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::get(::java::lang::Object* key)");
    return 0;
}

java::util::HashMap_Node* java::util::HashMap::getNode(int32_t hash, ::java::lang::Object* key)
{ /* stub */
    unimplemented_(u"java::util::HashMap_Node* java::util::HashMap::getNode(int32_t hash, ::java::lang::Object* key)");
    return 0;
}

java::lang::Object* java::util::HashMap::getOrDefault(::java::lang::Object* key, ::java::lang::Object* defaultValue)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::getOrDefault(::java::lang::Object* key, ::java::lang::Object* defaultValue)");
    return 0;
}

int32_t java::util::HashMap::hash(::java::lang::Object* key)
{ /* stub */
    clinit();
    unimplemented_(u"int32_t java::util::HashMap::hash(::java::lang::Object* key)");
    return 0;
}

void java::util::HashMap::internalWriteEntries(::java::io::ObjectOutputStream* s)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::internalWriteEntries(::java::io::ObjectOutputStream* s)");
}

bool java::util::HashMap::isEmpty()
{ /* stub */
    unimplemented_(u"bool java::util::HashMap::isEmpty()");
    return 0;
}

java::util::Set* java::util::HashMap::keySet()
{ /* stub */
    unimplemented_(u"java::util::Set* java::util::HashMap::keySet()");
    return 0;
}

float java::util::HashMap::loadFactor()
{ /* stub */
    unimplemented_(u"float java::util::HashMap::loadFactor()");
    return 0;
}

java::lang::Object* java::util::HashMap::merge(::java::lang::Object* key, ::java::lang::Object* value, ::java::util::function::BiFunction* remappingFunction)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::merge(::java::lang::Object* key, ::java::lang::Object* value, ::java::util::function::BiFunction* remappingFunction)");
    return 0;
}

java::util::HashMap_Node* java::util::HashMap::newNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, HashMap_Node* next)
{ /* stub */
    unimplemented_(u"java::util::HashMap_Node* java::util::HashMap::newNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, HashMap_Node* next)");
    return 0;
}

java::util::HashMap_TreeNode* java::util::HashMap::newTreeNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, HashMap_Node* next)
{ /* stub */
    unimplemented_(u"java::util::HashMap_TreeNode* java::util::HashMap::newTreeNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, HashMap_Node* next)");
    return 0;
}

java::lang::Object* java::util::HashMap::put(::java::lang::Object* key, ::java::lang::Object* value)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::put(::java::lang::Object* key, ::java::lang::Object* value)");
    return 0;
}

void java::util::HashMap::putAll(Map* m)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::putAll(Map* m)");
}

java::lang::Object* java::util::HashMap::putIfAbsent(::java::lang::Object* key, ::java::lang::Object* value)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::putIfAbsent(::java::lang::Object* key, ::java::lang::Object* value)");
    return 0;
}

void java::util::HashMap::putMapEntries(Map* m, bool evict)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::putMapEntries(Map* m, bool evict)");
}

java::lang::Object* java::util::HashMap::putVal(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, bool onlyIfAbsent, bool evict)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::putVal(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, bool onlyIfAbsent, bool evict)");
    return 0;
}

/* private: void java::util::HashMap::readObject(::java::io::ObjectInputStream* s) */
void java::util::HashMap::reinitialize()
{ /* stub */
    unimplemented_(u"void java::util::HashMap::reinitialize()");
}

java::lang::Object* java::util::HashMap::remove(::java::lang::Object* key)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::remove(::java::lang::Object* key)");
    return 0;
}

bool java::util::HashMap::remove(::java::lang::Object* key, ::java::lang::Object* value)
{ /* stub */
    unimplemented_(u"bool java::util::HashMap::remove(::java::lang::Object* key, ::java::lang::Object* value)");
    return 0;
}

java::util::HashMap_Node* java::util::HashMap::removeNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, bool matchValue, bool movable)
{ /* stub */
    unimplemented_(u"java::util::HashMap_Node* java::util::HashMap::removeNode(int32_t hash, ::java::lang::Object* key, ::java::lang::Object* value, bool matchValue, bool movable)");
    return 0;
}

java::lang::Object* java::util::HashMap::replace(::java::lang::Object* key, ::java::lang::Object* value)
{ /* stub */
    unimplemented_(u"java::lang::Object* java::util::HashMap::replace(::java::lang::Object* key, ::java::lang::Object* value)");
    return 0;
}

bool java::util::HashMap::replace(::java::lang::Object* key, ::java::lang::Object* oldValue, ::java::lang::Object* newValue)
{ /* stub */
    unimplemented_(u"bool java::util::HashMap::replace(::java::lang::Object* key, ::java::lang::Object* oldValue, ::java::lang::Object* newValue)");
    return 0;
}

void java::util::HashMap::replaceAll(::java::util::function::BiFunction* function)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::replaceAll(::java::util::function::BiFunction* function)");
}

java::util::HashMap_Node* java::util::HashMap::replacementNode(HashMap_Node* p, HashMap_Node* next)
{ /* stub */
    unimplemented_(u"java::util::HashMap_Node* java::util::HashMap::replacementNode(HashMap_Node* p, HashMap_Node* next)");
    return 0;
}

java::util::HashMap_TreeNode* java::util::HashMap::replacementTreeNode(HashMap_Node* p, HashMap_Node* next)
{ /* stub */
    unimplemented_(u"java::util::HashMap_TreeNode* java::util::HashMap::replacementTreeNode(HashMap_Node* p, HashMap_Node* next)");
    return 0;
}

java::util::HashMap_NodeArray* java::util::HashMap::resize()
{ /* stub */
    unimplemented_(u"java::util::HashMap_NodeArray* java::util::HashMap::resize()");
    return 0;
}

int32_t java::util::HashMap::size()
{ /* stub */
    unimplemented_(u"int32_t java::util::HashMap::size()");
    return 0;
}

int32_t java::util::HashMap::tableSizeFor(int32_t cap)
{ /* stub */
    clinit();
    unimplemented_(u"int32_t java::util::HashMap::tableSizeFor(int32_t cap)");
    return 0;
}

void java::util::HashMap::treeifyBin(HashMap_NodeArray* tab, int32_t hash)
{ /* stub */
    unimplemented_(u"void java::util::HashMap::treeifyBin(HashMap_NodeArray* tab, int32_t hash)");
}

java::util::Collection* java::util::HashMap::values()
{ /* stub */
    unimplemented_(u"java::util::Collection* java::util::HashMap::values()");
    return 0;
}

/* private: void java::util::HashMap::writeObject(::java::io::ObjectOutputStream* s) */
extern java::lang::Class *class_(const char16_t *c, int n);

java::lang::Class* java::util::HashMap::class_()
{
    static ::java::lang::Class* c = ::class_(u"java.util.HashMap", 17);
    return c;
}

bool java::util::HashMap::equals(::java::lang::Object* o)
{
    return AbstractMap::equals(o);
}

int32_t java::util::HashMap::hashCode()
{
    return AbstractMap::hashCode();
}

java::lang::Class* java::util::HashMap::getClass0()
{
    return class_();
}


text:
Provides support for HTTP Live Streaming (HLS) content in ExoPlayer.

## Getting the module

The easiest way to get the module is to add it as a gradle dependency:

```gradle
implementation 'androidx.media3:media3-exoplayer-hls:1.X.X'
```

where `1.X.X` is the version, which must match the version of the other media
modules being used.

Alternatively, you can clone this GitHub project and depend on the module
locally. Instructions for doing this can be found in the [top level README][].

[top level README]: ../../README.md

## Using the module

Adding a dependency to this module is all that's required to enable playback of
HLS media items added to `ExoPlayer` in its default configuration. Internally,
`DefaultMediaSourceFactory` will automatically detect the presence of the module
and convert an HLS `MediaItem` into an `HlsMediaSource` for playback.

Similarly, a `DownloadManager` in its default configuration will use
`DefaultDownloaderFactory`, which will automatically detect the presence of
the module and build `HlsDownloader` instances to download HLS content.

For advanced playback use cases, applications can build `HlsMediaSource`
instances and pass them directly to the player. For advanced download use cases,
`HlsDownloader` can be used directly.


text:
//========================================================================
//Copyright 2007-2008 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================

package com.dyuproject.util.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.mortbay.util.UrlEncoded;

/**
 * Simple http connector using the built-in HttpURLConnection
 *
 * @author David Yu
 * @created Sep 8, 2008
 */

public final class SimpleHttpConnector implements HttpConnector
{

    /**
     * THe default buffer size (4096 or the system property "shc.buffer_size")
     */
    public static int DEFAULT_BUFFER_SIZE = Integer.getInteger("shc.buffer_size", 4096).intValue();
    /**
     * The default connect timeout (10000 or the system property "shc.connect_timeout")
     */
    public static int DEFAULT_CONNECT_TIMEOUT = Integer.getInteger("shc.connect_timeout", 10000).intValue();
    /**
     * The defualt follow redirect flag (false or the system property "shc.follow_redirects")
     */
    public static boolean DEFAULT_FOLLOW_REDIRECT = !"false".equals(
            System.getProperty("shc.follow_redirects"));

    private static final SimpleHttpConnector DEFAULT = new SimpleHttpConnector();

    /**
     * Gets the default instance.
     */
    public static SimpleHttpConnector getDefault()
    {
        return DEFAULT;
    }

    private final int _bufferSize;
    private final int _connectTimeout;
    private final boolean _followRedirects;

    public SimpleHttpConnector()
    {
        this(DEFAULT_BUFFER_SIZE, DEFAULT_CONNECT_TIMEOUT, DEFAULT_FOLLOW_REDIRECT);
    }

    public SimpleHttpConnector(int bufferSize, int connectTimeout, boolean followRedirects)
    {
        _bufferSize = bufferSize;
        _connectTimeout = connectTimeout;
        _followRedirects = followRedirects;
    }

    /**
     * Gets the buffer size.
     */
    public int getBufferSize()
    {
        return _bufferSize;
    }

    /**
     * Gets the connection timeout.
     */
    public int getConnectTimeout()
    {
        return _connectTimeout;
    }

    /**
     * Checks whether this instance follows redirects or not.
     */
    public boolean isFollowRedirects()
    {
        return _followRedirects;
    }

    static HttpURLConnection getConnection(String url, Map<?,?> headers) throws IOException
    {
        HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
        if(headers!=null)
        {
            for(Map.Entry<?,?> entry : headers.entrySet())
            {
                connection.setRequestProperty(entry.getKey().toString(),
                        entry.getValue().toString());
            }
        }
        return connection;
    }

    static HttpURLConnection getConnection(String url, Iterable<Parameter> headers) throws IOException
    {
        HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
        if(headers!=null)
        {
            for(Parameter h : headers)
                connection.setRequestProperty(h.getKey(), h.getValue());
        }
        return connection;
    }

    static String appendUrl(String url, Map<?,?> queryParams)
    {
        StringBuilder buffer = new StringBuilder().append(url);
        char separator = url.lastIndexOf('?')==-1 ? '?' : '&';
        for(Map.Entry<?,?> entry : queryParams.entrySet())
        {
            buffer.append(separator).append(entry.getKey()).append('=').append(
                    UrlEncoded.encodeString(entry.getValue().toString()));
            separator = '&';
        }
        return buffer.toString();
    }

    static String appendUrl(String url, Iterable<Parameter> queryParams)
    {
        StringBuilder buffer = new StringBuilder().append(url);
        char separator = url.lastIndexOf('?')==-1 ? '?' : '&';
        for(Parameter p : queryParams)
        {
            buffer.append(separator).append(p.getKey()).append('=').append(
                    UrlEncoded.encodeString(p.getValue()));
            separator = '&';
        }
        return buffer.toString();
    }

    static byte[] getEncodedData(Map<?,?> parameters, String charset)
    throws UnsupportedEncodingException
    {
        StringBuilder buffer = new StringBuilder();
        for(Map.Entry<?,?> entry : parameters.entrySet())
        {
            buffer.append('&').append(entry.getKey()).append('=').append(
                    UrlEncoded.encodeString(entry.getValue().toString()));
        }
        return buffer.substring(1).getBytes(charset);
    }

    static byte[] getEncodedData(Iterable<Parameter> parameters, String charset)
    throws UnsupportedEncodingException
    {
        StringBuilder buffer = new StringBuilder();
        for(Parameter p : parameters)
        {
            buffer.append('&').append(p.getKey()).append('=').append(
                    UrlEncoded.encodeString(p.getValue().toString()));
        }
        return buffer.substring(1).getBytes(charset);
    }

    public Response doHEAD(String url, Map<?,?> headers) throws IOException
    {
        return send(HEAD, getConnection(url, headers));
    }

    public Response doHEAD(String url, Iterable<Parameter> headers) throws IOException
    {
        return send(HEAD, getConnection(url, headers));
    }

    public Response doGET(String url, Map<?,?> headers)
    throws IOException
    {
        return send(GET, getConnection(url, headers));
    }

    public Response doGET(String url, Iterable<Parameter> headers)
    throws IOException
    {
        return send(GET, getConnection(url, headers));
    }

    public Response doGET(String url, Map<?,?> headers, Map<?,?> parameters)
    throws IOException
    {
        return send(GET, getConnection(appendUrl(url, parameters), headers));
    }

    public Response doGET(String url, Iterable<Parameter> headers, Map<?,?> parameters)
    throws IOException
    {
        return send(GET, getConnection(appendUrl(url, parameters), headers));
    }

    public Response doGET(String url, Iterable<Parameter> headers, Iterable<Parameter> parameters)
    throws IOException
    {
        return send(GET, getConnection(appendUrl(url, parameters), headers));
    }

    public Response doDELETE(String url, Map<?,?> headers)
    throws IOException
    {
        return send(DELETE, getConnection(url, headers));
    }

    public Response doDELETE(String url, Iterable<Parameter> headers)
    throws IOException
    {
        return send(DELETE, getConnection(url, headers));
    }

    public Response doDELETE(String url, Map<?,?> headers, Map<?,?> parameters)
    throws IOException
    {
        return send(DELETE, getConnection(appendUrl(url, parameters), headers));
    }

    public Response doDELETE(String url, Iterable<Parameter> headers, Map<?,?> parameters)
    throws IOException
    {
        return send(DELETE, getConnection(appendUrl(url, parameters), headers));
    }

    public Response doDELETE(String url, Iterable<Parameter> headers, Iterable<Parameter> parameters)
    throws IOException
    {
        return send(DELETE, getConnection(appendUrl(url, parameters), headers));
    }

    Response send(String method, HttpURLConnection connection)
    throws IOException
    {
        connection.setRequestMethod(method);
        connection.setConnectTimeout(_connectTimeout);
        connection.setInstanceFollowRedirects(_followRedirects);
        connection.setDoInput(true);
        connection.connect();
        return new HttpURLConnectionWrapper(connection);
    }

    public Response doPOST(String url, Map<?,?> headers, Map<?,?> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(POST, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Map<?,?> headers, Iterable<Parameter> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(POST, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Iterable<Parameter> headers, Map<?,?> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(POST, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Iterable<Parameter> headers, Iterable<Parameter> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(POST, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Map<?,?> headers, String contentType, byte[] data)
    throws IOException
    {
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Iterable<Parameter> headers, String contentType, byte[] data)
    throws IOException
    {
        return sendContent(POST, getConnection(url, headers), contentType, data);
    }

    public Response doPOST(String url, Map<?,?> headers, String contentType,
            InputStreamReader reader) throws IOException
    {
        return sendContent(POST, getConnection(url, headers), contentType, reader);
    }

    public Response doPOST(String url, Iterable<Parameter> headers, String contentType,
            InputStreamReader reader) throws IOException
    {
        return sendContent(POST, getConnection(url, headers), contentType, reader);
    }

    // PUT

    public Response doPUT(String url, Map<?,?> headers, Map<?,?> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(PUT, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Map<?,?> headers, Iterable<Parameter> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(PUT, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Iterable<Parameter> headers, Map<?,?> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(PUT, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Iterable<Parameter> headers, Iterable<Parameter> parameters, String charset)
    throws IOException
    {
        if(parameters==null)
            return send(PUT, getConnection(url, headers));

        byte[] data = null;
        String contentType = null;
        if(charset==null)
        {
            data = getEncodedData(parameters, DEFAULT_ENCODING);
            contentType = X_WWW_FORM_URLENCODED;
        }
        else
        {
            data = getEncodedData(parameters, charset);
            contentType = X_WWW_FORM_URLENCODED + "; charset=" + charset;
        }
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Map<?,?> headers, String contentType, byte[] data)
    throws IOException
    {
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Iterable<Parameter> headers, String contentType, byte[] data)
    throws IOException
    {
        return sendContent(PUT, getConnection(url, headers), contentType, data);
    }

    public Response doPUT(String url, Map<?,?> headers, String contentType,
            InputStreamReader reader) throws IOException
    {
        return sendContent(PUT, getConnection(url, headers), contentType, reader);
    }

    public Response doPUT(String url, Iterable<Parameter> headers, String contentType,
            InputStreamReader reader) throws IOException
    {
        return sendContent(PUT, getConnection(url, headers), contentType, reader);
    }

    Response sendContent(String method, HttpURLConnection connection,
            String contentType, byte[] data) throws IOException
    {
        connection.setRequestMethod(method);
        connection.setRequestProperty(CONTENT_TYPE_HEADER, contentType);
        connection.setRequestProperty(CONTENT_LENGTH_HEADER, String.valueOf(data.length));
        connection.setConnectTimeout(_connectTimeout);
        connection.setInstanceFollowRedirects(_followRedirects);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStream out = null;
        try
        {
            out = connection.getOutputStream();
            out.write(data);
        }
        finally
        {
            if(out!=null)
                out.close();
        }
        return new HttpURLConnectionWrapper(connection);
    }

    Response sendContent(String method, HttpURLConnection connection, String contentType,
            InputStreamReader reader) throws IOException
    {
        connection.setRequestMethod(method);
        connection.setRequestProperty(CONTENT_TYPE_HEADER, contentType);
        connection.setConnectTimeout(_connectTimeout);
        connection.setInstanceFollowRedirects(_followRedirects);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStreamWriter out = null;
        try
        {
            out = new OutputStreamWriter(connection.getOutputStream(), reader.getEncoding());
            char[] buf = new char[_bufferSize];
            for(int len=0; (len=reader.read(buf))!=-1;)
                out.write(buf, 0, len);
        }
        finally
        {
            if(out!=null)
                out.close();
        }
        return new HttpURLConnectionWrapper(connection);
    }

    static final class HttpURLConnectionWrapper implements Response
    {
        private final HttpURLConnection _connection;

        HttpURLConnectionWrapper(HttpURLConnection connection)
        {
            _connection = connection;
        }

        public void close() throws IOException
        {
            _connection.disconnect();
        }

        public String getHeader(String name)
        {
            return _connection.getHeaderField(name);
        }

        public InputStream getInputStream() throws IOException
        {
            return _connection.getInputStream();
        }

        public int getStatus()
        {
            try
            {
                return _connection.getResponseCode();
            }
            catch(IOException e)
            {
                // TODO throw exception?
                e.printStackTrace();
                return 404;
            }
        }
    }

}


text:
export default class GalleryCtrl {

    constructor(petService, $location) {
        "ngInject";
        this.petService = petService;
        this.location = $location;
    }

    activate() {
        this.pets = this.petService.query();
        this.searchCriteria = {
            $: "",
            race: ""
        };
        this.selectedPet = null;
    }

    selectPet($event, newPet) {
        this.selectedPet = newPet;
        $event.stopPropagation();
    }

    deselectPet() {
        this.selectedPet = null;
    }

    setupDate() {
        this.location.path(`/pets/${this.selectedPet.id}`);
    }
}