text:
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Topology.Topologies
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using GreenPipes;
    using Observers;
    using Util;

    public class SendTopology :
        ISendTopologyConfigurator,
        ISendTopologyConfigurationObserver
    {
        readonly IList<IMessageSendTopologyConvention> _conventions;
        readonly object _lock = new object();
        readonly ConcurrentDictionary<Type, IMessageSendTopologyConfigurator> _messageTypes;
        readonly SendTopologyConfigurationObservable _observers;

        public SendTopology()
        {
            _messageTypes = new ConcurrentDictionary<Type, IMessageSendTopologyConfigurator>();

            _observers = new SendTopologyConfigurationObservable();

            _conventions = new List<IMessageSendTopologyConvention>();
            _observers.Connect(this);
        }

        void ISendTopologyConfigurationObserver.MessageTopologyCreated<T>(IMessageSendTopologyConfigurator<T> messageTopology)
        {
            ApplyConventionsToMessageTopology(messageTopology);
        }

        public IMessageSendTopologyConfigurator<T> GetMessageTopology<T>()
            where T : class
        {
            if (TypeMetadataCache<T>.IsValidMessageType == false)
                throw new ArgumentException(TypeMetadataCache<T>.InvalidMessageTypeReason, nameof(T));

            var specification = _messageTypes.GetOrAdd(typeof(T), CreateMessageTopology<T>);

            return specification as IMessageSendTopologyConfigurator<T>;
        }

        public ConnectHandle Connect(ISendTopologyConfigurationObserver observer)
        {
            return _observers.Connect(observer);
        }

        public void AddConvention(ISendTopologyConvention convention)
        {
            lock (_lock)
            {
                _conventions.Add(convention);
            }
        }

        void ISendTopologyConfigurator.AddMessageSendTopology<T>(IMessageSendTopology<T> topology)
        {
            IMessageSendTopologyConfigurator<T> messageConfiguration = GetMessageTopology<T>();

            messageConfiguration.Add(topology);
        }

        public virtual IEnumerable<ValidationResult> Validate()
        {
            return _messageTypes.Values.SelectMany(x => x.Validate());
        }

        protected virtual IMessageSendTopologyConfigurator CreateMessageTopology<T>(Type type)
            where T : class
        {
            var messageTopology = new MessageSendTopology<T>();

            OnMessageTopologyCreated(messageTopology);
            return messageTopology;
        }

        protected void OnMessageTopologyCreated<T>(IMessageSendTopologyConfigurator<T> messageTopology)
            where T : class
        {
            _observers.MessageTopologyCreated(messageTopology);
        }

        void ApplyConventionsToMessageTopology<T>(IMessageSendTopologyConfigurator<T> messageTopology)
            where T : class
        {
            IMessageSendTopologyConvention[] conventions;
            lock (_lock)
            {
                conventions = _conventions.ToArray();
            }

            foreach (var convention in conventions)
            {
                if (convention.TryGetMessageSendTopologyConvention(out IMessageSendTopologyConvention<T> messageSendTopologyConvention))
                    messageTopology.AddConvention(messageSendTopologyConvention);
            }
        }
    }
}


text:
* Add the standard `code` and `reason` parameters to the `close` method

### 0.9.4 / 2015-03-08

* Don't send input to the driver before `start()` is called

### 0.9.3 / 2015-02-19

* Make sure the TCP socket is not left open when closing the connection

### 0.9.2 / 2014-12-21

* Only emit `error` once, and don't emit it after `close`

### 0.9.1 / 2014-12-18

* Check that all options to the WebSocket constructor are recognized

### 0.9.0 / 2014-12-13

* Allow protocol extensions to be passed into websocket-extensions

### 0.8.1 / 2014-11-12

* Send the correct hostname when upgrading a connection to TLS

### 0.8.0 / 2014-11-08

* Support connections via HTTP proxies
* Close the connection cleanly if we're still waiting for a handshake response

### 0.7.3 / 2014-10-04

* Allow sockets to be closed when they are in any state other than `CLOSED`

### 0.7.2 / 2013-12-29

* Make sure the `close` event is emitted by clients on Node v0.10

### 0.7.1 / 2013-12-03

* Support the `maxLength` websocket-driver option
* Make the client emit `error` events on network errors

### 0.7.0 / 2013-09-09

* Allow the server to send custom headers with EventSource responses

### 0.6.1 / 2013-07-05

* Add `ca` option to the client for specifying certificate authorities
* Start the server driver asynchronously so that `onopen` handlers can be added

### 0.6.0 / 2013-05-12

* Add support for custom headers

### 0.5.0 / 2013-05-05

* Extract the protocol handlers into the `websocket-driver` library
* Support the Node streaming API

### 0.4.4 / 2013-02-14

* Emit the `close` event if TCP is closed before CLOSE frame is acked

### 0.4.3 / 2012-07-09

* Add `Connection: close` to EventSource response
* Handle situations where `request.socket` is undefined

### 0.4.2 / 2012-04-06

* Add WebSocket error code `1011`.
* Handle URLs with no path correctly by sending `GET /`

### 0.4.1 / 2012-02-26

* Treat anything other than a `Buffer` as a string when calling `send()`

### 0.4.0 / 2012-02-13

* Add `ping()` method to server-side `WebSocket` and `EventSource`
* Buffer `send()` calls until the draft-76 handshake is complete
* Fix HTTPS problems on Node 0.7

### 0.3.1 / 2012-01-16

* Call `setNoDelay(true)` on `net.Socket` objects to reduce latency

### 0.3.0 / 2012-01-13

* Add support for `EventSource` connections

### 0.2.0 / 2011-12-21

* Add support for `Sec-WebSocket-Protocol` negotiation
* Support `hixie-76` close frames and 75/76 ignored segments
* Improve performance of HyBi parsing/framing functions
* Decouple parsers from TCP and reduce write volume

### 0.1.2 / 2011-12-05

* Detect closed sockets on the server side when TCP connection breaks
* Make `hixie-76` sockets work through HAProxy

### 0.1.1 / 2011-11-30

* Fix `addEventListener()` interface methods

### 0.1.0 / 2011-11-27

* Initial release, based on WebSocket components from Faye

redpajama_set_name: RedPajamaGithub


text:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Arch.EntityFrameworkCore.UnitOfWork.Host.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;

namespace Arch.EntityFrameworkCore.UnitOfWork.Host
{
    public class Startup
    {
        public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsEnvironment("Development"))
            {
            }

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

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            // use in memory for testing.
            services
                .AddDbContext<BloggingContext>(opt => opt.UseMySql("Server=localhost;database=uow;uid=root;pwd=root1234;"))
                //.AddDbContext<BloggingContext>(opt => opt.UseInMemoryDatabase("UnitOfWork"))
                .AddUnitOfWork<BloggingContext>()
                .AddCustomRepository<Blog, CustomBlogRepository>();

            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggingBuilder loggingBuilder)
        {
            loggingBuilder.AddConsole();
            loggingBuilder.AddDebug();

            app.UseEndpoints(endpoints => {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}


text:
TurboSms Notifier
=================

Provides [TurboSms](https://turbosms.ua/) integration for Symfony Notifier.

DSN example
-----------

```
TURBOSMS_DSN=turbosms://AUTH_TOKEN@default?from=FROM
```

where:
 - `AUTH_TOKEN` is your TurboSms auth token
 - `FROM` is your sender name, should be alpha-numeral, max 20 symbols and activated in your TurboSms account

Resources
---------

 * [Contributing](https://symfony.com/doc/current/contributing/index.html)
 * [Report issues](https://github.com/symfony/symfony/issues) and
   [send Pull Requests](https://github.com/symfony/symfony/pulls)
   in the [main Symfony repository](https://github.com/symfony/symfony)


text:
// This is ExFat, an exFAT accessor written in pure C#
// Released under MIT license
// https://github.com/picrap/ExFat

namespace ExFat.Partition.Entries
{
    using System;

    /// <summary>
    /// Flags for secondary entries (common flags)
    /// </summary>
    [Flags]
    public enum ExFatGeneralSecondaryFlags : Byte
    {
        /// <summary>
        /// Indicates that allocation is possible (unofficial specs says it must always be set)
        /// </summary>
        ClusterAllocationPossible = 0x01,
        /// <summary>
        /// When the flag is set, all entry cluster are contiguous, so there is no need to read FAT
        /// </summary>
        NoFatChain = 0x02,
    }
}


text:
package com.coillighting.udder.mix;

import com.coillighting.udder.infrastructure.Stateful;

public interface Animator {

    /** Draw this animator's subscene and/or update its internal state given the
     *  current time. Animating is a separate step from rendering, so animating
     *  doesn't necessarily have anything to do with computing the values of
     *  individual pixels.
     */
    public void animate(TimePoint timePoint);

}


text:
<!doctype html>

  <title>Diego Eis </title>
  <meta content="" name="description">

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <meta http-equiv='X-UA-Compatible' content='IE=edge;chrome=1' />
  <link rel="alternate" type="application/atom+xml" title="Atom Feed" href="/feed.xml" />
  <link href="https://fonts.googleapis.com/css?family=Abhaya+Libre:400,600" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=PT+Serif:400,700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cormorant+Garamond:400,700" rel="stylesheet">

  <link href="../../assets/css/style.css" rel="stylesheet" />

  </script>

diegoeis.com

Sobre

  RSS
  @diegoeis

Página anterior

Sobre os pavões do mercado de front-end

Um desabafo sobre a autopromoção

Eu gostava quando o mercado de front-end era mais simples. Quando não haviam tantos eventos. Quando não...

      <time datetime="Sep 29 2014">Sep 29, 2014</time>
      Ler post

          desenvolvimento

Iniciando com Middleman - Gerador de arquivos estáticos

O Middleman, assim como o Jekyll, serve sites estáticos, sem banco de dados, baseados em puro código HTML e informação. Existem uma série...

      <time datetime="Jul  4 2014">Jul  4, 2014</time>
      Ler post

          desenvolvimento
          middleman
          front-end

Sobre traquejo social na internet

Um dos meus primeiros erros quando iniciei na interwebs era conseguir me comunicar decentemente via texto. Eu me expressava errado, principalmente...

      <time datetime="May 23 2014">May 23, 2014</time>
      Ler post

          artigos

Anotações Segurança em Aplicações Web

Minhas anotações sobre a palestra do Nando Vieira no 16ELW.

seu site está seguro? Você se pergunta isso quando coloca seu produto no ar...

      <time datetime="May 20 2014">May 20, 2014</time>
      Ler post

          notas
          desenvolvimento

Sobre o básico que você precisa aprender para ser um front-end

Estava navegando por aí e acabei encontrando um artigo bem legal do Leandro Oriente, que fala sobre tecnologias e o que você precisa saber...

      <time datetime="May 15 2014">May 15, 2014</time>
      Ler post

          desenvolvimento

Sobre o mercado de desenvolvimento front-end

Você já deve ter notado que o mercado cresceu demais nos últimos anos. De repente, codificar HTML virou a coisa mais importante do mundo e...

      <time datetime="Mar 25 2014">Mar 25, 2014</time>
      Ler post

          desenvolvimento

Anotações sobre gestão 3.0

Estas são as minhas anotações sobre o que ouvi em um curso de gerenciamento ágil.

gestão 3.0 não é uma metodologia. Ela é uma mindset. É...

      <time datetime="Feb 11 2014">Feb 11, 2014</time>
      Ler post

          notas
          gestão
          agile
          gestão

Sobre ter informações que ajudam a ter uma vida saudável

Essas são algumas anotações que tenho feito sobre o que tenho lido e aprendido com a tentativa de perder peso. Como são anotações, não espere...

      <time datetime="Feb  8 2014">Feb  8, 2014</time>
      Ler post

          saude

Organizando a Informação

Como qualquer criança, eu tinha o costume fazer muitos trabalhos para a escola. O processo era quase sempre igual: a professora definia o...

      <time datetime="Jun 30 2013">Jun 30, 2013</time>
      Ler post

          artigos
          desenvolvimento
          front-end


text:
package org.scalaide.ui.wizards

import org.junit.Test

class ScalaFileCreatorValidationTest extends ScalaFileCreator {

  def validateSuccess(name: String): Unit = {
    val actual = doValidation(name)
    actual match {
      case Left(v) =>
        throw new AssertionError(s"'$name' is invalid: $v")
      case _ =>
    }
  }

  def validateFailure(name: String): Unit = {
    val actual = doValidation(name)
    if (actual.isRight)
      throw new AssertionError(s"'$name' is valid")
  }

  @Test
  def empty_file_name_is_invalid() =
    validateFailure("")

  @Test
  def file_in_default_package_is_valid() =
    validateSuccess("File")

  @Test
  def file_and_package_is_valid() = {
    validateSuccess("a.File")
    validateSuccess("a.b.File")
    validateSuccess("a.b.c.File")
  }

  @Test
  def path_with_special_sign_in_file_name_is_invalid() =
    validateFailure("Fil-e")

  @Test
  def path_that_ends_with_dot_is_invalid() = {
    validateFailure("a.")
    validateFailure("a.b.")
  }

  @Test
  def package_with_special_sign_is_invalid() = {
    validateFailure("a.b-b.c.File")
    validateFailure("a.b.c.File/")
  }

  @Test
  def special_signs_in_file_names_are_valid_if_they_are_part_of_a_Scala_identifier() = {
    validateSuccess("***")
    validateSuccess("a.b.c.***")
    validateSuccess("a.b.c.File_***")
  }

  @Test
  def special_signs_in_file_names_are_invalid_if_they_are_not_part_of_a_Scala_identifier() = {
    validateFailure("A***")
    validateFailure("a.b.c.A***")
  }

  @Test
  def file_ending_addition_is_treated_as_file_name() =
    validateSuccess("a.b.c.File.scala")

  @Test
  def no_scala_keywords_allowed_in_package_notation() = {
    validateFailure("trait.File")
    validateFailure("a.trait")
    validateFailure("=>")
    validateFailure("a.>:")

    validateFailure(" trait . File ")
    validateFailure(" a . trait ")
    validateFailure(" => ")
    validateFailure(" a . >: ")
  }

  @Test
  def various_literals_are_invalid_as_Scala_indentifier() = {
    validateFailure("\"\"")
    validateFailure(" \"\" ")
    validateFailure("\"ab\"")
    validateFailure(" \"ab\" ")
    // Multi-line string literals.
    validateFailure("\"\"\"\"\"\"")
    validateFailure(" \"\"\"\"\"\" ")

    validateFailure("'a'")
    validateFailure("'0'")
    validateFailure("'\u0050'")
    validateFailure("'\u0060'")

    validateFailure(" 1234 ")
    validateFailure("a. 1234 ")
    validateFailure("0")
    validateFailure("-0")

    validateFailure("123.45")
    validateFailure("-123.45")
    validateFailure("0.0")

    validateFailure("true")
    validateFailure("false")
  }

  @Test
  def valid_back_quote_usage_for_Scala_identifiers_succeeds() = {
    validateSuccess("`a b`")
    validateSuccess("a.`a b`")
    validateSuccess("a.b.`a b`")
    validateSuccess("`\u0055`")
    validateSuccess("`a\\nb`")
    validateSuccess("` `")
    validateSuccess("`yield`")
    validateSuccess("`def`")
    validateSuccess("`object`")
    validateSuccess("` \u0060")
    validateSuccess("\u0060 `")
    validateSuccess("\u0060 \u0060")
  }

  @Test
  def invalid_back_quote_usage_for_Scala_identifiers_fails() = {
    validateFailure("``")
    validateFailure("`\u0060")
    validateFailure("```")
    validateFailure("````")
    validateFailure("`a`b`")
    validateFailure("`a``")
    validateFailure(" `a``b` ")
    validateFailure("```ab `")
  }

  @Test
  def java_keywords_are_not_allowed_as_package_name() =
    validateFailure("int.File")

  @Test
  def java_keywords_are_allowed_as_file_name() =
    validateSuccess("a.int")
}


text:
<?php

/**
 * Our main calendar template, which encapsulates weeks and months.
 */
function template_main()
{
	global $context;

	// The main calendar wrapper.
	echo '

';

	// Show the mini-blocks if they're enabled.
	if (empty($context['blocks_disabled']))
		echo '

				', template_show_month_grid('prev', true), '
				', template_show_month_grid('current', true), '
				', template_show_month_grid('next', true), '

';

	// What view are we showing?
	if ($context['calendar_view'] == 'viewlist')
		echo '

				', template_show_upcoming_list('main'), '

';
	elseif ($context['calendar_view'] == 'viewweek')
		echo '

				', template_show_week_grid('main'), '

';
	else
		echo '

				', template_show_month_grid('main'), '

';

	// Close our wrapper.
	echo '

';
}

/**
 * Display a list of upcoming events, birthdays, and holidays.
 *
 * @param string $grid_name The grid name
 * @return void|bool Returns false if the grid doesn't exist.
 */
function template_show_upcoming_list($grid_name)
{
	global $context, $scripturl, $txt;

	// Bail out if we have nothing to work with
	if (!isset($context['calendar_grid_' . $grid_name]))
		return false;

	// Protect programmer sanity
	$calendar_data = &$context['calendar_grid_' . $grid_name];

	// Do we want a title?
	if (empty($calendar_data['disable_title']))
		echo '

					', $txt['calendar_upcoming'], '

';

	// Give the user some controls to work with
	template_calendar_top($calendar_data);

	// Output something just so people know it's not broken
	if (empty($calendar_data['events']) && empty($calendar_data['birthdays']) && empty($calendar_data['holidays']))
		echo '

', $txt['calendar_empty'], '
';

	// First, list any events
	if (!empty($calendar_data['events']))
	{
		echo '

', str_replace(':', '', $txt['events']), '

';

		foreach ($calendar_data['events'] as $date => $date_events)
		{
			foreach ($date_events as $event)
			{
				echo '

						', $event['link'], '';

				if ($event['can_edit'])
					echo ' ';

				if ($event['can_export'])
					echo ' ';

				echo '

';

				if (!empty($event['allday']))
				{
					echo '<time datetime="' . $event['start_iso_gmdate'] . '">', trim($event['start_date_local']), '</time>', ($event['start_date'] != $event['end_date']) ? ' – <time datetime="' . $event['end_iso_gmdate'] . '">' . trim($event['end_date_local']) . '</time>' : '';
				}
				else
				{
					// Display event info relative to user's local timezone
					echo '<time datetime="' . $event['start_iso_gmdate'] . '">', trim($event['start_date_local']), ', ', trim($event['start_time_local']), '</time> – <time datetime="' . $event['end_iso_gmdate'] . '">';

					if ($event['start_date_local'] != $event['end_date_local'])
						echo trim($event['end_date_local']) . ', ';

					echo trim($event['end_time_local']);

					// Display event info relative to original timezone
					if ($event['start_date_local'] . $event['start_time_local'] != $event['start_date_orig'] . $event['start_time_orig'])
					{
						echo '</time> (<time datetime="' . $event['start_iso_gmdate'] . '">';

						if ($event['start_date_orig'] != $event['start_date_local'] || $event['end_date_orig'] != $event['end_date_local'] || $event['start_date_orig'] != $event['end_date_orig'])
							echo trim($event['start_date_orig']), ', ';

						echo trim($event['start_time_orig']), '</time> – <time datetime="' . $event['end_iso_gmdate'] . '">';

						if ($event['start_date_orig'] != $event['end_date_orig'])
							echo trim($event['end_date_orig']) . ', ';

						echo trim($event['end_time_orig']), ' ', $event['tz_abbrev'], '</time>)';
					}
					// Event is scheduled in the user's own timezone? Let 'em know, just to avoid confusion
					else
						echo ' ', $event['tz_abbrev'], '</time>';
				}

				if (!empty($event['location']))
					echo '
', $event['location'];

				echo '

';
			}
		}

		echo '

';
	}

	// Next, list any birthdays
	if (!empty($calendar_data['birthdays']))
	{
		echo '

', str_replace(':', '', $txt['birthdays']), '

';

		foreach ($calendar_data['birthdays'] as $date)
		{
			echo '

						', $date['date_local'], ': ';

			unset($date['date_local']);

			$birthdays = array();

			foreach ($date as $member)
				$birthdays[] = '' . $member['name'] . (isset($member['age']) ? ' (' . $member['age'] . ')' : '') . '';

			echo implode(', ', $birthdays);

			echo '

';
		}

		echo '

';
	}

	// Finally, list any holidays
	if (!empty($calendar_data['holidays']))
	{
		echo '

', str_replace(':', '', $txt['calendar_prompt']), '

';

		$holidays = array();

		foreach ($calendar_data['holidays'] as $date)
		{
			$date_local = $date['date_local'];
			unset($date['date_local']);

			foreach ($date as $holiday)
				$holidays[] = $holiday . ' (' . $date_local . ')';
		}

		echo implode(', ', $holidays);

		echo '

';
	}
}

/**
 * Display a monthly calendar grid.
 *
 * @param string $grid_name The grid name
 * @param bool $is_mini Is this a mini grid?
 * @return void|bool Returns false if the grid doesn't exist.
 */
function template_show_month_grid($grid_name, $is_mini = false)
{
	global $context, $txt, $scripturl, $modSettings;

	// If the grid doesn't exist, no point in proceeding.
	if (!isset($context['calendar_grid_' . $grid_name]))
		return false;

	// A handy little pointer variable.
	$calendar_data = &$context['calendar_grid_' . $grid_name];

	// Some conditions for whether or not we should show the week links *here*.
	if (isset($calendar_data['show_week_links']) && ($calendar_data['show_week_links'] == 3 || (($calendar_data['show_week_links'] == 1 && $is_mini === true) || $calendar_data['show_week_links'] == 2 && $is_mini === false)))
		$show_week_links = true;
	else
		$show_week_links = false;

	// Assuming that we've not disabled it, show the title block!
	if (empty($calendar_data['disable_title']))
	{
		echo '

';

		// Previous Link: If we're showing prev / next and it's not a mini-calendar.
		if (empty($calendar_data['previous_calendar']['disabled']) && $calendar_data['show_next_prev'] && $is_mini === false)
			echo '

						«
					';

		// Next Link: if we're showing prev / next and it's not a mini-calendar.
		if (empty($calendar_data['next_calendar']['disabled']) && $calendar_data['show_next_prev'] && $is_mini === false)
			echo '

						»
					';

		// Arguably the most exciting part, the title!
		echo '
					', $txt['months_titles'][$calendar_data['current_month']], ' ', $calendar_data['current_year'], '

';
	}

	// Show the controls on main grids
	if ($is_mini === false)
		template_calendar_top($calendar_data);

	// Finally, the main calendar table.
	echo '

';

	// Show each day of the week.
	if (empty($calendar_data['disable_day_titles']))
	{
		echo '

';

		// If we're showing week links, there's an extra column ahead of the week links, so let's think ahead and be prepared!
		if ($show_week_links === true)
			echo '
						';

		// Now, loop through each actual day of the week.
		foreach ($calendar_data['week_days'] as $day)
			echo '
					', !empty($calendar_data['short_day_titles']) || $is_mini === true ? $txt['days_short'][$day] : $txt['days'][$day], '	';

		echo '

';
	}

	// Our looping begins on a per-week basis.
	foreach ($calendar_data['weeks'] as $week)
	{
		// Some useful looping variables.
		$current_month_started = false;
		$count = 1;
		$final_count = 1;

		echo '

';

		// This is where we add the actual week link, if enabled on this location.
		if ($show_week_links === true)
			echo '

						»
						';

		// Now loop through each day in the week we're on.
		foreach ($week['days'] as $day)
		{
			// What classes should each day inherit? Day is default.
			$classes = array('days');
			if (!empty($day['day']))
			{
				$classes[] = !empty($day['is_today']) ? 'calendar_today' : 'windowbg';

				// Additional classes are given for events, holidays, and birthdays.
				foreach (array('events', 'holidays', 'birthdays') as $event_type)
					if (!empty($day[$event_type]))
						$classes[] = $event_type;
			}
			else
			{
				$classes[] = 'disabled';
			}

			// Now, implode the classes for each day.
			echo '
					';

			// If it's within this current month, go ahead and begin.
			if (!empty($day['day']))
			{
				// If it's the first day of this month and not a mini-calendar, we'll add the month title - whether short or full.
				$title_prefix = !empty($day['is_first_of_month']) && $context['current_month'] == $calendar_data['current_month'] && $is_mini === false ? (!empty($calendar_data['short_month_titles']) ? $txt['months_short'][$calendar_data['current_month']] . ' ' : $txt['months_titles'][$calendar_data['current_month']] . ' ') : '';

				// The actual day number - be it a link, or just plain old text!
				if (!empty($modSettings['cal_daysaslink']) && $context['can_post'])
					echo '
						', $title_prefix, $day['day'], '';
				elseif ($is_mini)
					echo '
						', $title_prefix, $day['day'], '';
				else
					echo '
						', $title_prefix, $day['day'], '';

				// A lot of stuff, we're not showing on mini-calendars to conserve space.
				if ($is_mini === false)
				{
					// Holidays are always fun, let's show them!
					if (!empty($day['holidays']))
						echo '

							', $txt['calendar_prompt'], ' ', implode(', ', $day['holidays']), '

';

					// Happy Birthday Dear Member!
					if (!empty($day['birthdays']))
					{
						echo '

							', $txt['birthdays'], ' ';

						/* Each of the birthdays has:
							id, name (person), age (if they have one set?), and is_last. (last in list?) */
						$use_js_hide = empty($context['show_all_birthdays']) && count($day['birthdays']) > 15;
						$birthday_count = 0;
						foreach ($day['birthdays'] as $member)
						{
							echo '', $member['name'], '', isset($member['age']) ? ' (' . $member['age'] . ')' : '', '', $member['is_last'] || ($count == 10 && $use_js_hide) ? '' : ', ';

							// 9...10! Let's stop there.
							if ($birthday_count == 10 && $use_js_hide)
								// !!TODO - Inline CSS and JavaScript should be moved.
								echo '...
(', sprintf($txt['calendar_click_all'], count($day['birthdays'])), '), ';

							++$birthday_count;
						}
						if ($use_js_hide)
							echo '
							';

						echo '

';
					}

					// Any special posted events?
					if (!empty($day['events']))
					{
						// Sort events by start time (all day events will be listed first)
						uasort(
							$day['events'],
							function($a, $b)
							{
								if ($a['start_timestamp'] == $b['start_timestamp'])
									return 0;

								return ($a['start_timestamp'] < $b['start_timestamp']) ? -1 : 1;
							}
						);

						echo '

							', $txt['events'], '
';

						/* The events are made up of:
							title, href, is_last, can_edit (are they allowed to?), and modify_href. */
						foreach ($day['events'] as $event)
						{
							$event_icons_needed = ($event['can_edit'] || $event['can_export']) ? true : false;

							echo '

								', $event['link'], '

								';

							if (!empty($event['start_time_local']) && $event['starts_today'] == true)
								echo trim(str_replace(':00 ', ' ', $event['start_time_local']));
							elseif (!empty($event['end_time_local']) && $event['ends_today'] == true)
								echo strtolower($txt['ends']), ' ', trim(str_replace(':00 ', ' ', $event['end_time_local']));
							elseif (!empty($event['allday']))
								echo $txt['calendar_allday'];

							echo '
								';

							if (!empty($event['location']))
								echo '

								' . $event['location'] . '';

							if ($event['can_edit'] || $event['can_export'])
							{
								echo '
								';

								// If they can edit the event, show an icon they can click on....
								if ($event['can_edit'])
									echo '

									';

								// Exporting!
								if ($event['can_export'])
									echo '

									';

								echo '

';
							}

							echo '

';
						}

						echo '

';
					}
				}
				$current_month_started = $count;
			}
			// Otherwise, assuming it's not a mini-calendar, we can show previous / next month days!
			elseif ($is_mini === false)
			{
				if (empty($current_month_started) && !empty($context['calendar_grid_prev']))
					echo '', $context['calendar_grid_prev']['last_of_month'] - $calendar_data['shift']-- +1, '';
				elseif (!empty($current_month_started) && !empty($context['calendar_grid_next']))
					echo '', $current_month_started + 1 == $count ? (!empty($calendar_data['short_month_titles']) ? $txt['months_short'][$context['calendar_grid_next']['current_month']] . ' ' : $txt['months_titles'][$context['calendar_grid_next']['current_month']] . ' ') : '', $final_count++, '';
			}

			// Close this day and increase var count.
			echo '
						';

			++$count;
		}

		echo '

';
	}

	// The end of our main table.
	echo '

';
}

/**
 * Shows a weekly grid
 *
 * @param string $grid_name The name of the grid
 * @return void|bool Returns false if the grid doesn't exist
 */
function template_show_week_grid($grid_name)
{
	global $context, $txt, $scripturl, $modSettings;

	// We might have no reason to proceed, if the variable isn't there.
	if (!isset($context['calendar_grid_' . $grid_name]))
		return false;

	// Handy pointer.
	$calendar_data = &$context['calendar_grid_' . $grid_name];

	// At the very least, we have one month. Possibly two, though.
	$iteration = 1;
	foreach ($calendar_data['months'] as $month_data)
	{
		// For our first iteration, we'll add a nice header!
		if ($iteration == 1)
		{
			echo '

';

			// Previous Week Link...
			if (empty($calendar_data['previous_calendar']['disabled']) && !empty($calendar_data['show_next_prev']))
				echo '

							«
						';

			// Next Week Link...
			if (empty($calendar_data['next_calendar']['disabled']) && !empty($calendar_data['show_next_prev']))
				echo '

							»
						';

			// "Week beginning <date>"
			if (!empty($calendar_data['week_title']))
				echo $calendar_data['week_title'];

			echo '

';

			// Show the controls
			template_calendar_top($calendar_data);
		}

		// Our actual month...
		echo '

						', $txt['months_titles'][$month_data['current_month']], '

';

		// The main table grid for $this week.
		echo '

						', $txt['calendar_day'], '
						', $txt['events'], '
						', $txt['calendar_prompt'], '
						', $txt['birthdays'], '

';

		// Each day of the week.
		foreach ($month_data['days'] as $day)
		{
			// How should we be highlighted or otherwise not...?
			$classes = array('days');
			$classes[] = !empty($day['is_today']) ? 'calendar_today' : 'windowbg';

			echo '

						';

			// Should the day number be a link?
			if (!empty($modSettings['cal_daysaslink']) && $context['can_post'])
				echo '
							', $txt['days'][$day['day_of_week']], ' - ', $day['day'], '';
			else
				echo $txt['days'][$day['day_of_week']], ' - ', $day['day'];

			echo '

						';

			// Show any events...
			if (!empty($day['events']))
			{
				// Sort events by start time (all day events will be listed first)
				uasort(
					$day['events'],
					function($a, $b)
					{
						if ($a['start_timestamp'] == $b['start_timestamp'])
							return 0;

						return ($a['start_timestamp'] < $b['start_timestamp']) ? -1 : 1;
					}
				);

				foreach ($day['events'] as $event)
				{
					echo '

';

					$event_icons_needed = ($event['can_edit'] || $event['can_export']) ? true : false;

					echo $event['link'], '

								';

					if (!empty($event['start_time_local']))
						echo trim($event['start_time_local']), !empty($event['end_time_local']) ? ' – ' . trim($event['end_time_local']) : '';
					else
						echo $txt['calendar_allday'];

					echo '
								';

					if (!empty($event['location']))
						echo '

								' . $event['location'] . '';

					if (!empty($event_icons_needed))
					{
						echo ' ';

						// If they can edit the event, show a star they can click on....
						if (!empty($event['can_edit']))
							echo '

									';

						// Can we export? Sweet.
						if (!empty($event['can_export']))
							echo '

									';

						echo '

';
					}

					echo '

';
				}

				if (!empty($context['can_post']))
				{
					echo '

								', $txt['calendar_post_event'], '

';
				}
			}
			else
			{
				if (!empty($context['can_post']))
					echo '

								', $txt['calendar_post_event'], '

';
			}
			echo '

						';

			// Show any holidays!
			if (!empty($day['holidays']))
				echo implode('
', $day['holidays']);

			echo '

						';

			// Show any birthdays...
			if (!empty($day['birthdays']))
			{
				foreach ($day['birthdays'] as $member)
					echo '
							', $member['name'], '
							', isset($member['age']) ? ' (' . $member['age'] . ')' : '', '
							', $member['is_last'] ? '' : '
';
			}
			echo '

';
		}

		// Increase iteration for loop counting.
		++$iteration;

		echo '

';
	}
}

/**
 * Calendar controls under the title
 *
 * Creates the view selector (list, month, week), the date selector (either a
 * select menu or a date range chooser, depending on the circumstances), and the
 * "Post Event" button.
 *
 * @param array $calendar_data The data for the calendar grid that this is for
 */
function template_calendar_top($calendar_data)
{
	global $context, $scripturl, $txt;

	echo '

				', $txt['calendar_list'], '
				', $txt['calendar_month'], '
				', $txt['calendar_week'], '

			', template_button_strip($context['calendar_buttons'], 'right');

	echo '
			<form action="', $scripturl, '?action=calendar;', $context['calendar_view'], '" id="', !empty($calendar_data['end_date']) ? 'calendar_range' : 'calendar_navigation', '" method="post" accept-charset="', $context['character_set'], '">
				<input type="text" name="start_date" id="start_date" value="', trim($calendar_data['start_date']), '" tabindex="', $context['tabindex']++, '" class="date_input start" data-type="date">';

	if (!empty($calendar_data['end_date']))
		echo '
				', strtolower($txt['to']), '
				<input type="text" name="end_date" id="end_date" value="', trim($calendar_data['end_date']), '" tabindex="', $context['tabindex']++, '" class="date_input end" data-type="date">';

	echo '
				<input type="submit" class="button" style="float:none" id="view_button" value="', $txt['view'], '">
			</form>

';
}

/**
 * Template for posting a calendar event.
 */
function template_event_post()
{
	global $context, $txt, $scripturl, $modSettings;

	echo '
		<form action="', $scripturl, '?action=calendar;sa=post" method="post" name="postevent" accept-charset="', $context['character_set'], '" onsubmit="submitonce(this);">';

	if (!empty($context['event']['new']))
		echo '
			<input type="hidden" name="eventid" value="', $context['event']['eventid'], '">';

	// Start the main table.
	echo '

						', $context['page_title'], '

';

	if (!empty($context['post_error']['messages']))
		echo '

							', $context['error_type'] == 'serious' ? '' . $txt['error_while_submitting'] . '' : '', '

							', implode('
', $context['post_error']['messages']), '

';

	echo '

					<fieldset id="event_main">
						<legend>', $txt['calendar_event_title'], '</legend>
						<input type="hidden" name="calendar" value="1">

								<input type="text" id="evtitle" name="evtitle" maxlength="255" size="55" value="', $context['event']['title'], '" tabindex="', $context['tabindex']++, '">

';

	// If this is a new event let the user specify which board they want the linked post to be put into.
	if ($context['event']['new'] && !empty($context['event']['categories']))
	{
		echo '

								', $txt['calendar_post_in'], '
								<input type="checkbox" name="link_to_board"', (!empty($context['event']['board']) ? ' checked' : ''), ' onclick="toggleLinked(this.form);">
								<select name="board"', empty($context['event']['board']) ? ' disabled' : '', '>';

		foreach ($context['event']['categories'] as $category)
		{
			echo '
									<optgroup label="', $category['name'], '">';

			foreach ($category['boards'] as $board)
				echo '
										<option value="', $board['id'], '"', $board['selected'] ? ' selected' : '', '>', $board['child_level'] > 0 ? str_repeat('==', $board['child_level'] - 1) . '=>' : '', ' ', $board['name'], '</option>';
			echo '
									</optgroup>';
		}
		echo '
								</select>

';
	}

	// Note to theme writers: The JavaScript expects the input fields for the start and end dates & times to be contained in a wrapper element with the id "event_time_input"
	echo '
					</fieldset>
					<fieldset id="event_options">
						<legend>', $txt['calendar_event_options'], '</legend>

								', $txt['start'], '
								<input type="text" name="start_date" id="start_date" value="', trim($context['event']['start_date_orig']), '" tabindex="', $context['tabindex']++, '" class="date_input start" data-type="date">
								<input type="text" name="start_time" id="start_time" maxlength="11" value="', $context['event']['start_time_orig'], '" tabindex="', $context['tabindex']++, '" class="time_input start" data-type="time"', !empty($context['event']['allday']) ? ' disabled' : '', '>

								', $txt['end'], '
								<input type="text" name="end_date" id="end_date" value="', trim($context['event']['end_date_orig']), '" tabindex="', $context['tabindex']++, '" class="date_input end" data-type="date"', $modSettings['cal_maxspan'] == 1 ? ' disabled' : '', '>
								<input type="text" name="end_time" id="end_time" maxlength="11" value="', $context['event']['end_time_orig'], '" tabindex="', $context['tabindex']++, '" class="time_input end" data-type="time"', !empty($context['event']['allday']) ? ' disabled' : '', '>

								', $txt['calendar_allday'], '
								<input type="checkbox" name="allday" id="allday"', !empty($context['event']['allday']) ? ' checked' : '', ' tabindex="', $context['tabindex']++, '">

								', $txt['calendar_timezone'], '
								<select name="tz" id="tz"', !empty($context['event']['allday']) ? ' disabled' : '', '>';

	foreach ($context['all_timezones'] as $tz => $tzname)
		echo '
									<option', is_numeric($tz) ? ' value="" disabled' : ' value="' . $tz . '"', $tz === $context['event']['tz'] ? ' selected' : '', '>', $tzname, '</option>';

	echo '
								</select>

							', $txt['location'], '
							<input type="text" name="event_location" id="event_location" maxlength="255" value="', !empty($context['event']['location']) ? $context['event']['location'] : '', '" tabindex="', $context['tabindex']++, '">

					</fieldset>';

	echo '
					<input type="submit" value="', empty($context['event']['new']) ? $txt['save'] : $txt['post'], '" class="button">';

	// Delete button?
	if (empty($context['event']['new']))
		echo '
					<input type="submit" name="deleteevent" value="', $txt['event_delete'], '" data-confirm="', $txt['calendar_confirm_delete'], '" class="button you_sure">';

	echo '
					<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '">
					<input type="hidden" name="eventid" value="', $context['event']['eventid'], '">

		</form>';
}

/**
 * Displays a clock
 */
function template_bcd()
{
	global $context, $scripturl;
	$alt = false;

	echo '

				BCD Clock

';

	foreach ($context['clockicons'] as $t => $v)
	{
		echo '
				';

		foreach ($v as $i)
			echo '

';

		echo '
					';

		$alt = !$alt;
	}
	echo '

					Are you hardcore?

		';
}

/**
 * Displays the hours, minutes and seconds for our clock
 */
function template_hms()
{
	global $context, $scripturl;
	$alt = false;

	echo '

				Binary Clock

';

	foreach ($context['clockicons'] as $t => $v)
	{
		echo '

				';

		foreach ($v as $i)
			echo '
					';

		echo '

';

		$alt = !$alt;
	}
	echo '

					Too tough for you?

';

	echo '
		';
}

/**
 * Displays a binary clock
 */
function template_omfg()
{
	global $context;
	$alt = false;

	echo '

				OMFG Binary Clock

';

	foreach ($context['clockicons'] as $t => $v)
	{
		echo '

				';

		foreach ($v as $i)
			echo '
					';

		echo '

';

		$alt = !$alt;
	}

	echo '

		';
}

/**
 * Displays the time
 */
function template_thetime()
{
	global $context;
	$alt = false;

	echo '

				The time you requested

';

	foreach ($context['clockicons'] as $v)
	{
		echo '

				';

		foreach ($v as $i)
			echo '
					';

		echo '

';

		$alt = !$alt;
	}

	echo '

';
}

?>


text:
<?php
$page->title('People: Details')
     ->navbar_image('people')
     ->breadcrumbs('Search Results');

$page->content_begin();

$content->output($people);

$page->content_end();
?>


text:
<#
Copyright 2016 ASOS.com Limited

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.
#>

<#
.NAME
    Get-OctopusApiActionTemplate.Tests

.SYNOPSIS
    Pester tests for Get-OctopusApiActionTemplate.
#>

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

InModuleScope "OctopusStepTemplateCi" {

    Describe "Get-OctopusApiActionTemplate" {

        $env:OctopusUri    = "http://example.local";
        $env:OctopusApiKey = "secret";

        Mock -CommandName "Invoke-WebRequest" `
             -MockWith { throw "Invoke-WebRequest should be mocked with a ParameterFilter!" };

        It "Should construct the uri based on the object type" {

            Mock -CommandName "Invoke-WebRequest" `
                 -ParameterFilter { ($Uri -eq "http://example.local/api/ActionTemplates/All") -and ($Method -eq "GET") } `
                 -MockWith { return @{ "Content" = "" }; } `
                 -Verifiable;

            Get-OctopusApiActionTemplate -ObjectId "All";

            Assert-VerifiableMock;

        }

        It "Should use the appropriate http method based on the type of request" {

            Mock -CommandName "Invoke-WebRequest" `
                 -ParameterFilter { ($Uri -eq "http://example.local/api/ActionTemplates/100") -and ($Method -eq "GET") } `
                 -MockWith { return @{ "Content" = "" }; } `
                 -Verifiable;

            Get-OctopusApiActionTemplate -ObjectId "100";

            Assert-VerifiableMock;

        }

        It "Should use the cache if 'UseCache' is specified" {

            $cache = @{};

            Mock -CommandName "Get-OctopusApiCache" `
                 -MockWith { return $cache; } `
                 -Verifiable;

            Mock -CommandName "Invoke-WebRequest" `
                 -ParameterFilter { ($Uri -eq "http://example.local/api/ActionTemplates/200") -and ($Method -eq "GET") } `
                 -MockWith { return @{ "Content" = "" }; } `
                 -Verifiable;

            Get-OctopusApiActionTemplate -ObjectId "200" -UseCache;

            Assert-VerifiableMock;

            $cache.Count | Should Be 1;
            Assert-MockCalled "Invoke-WebRequest" -Exactly 1 -Scope It;

        }

    }

}


text:
import Ember from 'ember';
import fetch from 'ember-network/fetch';

export default Ember.Component.extend({
  rawContent: 'Loading...',

  didInsertElement: function() {
    fetch(this.get('model.rawPath')).then((response) => {
      return response.text();
    }).then((result) => {
      this.set('rawContent', result);
    });
  }
});


text:
layout: post
title: "NeoSiteLinux"
date: 2017-09-08 08:50:57
tags: [Tecnología]
categories: [Argentina]
preview: https://ia601507.us.archive.org/29/items/TAPEANDORADIO500/Neositelinux300.jpg
---

![NeoSiteLinux](https://ia601507.us.archive.org/29/items/TAPEANDORADIO500/Neositelinux500.jpg)

## Escucha su más reciente episodio

<audio id="audio" preload="auto" controls="" src="http://www.ivoox.com/neositelinux-podcast-2018-15-ultimo-episodio_mf_30794122_feed_1.mp3"></audio>

Un podcast para hablar abiertamente sobre el software libre, GNU/Linux y la tecnología en general.

_ _ _

Autor: **Natanael Garrido**
[web](https://neositelinux.com)
[Feed](http://www.ivoox.com/neositelinux-podcast_fg_f1169111_filtro_1.xml)

**Puedes escuchar este podcast en:**
[iTunes](@NeoSiteLinux)

**Contacta:**
Twitter: [@NeoSiteLinux](https://twitter.com/NeoSiteLinux)
Correo: [nag.garrido@gmail.com](mailto:nag.garrido@gmail.com)


text:
package buf

import (
	"math"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestByte2Int(t *testing.T) {
	assert.Equal(t, 1, Byte2Int(Int2Bytes(1)))
	assert.Equal(t, math.MaxInt32, Byte2Int(Int2Bytes(math.MaxInt32)))
}

func TestByte2Int64(t *testing.T) {
	assert.Equal(t, int64(1), Byte2Int64(Int64ToBytes(1)))
	assert.Equal(t, int64(math.MaxInt64), Byte2Int64(Int64ToBytes(math.MaxInt64)))
}

func TestByte2Uint64(t *testing.T) {
	assert.Equal(t, uint64(1), Byte2Uint64(Uint64ToBytes(1)))
	assert.Equal(t, uint64(math.MaxUint64), Byte2Uint64(Uint64ToBytes(math.MaxUint64)))
}

func TestByte2Uint32(t *testing.T) {
	assert.Equal(t, uint32(1), Byte2Uint32(Uint32ToBytes(1)))
	assert.Equal(t, uint32(math.MaxUint32), Byte2Uint32(Uint32ToBytes(math.MaxUint32)))
}

func TestByte2Uint16(t *testing.T) {
	assert.Equal(t, uint16(1), Byte2Uint16(Uint16ToBytes(1)))
	assert.Equal(t, uint16(math.MaxUint16), Byte2Uint16(Uint16ToBytes(math.MaxUint16)))
}


text:
<?php

namespace Elgg\Likes;

/**
 * @access private
 */
class DataService {

	/**
	 * @var array [GUID => boolean]
	 */
	protected $current_user_likes = array();

	/**
	 * @var array [GUID => int]
	 */
	protected $num_likes = array();

	/**
	 * @param int $guid
	 * @param int $num
	 */
	public function setNumLikes($guid, $num) {
		$this->num_likes[$guid] = (int)$num;
	}

	/**
	 * @param int  $guid
	 * @param bool $is_liked
	 */
	public function setLikedByCurrentUser($guid, $is_liked) {
		$this->current_user_likes[$guid] = (bool)$is_liked;
	}

	/**
	 * @param int $entity_guid
	 * @return bool
	 */
	public function currentUserLikesEntity($entity_guid) {
		if (!isset($this->current_user_likes[$entity_guid])) {
			$this->current_user_likes[$entity_guid] = elgg_annotation_exists($entity_guid, 'likes');
		}
		return $this->current_user_likes[$entity_guid];
	}

	/**
	 * @param \ElggEntity $entity
	 * @return int
	 */
	public function getNumLikes(\ElggEntity $entity) {
		$guid = $entity->guid;
		if (!isset($this->num_likes[$guid])) {
			$this->num_likes[$guid] = likes_count($entity);
		}
		return $this->num_likes[$guid];
	}

	/**
	 * @return DataService
	 */
	public static function instance() {
		static $inst;
		if ($inst === null) {
			$inst = new self();
		}
		return $inst;
	}
}


text:
namespace DurableTaskSamples.ErrorHandling
{
    using System;
    using DurableTask;

    public sealed class GoodTask : TaskActivity<string, string>
    {
        public GoodTask()
        {
        }

        protected override string Execute(DurableTask.TaskContext context, string input)
        {
            Console.WriteLine("GoodTask Executed...");

            return "GoodResult";
        }
    }

    public sealed class BadTask : TaskActivity<string, string>
    {
        public BadTask()
        {
        }

        protected override string Execute(DurableTask.TaskContext context, string input)
        {
            Console.WriteLine("BadTask Executed...");

            throw new InvalidOperationException("BadTask failed.");
        }
    }

    public sealed class CleanupTask : TaskActivity<string, string>
    {
        public CleanupTask()
        {
        }

        protected override string Execute(DurableTask.TaskContext context, string input)
        {
            Console.WriteLine("CleanupTask Executed...");

            return "CleanupResult";
        }
    }

}


text:
import json
import logging
import os

from jinja2 import Environment, FileSystemLoader
from ochopod.bindings.ec2.kubernetes import Pod
from ochopod.core.fsm import diagnostic
from ochopod.core.utils import merge, retry, shell
from ochopod.models.piped import Actor as Piped
from ochopod.models.reactive import Actor as Reactive
from os.path import join, dirname

logger = logging.getLogger('ochopod')

if __name__ == '__main__':

    #
    # - load our pod configuration settings
    # - this little json payload is packaged by the deployment tool
    # - is it passed down to the container as the $pod environment variable
    #
    cfg = json.loads(os.environ['pod'])

    class Model(Reactive):

        damper = 15.0

        sequential = True

        depends_on = ['zookeeper']

    class Strategy(Piped):

        cwd = '/opt/kafka_2.9.2-0.8.2.1'

        strict = True

        def can_configure(self, cluster):

            #
            # - we want a 3+ zk ensemble in our namespace
            # - if the assert blows up the pod will attempt to re-configure later on
            #
            assert len(cluster.dependencies['zookeeper']) >= 3, '3+ zookeeper ensemble required'

        def configure(self, cluster):

            #
            # - look our broker index up
            # - this index is required in the configuration
            #
            pod = cluster.pods[cluster.key]
            assert '9092' in pod['ports'], 'kafka container not exposing 9092 ?'

            #
            # - render the server.properties file
            # - the bulk of the broker settings come from our pod configuration
            # - it is hardcoded to use our mounted /var/lib/kafka directory for the log files
            #
            env = Environment(loader=FileSystemLoader(join(dirname(__file__), 'templates')))
            template = env.get_template('server.properties')
            index = cluster.seq + 1
            mapping = \
                {
                    'id':       index,
                    'host':     pod['ip'],
                    'port':     9092,
                    'settings': cfg['broker'],
                    'zk':       cluster.grep('zookeeper', 2181)
                }

            logger.debug('starting broker #%d' % index)

            with open('%s/config/server.properties' % self.cwd, 'wb') as f:
                f.write(template.render(mapping))

            return 'bin/kafka-server-start.sh config/server.properties', {}

    Pod().boot(Strategy, model=Model)


text:
var q = require('q');
var FirefoxProfile = require('firefox-profile');

exports.getFirefoxProfile = function() {
  var deferred = q.defer();

  var firefoxProfile = new FirefoxProfile();
  firefoxProfile.setPreference('media.navigator.permission.disabled', true);
  firefoxProfile.setPreference('media.navigator.streams.fake', true);
  firefoxProfile.setPreference('media.getusermedia.screensharing.allowed_domains',
    'localhost,adam.local');
  firefoxProfile.encoded(function(encodedProfile) {
    var multiCapabilities = [{
      browserName: 'firefox',
      acceptSslCert: true,
      'firefox_profile' : encodedProfile
    }];
    deferred.resolve(multiCapabilities);
  });

  return deferred.promise;
};


text:
{-# LANGUAGE OverloadedStrings #-}

module BaseSpec where

import Web.Twitter.Conduit.Base
import Web.Twitter.Conduit.Response

import Control.Applicative
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import Data.Conduit
import qualified Data.Conduit.Attoparsec as CA
import Data.Maybe
import qualified Data.Text as T
import qualified Network.HTTP.Types as HT

import Test.Hspec

spec :: Spec
spec = do
    unit

unit :: Spec
unit = do
    describe "checkResponse" $ do
        describe "when the response has \"errors\" key" $ do
            let errorMessage = fromJust . decode $ "{\"errors\":[{\"message\":\"Sorry, that page does not exist\",\"code\":34}]}"
                response = Response HT.status404 [] errorMessage
                result = checkResponse response

            it "returns TwitterErrorResponse" $ do
                case result of
                    Left res@(TwitterErrorResponse _ _ msgs) -> do
                        res `shouldBe` TwitterErrorResponse HT.status404 [] [TwitterErrorMessage 34 ""]
                        twitterErrorMessage (head msgs) `shouldBe` "Sorry, that page does not exist"
                    _ -> expectationFailure $ "Unexpected " ++ show result
        describe "when the response does not has \"errors\" key but have error status code" $ do
            let errorMessage = fromJust . decode $ "{}"
                response = Response HT.status404 [] errorMessage
                result = checkResponse response
            it "returns TwitterStatusError" $ do
                case result of
                    Left (TwitterStatusError st hdr body) -> do
                        st `shouldBe` HT.status404
                        hdr `shouldBe` []
                        body `shouldBe` errorMessage
                    _ -> expectationFailure $ "Unexpected " ++ show result

    describe "sinkJSON" $ do
        describe "when valid JSON input" $ do
            let input = "{\"test\": \"input\", \"status\": 200 }"
            it "can consume the input from Source and returns JSON Value" $ do
                res <- yield input $$ sinkJSON
                res ^. key "test" . _String `shouldBe` "input"
                res ^? key "status" . _Integer `shouldBe` Just 200
        describe "when invalid JSON input" $ do
            let input = "{]"
            it "should raise Data.Conduit.Attoparsec.ParseError" $ do
                let parseErrorException (CA.ParseError {}) = True
                    parseErrorException _ = False
                    action = yield input $$ sinkJSON
                action `shouldThrow` parseErrorException

    describe "sinkFromJSON" $ do
        describe "when valid JSON input" $ do
            let input = "{\"test\": \"input\", \"status\": 200 }"
            it "can consume the input from Source and returns a value which type is the specified one" $ do
                res <- yield input $$ sinkFromJSON
                res `shouldBe` TestJSON "input" 200
        describe "when the JSON value does not have expected format" $ do
            let input = "{\"status\": 200}"
            it "should raise FromJSONError" $ do
                let fromJSONException (FromJSONError {}) = True
                    fromJSONException _ = False
                    action :: IO TestJSON
                    action = yield input $$ sinkFromJSON
                action `shouldThrow` fromJSONException

data TestJSON = TestJSON
    { testField :: T.Text
    , testStatus :: Int
    }
    deriving (Show, Eq)
instance FromJSON TestJSON where
    parseJSON (Object o) =
        TestJSON <$> o .: "test"
            <*> o .: "status"
    parseJSON v = fail $ "Unexpected: " ++ show v


text:
import threading
import urllib
import urllib.parse
import urllib.error
import urllib.request
import urllib.response
import json
import time
import os

def post(rawData):
	jsondata = json.dumps(rawData)
	url = urllib.request.Request("https://metazombies.ml/whatsapp_requests.php",jsondata.encode())
	url.add_header("Content-Type","application/json")
	data = urllib.request.urlopen(url, timeout=10).read().decode('utf8', 'ignore')
	return data
def getUserStatus(user):
	data = post({'command':'getUserStatus','userID':user})
	jsonObj = json.loads(data)
	userdata = jsonObj['0']
	print(userdata['USERNAME']+" ["+userdata['USERID'] + "]: " + userdata['STATUS'] +  " (" + userdata['HUMANSCORE'] + "/" + userdata['ZOMBIESCORE'] + ")");

data = post({'command':'claim','userID':'be74486','code':'qu79jmn9','password':'#EDC4rfv'})
print(data)
"""
data = "\t"+post({'command':'getLeaderboard'})
jd = json.loads(data)
print(jd)
text = ""
text+= ("*Zombie Leaderboard:*\n")
count = 1
for key in jd['zombies']:
	text+= ("%-4s%-25s%s\n" % (str(count)+".",key['USERNAME']+":",key['ZOMBIESCORE']))
	count += 1
count=0
text+= ("\n*Human Leaderboard:*\n")
for key in jd['humans']:
	text+= ("%-4s%-25s%s\n" % (str(count)+".",key['USERNAME']+":",key['HUMANSCORE']))
	count += 1
print(text)
"""
"""
print('User status')
getUserStatus('be74486')
data = post({'command':'getUserData'})
jsonObj = json.loads(data)
print ("User data")
for record in [x for x in jsonObj if x != 'success']:
	recordData = jsonObj[record]
	print("\t"+recordData['USERNAME'] + " " + recordData['USERID'] + " +27" + recordData['CELLNUMBER'][1:] + " " + recordData['STUDENTNUMBER'])
#curl -H "Content-Type: application/json" -X POST -d '{"command":"getLeaderboard"}' http://localhost/whatsapp_requests.php
print('Claim:')
print("\t"+post({'command':'claim','userID':'be74486','code':'abcdefg'}))
print('Claim: bad code')
print("\t"+post({'command':'claim','userID':'be74486','code':'abcefg'}))
print('Claim: bad id')
print("\t"+post({'command':'claim','userID':'b4486','code':'abcdefg'}))
print('Leaderboard')
print("\t"+post({'command':'getLeaderboard'}))
print('Kill')
getUserStatus('be74486')
getUserStatus('0853e70')
print("Kill\t"+post({'command':'kill','victimID':'0853e70','killerID':'be74486'}))
getUserStatus('be74486')
getUserStatus('0853e70')
print("Revive\t"+post({'command':'claim','userID':'0853e70','code':'12345'}))
getUserStatus('be74486')
getUserStatus('0853e70')
print()
"""
#INSERT INTO `Claims`('id',`type`, `claimValue`, `timeStart`, `timeValid`, `usesRemaining`) VALUES ('abcdefg',0,100,1500,36000,15)
#INSERT INTO `metazomb_MetazombiesDB`.`Claims` (`ID`, `type`, `claimValue`, `timeStart`, `timeValid`, `usesRemaining`) VALUES ('abcdefg', '0', '100', CURRENT_TIMESTAMP, '10000', '15');


text:
title: Запускаем Linux в браузере. Часть 1
layout: post
category: tutorial
tags:
- tutorial
- linux
- wasm
---

Как вам идея запустить настоящий Debian 11 в вашем браузере? Нет, не тонкий клиент на какой-то сервер, а целую операционную систему, которая работает оффлайн прямо у вас в браузере!

- Часть 1: Предисловие
- [Часть 2: Запускаем Debian]({{site.basepath}}/linux-in-the-browser-part-2/)
- Чвсть 3: Настраиваем сеть

# Часть 1: Предисловие

Я пишу курс по работе в терминалом и искал способы, как можно сделать этот курс интерактивным, чтобы читатель мог не меняя контекста сразу пробовать команды и получать ответ.

## xTerm

Первым в поиске мне попался [xterm](https://xtermjs.org/) - JS пакет, который "рисует" привычную оболочку на HTML и CSS. Выглядит очень достойно и на нём можно симулятор [эмулятора терминала](https://ru.wikipedia.org/wiki/Эмулятор_терминала), который бы выдавал заранее заготовленные ответы на введённые команды. Но это скучно и не интересно.

В примерах использования был [ttyd](https://github.com/tsl0922/ttyd) - утилита командной строки, которая демонстрирует возможность подключения xterm к работающему серверу. Уже интереснее.

У меня есть VPS, можно развернуть там виртуалку (для пущей безопасности), а внутри запускать по docker-контейнеру под каждого читателя... Дороговато. Может быть один на всех "гостей", а для зарегистрированных пользователей отдельную среду? Нужно было бы сделать систему распределения ресурсов... Но сколько таких контейнеров выдержит моя VPS'ка? Наверно на 10 уже начнёт загибаться. Сложно, дорого и нежизнеспособно, ищем дальше.

## WASM

Как уважающий себя инженер я оставил проблему мариноваться на неопределённый срок.

Третьего дня я, как обычно, сёрфил ютубчик и решил посмотреть [выступление](https://www.youtube.com/watch?v=Ndu9qU_vY9c) про перспективы [Web Assembly](https://ru.wikipedia.org/wiki/WebAssembly).

> Рассказывать что такое WASM выходит за рамки этой статьи, но если вкратце: код на языках высокого уровня (C, C++, Rust и [даже PHP](https://github.com/wasmerio/wasmer-php)) можно скомпилировать в web assembly, что позволит запустить его внутри современных браузеров.

Очень меня впечатлил и вдохновил этот доклад и я вспомнил про свою проблему. Запуск кода на C в браузере? Linux написан на C? Что если скомпилировать Linux в WASM?

Естественно, если бы я поискал готовые решения по запросу **linux wasm**, я бы сразу нашел, например, [webvm](https://webvm.io/), но вместо этого я начал искать самый маленький вариант ядра Linux на котором можно поэкспериментировать. Ядро бы я наверно не скомпилировал в WASM, но я вспомнил про другой мини-linux.

Что у нас используется, когда нужен очень маленький linux? Конечно, [Busybox](https://busybox.net/) - набор всеми нами любимых утилит типа cat, ls, vi, скомпилированных в один файл, который весит меньше мегабайта. Отличный кандидат!

По запросу **busybox webasm** первый результат вёл на ишью, буквально, с заголовком [Crazy idea: compile busybox to WebAssembly, boot a Linux VM to it](https://github.com/Xe/olin/issues/80), где в ответ выдали ссылку на...

## JSLinux

Как обычно, я только задумываюсь о чём-то, а гиганты мысли уже давным-давно развивают эту идею на практике.

Итак, [JSLinux](https://bellard.org/jslinux/tech.html) - эмулятор Linux, основанный на [TinyEMU](https://bellard.org/tinyemu/), скомпилированном в WASM, который позволяет запускать различные x86 системы, в том числе и linux.

Вот вам полноразмерный [Alpine Linux](https://bellard.org/jslinux/vm.html?url=alpine-x86.cfg&mem=192) в браузере с интернетом через вебсокеты и виртуальной сетевой файловой системой. Звучит! То что нужно? Почти.

Я придираюсь, но для меня было пару нюансов. Оболочка терминала под этот эмулятор была самописная, хоть и отлично выполненная, но не xterm. Не очень много документации: сам JSLinux было очень просто накатить и поиграться, но как мне его менять? И как собирать свои образы? В общем, вариант, но ищем ещё варианты. Благо, внизу страницы были ссылки на другие эмуляторы.

## v86

Например, [v86](https://github.com/copy/v86). Он эмулирует ЦПУ (на уровне 3 пентиума) и железо в браузере, а все софтовые вызовы на лету компилирует в WASM. Пушка-гонка. Проект живее всех живых, документация побогаче, есть пример как собрать образ Debian! Плюс, показывают в базовой сборке как подцепить xterm.

Наш вариант!

Btw [в примерах](https://copy.sh/v86/) есть [Arch linux](https://copy.sh/v86/?profile=archlinux), хоть по умолчанию и без сети.

# В следующей серии

Будем собирать и запускать образ Debian 11 под v86. Спойлер - самый маленький образ у меня получился 350 метров + 150 метров созранённого контекста для моментального запуска. Под уроки терминала тяжеловато, но поиграться с этим было очень интересно!


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Microsoft.AspNetCore.Http;
//using Microsoft.AspNetCore.Routing;
#if NET462
using System.Web;
using System.Web.Routing;
#endif

namespace Senparc.WebSocket
{
#if NET462
    /// <summary>
    /// WebSocketHansler,处理WebSocket请求
    /// </summary>
    public class WebSocketRouteHandler: IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new WebSocketHandler(requestContext);
        }

        //public RequestDelegate GetRequestHandler(HttpContext httpContext, RouteData routeData)
        //{
        //    //throw new NotImplementedException();
        //    return new WebSocketHandler(requestContext);
        //}
    }
#endif
}


text:
Rails.application.routes.draw do
  devise_for :users, path: "people/users",
                     path_names: {sign_in: "sign-in", sign_out: "sign-out"},
                     controllers: {
                       sessions: "people/users/sessions",
                       omniauth_callbacks: "people/users/omniauth_callbacks",
                       passwords: "people/users/passwords",
                       confirmations: "people/users/confirmations"
                     }
  get "people/users/signed-out", to: "landing#signed_out", as: :user_signed_out

  resources :communities, only: :index

  namespace :people do
    resources :sign_in_invitations, path: "sign-in-invitations", only: %i[new create]
    resources :birthdays, only: :index
    resources :vehicles, only: :index
    resources :member_types, path: "member-types"
    resource :settings, only: %i[edit update]
    resources :memorials do
      resources :messages, only: %i[edit create update destroy], controller: "memorial_messages"
    end
    resource :password_change, only: %i[show edit update], path: "password-change" do
      patch :check
      post :strength
    end
  end

  resources :users do
    collection do
      patch :update_setting, path: "update-setting"
    end
    member do
      put :activate
      put :deactivate
      put :resend_email_confirmation
      delete :cancel_email_change
      post :impersonate
      post :unimpersonate
    end
  end

  namespace :meals do
    resources :signups, only: %i[create update]
    resources :formulas do
      member do
        put :activate
        put :deactivate
      end
    end
    resources :imports, only: %i[show new create]
    resources :roles, except: :show do
      member do
        put :activate
        put :deactivate
      end
    end
    resources :types, except: :show do
      collection do
        get :categories
      end
      member do
        put :activate
        put :deactivate
      end
    end
  end

  get "/meals/reports", to: redirect("/meals/report") # Legacy path

  resources :meals, controller: "meals/meals" do
    collection do
      get :jobs
      get :report
      get :worker_form, path: "worker-form"
    end
    member do
      put :close
      put :reopen
      get :summary
    end

    resources :messages, only: %i[new create], module: :meals
    resource :finalize, only: %i[new create], module: :meals, controller: :finalize
  end

  # `namespace :x` is just a shorthand for scope :x, module: :x, as: :x
  # scope :x adds /x/ as a URL prefix
  # scope module: :x adds /x as a controller prefix (controllers will be fetched under controllers/x/foo.rb)
  # scope as: :x adds the x as a prefix for path helpers
  # We just want controller and path helper prefixes
  scope as: :groups, module: :groups do
    resources :groups do
      member do
        put :activate
        put :deactivate
        put :join
        put :leave
      end
    end
  end

  namespace :groups do
    namespace :mailman do
      get "templates/:template_name/:list_id/:locale",
          to: "templates#show", constraints: { list_id: /.*/ }, defaults: {format: "text"}
    end
  end

  # Legacy calendar export routes. They are highly constrained.
  # These come first so they don't get gobbled up by more generic calendar routes below.
  get "calendars/:id/:calendar_token",
      to: "calendars/exports#personalized",
      constraints: {
        # These are the original calendar export types. Only these need to work for legacy URLs.
        id: /meals|community-meals|all-meals|shifts|reservations|your-reservations/,
        # These URLs should always have a 20 character token with alphanumeric chars plus - and _.
        # Enforcing this will make it easier to distinguish from other calendars routes in future.
        calendar_token: /[A-Za-z0-9_\-]{20}/,
        format: :ics
      }

  resources :calendars, except: :show, controller: "calendars/calendars" do
    member do
      put :activate
      put :deactivate
      put :move
    end
  end

  namespace :calendars do
    resources :events
    resources :protocols
    resources :groups, only: %i[new edit create update destroy]

    # index - The calendar export page
    resources :exports, only: :index do
      member do
        token_constraints = {calendar_token: /[A-Za-z0-9_\-]{20}/}.freeze

        # This is the personalized show action, allowing paths to include the user's calendar token,
        # e.g. /calendars/exports/meals/D7sbPv7YCUhxMs4Pyx9D.
        # The calendar's type gets captured as the :id param, so this is equivalent to
        # /calendars/exports/:id/:calendar_token
        get ":calendar_token", to: "exports#personalized", as: :personalized, constraints: token_constraints

        # This is the community show action, allowing paths to include the community's calendar token.
        # The community part is indicated by a leading +, e.g.
        # e.g. /calendars/exports/meals/+X7sbPv7YCUhxMs4Pyx9D.
        get "+:calendar_token", to: "exports#community", as: :community, constraints: token_constraints
      end
      collection do
        put :reset_token
      end
    end
  end

  resources :households do
    member do
      put :activate
      put :deactivate
    end
  end

  resources :roles, only: :index

  resources :accounts, only: %i[index show edit update] do
    collection do
      get :yours
      put :apply_late_fees
    end
    resources :transactions, only: %i[index new create]
  end

  resources :transactions, only: :index

  resources :statements, only: [:show] do
    collection do
      post :generate
      get :more
    end
  end

  namespace :billing do
    resources :templates, except: [:show] do
      collection do
        post :apply
        post :review
      end
    end
  end

  resources :wiki_pages, controller: "wiki/pages", param: :slug, path: "wiki" do
    collection do
      get :all
    end
    member do
      get :history
      get :compare
    end
  end

  namespace :work do
    resources :shifts, path: :signups, only: %i[index show] do
      member do
        post :signup
        delete :unsignup
      end
    end
    resources :jobs
    resources :periods do
      member do
        get :review_notices
        post :send_notices
      end
    end
    resource :settings, only: %i[edit update]
    get "report", to: "periods#report", as: :report
    get "/", to: redirect("/work/signups")
  end

  resources :uploads, only: :create

  namespace :admin do
    get "settings/:type", to: "settings#edit", as: :settings
    patch "settings/:type", to: "settings#update"
  end

  get "sso", to: "single_sign_on#sign_on"

  get "ping", to: "landing#ping"
  get "inactive", to: "home#inactive"
  get "about/:page", to: "landing#public_static"

  authenticated :user do
    root to: "home#index", as: :authenticated_root
  end

  root to: "landing#index"
end


text:
"""
The data set that is in the specified hdf5 file has labels in two different locations.
The label input files have the .label suffix.
The foci input files have the .out suffix.

Vacuum up the labels from the two given directories, merge the relevant portions (image number,object number) and
convert from two-dimensional binary labeling into one multi class label, by the following scheme:

-1,-1 -> 0
1,-1 -> 1
-1,1 -> 2
1,1 -> 3
"""
from os import listdir, chdir, getcwd
from optparse import OptionParser

from tables.file import File, openFile, copyFile, hdf5Extension
from tables import Filters
from tables import Atom

import numpy as np

# Check that options are present, else print help msg.
parser = OptionParser()
parser.add_option("--labelinput", dest="labels_indir", help="read shape labels from here")
parser.add_option("--fociinput", dest="foci_indir", help="read foci labels from here")
parser.add_option("-f", "--filename", dest="filename", help="specify the .h5 filename that will contain the data labels")
(options, args) = parser.parse_args()

# label conversion dictionary
label_dict = {(-1.0,-1.0): 0, (1.0,-1.0): 1, (-1.0,1.0): 2, (1.0,1.0): 3}

''' Read files in directory loc, return a list of those ending with suffix '''
def read_filenames(loc,suffix):
    files = listdir(loc)
    selected = []
    for f in files:
        if f.endswith(suffix):
            selected.append(f)
    return selected

''' Read the given file (in directory dir) and return the numpy array within '''
def read_array_from_file(filename,dirname):
    chdir(dirname)
    array = np.genfromtxt(filename, delimiter=',', autostrip=True, usecols=(0,1,2))
    return array

''' Take two arrays, merge them together after translating the labels which are in the first
    column of each array
'''
def combine_arrays(foci_array,shape_array):
    foci_labels = foci_array[:,0]
    shape_labels = shape_array[:,0]
    new_labels = np.array([label_dict[t] for t in zip(foci_labels,shape_labels)])
    new_labels.shape = (len(new_labels),1)
    return np.hstack((new_labels,foci_array[:,(1,2)]))

# Open and prepare an hdf5 file, adding a labels group
filename = options.filename
h5file = openFile(filename, mode = "a", title = "Data File")
labels_group = h5file.createGroup("/", 'labels', 'The labels and object IDs')
zlib_filters = Filters(complib='zlib', complevel=5)

# Go to the files location in the filesystem.
shape_input = options.labels_indir
foci_input = options.foci_indir
cur_dir = getcwd()

try:
    foci_files = read_filenames(foci_input,'.out')
    shape_files = read_filenames(shape_input,'.label')
except:
    print "Could not read files from one of " + foci_input + ", " + shape_input
    sys.exit(1)

foci_files.sort()
shape_files.sort()

# iterate over sorted & zipped files
for (f,s) in zip(foci_files,shape_files):
    label_range = f.split('.')[0]
    foci_array = read_array_from_file(f,foci_input)
    shape_array = read_array_from_file(s,shape_input)
    relabeled_array = combine_arrays(foci_array,shape_array)
    atom = Atom.from_dtype(relabeled_array.dtype)
    labels = h5file.createCArray(where=labels_group, name=label_range, atom=atom, shape=relabeled_array.shape, filters=zlib_filters)
    labels[:] = relabeled_array
    h5file.flush()

# Close the h5 file when done.
h5file.close()


text:
<?php

namespace Censo\CensoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * RecoleccionBasura
 *
 * @ORM\Table(name="recoleccion_basura")
 * @ORM\Entity
 */
class RecoleccionBasura
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\SequenceGenerator(sequenceName="recoleccion_basura_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nombre", type="string", length=255, nullable=false)
     */
    private $nombre;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     * @return RecoleccionBasura
     */
    public function setNombre($nombre)
    {
        $this->nombre = $nombre;

        return $this;
    }

    /**
     * Get nombre
     *
     * @return string
     */
    public function getNombre()
    {
        return $this->nombre;
    }
    public function __toString() {
        return $this->getNombre();
    }
}


text:
class OakArrayLiteralConstructor : public virtual IASTConstructor
{
public:

	typedef struct
	{

		bool ExplicitType;

		bool ExplicitCount;
		uint32_t ElementCount;

	} ElementData;

	OakArrayLiteralConstructor ();
	~OakArrayLiteralConstructor ();

	void TryConstruct ( ASTConstructionInput & Input, ASTConstructionOutput & Output ) const;

	static OakArrayLiteralConstructor & Instance ();

private:

	static void ElementDataDestructor ( void * Data );

	ASTConstructionGroup LiteralGroup;
	ASTConstructionGroup TypeGroup;
	ASTConstructionGroup ExpressionGroup;

};

#endif


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.livescribe.community.orm.UGCategory" table="UGCategory">

		<id name="primaryKey" column="primaryKey" type="binary">
			<generator class="assigned"/>
		</id>

		<property name="displayName"	column="displayName"	type="string"	length="128" />
		<property name="metaInfo"		column="metaInfo"		type="clob" />

	</class>
</hibernate-mapping>


text:
package com.esotericsoftware.kryonetty.network.handler;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class NetworkEventManager {

    private final ArrayList<NetworkListener> eventList;

    public NetworkEventManager() {
        this.eventList = new ArrayList<>();
    }

    public void register(NetworkListener networkListener) {
        if (!this.eventList.contains(networkListener))
            this.eventList.add(networkListener);
    }

    public void unregisterAll() {
        this.eventList.clear();
    }

    public void callEvent(NetworkEvent networkEvent) {
        for(NetworkListener networkListener : new ArrayList<>(this.eventList)) {
            for(Method method : networkListener.getClass().getMethods()) {
                if(method.isAnnotationPresent(NetworkHandler.class) && method.getAnnotation(NetworkHandler.class) != null) {
                    Class<?>[] methodParameter = method.getParameterTypes();
                    if(methodParameter.length == 1 && networkEvent.getClass().getSimpleName().equals(methodParameter[0].getSimpleName())) {
                        try {
                            method.setAccessible(true);
                            method.invoke(networkListener, networkEvent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<title>rewot :: submit</title>
	<link rel="stylesheet" href="/rewot.css">
	<link rel="stylesheet" href="/fa/css/font-awesome.min.css">

submit log

	<form action="/submit" method="post">

title: <input name="title"></input>

<textarea name="log"></textarea>

		<input type="hidden" name="web" value="True">

<input type="submit" name="submit" value="submit">

	</form>


text:
package stopwatchapp

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	homedir "github.com/mitchellh/go-homedir"
)

// Variables set during build
var (
	// electronVersion is a string that tells the embedded electron version.
	electronVersion string

	// astilectronVersion is a string that tells the embedded astilectron version.
	astilectronVersion string

	// appVersion is the application version
	appVersion string

	// devTools enbables or disables developer tool support. Set to "true" to enable
	// developer tools.
	devTools string

	// build is the applications build hash
	build string

	// name is the name of the application.
	name string

	// prefix gives a filesystem prefix for generated content (dirs etc).
	prefix string

	// resourcesDir is a path prefix for assets
	resourcesDir string

	// useTemp tells to unpack assets into temp instead of a permanent location.
	// If "true", app will disembed everything at startup and delete everything
	// at exit. It makes startup slower, but makes sure assets are always fresh.
	useTemp string
)

// Application icon embedded paths
const (
	EmbeddedIconPng  = "icons/app.png"  // linux
	EmbeddedIconIcns = "icons/app.icns" // mac
	EmbeddedIconIco  = "icons/app.ico"  // windows
)

// EmbeddedUIPackageName is the embedded ui package path
const EmbeddedUIPackageName = "ui/ui.asar"

// Window size constants. These are both the minimum and default values for
// application window size.
const (
	WindowWidth  = 412
	WindowHeight = 732
)

// Dimensions describes size in width and height in pixels.
type Dimensions struct {
	Height int
	Width  int
}

// BundledVendorVersions returns versions for vendored packages that are bundled in
// the binary
func BundledVendorVersions() VendorVersions {
	return VendorVersions{
		Astilectron: &VendorVersionsPackage{Version: astilectronVersion},
		Electron: map[string]*VendorVersionsPackage{
			provisionElectronKey(): &VendorVersionsPackage{
				Version: electronVersion,
			},
		},
	}
}

// Name returns the application name
func Name() string {
	return name
}

// Build returns current build version
func Build() string {
	return build
}

// Version returns the app version
func Version() string {
	return appVersion
}

// ElectronVersion returns bundled electron version
func ElectronVersion() string {
	return electronVersion
}

// AstilectronVersion returns bundled astilectron version
func AstilectronVersion() string {
	return astilectronVersion
}

// DevTools returns if devtools should be enabled
func DevTools() bool {
	return strings.EqualFold(devTools, "true")
}

// UseTemp returns if temp should be user for assets
func UseTemp() bool {
	return strings.EqualFold(useTemp, "true")
}

// EmbeddedResources returns a list of resources that need to be unpacked
func EmbeddedResources() []string {
	return []string{EmbeddedUIPath(), EmbeddedIconPath()}
}

// EmbeddedElectronPath returns the embedded Electron package path
func EmbeddedElectronPath() string {
	return fmt.Sprintf("%s/runtime/electron-%s-%s-%s.zip", resourcesDir, electronVersion, runtime.GOOS, runtime.GOARCH)
}

// EmbeddedAstilectronPath returns the embedded Astilectron package path
func EmbeddedAstilectronPath() string {
	return fmt.Sprintf("%s/runtime/astilectron-%s.zip", resourcesDir, astilectronVersion)
}

// EmbeddedIconPath returns the embedded path of application icon for current
// OS.
func EmbeddedIconPath() string {
	switch runtime.GOOS {
	case "windows":
		return path.Join(resourcesDir, EmbeddedIconIco)

	case "darwin":
		return path.Join(resourcesDir, EmbeddedIconIcns)

	default:
		return path.Join(resourcesDir, EmbeddedIconPng)
	}
}

// EmbeddedUIPath returns path to the UI package
func EmbeddedUIPath() string {
	return path.Join(resourcesDir, EmbeddedUIPackageName)
}

// EmbeddedUIMountPoint return the path to give for Electron to boot up the GUI
func EmbeddedUIMountPoint() string {
	return path.Join(EmbeddedUIPath(), "index.html")
}

// WindowSize returns the effective size to be used for new application window
// to get correct effective size (takes window chrome into account).
func WindowSize() Dimensions {
	switch runtime.GOOS {
	case "windows": // In windows window height is content + chrome, thus offset.
		return Dimensions{Height: WindowHeight + 38, Width: WindowWidth + 26}
	default:
		return Dimensions{Height: WindowHeight, Width: WindowWidth}
	}
}

// TmpDataDir returns an directory path for placing temporary assets
func TmpDataDir() (string, error) {
	return ioutil.TempDir("", prefix)
}

// PersistentDataDir returns an directory path for storing persistent data
func PersistentDataDir() (string, error) {
	home, err := homedir.Dir()
	if err != nil {
		return "", err
	}

	tgt := filepath.Join(home, "."+prefix, appVersion)
	if err = os.MkdirAll(tgt, 0700); err != nil && os.IsExist(err) == false {
		return "", err
	}

	return tgt, nil
}


text:
var getBounds = require('./getBounds');
var populate = require('./populate');
var sortLeds = require('./sortLeds');

class LedCanvasMatrix {
	constructor(x = 0, y = 0, width = 1, height = 1, leds = []){
		if (Array.isArray(leds)) {
			this.leds = leds;
		} else {
			this.leds = populate(width, height, leds);
		}

		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	get(x, y) {
		x = x % this.width;
		y = y % this.height;
		let led = this.leds[x + y * this.width];
		let leds = led ? [led] : undefined;
		return led ? new LedCanvasMatrix(x, y, 1, 1, leds) : null;
	}

	index(idx) {
		var led = this.leds[idx];
		return new LedCanvasMatrix(led.x, led.y, 1, 1, [led]);
	}

	prop(key, value) {
		let leds = this.leds.filter(function(led){
			return led[key] == value;
		});

		let bounds = getBounds(leds);
		return new LedCanvasMatrix(bounds.x, bounds.y, bounds.width, bounds.height, leds);
	}

	row(y) {
		return new LedCanvasMatrix(this.x, y, this.width, 1, this.leds.filter(function(led){
			return led.y == y;
		}));
	}

	column(x) {
		return new LedCanvasMatrix(x, this.y, 1, this.height, this.leds.filter(function(led){
			return led.x == x;
		}));
	}

	rect(x, y, width = 1, height = 1) {
		let xmax = x + width;
		let ymax = y + height;

		return new LedCanvasMatrix(x, y, width, height, this.leds.filter(function(led){
			return led.x >= x && led.x < xmax && led.y >= y && led.y < ymax;
		}));
	}

	set(key, value) {
		if (typeof key !== 'string') {
			this.leds.forEach(function(led){
				led.enabled = typeof key === 'undefined' ? true : key;
			});
		} else {
			this.leds.forEach(function(led){
				led.set(key, value);
			});
		}
		return this;
	}

	toggle() {
		this.leds.forEach(function(led){
			led.enabled = ! led.enabled;
		});

		return this;
	}

	render(...args) {
		this.leds.forEach(function(led){
			led.render(...args);
		});

		return this;
	}

	add(matrix) {
		let moved = matrix.leds.map((led) => {
			led.x += this.width;
			return led;
		});

		let leds = this.leds.concat(moved).sort(sortLeds);

		let bounds = getBounds(leds);
		return new LedCanvasMatrix(bounds.x, bounds.y, bounds.width, bounds.height, leds);
	}

	join(matrix, x = 0, y = 0) {
		let leds = matrix.leds.map((led) => {
			let xl = (matrix.x + led.x + x) % this.width;
			let yl = (matrix.y + led.y + y) % this.height;
			return this.get(xl, yl).set(led.enabled).leds[0];
		});

		let xc = (matrix.x + x) % this.width;
		let yc = (matrix.y + y) % this.width;
		return new LedCanvasMatrix(xc, yc, matrix.width, matrix.height, leds);
	}
}

module.exports = LedCanvasMatrix;


text: java -jar FactorioRatioAssistant.jar 0.15.11 init.txt


text:
using UnitsNet;
using UnitsNet.CustomCode.Extensions;
using UnitsNet.Units;

namespace Pk.Signals
{
  public struct VoltageSignal
  {
    public VoltageSignal(Waveform waveform, ElectricPotential rms)
    {
      this.Waveform = waveform;
      this.Rms = rms;
      this.Peak = ElectricPotential.FromVolts(this.Waveform.CalculatePeak(this.Rms.Volts));
      this.Gain = new AmplitudeRatio(this.Rms);
    }

    public VoltageSignal(Waveform waveform, AmplitudeRatio gain)
    {
      this.Waveform = waveform;
      this.Gain = gain;
      this.Rms = gain.ToElectricPotential();
      this.Peak = ElectricPotential.FromVolts(this.Waveform.CalculatePeak(this.Rms.Volts));
    }

    public AmplitudeRatio Gain { get; }
    public ElectricPotential Peak { get; }
    public ElectricPotential Rms { get; }
    public Waveform Waveform { get; }
    public static VoltageSignal AsSinusoid(AmplitudeRatio gain) { return new VoltageSignal(Waveform.Sinusoid, gain); }

    public static VoltageSignal FromPeakAsSinusoid(double peak)
    {
      var rms = ElectricPotential.FromVolts(Waveform.Sinusoid.CalculateRms(peak));
      return new VoltageSignal(Waveform.Sinusoid, rms);
    }

    public static VoltageSignal FromRmsAsSinusoid(double rms)
    {
      return VoltageSignal.FromRmsAsSinusoid(ElectricPotential.FromVolts(rms));
    }

    public static VoltageSignal FromPeakAsSinusoid(ElectricPotential peak)
    {
      return VoltageSignal.FromPeakAsSinusoid(peak.Volts);
    }

    public static VoltageSignal FromRmsAsSinusoid(ElectricPotential rms)
    {
      return new VoltageSignal(Waveform.Sinusoid, rms);
    }

    public static VoltageSignal Unity(Waveform waveform, AmplitudeRatioUnit unit)
    {
      var gain = AmplitudeRatio.From(0, unit);
      return new VoltageSignal(waveform, gain);
    }
  }
}


text:
import React from 'react';
import { Link } from 'react-router';

export default class Layout extends React.Component {
    render () {
        return (

                    <Link to="/">

                    </Link>

{this.props.children}

                        This is a demo app!

        );
    }
}


text:
<?php namespace August\TimeInterval\Facades;

use Illuminate\Support\Facades\Facade;

class TimeInterval extends Facade {

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'timeinterval'; }

}


text:
import './global.css';

// Import vendor scripts which are not dynamically imported
// E.g. the moment package is dynamically imported, see "ping.js"
import 'hyperapp';
import '@hyperapp/router';

// +++ other 3'rd party, e.g. lodash


text:
package org.apache.camel.component.slack;

import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;

/**
 * The slack component allows you to send messages to Slack.
 */
@UriEndpoint(firstVersion = "2.16.0", scheme = "slack", title = "Slack", syntax = "slack:channel", producerOnly = true, label = "social")
public class SlackEndpoint extends DefaultEndpoint {

    @UriPath @Metadata(required = "true")
    private String channel;
    @UriParam
    private String webhookUrl;
    @UriParam(secret = true)
    private String username;
    @UriParam
    private String iconUrl;
    @UriParam
    private String iconEmoji;

    /**
     * Constructor for SlackEndpoint
     *
     * @param uri the full component url
     * @param channelName the channel or username the message is directed at
     * @param component the component that was created
     */
    public SlackEndpoint(String uri, String channelName, SlackComponent component) {
        super(uri, component);
        this.webhookUrl = component.getWebhookUrl();
        this.channel = channelName;
    }

    @Override
    public Producer createProducer() throws Exception {
        SlackProducer producer = new SlackProducer(this);
        return producer;
    }

    @Override
    public Consumer createConsumer(Processor processor) throws Exception {
        throw new UnsupportedOperationException("You cannot consume slack messages from this endpoint: " + getEndpointUri());
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    /**
     * The incoming webhook URL
     */
    public void setWebhookUrl(String webhookUrl) {
        this.webhookUrl = webhookUrl;
    }

    public String getWebhookUrl() {
        return webhookUrl;
    }

    public String getChannel() {
        return channel;
    }

    /**
     * The channel name (syntax #name) or slackuser (syntax @userName) to send a message directly to an user.
     */
    public void setChannel(String channel) {
        this.channel = channel;
    }

    public String getUsername() {
        return username;
    }

    /**
     * This is the username that the bot will have when sending messages to a channel or user.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public String getIconUrl() {
        return iconUrl;
    }

    /**
     * The avatar that the component will use when sending message to a channel or user.
     */
    public void setIconUrl(String iconUrl) {
        this.iconUrl = iconUrl;
    }

    public String getIconEmoji() {
        return iconEmoji;
    }

    /**
     * Use a Slack emoji as an avatar
     */
    public void setIconEmoji(String iconEmoji) {
        this.iconEmoji = iconEmoji;
    }
}