text:
package org.codegist.crest.io.http;

import org.codegist.crest.config.MethodConfig;
import org.codegist.crest.config.ParamConfig;
import org.codegist.crest.config.ParamType;
import org.codegist.crest.io.Request;
import org.codegist.crest.io.RequestBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.ArrayList;
import java.util.Arrays;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author laurent.gilles@codegist.org
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(ParamType.class)
public class HttpRequestBuilderFactoryTest {

    private final RequestBuilder toTest = new HttpRequestBuilderFactory().create();

    @Test
    public void addParamsValueShouldAddParam(){
        for(ParamType type : ParamType.values()){
            addParamValueShouldAddParam(type);
        }
    }

    @Test
    public void addParamValueWithNoValueShouldAddParamWithDefaultValue(){
        for(ParamType type : ParamType.values()){
            addParamValueWithNoValueShouldAddParamWithDefaultValue(type);
        }
    }

    @Test
    public void addParamsValueWithNoValueShouldAddParamsWithDefaultValue(){
        for(ParamType type : ParamType.values()){
            addParamsValueWithNoValueShouldAddParamsWithDefaultValue(type);
        }
    }

    private void addParamsValueWithNoValueShouldAddParamsWithDefaultValue(ParamType type){
        MethodConfig mockMethodConfig = mock(MethodConfig.class);
        ParamConfig paramConfig1 = mock(ParamConfig.class);
        when(paramConfig1.getType()).thenReturn(type);
        when(paramConfig1.getDefaultValue()).thenReturn("def1");
        ParamConfig paramConfig2 = mock(ParamConfig.class);
        when(paramConfig2.getType()).thenReturn(type);
        when(paramConfig2.getDefaultValue()).thenReturn("def2");
        ParamConfig paramConfig3 = mock(ParamConfig.class);
        when(paramConfig3.getType()).thenReturn(type);
        when(paramConfig3.getDefaultValue()).thenReturn("def3");

        assertSame(toTest, toTest.addParams(new ParamConfig[]{paramConfig1,paramConfig2,paramConfig3}));

        Request actual = toTest.build(mockMethodConfig);
        assertSame(mockMethodConfig, actual.getMethodConfig());
        assertEquals(3, actual.getParams(type).size());

        assertEquals(paramConfig1, actual.getParams(type).get(0).getParamConfig());
        assertEquals(1, actual.getParams(type).get(0).getValue().size());
        assertEquals("def1", actual.getParams(type).get(0).getValue().iterator().next());

        assertEquals(paramConfig2, actual.getParams(type).get(1).getParamConfig());
        assertEquals(1, actual.getParams(type).get(1).getValue().size());
        assertEquals("def2", new ArrayList(actual.getParams(type).get(1).getValue()).get(0));

        assertEquals(paramConfig3, actual.getParams(type).get(2).getParamConfig());
        assertEquals(1, actual.getParams(type).get(2).getValue().size());
        assertEquals("def3", new ArrayList(actual.getParams(type).get(2).getValue()).get(0));
    }

    private void addParamValueWithNoValueShouldAddParamWithDefaultValue(ParamType type){
        MethodConfig mockMethodConfig = mock(MethodConfig.class);
        ParamConfig paramConfig1 = mock(ParamConfig.class);
        when(paramConfig1.getType()).thenReturn(type);
        when(paramConfig1.getDefaultValue()).thenReturn("def1");

        assertSame(toTest, toTest.addParam(paramConfig1));

        Request actual = toTest.build(mockMethodConfig);
        assertSame(mockMethodConfig, actual.getMethodConfig());
        assertEquals(1, actual.getParams(type).size());

        assertEquals(paramConfig1, actual.getParams(type).get(0).getParamConfig());
        assertEquals(1, actual.getParams(type).get(0).getValue().size());
        assertEquals("def1", actual.getParams(type).get(0).getValue().iterator().next());
    }

    private void addParamValueShouldAddParam(ParamType type){
        MethodConfig mockMethodConfig = mock(MethodConfig.class);
        ParamConfig paramConfig1 = mock(ParamConfig.class);
        when(paramConfig1.getType()).thenReturn(type);
        ParamConfig paramConfig2 = mock(ParamConfig.class);
        when(paramConfig2.getType()).thenReturn(type);

        assertSame(toTest, toTest.addParam(paramConfig1, Arrays.<Object>asList("value")));
        assertSame(toTest, toTest.addParam(paramConfig2, Arrays.<Object>asList("value1","value2")));

        Request actual = toTest.build(mockMethodConfig);
        assertSame(mockMethodConfig, actual.getMethodConfig());
        assertEquals(2, actual.getParams(type).size());

        assertEquals(paramConfig1, actual.getParams(type).get(0).getParamConfig());
        assertEquals(1, actual.getParams(type).get(0).getValue().size());
        assertEquals("value", actual.getParams(type).get(0).getValue().iterator().next());

        assertEquals(paramConfig2, actual.getParams(type).get(1).getParamConfig());
        assertEquals(2, actual.getParams(type).get(1).getValue().size());
        assertEquals("value1", new ArrayList(actual.getParams(type).get(1).getValue()).get(0));
        assertEquals("value2", new ArrayList(actual.getParams(type).get(1).getValue()).get(1));

    }

}


text:
'''
test_k4atypes.py

Tests for the k4a types and enums.

Copyright (C) Microsoft Corporation. All rights reserved.
'''

import ctypes
from threading import Lock

import k4a

# Save capture to reuse in tests since it takes a while to get a capture from the device.
glb_capture = None
glb_color_format = None
glb_color_resolution = None
glb_depth_mode = None
glb_lock = Lock()

# Use for logging callback. But it doesn't work right now...
def glb_print_message(context:ctypes.c_void_p,
                      level:k4a.ELogLevel,
                      src_file:ctypes.POINTER(ctypes.c_char),
                      src_line:ctypes.c_int,
                      message:ctypes.POINTER(ctypes.c_char)):
    print(str(level) + " in " + str(src_file) + " at line " + str(src_line) + ": " + str(message))

# Used to get a capture from device, or a previously-captured capture.
def get_capture(device_handle:k4a._bindings.k4atypes._DeviceHandle,
                color_format:k4a.EImageFormat,
                color_resolution:k4a.EColorResolution,
                depth_mode:k4a.EDepthMode)->k4a._bindings.k4atypes._CaptureHandle:

    global glb_capture
    global glb_color_format
    global glb_color_resolution
    global glb_depth_mode

    capture = glb_capture

    if (capture is None or
        glb_color_format != color_format or
        glb_color_resolution != color_resolution or
        glb_depth_mode != depth_mode):

        # Release any previous captures.
        if (capture is not None):
            k4a._bindings.k4a.k4a_capture_release(capture)
            capture = None

        # Start the cameras.
        device_config = k4a.DeviceConfiguration()
        device_config.color_format = color_format
        device_config.color_resolution = color_resolution
        device_config.depth_mode = depth_mode
        device_config.camera_fps = k4a.EFramesPerSecond.FPS_15
        device_config.synchronized_images_only = True
        device_config.depth_delay_off_color_usec = 0
        device_config.wired_sync_mode = k4a.EWiredSyncMode.STANDALONE
        device_config.subordinate_delay_off_master_usec = 0
        device_config.disable_streaming_indicator = False

        status = k4a._bindings.k4a.k4a_device_start_cameras(device_handle, ctypes.byref(device_config))
        if(k4a.K4A_SUCCEEDED(status)):

            # Get a capture. Ignore the retured status.
            capture = k4a._bindings.k4a._CaptureHandle()
            timeout_ms = ctypes.c_int32(1000)
            status = k4a._bindings.k4a.k4a_device_get_capture(
                device_handle,
                ctypes.byref(capture),
                timeout_ms
            )

        # Stop the cameras.
        k4a._bindings.k4a.k4a_device_stop_cameras(device_handle)

        glb_capture = capture
        glb_color_format = color_format
        glb_color_resolution = color_resolution
        glb_depth_mode = depth_mode

    return capture

redpajama_set_name: RedPajamaGithub


text:
var temp_gcp_status = false;
var from_templl;
var to_templl;
var warped_layer; //the warped wms layer
var to_layer_switcher;
var navig;
var navigFrom;
var to_vectors;
var from_vectors;
var active_to_vectors;
var active_from_vectors;

if(typeof maps === 'undefined'){
	var maps = {};
}

maps['warp'] = {};
maps['from_map'] = {};
maps['to_map'] = {};

maps['from_map'].keyboard = new OpenLayers.Control.KeyboardDefaults({ observeElement: 'map' });
maps['to_map'].keyboard = new OpenLayers.Control.KeyboardDefaults({ observeElement: 'map' });

maps['from_map'].newZoom = null;
maps['from_map'].oldZoom = null;
maps['from_map'].resolutions = [0.12, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5, 6, 7, 8.5, 10, 14, 18]

maps['to_map'].newZoom = null;
maps['to_map'].oldZoom = null;
maps['to_map'].resolutions = [0.12, 0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5, 6, 7, 8.5, 10, 14, 18]

maps['warp'].active = false;
maps['warp'].deactivate = function(){
  //console.log('warp deactivate');
  maps['from_map'].keyboard.deactivate();
  maps['to_map'].keyboard.deactivate();

  maps['from_map'].active = false;
  maps['to_map'].active = false;
  maps['warp'].active = false;
}
maps['warp'].activate = function(){
  //console.log('warp activate');

  maps['from_map'].keyboard.activate();
  maps['to_map'].keyboard.activate();

  maps['from_map'].active = true;
  maps['to_map'].active = true;
  maps['warp'].active = true;
  warp_updateSize();
  currentMaps = ['from_map', 'to_map'];
}

///////////////////////////////////////////////////////////////////////////////////////////
//
// INIT
//
///////////////////////////////////////////////////////////////////////////////////////////
function init() {

  from_map = new OpenLayers.Map('from_map', {
    controls: [new OpenLayers.Control.PanZoomBar(), maps['from_map'].keyboard],
    maxExtent: new OpenLayers.Bounds(0, 0, image_width, image_height),
    resolutions: maps['from_map'].resolutions
  });

  maps['from_map'].map = from_map;

  var image = new OpenLayers.Layer.WMS(title,
          wms_url, {
            format: 'image/png',
            status: 'unwarped'},
  {
    transitionEffect: 'resize'
  });

  from_map.addLayer(image);

  if (!from_map.getCenter()) {
    from_map.zoomToMaxExtent();
  }

  OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
  OpenLayers.Util.onImageLoadErrorColor = "transparent";

  to_layer_switcher = new OpenLayers.Control.LayerSwitcher();
  var options = {
    projection: new OpenLayers.Projection("EPSG:900913"),
    displayProjection: new OpenLayers.Projection("EPSG:4326"),
    units: "m",
    numZoomLevels: 22,
    maxResolution: 156543.0339,
    maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34),
    controls: [new OpenLayers.Control.Attribution(), to_layer_switcher, new OpenLayers.Control.PanZoomBar()]
  };

  to_map = new OpenLayers.Map('to_map', options);
  maps['to_map'].map = to_map;

  warped_layer = new OpenLayers.Layer.WMS.Untiled("warped map", wms_url, {
    format: 'image/png',
    status: 'warped'},
  {TRANSPARENT: 'true', reproject: 'true'},
  {gutter: 15, buffer: 0},
  {projection: "epsg:4326", units: "m"}
  );

  var warpedOpacity = 0.6;
  warped_layer.setOpacity(warpedOpacity);
  warped_layer.setVisibility(false);
  warped_layer.setIsBaseLayer(false);
  to_map.addLayer(warped_layer);

  to_map.addLayer(mapnik);

  for (var i = 0; i < layers_array.length; i++) {
    to_map.addLayer(get_map_layer(layers_array[i]));
  }

  ny_2014.setVisibility(false);
  to_map.addLayer(ny_2014);

  if (map_has_bounds) {
    map_bounds_merc = new OpenLayers.Bounds();
    map_bounds_merc = lonLatToMercatorBounds(map_bounds);

    to_map.zoomToExtent(map_bounds_merc);

  } else {
    //set to the world
    to_map.setCenter(lonLatToMercator(new OpenLayers.LonLat(0.0, 0.0)), 10);
  }

  //style for the active, temporary vector marker, the one the user actually adds themselves,
  var active_style = OpenLayers.Util.extend({},
          OpenLayers.Feature.Vector.style['default']);
  active_style.graphicOpacity = 1;
  active_style.graphicWidth = 14;
  active_style.graphicHeight = 22;
  active_style.graphicXOffset = -(active_style.graphicWidth / 2);
  active_style.graphicYOffset = -active_style.graphicHeight;
  active_style.externalGraphic = icon_imgPath + "AQUA.png";

  to_vectors = new OpenLayers.Layer.Vector("To vector markers");
  to_vectors.displayInLayerSwitcher = false;

  from_vectors = new OpenLayers.Layer.Vector("From vector markers");
  from_vectors.displayInLayerSwitcher = false;

  active_to_vectors = new OpenLayers.Layer.Vector("active To vector markers", {style: active_style});
  active_to_vectors.displayInLayerSwitcher = false;

  active_from_vectors = new OpenLayers.Layer.Vector("active from vector markers", {style: active_style});
  active_from_vectors.displayInLayerSwitcher = false;

  to_map.addLayers([to_vectors, active_to_vectors]);
  from_map.addLayers([from_vectors, active_from_vectors]);
  //fix for dragging bug
  //  OpenLayers.Control.DragFeature.prototype.upFeature = function() {};
  //fix
  var to_panel = new OpenLayers.Control.Panel(
          {displayClass: 'olControlEditingToolbar'}
  );
  var dragMarker = new OpenLayers.Control.DragFeature(to_vectors,
          {displayClass: 'olControlDragFeature', title: 'Drag Control Point (d)'});
  dragMarker.onComplete = function(feature) {
    saveDraggedMarker(feature);
  };

  var drawFeatureTo = new OpenLayers.Control.DrawFeature(active_to_vectors, OpenLayers.Handler.Point,
          {displayClass: 'olControlDrawFeaturePoint', title: 'Add Control Point (p)', handlerOptions: {style: active_style}});
  drawFeatureTo.featureAdded = function(feature) {
    newaddGCPto(feature);
  };

  var drawFeatureFrom = new OpenLayers.Control.DrawFeature(active_from_vectors, OpenLayers.Handler.Point,
          {displayClass: 'olControlDrawFeaturePoint', title: 'Add Control Point (p)', handlerOptions: {style: active_style}});
  drawFeatureFrom.featureAdded = function(feature) {
    newaddGCPfrom(feature);
  };

  var from_panel = new OpenLayers.Control.Panel(
          {displayClass: 'olControlEditingToolbar'}
  );
  var dragMarkerFrom = new OpenLayers.Control.DragFeature(from_vectors,
          {displayClass: 'olControlDragFeature', title: 'Drag Control Point (d)'});
  dragMarkerFrom.onComplete = function(feature) {
    saveDraggedMarker(feature);
  };

  navig = new OpenLayers.Control.Navigation({title: "Move Around Map (m)", zoomWheelEnabled: true});
  navigFrom = new OpenLayers.Control.Navigation({title: "Move Around Map (m)", zoomWheelEnabled: true});

  to_panel.addControls([navig, dragMarker, drawFeatureTo]);
  to_map.addControl(to_panel);

  from_panel.addControls([navigFrom, dragMarkerFrom, drawFeatureFrom]);
  from_map.addControl(from_panel);

  //we'll add generic navigation controls so we can zoom whilst addingd
  to_map.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled: true}));
  from_map.addControl(new OpenLayers.Control.Navigation({zoomWheelEnabled: true}));

  navig.activate();
  navigFrom.activate();

  joinControls(dragMarker, dragMarkerFrom);
  joinControls(navig, navigFrom);
  joinControls(drawFeatureTo, drawFeatureFrom);

  // keyboard shortcuts for switching tools
  var keyboardControl = new OpenLayers.Control();
  var control = new OpenLayers.Control();
  var callbacks = { keydown: function(evt) {
    //console.log("You pressed a key: " + evt.keyCode);
    if (maps['warp'].active){
      switch(evt.keyCode) {
      	  case 65: // a
      	  	toggleWarpMap('from_map');
      	  	break;
      	  case 90: // z
      	  	toggleWarpMap('to_map');
      	  	break;
          case 80: // p
              switchTool('pin');
              break;
          case 68: // d
              switchTool('drag');
              break;
          case 77: // m
              switchTool('move');
              break;

          default:
            //console.log('default')
        }
      }
    }
  };

  var options = {};
  var handler = new OpenLayers.Handler.Keyboard(control, callbacks, options);

  handler.activate();
  to_map.addControl(keyboardControl);
  to_map.addControl(maps['to_map'].keyboard);

  function switchTool(newTool){
    // first deactivate everything
    from_map.controls[2].deactivate();
    from_map.controls[3].deactivate();
    from_map.controls[4].deactivate();

    switch(newTool) {
        case 'pin':
            from_map.controls[4].activate();
            break;
        case 'drag':
            from_map.controls[3].activate();
            break;
        case 'move':
            from_map.controls[2].activate();
            break;
        default:
          //console.log('switchTool ' + newTool + ' not matched');
    }
  }

    to_map.events.register("zoomend", to_map, function(){
        //console.log('zoomend -- to_map.zoom: ' + to_map.zoom + ' newZoom: ' + newZoom);
        if (to_map.zoom < maps['to_map'].newZoom){
          //console.log('adding .5 to accommediate for the math.floor -- to_map.zoom: ' + to_map.zoom + ' newZoom: ' + newZoom);
          maps['to_map'].newZoom = to_map.zoom + 0.5;
        } else {
          maps['to_map'].newZoom = to_map.zoom;
        }
    });

    from_map.events.register("zoomend", from_map, function(){
        //console.log('zoomend -- from_map.zoom: ' + from_map.zoom + ' newZoom: ' + newZoom);
        if (from_map.zoom < maps['from_map'].newZoom){
          //console.log('adding .5 to accommediate for the math.floor -- from_map.zoom: ' + from_map.zoom + ' newZoom: ' + newZoom);
          maps['from_map'].newZoom = from_map.zoom + 0.5;
        } else {
          maps['from_map'].newZoom = from_map.zoom;
        }
    });

  //set up jquery slider for warped layer
  jQuery("#warped-slider").slider({
    value: 100 * warpedOpacity,
    range: "min",
    slide: function(e, ui) {
      warped_layer.setOpacity(ui.value / 100);
    }
  });
  jQuery("#warped-slider").hide();
  warped_layer.events.register('visibilitychanged', this, function(layer) {
    if (layer.object.getVisibility() === true) {
      jQuery("#warped-slider").show();
    } else {
      jQuery("#warped-slider").hide();
    }
  });

	 /*
	  // switch between maps based upon zoom level
	  to_map.events.register("zoomend", mapnik, function () {
	    if (this.map.getZoom() > 18 && this.visibility == true) {
	      this.map.setBaseLayer(ny_2014);
	    }
	  });

	   to_map.events.register("zoomend", ny_2014, function () {
	    if (this.map.getZoom() < 15 && this.visibility == true) {
	      this.map.setBaseLayer(mapnik);
	    }
	  });
	*/

  // setup resize
  window.addEventListener("resize", warp_updateSize);
  warp_updateSize();
  from_map.zoomToMaxExtent();

} // end init

  function toggleWarpMap(mapName){

  	if (typeof maps['from_map'] != 'undefined' && typeof maps['to_map'] != 'undefined'){

  		if (maps[mapName].active){
  			maps[mapName].active = false;
  			maps[mapName].keyboard.deactivate();

  			// remove map from control array
	  		var newMaps = [];
	  		for (var i = 0; i < currentMaps.length; i++) {
	  			if (currentMaps[i] != mapName){
	  				newMaps.push(currentMaps[i]);
	  			}
	  		};
	  		currentMaps = newMaps;

  		} else {
  			maps[mapName].active = true;
  			maps[mapName].keyboard.activate();

  			// add map from control array if not present
	  		var matched = false;
	  		for (var i = 0; i < currentMaps.length; i++) {
	  			if (currentMaps[i] === mapName){
	  				matched = true;
	  			}
	  		};

	  		if (matched === false){
	  			currentMaps.push(mapName);
	  		}
  		}

  		console.log(mapName + ".active is now " + maps[mapName].active );

  		// check if both have been deactivated in which case reactive both
  		// because deactivating both maps will appear to be a bug
  		if (!maps['from_map'].active && !maps['to_map'].active){
  			console.log('automatically reenabling both maps when both have been disabled')
  			maps['from_map'].keyboard.activate();
  			maps['from_map'].active = true;
  			maps['to_map'].keyboard.activate();
  			maps['to_map'].active = true;
  			currentMaps = ['from_map', 'to_map'];
  		}
  	}

  }

  function enableWarpMap(mapName){
  	//console.log('enableWarpMap: ' + mapName);

  	if (typeof maps['from_map'] != 'undefined' && typeof maps['to_map'] != 'undefined'){

  		if (mapName === 'from_map'){
  			maps['from_map'].active = true;
  			maps['from_map'].keyboard.activate();

  			maps['to_map'].active = false;
  			maps['to_map'].keyboard.deactivate();

  			currentMaps = ['from_map']
  		} else if (mapName === 'to_map'){
  			maps['from_map'].active = false;
  			maps['from_map'].keyboard.deactivate();

  			maps['to_map'].active = true;
  			maps['to_map'].keyboard.activate();

  			currentMaps = ['to_map']
  		} else if (mapName === 'both'){
  			maps['from_map'].active = true;
  			maps['from_map'].keyboard.activate();

  			maps['to_map'].active = true;
  			maps['to_map'].keyboard.activate();

  			currentMaps = ['to_map', 'from_map'];
  		}

  	}

  }

function joinControls(first, second) {
  first.events.register("activate", first, function() {
    second.activate();
  });
  first.events.register("deactivate", first, function() {
    second.deactivate();
  });
  second.events.register("activate", second, function() {
    first.activate();
  });
  second.events.register("deactivate", second, function() {
    first.deactivate();
  });
}

function get_map_layer(layerid) {
  var newlayer_url = layer_baseurl + "/" + layerid;
  var map_layer = new OpenLayers.Layer.WMS
          ("Layer " + layerid,
                  newlayer_url,
                  {format: 'image/png'},
          {TRANSPARENT: 'true', reproject: 'true'},
          {gutter: 15, buffer: 0},
          {projection: "epsg:4326", units: "m"}
          );
  map_layer.setIsBaseLayer(false);
  map_layer.visibility = false;

  return map_layer;
}

var moving = false;
var origXYZ = new Object();

function moveStart(mapEvent) {
  var passiveMap;
  var activeMap;
  if (this == 1) {
    activeMap = from_map;
    passiveMap = to_map;
  } else {
    activeMap = to_map;
    passiveMap = from_map;
  }
  var cent = activeMap.getCenter();
  origXYZ.lonlat = cent;
  origXYZ.zoom = activeMap.zoom;
}

function moveEnd(mapEvent) {
  if (moving) {
    return;
  }
  moving = true;
  var passiveMap;
  var activeMap;
  if (this == 1) {
    activeMap = from_map;
    passiveMap = to_map;
  } else {
    activeMap = to_map;
    passiveMap = from_map;
  }
  var newZoom = passiveMap.zoom;
  if (origXYZ.zoom != activeMap.zoom) {
    diffzoom = origXYZ.zoom - activeMap.zoom;
    newZoom = passiveMap.zoom - diffzoom;
  }
  var origPixel = activeMap.getPixelFromLonLat(origXYZ.lonlat);
  var newPixel = activeMap.getPixelFromLonLat(activeMap.getCenter());
  var difx = origPixel.x - newPixel.x;
  var dify = origPixel.y - newPixel.y;
  var passCen = passiveMap.getPixelFromLonLat(passiveMap.getCenter());
  passiveMap.setCenter(passiveMap.getLonLatFromPixel(
          new OpenLayers.Pixel(passCen.x - difx, passCen.y - dify)), newZoom, false, false);

  moving = false;

}
var mapLinked = false;
function toggleJoinLinks() {
  //TODO change the icon
  if (mapLinked === true) {
    mapLinked = false;
    document.getElementById('link-map-button').className = 'link-map-button-off';
  } else {
    mapLinked = true;
    document.getElementById('link-map-button').className = 'link-map-button-on';
  }
  if (mapLinked === true) {
    from_map.events.register("moveend", 1, moveEnd);
    to_map.events.register("moveend", 0, moveEnd);
    from_map.events.register("movestart", 1, moveStart);
    to_map.events.register("movestart", 0, moveStart);
  } else {
    from_map.events.unregister("moveend", 1, moveEnd);
    to_map.events.unregister("moveend", 0, moveEnd);
    from_map.events.unregister("movestart", 1, moveStart);
    to_map.events.unregister("movestart", 0, moveStart);
  }
}

function gcp_notice(text) {
  //jquery effect
  jqHighlight('rectifyNotice');
  notice = document.getElementById('gcp_notice');
  notice.innerHTML = text;
}

function update_gcp_field(gcp_id, elem) {
  var id = gcp_id;
  var value = elem.value;
  var attrib = elem.id.substring(0, (elem.id.length - (id + "").length));
  var url = gcp_update_field_url + "/" + id;

  jQuery('#spinner').show();
  gcp_notice('Updating...');

  var request = jQuery.ajax({
    type: "PUT",
    url: url,
    data: {authenticity_token: encodeURIComponent(window._token), attribute: attrib, value: value}}
  ).success(function() {
    gcp_notice("Control Point updated!");
    move_map_markers(gcp_id, elem);
  }).done(function() {
    jQuery('#spinner').hide();
  }).fail(function() {
    gcp_notice("Had trouble updating that point with the server. Try again?");
    elem.value = value;
  });
}

function update_gcp(gcp_id, listele) {
  var id = gcp_id;
  var url = gcp_update_url + "/" + id;

  for (i = 0; i < listele.childNodes.length; i++) {
    listtd = listele.childNodes[i]; //td
    for (e = 0; e < listtd.childNodes.length; e++) {

      listItem = listtd.childNodes[e];//input
      if (listItem.id == "x" + gcp_id) {
        x = listItem.value;
      }
      if (listItem.id == "y" + gcp_id) {
        y = listItem.value;
      }
      if (listItem.id == "lon" + gcp_id) {
        lon = listItem.value;
      }
      if (listItem.id == "lat" + gcp_id) {
        lat = listItem.value;
      }

    }
  }
  gcp_notice('Updating...');
  jQuery('#spinner').show();

  var request = jQuery.ajax({
    type: "PUT",
    url: url,
    data: {authenticity_token: encodeURIComponent(window._token), x: x, y: y, lon: lon, lat: lat}}
  ).success(function() {
    gcp_notice("Control Point updated!");
  }).done(function() {
    jQuery('#spinner').hide();
  }).fail(function() {
    gcp_notice("Had trouble updating that point with the server. Try again?");
    elem.value = value;
  });

}

function move_map_markers(gcp_id, elem) {
  var avalue = elem.value;
  var attrib = elem.id;
  trele = elem.parentNode.parentNode; //input>td>tr
  //get the other siblings next door to this one.
  for (i = 0; i < trele.childNodes.length; i++) {
    trchild = trele.childNodes[i]; //tds
    for (e = 0; e < trchild.childNodes.length; e++) {

      inp = trchild.childNodes[e]; //inputs
      if (inp.id == 'x' + gcp_id) {
        x = inp.value;
      }
      if (inp.id == 'y' + gcp_id) {
        y = image_height - inp.value;
      }
      if (inp.id == 'lon' + gcp_id) {
        tlon = inp.value;
      }
      if (inp.id == 'lat' + gcp_id) {
        tlat = inp.value;
      }
    }
  }

  if (attrib == 'x' + gcp_id || attrib == 'y' + gcp_id) {
    var frommark;
    for (var a = 0; a < from_vectors.features.length; a++) {
      if (from_vectors.features[a].gcp_id == gcp_id) {
        frommark = from_vectors.features[a];
      }//if
    } //for
    if (attrib == 'x' + gcp_id) {
      x = avalue;
    }
    if (attrib == 'y' + gcp_id) {
      y = image_height - avalue;
    }
    //frommark.geometry.move(new OpenLayers.LonLat(x, y));
    frommark.geometry.x = x;
    frommark.geometry.y = y;
    frommark.geometry.clearBounds();
    frommark.layer.drawFeature(frommark);
  }

  else if (attrib == 'lon' + gcp_id || attrib == 'lat' + gcp_id) {
    var tomark;
    for (var b = 0; b < to_vectors.features.length; b++) {
      if (to_vectors.features[b].gcp_id == gcp_id) {
        tomark = to_vectors.features[b];
      } //if
    }//for
    if (attrib == 'lon' + gcp_id) {
      tlon = avalue;
    }
    if (attrib == 'lat' + gcp_id) {
      tlat = avalue;
    }

    hacklonlat = lonLatToMercator(new OpenLayers.LonLat(tlon, tlat));
    tomark.geometry.x = hacklonlat.lon;
    tomark.geometry.y = hacklonlat.lat;
    tomark.geometry.clearBounds();
    tomark.layer.drawFeature(tomark);
  }
}

//when a vector marker is dragged, update values on form and save
function saveDraggedMarker(feature) {

  var listele = document.getElementById("gcp" + feature.gcp_id); //listele is a tr
  for (i = 0; i < listele.childNodes.length; i++) {
    listtd = listele.childNodes[i];//listtd is a td

    for (e = 0; e < listtd.childNodes.length; e++) {
      listItem = listtd.childNodes[e]; //listitem is the input field

      if (feature.layer == from_vectors) {
        if (listItem.id == "x" + feature.gcp_id) {
          listItem.value = feature.geometry.x;
        }
        if (listItem.id == "y" + feature.gcp_id) {
          listItem.value = image_height - feature.geometry.y;
        }
      }
      if (feature.layer == to_vectors) {
        var merc = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
        var vll = mercatorToLonLat(merc);
        if (listItem.id == "lon" + feature.gcp_id) {
          listItem.value = vll.lon;
        }
        if (listItem.id == "lat" + feature.gcp_id) {
          listItem.value = vll.lat;
        }
      }
    }//for
  }//for
  update_gcp(feature.gcp_id, listele);
}

function save_new_gcp(x, y, lon, lat) {

  url = gcp_add_url;
  gcp_notice("Adding...");
  jQuery('#spinner').show();

  var request = jQuery.ajax({
    type: "POST",
    url: url,
    data: {authenticity_token: encodeURIComponent(window._token), x: x, y: y, lat: lat, lon: lon}}
  ).done(function() {
    update_row_numbers();
    jQuery('#spinner').hide();
  }).fail(function() {
    gcp_notice("Had trouble saving that point to the server. Try again?");
  });

}

function update_rms(new_rms) {
  fi = document.getElementById('errortitle');
  fi.value = "Error(" + new_rms + ")";
}

function delete_markers(gcp_id) {
  for (var a = 0; a < from_vectors.features.length; a++) {

    if (from_vectors.features[a].gcp_id == gcp_id) {

      del_from_mark = from_vectors.features[a];
      del_to_mark = to_vectors.features[a];

      from_vectors.destroyFeatures([del_from_mark]);
      to_vectors.destroyFeatures([del_to_mark]);
    }
  }
  update_row_numbers();
}

//called after initial populate, each delete, and each add
function update_row_numbers() {
  for (var a = 0; a < from_vectors.features.length; a++) {
    temp_marker = from_vectors.features[a];
    li_ele = document.getElementById("gcp" + temp_marker.gcp_id);

    ////////////////
    inputs = li_ele.getElementsByTagName("input");
    for (var b = 0; b < inputs.length; b++) {
      if (inputs[b].name == "error" + temp_marker.gcp_id) {
        error = inputs[b].value;
      }
    }
    var color = getColorString(error);
    updateGcpColor(from_vectors.features[a], color);
    updateGcpColor(to_vectors.features[a], color);
    ////////////

    span_ele = li_ele.getElementsByTagName("span");
    if (span_ele[0].className == "marker_number") {
      var thishtml = "<img src='" + icon_imgPath + (temp_marker.id_index + 1) + color + ".png' />";
      span_ele[0].innerHTML = thishtml;
    }

    if (span_ele[1] != undefined && span_ele[1].className == "ui-button-text") {
      var thishtml = "delete point " + (temp_marker.id_index + 1) + "";
      span_ele[1].innerHTML = thishtml;
    }

    jQuery('.marker_number').click(function(){
      var markerID = jQuery(this).parent().find('input').val();
      centerOnMarker(markerID);
    })

  }
  redrawGcpLayers();
}

function redrawGcpLayers() {
  from_vectors.redraw();
  to_vectors.redraw();
}

function updateGcpColor(marker, color) {
  marker.style.externalGraphic = icon_imgPath + (marker.id_index + 1) + color + '.png';
}

//blue, green, orange, red
function getColorString(error) {
  var colorString = "";
  if (error < 5) {
    colorString = "";
  } else if (error >= 5 && error < 10) {
    colorString = "_green";
  } else if (error >= 10 && error < 50) {
    colorString = "_orange";
  } else if (error >= 50) {
    colorString = "_red";
  }
  //TODO
  return colorString;
  //return "";
}

function populate_gcps(gcp_id, img_lon, img_lat, dest_lon, dest_lat, error) {
  //console.log('populate_gcps: ' + gcp_id);
  error = typeof (error) != "undefined" ? error : 0;
  var color = getColorString(error);

  //x y lon lat
  index = gcp_markers.length;
  gcp_markers.push(index); // 0 to 7 or so
  got_lon = img_lon;
  got_lat = image_height - img_lat;
  add_gcp_marker(from_vectors, new OpenLayers.LonLat(got_lon, got_lat), false, index, gcp_id, color);

  add_gcp_marker(to_vectors, lonLatToMercator(new OpenLayers.LonLat(dest_lon, dest_lat)), false, index, gcp_id, color);
}

function set_gcp() {
  check_if_gcp_ready();
  if (!temp_gcp_status) {
    alert("You have to add a new control point on each map before pressing this button.");
    return false;
  } else {
    var from_lonlat = from_templl;
    var to_lonlat = mercatorToLonLat(to_templl);

    var img_lon = from_lonlat.lon;
    var img_lat = from_lonlat.lat;

    var proper_img_lat = image_height - img_lat;
    var proper_img_lon = img_lon;
    console.log('proper_img_lon: ' + proper_img_lon + ' proper_img_lat: ' + proper_img_lat);

    save_new_gcp(proper_img_lon, proper_img_lat, to_lonlat.lon, to_lonlat.lat);

    active_from_vectors.destroyFeatures();
    active_to_vectors.destroyFeatures();
  }
}

function add_gcp_marker(markers_layer, lonlat, is_active_marker, id_index, gcp_id, color) {
  color = typeof (color) != "undefined" ? color : "";
  id_index = typeof (id_index) != 'undefined' ? id_index : -2;
  var style_mark = OpenLayers.Util.extend({},
          OpenLayers.Feature.Vector.style['default']);
  style_mark.graphicOpacity = 1;
  style_mark.graphicWidth = 14;
  style_mark.graphicHeight = 22;
  style_mark.graphicXOffset = -(style_mark.graphicWidth / 2);
  style_mark.graphicYOffset = -style_mark.graphicHeight;
  if (is_active_marker === true) {
    active_style.externalGraphic = icon_imgPath + "AQUA.png";
  } else {
    style_mark.externalGraphic = icon_imgPath + (id_index + 1) + color + '.png';
  }
  var thisVector = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
  var pointFeature = new OpenLayers.Feature.Vector(thisVector, null, style_mark);
  pointFeature.id_index = id_index;
  pointFeature.gcp_id = gcp_id;

  markers_layer.addFeatures([pointFeature]);

  resetHighlighting();
}

function addLayerToDest(frm) {
  num = frm.layer_num.value;
  new_wms_url = empty_wms_url + '/' + num;

  new_warped_layer = new OpenLayers.Layer.WMS.Untiled("warped map " + num, new_wms_url, {
    format: 'image/png',
    status: 'warped'
  },
  {
    TRANSPARENT: 'true',
    reproject: 'true'
  },
  {
    gutter: 15,
    buffer: 0
  },
  {
    projection: "epsg:4326",
    units: "m"
  });
  new_warped_layer.setOpacity(0.6);
  new_warped_layer.setVisibility(true);
  new_warped_layer.setIsBaseLayer(false);
  to_map.addLayer(new_warped_layer);

  to_layer_switcher.maximizeControl();

  jQuery('#add_layer').hide();

}

function show_warped_map() {
  warped_layer.setVisibility(true);
  warped_layer.mergeNewParams({'random': Math.random()});
  warped_layer.redraw(true);
  to_layer_switcher.maximizeControl();

  //cross tab issue - reloads the rectified map in the preview tab if its there
  if (typeof warpedmap != 'undefined' && typeof warped_wmslayer != 'undefined') {
    warped_wmslayer.mergeNewParams({'random': Math.random()});
    warped_wmslayer.redraw(true);
  }
}

function check_if_gcp_ready() {
  if (active_to_vectors.features.length > 0 && active_from_vectors.features.length > 0) {
    temp_gcp_status = true;
    document.getElementById("addPointDiv").className = "addPointHighlighted";
    document.getElementById("GcpButton").disabled = false;
  } else {
    temp_gcp_status = false;
  }
}

function newaddGCPto(feat) {
  if (active_to_vectors.features.length > 1) {
    var to_destroy = new Array();
    for (var a = 0; a < active_to_vectors.features.length; a++) {
      if (active_to_vectors.features[a] != feat) {
        to_destroy.push(active_to_vectors.features[a]);
      }
    }
    active_to_vectors.destroyFeatures(to_destroy);
  }
  var lonlat = new OpenLayers.LonLat(feat.geometry.x, feat.geometry.y);
  highlight(to_map.div);

  to_templl = lonlat;
  check_if_gcp_ready();
}

function newaddGCPfrom(feat) {
  if (active_from_vectors.features.length > 1) {
    var to_destroy = new Array();
    for (var a = 0; a < active_from_vectors.features.length; a++) {
      if (active_from_vectors.features[a] != feat) {
        to_destroy.push(active_from_vectors.features[a]);
      }
    }
    active_from_vectors.destroyFeatures(to_destroy);
  }
  var lonlat = new OpenLayers.LonLat(feat.geometry.x, feat.geometry.y);
  //console.log('feat.geometry.x: ' + feat.geometry.x + ' feat.geometry.y: ' + feat.geometry.y + ' lonlat: ' + lonlat);
  highlight(from_map.div);

  from_templl = lonlat;
  check_if_gcp_ready();
}

function addLayerToDest(frm) {
  num = frm.layer_num.value;
  new_wms_url = empty_wms_url + '/' + num;

  new_warped_layer = new OpenLayers.Layer.WMS.Untiled("warped map " + num, new_wms_url,
          {format: 'image/png', status: 'warped'},
  {TRANSPARENT: 'true', reproject: 'true'},
  {gutter: 15, buffer: 0},
  {projection: "epsg:4326", units: "m"}
  );
  new_warped_layer.setOpacity(.6);
  new_warped_layer.setVisibility(true);
  new_warped_layer.setIsBaseLayer(false);
  to_map.addLayer(new_warped_layer);

  to_layer_switcher.maximizeControl();

  jQuery('#add_layer').hide();

}

function resetHighlighting() {
  to_map.div.className = "map-off";
  from_map.div.className = "map-off";
  document.getElementById("addPointDiv").className = "addPoint";
  document.getElementById("GcpButton").disabled = true;
}

function highlight(thingToHighlight) {
  thingToHighlight.className = "highlighted";
}

//TODO deprecate these transform methods to use OL's transform command
function mercatorToLonLat(merc) {
  var lon = (merc.lon / 20037508.34) * 180;
  var lat = (merc.lat / 20037508.34) * 180;

  lat = 180 / Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

  return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercator(ll) {
  var lon = ll.lon * 20037508.34 / 180;
  var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);

  lat = lat * 20037508.34 / 180;

  return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercatorBounds(llbounds) {
  var proj = new OpenLayers.Projection("EPSG:4326");
  var newbounds = llbounds.transform(proj, to_map.getProjectionObject());

  return newbounds;

}

//this function is called is a map has no gcps, and fuzzy best guess
//locations are found. This uses Yahoo's Placemaker service.
function bestGuess(guessObj) {
  jQuery("#to_map_notification").hide();
  if (guessObj["status"] == "ok" && guessObj["count"] > 0) {
    var siblingExtent = guessObj["sibling_extent"];
    zoom = 10;
    if (siblingExtent) {
      sibBounds = new OpenLayers.Bounds.fromString(siblingExtent);
      zoom = to_map.getZoomForExtent(sibBounds.transform(to_map.displayProjection, to_map.projection));
    }
    var places = guessObj["places"];
    var message = "Map zoomed to best guess: " +
            "<a href='#' onclick='centerToMap(" + places[0].lon + "," + places[0].lat + "," + zoom + ");return false;'>" + places[0].name + "</a><br />";
    centerToMap(places[0].lon, places[0].lat, zoom);

    if (places.length > 1) {
      message = message + "Other places:<br />";
      for (var i = 1; i < places.length; i++) {
        var place = places[i];
        message = message + "<a href='#' onclick='centerToMap(" + place.lon + "," + place.lat + "," + zoom + ");return false;'>" + place.name + "</a><br />"
      }
    }
    jQuery("#to_map_notification_inner").html(message);
    jQuery("#to_map_notification").show('slow');
  }

}
function centerToMap(lon, lat, zoom) {
  var newCenter = new OpenLayers.LonLat(lon, lat).transform(to_map.displayProjection, to_map.projection);
  to_map.setCenter(newCenter, zoom);
}

function centerOnMarker(markerID){
	//console.log('centerOnMarker: ' + markerID);

	var imageLon = jQuery('input#x' + markerID).val();
	var imageLat = jQuery('input#y' + markerID).val();

	var mapLon = jQuery('input#lon' + markerID).val();
	var mapLat = jQuery('input#lat' + markerID).val();

	from_map.setCenter(new OpenLayers.LonLat(imageLon,image_height - imageLat), from_map.zoom)
	to_map.setCenter(lonLatToMercator(new OpenLayers.LonLat(mapLon, mapLat)), to_map.zoom)
}

function warp_updateSize() {
  //console.log('warp_updateSize')

  var headerSpace = 255

  var minHeight = 370;
  var calculatedHeight = Number(window.innerHeight - headerSpace);

  if (calculatedHeight < minHeight){
    calculatedHeight = minHeight;
  }

  from_map.div.style.height = calculatedHeight + "px";
  from_map.div.style.width = "100%";
  from_map.updateSize();

  to_map.div.style.height = calculatedHeight + "px";
  to_map.div.style.width = "100%";
  to_map.updateSize();

  // calculate the distance from the top of the browser to the top of the tabs to set the scroll position correctly
  var ele = document.getElementById("wooTabs");
  var offsetFromTop = 0;
  while(ele){
     offsetFromTop += ele.offsetTop;
     ele = ele.offsetParent;
  }

  //window.scrollTo(0, offsetFromTop);

  /* animate the scroll position transition  */
  jQuery('html, body').clearQueue();
  jQuery('html, body').animate({
        scrollTop: offsetFromTop
    }, 500);

 setTimeout( removePlaceholderHeight, 500);
}


text:
package com.rultor.spi;

import java.util.Collections;

/**
 * Pulse.
 *
 * @author Yegor Bugayenko (yegor@teamed.io)
 * @version $Id$
 * @since 1.20
 */
public interface Pulse {

    /**
     * Empty.
     */
    Pulse EMPTY = new Pulse() {
        @Override
        public void add(final Tick tick) {
            throw new UnsupportedOperationException("#add()");
        }
        @Override
        public Iterable<Tick> ticks() {
            return Collections.emptyList();
        }
        @Override
        public Iterable<Throwable> error() {
            return Collections.emptyList();
        }
        @Override
        public void error(final Iterable<Throwable> errors) {
            throw new UnsupportedOperationException("#error()");
        }
    };

    /**
     * Add new tick.
     * @param tick The tick
     */
    void add(Tick tick);

    /**
     * Get ticks.
     * @return Ticks
     */
    Iterable<Tick> ticks();

    /**
     * Most recent exception (or empty).
     * @return Problems
     */
    Iterable<Throwable> error();

    /**
     * Set recent exception (or empty).
     * @param errors Errors or empty if none
     */
    void error(Iterable<Throwable> errors);

}


text:
#ifndef ASF_H
#define ASF_H

/*
 * This file includes all API header files for the selected drivers from ASF.
 * Note: There might be duplicate includes required by more than one driver.
 *
 * The file is automatically generated and will be re-written when
 * running the ASF driver selector tool. Any changes will be discarded.
 */

// From module: Common SAM compiler driver
#include <compiler.h>
#include <status_codes.h>

// From module: Ethernet MAC (EMAC)
#include <emac.h>

// From module: Ethernet Physical Transceiver (DM9161A)
#include <ethernet_phy.h>

// From module: FreeRTOS mini Real-Time Kernel
#include <FreeRTOS.h>
#include <StackMacros.h>
#include <croutine.h>
#include <list.h>
#include <mpu_wrappers.h>
#include <portable.h>
#include <projdefs.h>
#include <queue.h>
#include <semphr.h>
#include <task.h>
#include <timers.h>

// From module: GPIO - General purpose Input/Output
#include <gpio.h>

// From module: Generic board support
#include <board.h>

// From module: IOPORT - General purpose I/O service
#include <ioport.h>

// From module: IPv4 support in lwIP v140
#include <lwip/autoip.h>
#include <lwip/icmp.h>
#include <lwip/igmp.h>
#include <lwip/inet.h>
#include <lwip/inet_chksum.h>
#include <lwip/ip.h>
#include <lwip/ip_addr.h>
#include <lwip/ip_frag.h>

// From module: Interrupt management - SAM implementation
#include <interrupt.h>

// From module: PIO - Parallel Input/Output Controller
#include <pio.h>

// From module: PMC - Power Management Controller
#include <pmc.h>
#include <sleep.h>

// From module: Part identification macros
#include <parts.h>

// From module: RSTC - Reset Controller
#include <rstc.h>

// From module: SAM3X EK LED support enabled
#include <led.h>

// From module: SAM3X startup code
#include <exceptions.h>

// From module: Standard serial I/O (stdio) - SAM implementation
#include <stdio_serial.h>

// From module: System Clock Control - SAM3X/A implementation
#include <sysclk.h>

// From module: TC - Timer Counter
#include <tc.h>

// From module: UART - Univ. Async Rec/Trans
#include <uart.h>

// From module: USART - Serial interface - SAM implementation for devices with both UART and USART
#include <serial.h>

// From module: USART - Univ. Syn Async Rec/Trans
#include <usart.h>

// From module: lwIP TCP/IP Stack v140
#include <api.h>
#include <api_msg.h>
#include <arch.h>
#include <debug.h>
#include <def.h>
#include <dhcp.h>
#include <dns.h>
#include <err.h>
#include <init.h>
#include <mem.h>
#include <memp.h>
#include <memp_std.h>
#include <netbuf.h>
#include <netdb.h>
#include <netif.h>
#include <netifapi.h>
#include <opt.h>
#include <pbuf.h>
#include <raw.h>
#include <sio.h>
#include <snmp.h>
#include <snmp_asn1.h>
#include <snmp_msg.h>
#include <snmp_structs.h>
#include <sockets.h>
#include <stats.h>
#include <sys.h>
#include <tcp.h>
#include <tcp_impl.h>
#include <tcpip.h>
#include <timers.h>
#include <udp.h>

// From module: lwIP v140 port to FreeRTOS on SAM hardware module.
#include <arch/cc.h>
#include <arch/perf.h>
#include <arch/sys_arch.h>
#include <netif/ethernetif.h>

// From module: pio_handler support enabled
#include <pio_handler.h>

#endif // ASF_H


text:
@interface DigestController () <UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextView *plainTextView;
@property (weak, nonatomic) IBOutlet UITextView *digestTextView;
@end

@implementation DigestController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIGestureRecognizer *tapGusture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagTheBackground)];
    [self.view addGestureRecognizer:tapGusture];
    self.plainTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.plainTextView.layer.borderWidth = 1;
    self.plainTextView.layer.cornerRadius = 5;
    self.plainTextView.delegate = self;
    self.digestTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.digestTextView.layer.borderWidth = 1;
    self.digestTextView.layer.cornerRadius = 5;
    self.digestTextView.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)generateDigest:(id)sender {
    if ([self canDoCrypt:self.plainTextView]) {
        DigestActor *digestActor = [DigestActor new];
        NSString *stringToDigest = self.plainTextView.text;
        NSString *result = [digestActor stringByMD5Digest:stringToDigest];
        self.digestTextView.text = result;
    }
}

- (void)tagTheBackground {
    [self.plainTextView resignFirstResponder];
    [self.digestTextView resignFirstResponder];
}

- (void)digestTest {
    DigestActor *digestActor = [DigestActor new];
    NSString *stringToDigest = @"test Digest";
    NSString *result = [digestActor stringByMD5Digest:stringToDigest];
    NSLog(@"result: %@", result);
}
@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Globalization;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.Administration;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.Internal.UI.Authoring.Pages.Azure;
using Microsoft.EnterpriseManagement.Mom.Internal.UI.Common;
using Microsoft.EnterpriseManagement.Mom.Internal.UI.Controls;
//using Microsoft.EnterpriseManagement.Mom.UI;
using Microsoft.EnterpriseManagement.Monitoring;
using Microsoft.EnterpriseManagement.Monitoring.Security;
using Microsoft.EnterpriseManagement.Security;
using Microsoft.EnterpriseManagement.UI;

namespace Microsoft.IT.SCOM.ASB.UI
{
    public partial class ProxyAgent : UIPage
    {
        private PartialMonitoringObject proxyAgentComputer;
        internal const string SharedUserDataProxyAgentComputerPrincipalName = "ProxyAgent.ProxyAgentComputerPrincipalName";
        internal const string SharedUserDataTemplateIdString = "ProxyAgent.TemplateIdString";
        private string templateIdString;

        private string ASBNamespaceName;
        private string runAsName;
        private byte[] runAsSsid;

        public ProxyAgent()
        {
            InitializeComponent();
        }

        private PartialMonitoringObject GetProxyAgentComputer(string proxyAgentComputerName)
        {
            if (base.ManagementGroup == null)
            {
                return null;
            }
            ManagementPackClass monitoringClass = base.ManagementGroup.EntityTypes.GetClass(SystemMonitoringClass.HealthService);
            if (monitoringClass == null)
            {
                return null;
            }

            List<PartialMonitoringObject> partialMonitoringObjects = new List<PartialMonitoringObject>();
            IObjectReader<PartialMonitoringObject> reader =
                ManagementGroup.EntityObjects.GetObjectReader<PartialMonitoringObject>(
                    new MonitoringObjectGenericCriteria(string.Format(CultureInfo.InvariantCulture, "Name = '{0}' OR DisplayName = '{0}'", new object[] { proxyAgentComputerName })), monitoringClass, ObjectQueryOptions.Default);

            partialMonitoringObjects.AddRange(reader);

            if (partialMonitoringObjects.Count == 1)
            {
                return partialMonitoringObjects[0];
            }
            return null;
        }

        private void GetSharedUserData()
        {
            this.ASBNamespaceName = base.SharedUserData["ASBNamespaceDetails.ASBNamespaceName"] as string;
            this.runAsName = base.SharedUserData["ASBNamespaceDetails.RunAsName"] as string;
            this.runAsSsid = base.SharedUserData["ASBNamespaceDetails.RunAsSsid"] as byte[];

            this.proxyAgentComputer = this.GetProxyAgentComputer(this.proxyAgentBrowseTextBox.Text);
        }

        public override void LoadPageConfig()
        {
            if (base.IsCreationMode)
            {
                this.templateIdString = Guid.NewGuid().ToString("N");
            }
            else
            {
                if (string.IsNullOrEmpty(base.InputConfigurationXml))
                {
                    return;
                }
                try
                {
                    ProxyAgentConfig config = XmlHelper.Deserialize(base.InputConfigurationXml, typeof(ProxyAgentConfig), true) as ProxyAgentConfig;
                    this.templateIdString = config.TemplateIdString;
                    this.proxyAgentBrowseTextBox.Text = config.ProxyAgentComputerPrincipalName;

                    this.SetSharedUserData();
                }
                catch (ArgumentNullException exception)
                {
                    return;
                }
                catch (InvalidOperationException exception2)
                {
                    return;
                }
            }
            base.IsConfigValid = this.ValidatePageConfiguration();
            base.LoadPageConfig();
        }

        private void proxyAgentBrowseButton_Click(object sender, EventArgs e)
        {
            this.ShowComputerPickerDialog();
        }

        private bool RunAsAccountDistributionDialog()
        {
            this.GetSharedUserData();

            SecureData securedData = base.ManagementGroup.Security.GetSecureData(this.runAsSsid);
            if (securedData == null)
            {
                return false;
            }

            IApprovedHealthServicesForDistribution<PartialMonitoringObject> newState = base.ManagementGroup.Security.GetApprovedHealthServicesForDistribution<PartialMonitoringObject>(securedData);

            if (newState == null)
            {
                return false;
            }
            bool flag2 = newState.Result.Equals(ApprovedHealthServicesResults.All) || newState.HealthServices.Contains(this.proxyAgentComputer);
            if (!flag2)
            {
                string text = string.Empty;
                StringBuilder builder = new StringBuilder();
                if (!flag2)
                {
                    builder.AppendLine(this.runAsName);
                }
                //TODO: Fix this language
                text = string.Format("To enable discovery of databases on SQL Azure Server <{0}>, the following Run As account must be distributed to the health service '{1}':\n\n{2}\n\nWould you like Operations Manager to distribute the accounts?", this.ASBNamespaceName, this.proxyAgentComputer.DisplayName, builder.ToString());
                if (MessageBox.Show(base.ParentForm, text, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes)
                {
                    return false;
                }
                if (!flag2)
                {
                    newState.Result = ApprovedHealthServicesResults.Specified;
                    newState.HealthServices.Add(this.proxyAgentComputer);
                    base.ManagementGroup.Security.SetApprovedHealthServicesForDistribution<PartialMonitoringObject>(securedData, newState);
                }
            }
            return true;
        }

        public override bool SavePageConfig()
        {
            base.IsConfigValid = this.ValidatePageConfiguration();
            if (!base.IsConfigValid)
            {
                return false;
            }
            if (!this.RunAsAccountDistributionDialog())
            {
                return false;
            }
            ProxyAgentConfig config = new ProxyAgentConfig();
            config.TemplateIdString = this.templateIdString;
            config.ProxyAgentComputerPrincipalName = this.proxyAgentBrowseTextBox.Text;

            base.OutputConfigurationXml = XmlHelper.Serialize(config, true);
            this.SetSharedUserData();
            return true;
        }

        private void SetSharedUserData()
        {
            base.SharedUserData["ProxyAgent.TemplateIdString"] = this.templateIdString;
            base.SharedUserData["ProxyAgent.ProxyAgentComputerPrincipalName"] = this.proxyAgentBrowseTextBox.Text;
        }

        private void ShowComputerPickerDialog()
        {
            AgentSimpleChooserDialog dialog = new AgentSimpleChooserDialog(base.Container);
            dialog.ShowDialog(this);
            if (dialog.DialogResult == DialogResult.OK)
            {
                if (dialog.SelectedItems != null)
                {
                    ChooserControlItem selectedItem = dialog.SelectedItem as ChooserControlItem;
                    if ((selectedItem == null) || (selectedItem.Item == null))
                    {
                    }
                    else
                    {
                        ComputerHealthService item = selectedItem.Item as ComputerHealthService;
                        if (!string.IsNullOrEmpty(item.PrincipalName))
                        {
                            this.proxyAgentBrowseTextBox.Text = item.PrincipalName;
                        }
                    }
                }
            }
        }

        private bool ValidatePageConfiguration()
        {
            this.errorProvider.Clear();
            if (string.IsNullOrEmpty(this.proxyAgentBrowseTextBox.Text))
            {
                this.errorProvider.SetError(this.proxyAgentBrowseButton, string.Format(CultureInfo.CurrentUICulture, "Proxy agent must be selected", new object[0]));
                return false;
            }

            this.SetSharedUserData();
            return true;
        }

        private void ValidatePageConfigurationEventHandler(object sender, EventArgs e)
        {
            base.IsConfigValid = this.ValidatePageConfiguration();
        }
    }
}


text:
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Threading;

namespace AdmNoc2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        #region Declarations
        Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
        DispatcherTimer dispatcherTimer = new DispatcherTimer();
        #endregion

        public MainWindow()
        {
            InitializeComponent();

            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 40);
        }

        private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
        {
            lblVersion.Content = System.Windows.Forms.Application.ProductVersion;
            txtSearch.Text = Properties.Settings.Default.SavedProgramString;
            if(Properties.Settings.Default.ShouldLetMeKnow == true)
            {
                chkLetMeKnow.IsChecked = true;
            }
            if (Properties.Settings.Default.StartProgramAutomatically != false)
            {
                chkAutomaticallyStart.IsChecked = true;
                startNow(Properties.Settings.Default.SavedProgramString);

                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\close"))
                {
                    chkCloseAfterStart.IsChecked = true;
                    Close();
                }
            }
        }

        #region Button Clicks
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            ofd.ShowDialog();
            if(ofd.FileName != null)
            txtSearch.Text = ofd.FileName;
        }

        private void btnStartNow_Click(object sender, RoutedEventArgs e)
        {
            startNow(txtSearch.Text);
        }

        private void btnStopNow_Click(object sender, RoutedEventArgs e)
        {
            killNow(txtSearch.Text);
        }

        private void btnDeleteSettings_Click(object sender, RoutedEventArgs e)
        {
            chkLetMeKnow.IsChecked = false;
            chkCloseAfterStart.IsChecked = false;
            chkAutomaticallyStart.IsChecked = false;
            txtSearch.Text = "";
            Properties.Settings.Default.Reset();
            Properties.Settings.Default.Save();
            this.ShowMessageAsync("Done", "All settings are deleted");
        }
        #endregion

        #region Timer
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            string choosenName = System.IO.Path.GetFileNameWithoutExtension(txtSearch.Text);
            if (!IsProcessOpen(choosenName))
            {
                this.ShowMessageAsync("Finish", "The process is now closed");

                lblProcessIsRunning.Visibility = Visibility.Hidden;
                prgssMain.Visibility = Visibility.Hidden;
                dispatcherTimer.Stop();
            }
        }
        #endregion

        #region Start Now
        void startNow(string pathToStart)
        {
            try
            {
                Process prs = new Process();
                prs.StartInfo.FileName = pathToStart;
                //Vista or higher check
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    prs.StartInfo.Verb = "runas";
                }
                else
                {
                   this.ShowMessageAsync("Too old system version", "Sorry but It's not possible to run this program in your system");
                    return;
                }

                prs.Start();
                if (chkLetMeKnow.IsChecked == true)
                {

                    lblProcessIsRunning.Visibility = Visibility.Visible;
                    prgssMain.Visibility = Visibility.Visible;
                    string choosenName = System.IO.Path.GetFileNameWithoutExtension(pathToStart);
                    while (!IsProcessOpen(choosenName))
                    {
                        Thread.Sleep(50);
                    }
                    dispatcherTimer.Start();
                }
            }
            catch (Exception ex)
            {
                this.ShowMessageAsync("Error", ex.Message);
            }
        }
        #endregion

        #region Kill Now
        void killNow(string pathToKill)
        {
            Process cmd = new Process();
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.Arguments = "cmd.exe /c taskkill /f /im \"" + System.IO.Path.GetFileName(pathToKill) + "\"";
            cmd.Start();
        }
        #endregion

        // IS PROCESS OPEN?     /////
        private static bool IsProcessOpen(string name)
        {
            foreach (Process clsProcess in Process.GetProcesses())
            {
                if (clsProcess.ProcessName.Contains(name))
                {
                    return true;
                }
            }
            return false;
        }

        private void MainWindow1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if ((chkAutomaticallyStart.IsChecked == true) && (txtSearch.Text != ""))
            {
                Properties.Settings.Default.StartProgramAutomatically = true;
                Properties.Settings.Default.SavedProgramString = txtSearch.Text;
            }
            else
            {
                Properties.Settings.Default.StartProgramAutomatically = false;
            }
            if (chkCloseAfterStart.IsChecked == true)
            {
                string[] lines = { "*** Delete This file if you want to prevent AdmNoc from closing after It starts your program ***", "   ", "Current Program:", Properties.Settings.Default.SavedProgramString };
                File.WriteAllLines((AppDomain.CurrentDomain.BaseDirectory + @"\close"), lines);
                // File.Create(Application.StartupPath + @"\close");
            }
            else
            {
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\close"))
                {
                    File.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\close");
                }
            }
            if(chkLetMeKnow.IsChecked == true)
            {
                Properties.Settings.Default.ShouldLetMeKnow = true;
            }else
            {
                Properties.Settings.Default.ShouldLetMeKnow = false;
            }
            Properties.Settings.Default.SavedProgramString = txtSearch.Text;
            Properties.Settings.Default.Save();
        }
    }
}


text:
function y = real( x )

%   Disciplined convex/geometric programming information for REAL:
%      REAL(X) may be freely applied to any CVX expression. However,
%      since REAL(X)=X for all real expressions (including convex,
%      concave, log-convex, and log-concave), it is only useful in
%      the complex affine case.

y = cvx( x.size_, real( x.basis_ ) );

% Copyright 2012 Michael C. Grant and Stephen P. Boyd.
% See the file COPYING.txt for full copyright information.
% The command 'cvx_where' will show where this file is located.


text:
require 'action_view'

module AWFormFor
  autoload :FormBuilder, 'aw_form_for/form_builder'
  autoload :FormHelpers, 'aw_form_for/form_helpers'
  autoload :Railtie, 'aw_form_for/railtie'
  autoload :VERSION, 'aw_form_for/version'
end

AWFormFor::Railtie #trigger loading the railtie


text:
<?php

namespace Doctrine\ORM\Mapping;

/**
 * @Annotation
 * @Target("CLASS")
 */
final class InheritanceType implements Annotation
{

    /**
     * The inheritance type used by the class and its subclasses.
     *
     * @var string
     *
     * @Enum({"NONE", "JOINED", "SINGLE_TABLE", "TABLE_PER_CLASS"})
     */
    public $value;
}


text:
name: Xamarin.iOS - Working With Tables
description: "Collection of small samples shows how to use UITableView to build lists in Xamarin.iOS"
page_type: sample
languages:
- csharp
products:
- xamarin
urlFragment: workingwithtables
---
# Working With Tables

This collection of small samples shows how to use tables in Xamarin.iOS. The directory structure reflects the collection of article in the developer centre on [Working with Tables and Cells](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/).

## [Part 2 - Populating a Table with Data](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/populating-a-table-with-data)

* [BasicTable](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/populating-a-table-with-data#Subclassing_UITableViewSource)
* [BasicTableHeaderFooter](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/populating-a-table-with-data#Adding_Headers_and_Footers)
* [BasicTableIndex](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/populating-a-table-with-data#Adding_an_Index)

## [Part 3 - Customizing a Table's Appearance](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/customizing-table-appearance)

* [CellDefaultTable](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/customizing-table-appearance)
* [CellAccessory](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/customizing-table-appearance#accessories)
* [CellCustomTable](https://docs.microsoft.com/en-us/xamarin/ios/user-interface/controls/tables/customizing-table-appearance#creating-custom-cell-layouts)

## [Part 4 - Editing](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/editing)

* [TableEditMode](https://docs.microsoft.com/xamarin/ios/user-interface/controls/tables/editing#edit-mode)
* [TableEditModeAdd](https://docs.microsoft.com/en-us/xamarin/ios/user-interface/controls/tables/editing#row-insertion-editing-style)

Also related to these samples are:

* [StoryboardTable](https://docs.microsoft.com/samples/xamarin/ios-samples/storyboardtable/), which describes how to access a table created in a storyboard, via code.
* [TableEditing](https://docs.microsoft.com/samples/xamarin/ios-samples/tableediting/), which shows how to implement swipe to delete in a cell.


text:
class UselessIsBeforeAs
{
    class Square
    {
        public int width;
    }
    class Rectangle : Square
    {
        public int height;
    }
    public static void Main(string[] args)
    {
        Square a = new Rectangle();
        Rectangle r = a as Rectangle;
        if (r != null)
        {
            Console.WriteLine(r.height);
        }
    }
}


text:
#region Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NumCIL;
using Utilities;

namespace nbody
{
	public static class nBody
    {
		public static void Main (string[] args)
		{
			var opts = Utilities.CommandLineParser.ExtractOptions(args.ToList());
			var manualTempRemoval = Utilities.RunBenchmark.ParseBoolOption(opts, "no-temp-arrays");

			Utilities.RunBenchmark.Run(args, 2,
               // Running the benchmark
               (input) => {
					var size = input.sizes[0];
					var iterations = input.sizes[1];

					if (manualTempRemoval)
					{
						if (input.type == typeof(double)) {
							var data = new nBodySolverDoubleNoTempArrays.Galaxy(size);
							if (input.use_bohrium)
								NumCIL.Bohrium.Utility.Flush();

							using (new DispTimer(string.Format("nBodyNoTemp (Double) {0}*{1}", size, iterations)))
							{
								nBodySolverDoubleNoTempArrays.Solve(data, iterations);
								data.Sync();
							}
						} else {
							var data = new nBodySolverFloatNoTempArrays.Galaxy (size);
							if (input.use_bohrium)
								NumCIL.Bohrium.Utility.Flush();

							using (new DispTimer(string.Format("nBodyNoTemp (Float) {0}*{1}", size, iterations)))
							{
								nBodySolverFloatNoTempArrays.Solve(data, iterations);
								data.Sync();
							}
						}
					}
					else
					{
						if (input.type == typeof(double)) {
							var data = new nBodySolverDouble.Galaxy(size);
							if (input.use_bohrium)
								NumCIL.Bohrium.Utility.Flush();

							using (new DispTimer(string.Format("nBody (Double) {0}*{1}", size, iterations)))
							{
								nBodySolverDouble.Solve(data, iterations);
								data.Sync();
							}
						} else {
							var data = new nBodySolverFloat.Galaxy (size);
							if (input.use_bohrium)
								NumCIL.Bohrium.Utility.Flush();

							using (new DispTimer(string.Format("nBody (Float) {0}*{1}", size, iterations)))
							{
								nBodySolverFloat.Solve(data, iterations);
								data.Sync();
							}
						}
					}
				}
			);
		}
    }
}


text:
export interface IAccident {
	state: string;
	time: Date;
	vehiclesInvolved: number;
}


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

<TITLE>
Uses of Class framenet.corpus.Document
</TITLE>

<META NAME="date" CONTENT="2012-07-13">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
framenet.corpus.Document

Packages that use Document

framenet.corpus

Uses of Document in framenet.corpus

Methods in framenet.corpus that return Document

 Document
ObjectFactory.createDocument()

          Create an instance of Document

Methods in framenet.corpus that return types with arguments of type Document

 java.util.List<Document>
Documents.getDocument()

          Gets the value of the document property.

Methods in framenet.corpus with parameters of type Document

 void
Corpus.addDocument(Document doc)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
from __future__ import print_function
import numpy as np
from load_ml100k import load
from all_correlations import all_correlations

def nn_movie(ureviews, reviews, uid, mid, k=1):
    X = ureviews
    y = ureviews[mid].copy()
    y -= y.mean()
    y /= (y.std() + 1e-5)
    corrs = np.dot(X, y)
    likes = corrs.argsort()
    likes = likes[::-1]
    c = 0
    pred = 3.
    for ell in likes:
        if ell == mid:
            continue
        if reviews[uid, ell] > 0:
            pred = reviews[uid, ell]
            if c == k:
                return pred
            c += 1
    return pred

def all_estimates(reviews, k=1):
    reviews = reviews.astype(float)
    k -= 1
    nusers, nmovies = reviews.shape
    estimates = np.zeros_like(reviews)
    for u in range(nusers):
        ureviews = np.delete(reviews, u, 0)
        ureviews -= ureviews.mean(0)
        ureviews /= (ureviews.std(0) + 1e-4)
        ureviews = ureviews.T.copy()
        for m in np.where(reviews[u] > 0)[0]:
            estimates[u, m] = nn_movie(ureviews, reviews, u, m, k)
    return estimates

if __name__ == '__main__':
    reviews = load().toarray()
    estimates = all_estimates(reviews)
    error = (estimates - reviews)
    error **= 2
    error = error[reviews > 0]
    print(np.sqrt(error).mean())


text:
package util

import (
	"fmt"
	"strconv"

	apps "k8s.io/api/apps/v1"
	v1 "k8s.io/api/core/v1"
	extensions "k8s.io/api/extensions/v1beta1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	intstrutil "k8s.io/apimachinery/pkg/util/intstr"
	v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
)

// GetTemplateGeneration gets the template generation associated with a v1.DaemonSet by extracting it from the
// deprecated annotation. If no annotation is found nil is returned. If the annotation is found and fails to parse
// nil is returned with an error. If the generation can be parsed from the annotation, a pointer to the parsed int64
// value is returned.
func GetTemplateGeneration(ds *apps.DaemonSet) (*int64, error) {
	annotation, found := ds.Annotations[apps.DeprecatedTemplateGeneration]
	if !found {
		return nil, nil
	}
	generation, err := strconv.ParseInt(annotation, 10, 64)
	if err != nil {
		return nil, err
	}
	return &generation, nil
}

// AddOrUpdateDaemonPodTolerations apply necessary tolerations to DaemonSet Pods, e.g. node.kubernetes.io/not-ready:NoExecute.
func AddOrUpdateDaemonPodTolerations(spec *v1.PodSpec) {
	// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.
	// Add infinite toleration for taint notReady:NoExecute here
	// to survive taint-based eviction enforced by NodeController
	// when node turns not ready.
	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodeNotReady,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoExecute,
	})

	// DaemonSet pods shouldn't be deleted by NodeController in case of node problems.
	// Add infinite toleration for taint unreachable:NoExecute here
	// to survive taint-based eviction enforced by NodeController
	// when node turns unreachable.
	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodeUnreachable,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoExecute,
	})

	// According to TaintNodesByCondition feature, all DaemonSet pods should tolerate
	// MemoryPressure, DiskPressure, PIDPressure, Unschedulable and NetworkUnavailable taints.
	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodeDiskPressure,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoSchedule,
	})

	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodeMemoryPressure,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoSchedule,
	})

	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodePIDPressure,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoSchedule,
	})

	v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
		Key:      v1.TaintNodeUnschedulable,
		Operator: v1.TolerationOpExists,
		Effect:   v1.TaintEffectNoSchedule,
	})

	if spec.HostNetwork {
		v1helper.AddOrUpdateTolerationInPodSpec(spec, &v1.Toleration{
			Key:      v1.TaintNodeNetworkUnavailable,
			Operator: v1.TolerationOpExists,
			Effect:   v1.TaintEffectNoSchedule,
		})
	}
}

// CreatePodTemplate returns copy of provided template with additional
// label which contains templateGeneration (for backward compatibility),
// hash of provided template and sets default daemon tolerations.
func CreatePodTemplate(template v1.PodTemplateSpec, generation *int64, hash string) v1.PodTemplateSpec {
	newTemplate := *template.DeepCopy()

	AddOrUpdateDaemonPodTolerations(&newTemplate.Spec)

	if newTemplate.ObjectMeta.Labels == nil {
		newTemplate.ObjectMeta.Labels = make(map[string]string)
	}
	if generation != nil {
		newTemplate.ObjectMeta.Labels[extensions.DaemonSetTemplateGenerationKey] = fmt.Sprint(*generation)
	}
	// TODO: do we need to validate if the DaemonSet is RollingUpdate or not?
	if len(hash) > 0 {
		newTemplate.ObjectMeta.Labels[extensions.DefaultDaemonSetUniqueLabelKey] = hash
	}
	return newTemplate
}

// AllowsSurge returns true if the daemonset allows more than a single pod on any node.
func AllowsSurge(ds *apps.DaemonSet) bool {
	maxSurge, err := SurgeCount(ds, 1)
	return err == nil && maxSurge > 0
}

// SurgeCount returns 0 if surge is not requested, the expected surge number to allow
// out of numberToSchedule if surge is configured, or an error if the surge percentage
// requested is invalid.
func SurgeCount(ds *apps.DaemonSet, numberToSchedule int) (int, error) {
	if ds.Spec.UpdateStrategy.Type != apps.RollingUpdateDaemonSetStrategyType {
		return 0, nil
	}

	r := ds.Spec.UpdateStrategy.RollingUpdate
	if r == nil {
		return 0, nil
	}
	// If surge is not requested, we should default to 0.
	if r.MaxSurge == nil {
		return 0, nil
	}
	return intstrutil.GetScaledValueFromIntOrPercent(r.MaxSurge, numberToSchedule, true)
}

// UnavailableCount returns 0 if unavailability is not requested, the expected
// unavailability number to allow out of numberToSchedule if requested, or an error if
// the unavailability percentage requested is invalid.
func UnavailableCount(ds *apps.DaemonSet, numberToSchedule int) (int, error) {
	if ds.Spec.UpdateStrategy.Type != apps.RollingUpdateDaemonSetStrategyType {
		return 0, nil
	}
	r := ds.Spec.UpdateStrategy.RollingUpdate
	if r == nil {
		return 0, nil
	}
	return intstrutil.GetScaledValueFromIntOrPercent(r.MaxUnavailable, numberToSchedule, true)
}

// IsPodUpdated checks if pod contains label value that either matches templateGeneration or hash
func IsPodUpdated(pod *v1.Pod, hash string, dsTemplateGeneration *int64) bool {
	// Compare with hash to see if the pod is updated, need to maintain backward compatibility of templateGeneration
	templateMatches := dsTemplateGeneration != nil &&
		pod.Labels[extensions.DaemonSetTemplateGenerationKey] == fmt.Sprint(*dsTemplateGeneration)
	hashMatches := len(hash) > 0 && pod.Labels[extensions.DefaultDaemonSetUniqueLabelKey] == hash
	return hashMatches || templateMatches
}

// ReplaceDaemonSetPodNodeNameNodeAffinity replaces the RequiredDuringSchedulingIgnoredDuringExecution
// NodeAffinity of the given affinity with a new NodeAffinity that selects the given nodeName.
// Note that this function assumes that no NodeAffinity conflicts with the selected nodeName.
func ReplaceDaemonSetPodNodeNameNodeAffinity(affinity *v1.Affinity, nodename string) *v1.Affinity {
	nodeSelReq := v1.NodeSelectorRequirement{
		Key:      metav1.ObjectNameField,
		Operator: v1.NodeSelectorOpIn,
		Values:   []string{nodename},
	}

	nodeSelector := &v1.NodeSelector{
		NodeSelectorTerms: []v1.NodeSelectorTerm{
			{
				MatchFields: []v1.NodeSelectorRequirement{nodeSelReq},
			},
		},
	}

	if affinity == nil {
		return &v1.Affinity{
			NodeAffinity: &v1.NodeAffinity{
				RequiredDuringSchedulingIgnoredDuringExecution: nodeSelector,
			},
		}
	}

	if affinity.NodeAffinity == nil {
		affinity.NodeAffinity = &v1.NodeAffinity{
			RequiredDuringSchedulingIgnoredDuringExecution: nodeSelector,
		}
		return affinity
	}

	nodeAffinity := affinity.NodeAffinity

	if nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
		nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = nodeSelector
		return affinity
	}

	// Replace node selector with the new one.
	nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms = []v1.NodeSelectorTerm{
		{
			MatchFields: []v1.NodeSelectorRequirement{nodeSelReq},
		},
	}

	return affinity
}

// GetTargetNodeName get the target node name of DaemonSet pods. If `.spec.NodeName` is not empty (nil),
// return `.spec.NodeName`; otherwise, retrieve node name of pending pods from NodeAffinity. Return error
// if failed to retrieve node name from `.spec.NodeName` and NodeAffinity.
func GetTargetNodeName(pod *v1.Pod) (string, error) {
	if len(pod.Spec.NodeName) != 0 {
		return pod.Spec.NodeName, nil
	}

	// Retrieve node name of unscheduled pods from NodeAffinity
	if pod.Spec.Affinity == nil ||
		pod.Spec.Affinity.NodeAffinity == nil ||
		pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
		return "", fmt.Errorf("no spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution for pod %s/%s",
			pod.Namespace, pod.Name)
	}

	terms := pod.Spec.Affinity.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms
	if len(terms) < 1 {
		return "", fmt.Errorf("no nodeSelectorTerms in requiredDuringSchedulingIgnoredDuringExecution of pod %s/%s",
			pod.Namespace, pod.Name)
	}

	for _, term := range terms {
		for _, exp := range term.MatchFields {
			if exp.Key == metav1.ObjectNameField &&
				exp.Operator == v1.NodeSelectorOpIn {
				if len(exp.Values) != 1 {
					return "", fmt.Errorf("the matchFields value of '%s' is not unique for pod %s/%s",
						metav1.ObjectNameField, pod.Namespace, pod.Name)
				}

				return exp.Values[0], nil
			}
		}
	}

	return "", fmt.Errorf("no node name found for pod %s/%s", pod.Namespace, pod.Name)
}


text:
namespace dawn {

struct ReadWriteAccumulator {
  int numReads = 0;
  int numWrites = 0;

  int totalAccesses() const { return numReads + numWrites; }
};

/// @brief This Pass computes a heuristic measuring the data-locality of each stencil
///
/// @ingroup optimizer
///
/// This pass is not necessary to create legal code and is hence not in the debug-group
class PassDataLocalityMetric : public Pass {
public:
  PassDataLocalityMetric();

  /// @brief Pass implementation
  bool run(const std::shared_ptr<StencilInstantiation>& stencilInstantiation) override;
};

std::pair<int, int>
computeReadWriteAccessesMetric(const std::shared_ptr<StencilInstantiation>& instantiation,
                               const MultiStage& multiStage);
std::unordered_map<int, ReadWriteAccumulator> computeReadWriteAccessesMetricPerAccessID(
    const std::shared_ptr<StencilInstantiation>& instantiation, const MultiStage& multiStage);

} // namespace dawn

#endif


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='comment',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='invitation',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='object',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='revision',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='tag',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='updaterecord',
            name='date_created',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='user',
            name='last_access',
            field=models.DateTimeField(default=django.utils.timezone.now),
            preserve_default=True,
        ),
    ]


text:
package org.eclipse.moquette.spi.persistence;

import org.eclipse.moquette.proto.MQTTException;
import org.eclipse.moquette.spi.IMatchingCondition;
import org.eclipse.moquette.spi.IMessagesStore;
import org.eclipse.moquette.spi.ISessionsStore;
import org.eclipse.moquette.spi.impl.events.PublishEvent;
import org.eclipse.moquette.spi.impl.storage.StoredPublishEvent;
import org.eclipse.moquette.spi.impl.subscriptions.Subscription;
import org.eclipse.moquette.proto.messages.AbstractMessage;

import static org.eclipse.moquette.spi.impl.Utils.defaultGet;

import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentMap;

/**
 * MapDB main persistence implementation
 */
public class MapDBPersistentStore implements IMessagesStore, ISessionsStore {

    private static final Logger LOG = LoggerFactory.getLogger(MapDBPersistentStore.class);

    private ConcurrentMap<String, StoredMessage> m_retainedStore;
    //maps clientID to the list of pending messages stored
    private ConcurrentMap<String, List<StoredPublishEvent>> m_persistentMessageStore;
    //bind clientID+MsgID -> evt message published
    private ConcurrentMap<String, StoredPublishEvent> m_inflightStore;
    //map clientID <-> set of currently in flight packet identifiers
    Map<String, Set<Integer>> m_inFlightIds;
    //bind clientID+MsgID -> evt message published
    private ConcurrentMap<String, StoredPublishEvent> m_qos2Store;
    //persistent Map of clientID, set of Subscriptions
    private ConcurrentMap<String, Set<Subscription>> m_persistentSubscriptions;
    private DB m_db;
    private String m_storePath;

    /*
     * The default constructor will create an in memory store as no file path was specified
     */

    public MapDBPersistentStore() {
    	this.m_storePath = "";
    }

    public MapDBPersistentStore(String storePath) {
        this.m_storePath = storePath;
    }

    @Override
    public void initStore() {
    	if (m_storePath == null || m_storePath.isEmpty()) {
    		m_db = DBMaker.newMemoryDB().make();
    	} else {
	        File tmpFile;
	        try {
	            tmpFile = new File(m_storePath);
	            tmpFile.createNewFile();
	        } catch (IOException ex) {
	            LOG.error(null, ex);
	            throw new MQTTException("Can't create temp file for subscriptions storage [" + m_storePath + "]", ex);
	        }
	        m_db = DBMaker.newFileDB(tmpFile).make();
    	}
        m_retainedStore = m_db.getHashMap("retained");
        m_persistentMessageStore = m_db.getHashMap("persistedMessages");
        m_inflightStore = m_db.getHashMap("inflight");
        m_inFlightIds = m_db.getHashMap("inflightPacketIDs");
        m_persistentSubscriptions = m_db.getHashMap("subscriptions");
        m_qos2Store = m_db.getHashMap("qos2Store");
    }

    @Override
    public void cleanRetained(String topic) {
        m_retainedStore.remove(topic);
    }

    @Override
    public void storeRetained(String topic, ByteBuffer message, AbstractMessage.QOSType qos) {
        if (!message.hasRemaining()) {
            //clean the message from topic
            m_retainedStore.remove(topic);
        } else {
            //store the message to the topic
            byte[] raw = new byte[message.remaining()];
            message.get(raw);
            m_retainedStore.put(topic, new StoredMessage(raw, qos, topic));
        }
        m_db.commit();
    }

    @Override
    public Collection<StoredMessage> searchMatching(IMatchingCondition condition) {
        LOG.debug("searchMatching scanning all retained messages, presents are {}", m_retainedStore.size());

        List<StoredMessage> results = new ArrayList<StoredMessage>();

        for (Map.Entry<String, StoredMessage> entry : m_retainedStore.entrySet()) {
            StoredMessage storedMsg = entry.getValue();
            if (condition.match(entry.getKey())) {
                results.add(storedMsg);
            }
        }

        return results;
    }

    @Override
    public void storePublishForFuture(PublishEvent evt) {
        List<StoredPublishEvent> storedEvents;
        String clientID = evt.getClientID();
        if (!m_persistentMessageStore.containsKey(clientID)) {
            storedEvents = new ArrayList<>();
        } else {
            storedEvents = m_persistentMessageStore.get(clientID);
        }
        storedEvents.add(convertToStored(evt));
        m_persistentMessageStore.put(clientID, storedEvents);
        m_db.commit();
        //NB rewind the evt message content
        LOG.debug("Stored published message for client <{}> on topic <{}>", clientID, evt.getTopic());
    }

    @Override
    public List<PublishEvent> listMessagesInSession(String clientID) {
        List<PublishEvent> liveEvts = new ArrayList<>();
        List<StoredPublishEvent> storedEvts = defaultGet(m_persistentMessageStore, clientID, Collections.<StoredPublishEvent>emptyList());

        for (StoredPublishEvent storedEvt : storedEvts) {
            liveEvts.add(convertFromStored(storedEvt));
        }
        return liveEvts;
    }

    @Override
    public void removeMessageInSession(String clientID, Integer messageID) {
        List<StoredPublishEvent> events = m_persistentMessageStore.get(clientID);
        if (events == null) {
            return;
        }
        StoredPublishEvent toRemoveEvt = null;
        for (StoredPublishEvent evt : events) {
            if (evt.getMessageID() == null && messageID == null) {
                //was a qos0 message (no ID)
                toRemoveEvt = evt;
            }
            if (evt.getMessageID() == messageID) {
                toRemoveEvt = evt;
            }
        }
        events.remove(toRemoveEvt);
        m_persistentMessageStore.put(clientID, events);
        m_db.commit();
    }

    public void dropMessagesInSession(String clientID) {
        m_persistentMessageStore.remove(clientID);
        m_db.commit();
    }

    //----------------- In flight methods -----------------
    @Override
    public void cleanInFlight(String clientID, int packetID) {
        String publishKey = String.format("%s%d", clientID, packetID);
        m_inflightStore.remove(publishKey);
        Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
        if (inFlightForClient != null) {
            inFlightForClient.remove(packetID);
        }
        m_db.commit();
    }

    @Override
    public void addInFlight(PublishEvent evt, String clientID, int packetID) {
        String publishKey = String.format("%s%d", clientID, packetID);
        StoredPublishEvent storedEvt = convertToStored(evt);
        m_inflightStore.put(publishKey, storedEvt);
        m_db.commit();
    }

    /**
     * Return the next valid packetIdentifier for the given client session.
     * */
    @Override
    public int nextPacketID(String clientID) {
        Set<Integer> inFlightForClient = this.m_inFlightIds.get(clientID);
        if (inFlightForClient == null) {
            int nextPacketId = 1;
            inFlightForClient = new HashSet<>();
            inFlightForClient.add(nextPacketId);
            this.m_inFlightIds.put(clientID, inFlightForClient);
            return nextPacketId;
        }
        int maxId = inFlightForClient.isEmpty() ? 0 : Collections.max(inFlightForClient);
        int nextPacketId = (maxId + 1) % 0xFFFF;
        inFlightForClient.add(nextPacketId);
        return nextPacketId;
    }

    @Override
    public void removeSubscription(String topic, String clientID) {
        LOG.debug("removeSubscription topic filter: {} for clientID: {}", topic, clientID);
        if (!m_persistentSubscriptions.containsKey(clientID)) {
            return;
        }
        Set<Subscription> clientSubscriptions = m_persistentSubscriptions.get(clientID);
        //search for the subscription to remove
        Subscription toBeRemoved = null;
        for (Subscription sub : clientSubscriptions) {
            if (sub.getTopicFilter().equals(topic)) {
                toBeRemoved = sub;
                break;
            }
        }

        if (toBeRemoved != null) {
            clientSubscriptions.remove(toBeRemoved);
        }
        m_persistentSubscriptions.put(clientID, clientSubscriptions);
        m_db.commit();
    }

    @Override
    public void addNewSubscription(Subscription newSubscription) {
        LOG.debug("addNewSubscription invoked with subscription {}", newSubscription);
        final String clientID = newSubscription.getClientId();
        if (!m_persistentSubscriptions.containsKey(clientID)) {
            LOG.debug("clientID {} is a newcome, creating it's subscriptions set", clientID);
            m_persistentSubscriptions.put(clientID, new HashSet<Subscription>());
        }

        Set<Subscription> subs = m_persistentSubscriptions.get(clientID);
        if (!subs.contains(newSubscription)) {
            LOG.debug("updating clientID {} subscriptions set with new subscription", clientID);
            //TODO check the subs doesn't contain another subscription to the same topic with different
            Subscription existingSubscription = null;
            for (Subscription scanSub : subs) {
                if (newSubscription.getTopicFilter().equals(scanSub.getTopicFilter())) {
                    existingSubscription = scanSub;
                    break;
                }
            }
            if (existingSubscription != null) {
                subs.remove(existingSubscription);
            }
            subs.add(newSubscription);
            m_persistentSubscriptions.put(clientID, subs);
            LOG.debug("clientID {} subscriptions set now is {}", clientID, subs);
        }
        m_db.commit();
    }

    public void wipeSubscriptions(String clientID) {
        m_persistentSubscriptions.remove(clientID);
        m_db.commit();
    }

    @Override
    public void updateSubscriptions(String clientID, Set<Subscription> subscriptions) {
        m_persistentSubscriptions.put(clientID, subscriptions);
        m_db.commit();
    }

    public List<Subscription> listAllSubscriptions() {
        List<Subscription> allSubscriptions = new ArrayList<Subscription>();
        for (Map.Entry<String, Set<Subscription>> entry : m_persistentSubscriptions.entrySet()) {
            allSubscriptions.addAll(entry.getValue());
        }
        LOG.debug("retrieveAllSubscriptions returning subs {}", allSubscriptions);
        return allSubscriptions;
    }

    @Override
    public boolean contains(String clientID) {
        return m_persistentSubscriptions.containsKey(clientID);
    }

    public void close() {
        this.m_db.commit();
        LOG.debug("persisted subscriptions {}", m_persistentSubscriptions);
        this.m_db.close();
        LOG.debug("closed disk storage");
    }

    /*-------- QoS 2  storage management --------------*/
    public void persistQoS2Message(String publishKey, PublishEvent evt) {
        LOG.debug("persistQoS2Message store pubKey: {}, evt: {}", publishKey, evt);
        m_qos2Store.put(publishKey, convertToStored(evt));
    }

    public void removeQoS2Message(String publishKey) {
        LOG.debug("Removing stored Q0S2 message <{}>", publishKey);
        m_qos2Store.remove(publishKey);
    }

    public PublishEvent retrieveQoS2Message(String publishKey) {
        StoredPublishEvent storedEvt = m_qos2Store.get(publishKey);
        return convertFromStored(storedEvt);
    }

    private StoredPublishEvent convertToStored(PublishEvent evt) {
        StoredPublishEvent storedEvt = new StoredPublishEvent(evt);
        return storedEvt;
    }

    private PublishEvent convertFromStored(StoredPublishEvent evt) {
        byte[] message = evt.getMessage();
        ByteBuffer bbmessage = ByteBuffer.wrap(message);
        //bbmessage.flip();
        PublishEvent liveEvt = new PublishEvent(evt.getTopic(), evt.getQos(),
                bbmessage, evt.isRetain(), evt.getClientID(), evt.getMessageID());
        return liveEvt;
    }
}


text:
#pragma once

#include <atomic>
#include <filesystem>
#include <memory>
#include <string>
#include <vector>

namespace mos::aud {

class Buffer;
using Shared_buffer = std::shared_ptr<Buffer>;

/** 16bit integer audio buffer. */
class Buffer final {
public:
  using Samples = std::vector<short>;

  template <class T>
  /** Construct buffer from a container of shorts. */
  Buffer(const T begin, const T end, const int channels = 1,
         const int sample_rate = 44100)
      : id_(current_id_++), samples_(begin, end), channels_(channels),
        sample_rate_(sample_rate) {}

  /** Empty buffer constructor. */
  explicit Buffer(int channels = 1, int sample_rate = 44100);

  /** Load shared buffer. */
  static auto load(const std::filesystem::path &path) -> Buffer;

  Samples::const_iterator begin() const;

  Samples::const_iterator end() const;

  /** Raw data. */
  auto data() const -> const short *;

  /** Unique id. */
  auto id() const -> unsigned int;

  /** Get number of channels. */
  auto channels() const -> int;

  /** Get sample rate */
  auto sample_rate() const -> int;

  /** Duration in seconds. */
  auto duration() const -> float;

  /** Size of samples container. */
  auto size() const -> size_t;

private:
  static std::atomic_uint current_id_;
  unsigned int id_;
  Samples samples_;
  int channels_;
  int sample_rate_;
};
} // namespace mos::aud


text:
  <form class="form" id="prep_form" role="form" onsubmit="return false">

        Preparation Form

        Before Prep

              <select class="form-control" name="before_item" required>
                <option value="0">-Select Item-</option>
                 <?php
                $it = $this->inventory_model->get_item();
                foreach ($it as $key => $value) {
                    $ctr = $this->inventory_model->count_before_prep_stock($value['id']);
                    if ($ctr['stock'] > 0) {
                        echo "<option value='".$value['id']."|".$ctr['stock']."|".$ctr['unit']."'>".$value['ingredient_name']."</option>";
                    }
                }
              ?>
              </select>

        <input class="form-control" type="text" name="stock" disabled required value="Stock:">

            <input type="hidden" name="hidden_id" value="0">

                <input class="form-control" type="number" name="out_quantity" required placeholder="pull-out quantity">

        <input class="form-control" type="text" name="price1" disabled required value="Price:">

        After Prep

              <select class="form-control" name="after_item" required>
                <option value="0">-Select Item-</option>
                 <?php
                $it = $this->inventory_model->get_after_prep();
                foreach ($it as $key => $value) {
                  echo "<option value='".$value['id']."'>".$value['ingredient_name']."</option>";
                }
              ?>
              </select>

        <input type="hidden" name='hidden_price' value="0">

                <input class="form-control" type="number" name="in_quantity" required placeholder="prep quantity">

        <input class="form-control" type="text" name="price2" disabled required value="Price:">
        <button type="submit" class="btn btn-warning btn-block">Save</button>

  </form>

      <?php
        $this->load->view('inventory/_prep_list');
      ?>