text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using DesktopWidgets.Helpers;
using DesktopWidgets.Properties;
using DesktopWidgets.View;
using DesktopWidgets.WidgetBase.Settings;
using HorizontalAlignment = System.Windows.HorizontalAlignment;

namespace DesktopWidgets.Classes
{
    public class MouseChecker
    {
        private readonly WidgetSettingsBase _settings;
        private readonly WidgetView _view;
        private DispatcherTimer _hideTimer;
        private DispatcherTimer _mouseCheckTimer;
        private DispatcherTimer _showTimer;
        public bool KeepOpenForIntro;

        public bool KeepOpenUntilIdle;
        public IntroData QueueIntro;

        public MouseChecker(WidgetView view, WidgetSettingsBase settings)
        {
            _view = view;
            _settings = settings;
            _mouseCheckTimer = new DispatcherTimer();
            _hideTimer = new DispatcherTimer();
            _showTimer = new DispatcherTimer();

            _mouseCheckTimer.Tick += (sender, args) => Update();
            _hideTimer.Tick += delegate
            {
                _hideTimer.Stop();
                Hide(checkIdleStatus: false);
            };
            _showTimer.Tick += delegate
            {
                _showTimer.Stop();
                Show(activate: true);
            };

            UpdateIntervals();
        }

        public bool IsRunning => _mouseCheckTimer.IsEnabled;

        private Point GetMouseLocation()
            =>
                new Point(Control.MousePosition.X - _settings.MouseDetectionOffset.X,
                    Control.MousePosition.Y - _settings.MouseDetectionOffset.Y);

        public void UpdateIntervals()
        {
            _mouseCheckTimer.Interval = TimeSpan.FromMilliseconds(Settings.Default.MouseBoundsPollingInterval);
            _hideTimer.Interval = TimeSpan.FromMilliseconds(_settings.HideDelay);
            _showTimer.Interval = TimeSpan.FromMilliseconds(_settings.ShowDelay);
        }

        public void Start() => _mouseCheckTimer.Start();

        public void Stop() => _mouseCheckTimer.Stop();

        private Rect GetCenterBounds()
        {
            var viewBounds = _view.GetBounds();
            return new Rect(viewBounds.Left - _settings.MouseBounds, viewBounds.Top - _settings.MouseBounds,
                viewBounds.Width + _settings.MouseBounds * 2, viewBounds.Height + _settings.MouseBounds * 2);
        }

        private bool IsMouseInMouseBounds() => GetValidBounds().Any(checkRect => checkRect.Contains(GetMouseLocation()));

        private bool IsMouseInWindowBounds() => _view.GetBounds().Contains(GetMouseLocation());

        private bool IsMouseInCorners()
            => _view.ViewModel.GetScreenBounds().GetCorners(_settings.IgnoreScreenCornerSize)
                .Any(x => x.Contains(GetMouseLocation()));

        private IEnumerable<Rect> GetValidBounds()
        {
            if (_settings.CustomMouseDetectionBounds.Width > 0 && _settings.CustomMouseDetectionBounds.Height > 0)
            {
                yield return _settings.CustomMouseDetectionBounds;
            }
            else if (!_settings.IsDocked)
            {
                yield return GetCenterBounds();
            }
            else
            {
                if (_settings.StretchBounds)
                {
                    if (_settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Both ||
                        _settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Horizontal)
                    {
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Left ||
                            _settings.HorizontalAlignment == HorizontalAlignment.Stretch)
                        {
                            yield return
                                new Rect(_view.ViewModel.GetScreenBounds().Left, _view.ViewModel.GetScreenBounds().Top,
                                    _settings.MouseBounds,
                                    _view.ViewModel.GetScreenBounds().Height);
                        }
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Right ||
                            _settings.HorizontalAlignment == HorizontalAlignment.Stretch)
                        {
                            yield return new Rect(_view.ViewModel.GetScreenBounds().Right - _settings.MouseBounds,
                                _view.ViewModel.GetScreenBounds().Top, _settings.MouseBounds,
                                _view.ViewModel.GetScreenBounds().Height);
                        }
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Center)
                        {
                            if (_settings.CenterBoundsOnNonSidedDock)
                            {
                                yield return GetCenterBounds();
                            }
                        }
                    }
                    if (_settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Both ||
                        _settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Vertical)
                    {
                        if (_settings.VerticalAlignment == VerticalAlignment.Top ||
                            _settings.VerticalAlignment == VerticalAlignment.Stretch)
                        {
                            yield return
                                new Rect(_view.ViewModel.GetScreenBounds().Left, _view.ViewModel.GetScreenBounds().Top,
                                    _view.ViewModel.GetScreenBounds().Width,
                                    _settings.MouseBounds);
                        }
                        if (_settings.VerticalAlignment == VerticalAlignment.Bottom ||
                            _settings.VerticalAlignment == VerticalAlignment.Stretch)
                        {
                            yield return new Rect(_view.ViewModel.GetScreenBounds().Left,
                                _view.ViewModel.GetScreenBounds().Bottom - _settings.MouseBounds,
                                _view.ViewModel.GetScreenBounds().Width,
                                _settings.MouseBounds);
                        }
                        if (_settings.VerticalAlignment == VerticalAlignment.Center)
                        {
                            if (_settings.CenterBoundsOnNonSidedDock)
                            {
                                yield return GetCenterBounds();
                            }
                        }
                    }
                }
                else
                {
                    var viewBounds = _view.GetBounds();
                    if (_settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Both ||
                        _settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Horizontal)
                    {
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Left ||
                            _settings.HorizontalAlignment == HorizontalAlignment.Stretch)
                        {
                            yield return new Rect(viewBounds.Left, viewBounds.Top, _settings.MouseBounds,
                                viewBounds.Height);
                        }
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Right ||
                            _settings.HorizontalAlignment == HorizontalAlignment.Stretch)
                        {
                            yield return new Rect(viewBounds.Right - _settings.MouseBounds,
                                viewBounds.Top, _settings.MouseBounds, viewBounds.Height);
                        }
                        if (_settings.HorizontalAlignment == HorizontalAlignment.Center)
                        {
                            if (_settings.CenterBoundsOnNonSidedDock)
                            {
                                yield return GetCenterBounds();
                            }
                        }
                    }
                    if (_settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Both ||
                        _settings.MouseBoundsDetectionAxis == MouseBoundsDetectionAxis.Vertical)
                    {
                        if (_settings.VerticalAlignment == VerticalAlignment.Top ||
                            _settings.VerticalAlignment == VerticalAlignment.Stretch)
                        {
                            yield return new Rect(viewBounds.Left, viewBounds.Top, viewBounds.Width,
                                _settings.MouseBounds);
                        }
                        if (_settings.VerticalAlignment == VerticalAlignment.Bottom ||
                            _settings.VerticalAlignment == VerticalAlignment.Stretch)
                        {
                            yield return new Rect(viewBounds.Left,
                                viewBounds.Bottom - _settings.MouseBounds, viewBounds.Width,
                                _settings.MouseBounds);
                        }
                        if (_settings.VerticalAlignment == VerticalAlignment.Center)
                        {
                            if (_settings.CenterBoundsOnNonSidedDock)
                            {
                                yield return GetCenterBounds();
                            }
                        }
                    }
                }
            }
        }

        private void Update()
        {
            if (_settings.Disabled || _view.AnimationRunning)
            {
                return;
            }

            if ((App.IsMuted || _settings.IsMuted()) && !_settings.IgnoreMute)
            {
                Hide(checkHideStatus: false, checkIdleStatus: false);
                return;
            }

            if (!_settings.FullscreenActivation &&
                FullScreenHelper.DoesMonitorHaveFullscreenApp(_view.ViewModel.GetActualScreenBounds(), _view.ThisApp))
            {
                _showTimer.Stop();
                _hideTimer.Stop();
                Hide(false, false, false);
                return;
            }

            if (QueueIntro != null && !App.IsWorkstationLocked)
            {
                _view.ShowIntro(QueueIntro);
                return;
            }

            if (_settings.OpenMode == OpenMode.AlwaysOpen || KeepOpenForIntro)
            {
                Show();
                return;
            }

            if (_settings.DetectIdle && KeepOpenUntilIdle)
            {
                if (!_view.IsIdle)
                {
                    Show();
                }
                else
                {
                    Hide();
                }
                return;
            }

            if (_settings.OpenMode == OpenMode.Hidden)
            {
                Hide();
                return;
            }

            UpdateVisibilityStatus();
        }

        private void UpdateVisibilityStatus()
        {
            if (_settings.OpenMode == OpenMode.Mouse)
            {
                if (IsShowable())
                {
                    if (!_view.IsVisible && !(_settings.IgnoreScreenCornerSize != 0 && IsMouseInCorners()))
                    {
                        if (_settings.ShowDelay == 0)
                        {
                            Show(activate: true);
                        }
                        else
                        {
                            if (_showTimer.IsEnabled == false)
                            {
                                _showTimer.Start();
                            }
                        }
                    }
                }
                else
                {
                    if (_showTimer.IsEnabled)
                    {
                        _showTimer.Stop();
                    }
                    if (IsHideable())
                    {
                        if (_settings.HideDelay == 0)
                        {
                            Hide(checkIdleStatus: false);
                        }
                        else
                        {
                            if (_hideTimer.IsEnabled == false)
                            {
                                _hideTimer.Start();
                            }
                        }
                    }
                    else
                    {
                        if (_hideTimer.IsEnabled)
                        {
                            _hideTimer.Stop();
                        }
                    }
                }
            }
        }

        private bool IsHideable()
            =>
                _view.IsVisible && !_view.IsContextMenuOpen &&
                !(_settings.StayOpenIfMouseFocus && (IsShowable() || IsMouseInWindowBounds()));

        private bool IsShowable() => _view.IsMouseOver || IsMouseInMouseBounds();

        public void Show(bool animate = true, bool activate = false)
        {
            if (_view.AnimationRunning || _view.IsVisible ||
                ((App.IsMuted || _settings.IsMuted()) && !_settings.IgnoreMute) ||
                _settings.ForceHide)
            {
                return;
            }
            if (animate && _settings.Style.AnimationTime != 0)
            {
                _view.Animate(AnimationMode.Show, activate);
            }
            else
            {
                _view.Show();
            }
            if (activate && _settings.ActivateOnShow)
            {
                _view.Activate();
            }

            _view.ViewModel.OnShow();
        }

        public void Hide(bool animate = true, bool checkHideStatus = true, bool checkIdleStatus = true)
        {
            KeepOpenForIntro = false;
            KeepOpenUntilIdle = false;
            if (_view.AnimationRunning || !_view.IsVisible)
            {
                return;
            }
            if (checkHideStatus && !IsHideable())
            {
                return;
            }

            if (checkIdleStatus && !_view.IsIdle)
            {
                KeepOpenUntilIdle = true;
                return;
            }

            if (animate && _settings.Style.AnimationTime != 0)
            {
                _view.Animate(AnimationMode.Hide);
            }
            else
            {
                _view.Hide();
            }

            _view.ViewModel.OnHide();
        }

        public void Dispose()
        {
            _mouseCheckTimer?.Stop();
            _mouseCheckTimer = null;
            _hideTimer?.Stop();
            _hideTimer = null;
            _showTimer?.Stop();
            _showTimer = null;
        }
    }
}


text:
'use strict';

var React;
var ReactNoop;
var ReactCoroutine;
var ReactFeatureFlags;

describe('ReactCoroutine', () => {
  beforeEach(() => {
    jest.resetModules();
    React = require('react');
    ReactNoop = require('react-noop-renderer');
    // TODO: can we express this test with only public API?
    ReactCoroutine = require('ReactCoroutine');
    ReactFeatureFlags = require('ReactFeatureFlags');
    ReactFeatureFlags.disableNewFiberFeatures = false;
  });

  function div(...children) {
    children = children.map(c => (typeof c === 'string' ? {text: c} : c));
    return {type: 'div', children, prop: undefined};
  }

  function span(prop) {
    return {type: 'span', children: [], prop};
  }

  it('should render a coroutine', () => {
    var ops = [];

    function Continuation({isSame}) {
      ops.push(['Continuation', isSame]);
      return ;
    }

    // An alternative API could mark Continuation as something that needs
    // yielding. E.g. Continuation.yieldType = 123;
    function Child({bar}) {
      ops.push(['Child', bar]);
      return ReactCoroutine.createYield({
        props: {
          bar: bar,
        },
        continuation: Continuation,
      });
    }

    function Indirection() {
      ops.push('Indirection');
      return [<Child key="a" bar={true} />, <Child key="b" bar={false} />];
    }

    function HandleYields(props, yields) {
      ops.push('HandleYields');
      return yields.map((y, i) => (
        <y.continuation key={i} isSame={props.foo === y.props.bar} />
      ));
    }

    // An alternative API could mark Parent as something that needs
    // yielding. E.g. Parent.handler = HandleYields;
    function Parent(props) {
      ops.push('Parent');
      return ReactCoroutine.createCoroutine(
        props.children,
        HandleYields,
        props,
      );
    }

    function App() {
      return
<Parent foo={true}><Indirection /></Parent>
;
    }

    ReactNoop.render(<App />);
    ReactNoop.flush();

    expect(ops).toEqual([
      'Parent',
      'Indirection',
      ['Child', true],
      // Yield
      ['Child', false],
      // Yield
      'HandleYields',
      // Continue yields
      ['Continuation', true],
      ['Continuation', false],
    ]);
    expect(ReactNoop.getChildren()).toEqual([
      div(span('foo==bar'), span('foo!=bar')),
    ]);
  });

  it('should update a coroutine', () => {
    function Continuation({isSame}) {
      return ;
    }

    function Child({bar}) {
      return ReactCoroutine.createYield({
        props: {
          bar: bar,
        },
        continuation: Continuation,
      });
    }

    function Indirection() {
      return [<Child key="a" bar={true} />, <Child key="b" bar={false} />];
    }

    function HandleYields(props, yields) {
      return yields.map((y, i) => (
        <y.continuation key={i} isSame={props.foo === y.props.bar} />
      ));
    }

    function Parent(props) {
      return ReactCoroutine.createCoroutine(
        props.children,
        HandleYields,
        props,
      );
    }

    function App(props) {
      return
<Parent foo={props.foo}><Indirection /></Parent>
;
    }

    ReactNoop.render(<App foo={true} />);
    ReactNoop.flush();
    expect(ReactNoop.getChildren()).toEqual([
      div(span('foo==bar'), span('foo!=bar')),
    ]);

    ReactNoop.render(<App foo={false} />);
    ReactNoop.flush();
    expect(ReactNoop.getChildren()).toEqual([
      div(span('foo!=bar'), span('foo==bar')),
    ]);
  });

  it('should unmount a composite in a coroutine', () => {
    var ops = [];

    class Continuation extends React.Component {
      render() {
        ops.push('Continuation');
        return
;
      }
      componentWillUnmount() {
        ops.push('Unmount Continuation');
      }
    }

    class Child extends React.Component {
      render() {
        ops.push('Child');
        return ReactCoroutine.createYield(Continuation);
      }
      componentWillUnmount() {
        ops.push('Unmount Child');
      }
    }

    function HandleYields(props, yields) {
      ops.push('HandleYields');
      return yields.map((ContinuationComponent, i) => (
        <ContinuationComponent key={i} />
      ));
    }

    class Parent extends React.Component {
      render() {
        ops.push('Parent');
        return ReactCoroutine.createCoroutine(
          this.props.children,
          HandleYields,
          this.props,
        );
      }
      componentWillUnmount() {
        ops.push('Unmount Parent');
      }
    }

    ReactNoop.render(<Parent><Child /></Parent>);
    ReactNoop.flush();

    expect(ops).toEqual(['Parent', 'Child', 'HandleYields', 'Continuation']);

    ops = [];

    ReactNoop.render(
);
    ReactNoop.flush();

    expect(ops).toEqual([
      'Unmount Parent',
      'Unmount Child',
      'Unmount Continuation',
    ]);
  });

  it('should handle deep updates in coroutine', () => {
    let instances = {};

    class Counter extends React.Component {
      state = {value: 5};
      render() {
        instances[this.props.id] = this;
        return ReactCoroutine.createYield(this.state.value);
      }
    }

    function App(props) {
      return ReactCoroutine.createCoroutine(
        [
          <Counter key="a" id="a" />,
          <Counter key="b" id="b" />,
          <Counter key="c" id="c" />,
        ],
        (p, yields) => yields.map((y, i) => ),
        {},
      );
    }

    ReactNoop.render(<App />);
    ReactNoop.flush();
    expect(ReactNoop.getChildren()).toEqual([span(500), span(500), span(500)]);

    instances.a.setState({value: 1});
    instances.b.setState({value: 2});
    ReactNoop.flush();
    expect(ReactNoop.getChildren()).toEqual([span(100), span(200), span(500)]);
  });
});

redpajama_set_name: RedPajamaGithub


text:
package cl.ml.ceppi.web.logic;

import java.util.List;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.log4j.Logger;

import cl.ml.ceppi.core.facade.PerfilFacade;
import cl.ml.ceppi.core.facade.UsuarioFacade;
import cl.ml.ceppi.core.model.menu.Menu;
import cl.ml.ceppi.core.model.menu.MenuCompuesto;
import cl.ml.ceppi.core.model.perfil.Perfil;
import cl.ml.ceppi.core.model.usuario.Usuario;
import cl.ml.ceppi.core.util.Crypt;
import cl.ml.ceppi.web.locator.ServiceLocator;
import cl.ml.ceppi.web.util.Constantes;

/**
 *
 * @author Maldonado Le�n
 *
 */
public class UsuarioLogic {

	private static final Logger LOGGER = Logger.getLogger(UsuarioLogic.class);

	public UsuarioLogic() {
	}

	/**
	 * Autenticar usuario
	 * @param user
	 * @param pass
	 * @param request
	 * @return
	 */
	public static Usuario autenticar(String user, String pass)
	{
		Usuario usuario = null;
		try
		{
			UsuarioFacade usuarioFacade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);
			String password = Crypt.encrypt(pass);
			usuario = usuarioFacade.autenticar(user, password);

		}
		catch (Exception e)
		{
			LOGGER.error("Error al autenticar usuario "+ user +".", e);
		}
		return usuario;
	}

	/**
	 * Obtiene el acceso por perfil
	 * @param perfil
	 * @return
	 */
	public static List<MenuCompuesto> acceso(Perfil perfil)
	{
		try
		{
			PerfilFacade facade = (PerfilFacade) ServiceLocator.getInstance().getBean(Constantes.PERFIL_FACADE);

			List<MenuCompuesto> menu = facade.listMenuPerfil(perfil.getOid());

			for (MenuCompuesto menuCompuesto : menu) {
				menuCompuesto.setMenu(null);
				for (Menu item :menuCompuesto.getItemMenu())
				{
					item.setMenu(null);
				}
			}
			createMenu(menu);
			return menu;
		}
		catch (Exception e)
		{
			LOGGER.error("Error al obtener el menu por perfil.", e);
			return null;
		}
	}

	/**
	 *
	 * @param menu
	 * @return
	 */
	private static String createMenu(List<MenuCompuesto> menu)
	{
		StringBuilder builder = new StringBuilder();

		builder.append("");
		builder.append("
");
		builder.append("
Menú
");
		builder.append("
");

		for (MenuCompuesto menuCompuesto : menu)
		{
			builder.append("
");
			builder.append("");
			builder.append("");
			builder.append("" + menuCompuesto.getNombre() + "");
			builder.append("");
			builder.append("");
			builder.append("
");
			builder.append("
" + menuCompuesto.getNombre() + "
");
			for (Menu subMenu : menuCompuesto.getItemMenu())
			{
				builder.append("
");
				builder.append(""+ subMenu.getNombre() + "");
				builder.append("
");
			}
			builder.append("
");
			builder.append("
");
		}

		builder.append("
");
		builder.append("
");
		builder.append("");

		LOGGER.info("MENU: " + builder.toString());

		return builder.toString();
	}

	/**
	 * Obtiene la lista de usuarios
	 * @return
	 */
	public static Response listaUsuarios()
	{
		try
		{
			UsuarioFacade facade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);
			List<Usuario> lista = facade.listUsuario();
			return Response.status(Status.OK).entity(lista).build();
		}
		catch (Exception e)
		{
			LOGGER.error("Error al guardar un usuario.", e);
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build();
		}
	}

	/**
	 * Guarda un usuario
	 * @param usuario
	 * @return
	 */
	public static Response save(Usuario usuario)
	{
		try
		{
			UsuarioFacade facade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);

			String pass = Crypt.encrypt(usuario.getPassword());
			usuario.setPassword(pass);

			facade.save(usuario);

			return Response.status(Status.OK).entity(null).build();
		}
		catch (Exception e)
		{
			LOGGER.error("Error al guardar un usuario.", e);
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build();
		}
	}

	/**
	 * Actualiza un usuario
	 * @param usuario
	 * @return
	 */
	public static Response update(Usuario usuario)
	{
		try
		{
			UsuarioFacade facade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);

			String pass = Crypt.encrypt(usuario.getPassword());
			usuario.setPassword(pass);

			facade.update(usuario);
			return Response.status(Status.OK).entity(null).build();
		}
		catch (Exception e)
		{
			LOGGER.error("Error al actualizar un usuario.", e);
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build();
		}
	}

	/**
	 * Elimina un usuario
	 * @param usuario
	 * @return
	 */
	public static Response delete(Usuario usuario)
	{
		try
		{
			UsuarioFacade facade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);

			facade.delete(usuario);
			return Response.status(Status.OK).entity(null).build();
		}
		catch (Exception e)
		{
			LOGGER.error("Error al eliminar un usuario.", e);
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build();
		}
	}

	/**
	 *
	 * @param id
	 * @return
	 */
	public static Response findUsuarioById(int id)
	{
		try
		{
			UsuarioFacade facade = (UsuarioFacade) ServiceLocator.getInstance().getBean(Constantes.USUARIO_FACADE);
			Usuario usuario = facade.findUsuarioById(id);
			return Response.status(Status.OK).entity(usuario).build();
		}
		catch (Exception e)
		{
			LOGGER.error("Error al obtener el usuario " + id, e);
			return Response.status(Status.INTERNAL_SERVER_ERROR).entity(null).build();
		}
	}
}


text:
CIMPLE_NAMESPACE_BEGIN

#if 0
# define TRACE CIMPLE_TRACE
#else
# define TRACE
#endif

Lamp_Provider::Lamp_Provider()
{
    TRACE;
}

Lamp_Provider::~Lamp_Provider()
{
    TRACE;
}

Load_Status Lamp_Provider::load()
{
    TRACE;

    Lamp* instance;

    instance = Lamp::create();
    instance->model.value = "A";
    instance->vendor.value = "Euro Lamps Inc";
    instance->wattage.value = 300;
    instance->color.value = "Silver";
    _map.insert(instance);

    instance = Lamp::create();
    instance->model.value = "B";
    instance->vendor.value = "US Lighting";
    instance->wattage.value = 400;
    instance->color.value = "Blue";
    _map.insert(instance);

    {
        ModernLamp* inst = ModernLamp::create();
        inst->model.value = "Zippy";
        inst->vendor.value = "Euro Lamps Inc";
        inst->wattage.value = 5000;
        inst->color.value = "White";
        inst->artist.value = "Jean Do Van Dam";
        _map.insert(cast<Lamp*>(inst));
    }

    return LOAD_OK;
}

Unload_Status Lamp_Provider::unload()
{
    TRACE;
    return UNLOAD_OK;
}

Get_Instance_Status Lamp_Provider::get_instance(
    const Lamp* model,
    Lamp*& instance)
{
    TRACE;

    return _map.get_instance(model, instance);
}

Enum_Instances_Status Lamp_Provider::enum_instances(
    const Lamp* model,
    Enum_Instances_Handler<Lamp>* handler)
{
    TRACE;
    return _map.enum_instances(model, handler);
}

Create_Instance_Status Lamp_Provider::create_instance(
    Lamp* instance)
{
    TRACE;
    return _map.create_instance(instance);
}

Delete_Instance_Status Lamp_Provider::delete_instance(
    const Lamp* instance)
{
    TRACE;
    return _map.delete_instance(instance);
}

Modify_Instance_Status Lamp_Provider::modify_instance(
    const Lamp* model,
    const Lamp* instance)
{
    TRACE;
    return _map.modify_instance(model, instance);
}

Invoke_Method_Status Lamp_Provider::foo(
    const Lamp* self,
    const Property<String>& arg1,
    const Property<String>& arg2,
    Property<uint32>& return_value)
{
    TRACE;
    return_value.null = false;
    return_value.value = 100;

    return INVOKE_METHOD_OK;
}

CIMPLE_NAMESPACE_END


text:
<?php

/**
 * The "orderreports" collection of methods.
 * Typical usage is:
 *  <code>
 *   $contentService = new Google_Service_ShoppingContent(...);
 *   $orderreports = $contentService->orderreports;
 *  </code>
 */
class Google_Service_ShoppingContent_Resource_Orderreports extends Google_Service_Resource
{
  /**
   * Retrieves a report for disbursements from your Merchant Center account.
   * (orderreports.listdisbursements)
   *
   * @param string $merchantId The ID of the account that manages the order. This
   * cannot be a multi-client account.
   * @param string $disbursementStartDate The first date which disbursements
   * occurred. In ISO 8601 format.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string disbursementEndDate The last date which disbursements
   * occurred. In ISO 8601 format. Default: current date.
   * @opt_param string maxResults The maximum number of disbursements to return in
   * the response, used for paging.
   * @opt_param string pageToken The token returned by the previous request.
   * @return Google_Service_ShoppingContent_OrderreportsListDisbursementsResponse
   */
  public function listdisbursements($merchantId, $disbursementStartDate, $optParams = array())
  {
    $params = array('merchantId' => $merchantId, 'disbursementStartDate' => $disbursementStartDate);
    $params = array_merge($params, $optParams);
    return $this->call('listdisbursements', array($params), "Google_Service_ShoppingContent_OrderreportsListDisbursementsResponse");
  }
  /**
   * Retrieves a list of transactions for a disbursement from your Merchant Center
   * account. (orderreports.listtransactions)
   *
   * @param string $merchantId The ID of the account that manages the order. This
   * cannot be a multi-client account.
   * @param string $disbursementId The Google-provided ID of the disbursement
   * (found in Wallet).
   * @param string $transactionStartDate The first date in which transaction
   * occurred. In ISO 8601 format.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string maxResults The maximum number of disbursements to return in
   * the response, used for paging.
   * @opt_param string pageToken The token returned by the previous request.
   * @opt_param string transactionEndDate The last date in which transaction
   * occurred. In ISO 8601 format. Default: current date.
   * @return Google_Service_ShoppingContent_OrderreportsListTransactionsResponse
   */
  public function listtransactions($merchantId, $disbursementId, $transactionStartDate, $optParams = array())
  {
    $params = array('merchantId' => $merchantId, 'disbursementId' => $disbursementId, 'transactionStartDate' => $transactionStartDate);
    $params = array_merge($params, $optParams);
    return $this->call('listtransactions', array($params), "Google_Service_ShoppingContent_OrderreportsListTransactionsResponse");
  }
}


text:
import { createStore, applyMiddleware, compose } from 'redux';
import { reduxReactRouter } from 'redux-router';
import routes from '../routes';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from '../reducers';
import { isDevEnv } from 'utils/config';

let createHistory, composeConfig;

if (isDevEnv()) {
  createHistory = require('history/lib/createHashHistory');
  const logger = createLogger({
    // predicate: (getState, action) => action.type !== AUTH_REMOVE_TOKEN,   // log all actions except AUTH_REMOVE_TOKEN
    level: 'info',
    collapsed: true
  });
  composeConfig = [
    applyMiddleware(thunk),
    reduxReactRouter({ routes, createHistory }),
    applyMiddleware(logger)
  ]
} else {
  createHistory = require('history/lib/createBrowserHistory');
  composeConfig = [
    applyMiddleware(thunk),
    reduxReactRouter({ routes, createHistory })
  ]
}

const finalCreateStore = compose(
  ...composeConfig
)(createStore);

export default function configureStore(initialState) {
  const store = finalCreateStore(rootReducer, initialState);

  if (module.hot) {
    // Enable Webpack hot module replacement for reducers
    module.hot.accept('../reducers', () => {
      const nextRootReducer = require('../reducers');
      store.replaceReducer(nextRootReducer);
    });
  }

  return store;
}


text:
package com.jcwhatever.nucleus.managed.commands.arguments;

import org.bukkit.Location;
import org.bukkit.entity.Player;

/**
 * A delegate to handle player location selection.
 */
public interface ILocationHandler {

    /**
     * Invoked when a location is retrieved from a player.
     *
     * @param player  The player that selected a location.
     * @param result  The location that was selected.
     */
    void onLocationRetrieved(Player player, Location result);
}


text:
using Aspose.Cells;
using Aspose.Email.Mail;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Email.Examples.CSharp.Email.Knowledge.Base
{
    class SendExcelWorksheetAsMessageBody
    {
        public static void Run()
        {
            try
            {
                // ExStart:SendExcelWorksheetAsMessageBody
                // The path to the File directory
                string dataDir = RunExamples.GetDataDir_KnowledgeBase();

                // Load the desired workbook from disk
                Workbook workbook = new Workbook(dataDir + "Data.xlsx");

                // Save the workbook to Memory Stream in HTML format
                MemoryStream ms = new MemoryStream();
                workbook.Save(ms, SaveFormat.Html);
                ms.Position = 0;

                // Define a StreamReader object with the above MemoryStream
                StreamReader sr = new StreamReader(ms);

                // Load the saved HTML from StreamReader now into a string variable
                string strHtmlBody = sr.ReadToEnd();

                // Define a new Message object and set its HtmlBody
                MailMessage message = new MailMessage();
                message.HtmlBody = strHtmlBody;
                message.Subject = "Inline Excel Message";
                message.From = "sender@abc.com";
                message.To = "receiver@xyz.com";
                message.IsBodyHtml = true;
                SmtpClient client = new SmtpClient();
                client.Host = "smtp.gmail.com";
                client.Username = "Username";
                client.Password = "Password";
                client.Port = 587;
                client.SecurityOptions = SecurityOptions.Auto;
                client.Send(message);
                // ExEnd:SendExcelWorksheetAsMessageBody
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


text:
// Register a jsDump parser for Base.
QUnit.jsDump.setParser('Base', function (obj, stack) {
	// Just compare the string representation of classes inheriting from Base,
	// since they hide the internal values.
	return obj.toString();
});

// Override the default object parser to handle Base objects.
// We need to keep a reference to the previous implementation.
var objectParser = QUnit.jsDump.parsers.object;

QUnit.jsDump.setParser('object', function (obj, stack) {
	return (obj instanceof Base
			? QUnit.jsDump.parsers.Base
			: objectParser).call(this, obj, stack);
});

function getFunctionBody(func) {
	return func.toString().match(
		/^\s*function[^\{]*\{([\s\S]*)\}\s*$/)[1]
			.replace(/    /g, '')
			.replace(/^\s+|\s+$/g, '');
}

// Override equals to convert functions to message and execute them as tests()
function equals(actual, expected, message, tolerance) {
	if (typeof actual === 'function') {
		if (!message) {
			message = getFunctionBody(actual);
			if (/^return /.test(message)) {
				message = message
					.replace(/^return /, '')
					.replace(/;$/, '');
			}
		}
		actual = actual();
	}
	// See if we need to compare with a tolerance, and if so, assume a number.
	if (tolerance !== undefined) {
		var ok = Math.abs(actual - expected) <= tolerance;
		return QUnit.push(ok, ok ? expected : actual, expected, message);
	} else if (actual && actual.equals) {
		// Support calling of #equals() on the actual or expected value, and
		// automatically convert displayed values to strings.
		return QUnit.push(actual.equals(expected), actual, expected, message);
	} else if (expected && expected.equals) {
		return QUnit.push(expected.equals(actual), actual, expected, message);
	}
	// Let's be strict
	return strictEqual(actual, expected, message);
}

function test(testName, expected) {
	return QUnit.test(testName, function() {
		var project = new Project();
		expected();
		project.remove();
	});
}

function asyncTest(testName, expected) {
	return QUnit.asyncTest(testName, function() {
		var project = new Project();
		expected(function() {
			project.remove();
			start();
		});
	});
}

function compareNumbers(number1, number2, message, precision) {
	var formatter = new Formatter(precision);
	equals(formatter.number(number1),
			formatter.number(number2), message);
}

function compareArrays(array1, array2, message, precision) {
	var formatter = new Formatter(precision);
	function format(array) {
		return Base.each(array, function(value, index) {
			this[index] = formatter.number(value);
		}, []).toString();
	}
	equals(format(array1), format(array2), message);
}

function comparePoints(point1, point2, message) {
	compareNumbers(point1.x, point2.x, (message || '') + ' x');
	compareNumbers(point1.y, point2.y, (message || '') + ' y');
}

function compareRectangles(rect1, rect2, message) {
	compareNumbers(rect1.x, rect2.x, (message || '') + ' x');
	compareNumbers(rect1.y, rect2.y, (message || '') + ' y');
	compareNumbers(rect1.width, rect2.width, (message || '') + ' width');
	compareNumbers(rect1.height, rect2.height, (message || '') + ' height');
}

function compareColors(color1, color2, message, precision) {
	color1 = color1 && new Color(color1);
	color2 = color2 && new Color(color2);
	if (color1 && color2) {
		equals(color1.type, color2.type, (message || '') + ' type');
		compareArrays(color1.components, color2.components,
				(message || '') + ' components', precision);
	} else {
		equals(color1, color2, message);
	}
}

function compareStyles(style, style2, checkIdentity) {
	if (checkIdentity) {
		equals(function() {
			return style !== style2;
		}, true);
	}
	Base.each(['fillColor', 'strokeColor'], function(key) {
		if (style[key]) {
			// The color should not point to the same color object:
			if (checkIdentity) {
				equals(function() {
					return style[key] !== style2[key];
				}, true, 'The ' + key + ' should not point to the same color object:');
			}
			if (style[key] instanceof Color) {
				if (style[key].type === 'gradient' && checkIdentity) {
					equals(function() {
						return style[key].gradient === style2[key].gradient;
					}, true, 'The ' + key + '.gradient should point to the same object:');
				}
				compareColors(style[key], style2[key],
						'Compare Style#' + key);
			} else {
				equals(style[key] && style[key].toString(),
						style2[key] && style2[key].toString(),
						'Compare Style#' + key);
			}
		}
	});

	compareObjects('Style', ['strokeCap', 'strokeJoin', 'dashArray',
			'dashOffset', 'miterLimit', 'strokeOverprint', 'fillOverprint',
			'fontSize', 'font', 'leading', 'justification'],
			style, style2, checkIdentity);
}

function compareObjects(name, keys, obj, obj2, checkIdentity) {
	if (checkIdentity) {
		equals(function() {
			return obj !== obj2;
		}, true);
	}
	Base.each(keys, function(key) {
		var val = obj[key], val2 = obj2[key],
			message = 'Compare ' + name + '#' + key;
		if (typeof val === 'number') {
			compareNumbers(val, val2, message);
		} else if (Array.isArray(val)) {
			compareArrays(val, val2, message);
		} else {
			equals(val, val2, message);
		}
	});
}

function compareSegmentPoints(segmentPoint, segmentPoint2, checkIdentity) {
	compareObjects('SegmentPoint', ['x', 'y', 'selected'],
			segmentPoint, segmentPoint2, checkIdentity);
}

function compareSegments(segment, segment2, checkIdentity) {
	if (checkIdentity) {
		equals(function() {
			return segment !== segment2;
		}, true);
	}
	equals(function() {
		return segment.selected == segment2.selected;
	}, true);
	Base.each(['handleIn', 'handleOut', 'point'], function(key) {
		compareSegmentPoints(segment[key], segment2[key]);
	});
}

function compareSegmentLists(segmentList, segmentList2, checkIdentity) {
	if (checkIdentity) {
		equals(function() {
			return segmentList !== segmentList2;
		}, true);
	}
	equals(segmentList.toString(), segmentList2.toString(),
			'Compare Item#segments');
	if (checkIdentity) {
		for (var i = 0, l = segmentList.length; i < l; i++) {
			var segment = segmentList[i],
				segment2 = segmentList2[i];
			compareSegments(segment, segment2, checkIdentity);
		}
	}
}

function compareItems(item, item2, cloned, checkIdentity, dontShareProject) {
	if (checkIdentity) {
		equals(function() {
			return item !== item2;
		}, true);

		equals(function() {
			return item.id !== item2.id;
		}, true);
	}

	equals(function() {
		return item.constructor == item2.constructor;
	}, true);

	var itemProperties = ['opacity', 'locked', 'visible', 'blendMode', 'name',
			'selected', 'clipMask', 'guide'];
	Base.each(itemProperties, function(key) {
		var value = item[key];
		// When item was cloned and had a name, the name will be versioned
		equals(
			key == 'name' && cloned && value
				? value + ' 1'
				: value,
			item2[key],
			'compare Item#' + key);
	});

	if (checkIdentity) {
		equals(function() {
			return item.bounds !== item2.bounds;
		}, true);
	}

	equals(item.bounds.toString(), item2.bounds.toString(),
			'Compare Item#bounds');

	if (checkIdentity) {
		equals(function() {
			return item.position !== item2.position;
		}, true);
	}

	equals(item.position.toString(), item2.position.toString(),
			'Compare Item#position');

	equals(function() {
		return Base.equals(item.data, item2.data);
	}, true);

	if (item.matrix) {
		if (checkIdentity) {
			equals(function() {
				return item.matrix !== item2.matrix;
			}, true);
		}
		equals(item.matrix.toString(), item2.matrix.toString(),
				'Compare Item#matrix');
	}

	// Path specific
	if (item instanceof Path) {
		var keys = ['closed', 'fullySelected', 'clockwise'];
		for (var i = 0, l = keys.length; i < l; i++) {
			var key = keys[i];
			equals(item[key], item2[key], 'Compare Path#' + key);
		}
		compareNumbers(item.length, item2.length, 'Compare Path#length');
		compareSegmentLists(item.segments, item2.segments, checkIdentity);
	}

	// Shape specific
	if (item instanceof Shape) {
		var keys = ['shape', 'size', 'radius'];
		for (var i = 0, l = keys.length; i < l; i++) {
			var key = keys[i];
			equals(item[key], item2[key], 'Compare Shape#' + key);
		}
	}

	// Group specific
	if (item instanceof Group) {
		equals(function() {
			return item.clipped == item2.clipped;
		}, true);
	}

	// Layer specific
	if (item instanceof Layer) {
		equals(function() {
			return dontShareProject
					? item.project != item2.project
					: item.project == item2.project;
		}, true);
	}

	// PlacedSymbol specific
	if (item instanceof PlacedSymbol) {
		if (dontShareProject) {
			compareItems(item.symbol.definition, item2.symbol.definition,
					cloned, checkIdentity, dontShareProject,
					'Compare Symbol#definition');
		} else {
			equals(function() {
				return item.symbol == item2.symbol;
			}, true);
		}
	}

	// Raster specific
	if (item instanceof Raster) {
		equals(item.size.toString(), item2.size.toString(),
				'Compare Raster#size');
		compareNumbers(item.width, item2.width, 'Compare Raster#width');
		compareNumbers(item.height, item2.height, 'Compare Raster#height');

		equals(item.ppi.toString(), item2.ppi.toString(),
				'Compare Raster#ppi');

		equals(item.source, item2.source, 'Compare Raster#source');
		if (checkIdentity) {
			equals(item.image, item2.image, 'Compare Raster#image');
		}
		equals(item.size.toString(), item2.size.toString(),
				'Compare Raster#size');
		equals(item.toDataURL() == item2.toDataURL(), true,
				'Compare Raster#toDataUrl()');
	}

	// TextItem specific:
	if (item instanceof TextItem) {
		equals(item.content, item2.content, 'Compare Item#content');
	}

	// PointText specific:
	if (item instanceof PointText) {
		if (checkIdentity) {
			equals(function() {
				return item.point !== item2.point;
			}, true);
		}
		equals(item.point.toString(), item2.point.toString(),
				'Compare Item#point');
	}

	if (item.style) {
		// Style
		compareStyles(item.style, item2.style, checkIdentity);
	}

	// Check length of children and recursively compare them:
	if (item.children) {
		equals(function() {
			return item.children.length == item2.children.length;
		}, true);
		for (var i = 0, l = item.children.length; i < l; i++) {
			compareItems(item.children[i], item2.children[i], cloned,
					checkIdentity, dontShareProject);
		}
	}
}

function compareProjects(project, project2) {
	// Compare Project#symbols:
	equals(function() {
		return project.symbols.length == project2.symbols.length;
	}, true);
	for (var i = 0, l = project.symbols.length; i < l; i++) {
		var definition1 = project.symbols[i].definition;
		var definition2 = project2.symbols[i].definition;
		compareItems(definition1, definition2, false, false, true,
				'Compare Symbol#definition');
	}

	// Compare Project#layers:
	equals(function() {
		return project.layers.length == project2.layers.length;
	}, true);
	for (var i = 0, l = project.layers.length; i < l; i++) {
		compareItems(project.layers[i], project2.layers[i], false, false, true);
	}
}

// SVG

function createSVG(xml) {
	return new DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg">' + xml + '</svg>', 'application/xml');
}


text:
layout: post
title: Serverless GIS
date: 2017-10-25
duration: 2017.09 - Present
image: /assets/img/projects/serverless.jpg
link: https://serverless-gis.com
description: Serverless GIS is aimed at providing an alternative access to easily manipulate and manage your geo-datasets. The tech-stack is made up of Serverless, AWS Lambda, DynamoDB, S3, Cognito, CloudFront, React, Mapbox GL and Antd.
categories: [project]
tags: [project]
---


text:
package com.github.dieterdepaepe.jsearch.datastructure.priority;

/**
 * A data container used by a {@link FibonacciHeap} to store and organize data owned by that heap. Each entry can
 * be owned by at most a single {@code FibonacciHeap}, this owning heap should be used to perform any actions involving
 * this entry.
 *
 * @author Dieter De Paepe
 */
public class FibonacciHeapEntry<K, V> {
    V value;
    K key;
    FibonacciHeapEntry<K, V> parent;
    FibonacciHeapEntry<K, V> nextSibling;
    FibonacciHeapEntry<K, V> prevSibling;
    FibonacciHeapEntry<K, V> child;
    /** The number of children of this entry */
    int degree;
    boolean marked;

    /**
     * Creates a new unmarked entry that contains no references.
     * @param key the priority key
     * @param value the value to store in this entry
     */
    FibonacciHeapEntry(K key, V value) {
        this.value = value;
        this.key = key;
    }

    /**
     * Returns whether this entry has been cleared of its sibling references (indicating it has been removed from its heap).
     * @return true if the entry has been removed from its heap
     */
    boolean hasBeenRemoved() {
        return nextSibling == null;
    }

    /**
     * Returns the value stored in this entry.
     * @return the stored value
     */
    public V getValue() {
        return value;
    }

    /**
     * Replaces the value stored in this entry.
     * @param value the new value
     */
    public void setValue(V value) {
        this.value = value;
    }

    /**
     * Gets the key stored in this entry.
     * @return the key value
     * @see FibonacciHeap#decreaseKey(FibonacciHeapEntry, Object)
     */
    public K getKey() {
        return key;
    }

    @Override
    public String toString() {
        return "FibonacciHeapEntry{" +
                key + ", " +
                value +
                '}';
    }
}


text:
package com.alibaba.rocketmq.broker.processor;

import com.alibaba.rocketmq.broker.BrokerController;
import com.alibaba.rocketmq.common.constant.LoggerName;
import com.alibaba.rocketmq.remoting.netty.NettyRequestProcessor;
import com.alibaba.rocketmq.remoting.protocol.RemotingCommand;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author shijia.wxr
 */
public class ForwardRequestProcessor implements NettyRequestProcessor {
    private static final Logger log = LoggerFactory.getLogger(LoggerName.BrokerLoggerName);

    private final BrokerController brokerController;

    public ForwardRequestProcessor(final BrokerController brokerController) {
        this.brokerController = brokerController;
    }

    @Override
    public RemotingCommand processRequest(ChannelHandlerContext ctx, RemotingCommand request) {
        return null;
    }

    @Override
    public boolean rejectRequest() {
        return false;
    }
}


text:
@Master['_layout.html']

@Section['navbar']

<button type="button" class="pull-right navbar-btn btn btn-default" onclick='window.location.href="@Path['~/register']"'>Register</button>

@EndSection

@Section['Content']

Sign In

Need an account? Register

  <form class="form-horizontal" method="post" role="form">

        <input type="text" class="form-control" name="username" id="username" placeholder="Username or Email">

        <input type="password" class="form-control" name="password" id="password" placeholder="Password">

            <input type="checkbox"> Remember me

        <button type="submit" class="btn btn-primary">Sign in</button>

    @If.Error

@Model.ErrorHeading

@Model.ErrorMessage

    @EndIf
  </form>

@EndSection


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

package eu.danieldk.dictomaton.collections;

import eu.danieldk.dictomaton.DictionaryBuilder;
import eu.danieldk.dictomaton.DictionaryBuilderException;
import eu.danieldk.dictomaton.PerfectHashDictionary;

import java.io.Serializable;
import java.util.*;

/**
 * An immutable mapping from {@link String} to <tt>int</tt>.
 */
public class ImmutableStringIntMap extends AbstractMap<String, Integer> implements Serializable {
    private static final long serialVersionUID = 1L;

    private final PerfectHashDictionary d_keys;
    private final int[] d_values;

    /**
     * A builder for {@link ImmutableStringIntMap}. Mappings
     * can be added to the builder using the {@link #put} and
     * {@link #putAll} methods. The {@link ImmutableStringIntMap}
     * can then be constructed using the {@link #build} method.
     */
    public static class Builder {

        private final TreeMap<String, Integer> d_map;

        public Builder() {
            d_map = new TreeMap<>();
        }

        /**
         * Put a key/value pair.
         */
        public synchronized Builder put(String key, Integer value) {
            d_map.put(key, value);
            return this;
        }

        /**
         * Put all key/value pairs from a {@link Map}.
         */
        public synchronized Builder putAll(Map<String, Integer> map) {
            d_map.putAll(map);
            return this;
        }

        /**
         * Construct a {@link ImmutableStringIntMap}.
         */
        public synchronized ImmutableStringIntMap build() throws DictionaryBuilderException {
            PerfectHashDictionary dict = new DictionaryBuilder().addAll(d_map.keySet()).buildPerfectHash(false);

            int[] values = new int[d_map.size()];

            int i = 0;
            for (int value : d_map.values())
                values[i++] = value;

            return new ImmutableStringIntMap(dict, values);
        }

    }

    /**
     * A builder for {@link ImmutableStringIntMap}. Mappings can be added to the builder using the {@link #put} and
     * {@link #putAll} methods. The {@link ImmutableStringIntMap} can then be constructed using the {@link #build}
     * method. <b>Note:</b> This builder assumes that entries are put in key order. This additional assumption makes
     * the builder more efficient than {@link Builder}.
     */
    public static class OrderedBuilder {
        private final DictionaryBuilder dictionaryBuilder;

        private final ArrayList<Integer> values;

        public OrderedBuilder() {
            this.dictionaryBuilder = new DictionaryBuilder();
            this.values = new ArrayList<>();
        }

        /**
         * Put a key/value pair.
         */
        public synchronized OrderedBuilder put(String key, Integer value) throws DictionaryBuilderException {
            dictionaryBuilder.add(key);
            values.add(value);
            return this;
        }

        /**
         * Put all key/value pairs from a {@link Map}. The map should be an ordered map (by key). If
         * not, a {@link IllegalArgumentException} is thrown.
         */
        public synchronized OrderedBuilder putAll(SortedMap<String, Integer> map) throws DictionaryBuilderException {
            if (map.comparator() != null)
                throw new IllegalArgumentException("SortedMap does not use the natural ordering of its keys");

            values.ensureCapacity(values.size() + map.size());

            for (SortedMap.Entry<String, Integer> entry: map.entrySet()) {
                dictionaryBuilder.add(entry.getKey());
                values.add(entry.getValue());
            }

            return this;
        }

        /**
         * Construct a {@link ImmutableStringIntMap}.
         */
        public synchronized ImmutableStringIntMap build() throws DictionaryBuilderException {
            PerfectHashDictionary dict = dictionaryBuilder.buildPerfectHash(false);

            int[] arr = new int[values.size()];

            for (int i = 0; i < values.size(); ++i)
                arr[i] = values.get(i);

            return new ImmutableStringIntMap(dict, arr);
        }
    }

    private class EntrySet extends AbstractSet<Entry<String, Integer>> {
        private class EntrySetIterator implements Iterator<Entry<String, Integer>> {
            private final Iterator<String> d_keyIter;

            public EntrySetIterator() {
                d_keyIter = d_keys.iterator();
            }

            @Override
            public boolean hasNext() {
                return d_keyIter.hasNext();
            }

            @Override
            public Entry<String, Integer> next() {
                String key = d_keyIter.next();
                int idx = d_keys.number(key) - 1;
                return new SimpleEntry<>(key, d_values[idx]);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        }

        @Override
        public boolean contains(Object o) {
            if (o == null)
                return false;

            if (!(o instanceof Entry))
                return false;

            Entry e = (Entry) o;

            // Values are primitive and cannot be null.
            if (e.getKey() == null || e.getKey() == null)
                return false;

            if (!(e.getKey() instanceof String) || !(e.getValue() instanceof Integer))
                return false;

            String key = (String) e.getKey();
            Integer value = (Integer) e.getValue();

            int hash = d_keys.number(key);

            // Does not contain the key.
            if (hash == -1)
                return false;

            return d_values[hash - 1] == value;

        }

        @Override
        public boolean isEmpty()  {
            return d_keys.isEmpty();
        }

        @Override
        public Iterator<Entry<String, Integer>> iterator() {
            return new EntrySetIterator();
        }

        @Override
        public int size() {
            return d_keys.size();
        }
    }

    private class IntArrayList extends AbstractList<Integer> {
        @Override
        public Integer get(int index) {
            return d_values[index];
        }

        @Override
        public int size() {
            return d_values.length;
        }
    }

    private ImmutableStringIntMap(PerfectHashDictionary keys, int[] values) {
        d_keys = keys;
        d_values = values;
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsKey(Object o) {
        return d_keys.contains(o);
    }

    @Override
    public Set<Entry<String, Integer>> entrySet() {
        return new EntrySet();
    }

    @Override
    public Integer get(Object o) {
        if (!(o instanceof String))
            return null;

        String key = (String) o;

        int hashcode = d_keys.number(key);
        if (hashcode == -1)
            return null;

        return d_values[hashcode - 1];
    }

    /**
     * Get the value associated with a key, returning a default value is it
     * is not in the mapping.
     */
    public int getOrElse(String key, int defaultValue) {
        int hash = d_keys.number(key);
        if (hash == -1)
            return defaultValue;

        return d_values[hash - 1];
    }

    @Override
    public boolean isEmpty() {
        return d_keys.isEmpty();
    }

    @Override
    public Set<String> keySet() {
        return d_keys;
    }

    @Override
    public Integer put(String k, Integer v) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map<? extends String, ? extends Integer> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Integer remove(Object key) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int size() {
        return d_keys.size();
    }

    /**
     * Get an iterator over the keys in the mapping.
     */
    public Iterator<String> keyIterator() {
        return d_keys.iterator();
    }

    @Override
    public Collection<Integer> values() {
        return new IntArrayList();
    }
}


text:
function lintblock(ex::Expr, ctx::LintContext)
    lastexpr = nothing
    similarexprs = Expr[]
    diffs = Float64[]
    checksimilarityflag = !(LintIgnore(:W651, "") in ctx.ignore)

    if checksimilarityflag
        checksimilarity = ()->begin
            if length(similarexprs) <= 2 # not much I can do
                diffs = Float64[]
                lastexpr = nothing
                similarexprs = Expr[]
            else
                # cyclic diffs, so now we have at least 3 similarity scores
                push!(diffs, expr_similar_score(similarexprs[1], similarexprs[end]))
                local n = length(diffs)
                local m = mean(diffs)
                local s = std(diffs)
                local m2 = mean([diffs[end-1], diffs[end]])
                # look for screw up at the end
                #println(diffs, "\nm=", m, " s=", s, " m2=", m2, " m-m2=", m-m2)
                if m2 < m && m-m2 > s/2.5 && s / m > 0.0001
                    msg(ctx, :W651, "the last of a $(n)-expr block looks different" *
                        ";  Avg similarity score: " * @sprintf("%8.2f", m) *
                        ";  Last part: " * @sprintf("%9.2f", m2))
                end
                diffs = Float64[]
                lastexpr = nothing
                similarexprs = Expr[]
            end
        end
    end

    for (i,sube) in enumerate(ex.args)
        if typeof(sube) == Expr
            if sube.head == :line
                ctx.line = sube.args[1]-1
                #=
                # We don't use the file argument since it is inaccurate
                # as of 0.4.0-dev+1833
                if length(sube.args)>1
                    file= string(sube.args[2])
                    if file != "none"
                        ctx.file = file
                    end
                end
                =#
                continue
            elseif sube.head == :return && i != length(ex.args)
                msg(ctx, :W641, "unreachable code after return")
                lintexpr(sube, ctx)
                break
            else
                if checksimilarityflag
                    if lastexpr != nothing
                        local dif = expr_similar_score(lastexpr, sube)
                        if dif > SIMILARITY_THRESHOLD
                            if !isempty(similarexprs)
                                append!(similarexprs, [lastexpr, sube])
                            else
                                push!(similarexprs, sube)
                            end
                            push!(diffs, dif)
                        else
                            checksimilarity()
                        end
                    end
                end
                lintexpr(sube, ctx)
                lastexpr = sube
            end
        elseif typeof(sube) == QuoteNode
            lintexpr(sube,ctx)
        elseif typeof(sube) == LineNumberNode
            ctx.line = sube.line-1
            continue
        elseif typeof(sube) == Symbol
            registersymboluse(sube, ctx)
            if checksimilarityflag
                checksimilarity()
            end
        end
    end

    if checksimilarityflag
        checksimilarity()
    end
end

function expr_similar_score(e1::Expr, e2::Expr, base::Float64 = 1.0)
    if e1.head != e2.head
        return -base
    end

    score = base - abs(length(e1.args) - length(e2.args)) * base * 2.0

    for i in 1:min(length(e1.args), length(e2.args))
        if typeof(e1.args[i]) == Expr && typeof(e2.args[i]) == Expr
            score += expr_similar_score(e1.args[i], e2.args[i], base * 1.1)
        elseif typeof(e1.args[i]) == typeof(e2.args[i])
            score += base * 0.3
            if e1.args[i] == e2.args[i]
                score += base * 0.8
            end
        else
            score -= base
        end
        if score < 0.0 # so early disagreement dominates and short-circuit
            break
        end
    end
    return score
end

function test_similarity_string{T<:AbstractString}(str::T)
    i = start(str)
    firstexpr = nothing
    lastexpr = nothing
    diffs = Float64[]
    while !done(str,i)
        problem = false
        ex = nothing
        try
            (ex, i) = parse(str,i)
        catch
            problem = true
        end
        if !problem
            if firstexpr == nothing
                firstexpr = ex
            end
            if lastexpr != nothing
                push!(diffs, expr_similar_score(lastexpr, ex))
            end
            lastexpr = ex
        else
            break
        end
    end
    if lastexpr != nothing && length(diffs) >= 2
        push!(diffs, expr_similar_score(lastexpr, firstexpr))
    end
    return diffs
end

function linttry(ex::Expr, ctx::LintContext)
    pushVarScope(ctx)
    stacktop = ctx.callstack[end]
    lintexpr(ex.args[1], ctx)
    popVarScope(ctx)
    if typeof(ex.args[2]) == Symbol
        stacktop.localvars[end][ex.args[2]] = VarInfo(ctx.line)
    end
    for i in 3:length(ex.args)
        pushVarScope(ctx)
        lintexpr(ex.args[i], ctx)
        popVarScope(ctx)
    end
end

function lintlet(ex::Expr, ctx::LintContext)
    if ctx.macroLvl == 0
        pushVarScope(ctx)
    end

    ctx.functionLvl += 1
    for j = 2:length(ex.args)
        # it's always assignment, or the parser would have thrown at the very start
        if isexpr(ex.args[j], :(=)) && !isexpr(ex.args[j].args[1], :call)
            lintassignment(ex.args[j], :(=), ctx; islocal = true)
        end
    end
    blk = ex.args[1]
    @assert(blk.head == :block)
    for i = 1:length(blk.args)
        if isexpr(blk.args[i], :(=)) && !isexpr(blk.args[i].args[1], :call)
            lintassignment(blk.args[i], :(=), ctx; islocal = true)
        else
            lintexpr(blk.args[i], ctx)
        end
    end
    ctx.functionLvl -= 1

    if ctx.macroLvl == 0
        popVarScope(ctx)
    end
end


text:
Smart way of organizing your sandbox/root folder with dynamic search capabilities so no matter how big or how small your sandbox/root folder gets, you can easily find your projects.

## About
This came to mind when I realized how often I would just forget the name or simply had to many folders on my sandbox environment, this is a local site where i just mess around for creating quick prototypes and ideas.

So I created an easy way to display all folders in my sandbox environment with search capabilities.

This has proven a very useful "tool" to have has the years went by for the young developers I have mentored, providing them with an easy and quick way to jump strait into coding while keeping things organized.

Now I have also released a sandbox environment for Docker, where you can use this. Find out more in this [repo](https://github.com/Mario-Duarte/docker-smart-sandbox).

![smartsandbox demo](https://github.com/Mario-Duarte/Smart-Sandbox/blob/master/smartsandbox-demo_v3.gif?raw=true)

## New Features on 3.0
- New modern design
- Better search
- Improved theme detection and selection
- Bug fixes

## installation
Download the latest release from [here](https://github.com/Mario-Duarte/Smart-Sandbox/releases) or copy the index.php at the root of this repo into your desired location.

### Tip
Set up a domain on you local machine as dev.sandbox.com and place this index.php at the root level of that domain alternatively you could just place this at the root level of your htdocs if you use software like mamp/xamp/wamp, etc.

### Requirements

- PHP (with read access to the folders)
- JavaScript
- modern browser (chrome, firefox, safari or edge)

If you require legacy browser support check out an older version of this tool [here (<v2.1)](https://github.com/Mario-Duarte/Smart-Sandbox/releases).

That's it really, all the magic is done with php and javascript.

__Found a bug? Want to help to make this tool better?__
Contact me via [Twitter](https://twitter.com/MDesignsuk)


text:
package com.grapp.soosec.viewmodel;

import com.grapp.soosec.BuildConfig;
import com.grapp.soosec.MainActivity;
import com.grapp.soosec.RegisterStep1Activity;
import com.grapp.soosec.api.model.Registro;
import com.grapp.soosec.common.mvvm.base.UIFormViewModel;
import com.grapp.soosec.common.mvvm.fields.UICommand;
import com.grapp.soosec.common.mvvm.fields.UIString;
import com.grapp.soosec.api.model.Usuario;
import com.grapp.soosec.api.authentication.Authenticate;
import com.grapp.soosec.api.error.FailResponse;
import com.grapp.soosec.viewmodel.common.ViewModelPopulateHelper;
import com.grapp.validation.annotation.Email;
import com.grapp.validation.annotation.NotEmpty;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginViewModel extends UIFormViewModel {
    @Email
    public final UIString email;
    @NotEmpty
    public final UIString password;

    public final UICommand commandSignIn;
    public final UICommand commandSignUp;

    public LoginViewModel() {
        email = new UIString();
        password = new UIString();

        commandSignIn = new UICommand(
                this::submit,
                () -> true);

        commandSignUp = new UICommand(
                () -> navigateTo(RegisterStep1Activity.class),
                () -> true);

        if (BuildConfig.DEBUG) {
            ViewModelPopulateHelper.populate(this);
        }
    }

    @Override
    protected String internalGetTitle() {
        return "Entrar";
    }

    @Override
    protected boolean internalSubmit() {
        view().beginInteractWithProgress();

        remoteSvc()
                .authenticate(new Authenticate(email.get(), password.get()))
                .enqueue(
                new Callback<Usuario>() {
                    @Override
                    public void onResponse(Call<Usuario> call, Response<Usuario> response) {
                        view().endInteractWithProgress();

                        if(response.isSuccessful()) {
                            Usuario usuario = response.body();

                            // TODO: Ajustar o logon
                            view().app().logon(new Registro());

                            navigateTo(MainActivity.class);
                            view().finish();
                        } else {
                            FailResponse apiError = FailResponse.create(component().retrofit(), response);
                            view().interactWithMessage(apiError.message());
                        }
                    }

                    @Override
                    public void onFailure(Call<Usuario> call, Throwable t) {
                        view().endInteractWithProgress();
                        view().interactWithMessage(t);
                    }
                });

        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334641 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.gmp-rootrem">
 <refnamediv>
  <refname>gmp_rootrem</refname>
  <refpurpose>Take the integer part and remainder of nth root</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>array</type><methodname>gmp_rootrem</methodname>
   <methodparam><type>GMP</type><parameter>a</parameter></methodparam>
   <methodparam><type>int</type><parameter>nth</parameter></methodparam>
  </methodsynopsis>
  <para>
   Takes the <parameter>nth</parameter> root of <parameter>a</parameter> and
   returns the integer component and remainder of the result.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>a</parameter></term>
     <listitem>
      &gmp.parameter;
     </listitem>
    </varlistentry>
    <varlistentry>
     <term><parameter>nth</parameter></term>
     <listitem>
      <para>
       The positive root to take of <parameter>a</parameter>.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   A two element array, where the first element is the integer component of
   the root, and the second element is the remainder, both represented as GMP
   numbers.
  </para>
 </refsect1>
</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
package com.wolfsoft.epower;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class Question2 extends Activity {

	int total;
	int waittime=3000;
	int i = 0;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.question2);

		Intent intent = getIntent();

		total = intent.getIntExtra("total", 0);

		// get action bar
        ActionBar actionBar = getActionBar();
        // Enabling Up / Back navigation
        actionBar.setDisplayHomeAsUpEnabled(true);

		findViewById(R.id.wrong1).setOnClickListener(new View.OnClickListener() {

		    @Override
		    public void onClick(View v) {

		    	Toast display= Toast.makeText(getApplicationContext(),
			   			 "Wrong Answer", 0);

			   				display.setGravity(Gravity.BOTTOM, 0, 0);
			   				display.setDuration(Toast.LENGTH_SHORT);
			   			    display.show();

		    	TextView right = (TextView)findViewById(R.id.right);
				TextView wrong1 = (TextView)findViewById(R.id.wrong1);
				wrong1.setTextColor(Color.parseColor("#ED2E2E"));
				right.setTextColor(Color.parseColor("#3775A6"));

				Thread mythread = new Thread() {
					public void run() {
					try {
					while (i < waittime) {

					i=i+200;
					sleep(100);

					}
					}
					catch(Exception e) {}
					finally {
					Intent q2 = new Intent(Question2.this, Question3.class);
					q2.putExtra("total", total);
					startActivity(q2);
					 overridePendingTransition(R.anim.anim_slide_in_left,
				                R.anim.anim_slide_out_right);
					}
					}
					};
					mythread.start();
					}
		    });

		findViewById(R.id.wrong2).setOnClickListener(new View.OnClickListener() {

		    @Override
		    public void onClick(View v) {

		    	Toast display= Toast.makeText(getApplicationContext(),
			   			 "Wrong Answer", 0);

			   				display.setGravity(Gravity.BOTTOM, 0, 0);
			   				display.setDuration(Toast.LENGTH_SHORT);
			   			    display.show();

		    	TextView right = (TextView)findViewById(R.id.right);
				TextView wrong2 = (TextView)findViewById(R.id.wrong2);
				wrong2.setTextColor(Color.parseColor("#ED2E2E"));
				right.setTextColor(Color.parseColor("#3775A6"));

				Thread mythread = new Thread() {
					public void run() {
					try {
					while (i < waittime) {

					i=i+200;
					sleep(100);

					}
					}
					catch(Exception e) {}
					finally {
					Intent q2 = new Intent(Question2.this, Question3.class);
					q2.putExtra("total", total);
					startActivity(q2);
					 overridePendingTransition(R.anim.anim_slide_in_left,
				                R.anim.anim_slide_out_right);
					}
					}
					};
					mythread.start();
					}
		    });

		findViewById(R.id.right).setOnClickListener(new View.OnClickListener() {

		    @Override
		    public void onClick(View v) {

		    	Toast display= Toast.makeText(getApplicationContext(),
			   			 "Right Answer", 0);

			   				display.setGravity(Gravity.BOTTOM, 0, 0);
			   				display.setDuration(Toast.LENGTH_SHORT);
			   			    display.show();

		    	total+=10;

		    	TextView right = (TextView)findViewById(R.id.right);
				right.setTextColor(Color.parseColor("#3775A6"));

				Thread mythread = new Thread() {
					public void run() {
					try {
					while (i < waittime) {

					i=i+200;
					sleep(100);

					}
					}
					catch(Exception e) {}
					finally {
					Intent q2 = new Intent(Question2.this, Question3.class);
					q2.putExtra("total", total);
					startActivity(q2);
					 overridePendingTransition(R.anim.anim_slide_in_left,
				                R.anim.anim_slide_out_right);
					}
					}
					};
					mythread.start();
					}
		    });

	}

	public void hint(View v)
	{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

		alertDialogBuilder.setTitle("Hint!!");
		alertDialogBuilder
		.setMessage("White color reflects 80% of the light, any light color can be painted in room to get more light and hence to save power")
		.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				// if this button is clicked, close
				// current activity
				dialog.cancel();
			}
		  });
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case android.R.id.home:
			Intent intent = new Intent(this,MainActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(intent);
			 overridePendingTransition(R.anim.anim_slide_in_left,
		                R.anim.anim_slide_out_right);
	            default:
	            return super.onOptionsItemSelected(item);
	    }
	}

}


text:
<?php

namespace Sentinnel\CoreBundle\Controller;

use Sentinnel\CoreBundle\Manager\LogsManager;
use Sentinnel\CoreBundle\Manager\ProfilerManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpKernel\Profiler\FileProfilerStorage;

/**
 * Class LogsController
 * @package Sentinnel\CoreBundle\Controller
 *
 * @Route("/logs")
 */
class LogsController extends Controller
{
    /**
     * @Route("/", name="logs_list")
     */
    public function indexAction()
    {
        $systemDir = '/home/cinfante/htdocs/www/buses.taller';
        $dir = $systemDir . '/app/logs/prod.log';

        $logsManager = new LogsManager();

        $logs = $logsManager->findAll($dir);
//        $grep = preg_grep("#^\[2015-06-07 11:30:17\]#", $logs);

        $grep = preg_grep("#ERROR#", $logs);
        var_dump($grep);die;
        return $this->render('@SentinnelCore/Logs/index.html.twig', array(
            'logs' => $logs,
        ));
    }
}


text:
TEST_F(RasterImplementationTest, Flush) {
  struct Cmds {
    cmds::Flush cmd;
  };
  Cmds expected;
  expected.cmd.Init();

  gl_->Flush();
  EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
}

TEST_F(RasterImplementationTest, GenQueriesEXT) {
  GLuint ids[2] = {
      0,
  };
  struct Cmds {
    cmds::GenQueriesEXTImmediate gen;
    GLuint data[2];
  };
  Cmds expected;
  expected.gen.Init(base::size(ids), &ids[0]);
  expected.data[0] = kQueriesStartId;
  expected.data[1] = kQueriesStartId + 1;
  gl_->GenQueriesEXT(base::size(ids), &ids[0]);
  EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
  EXPECT_EQ(kQueriesStartId, ids[0]);
  EXPECT_EQ(kQueriesStartId + 1, ids[1]);
}

TEST_F(RasterImplementationTest, DeleteQueriesEXT) {
  GLuint ids[2] = {kQueriesStartId, kQueriesStartId + 1};
  struct Cmds {
    cmds::DeleteQueriesEXTImmediate del;
    GLuint data[2];
  };
  Cmds expected;
  expected.del.Init(base::size(ids), &ids[0]);
  expected.data[0] = kQueriesStartId;
  expected.data[1] = kQueriesStartId + 1;
  gl_->DeleteQueriesEXT(base::size(ids), &ids[0]);
  EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
}

TEST_F(RasterImplementationTest, LoseContextCHROMIUM) {
  struct Cmds {
    cmds::LoseContextCHROMIUM cmd;
  };
  Cmds expected;
  expected.cmd.Init(GL_GUILTY_CONTEXT_RESET_ARB, GL_GUILTY_CONTEXT_RESET_ARB);

  gl_->LoseContextCHROMIUM(GL_GUILTY_CONTEXT_RESET_ARB,
                           GL_GUILTY_CONTEXT_RESET_ARB);
  EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected)));
}
#endif  // GPU_COMMAND_BUFFER_CLIENT_RASTER_IMPLEMENTATION_UNITTEST_AUTOGEN_H_


text:
class BrainsController < ApplicationController
  include Errship::ActiveRecord::Rescuers

  def index
    raise ActiveRecord::RecordNotFound.new
  end
end


text:
// source:

package nl.uva.vlet.vjs.wms;

import org.glite.wsdl.types.lb.JobStatus;

public class JobEvent
{
    public static enum JobEventType
    {
        NEW_JOB, UPDATE_STATUS, UPDATE_USERJOBS;
    }

    private long eventTime = -1;

    private JobEventType type;

    private String jobIds[];

    private JobStatus jobStatus;

    private JobEvent(JobEventType type)
    {
        eventTime = System.currentTimeMillis();
        this.type = type;
    }

    public JobEventType getType()
    {
        return type;
    }

    public long getTime()
    {
        return this.eventTime;
    }

    public boolean isType(JobEventType type)
    {
        return (this.type == type);
    }

    public JobStatus getJobStatus()
    {
        return this.jobStatus;
    }

    public String getStatusString()
    {
        if (this.jobStatus == null)
            return null;

        return jobStatus.getState().getValue();
    }

    public String getJobID()
    {
        if (jobIds == null)
            return null;
        return jobIds[0];
    }

    public String[] getUserJobs()
    {
        return jobIds;
    }

    public String toString()
    {
        String id = getJobID();
        String info = getStatusString();

        if (this.type == JobEventType.UPDATE_USERJOBS)
        {
            id = "<first id>" + id;
            info = "#" + this.jobIds.length + " userjobs";
        }

        return "<JobEvent>{" + type + ":" + id + ":" + info + "}";
    }

    public static JobEvent createStatusEvent(JobStatus status)
    {
        if (status == null)
            throw new NullPointerException("JobStatus can not be NULL");

        JobEvent event = new JobEvent(JobEventType.UPDATE_STATUS);
        event.jobIds = new String[] { status.getJobId() };
        event.jobStatus = status;
        return event;
    }

    public static JobEvent createNewJobEvent(String id)
    {
        if (id == null)
            throw new NullPointerException("JobId can not be NULL");

        JobEvent event = new JobEvent(JobEventType.NEW_JOB);
        event.jobStatus = null;
        event.jobIds = new String[] { id };
        return event;
    }

    public static JobEvent createUpdateUserJobs(String[] jobarr)
    {
        if (jobarr == null)
            throw new NullPointerException("JobId array can not be NULL");

        JobEvent event = new JobEvent(JobEventType.UPDATE_USERJOBS);
        event.jobIds = jobarr;
        return event;
    }
}


text:
module Rbeapi
  VERSION = '1.3'.freeze
end


text:
using gpu::gles2::GLES2Interface;

namespace cc {

ScopedGpuRaster::ScopedGpuRaster(viz::ContextProvider* context_provider)
    : context_provider_(context_provider) {
  BeginGpuRaster();
}

ScopedGpuRaster::~ScopedGpuRaster() {
  EndGpuRaster();
}

void ScopedGpuRaster::BeginGpuRaster() {
  GLES2Interface* gl = context_provider_->ContextGL();

  // TODO(alokp): Use a trace macro to push/pop markers.
  // Using push/pop functions directly incurs cost to evaluate function
  // arguments even when tracing is disabled.
  gl->TraceBeginCHROMIUM("ScopedGpuRaster", "GpuRasterization");

#if defined(OS_ANDROID)
  // TODO(crbug.com/832810): The following reset should not be necessary.
  GrDirectContext* gr_context = context_provider_->GrContext();
  gr_context->resetContext();
#endif
}

void ScopedGpuRaster::EndGpuRaster() {
  GLES2Interface* gl = context_provider_->ContextGL();

  // Restore default GL unpack alignment.  TextureUploader expects this.
  gl->PixelStorei(GL_UNPACK_ALIGNMENT, 4);

  // TODO(alokp): Use a trace macro to push/pop markers.
  // Using push/pop functions directly incurs cost to evaluate function
  // arguments even when tracing is disabled.
  gl->TraceEndCHROMIUM();
}

}  // namespace cc


text:
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""

import re

from lib.core.enums import HTTP_HEADER
from lib.core.settings import WAF_ATTACK_VECTORS

__product__ = "Barracuda Web Application Firewall (Barracuda Networks)"

def detect(get_page):
    retval = False

    for vector in WAF_ATTACK_VECTORS:
        page, headers, code = get_page(get=vector)
        retval = re.search(r"\Abarra_counter_session=", headers.get(HTTP_HEADER.SET_COOKIE, ""), re.I) is not None
        if retval:
            break

    return retval


text:
#ifndef _RTPP_DEFINES_H_
#define _RTPP_DEFINES_H_

/*
 * Version of the command protocol, bump only when backward-incompatible
 * change is introduced
 */
#define	CPROTOVER	20040107

#define	PORT_MIN	35000
#define	PORT_MAX	65000
#define	TIMETICK	1	/* in seconds */
#define	SESSION_TIMEOUT	60	/* in ticks */
#define	TOS		0xb8
#define	LBR_THRS	128	/* low-bitrate threshold */
#define	CPORT		"22222"
#define	MAX_RTP_RATE	100
#define	POLL_RATE	(MAX_RTP_RATE * 2)	/* target number of poll(2) calls per second */
#define	LOG_LEVEL	RTPP_LOG_DBUG
#define	UPDATE_WINDOW	10.0	/* in seconds */
#define	PCAP_FORMAT	DLT_EN10MB

/* Dummy service, getaddrinfo needs it */
#define	SERVICE		"34999"

#define	CMD_SOCK	"/var/run/rtpproxy.sock"
#define	PID_FILE	"/var/run/rtpproxy.pid"

struct pollfd;
struct bindaddr_list;
struct rtpp_timeout_handler;

struct sessinfo {
    struct pollfd *pfds_rtp;
    struct pollfd *pfds_rtcp;
    struct rtpp_session **sessions;
    int nsessions;
    pthread_mutex_t lock;
};

struct rtpp_hash_table_obj;
struct rtpp_cfg_stable;

struct cfg {
    struct rtpp_cfg_stable *stable;

    /*
     * Data fields that must be locked separately from the main configuration
     * structure below.
     */
    struct sessinfo sessinfo;

    struct bindaddr_list *bindaddr_list;
    pthread_mutex_t bindaddr_lock;

    /* Structures below are protected by the glock */
    struct rtpp_session **rtp_servers;

    int rtp_nsessions;
    int sessions_active;
    unsigned long long sessions_created;
    int nofile_limit_warned;

    struct rtpp_timeout_handler *timeout_handler;

    int port_table_idx;

    pthread_mutex_t glock;
};

#endif


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

package com.google.security.zynamics.reil.interpreter;

import java.math.BigInteger;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.reil.OperandSize;

/**
 * Used by the interpreter to keep track of the values of the registers during interpretation of
 * REIL code.
 */
public class ReilRegister {
  /**
   * Name of the register
   */
  private final String register;

  /**
   * Size of the register
   */
  private final OperandSize size;

  /**
   * Value of the register
   */
  private final BigInteger value;

  /**
   * Creates a new REIL register object.
   *
   * @param register Name of the register
   * @param size Size of the register
   * @param value Value of the register
   */
  public ReilRegister(final String register, final OperandSize size, final BigInteger value) {
    this.register = Preconditions.checkNotNull(register, "Error: Argument register can't be null");
    this.size = Preconditions.checkNotNull(size, "Error: Argument size can't be null");
    this.value = value;
  }

  /**
   * Returns the name of the register.
   *
   * @return The name of the register
   */
  public String getRegister() {
    return register;
  }

  /**
   * Returns the size of the register.
   *
   * @return The size of the register
   */
  public OperandSize getSize() {
    return size;
  }

  /**
   * Returns the value of the register.
   *
   * @return The value of the register
   */
  public BigInteger getValue() {
    return value;
  }

  @Override
  public String toString() {
    return String.format("%s: %s", register, value);
  }
}


text:
import { Lib } from './lib';
import type { Program } from 'typescript';
declare type DebugLevel = boolean | ('typescript-eslint' | 'eslint' | 'typescript')[];
declare type EcmaVersion = 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | 2022;
declare type SourceType = 'script' | 'module';
interface ParserOptions {
    ecmaFeatures?: {
        globalReturn?: boolean;
        jsx?: boolean;
    };
    ecmaVersion?: EcmaVersion | 'latest';
    jsxPragma?: string | null;
    jsxFragmentName?: string | null;
    lib?: Lib[];
    comment?: boolean;
    debugLevel?: DebugLevel;
    errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
    errorOnUnknownASTType?: boolean;
    EXPERIMENTAL_useSourceOfProjectReferenceRedirect?: boolean;
    extraFileExtensions?: string[];
    filePath?: string;
    loc?: boolean;
    program?: Program;
    project?: string | string[];
    projectFolderIgnoreList?: (string | RegExp)[];
    range?: boolean;
    sourceType?: SourceType;
    tokens?: boolean;
    tsconfigRootDir?: string;
    useJSXTextNode?: boolean;
    warnOnUnsupportedTypeScriptVersion?: boolean;
    moduleResolver?: string;
}
export { DebugLevel, EcmaVersion, ParserOptions, SourceType };
//# sourceMappingURL=parser-options.d.ts.map


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Persoonia 5(4): 500 (1969)

#### Original name
Amanita crassiconus Bas

### Remarks
null


text:
/*
 * $Id$
 *
 * Routines common to all platforms.
 */

#include <Python.h>

/*
 * Set OSError(errno=ESRCH, strerror="No such process") Python exception.
 */
PyObject *
NoSuchProcess(void) {
    PyObject *exc;
    char *msg = strerror(ESRCH);
    exc = PyObject_CallFunction(PyExc_OSError, "(is)", ESRCH, msg);
    PyErr_SetObject(PyExc_OSError, exc);
    Py_XDECREF(exc);
    return NULL;
}

/*
 * Set OSError(errno=EACCES, strerror="Permission denied") Python exception.
 */
PyObject *
AccessDenied(void) {
    PyObject *exc;
    char *msg = strerror(EACCES);
    exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg);
    PyErr_SetObject(PyExc_OSError, exc);
    Py_XDECREF(exc);
    return NULL;
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Freelancer - Start Bootstrap Theme</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

    <link href="css/freelancer.css" rel="stylesheet">

        Start Bootstrap
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

              Portfolio

              About

              Contact

What are you looking for? :D

<big><big><big>

Curious about life in certain careers?

Check out these search options!

                We'll help you find
 real people
working real jobs
that you might think are cool!</big></big></big>

Search

            <form name="sentMessage" id="contactForm" novalidate>

                  Name
                  <input class="form-control" id="name" type="text" placeholder="Name" ng-model="name">

                  Degree, University
                  <input class="form-control" id="company" type="text" placeholder="Degree, University" ng-model="degree">

                  Job Title
                  <input class="form-control" id="jobTitle" type="text" placeholder="Job Title" ng-model="jobTitle">

                  Company
                  <input class="form-control" id="company" type="text" placeholder="Company" ng-model="company">

                  City, State
                  <input class="form-control" id="state" type="text" placeholder="City, State" ng-model="location">

                <button type="submit" class="btn btn-success btn-lg" id="sendMessageButton" ng-click="submit()">Send</button>

            </form>

            {{result["name"]}}

              Copyright © Your Website 2017


text:
from flask import Flask, request, redirect, render_template, session, flash
import re
from mysqlconnection import MySQLConnector
app = Flask (__name__)
app.secret_key = 'kjndieuwh347'
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
mysql = MySQLConnector(app, 'email')

@app.route('/')
def index():
    email = mysql.query_db('SELECT * FROM email')
    print(email)
    return render_template('index.html')

@app.route('/add', methods = ['POST'])
def add():

    query = "INSERT INTO email (email, created_at, updated_at) VALUES(:email, NOW(), NOW())"
    data = {
        'email':request.form['email']
    }
    if len(data['email']) < 1:
        flash('Email field cannot be empty')
        return redirect('/')
    elif not EMAIL_REGEX.match(data['email']):
        flash('Please enter a valid email')
        return redirect('/')

    mysql.query_db(query,data)

    return redirect('/results')

@app.route('/results')
def results():
    flash('The email address you entered is Valid')
    query = 'SELECT * from email'
    datas= mysql.query_db(query)
    return render_template('results.html', emails=datas)

@app.route('/remove/<email_id>')
def delete(email_id):
    query = "DELETE FROM email WHERE id = :id"
    data = {'id' : email_id}
    mysql.query_db(query, data)
    flash("email has been delete")
    return redirect('/results')

app.run(debug=True)


text:
Create Connection

<mat-autocomplete #autocompleteFrom>
  <mat-option *ngFor="let entity of filteredEntitiesFrom | async" [value]="entity.name">
    {{ entity.name }} |
    {{ entity.time !== undefined ? 'transition' : 'pinnacle' }}
  </mat-option>
</mat-autocomplete>

<mat-autocomplete #autocompleteTo>
  <mat-option *ngFor="let entity of filteredEntitiesTo | async" [value]="entity.name">
    {{ entity.name }} |
    {{ entity.time !== undefined ? 'transition' : 'pinnacle' }}
  </mat-option>
</mat-autocomplete>

<form [formGroup]="connectionForm" (ngSubmit)="onSubmit()" novalidate>
  <mat-form-field>
    <input matInput placeholder="From" [matAutocomplete]="autocompleteFrom" formControlName="from">
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Value" type="number" formControlName="value">
    <mat-icon matSuffix>arrow_forward</mat-icon>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="To" [matAutocomplete]="autocompleteTo" formControlName="to">
  </mat-form-field>

  <button mat-raised-button color="primary" type="submit" [disabled]="connectionForm.invalid">Create</button>
  <mat-spinner [diameter]="40" *ngIf="spinner"></mat-spinner>
</form>


text:
using System.Collections.Generic;
using System.Linq;

namespace IronAssembler.Data
{
    /// <summary>
    /// Represents an assembled block containing assembled instructions.
    /// </summary>
    internal sealed class AssembledBlock
    {
        private readonly List<AssembledInstruction> instructions;

        /// <summary>
        /// Gets the name of the block.
        /// </summary>
        public string Name { get; }

        /// <summary>
        /// Gets a read-only list of assembled instructions within the block.
        /// </summary>
        public IReadOnlyList<AssembledInstruction> Instructions => instructions.AsReadOnly();

        /// <summary>
        /// Gets the size of this block in bytes.
        /// </summary>
        public ulong BlockSizeInBytes { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="AssembledBlock"/> class.
        /// </summary>
        /// <param name="name">The name of the block.</param>
        /// <param name="instructions">A sequence of assembled instructions.</param>
        /// <param name="blockSizeInBytes">The size of the assembled block in bytes.</param>
        public AssembledBlock(string name, IEnumerable<AssembledInstruction> instructions,
            ulong blockSizeInBytes)
        {
            Name = name;
            this.instructions = instructions.ToList();
            BlockSizeInBytes = blockSizeInBytes;
        }
    }
}


text:
from peewee import Model, SqliteDatabase

from config import DATABASE_PATH

database = SqliteDatabase(DATABASE_PATH)

class BaseModel(Model):
    class Meta:
        database = database