text:
using Scheduler.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Scheduler.Data
{
    public class SchedulerDbInitializer
    {
        private static SchedulerContext context;
        public static void Initialize(IServiceProvider serviceProvider)
        {
            context = (SchedulerContext)serviceProvider.GetService(typeof(SchedulerContext));

            InitializeSchedules();
        }

        private static void InitializeSchedules()
        {
            if(!context.Users.Any())
            {
                User user_01 = new User { Name = "Chris Sakellarios", Profession = "Developer", Avatar = "avatar_02.png" };

                User user_02 = new User { Name = "Charlene Campbell", Profession = "Web Designer", Avatar = "avatar_03.jpg" };

                User user_03 = new User { Name = "Mattie Lyons", Profession = "Engineer", Avatar = "avatar_05.png" };

                User user_04 = new User { Name = "Kelly Alvarez", Profession = "Network Engineer", Avatar = "avatar_01.png" };

                User user_05 = new User { Name = "Charlie Cox", Profession = "Developer", Avatar = "avatar_03.jpg" };

                User user_06 = new User { Name = "Megan	Fox", Profession = "Hacker", Avatar = "avatar_05.png" };

                context.Users.Add(user_01); context.Users.Add(user_02);
                context.Users.Add(user_03); context.Users.Add(user_04);
                context.Users.Add(user_05); context.Users.Add(user_06);

                context.SaveChanges();
            }

            if(!context.Schedules.Any())
            {
                Schedule schedule_01 = new Schedule
                {
                    Title = "Meeting",
                    Description = "Meeting at work with the boss",
                    Location = "Korai",
                    CreatorId = 1,
                    Status = ScheduleStatus.Valid,
                    Type = ScheduleType.Work,
                    TimeStart = DateTime.Now.AddHours(4),
                    TimeEnd = DateTime.Now.AddHours(6),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 1, UserId = 2 },
                        new Attendee() { ScheduleId = 1, UserId = 3 },
                        new Attendee() { ScheduleId = 1, UserId = 4 }
                    }
                };

                Schedule schedule_02 = new Schedule
                {
                    Title = "Coffee",
                    Description = "Coffee with folks",
                    Location = "Athens",
                    CreatorId = 2,
                    Status = ScheduleStatus.Valid,
                    Type = ScheduleType.Coffee,
                    TimeStart = DateTime.Now.AddHours(3),
                    TimeEnd = DateTime.Now.AddHours(6),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 2, UserId = 1 },
                        new Attendee() { ScheduleId = 1, UserId = 3 },
                        new Attendee() { ScheduleId = 2, UserId = 4 }
                    }
                };

                Schedule schedule_03 = new Schedule
                {
                    Title = "Shopping day",
                    Description = "Shopping therapy",
                    Location = "Attica",
                    CreatorId = 3,
                    Status = ScheduleStatus.Valid,
                    Type = ScheduleType.Shopping,
                    TimeStart = DateTime.Now.AddHours(3),
                    TimeEnd = DateTime.Now.AddHours(6),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 3, UserId = 1 },
                        new Attendee() { ScheduleId = 3, UserId = 4 },
                        new Attendee() { ScheduleId = 3, UserId = 5 }
                    }
                };

                Schedule schedule_04 = new Schedule
                {
                    Title = "Family",
                    Description = "Thanks giving day",
                    Location = "Home",
                    CreatorId = 5,
                    Status = ScheduleStatus.Valid,
                    Type = ScheduleType.Other,
                    TimeStart = DateTime.Now.AddHours(3),
                    TimeEnd = DateTime.Now.AddHours(6),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 4, UserId = 1 },
                        new Attendee() { ScheduleId = 4, UserId = 2 },
                        new Attendee() { ScheduleId = 4, UserId = 5 }
                    }
                };

                Schedule schedule_05 = new Schedule
                {
                    Title = "Friends",
                    Description = "Friends giving day",
                    Location = "Home",
                    CreatorId = 5,
                    Status = ScheduleStatus.Cancelled,
                    Type = ScheduleType.Other,
                    TimeStart = DateTime.Now.AddHours(5),
                    TimeEnd = DateTime.Now.AddHours(7),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 4, UserId = 1 },
                        new Attendee() { ScheduleId = 4, UserId = 2 },
                        new Attendee() { ScheduleId = 4, UserId = 3 },
                        new Attendee() { ScheduleId = 4, UserId = 4 },
                        new Attendee() { ScheduleId = 4, UserId = 5 }
                    }
                };

                Schedule schedule_06 = new Schedule
                {
                    Title = "Meeting with the boss and collegues",
                    Description = "Discuss project planning",
                    Location = "Office",
                    CreatorId = 3,
                    Status = ScheduleStatus.Cancelled,
                    Type = ScheduleType.Other,
                    TimeStart = DateTime.Now.AddHours(22),
                    TimeEnd = DateTime.Now.AddHours(30),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 4, UserId = 1 },
                        new Attendee() { ScheduleId = 4, UserId = 2 },
                        new Attendee() { ScheduleId = 4, UserId = 5 }
                    }
                };

                Schedule schedule_07 = new Schedule
                {
                    Title = "Scenario presentation",
                    Description = "Discuss new movie's scenario",
                    Location = "My special place",
                    CreatorId = 6,
                    Status = ScheduleStatus.Cancelled,
                    Type = ScheduleType.Other,
                    TimeStart = DateTime.Now.AddHours(11),
                    TimeEnd = DateTime.Now.AddHours(13),
                    Attendees = new List<Attendee>
                    {
                        new Attendee() { ScheduleId = 4, UserId = 4 },
                        new Attendee() { ScheduleId = 4, UserId = 2 },
                        new Attendee() { ScheduleId = 4, UserId = 3 }
                    }
                };

                context.Schedules.Add(schedule_01); context.Schedules.Add(schedule_02);
                context.Schedules.Add(schedule_03); context.Schedules.Add(schedule_04);
                context.Schedules.Add(schedule_05); context.Schedules.Add(schedule_06);
            }

            context.SaveChanges();
        }
    }
}


text:
namespace quic {

// QboneTunnelSilo is a thread that initializes and evaluates a QboneTunnel's
// event loop.
class QboneTunnelSilo : public QuicThread {
 public:
  // Does not take ownership of |tunnel|
  explicit QboneTunnelSilo(QboneTunnelInterface* tunnel, bool only_setup_tun)
      : QuicThread("QboneTunnelSilo"),
        tunnel_(tunnel),
        only_setup_tun_(only_setup_tun) {}

  QboneTunnelSilo(const QboneTunnelSilo&) = delete;
  QboneTunnelSilo& operator=(const QboneTunnelSilo&) = delete;

  QboneTunnelSilo(QboneTunnelSilo&&) = delete;
  QboneTunnelSilo& operator=(QboneTunnelSilo&&) = delete;

  // Terminates the tunnel's event loop. This silo must still be joined.
  void Quit();

 protected:
  void Run() override;

 private:
  bool ShouldRun();

  QboneTunnelInterface* tunnel_;

  absl::Notification quitting_;

  const bool only_setup_tun_;
};

}  // namespace quic

#endif  // QUICHE_QUIC_QBONE_BONNET_QBONE_TUNNEL_SILO_H_

redpajama_set_name: RedPajamaGithub


text:
layout: article
title: "Ser adaptable"
description: "Se puede acceder a la Web desde una amplia gama de dispositivos, desde teléfonos de pantalla pequeña a televisores de grandes dimensiones. Obtén más información sobre cómo crear un sitio que funcione bien en todos estos dispositivos."
introduction: "Se puede acceder a la Web desde una amplia gama de dispositivos, desde teléfonos de pantalla pequeña a televisiones de grandes dimensiones. Cada dispositivo presenta ciertas ventajas propias, pero también limitaciones. Como desarrollador web, el público espera que crees sitios compatibles con todas las gamas de dispositivos."
key-takeaways:
  make-responsive:
    - Utiliza siempre una ventana gráfica.
    - Empieza siempre con una ventana gráfica estrecha y después aumenta el tamaño.
    - Basa los puntos de interrupción en los momentos en los que es necesario adaptar el contenido.
    - Crea una visión de nivel alto de tu diseño con los puntos de interrupción principales.
authors:
  - paulkinlan
translators:
related-guides:
  responsive:
    -
      title: Establecer la ventana gráfica
      href: fundamentals/layouts/rwd-fundamentals/set-the-viewport
      section:
        title: "Diseño web adaptable"
        href: fundamentals/layouts/rwd-fundamentals/set-the-viewport
    -
      title: Adaptar el tamaño del contenido a la ventana gráfica
      href: fundamentals/layouts/rwd-fundamentals/size-content-to-the-viewport
      section:
        id: rwd-fundamentals
        title: "Diseño web adaptable"
        href: fundamentals/layouts/rwd-fundamentals/size-content-to-the-viewport
  first-break-point:
    -
      title: Usar consultas multimedia
      href: fundamentals/layouts/rwd-fundamentals/use-media-queries
      section:
        id: rwd-fundamentals
        title: "Diseño web adaptable"
        href: fundamentals/layouts/rwd-fundamentals/use-media-queries
    -
      title: Patrones de diseño
      href: fundamentals/layouts/rwd-patterns/
      section:
        id: rwd-patterns
        title: "Patrones de diseño"
        href: fundamentals/layouts/rwd-patterns/
    -
      title: Diseño principalmente fluido
      href: fundamentals/layouts/rwd-patterns/mostly-fluid
      section:
        id: rwd-patterns
        title: "Diseño web adaptable"
        href: fundamentals/layouts/rwd-patterns/mostly-fluid
  images:
    -
      title: "Optimizar imágenes con el atributo srcset para dispositivos con alta proporción de puntos por pulgada"
      href: fundamentals/media/images/images-in-markup.html#enhance-imgs-with-srcset-for-high-dpi-devices
      section:
        id: images
        title: "Imágenes"
        href: media/images/
    -
      title: "Utilizar consultas multimedia para proporcionar imágenes de alta resolución o dirección de recursos gráficos"
      href: fundamentals/media/images/images-in-css.html#use-media-queries-for-conditional-image-loading-or-art-direction
      section:
        id: images
        title: "Imágenes"
        href: media/images/
notes:
  styling:
    - Hemos dado por supuesto un conjunto de estilos que incluyen color, espaciado interno y estilo de fuente que coinciden con nuestras directrices de marca.
  not-all-at-once:
    - No tienes que mover todos los elementos a la vez, sino que, si es necesario, puedes hacer ajustes menores.
article:
  written_on: 2014-04-17
  updated_on: 2014-04-23
  order: 2
collection: multi-screen
id: multi-screen-responsive
---

{% wrap content %}

{% include modules/toc.liquid %}

Vamos a crear un sitio que funciona en varios tamaños de pantalla y tipos de dispositivo. En el [artículo anterior]({{site.baseurl}}{{page.article.previous.url}}), creamos la arquitectura de información de la página y creamos una estructura básica.
En esta guía, vamos a utilizar esa estructura básica con contenido y la vamos a convertir en una atractiva página que se adapte a un gran número de tamaños de pantalla.

{% link_sample _code/content-without-styles.html %} Contenido y estructura {% endlink_sample %}

{% link_sample _code/content-with-styles.html %} Sitio finalizado {% endlink_sample %}

Siguiendo los principios del desarrollo web Mobile First, vamos a empezar con una ventana gráfica estrecha (parecida a un dispositivo móvil) y vamos a desarrollar primero para esa experiencia.
Después ampliaremos el tamaño para dispositivos más grandes.
Para ello, ampliaremos el ancho de la ventana gráfica y decidimos si el diseño nos satisface.

Antes hemos creado un par de diseños diferentes de alto nivel que definen la visualización del contenido. Ahora tenemos que definir que la página se adapte a esos diferentes diseños.
La forma de definirlo es decidir dónde queremos colocar los puntos de interrupción (un punto en el que el diseño y el estilo cambian) en función del modo en el que el contenido se adapta al tamaño de pantalla.

{% include modules/takeaway.liquid list=page.key-takeaways.make-responsive %}

## Añadir una ventana gráfica

Aunque la página sea básica, siempre **tienes** que incluir una metaetiqueta de ventana gráfica.
La ventana gráfica es el componente más importante que necesitas para crear experiencias multidispositivo.
Sin ella, el sitio no funcionará bien en un dispositivo móvil.

La ventana gráfica indica al navegador que el tamaño de la página se tiene que adaptar a la pantalla.  Puede que haya muchas configuraciones diferentes que puedes especificar para que la ventana gráfica controle la visualización de la página.  De forma predeterminada, recomendamos esta configuración:

{% include_code _code/viewport.html viewport %}

La ventana gráfica reside en el encabezamiento del documento y solo se tiene que declarar una vez.

{% include modules/related_guides.liquid inline=true list=page.related-guides.responsive %}

## Aplicar un estilo sencillo

Nuestro producto y nuestra empresa ya tienen unas directrices de marca y de fuente muy específicas indicadas en una guía de estilo.

### Guía de estilo

Una guía de estilo es una forma práctica de obtener una explicación de nivel alto de la representación visual de la página y, además, ayuda a garantizar la homogeneidad del diseño.

#### Color

#39b1a4

#ffffff

#f5f5f5

#e9e9e9

#dc4d38

### Añadir imágenes estilísticas

En la guía anterior, hemos añadido imágenes llamadas `imágenes de contenido`.  Eran imágenes importantes para la narrativa de nuestro producto.  Las imágenes estilísticas son imágenes que no forman parte del contenido central pero que añaden un toque visual o ayudan a guiar la atención del usuario a una parte específica del contenido.

Un buen ejemplo sería una imagen de título para el contenido situado en la mitad superior de la página. A menudo se utiliza para atraer al usuario para que obtenga más información del producto.

Incluirlas puede ser muy sencillo. En nuestro caso, va a hacer de fondo del encabezado y la vamos a aplicar con un CSS sencillo.

{% highlight css %}
#headline {
  padding: 0.8em;
  color: white;
  font-family: Roboto, sans-serif;
  background-image: url(backgroundimage.jpg);
  background-size: cover;
}
{% endhighlight %}

Hemos elegido una imagen de fondo sencilla que está difuminada para que no interfiera con el contenido. Además, hemos establecido que ocupe todo el elemento, así se amplía sin modificar la relación de aspecto.

## Establezca su primer punto de interrupción

El diseño empieza a perder calidad a los 600 px de ancho.  En nuestro caso, la longitud de la línea va a ser superior a diez palabras (la longitud de lectura óptima) y conviene cambiarla llegada esa cifra.

<video controls poster="images/firstbreakpoint.png" style="width: 100%;">
  <source src="videos/firstbreakpoint.mov" type="video/mov"></source>
  <source src="videos/firstbreakpoint.webm" type="video/webm"></source>

Lo sentimos, pero tu navegador no permite reproducir vídeo.
     Descarga el vídeo.

</video>

Parece que los 600 px es un buen sitio para crear el primer punto de interrupción, ya que nos proporcionará el punto de mira para recolocar elementos y que así se ajusten mejor a la pantalla.  Para crearlo, podemos utilizar una tecnología llamada [consultas multimedia]({{site.fundamentals}}/layouts/rwd-fundamentals/#use-css-media-queries-for-responsiveness).

{% highlight css %}
@media (min-width: 600px) {

}
{% endhighlight %}

En las pantallas de mayor tamaño hay más espacio, así que también hay más flexibilidad en cuanto a la forma de mostrar contenido.

{% include modules/remember.liquid title="Note" list=page.notes.not-all-at-once %}

En el contexto de nuestra página de producto, parece necesario:

*  restringir el ancho máximo del diseño,
*  modificar el espaciado interno de elementos y disminuir el tamaño del texto,
*  mover el formulario para que esté alineado con el contenido de encabezado,
*  establecer que el vídeo flote alrededor del contenido,
*  reducir el tamaño de las imágenes y definir que aparezcan según una cuadrícula más atractiva.

{% include modules/related_guides.liquid inline=true list=page.related-guides.first-break-point %}

## Restringir el ancho máximo del diseño

Hemos decidido utilizar solo dos diseños principales: una ventana gráfica estrecha y una ventana gráfica ancha, de modo que nuestro proceso de creación se simplifica en gran medida.

También hemos decidido crear secciones de sangrado completo en la ventana gráfica estrecha que sigan siendo de sangrado completo en la ventana gráfica ancha.  Esto quiere decir que debemos restringir el ancho máximo de la pantalla para que el texto y los párrafos no se prolonguen en una sola línea larga en las pantallas de anchura extrema.  Hemos decidido que ese punto sean los 800 px aproximadamente.

Para lograrlo, tenemos que restringir el ancho y centrar los elementos.  Tenemos que crear un contenedor alrededor de cada sección principal y aplicar un atributo `margin: auto`. Así la pantalla podrá crecer pero el contenido seguirá centrado y a un tamaño máximo de 800 px.

El contenedor será un atributo `div` sencillo con la forma siguiente:

{% highlight html %}
...
{% endhighlight %}

{% include_code _code/fixingfirstbreakpoint.html containerhtml html %}

{% include_code _code/fixingfirstbreakpoint.html container css %}

## Modificar el espaciado interno y reducir el tamaño de texto

En la ventana gráfica estrecha no tenemos mucho espacio para mostrar contenido, por lo que el tamaño y el peso de la tipografía se suelen reducir de forma drástica para que se ajusten a la pantalla.

Si la ventana gráfica es más ancha, tenemos que tener en cuenta que es más probable que el usuario se encuentre ante una pantalla más grande pero más alejado.  Para incrementar la facilidad de lectura del contenido, podemos aumentar el tamaño y el peso de la tipografía, además de modificar el espaciado interno para resaltar ciertas áreas.

En nuestra página de producto, para aumentar el espaciado interno de los elementos de la sección, estableceremos que el ancho del contenido siga estando a un 5%.  También aumentaremos el tamaño de los encabezados de cada sección.

{% include_code _code/fixingfirstbreakpoint.html padding css %}

## Adaptar elementos a una ventana gráfica ancha

Nuestra ventana gráfica estrecha era una pantalla lineal apilada.  Cada sección importante y el contenido incluido se mostraban en orden de arriba abajo.

Las ventanas gráficas anchas nos proporcionan espacio adicional que podemos utilizar para mostrar el contenido de forma óptima para la pantalla en cuestión.  Para nuestra página de producto, esto quiere decir que, de acuerdo con nuestra arquitectura de información, podemos:

*  mover el formulario alrededor de la información del encabezado,
*  colocar el vídeo a la derecha de los puntos clave,
*  titular las imágenes,
*  ampliar la tabla.

### Hacer flotar el elemento de formulario

Al tener una ventana gráfica estrecha, tenemos disponible mucho menos espacio horizontal para colocar con comodidad los elementos de la pantalla.

Para utilizar el espacio horizontal de la pantalla de forma más eficiente, tenemos que romper el flujo lineal del encabezado y mover el formulario y la lista para que estén uno al lado del otro.

{% include_code _code/fixingfirstbreakpoint.html formfloat css %}

{% include_code _code/fixingfirstbreakpoint.html padding css %}

<video controls poster="images/floatingform.png" style="width: 100%;">
  <source src="videos/floatingform.mov" type="video/mov"></source>
  <source src="videos/floatingform.webm" type="video/webm"></source>

Lo sentimos, pero tu navegador no permite reproducir vídeo.
     Descarga el vídeo.

</video>

### Hacer flotar el elemento de vídeo

El vídeo de la interfaz de ventana gráfica estrecha está diseñado para que ocupe el ancho total de la pantalla y se sitúe después de la lista de funciones clave. En una ventana gráfica ancha, el vídeo se amplía demasiado y parece incorrecto cuando se sitúa junto a nuestra lista de funciones.

El elemento de vídeo se tiene que sacar del flujo vertical de la ventana gráfica estrecha y se tiene que mostrar en paralelo a la lista con viñetas de contenido de una ventana gráfica ancha.

{% include_code _code/fixingfirstbreakpoint.html floatvideo css %}

### Titular las imágenes

Las imágenes de la interfaz de ventana gráfica estrecha (sobre todo en dispositivos móviles) están configuradas para que ocupen el ancho total de la pantalla y se apilen en vertical.  Este diseño no se amplía bien en una ventana gráfica ancha.

Para que el aspecto de las imágenes sea correcto, se amplían un 30% del ancho del contenedor y se colocan en horizontal (en vez de en vertical en la ventana gráfica ancha). También vamos a añadir algunos radios de borde y sombra del cuadro para que las imágenes sean más atractivas.

{% include_code _code/fixingfirstbreakpoint.html tileimages css %}

### Definir que las imágenes se adapten a los puntos por pulgada

Si usas imágenes, ten en cuenta el tamaño de la ventana gráfica y la densidad de la pantalla.

La Web está creada para pantallas de 96 ppp.  Con la introducción de los dispositivos móviles, hemos visto cómo aumentaba en gran medida la densidad de píxeles de las pantallas, por no hablar las pantallas de clase Retina de los portátiles.  Por eso, las imágenes codificadas para 96 ppp suelen mostrarse mal en los dispositivos con ppp alto.

Tenemos una solución que aún no se ha extendido.
En el caso de los navegadores compatibles, puedes mostrar una imagen de alta densidad en una pantalla de alta densidad,

{% highlight html %}

{% endhighlight %}

{% include modules/related_guides.liquid inline=true list=page.related-guides.images %}

### Tablas

Es muy difícil mostrar bien las tablas en los dispositivos que tienen una ventana gráfica estrecha y, por eso, necesitan una consideración especial.

Te recomendamos que, en una ventana gráfica estrecha, dividas la tabla en dos filas y pases el encabezado y las celdas a una fila para crear el columnado.

<video controls poster="images/responsivetable.png" style="width: 100%;">
  <source src="videos/responsivetable.mov" type="video/mov"></source>
  <source src="videos/responsivetable.webm" type="video/webm"></source>

Lo sentimos, pero tu navegador no permite reproducir vídeo.
     Descarga el vídeo.

</video>

En nuestro sitio, hemos tenido que crear un punto de interrupción adicional para el contenido de la tabla.
Como al crear primero para un dispositivo móvil es más difícil deshacer los estilos aplicados, tenemos que seccionar el CSS de tablas de la ventana gráfica estrecha a partir del CSS de la ventana gráfica ancha.
Así obtenemos una interrupción clara y constante.

{% include_code _code/content-with-styles.html table-css css %}

## Conclusión

**ENHORABUENA.** Para cuando leas esto, habrás creado tu primera página de destino sencilla para el producto que funcione en una amplia gama de dispositivos, factores de formulario y tamaños de pantalla.

Si sigues estas directrices, empezarás con buen pie:

1.  Crea una arquitectura de información básica y entiende el contenido antes de crear código.
2.  Configura siempre una ventana gráfica.
3.  Crea tu experiencia básica a partir del método de `dispositivo móvil primero`.
4.  Cuando ya tengas la experiencia para dispositivos móviles, incrementa el ancho de la pantalla hasta que no se vea bien y establece ahí el punto de interrupción.
5.  Repite los pasos.

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
package net.catchpole.B9.codec.transcoder;

import net.catchpole.B9.codec.stream.BitInputStream;
import net.catchpole.B9.codec.stream.BitOutputStream;

import java.io.IOException;

class ShortTranscoder implements TypeTranscoder<Short> {
    public Short read(BitInputStream in) throws IOException {
        if (!in.readBoolean()) {
            return 0;
        }
        return (short)in.read(16);
    }

    public void write(BitOutputStream out, Short value) throws IOException {
        out.writeBoolean(value != 0);
        if (value != 0) {
            out.write(value & 0xffff, 16);
        }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="ICloudBlob.Common.cs" company="Microsoft">
//    Copyright 2013 Microsoft Corporation
//
//    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.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.WindowsAzure.Storage.Blob
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// An interface required for Windows Azure blob types. The <see cref="CloudBlockBlob"/> and <see cref="CloudPageBlob"/> classes implement the <see cref="ICloudBlob"/> interface.
    /// </summary>
    public partial interface ICloudBlob : IListBlobItem
    {
        /// <summary>
        /// Gets the blob's name.
        /// </summary>
        /// <value>A string containing the name of the blob.</value>
        string Name { get; }

        /// <summary>
        /// Gets the <see cref="CloudBlobClient"/> object that represents the Blob service.
        /// </summary>
        /// <value>A <see cref="CloudBlobClient"/> object.</value>
        CloudBlobClient ServiceClient { get; }

        /// <summary>
        /// Gets or sets the number of bytes to buffer when writing to a page blob stream or
        /// the block size for writing to a block blob.
        /// </summary>
        /// <value>The number of bytes to buffer or the size of a block, in bytes.</value>
        int StreamWriteSizeInBytes { get; set; }

        /// <summary>
        /// Gets or sets the minimum number of bytes to buffer when reading from a blob stream.
        /// </summary>
        /// <value>The minimum number of bytes to buffer.</value>
        int StreamMinimumReadSizeInBytes { get; set; }

        /// <summary>
        /// Gets the blob's system properties.
        /// </summary>
        /// <value>A <see cref="BlobProperties"/> object.</value>
        BlobProperties Properties { get; }

        /// <summary>
        /// Gets the user-defined metadata for the blob.
        /// </summary>
        /// <value>An <see cref="IDictionary{TKey,TValue}"/> object containing the blob's metadata as a collection of name-value pairs.</value>
        IDictionary<string, string> Metadata { get; }

        /// <summary>
        /// Gets the date and time that the blob snapshot was taken, if this blob is a snapshot.
        /// </summary>
        /// <value>A <see cref="DateTimeOffset"/> containing the blob's snapshot time if the blob is a snapshot; otherwise, <c>null</c>.</value>
        /// <remarks>
        /// If the blob is not a snapshot, the value of this property is <c>null</c>.
        /// </remarks>
        DateTimeOffset? SnapshotTime { get; }

        /// <summary>
        /// Gets a value indicating whether this blob is a snapshot.
        /// </summary>
        /// <value><c>true</c> if this blob is a snapshot; otherwise, <c>false</c>.</value>
        bool IsSnapshot { get; }

        /// <summary>
        /// Gets the absolute URI to the blob, including query string information if the blob is a snapshot.
        /// </summary>
        /// <value>A <see cref="System.Uri"/> specifying the absolute URI to the blob, including snapshot query information if the blob is a snapshot.</value>
        Uri SnapshotQualifiedUri { get; }

        /// <summary>
        /// Gets the blob's URI for both the primary and secondary locations, including query string information if the blob is a snapshot.
        /// </summary>
        /// <value>An object of type <see cref="StorageUri"/> containing the blob's URIs for both the primary and secondary locations,
        /// including snapshot query information if the blob is a snapshot.</value>
        StorageUri SnapshotQualifiedStorageUri { get; }

        /// <summary>
        /// Gets the state of the most recent or pending copy operation.
        /// </summary>
        /// <value>A <see cref="CopyState"/> object containing the copy state, or <c>null</c> if there is no copy state for the blob.</value>
        CopyState CopyState { get; }

        /// <summary>
        /// Gets the type of the blob.
        /// </summary>
        /// <value>A <see cref="BlobType"/> enumeration value.</value>
        BlobType BlobType { get; }

#if !PORTABLE
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
        string GetSharedAccessSignature(SharedAccessBlobPolicy policy);

        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        /// <remarks>The query string returned includes the leading question mark.</remarks>
#if WINDOWS_RT
        [Windows.Foundation.Metadata.DefaultOverload]
#endif
        string GetSharedAccessSignature(SharedAccessBlobPolicy policy, string groupPolicyIdentifier);

        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers);

        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier);

        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format. Value must be <c>2012-02-12</c> or later.</param>
        /// <returns>A shared access signature.</returns>
        string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, string sasVersion);
#endif
    }
}


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

  <title>Description of tpsGetWarp</title>
  <meta name="keywords" content="tpsGetWarp">
  <meta name="description" content="Given two sets of corresponding points, calculates warp between them.">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../m2html.css">

tpsGetWarp

PURPOSE

Given two sets of corresponding points, calculates warp between them.

SYNOPSIS

function [warp,L,LnInv,bendE] = tpsGetWarp( lambda, xsS, ysS, xsD, ysD )

DESCRIPTION

 Given two sets of corresponding points, calculates warp between them.

 Uses booksteins PAMI89 method.  Can then apply warp to a new set of
 points (tpsInterpolate), or even an image (tpsInterpolateIm).
  "Principal Warps: Thin-Plate Splines and the Decomposition of
  Deformations".  Bookstein.  PAMI 1989.

 USAGE
  [warp,L,LnInv,bendE] = tpsGetWarp( lambda, xsS, ysS, xsD, ysD )

 INPUTS
  lambda      - rigidity of warp (inf means warp becomes affine)
  xsS, ysS    - [1xn] correspondence points from source image
  xsD, ysD    - [1xn] correspondence points from destination image

 OUTPUTS
  warp        - bookstein warping parameters
  L, LnInv    - see bookstein
  bendE       - bending energy

 EXAMPLE - 1
  xsS=[0 -1 0 1];  ysS=[1 0 -1 0];  xsD=xsS;  ysD=[3/4 1/4 -5/4 1/4];
  warp = tpsGetWarp( 0, xsS, ysS, xsD, ysD );
  [gxs, gys] = meshgrid(-1.25:.25:1.25,-1.25:.25:1.25);
  tpsInterpolate( warp, gxs, gys, 1 );

 EXAMPLE - 2
  xsS = [3.6929 6.5827 6.7756 4.8189 5.6969];
  ysS = [10.3819 8.8386 12.0866 11.2047 10.0748];
  xsD = [3.9724 6.6969 6.5394 5.4016 5.7756];
  ysD = [6.5354 4.1181 7.2362 6.4528 5.1142];
  warp = tpsGetWarp( 0, xsS, ysS, xsD, ysD );
  [gxs, gys] = meshgrid(3.5:.25:7, 8.5:.25: 12.5);
  tpsInterpolate( warp, gxs, gys, 1 );

 See also TPSINTERPOLATE, TPSINTERPOLATEIM, TPSRANDOM

 Piotr's Image&Video Toolbox      Version 2.0
 Copyright 2012 Piotr Dollar.  [pdollar-at-caltech.edu]
 Please email me if you find bugs, or have suggestions or questions!
 Licensed under the Simplified BSD License [see external/bsd.txt]

<address>Generated by m2html © 2003</address>


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\RuleSet\Sets;

use PhpCsFixer\RuleSet\AbstractRuleSetDescription;

/**
 * @internal
 */
final class PhpCsFixerSet extends AbstractRuleSetDescription
{
    public function getRules(): array
    {
        return [
            '@Symfony' => true,
            'align_multiline_comment' => true,
            'array_indentation' => true,
            'blank_line_before_statement' => [
                'statements' => [
                    'break',
                    'case',
                    'continue',
                    'declare',
                    'default',
                    'exit',
                    'goto',
                    'include',
                    'include_once',
                    'phpdoc',
                    'require',
                    'require_once',
                    'return',
                    'switch',
                    'throw',
                    'try',
                    'yield',
                ],
            ],
            'combine_consecutive_issets' => true,
            'combine_consecutive_unsets' => true,
            'empty_loop_body' => true,
            'escape_implicit_backslashes' => true,
            'explicit_indirect_variable' => true,
            'explicit_string_variable' => true,
            'heredoc_to_nowdoc' => true,
            'method_argument_space' => [
                'on_multiline' => 'ensure_fully_multiline',
            ],
            'method_chaining_indentation' => true,
            'multiline_comment_opening_closing' => true,
            'multiline_whitespace_before_semicolons' => [
                'strategy' => 'new_line_for_chained_calls',
            ],
            'no_extra_blank_lines' => [
                'tokens' => [
                    'break',
                    'case',
                    'continue',
                    'curly_brace_block',
                    'default',
                    'extra',
                    'parenthesis_brace_block',
                    'return',
                    'square_brace_block',
                    'switch',
                    'throw',
                    'use',
                ],
            ],
            'no_null_property_initialization' => true,
            'no_superfluous_elseif' => true,
            'no_useless_else' => true,
            'no_useless_return' => true,
            'operator_linebreak' => [
                'only_booleans' => true,
            ],
            'ordered_class_elements' => true,
            'php_unit_internal_class' => true,
            'php_unit_test_class_requires_covers' => true,
            'phpdoc_add_missing_param_annotation' => true,
            'phpdoc_no_empty_return' => true,
            'phpdoc_order' => true,
            'phpdoc_order_by_value' => true,
            'phpdoc_types_order' => true,
            'phpdoc_var_annotation_correct_order' => true,
            'return_assignment' => true,
            'simple_to_complex_string_variable' => true,
            'single_line_comment_style' => true,
            'single_line_throw' => false,
        ];
    }

    public function getDescription(): string
    {
        return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.';
    }
}


text:
class KpmException(Exception):
    status_code = 500
    errorcode = "internal-error"

    def __init__(self, message, payload=None):
        super(KpmException, self).__init__()
        self.payload = dict(payload or ())
        self.message = message

    def to_dict(self):
        r = {"code": self.errorcode,
             "message": self.message,
             "details": self.payload}
        return r

    def __str__(self):
        return self.message

class InvalidUsage(KpmException):
    status_code = 400
    errorcode = "invalid-usage"

class InvalidVersion(KpmException):
    status_code = 422
    errorcode = "invalid-version"

class PackageAlreadyExists(KpmException):
    status_code = 409
    errorcode = "package-exists"

class ChannelAlreadyExists(KpmException):
    status_code = 409
    errorcode = "channel-exists"

class PackageNotFound(KpmException):
    status_code = 404
    errorcode = "package-not-found"

class ChannelNotFound(KpmException):
    status_code = 404
    errorcode = "channel-not-found"

class PackageVersionNotFound(KpmException):
    status_code = 404
    errorcode = "package-version-not-found"

class UnauthorizedAccess(KpmException):
    status_code = 401
    errorcode = "unauthorized-access"


text:
/**
 * @test
 * @bug     8020983 8024697
 * @summary Test verifies that jpeg writer instances are collected
 *          even if destroy() or reset() methods is not invoked.
 *
 * @run main JpegWriterLeakTest
 */

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

public class JpegWriterLeakTest {

    public static void main(String[] args) {
        final ReferenceQueue<ImageWriter> queue = new ReferenceQueue<>();
        final ArrayList<Reference<? extends ImageWriter>> refs = new ArrayList<>();

        int count = 2;

        do {
            ImageWriter writer =
                    ImageIO.getImageWritersByFormatName("jpeg").next();

            final WeakReference<? extends ImageWriter> ref =
                    new WeakReference<>(writer, queue);

            refs.add(ref);

            try {
                final ImageOutputStream os =
                        ImageIO.createImageOutputStream(new ByteArrayOutputStream());
                writer.setOutput(os);

                writer.write(getImage());

                // NB: dispose() or reset() workarounds the problem.
            } catch (IOException e) {
            } finally {
                writer = null;
            }
            count--;
        } while (count > 0);

        System.out.println("Wait for GC...");

        final long testTimeOut = 60000L;

        final long startTime = System.currentTimeMillis();

        while (!refs.isEmpty()) {
            // check for the test timeout
            final long now = System.currentTimeMillis();

            if (now - startTime > testTimeOut) {
                System.out.println();
                throw new RuntimeException("Test FAILED.");
            }

            System.gc();

            try {
                System.out.print(".");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            };

            Reference<? extends ImageWriter> r = queue.poll();
            if (r != null) {
                System.out.println("Got reference: " + r);
                refs.remove(r);
            }
        }
        System.out.println("Test PASSED.");
    }

    private static BufferedImage getImage() {
        int width = 2500;
        int height = new Random().nextInt(2500) + 1;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();
        g.setColor(Color.blue);
        g.fillRect(0, 0, width, height);

        return image;
    }
}


text:
```
title: "FlxTeroids"
layout: demo
pageOrder: 1
SWFHeight: 480
SWFWidth: 640
source: "Arcade%20Classics/FlxTeroids"
```

FlxTeroids is a simple Asteroids clone. The original GitHub repo by [Adam "Atomic" Saltsman](https://twitter.com/ADAMATOMIC) can be found [here](https://github.com/AdamAtomic/FlxTeroids).

**Controls:**

Move - Arrow keys

Shoot -Space


text:
        <button class="btn btn-success"
                data-bind="click: m.createNewSpecModule"></button>

            <input type="text" class="moduleName brandit typeahead selectedModule"
                   data-bind="value: m.selectedSpecModel().moduleName,attr: {'size': m.selectedSpecModel().moduleName().length + 1}">

                <input class="typeahead col-md-12" type="text" placeholder="Search for module ...">


text:
<!DOCTYPE html>
<title>File-012-001-Enumerablity check: File.slice</title>
<link rel="stylesheet" href="../resources/style.css"/>

Please select "blob.txt" from resources folder to test: <input type='file' id='t_file' name='t_file' />


text:
package io.getlime.security.powerauth.lib.nextstep.model.converter;

/**
 * Normalizer for text used in QR codes.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
public class OperationTextNormalizer {

    /**
     * Normalize generic text in QR code (e.g. title and message).
     * @param text Text to normalize.
     * @return Normalized text.
     */
    public String normalizeText(String text) {
        if (text == null) {
            return "";
        }
        // Escape \ character.
        text = text.replace("\\", "\\\\");
        // Convert newlines.
        text = text.replaceAll("\r?\n", "\\\\n");
        // Remove special characters with ASCII code < 32.
        text = text.replaceAll("^[\\\\u0000-\\\\u001F]*$", "");
        // Compress spaces.
        text = text.replaceAll("\\s+", " ");
        return text;
    }

    /**
     * Normalize operation data text in QR code (e.g. note, reference and text).
     * @param text Text to normalize.
     * @return Normalized text.
     */
    public String normalizeOperationData(String text) {
        if (text == null) {
            return "";
        }
        // Perform regular text normalization.
        text = normalizeText(text);
        // Escape * character, it has special meaning in operation data.
        text = text.replace("*", "\\*");
        return text;
    }

}


text:
<?php

/**
 * Module Config For ZF2
 */

namespace Reliv\AxosoftApi;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;

class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig()
    {
        return [
            'Zend\Loader\StandardAutoloader' => [
                'namespaces' => [
                    __NAMESPACE__ => __DIR__,
                ],
            ],
        ];
    }

    /**
     * getConfig() is a requirement for all Modules in ZF2.  This
     * function is included as part of that standard.  See Docs on ZF2 for more
     * information.
     *
     * @return array Returns array to be used by the ZF2 Module Manager
     */
    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }
}


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('service:session-account', 'Unit | Service | session account', {
  // Specify the other units that are required for this test.
  // needs: ['service:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let service = this.subject();
  assert.ok(service);
});


text:
datafork
========

``datafork`` is a Python utility library for creating data slots whose content
can be temporarily "forked", possibly mutated, and then merged back into what
was already present.

This allows for code to evaluate "what if" scenarios, and then conditionally
merge the result depending on whether the outcome was acceptable.

This model could be thought of as a sort of "transactional memory", though
it also evokes the idea of dynamic scope.

The simplest use-case is a transaction block whose side-effects apply only
if the block runs to completion without raising an exception::

    import datafork

    with datafork.root() as root:
        example_slot = root.slot(initial_value=1)
        with root.transaction():
            example_slot.value = 2
            might_raise_exception()
        # this will print 1 if an exception was raised, or 2 if not.
        print example_slot.value

For other examples and reference documentation, see the manual.

Installation
------------

Stable versions of this module can be installed from pypi as ``datafork``.

Development Environment Setup
-----------------------------

If you'd like to contribute to this library you can clone this repository
and run the following steps to get set up. This assumes you already have
Python installed, and virtualenv available.

 * ``virtualenv env``
 * ``source env/bin/activate``
 * ``pip install -r requirements-dev.txt``

You should then be able to run the tests by running ``nosetests``.

Contributing
------------

Contributions are welcome but please ensure that any changes are tested and
that code style follows what's already present. The baseline code style for
this library is PEP8.


text:
#pragma once

namespace Envoy {
namespace Upstream {

/**
 * Type of load balancing to perform.
 */
enum class LoadBalancerType { RoundRobin, LeastRequest, Random, RingHash, OriginalDst };

} // namespace Upstream
} // namespace Envoy


text:
<?php

use Illuminate\Database\Seeder;

class TasksTableSeeder extends Seeder {

    public function run()
    {
        DB::unprepared(file_get_contents('sql/tasks.sql'));
    }
}


text:
package Engine.Systems;

import Engine.Components.Interaction.InputComponent;
import Engine.Components.ItemComponents.ItemsHolder;
import Engine.Input.Intent;
import abstraction.IEntity;
import abstraction.ISystem;
import shell.Game;

public class InventorySystem implements ISystem {
    @Override
    public void Update(long gameTime, Game game) {
        for (IEntity entity : game.GetEntities()) {
            ItemsHolder itemsHolder = entity.GetComponentOfType(ItemsHolder.class);
            InputComponent inputComponent = entity.GetComponentOfType(InputComponent.class);
            if (itemsHolder != null && inputComponent != null) {
                for (Intent intent : inputComponent.Intents) {
                    switch (intent) {
                        case DropItem: {
//                            Item item = EntityManager.GetComponent(inputComponent.Target);
//                            item.setHolderId(null);
//                            itemsHolder.getItems().remove(item);
                        }
                            break;
                        case PlaceItem: {
//                            Item item = EntityManager.GetComponent(inputComponent.Target);
//                            item.setHolderId(itemsHolder.getId());
//                            itemsHolder.getItems().add(item);
                        }
                        break;
                        default:
                            break;
                    }
                }
            }

        }
    }
}


text:
package com.goodskill.service.mock.strategy;

/**
 * 秒杀策略枚举,通过枚举避免暴露具体方法
 *
 * @author heng
 */
public enum GoodsKillStrategyEnum {

    /**
     *
     */
    SYNCHRONIZED(1, "Synchronized同步锁", SynchronizedLockStrategy.class.getName()),
    REDISSON(2, "redis分布式锁", RedissonStrategy.class.getName()),
    ATOMIC_UPDATE(5, "数据库原子性更新", AtomicUpdateStrategy.class.getName()),
    ZOOKEEPER_LOCK(7, "zookeeper分布式锁", ZookeeperLockStrategy.class.getName()),
    REDIS_MONGO_REACTIVE(8, "秒杀商品存放redis减库存,异步发送秒杀成功MQ", RedisMongoReactiveStrategy.class.getName()),
    SENTINEL_LIMIT(10, "Sentinel限流+数据库原子性更新", SentinelLimitStrategy.class.getName()),
    ATOMIC_CANAL(11, "数据库原子性更新+canal 数据库binlog日志监听秒杀结果", AtomicWithCanalStrategy.class.getName()),
    ;

    private int code;

    private String strategyName;

    private String className;

    public String getStrategyName() {
        return strategyName;
    }

    public String getClassName() {
        return className;
    }

    public int getCode() {
        return code;
    }

    GoodsKillStrategyEnum(int code, String strategyName, String className) {
        this.code = code;
        this.strategyName = strategyName;
        this.className = className;
    }

    public static GoodsKillStrategyEnum stateOf(int code) {
        for (GoodsKillStrategyEnum state : values()) {
            if (state.code == code) {
                return state;
            }
        }
        return null;
    }
}


text:
require 'net/http'
require 'cgi'
require 'net/smtp'
require 'etc'
require 'socket'

def send_email(smtp_host, to, subject, message)
  from = "#{Etc.getlogin}@#{Socket.gethostname}"
  msg = <<-EOM
To: <#{to}>
From: <#{from}>
Subject: #{subject}

#{message}
  EOM

  Net::SMTP.start(smtp_host) do |smtp|
    smtp.send_message msg, from, to
  end
end

def ruminate(arg0, rumx_mount, username, password, host, port, smtp_host, config_params, query, fields, alerts)
  if arg0 == 'config'
    puts config_params
    return
  end

  # Args can be of the form Myfolder/Subfolder/Foo?reset=true which will expand to <mount>/attributes.<format>?query0=Myfolder/Subfolder/Foo/attributes?reset=true&query1=etc
  path = rumx_mount + '/attributes.properties?'
  query.split.each_with_index do |query_part, index|
    path += '&' if index > 0
    path += "query_#{index}=#{CGI.escape(query_part)}"
  end

  req = Net::HTTP::Get.new(path)
  req.basic_auth(username, password) if username
  res = Net::HTTP.start(host, port) { |http| http.request(req) }
  if res.kind_of?(Net::HTTPSuccess)
    result_hash = {}
    res.body.split("\n").each do |line|
      if i = line.index('=')
        value = line[(i+1)..-1]
        if value.match(/^\s*[+-]?\d+\s*$/)
          value = value.to_i
        elsif value.match(/^\s*[+-]?((\d+_?)*\d+(\.(\d+_?)*\d+)?|\.(\d+_?)*\d+)(\s*|([eE][+-]?(\d+_?)*\d+)\s*)$/)
          value = value.to_f
        end
        result_hash[line[0,i]] = value
      end
    end
    fields.each_with_index do |field_name, i|
      puts "field#{i}.value #{result_hash[field_name]}"
    end
    alerts.each do |alert|
      filter = String.new(alert[:filter])
      result_hash.each do |field_name, value|
        filter.gsub!(Regexp.new("\\b#{field_name.gsub('.', '\\.')}\\b"), value.inspect)
      end
      status = false
      begin
        if eval(filter)
          filter = String.new(alert[:filter])
          result_hash.each do |field_name, value|
            filter.gsub!(Regexp.new("\\b#{field_name.gsub('.', '\\.')}\\b"), "#{field_name}(#{value})")
          end
          message = <<-EOM
The following filter has been triggered:

#{filter}

Output:
#{res.body}
          EOM
          send_email(smtp_host, alert[:email], "ALERT: #{alert[:title]}", message)
        end
      rescue Exception => e
        message = <<-EOM
The following filter caused an exception #{e.message}:

Original Filter: #{alert[:filter]}
Evaled Filter:   #{filter}

Output:
#{res.body}
        EOM
        send_email(smtp_host, alert[:email], "ALERT EXCEPTION: #{alert[:title]}", message)
        raise
      end
    end
  end
end


text:
<template name="confirmationDialogFinalize">
    {{#markdown}}{{__ 'Dialog.ConfirmFinalizeMinutes.really' _purify='string => string' minutesDate=minutesDate }}{{/markdown}}
    {{#if hasOpenActionItems}}

                <input id='cbSendAI' type='checkbox' class='checkbox' {{sendActionItems}}> {{__ 'Dialog.ConfirmFinalizeMinutes.sendActionItems' }}

     {{/if}}

            <input id='cbSendII' type='checkbox' class='checkbox' {{sendInformationItems}}> {{__ 'Dialog.ConfirmFinalizeMinutes.sendMinutes' }}

</template>


text:
"use strict";

global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var noConflictSelf = global.self;
global.self = {};
require('whatwg-fetch');
global.Headers = global.self.Headers;
global.Request = global.self.Request;
global.Response = global.self.Response;
var realFetch = global.self.fetch;
module.exports = global.fetch = function(url, options) {
	if (/^\/\//.test(url)) {
		url = 'https:' + url;
	}
	return realFetch.call(this, url, options);
};
global.self = noConflictSelf;


text:
using System.Linq.Expressions;

namespace AutoMapper.XpressionMapper.ArgumentMappers
{
    internal class DefaultArgumentMapper : ArgumentMapper
    {
        public DefaultArgumentMapper(XpressionMapperVisitor expressionVisitor, Expression argument)
            : base(expressionVisitor, argument)
        {
        }

        public override Expression MappedArgumentExpression => ExpressionVisitor.Visit(Argument);
    }
}


text: tasks/spreadsheet.js > src/_data/projects.json \


text:
<?php
// ======================================================================
// adminnistration // hvilken admin side er man på
if(isset($_GET['administration']))
{
	$admin = mysqli_real_escape_string($db_conn,strip_tags($_GET['administration']));
    $html_headder_title = $admin;
}
else {
    $admin = '';
}
// ======================================================================
// page // hvilken side er det man står på
if(isset($_GET['page']))
{
	$page = mysqli_real_escape_string($db_conn,strip_tags($_GET['page']));
    $html_headder_title = $page;
}
else if($admin == '')
{
	$page = 'Forside';
    $html_headder_title = $page;
}
// ======================================================================
// subpage // hvilken subside er det man står på eller om man ikke er på en.
if(isset($_GET['subpage']))
{
	$subpage = mysqli_real_escape_string($db_conn,strip_tags($_GET['subpage']));
    $html_headder_title = $page.' -> '.$subpage;
}
else
{
	$subpage = '';
}
// ======================================================================
// action // hvad skal der ske
if(isset($_GET['action']))
{
	$action = mysqli_real_escape_string($db_conn,strip_tags($_GET['action']));
}
?>


text:
using System;
using System.ComponentModel;

namespace Azure.Storage.Blobs.Batch.Models
{
    /// <summary> The BatchRehydratePriority. </summary>
    internal readonly partial struct BatchRehydratePriority : IEquatable<BatchRehydratePriority>
    {
        private readonly string _value;

        /// <summary> Determines if two <see cref="BatchRehydratePriority"/> values are the same. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public BatchRehydratePriority(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string HighValue = "High";
        private const string StandardValue = "Standard";

        /// <summary> High. </summary>
        public static BatchRehydratePriority High { get; } = new BatchRehydratePriority(HighValue);
        /// <summary> Standard. </summary>
        public static BatchRehydratePriority Standard { get; } = new BatchRehydratePriority(StandardValue);
        /// <summary> Determines if two <see cref="BatchRehydratePriority"/> values are the same. </summary>
        public static bool operator ==(BatchRehydratePriority left, BatchRehydratePriority right) => left.Equals(right);
        /// <summary> Determines if two <see cref="BatchRehydratePriority"/> values are not the same. </summary>
        public static bool operator !=(BatchRehydratePriority left, BatchRehydratePriority right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="BatchRehydratePriority"/>. </summary>
        public static implicit operator BatchRehydratePriority(string value) => new BatchRehydratePriority(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is BatchRehydratePriority other && Equals(other);
        /// <inheritdoc />
        public bool Equals(BatchRehydratePriority other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
package geoptimize.pso.fitness;

import java.awt.Rectangle;

import geoptimize.GridData;
import geoptimize.ServiceNode;
import geoptimize.pso.PSOSolution;

public class PSOFitnessFast extends PSOFitnessFunction {

	public PSOFitnessFast(GridData grid, Rectangle region) {
		super(grid, region);
	}

	/***
	 * Steps through entire population grid and adds a the pixel
	 * to the fitness if it is within range of a tower.
	 * TODO: Broken atm.
	 * @param grid
	 * @param region
	 * @return
	 */
	@Override
	public float calcFitness(PSOSolution solution) {

		float[] inrange = new float[region.width * region.height];

		for(int y = (int)region.getMinY(); y < region.getMaxY(); y++) {
			for(int x = (int)region.getMinX(); x < region.getMaxX(); x++) {
				for(ServiceNode n : solution.getNodes()) {
					int xdist = x - n.getPosition().x;
					int ydist = y - n.getPosition().y;
					int distsqr = xdist*xdist+ydist*ydist;

					if(distsqr < n.getRange() * n.getRange()) {
						int rx = x - region.x;
						int ry = y - region.y;
						inrange[ry*region.width + rx] = grid.get(x, y);
					}

				}
			}
		}

		float fitness = 0;
		for(int ry = 0; ry < region.height; ry++) {
			for(int rx = 0; rx < region.width; rx++) {
				fitness += inrange[ry*region.width+rx];
			}
		}
		return fitness;
	}

}


text:
from google.appengine.ext import ndb

class Availability(ndb.Model):
	date = ndb.DateProperty()
	opens_at = ndb.DateTimeProperty()
	closes_at = ndb.DateTimeProperty()
	location = ndb.StringProperty()


text:
local socketchannel = require "skynet.socketchannel"
local crypt = require "skynet.crypt"

local sub = string.sub
local strgsub = string.gsub
local strformat = string.format
local strbyte = string.byte
local strchar = string.char
local strrep = string.rep
local strunpack = string.unpack
local strpack = string.pack
local sha1 = crypt.sha1
local setmetatable = setmetatable
local error = error
local tonumber = tonumber
local tointeger = math.tointeger

local _M = {_VERSION = "0.14"}

-- constants
local COM_QUERY = "\x03"
local COM_PING = "\x0e"
local COM_STMT_PREPARE = "\x16"
local COM_STMT_EXECUTE = "\x17"
local CURSOR_TYPE_NO_CURSOR = 0x00
local SERVER_MORE_RESULTS_EXISTS = 8

local mt = {__index = _M}

-- mysql field value type converters
local converters = {}

for i = 0x01, 0x05 do
    -- tiny, short, long, float, double
    converters[i] = tonumber
end
converters[0x08] = tonumber -- long long
converters[0x09] = tonumber -- int24
converters[0x0d] = tonumber -- year
converters[0xf6] = tonumber -- newdecimal

local function _get_byte1(data, i)
    return strbyte(data, i), i + 1
end

local function _get_byte2(data, i)
    return strunpack("<I2", data, i)
end

local function _get_byte3(data, i)
    return strunpack("<I3", data, i)
end

local function _get_byte4(data, i)
    return strunpack("<I4", data, i)
end

local function _get_byte8(data, i)
    return strunpack("<I8", data, i)
end

local function _get_float(data, i)
    return strunpack("<f", data, i)
end

local function _get_double(data, i)
    return strunpack("<d", data, i)
end

local function _set_byte2(n)
    return strpack("<I2", n)
end

local function _set_byte3(n)
    return strpack("<I3", n)
end

local function _set_byte4(n)
    return strpack("<I4", n)
end

local function _set_byte8(n)
    return strpack("<I8", n)
end

local function _set_float(n)
    return strpack("<f", n)
end

local function _set_double(n)
    return strpack("<d", n)
end

local function _from_cstring(data, i)
    return strunpack("z", data, i)
end

local function _dumphex(bytes)
    return strgsub(bytes, ".",
        function(x)
            return strformat("%02x ", strbyte(x))
        end)
end

local function _compute_token(password, scramble)
    if password == "" then
        return ""
    end
    --_dumphex(scramble)

    local stage1 = sha1(password)
    --print("stage1:", _dumphex(stage1) )
    local stage2 = sha1(stage1)
    local stage3 = sha1(scramble .. stage2)

    local i = 0
    return strgsub(stage3, ".",
        function(x)
            i = i + 1
            -- ~ is xor in lua 5.3
            return strchar(strbyte(x) ~ strbyte(stage1, i))
        end
    )
end

local function _compose_packet(self, req)
    self.packet_no = self.packet_no + 1
    local size = #req
    return strpack("<I3Bc" .. size, size, self.packet_no, req)
end

local function _recv_packet(self, sock)
    local data = sock:read(4)
    if not data then
        return nil, nil, "failed to receive packet header: "
    end

    local len, pos = _get_byte3(data, 1)
    if len == 0 then
        return nil, nil, "empty packet"
    end

    self.packet_no = strbyte(data, pos)

    data = sock:read(len)
    if not data then
        return nil, nil, "failed to read packet content: "
    end

    local field_count = strbyte(data, 1)
    local typ
    if field_count == 0x00 then
        typ = "OK"
    elseif field_count == 0xff then
        typ = "ERR"
    elseif field_count == 0xfe then
        typ = "EOF"
    else
        typ = "DATA"
    end

    return data, typ
end

local function _from_length_coded_bin(data, pos)
    local first = strbyte(data, pos)

    if not first then
        return nil, pos
    end

    if first >= 0 and first <= 250 then
        return first, pos + 1
    end

    if first == 251 then
        return nil, pos + 1
    end

    if first == 252 then
        pos = pos + 1
        return _get_byte2(data, pos)
    end

    if first == 253 then
        pos = pos + 1
        return _get_byte3(data, pos)
    end

    if first == 254 then
        pos = pos + 1
        return _get_byte8(data, pos)
    end

    return false, pos + 1
end

local function _set_length_coded_bin(n)
    if n < 251 then
        return strchar(n)
    end

    if n < (1 << 16) then
        return strpack("<BI2", 0xfc, n)
    end

    if n < (1 << 24) then
        return strpack("<BI3", 0xfd, n)
    end

    return strpack("<BI8", 0xfe, n)
end

local function _from_length_coded_str(data, pos)
    local len
    len, pos = _from_length_coded_bin(data, pos)
    if len == nil then
        return nil, pos
    end
    return sub(data, pos, pos + len - 1), pos + len
end

local function _parse_ok_packet(packet)
    local res = {}
    local pos

    res.affected_rows, pos = _from_length_coded_bin(packet, 2)
    res.insert_id, pos = _from_length_coded_bin(packet, pos)
    res.server_status, pos = _get_byte2(packet, pos)
    res.warning_count, pos = _get_byte2(packet, pos)

    local message = sub(packet, pos)
    if message and message ~= "" then
        res.message = message
    end
    return res
end

local function _parse_eof_packet(packet)
    local pos = 2
    local warning_count, pos = _get_byte2(packet, pos)
    local status_flags = _get_byte2(packet, pos)
    return warning_count, status_flags
end

local function _parse_err_packet(packet)
    local errno, pos = _get_byte2(packet, 2)
    local marker = sub(packet, pos, pos)
    local sqlstate
    if marker == '#' then
        -- with sqlstate
        pos = pos + 1
        sqlstate = sub(packet, pos, pos + 5 - 1)
        pos = pos + 5
    end
    local message = sub(packet, pos)
    return errno, message, sqlstate
end

local function _parse_result_set_header_packet(packet)
    local field_count, pos = _from_length_coded_bin(packet, 1)
    return field_count, _from_length_coded_bin(packet, pos)
end

local function _parse_field_packet(data)
    local col = {}
    local catalog, db, table, orig_table, orig_name, charsetnr, length
    local pos

    catalog, pos = _from_length_coded_str(data, 1)
    db, pos = _from_length_coded_str(data, pos)
    table, pos = _from_length_coded_str(data, pos)
    orig_table, pos = _from_length_coded_str(data, pos)
    col.name, pos = _from_length_coded_str(data, pos)
    orig_name, pos = _from_length_coded_str(data, pos)
    pos = pos + 1 -- ignore the filler
    charsetnr, pos = _get_byte2(data, pos)
    length, pos = _get_byte4(data, pos)
    col.type = strbyte(data, pos)

    --[[
    pos = pos + 1
    col.flags, pos = _get_byte2(data, pos)
    col.decimals = strbyte(data, pos)
    pos = pos + 1
    local default = sub(data, pos + 2)
    if default and default ~= "" then
        col.default = default
    end
    --]]
    return col
end

local function _parse_row_data_packet(data, cols, compact)
    local value, col, conv
    local pos = 1
    local ncols = #cols
    local row = {}

    for i = 1, ncols do
        value, pos = _from_length_coded_str(data, pos)
        col = cols[i]

        if value ~= nil then
            conv = converters[col.type]
            if conv then
                value = conv(value)
            end
        end

        if compact then
            row[i] = value
        else
            row[col.name] = value
        end
    end

    return row
end

local function _recv_field_packet(self, sock)
    local packet, typ, err = _recv_packet(self, sock)
    if not packet then
        return nil, err
    end

    if typ == "ERR" then
        local errno, msg, sqlstate = _parse_err_packet(packet)
        return nil, msg, errno, sqlstate
    end

    if typ ~= "DATA" then
        return nil, "bad field packet type: " .. typ
    end

    -- typ == 'DATA'

    return _parse_field_packet(packet)
end

local function _recv_decode_packet_resp(self)
    return function(sock)
        local packet, typ, err = _recv_packet(self, sock)
        if not packet then
            return false, "failed to receive the result packet" .. err
        end

        if typ == "ERR" then
            local errno, msg, sqlstate = _parse_err_packet(packet)
            return false, strformat("errno:%d, msg:%s,sqlstate:%s", errno, msg, sqlstate)
        end

        if typ == "EOF" then
            return false, "old pre-4.1 authentication protocol not supported"
        end

        return true, packet
    end
end

local function _mysql_login(self, user, password, database, on_connect)
    return function(sockchannel)
        local dispatch_resp = _recv_decode_packet_resp(self)
        local packet = sockchannel:response(dispatch_resp)

        self.protocol_ver = strbyte(packet)

        local server_ver, pos = _from_cstring(packet, 2)
        if not server_ver then
            error "bad handshake initialization packet: bad server version"
        end

        self._server_ver = server_ver

        local thread_id, pos = _get_byte4(packet, pos)
        local scramble1 = sub(packet, pos, pos + 8 - 1)
        if not scramble1 then
            error "1st part of scramble not found"
        end

        pos = pos + 9 -- skip filler

        -- two lower bytes
        self._server_capabilities, pos = _get_byte2(packet, pos)
        self._server_lang = strbyte(packet, pos)
        pos = pos + 1
        self._server_status, pos = _get_byte2(packet, pos)

        local more_capabilities
        more_capabilities, pos = _get_byte2(packet, pos)

        self._server_capabilities = self._server_capabilities | more_capabilities << 16

        local len = 21 - 8 - 1
        pos = pos + 1 + 10

        local scramble_part2 = sub(packet, pos, pos + len - 1)
        if not scramble_part2 then
            error "2nd part of scramble not found"
        end

        local scramble = scramble1 .. scramble_part2
        local token = _compute_token(password, scramble)
        local client_flags = 260047
        local req = strpack("<I4I4c24zs1z",
            client_flags,
            self._max_packet_size,
            strrep("\0", 24), -- TODO: add support for charset encoding
            user,
            token,
            database
        )
        local authpacket = _compose_packet(self, req)
        sockchannel:request(authpacket, dispatch_resp)
        if on_connect then
            on_connect(self)
        end
    end
end

-- 构造ping数据包
local function _compose_ping(self)
    self.packet_no = -1
    return _compose_packet(self, COM_PING)
end

local function _compose_query(self, query)
    self.packet_no = -1
    local cmd_packet = COM_QUERY .. query
    return _compose_packet(self, cmd_packet)
end

local function _compose_stmt_prepare(self, query)
    self.packet_no = -1
    local cmd_packet = COM_STMT_PREPARE .. query
    return _compose_packet(self, cmd_packet)
end

--参数字段类型转换
local store_types = {
    number = function(v)
        if not tointeger(v) then
            return _set_byte2(0x05), _set_double(v)
        else
            return _set_byte2(0x08), _set_byte8(v)
        end
    end,
    string = function(v)
        return _set_byte2(0x0f), _set_length_coded_bin(#v) .. v
    end,
    --bool转换为0,1
    boolean = function(v)
        if v then
            return _set_byte2(0x01), strchar(1)
        else
            return _set_byte2(0x01), strchar(0)
        end
    end
}

local function _compose_stmt_execute(self, stmt, cursor_type, args)
    local arg_num = #args
    if arg_num ~= stmt.param_count then
        error("require stmt.param_count " .. stmt.param_count .. " get arg_num " .. arg_num)
    end

    self.packet_no = -1

    local cmd_packet = strpack("<c1I4BI4", COM_STMT_EXECUTE, stmt.prepare_id, cursor_type, 0x01)
    if arg_num > 0 then
        local null_count = (arg_num + 7) // 8
        local f, ts, vs
        local types_buf = ""
        local values_buf = ""
        for _, v in pairs(args) do
            f = store_types[type(v)]
            if not f then
                error("invalid parameter type", type(v))
            end
            ts, vs = f(v)
            types_buf = types_buf .. ts
            values_buf = values_buf .. vs
        end
        cmd_packet = cmd_packet .. strrep("\0", null_count) .. strchar(0x01) .. types_buf .. values_buf
    end

    return _compose_packet(self, cmd_packet)
end

local function read_result(self, sock)
    local packet, typ, err = _recv_packet(self, sock)
    if not packet then
        return nil, err
        --error( err )
    end

    if typ == "ERR" then
        local errno, msg, sqlstate = _parse_err_packet(packet)
        return nil, msg, errno, sqlstate
        --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate))
    end

    if typ == "OK" then
        local res = _parse_ok_packet(packet)
        if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then
            return res, "again"
        end
        return res
    end

    if typ ~= "DATA" then
        return nil, "packet type " .. typ .. " not supported"
        --error( "packet type " .. typ .. " not supported" )
    end

    -- typ == 'DATA'

    local field_count, extra = _parse_result_set_header_packet(packet)
    local cols = {}
    for i = 1, field_count do
        local col, err, errno, sqlstate = _recv_field_packet(self, sock)
        if not col then
            return nil, err, errno, sqlstate
            --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate))
        end
        cols[i] = col
    end

    local packet, typ, err = _recv_packet(self, sock)
    if not packet then
        --error( err)
        return nil, err
    end

    if typ ~= "EOF" then
        --error ( "unexpected packet type " .. typ .. " while eof packet is ".. "expected" )
        return nil, "unexpected packet type " .. typ .. " while eof packet is " .. "expected"
    end

    -- typ == 'EOF'

    local compact = self.compact
    local rows = {}
    local i = 0
    while true do
        packet, typ, err = _recv_packet(self, sock)
        if not packet then
            --error (err)
            return nil, err
        end

        if typ == "EOF" then
            local warning_count, status_flags = _parse_eof_packet(packet)
            if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then
                return rows, "again"
            end
            break
        end

        -- if typ ~= 'DATA' then
        --     return nil, 'bad row packet type: ' .. typ
        -- end

        -- typ == 'DATA'

        i = i + 1
        rows[i] = _parse_row_data_packet(packet, cols, compact)
    end

    return rows
end

local function _query_resp(self)
    return function(sock)
        local res, err, errno, sqlstate = read_result(self, sock)
        if not res then
            local badresult = {}
            badresult.badresult = true
            badresult.err = err
            badresult.errno = errno
            badresult.sqlstate = sqlstate
            return true, badresult
        end
        if err ~= "again" then
            return true, res
        end
        local multiresultset = {res}
        multiresultset.multiresultset = true
        local i = 2
        while err == "again" do
            res, err, errno, sqlstate = read_result(self, sock)
            if not res then
                multiresultset.badresult = true
                multiresultset.err = err
                multiresultset.errno = errno
                multiresultset.sqlstate = sqlstate
                return true, multiresultset
            end
            multiresultset[i] = res
            i = i + 1
        end
        return true, multiresultset
    end
end

function _M.connect(opts)
    local self = setmetatable({}, mt)

    local max_packet_size = opts.max_packet_size
    if not max_packet_size then
        max_packet_size = 1024 * 1024 -- default 1 MB
    end
    self._max_packet_size = max_packet_size
    self.compact = opts.compact_arrays

    local database = opts.database or ""
    local user = opts.user or ""
    local password = opts.password or ""

    local channel =
        socketchannel.channel {
        host = opts.host,
        port = opts.port or 3306,
        auth = _mysql_login(self, user, password, database, opts.on_connect),
        overload = opts.overload
    }
    self.sockchannel = channel
    -- try connect first only once
    channel:connect(true)

    return self
end

function _M.disconnect(self)
    self.sockchannel:close()
    setmetatable(self, nil)
end

function _M.query(self, query)
    local querypacket = _compose_query(self, query)
    local sockchannel = self.sockchannel
    if not self.query_resp then
        self.query_resp = _query_resp(self)
    end
    return sockchannel:request(querypacket, self.query_resp)
end

local function read_prepare_result(self, sock)
    local resp = {}
    local packet, typ, err = _recv_packet(self, sock)
    if not packet then
        resp.badresult = true
        resp.errno = 300101
        resp.err = err
        return false, resp
    end

    if typ == "ERR" then
        local errno, msg, sqlstate = _parse_err_packet(packet)
        resp.badresult = true
        resp.errno = errno
        resp.err = msg
        resp.sqlstate = sqlstate
        return true, resp
    end

    --第一节只能是OK
    if typ ~= "OK" then
        resp.badresult = true
        resp.errno = 300201
        resp.err = "first typ must be OK,now" .. typ
        return false, resp
    end
    resp.prepare_id, resp.field_count, resp.param_count, resp.warning_count = strunpack("<I4I2I2xI2", packet, 2)

    resp.params = {}
    resp.fields = {}

    if resp.param_count > 0 then
        local param = _recv_field_packet(self, sock)
        while param do
            table.insert(resp.params, param)
            param = _recv_field_packet(self, sock)
        end
    end
    if resp.field_count > 0 then
        local field = _recv_field_packet(self, sock)
        while field do
            table.insert(resp.fields, field)
            field = _recv_field_packet(self, sock)
        end
    end

    return true, resp
end

local function _prepare_resp(self, sql)
    return function(sock)
        return read_prepare_result(self, sock, sql)
    end
end

-- 注册预处理语句
function _M.prepare(self, sql)
    local querypacket = _compose_stmt_prepare(self, sql)
    local sockchannel = self.sockchannel
    if not self.prepare_resp then
        self.prepare_resp = _prepare_resp(self)
    end
    return sockchannel:request(querypacket, self.prepare_resp)
end

local function _get_datetime(data, pos)
    local len, year, month, day, hour, minute, second
    local value
    len, pos = _from_length_coded_bin(data, pos)
    if len == 7 then
        year, month, day, hour, minute, second, pos = string.unpack("<I2BBBBB", data, pos)
        value = strformat("%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second)
    else
        value = "2017-09-09 20:08:09"
        --unsupported format
        pos = pos + len
    end
    return value, pos
end

local _binary_parser = {
    [0x01] = _get_byte1,
    [0x02] = _get_byte2,
    [0x03] = _get_byte4,
    [0x04] = _get_float,
    [0x05] = _get_double,
    [0x07] = _get_datetime,
    [0x08] = _get_byte8,
    [0x0c] = _get_datetime,
    [0x0f] = _from_length_coded_str,
    [0x10] = _from_length_coded_str,
    [0xf9] = _from_length_coded_str,
    [0xfa] = _from_length_coded_str,
    [0xfb] = _from_length_coded_str,
    [0xfc] = _from_length_coded_str,
    [0xfd] = _from_length_coded_str,
    [0xfe] = _from_length_coded_str
}

local function _parse_row_data_binary(data, cols, compact)
    local ncols = #cols
    -- 空位图,前两个bit系统保留 (列数量 + 7 + 2) / 8
    local null_count = (ncols + 9) // 8
    local pos = 2 + null_count
    local value

    --空字段表
    local null_fields = {}
    local field_index = 1
    local byte
    for i = 2, pos - 1 do
        byte = strbyte(data, i)
        for j = 0, 7 do
            if field_index > 2 then
                if byte & (1 << j) == 0 then
                    null_fields[field_index - 2] = false
                else
                    null_fields[field_index - 2] = true
                end
            end
            field_index = field_index + 1
        end
    end

    local row = {}
    local parser
    for i = 1, ncols do
        local col = cols[i]
        local typ = col.type
        local name = col.name
        if not null_fields[i] then
            parser = _binary_parser[typ]
            if not parser then
                error("_parse_row_data_binary()error,unsupported field type " .. typ)
            end
            value, pos = parser(data, pos)
            if compact then
                row[i] = value
            else
                row[name] = value
            end
        end
    end

    return row
end

local function read_execute_result(self, sock)
    local packet, typ, err = _recv_packet(self, sock)
    if not packet then
        return nil, err
        --error( err )
    end

    if typ == "ERR" then
        local errno, msg, sqlstate = _parse_err_packet(packet)
        return nil, msg, errno, sqlstate
        --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate))
    end

    if typ == "OK" then
        local res = _parse_ok_packet(packet)
        if res and res.server_status & SERVER_MORE_RESULTS_EXISTS ~= 0 then
            return res, "again"
        end
        return res
    end

    if typ ~= "DATA" then
        return nil, "packet type " .. typ .. " not supported"
        --error( "packet type " .. typ .. " not supported" )
    end

    -- typ == 'DATA'

    local field_count, extra = _parse_result_set_header_packet(packet)

    local cols = {}
    local col
    while true do
        packet, typ, err = _recv_packet(self, sock)
        if typ == "EOF" then
            local warning_count, status_flags = _parse_eof_packet(packet)
            break
        end
        col = _parse_field_packet(packet)
        if not col then
            break
            --error( strformat("errno:%d, msg:%s,sqlstate:%s",errno,msg,sqlstate))
        end
        table.insert(cols, col)
    end

    --没有记录集返回
    if #cols < 1 then
        return {}
    end

    local compact = self.compact
    local rows = {}
    local row
    while true do
        packet, typ, err = _recv_packet(self, sock)
        if typ == "EOF" then
            local warning_count, status_flags = _parse_eof_packet(packet)
            if status_flags & SERVER_MORE_RESULTS_EXISTS ~= 0 then
                return rows, "again"
            end
            break
        end
        row = _parse_row_data_binary(packet, cols, compact)
        if not col then
            break
        end
        table.insert(rows, row)
    end

    return rows
end

local function _execute_resp(self)
    return function(sock)
        local res, err, errno, sqlstate = read_execute_result(self, sock)
        if not res then
            local badresult = {}
            badresult.badresult = true
            badresult.err = err
            badresult.errno = errno
            badresult.sqlstate = sqlstate
            return true, badresult
        end
        if err ~= "again" then
            return true, res
        end
        local mulitresultset = {res}
        mulitresultset.mulitresultset = true
        local i = 2
        while err == "again" do
            res, err, errno, sqlstate = read_execute_result(self, sock)
            if not res then
                mulitresultset.badresult = true
                mulitresultset.err = err
                mulitresultset.errno = errno
                mulitresultset.sqlstate = sqlstate
                return true, mulitresultset
            end
            mulitresultset[i] = res
            i = i + 1
        end
        return true, mulitresultset
    end
end

--[[
    执行预处理语句
    失败返回字段
        errno
        badresult
        sqlstate
        err
]]
function _M.execute(self, stmt, ...)
    -- 检查参数,不能为nil
    local p_n = select('#', ...)
    local p_v
    for i = 1, p_n do
        p_v = select(i, ...)
        if p_v == nil then
            return {
                badresult = true,
                errno = 30902,
                err = "parameter " .. i .. " is nil"
            }
        end
    end

    local querypacket, er = _compose_stmt_execute(self, stmt, CURSOR_TYPE_NO_CURSOR, {...})
    if not querypacket then
        return {
            badresult = true,
            errno = 30902,
            err = er
        }
    end
    local sockchannel = self.sockchannel
    if not self.execute_resp then
        self.execute_resp = _execute_resp(self)
    end
    return sockchannel:request(querypacket, self.execute_resp)
end

function _M.ping(self)
    local querypacket, er = _compose_ping(self)
    if not querypacket then
        return {
            badresult = true,
            errno = 30902,
            err = er
        }
    end
    local sockchannel = self.sockchannel
    if not self.query_resp then
        self.query_resp = _query_resp(self)
    end
    return sockchannel:request(querypacket, self.query_resp)
end

function _M.server_ver(self)
    return self._server_ver
end

local escape_map = {
    ['\0'] = "\\0",
    ['\b'] = "\\b",
    ['\n'] = "\\n",
    ['\r'] = "\\r",
    ['\t'] = "\\t",
    ['\26'] = "\\Z",
    ['\\'] = "\\\\",
    ["'"] = "\\'",
    ['"'] = '\\"',
}

function _M.quote_sql_str( str)
    return strformat("'%s'", strgsub(str, "[\0\b\n\r\t\26\\\'\"]", escape_map))
end

function _M.set_compact_arrays(self, value)
    self.compact = value
end

return _M


text:
"""Functional tests using WebTest.

See: http://webtest.readthedocs.org/
"""
from innovator.public.models import News

class TestNews:

    def test_add_news(self, admin, testapp):
        # Goes to homepage
        res = testapp.get('/')
        # Fills out login form in navbar
        form = res.forms['loginForm']
        form['username'] = admin.username
        form['password'] = '12345678'
        # Submits
        res = form.submit().follow()
        news_old_count = len(News.query.all())
        res = testapp.get('/admin/news/compose-new/')
        form = res.forms['composeForm']
        form['title'] = 'testnews1'
        form['summary'] = 'testsummary1'
        form['content'] = 'testcontent1'
        res = form.submit().follow()
        news_new_count = len(News.query.all())
        assert news_new_count - news_old_count == 1
        assert res.status_code == 200
        assert 'News posted.' in res

    def test_delete_news(self, admin, news, testapp):
        # Goes to homepage
        res = testapp.get('/')
        # Fills out login form in navbar
        form = res.forms['loginForm']
        form['username'] = admin.username
        form['password'] = '12345678'
        # Submits
        res = form.submit().follow()
        news_old_count = len(News.query.all())
        # Go to edit page
        res = testapp.get('/admin/news/').click('unique')
        form = res.forms['deleteForm']
        res = form.submit().follow()
        assert res.status_code == 200
        assert 'News deleted.' in res
        news_new_count = len(News.query.all())
        assert news_old_count - news_new_count == 1

    def test_edit_news(self, admin, news, testapp):
        # Goes to homepage
        res = testapp.get('/')
        # Fills out login form in navbar
        form = res.forms['loginForm']
        form['username'] = admin.username
        form['password'] = '12345678'
        # Submits
        res = form.submit().follow()
        assert len(News.query.filter_by(title='unique').all()) == 1
        assert len(News.query.filter_by(title='new title').all()) == 0
        # Go to edit page
        res = testapp.get('/admin/news/').click('unique')
        form = res.forms['editForm']
        form['title'] = 'new title'
        res = form.submit().follow()
        assert res.status_code == 200
        assert 'News edited.' in res
        assert len(News.query.filter_by(title='unique').all()) == 0
        assert len(News.query.filter_by(title='new title').all()) == 1

    def test_news_display(self, admin, news, testapp):
        res = testapp.get('/news/')
        assert res.status_code == 200
        assert 'unique' in res
        assert 'summary' in res
        res = res.click('unique')
        assert res.status_code == 200
        assert 'unique' in res
        assert 'content' in res
        assert 'summary' not in res


text:
package org.apache.causeway.persistence.jpa.integration.typeconverters.applib;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import org.apache.causeway.applib.value.Markup;

/**
 * @since 2.0 {@index}
 */
@Converter(autoApply = true)
public class CausewayMarkupConverter
implements AttributeConverter<Markup, String> {

    @Override
    public String convertToDatabaseColumn(final Markup memberValue) {
        return memberValue != null
                ? memberValue.asHtml()
                : null;
    }

    @Override
    public Markup convertToEntityAttribute(final String datastoreValue) {
        return datastoreValue != null
                ? new Markup(datastoreValue)
                : null;
    }

}


text:
<TITLE>Review for Chase, The (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Chase, The (1994)

reviewed by
Mark R. Leeper

                                 THE CHASE
                      A film review by Mark R. Leeper
                       Copyright 1994 Mark R. Leeper

          Capsule review:  THE CHASE is satire of chase films
     that takes some funny knocks at TV-news, but otherwise
     offers little. The film works neither as an action film
     nor as a comedy. THE CHASE manages to drag even at a short
     87 minutes.  Rating: low 0 (-4 to +4).

     Adam Rifkin is back in the driver seat for his third film.  Rifkin
directed the film NEVER ON TUESDAY (which I'm sorry I haven't seen) and the
surrealist comedy THE DARK BACKWARD (which I'm sorry I did see).  He is back
with THE CHASE.  Rifkin's talent is improving at high speed--faster, in
fact, then the chase in THE CHASE.  His latest does not have an incredibly
greasy-looking Judd Nelson with a third arm growing out of his back and does
not leave the audience with something akin to flu symptoms.  So Rifkin is
showing real signs of improvement.  Just not enough.

     The plot of THE CHASE is little more than the title might suggest.
Charlie Sheen plays Jack Hammond, a man running from the police but spotted
by them at a convenience store.  To escape he takes as hostage Natalie Voss
(played by Kristy Swanson) and flees only to be chased by the law and
several live-tv-news teams all the way to the Mexican border.  Along the way
he gets to know his hostage who turns out to be the daughter of the
"Californian Donald Trump," Dalton Voss (Ray Wise).  Some of the film's
satirical edge, in fact most of what works, is aimed at the news team and
the absurd risks they take for ratings, chasing along with--and often ahead
of--the police anxious to beat the competition to a story.

     This film is appears to want to be a madcap satire of a particular type
of film, much as AIRPLANE was for a different sub-genre, but in this case
neither the humor nor the action carries film.  The humor is all on a fairly
lukewarm level that is sometimes helped but more often hindered by Sheen's
deadpan serious delivery.  There are chuckles, but they are often miles
apart.  The action scenes are often mechanical and punctuated with overly
familiar-looking stunt crashes.  The premise seems to be that we are
watching a high-speed chase, but we never get much of a sense of speed.  We
see the two leads talking with the rear-projection showing the police cars
following them, but you rarely have the feel that the speed gets over the
speed limit.  Sheen is just not attentive enough to the road and the scenery
does not seem to go by all that fast.  That may seem like a picayune point,
but it gets in the way of the storytelling.  We do see some of the requisite
explosions and carnage--both fairly mechanical--but it doesn't seem clear
exactly why for the speeds shown.

     Sheen's acting is flat and dry throughout in a film in which there was
little real acting required.  Kristy Swanson, who played the title roles in
DEADLY FRIEND and BUFFY THE VAMPIRE SLAYER competes with Sheen to see who
can more underplay a role.  Trying his hand at acting is rock musician Henry
Rollins as one of the pursuing policemen who seems more interested in
impressing an interviewer riding along with him than in actually capturing
Hammond.

     This is a comedy whose engine seems unwilling to turn over and which
never manages to get all its sparkplugs to fire.  I give it a low 0 on the
-4 to +4 scale.

                                        Mark R. Leeper
                                        att!mtgzfs3!leeper
                                        leeper@mtgzfs3.att.com

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
namespace OnlineShop.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class IdentityInit : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}