text:
"""Tests for tensorflow.kernels.logging_ops."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import sys
import tempfile

from tensorflow.python.eager import context
from tensorflow.python.eager import function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import test_util
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import string_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

class LoggingOpsTest(test.TestCase):

  def testAssertDivideByZero(self):
    with self.cached_session() as sess:
      epsilon = ops.convert_to_tensor(1e-20)
      x = ops.convert_to_tensor(0.0)
      y = ops.convert_to_tensor(1.0)
      z = ops.convert_to_tensor(2.0)
      # assert(epsilon < y)
      # z / y
      with sess.graph.control_dependencies([
          control_flow_ops.Assert(
              math_ops.less(epsilon, y), ["Divide-by-zero"])
      ]):
        out = math_ops.div(z, y)
      self.assertAllEqual(2.0, self.evaluate(out))
      # assert(epsilon < x)
      # z / x
      #
      # This tests printing out multiple tensors
      with sess.graph.control_dependencies([
          control_flow_ops.Assert(
              math_ops.less(epsilon, x), ["Divide-by-zero", "less than x"])
      ]):
        out = math_ops.div(z, x)
      with self.assertRaisesOpError("less than x"):
        self.evaluate(out)

class PrintV2Test(test.TestCase):

  @test_util.run_in_graph_and_eager_modes()
  def testPrintOneTensor(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor)
        self.evaluate(print_op)

      expected = "[0 1 2 ... 7 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintOneTensorVarySummarize(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor, summarize=1)
        self.evaluate(print_op)

      expected = "[0 ... 9]"
      self.assertTrue((expected + "\n") in printed.contents())

    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor, summarize=2)
        self.evaluate(print_op)

      expected = "[0 1 ... 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor, summarize=3)
        self.evaluate(print_op)

      expected = "[0 1 2 ... 7 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor, summarize=-1)
        self.evaluate(print_op)

      expected = "[0 1 2 3 4 5 6 7 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintOneVariable(self):
    with self.cached_session():
      var = variables.Variable(math_ops.range(10))
      if not context.executing_eagerly():
        variables.global_variables_initializer().run()
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(var)
        self.evaluate(print_op)
      expected = "[0 1 2 ... 7 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintTwoVariablesInStructWithAssignAdd(self):
    with self.cached_session():
      var_one = variables.Variable(2.14)
      plus_one = var_one.assign_add(1.0)
      var_two = variables.Variable(math_ops.range(10))
      if not context.executing_eagerly():
        variables.global_variables_initializer().run()
      with self.captureWritesToStream(sys.stderr) as printed:
        self.evaluate(plus_one)
        print_op = logging_ops.print_v2(var_one, {"second": var_two})
        self.evaluate(print_op)
      expected = "3.14 {'second': [0 1 2 ... 7 8 9]}"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintTwoTensors(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor, tensor * 10)
        self.evaluate(print_op)
      expected = "[0 1 2 ... 7 8 9] [0 10 20 ... 70 80 90]"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintPlaceholderGeneration(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2("{}6", {"{}": tensor * 10})
        self.evaluate(print_op)
      expected = "{}6 {'{}': [0 10 20 ... 70 80 90]}"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintNoTensors(self):
    with self.cached_session():
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(23, [23, 5], {"6": 12})
        self.evaluate(print_op)
      expected = "23 [23, 5] {'6': 12}"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintFloatScalar(self):
    with self.cached_session():
      tensor = ops.convert_to_tensor(434.43)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor)
        self.evaluate(print_op)
      expected = "434.43"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintStringScalar(self):
    with self.cached_session():
      tensor = ops.convert_to_tensor("scalar")
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(tensor)
        self.evaluate(print_op)
      expected = "scalar"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintComplexTensorStruct(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      small_tensor = constant_op.constant([0.3, 12.4, -16.1])
      big_tensor = math_ops.mul(tensor, 10)
      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(
            "first:", tensor, "middle:",
            {"small": small_tensor, "Big": big_tensor}, 10,
            [tensor * 2, tensor])
        self.evaluate(print_op)
      # Note that the keys in the dict will always be sorted,
      # so 'Big' comes before 'small'
      expected = ("first: [0 1 2 ... 7 8 9] "
                  "middle: {'Big': [0 10 20 ... 70 80 90], "
                  "'small': [0.3 12.4 -16.1]} "
                  "10 [[0 2 4 ... 14 16 18], [0 1 2 ... 7 8 9]]")
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintSparseTensor(self):
    with self.cached_session():
      ind = [[0, 0], [1, 0], [1, 3], [4, 1], [1, 4], [3, 2], [3, 3]]
      val = [0, 10, 13, 4, 14, 32, 33]
      shape = [5, 6]

      sparse = sparse_tensor.SparseTensor(
          constant_op.constant(ind, dtypes.int64),
          constant_op.constant(val, dtypes.int64),
          constant_op.constant(shape, dtypes.int64))

      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2(sparse)
        self.evaluate(print_op)
      expected = ("'SparseTensor(indices=[[0 0]\n"
                  " [1 0]\n"
                  " [1 3]\n"
                  " ...\n"
                  " [1 4]\n"
                  " [3 2]\n"
                  " [3 3]], values=[0 10 13 ... 14 32 33], shape=[5 6])'")
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintSparseTensorInDataStruct(self):
    with self.cached_session():
      ind = [[0, 0], [1, 0], [1, 3], [4, 1], [1, 4], [3, 2], [3, 3]]
      val = [0, 10, 13, 4, 14, 32, 33]
      shape = [5, 6]

      sparse = sparse_tensor.SparseTensor(
          constant_op.constant(ind, dtypes.int64),
          constant_op.constant(val, dtypes.int64),
          constant_op.constant(shape, dtypes.int64))

      with self.captureWritesToStream(sys.stderr) as printed:
        print_op = logging_ops.print_v2([sparse])
        self.evaluate(print_op)
      expected = ("['SparseTensor(indices=[[0 0]\n"
                  " [1 0]\n"
                  " [1 3]\n"
                  " ...\n"
                  " [1 4]\n"
                  " [3 2]\n"
                  " [3 3]], values=[0 10 13 ... 14 32 33], shape=[5 6])']")
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintOneTensorStdout(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.captureWritesToStream(sys.stdout) as printed:
        print_op = logging_ops.print_v2(
            tensor, output_stream=sys.stdout)
        self.evaluate(print_op)
      expected = "[0 1 2 ... 7 8 9]"
      self.assertTrue((expected + "\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintTensorsToFile(self):
    tmpfile_name = tempfile.mktemp(".printv2_test")
    tensor_0 = math_ops.range(0, 10)
    print_op_0 = logging_ops.print_v2(tensor_0,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_0)
    tensor_1 = math_ops.range(11, 20)
    print_op_1 = logging_ops.print_v2(tensor_1,
                                      output_stream="file://"+tmpfile_name)
    self.evaluate(print_op_1)
    try:
      f = open(tmpfile_name, "r")
      line_0 = f.readline()
      expected_0 = "[0 1 2 ... 7 8 9]"
      self.assertTrue(expected_0 in line_0)
      line_1 = f.readline()
      expected_1 = "[11 12 13 ... 17 18 19]"
      self.assertTrue(expected_1 in line_1)
      f.close()
      os.remove(tmpfile_name)
    except IOError as e:
      self.fail(e)

  @test_util.run_in_graph_and_eager_modes()
  def testInvalidOutputStreamRaisesError(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      with self.assertRaises(ValueError):
        print_op = logging_ops.print_v2(
            tensor, output_stream="unknown")
        self.evaluate(print_op)

  def testPrintOpName(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      print_op = logging_ops.print_v2(tensor, name="print_name")
      self.assertEqual(print_op.name, "print_name")

  def testNoDuplicateFormatOpGraphModeAfterExplicitFormat(self):
    with self.cached_session():
      tensor = math_ops.range(10)
      formatted_string = string_ops.string_format("{}", tensor)
      print_op = logging_ops.print_v2(formatted_string)
      self.evaluate(print_op)
      graph_ops = ops.get_default_graph().get_operations()
      format_ops = [op for op in graph_ops if op.type == "StringFormat"]
      # Should be only 1 format_op for graph mode.
      self.assertEqual(len(format_ops), 1)

  def testPrintOneTensorEagerOnOpCreate(self):
    with self.cached_session():
      with context.eager_mode():
        tensor = math_ops.range(10)
        expected = "[0 1 2 ... 7 8 9]"
        with self.captureWritesToStream(sys.stderr) as printed:
          logging_ops.print_v2(tensor)
        self.assertTrue((expected + "\n") in printed.contents())

  def testPrintsOrderedInDefun(self):
    with context.eager_mode():

      @function.defun
      def prints():
        logging_ops.print_v2("A")
        logging_ops.print_v2("B")
        logging_ops.print_v2("C")

      with self.captureWritesToStream(sys.stderr) as printed:
        prints()
      self.assertTrue(("A\nB\nC\n") in printed.contents())

  @test_util.run_in_graph_and_eager_modes()
  def testPrintInDefunWithoutExplicitEvalOfPrint(self):
    @function.defun
    def f():
      tensor = math_ops.range(10)
      logging_ops.print_v2(tensor)
      return tensor

    expected = "[0 1 2 ... 7 8 9]"
    with self.captureWritesToStream(sys.stderr) as printed_one:
      x = f()
      self.evaluate(x)
    self.assertTrue((expected + "\n") in printed_one.contents())

    # We execute the function again to make sure it doesn't only print on the
    # first call.
    with self.captureWritesToStream(sys.stderr) as printed_two:
      y = f()
      self.evaluate(y)
    self.assertTrue((expected + "\n") in printed_two.contents())

class PrintGradientTest(test.TestCase):

  @test_util.run_in_graph_and_eager_modes
  def testPrintShape(self):
    inp = constant_op.constant(2.0, shape=[100, 32])
    inp_printed = logging_ops.Print(inp, [inp])
    self.assertEqual(inp.get_shape(), inp_printed.get_shape())

  def testPrintString(self):
    inp = constant_op.constant(2.0, shape=[100, 32])
    inp_printed = logging_ops.Print(inp, ["hello"])
    self.assertEqual(inp.get_shape(), inp_printed.get_shape())

  def testPrintGradient(self):
    with self.cached_session():
      inp = constant_op.constant(2.0, shape=[100, 32], name="in")
      w = constant_op.constant(4.0, shape=[10, 100], name="w")
      wx = math_ops.matmul(w, inp, name="wx")
      wx_print = logging_ops.Print(wx, [w, w, w])
      wx_grad = gradients_impl.gradients(wx, w)[0]
      wx_print_grad = gradients_impl.gradients(wx_print, w)[0]
      wxg = self.evaluate(wx_grad)
      wxpg = self.evaluate(wx_print_grad)
    self.assertAllEqual(wxg, wxpg)

if __name__ == "__main__":
  test.main()


text:
.class public abstract Landroid/hardware/ISerialManager$Stub;
.super Landroid/os/Binder;
.source "ISerialManager.java"

# interfaces
.implements Landroid/hardware/ISerialManager;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/ISerialManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "Stub"
.end annotation

.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/hardware/ISerialManager$Stub$Proxy;
    }
.end annotation

# static fields
.field private static final DESCRIPTOR:Ljava/lang/String; = "android.hardware.ISerialManager"

.field static final TRANSACTION_getSerialPorts:I = 0x1

.field static final TRANSACTION_openSerialPort:I = 0x2

# direct methods
.method public constructor <init>()V
    .locals 1

    invoke-direct {p0}, Landroid/os/Binder;-><init>()V

    const-string/jumbo v0, "android.hardware.ISerialManager"

    invoke-virtual {p0, p0, v0}, Landroid/hardware/ISerialManager$Stub;->attachInterface(Landroid/os/IInterface;Ljava/lang/String;)V

    return-void
.end method

.method public static asInterface(Landroid/os/IBinder;)Landroid/hardware/ISerialManager;
    .locals 2

    const/4 v1, 0x0

    if-nez p0, :cond_0

    return-object v1

    :cond_0
    const-string/jumbo v1, "android.hardware.ISerialManager"

    invoke-interface {p0, v1}, Landroid/os/IBinder;->queryLocalInterface(Ljava/lang/String;)Landroid/os/IInterface;

    move-result-object v0

    if-eqz v0, :cond_1

    instance-of v1, v0, Landroid/hardware/ISerialManager;

    if-eqz v1, :cond_1

    check-cast v0, Landroid/hardware/ISerialManager;

    return-object v0

    :cond_1
    new-instance v1, Landroid/hardware/ISerialManager$Stub$Proxy;

    invoke-direct {v1, p0}, Landroid/hardware/ISerialManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V

    return-object v1
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 0

    return-object p0
.end method

.method public onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v4, 0x1

    sparse-switch p1, :sswitch_data_0

    invoke-super {p0, p1, p2, p3, p4}, Landroid/os/Binder;->onTransact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    move-result v3

    return v3

    :sswitch_0
    const-string/jumbo v3, "android.hardware.ISerialManager"

    invoke-virtual {p3, v3}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    return v4

    :sswitch_1
    const-string/jumbo v3, "android.hardware.ISerialManager"

    invoke-virtual {p2, v3}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p0}, Landroid/hardware/ISerialManager$Stub;->getSerialPorts()[Ljava/lang/String;

    move-result-object v2

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    invoke-virtual {p3, v2}, Landroid/os/Parcel;->writeStringArray([Ljava/lang/String;)V

    return v4

    :sswitch_2
    const-string/jumbo v3, "android.hardware.ISerialManager"

    invoke-virtual {p2, v3}, Landroid/os/Parcel;->enforceInterface(Ljava/lang/String;)V

    invoke-virtual {p2}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p0, v0}, Landroid/hardware/ISerialManager$Stub;->openSerialPort(Ljava/lang/String;)Landroid/os/ParcelFileDescriptor;

    move-result-object v1

    invoke-virtual {p3}, Landroid/os/Parcel;->writeNoException()V

    if-eqz v1, :cond_0

    invoke-virtual {p3, v4}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {v1, p3, v4}, Landroid/os/ParcelFileDescriptor;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_0
    return v4

    :cond_0
    const/4 v3, 0x0

    invoke-virtual {p3, v3}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_0

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_1
        0x2 -> :sswitch_2
        0x5f4e5446 -> :sswitch_0
    .end sparse-switch
.end method

redpajama_set_name: RedPajamaGithub


text:
package io.pivotal.spring.cloud.config.java;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * Bootstrap configuration to set properties for applications using Spring Cloud Services.
 */
@Configuration
@PropertySource(name="springCloudServicesBootstrap", value="classpath:/io/pivotal/spring/cloud/config/java/app-name.properties")
public class CloudEnvironmentBootstrapConfiguration {
}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<process-definition xmlns="urn:jbpm.org:jpdl-3.2" name="(VEF) Conclusão para Sentença - Genérica - Execução Fiscal">
    <description><![CDATA[Código do fluxo: VEF_PAJ_EXEF_SENT_GEN

Descrição: Fluxo destinado ao preparo de atos judiciais de decisões genéricas...]]></description>
    <!-- SWIMLANES -->
    <swimlane name="Magistrado">
        <assignment pooled-actors="#{localizacaoAssignment.getPooledActors('6:1469,5:1338,7:5197,8:5852,8:5853,6:5901')}"/>
    </swimlane>
    <swimlane name="Assessor">
        <assignment pooled-actors="#{localizacaoAssignment.getPooledActors('6:1469,7:5197,5:1338,8:5852,8:5853')}" actor-id="#{actor.id}"/>
    </swimlane>
    <!-- START-STATE -->
    <start-state name="Início">
        <task name="Tarefa inicial"/>
        <transition to="(VEF) Concluso para sentença - Fila genérica - MINUTAR" name="(VEF) Concluso para sentença - Fila genérica - MINUTAR"/>
    </start-state>
    <!-- NODES -->
    <task-node end-tasks="true" name="(VEF) Concluso para sentença - Fila genérica - MINUTAR">
        <task name="(VEF) Concluso para sentença - Fila genérica - MINUTAR" swimlane="Assessor">
            <controller>
                <variable name="minuta_ato_judicial" mapped-name="textEditCombo:minuta_ato_judicial" access="read,write,required"/>
                <variable name="minutarLote" mapped-name="minutarLote:minutarLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: minuta_ato_judicial
   Label: Minuta em elaboração
   Escrita: Sim
   Obrig. Sim
   Tipo: Editor

2. Variável: minutarLote
   Label:
   Escrita: Sim
   Obrig. Não
   Tipo: Habilitar Minutar em Lote

*Eventos de Tarefa*

1. Tipo do evento: Sair Tarefa
   Agrupamento eventos: Magistrado
   Condição para lançamento temporário: #{true}]]></description>
        <transition to="(VEF) Concluso para sentença - Fila genérica - ASSINAR" name="Encaminhar para assinatura do magistrado"/>
        <transition to="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal" name="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(VEF) Selecionar outro tipo de conclusão" name="Alterar escolha do tipo de conclusão"/>
        <event type="task-start">
            <action name="Condicao do lancamento temporario de movimentos" expression="#{lancadorMovimentosService.setCondicaoLancamentoMovimentosTemporarioNoFluxo('#{true}')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds', '62,63,64')}"/>
        </event>
        <event type="task-end">
            <action expression="#{not empty tramitacaoProcessualService.recuperaVariavelTarefa('textEditCombo:minuta_ato_judicial') ? tramitacaoProcessualService.gravaVariavel('minutaEmElaboracao', tramitacaoProcessualService.recuperaVariavelTarefa('textEditCombo:minuta_ato_judicial')) : ''}"/>
            <action expression="#{not empty processoHome.idProcessoDocumento ? tramitacaoProcessualService.gravaVariavel('minutaEmElaboracao', processoHome.idProcessoDocumento) : ''}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('TipoDocumentoTipoProcessoDocumento')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('pje:fluxo:transicao:dispensaRequeridos', 'Alterar escolha do tipo de conclusão')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('pje:fluxo:transicao:lancamentoMovimentoObrigatorio','true')}"/>
        </event>
    </task-node>
    <task-node end-tasks="true" name="(VEF) Concluso para sentença - Fila genérica - ASSINAR">
        <task name="(VEF) Concluso para sentença - Fila genérica - ASSINAR" swimlane="Magistrado">
            <controller>
                <variable name="Processo_Fluxo_revisarMinuta" mapped-name="frame:Processo_Fluxo_revisarMinuta" access="read,write"/>
                <variable name="movimentacaoLote" mapped-name="movimentarLote:movimentacaoLote" access="read,write"/>
                <variable name="assinaturaLote" mapped-name="assinarLote:assinaturaLote" access="read,write"/>
            </controller>
        </task>
        <description><![CDATA[*Variáveis*

1. Variável: Processo_Fluxo_revisarMinuta
   Label:
   Escrita: Sim
   Obrig. Não
   Tipo: Frame

2. Variável: movimentacaoLote
   Label:
   Escrita: Sim
   Obrig. Não
   Tipo: Habilitar Movimentação em Lote

3. Variável: assinaturaLote
   Label:
   Escrita: Sim
   Obrig. Não
   Tipo: Habilitar Assinatura em Lote

4. Variável: confirmarMovimentacao
   Label: Confirma Movimentação
   Escrita: Sim
   Obrig. Não
   Tipo: Homologador de Movimentos Temporários]]></description>
        <transition to="(VEF) Concluso para sentença - Fila genérica - MINUTAR" name="Retornar para minuta"/>
        <transition to="(VEF) Encaminhar para sentenciados" name="(VEF) Encaminhar para sentenciados">
            <condition expression="#{true}"/>
        </transition>
        <transition to="(VEF) Encaminhar para sentenciados" name="Documento já assinado! Encaminhar para secretaria">
            <condition expression="#{processoHome.instance.idProcesso > 0 and not empty revisarMinutaAction.processoDocumento.processoDocumentoBin.signatarios and revisarMinutaAction.processoDocumento.ativo}"/>
        </transition>
        <transition to="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal" name="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal">
            <condition expression="#{true}"/>
        </transition>
        <event type="task-end">
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('tiposDisponiveisIds')}"/>
            <action expression="#{tramitacaoProcessualService.apagaVariavelTarefa('frameDefaultLeavingTransition')}"/>
        </event>
        <event type="task-create">
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('frameDefaultLeavingTransition', '(VEF) Encaminhar para sentenciados')}"/>
            <action expression="#{lancadorMovimentosService.setCondicaoLancamentoMovimentosTemporarioNoFluxo('#{false}')}"/>
            <action expression="#{tramitacaoProcessualService.gravaVariavelTarefa('tiposDisponiveisIds', '63,64,62')}"/>
        </event>
    </task-node>
    <end-state name="Término"/>
    <task-node end-tasks="true" name="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal">
        <task name="Nó de Desvio - (VEF) Conclusão para Sentença - Genérica - Execução Fiscal"/>
        <transition to="(VEF) Concluso para sentença - Fila genérica - MINUTAR" name="(VEF) Concluso para sentença - Fila genérica - MINUTAR"/>
        <transition to="(VEF) Concluso para sentença - Fila genérica - ASSINAR" name="(VEF) Concluso para sentença - Fila genérica - ASSINAR"/>
        <transition to="Término" name="Término"/>
    </task-node>
    <process-state name="(VEF) Encaminhar para sentenciados">
        <sub-process name="(VEF) Sentenças - Genérica - Execução Fiscal" binding="late"/>
        <transition to="Término" name="Término"/>
    </process-state>
    <node name="(VEF) Selecionar outro tipo de conclusão">
        <transition to="Término" name="Término"/>
        <event type="node-enter">
            <action expression="#{tramitacaoProcessualService.gravaVariavel('pje:vef:cancelou', true)}"/>
        </event>
    </node>
    <!-- PROCESS-EVENTS -->
    <event type="superstate-enter">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="process-start">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="before-signal">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="subprocess-created">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-create">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="transition">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-assign">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="after-signal">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="timer">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="task-start">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="subprocess-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="node-leave">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="process-end">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="superstate-leave">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <event type="node-enter">
        <script>br.com.infox.ibpm.util.JbpmEvents.raiseEvent(executionContext)</script>
    </event>
    <!-- ACTIONS -->
</process-definition>


text:
using Google.Cloud.Kms.V1;
using Google.Protobuf;
using System.Security.Cryptography;
using System.Text;
using Xunit;

[Collection(nameof(KmsFixture))]
public class VerifyAsymmetricSignRsa
{
    private readonly KmsFixture _fixture;
    private readonly VerifyAsymmetricSignatureRsaSample _sample;

    public VerifyAsymmetricSignRsa(KmsFixture fixture)
    {
        _fixture = fixture;
        _sample = new VerifyAsymmetricSignatureRsaSample();
    }

    [Fact]
    public void VerifiesData()
    {
        var message = "testing1234";

        // Calculate the message digest.
        var sha256 = SHA256.Create();
        var digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Sign the data
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();
        CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricSignRsaKeyId, "1");
        var result = client.AsymmetricSign(keyVersionName, new Digest
        {
            Sha256 = ByteString.CopyFrom(digest),
        });

        // Run the sample.
        var verified = _sample.VerifyAsymmetricSignatureRsa(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricSignRsaKeyId, keyVersionId: "1",
            message: message,
            signature: result.Signature.ToByteArray());

        Assert.True(verified);
    }
}


text:
package com.rehivetech.beeeon.household.device.units;

import android.content.SharedPreferences;
import android.support.annotation.Nullable;

import com.rehivetech.beeeon.R;

import static com.rehivetech.beeeon.household.device.units.BaseUnit.Item.DEFAULT_ID;

public class EmissionUnit extends BaseUnit {

	public EmissionUnit() {
		super(-1);
		mItems.add(new Item(DEFAULT_ID, R.string.unit_emission, R.string.unit_emission));
	}

	@Override
	public Item fromSettings(@Nullable SharedPreferences prefs) {
		return mItems.get(0);
	}

	@Override
	public double convertValue(Item to, double value) {
		return value;
	}

	@Override
	public double convertToDefaultValue(Item from, double value) {
		return value;
	}
}


text:
"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "LoadingBar", {
  enumerable: true,
  get: function get() {
    return _loading_bar.LoadingBar;
  }
});
Object.defineProperty(exports, "loadingBarMiddleware", {
  enumerable: true,
  get: function get() {
    return _loading_bar_middleware["default"];
  }
});
Object.defineProperty(exports, "hideLoading", {
  enumerable: true,
  get: function get() {
    return _loading_bar_ducks.hideLoading;
  }
});
Object.defineProperty(exports, "loadingBarReducer", {
  enumerable: true,
  get: function get() {
    return _loading_bar_ducks.loadingBarReducer;
  }
});
Object.defineProperty(exports, "resetLoading", {
  enumerable: true,
  get: function get() {
    return _loading_bar_ducks.resetLoading;
  }
});
Object.defineProperty(exports, "showLoading", {
  enumerable: true,
  get: function get() {
    return _loading_bar_ducks.showLoading;
  }
});
Object.defineProperty(exports, "ImmutableLoadingBar", {
  enumerable: true,
  get: function get() {
    return _immutable["default"];
  }
});
exports["default"] = void 0;

var _loading_bar = _interopRequireWildcard(require("./loading_bar"));

var _loading_bar_middleware = _interopRequireDefault(require("./loading_bar_middleware"));

var _loading_bar_ducks = require("./loading_bar_ducks");

var _immutable = _interopRequireDefault(require("./immutable"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var _default = _loading_bar["default"];
exports["default"] = _default;


text:
<?xml version="1.0"?>
<!--
 censed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
-->
<configuration xmlns:xi="http://www.w3.org/2001/XInclude" supports_final="true">
  <property>
    <name>java.library.path</name>
    <value>/usr/local/lib:/opt/local/lib:/usr/lib:/usr/hdp/current/storm-client/lib</value>
    <description>This value is passed to spawned JVMs (e.g., Nimbus, Supervisor, and Workers)
      for the java.library.path value. java.library.path tells the JVM where
      to look for native libraries. It is necessary to set this config correctly since
      Storm uses the ZeroMQ and JZMQ native libs. </description>
    <on-ambari-upgrade add="true"/>
  </property>
  <property>
    <name>nimbus.childopts</name>
    <value>-Xmx1024m _JAAS_PLACEHOLDER -javaagent:/usr/hdp/current/storm-nimbus/contrib/storm-jmxetric/lib/jmxetric-1.0.4.jar=host=localhost,port=8649,wireformat31x=true,mode=multicast,config=/usr/hdp/current/storm-nimbus/contrib/storm-jmxetric/conf/jmxetric-conf.xml,process=Nimbus_JVM</value>
    <description>This parameter is used by the storm-deploy project to configure the jvm options for the nimbus daemon.</description>
    <value-attributes>
      <overridable>false</overridable>
    </value-attributes>
    <on-ambari-upgrade add="true"/>
  </property>
  <property>
    <name>worker.childopts</name>
    <value>-Xmx768m _JAAS_PLACEHOLDER -javaagent:/usr/hdp/current/storm-client/contrib/storm-jmxetric/lib/jmxetric-1.0.4.jar=host=localhost,port=8650,wireformat31x=true,mode=multicast,config=/usr/hdp/current/storm-client/contrib/storm-jmxetric/conf/jmxetric-conf.xml,process=Worker_%ID%_JVM</value>
    <description>The jvm opts provided to workers launched by this supervisor. All \"%ID%\" substrings are replaced with an identifier for this worker.</description>
    <value-attributes>
      <type>multiLine</type>
    </value-attributes>
    <on-ambari-upgrade add="true"/>
  </property>
  <property>
    <name>supervisor.childopts</name>
    <value>-Xmx256m _JAAS_PLACEHOLDER -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port={{jmxremote_port}} -javaagent:/usr/hdp/current/storm-supervisor/contrib/storm-jmxetric/lib/jmxetric-1.0.4.jar=host=localhost,port=8650,wireformat31x=true,mode=multicast,config=/usr/hdp/current/storm-supervisor/contrib/storm-jmxetric/conf/jmxetric-conf.xml,process=Supervisor_JVM</value>
    <description>This parameter is used by the storm-deploy project to configure the jvm options for the supervisor daemon.</description>
    <value-attributes>
      <overridable>false</overridable>
    </value-attributes>
    <on-ambari-upgrade add="true"/>
  </property>

  <!--
   Property storm.topology.submission.notifier.plugin.class definition is required only when Atlas service is installed.
   To remove this property, we need to create dependency with Atlas service.
   -->
  <property>
    <name>storm.topology.submission.notifier.plugin.class</name>
    <value> </value>
    <depends-on>
      <property>
        <type>application-properties</type>
        <name>atlas.authentication.method</name>
      </property>
       <property>
        <type>storm-env</type>
        <name>storm.atlas.hook</name>
      </property>
    </depends-on>
    <on-ambari-upgrade add="false"/>
    <on-stack-upgrade merge="false"/>
  </property>
</configuration>


text:
<!DOCTYPE html>

<body>
<script src="/js-test-resources/js-test.js"></script>
<script>
description('This tests that XMLHttpRequest.responseXML returns an XMLDocument.');
window.jsTestIsAsync = true;

new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'resources/redirect.php?url=reply2.xml', true);
    xhr.responseType = 'document';
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            resolve(xhr);
        }
    }
    xhr.send();
}).then(function(xhr) {
    responseDocument = String(xhr.responseXML);
    shouldBeEqualToString('responseDocument', '[object XMLDocument]');
}).catch(function(reason) {
    testFailed(String(reason));
}).then(finishJSTest, finishJSTest);

</script>
</body>
</html>


text:
namespace xls {

// Pass which removes asserts that have a literal 1 as the condition, meaning
// they are never triggered. Rewires tokens to ensure nothing breaks.
class UselessAssertRemovalPass : public FunctionBasePass {
 public:
  UselessAssertRemovalPass()
      : FunctionBasePass("useless_assert_remove",
                         "Remove useless (always true) asserts") {}
  ~UselessAssertRemovalPass() override {}

 protected:
  absl::StatusOr<bool> RunOnFunctionBaseInternal(
      FunctionBase* f, const PassOptions& options,
      PassResults* results) const override;
};

}  // namespace xls

#endif


text:
const Base = require('./base')
const {middleware: paginate} = require('koa-pagination')
const convert = require('koa-convert')
const _ = require('lodash')

module.exports = class Aggregate extends Base {
  getConfig (path, options) {
    const { dimensions: [dimension], metrics: [metric] } = options
    if (path instanceof Function) {
      options.collection = path.collection()
      options.model = path
    } else {
      options.path = path
    }
    options = Object.assign({
      filterable: [],
      searchable: [],
      path: `/aggregate/${options.model.prototype.tableName}`,
      defaults: {
        dimensions: [dimension.name],
        metrics: [metric.name],
        by: dimension.name
      }
    }, options)
    return options
  }
  aggregate (path, ...args) {
    const { middlewares, options } = this.parseArgs(args)
    const config = this.getConfig(path, options)
    this.get(config.path, convert(paginate(config.pagination)), ...(middlewares || []), async ctx => {
      const { model, dimensions, metrics, defaults } = config
      const { query: input } = ctx.request
      const query = model.forge().query()
      ;(input.dimensions || defaults.dimensions).forEach(name => {
        const dimension = dimensions.find(dim => dim.name === name)
        query.column(dimension.column)
      })
      ;(input.metrics || defaults.metrics).forEach(name => {
        const metric = metrics.find(metric => metric.name === name)
        query[metric.aggregate](metric.column)
      })
      if (!_.isEmpty(input.filters) && config.filterable) {
        const filter = field => {
          if (input.filters[field]) {
            query.where({[field]: input.filters[field]})
          }
        }
        let filterable = config.filterable
        if (_.isArray(config.filterable)) {
          filterable = () => config.filterable.map(filter)
        }
        filterable({ filter, query, filters: input.filters })
      }
      if (config.searchable) {
        if (input.q) {
          query.where(function () {
            options.searchable.forEach((field, index) => {
              this[index ? 'orWhere' : 'where'](field, 'LIKE', `%${input.q}%`)
            })
          })
        }
      }
      query.groupBy(input.by || defaults.by)
      query.limit(ctx.pagination.limit).offset(ctx.pagination.offset)
      ctx.body = await query.select()
    })
  }
}


text:
namespace chromeos {
namespace settings {

OsSettingsSections::OsSettingsSections(
    Profile* profile,
    SearchTagRegistry* search_tag_registry,
    multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client,
    phonehub::PhoneHubManager* phone_hub_manager,
    syncer::SyncService* sync_service,
    SupervisedUserService* supervised_user_service,
    KerberosCredentialsManager* kerberos_credentials_manager,
    ArcAppListPrefs* arc_app_list_prefs,
    signin::IdentityManager* identity_manager,
    android_sms::AndroidSmsService* android_sms_service,
    CupsPrintersManager* printers_manager,
    apps::AppServiceProxy* app_service_proxy,
    ash::eche_app::EcheAppManager* eche_app_manager) {
  // Special case: Main section does not have an associated enum value.
  sections_.push_back(
      std::make_unique<MainSection>(profile, search_tag_registry));

  auto internet_section =
      std::make_unique<InternetSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kNetwork] = internet_section.get();
  sections_.push_back(std::move(internet_section));

  auto bluetooth_section =
      std::make_unique<BluetoothSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kBluetooth] = bluetooth_section.get();
  sections_.push_back(std::move(bluetooth_section));

  auto multidevice_section = std::make_unique<MultiDeviceSection>(
      profile, search_tag_registry, multidevice_setup_client, phone_hub_manager,
      android_sms_service, profile->GetPrefs(), eche_app_manager);
  sections_map_[mojom::Section::kMultiDevice] = multidevice_section.get();
  sections_.push_back(std::move(multidevice_section));

  auto people_section = std::make_unique<PeopleSection>(
      profile, search_tag_registry, sync_service, supervised_user_service,
      identity_manager, profile->GetPrefs());
  sections_map_[mojom::Section::kPeople] = people_section.get();
  sections_.push_back(std::move(people_section));

  auto device_section = std::make_unique<DeviceSection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kDevice] = device_section.get();
  sections_.push_back(std::move(device_section));

  auto personalization_section = std::make_unique<PersonalizationSection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kPersonalization] =
      personalization_section.get();
  sections_.push_back(std::move(personalization_section));

  auto search_section =
      std::make_unique<SearchSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kSearchAndAssistant] = search_section.get();
  sections_.push_back(std::move(search_section));

  auto apps_section = std::make_unique<AppsSection>(
      profile, search_tag_registry, profile->GetPrefs(), arc_app_list_prefs,
      app_service_proxy);
  sections_map_[mojom::Section::kApps] = apps_section.get();
  sections_.push_back(std::move(apps_section));

  auto crostini_section = std::make_unique<CrostiniSection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kCrostini] = crostini_section.get();
  sections_.push_back(std::move(crostini_section));

  auto date_time_section =
      std::make_unique<DateTimeSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kDateAndTime] = date_time_section.get();
  sections_.push_back(std::move(date_time_section));

  auto privacy_section = std::make_unique<PrivacySection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kPrivacyAndSecurity] = privacy_section.get();
  sections_.push_back(std::move(privacy_section));

  auto language_section = std::make_unique<LanguagesSection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kLanguagesAndInput] = language_section.get();
  sections_.push_back(std::move(language_section));

  auto files_section =
      std::make_unique<FilesSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kFiles] = files_section.get();
  sections_.push_back(std::move(files_section));

  auto printing_section = std::make_unique<PrintingSection>(
      profile, search_tag_registry, printers_manager);
  sections_map_[mojom::Section::kPrinting] = printing_section.get();
  sections_.push_back(std::move(printing_section));

  auto accessibility_section = std::make_unique<AccessibilitySection>(
      profile, search_tag_registry, profile->GetPrefs());
  sections_map_[mojom::Section::kAccessibility] = accessibility_section.get();
  sections_.push_back(std::move(accessibility_section));

  auto reset_section =
      std::make_unique<ResetSection>(profile, search_tag_registry);
  sections_map_[mojom::Section::kReset] = reset_section.get();
  sections_.push_back(std::move(reset_section));

#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  auto about_section = std::make_unique<AboutSection>(
      profile, search_tag_registry, profile->GetPrefs());
#else
  auto about_section =
      std::make_unique<AboutSection>(profile, search_tag_registry);
#endif  // BUILDFLAG(GOOGLE_CHROME_BRANDING)
  sections_map_[mojom::Section::kAboutChromeOs] = about_section.get();
  sections_.push_back(std::move(about_section));

  auto kerberos_section = std::make_unique<KerberosSection>(
      profile, search_tag_registry, kerberos_credentials_manager);
  sections_map_[mojom::Section::kKerberos] = kerberos_section.get();
  sections_.push_back(std::move(kerberos_section));
}

OsSettingsSections::OsSettingsSections() = default;

OsSettingsSections::~OsSettingsSections() = default;

const OsSettingsSection* OsSettingsSections::GetSection(
    mojom::Section section) const {
  const auto it = sections_map_.find(section);
  CHECK(it != sections_map_.end());
  return it->second;
}

}  // namespace settings
}  // namespace chromeos


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/web_ponty.iml" filepath="$PROJECT_DIR$/.idea/web_ponty.iml" />
    </modules>
  </component>
</project>


text:
package "vim"
package "git"

# Uses the Opscode 'apt' LWP to setup another apt source (ppa repo)
apt_repository "brightbox-ruby-ng-experimental" do
  uri "http://ppa.launchpad.net/brightbox/ruby-ng-experimental/ubuntu"
  distribution node['lsb']['codename']
  components ["main"]
  keyserver "keyserver.ubuntu.com"
  key "C3173AA6"
end

apt_repository "brightbox-passenger-experimental" do
  uri "http://ppa.launchpad.net/brightbox/passenger-experimental/ubuntu"
  distribution node['lsb']['codename']
  components ["main"]
  keyserver "keyserver.ubuntu.com"
  key "C3173AA6"
end

# Install the "ruby2.0" and "ruby2.0-dev" package via apt
package "ruby2.0"
package "ruby2.0-dev"

# Bundler for managing our gems
gem_package "bundler"

# Install the libcurl4-openssl-dev package via apt (needed for Passenger)
package "libcurl4-openssl-dev"

# Install the "apache2-dev" package via apt (needed for Passenger)
package "apache2-dev"

# Install the "libapache2-mod-passenger" package via apt
package "libapache2-mod-passenger"

# Uses the Opscode 'apache2' LWP to setup an Apache2 virtual host
web_app "rails4" do
  server_name node['hostname']
  server_aliases [node['fqdn'], "my-site.example.com"]
  docroot "/var/www/rails4/current/public"
  allow_override ["All"]
  directory_options ["-MultiViews"]
end

# Create has containing database info
mysql_connection_info = {:host => "localhost", :username => 'root', :password => node['mysql']['server_root_password']}

# Uses the Opscode 'mysql_database' LWP set create a database
mysql_database 'rails4' do
  connection mysql_connection_info
  action :create
end

# Uses the Opscode 'mysql_database' LWP set create a database user with full permissions
mysql_database_user 'rails_user' do
  connection mysql_connection_info
  password 'super_secret'
  database_name 'rails4'
  host 'localhost'
  privileges [:all]
  action [:create,:grant]
end


text:
package com.tripasfactory.thetripaslibrary.RoboSpice;

import android.app.Application;

import com.octo.android.robospice.persistence.ObjectPersisterFactory;
import com.octo.android.robospice.persistence.exception.CacheCreationException;
import com.tripasfactory.thetripaslibrary.Configs;
import com.tripasfactory.thetripaslibrary.Security.SecurityUtils;

public class MemoryGsonObjectPersisterFactory extends ObjectPersisterFactory {

    public MemoryGsonObjectPersisterFactory(Application application) throws CacheCreationException {
        super(application);
    }

    @Override
    public <DATA> MemoryGsonObjectPersister<DATA> createObjectPersister(Class<DATA> clazz)
            throws CacheCreationException {
        String seed = null;
        if (Configs.ENCRYPT_CACHE) {
            seed = SecurityUtils.generateSeedForCache();
        }
        return new MemoryGsonObjectPersister<DATA>(getApplication(), clazz, seed);
    }

}


text:
#!/usr/bin/env python

import re
import os
import fnmatch
import argparse

MACRO = """
#define %(func_name)s%(func_suffix)s%(macro_args)s ({ \\
   ret_t __ret = %(func_orig)s %(macro_args)s; \\
   if (unlikely (__ret != ret_ok)) return __ret; \\
   __ret; \\
})
"""

SECTION = """
/* %(fullpath_h)s
 */
"""

def parse_file (fullpath_h, replacement_pair, func_suffix):
	with open(fullpath_h, 'r') as f:
		cont = f.read()

	# Find functions
	funcs = re.findall (r'ret_t\s+?[^\\#]+?\(.+?\);', cont, re.S)
	if not funcs:
		return ''

	output = SECTION%(locals())
	for func in funcs:
		# Remove new-lines and multiple spaces
		func = re.sub(' +',' ', func.replace('\n',' '))

		# Ignore function typedefs
		if re.findall('\(\s*?\*', func):
			continue

		# Parse it
		tmp = (re.findall (r'ret_t (.+?)\s*(\(.+\));', func) or [()])[0]
		if not tmp:
			print func
			raise SystemExit
		func_orig = tmp[0]
		func_name = func_orig.replace(replacement_pair[0], replacement_pair[1])

		# Arguments
		args = []
		func_args = [x.strip() for x in tmp[1].split(',')]
		for arg in func_args:
			if arg == '(void)':
				break
			args += [filter(lambda x: len(x), re.split(' |\*|\&|\)', arg))[-1]]
		macro_args = '(%s)' %(','.join(args))

		output += MACRO %(locals())

	return output

def parse_dir (path_dir, path_header, replacement_pair, func_suffix):
	header = ''
	# Parse header files
	for root, dirnames, filenames in os.walk(path_dir):
		for filename in fnmatch.filter(filenames, "*.h"):
			fp = os.path.abspath (os.path.join (root, filename))
			if fp == path_header:
				print "Ignoring %s" %(fp)
				continue
			header += parse_file(fp, replacement_pair, func_suffix)

	# Write target header
	with open(path_header, 'w+') as f:
		f.write(header)

	print '%s: %s definitions' %(path_header, header.count('#define'))

def main():
	# Command Line Args
	parser = argparse.ArgumentParser()
	parser.add_argument ('--path',        action="store", required=True, help="")
	parser.add_argument ('--output',      action="store", required=True, help="Output header file")
	parser.add_argument ('--replacement', action="store", default=":", help="Name replacement. Eg: chula_:chuli_")
	parser.add_argument ('--suffix',      action="store", default="",  help="Name suffix. Eg: _R")
	ns = parser.parse_args()
	if not ns:
		print ("ERROR: Couldn't parse parameters")
		raise SystemExit

	# Parse headers
	parse_dir (ns.path, os.path.abspath(ns.output), ns.replacement.split(':'), ns.suffix)

if __name__ == "__main__":
	main()


text:
#ifndef GOF_STATE_STATE_CONTEXT_H
#define GOF_STATE_STATE_CONTEXT_H

#include <string>
#include "State/IState.h"
#include "State/EmptyState.h"
#include "State/ResultState.h"
#include "State/OperationState.h"
#include "State/OperandLeftState.h"
#include "State/OperandRightState.h"

namespace GoF {

    namespace State {

        enum Operation;
        class AbstractState;
        class StateContext
        {
        public:
            StateContext();
            ~StateContext();

            void clear();
            IState * getCurrentState();

        private:
            // Using friendship to void creating lots of set and get repetitive methods
            // in both two related classes. A choice with no side effects in this scenario.
            //
            // Note.: The same technique is used in a similar way in the GoF Pattern's book.
            friend class AbstractState;

            // Only the states must be able to change the context state.
            void changeState(IState *);

            double leftOperand;
            double rightOperand;
            Operation operation;
            IState * currentState;

        };

    }

}

#endif


text:
.dashboard-container {
  width: 60vw;
}

.no-data-text,
.loading-text {
  width: inherit;
  margin-top: 48px;
  font-size: larger;
  text-align: center;
}

.loading-text:before {
  content: " ";
  position: absolute;
  top: 0;
  left: 0;
  width: 20%;
  height: 2px;
  background: #81d4fa;
  animation: loading-animation 2s ease-out infinite;
}

@keyframes loading-animation {
  0% {
    transform: translate(0%);
  }
  100% {
    transform: translate(500%);
  }
}

@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  .dashboard-container {
    width: 90vw;
  }
}

@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) {
  .dashboard-container {
    width: 75vw;
  }
}


text:
<?php

namespace App\Tests\Functional\Repository\TaskRepositoryTestDataProviders;

use App\Tests\Services\TaskOutputFactory;
use App\Tests\Services\JobFactory;

trait GetWarningCountByJobDataProvider
{
    /**
     * @return array
     */
    public function getWarningCountByJobDataProvider()
    {
        return [
            'job zero' => [
                'jobValuesCollection' => [
                    [
                        JobFactory::KEY_USER => 'public',
                    ],
                    [
                        JobFactory::KEY_USER => 'private',
                    ],
                ],
                'taskOutputValuesCollection' => [
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 3,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 2,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 1,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 0,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 0,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 1,
                    ],
                ],
                'jobIndex' => 0,
                'expectedWarningCount' => 6,
            ],
            'job one' => [
                'jobValuesCollection' => [
                    [
                        JobFactory::KEY_USER => 'public',
                    ],
                    [
                        JobFactory::KEY_USER => 'private',
                    ],
                ],
                'taskOutputValuesCollection' => [
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 3,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 2,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 1,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 0,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 1,
                    ],
                    [
                        TaskOutputFactory::KEY_WARNING_COUNT => 1,
                    ],
                ],
                'jobIndex' => 1,
                'expectedWarningCount' => 2,
            ],
        ];
    }
}


text:
for i in {1..30}
do
     echo Running testcase $i
    (time ./testcases < lab03/testcases/input$i.txt) > a.txt

    if diff a.txt lab03/testcases/output$i.txt
       then echo SAME!
    else
       echo DIFFERENT!
    fi
done


text:
This is a Unity application for "Roll and Keep" dice systems. The primary target platform are andriod tablets.

## Required Assets
Imported assets are stored in 'Assets/Import'. The following assets from the asset store are required for this project:
-	Dice Pack Light (https://www.assetstore.unity3d.com/en/#!/content/165)

## License
This project is licensensed under the Terms of the MIT License. Check the LICENSE file for details.


text:
using System;
using System.Collections;
using System.Collections.Generic;
using BTCPayServer.Payments;

namespace BTCPayServer.Services.Invoices
{
    public class PaymentMethodDictionary : IEnumerable<PaymentMethod>
    {
        readonly Dictionary<PaymentMethodId, PaymentMethod> _Inner = new Dictionary<PaymentMethodId, PaymentMethod>();
        public PaymentMethodDictionary()
        {

        }

        public PaymentMethod this[PaymentMethodId index]
        {
            get
            {
                return _Inner[index];
            }
        }

        public void Add(PaymentMethod paymentMethod)
        {
            _Inner.Add(paymentMethod.GetId(), paymentMethod);
        }

        public void Remove(PaymentMethod paymentMethod)
        {
            _Inner.Remove(paymentMethod.GetId());
        }
        public bool TryGetValue(PaymentMethodId paymentMethodId, out PaymentMethod data)
        {
            ArgumentNullException.ThrowIfNull(paymentMethodId);
            return _Inner.TryGetValue(paymentMethodId, out data);
        }

        public void AddOrReplace(PaymentMethod paymentMethod)
        {
            var key = paymentMethod.GetId();
            _Inner.Remove(key);
            _Inner.Add(key, paymentMethod);
        }

        public IEnumerator<PaymentMethod> GetEnumerator()
        {
            return _Inner.Values.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public PaymentMethod TryGet(PaymentMethodId paymentMethodId)
        {
            ArgumentNullException.ThrowIfNull(paymentMethodId);
            _Inner.TryGetValue(paymentMethodId, out var value);
            return value;
        }
        public PaymentMethod TryGet(string network, PaymentType paymentType)
        {
            ArgumentNullException.ThrowIfNull(network);
            var id = new PaymentMethodId(network, paymentType);
            return TryGet(id);
        }
    }
}


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /*
  */
  class AWS_EC2_API CancelConversionTaskRequest : public EC2Request
  {
  public:
    CancelConversionTaskRequest();
    Aws::String SerializePayload() const override;

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline bool GetDryRun() const{ return m_dryRun; }

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline CancelConversionTaskRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

    /*

The ID of the conversion task.

    */
    inline const Aws::String& GetConversionTaskId() const{ return m_conversionTaskId; }

    /*

The ID of the conversion task.

    */
    inline void SetConversionTaskId(const Aws::String& value) { m_conversionTaskIdHasBeenSet = true; m_conversionTaskId = value; }

    /*

The ID of the conversion task.

    */
    inline void SetConversionTaskId(Aws::String&& value) { m_conversionTaskIdHasBeenSet = true; m_conversionTaskId = value; }

    /*

The ID of the conversion task.

    */
    inline void SetConversionTaskId(const char* value) { m_conversionTaskIdHasBeenSet = true; m_conversionTaskId.assign(value); }

    /*

The ID of the conversion task.

    */
    inline CancelConversionTaskRequest& WithConversionTaskId(const Aws::String& value) { SetConversionTaskId(value); return *this;}

    /*

The ID of the conversion task.

    */
    inline CancelConversionTaskRequest& WithConversionTaskId(Aws::String&& value) { SetConversionTaskId(value); return *this;}

    /*

The ID of the conversion task.

    */
    inline CancelConversionTaskRequest& WithConversionTaskId(const char* value) { SetConversionTaskId(value); return *this;}

    /*

The reason for canceling the conversion task.

    */
    inline const Aws::String& GetReasonMessage() const{ return m_reasonMessage; }

    /*

The reason for canceling the conversion task.

    */
    inline void SetReasonMessage(const Aws::String& value) { m_reasonMessageHasBeenSet = true; m_reasonMessage = value; }

    /*

The reason for canceling the conversion task.

    */
    inline void SetReasonMessage(Aws::String&& value) { m_reasonMessageHasBeenSet = true; m_reasonMessage = value; }

    /*

The reason for canceling the conversion task.

    */
    inline void SetReasonMessage(const char* value) { m_reasonMessageHasBeenSet = true; m_reasonMessage.assign(value); }

    /*

The reason for canceling the conversion task.

    */
    inline CancelConversionTaskRequest& WithReasonMessage(const Aws::String& value) { SetReasonMessage(value); return *this;}

    /*

The reason for canceling the conversion task.

    */
    inline CancelConversionTaskRequest& WithReasonMessage(Aws::String&& value) { SetReasonMessage(value); return *this;}

    /*

The reason for canceling the conversion task.

    */
    inline CancelConversionTaskRequest& WithReasonMessage(const char* value) { SetReasonMessage(value); return *this;}

  private:
    bool m_dryRun;
    bool m_dryRunHasBeenSet;
    Aws::String m_conversionTaskId;
    bool m_conversionTaskIdHasBeenSet;
    Aws::String m_reasonMessage;
    bool m_reasonMessageHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text: An ANTLR4 grammar for Power Query (*.pq) files.


text:
pimcore.registerNS("pimcore.object.classes.data.checkbox");
pimcore.object.classes.data.checkbox = Class.create(pimcore.object.classes.data.data, {

    type: "checkbox",

    /**
     * define where this datatype is allowed
     */
    allowIn: {
        object: true,
        objectbrick: true,
        fieldcollection: true,
        localizedfield: true
    },

    initialize: function (treeNode, initData) {
        this.type = "checkbox";

        this.initData(initData);

        this.treeNode = treeNode;
    },

    getTypeName: function () {
        return t("checkbox");
    },

    getIconClass: function () {
        return "pimcore_icon_checkbox";
    },

    getLayout: function ($super) {

        $super();

        this.specificPanel.removeAll();
        this.specificPanel.add([
            {
                xtype: "checkbox",
                fieldLabel: t("default_value"),
                name: "defaultValue",
                checked: this.datax.defaultValue
            },
            new Ext.form.DisplayField({hideLabel:true,html:''
                                                +t('default_value_warning')+''})
        ]);

        return this.layout;
    }

});


text:
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="milan C." name="author"/>

<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/>
<?php
if(isset($css))
	foreach($css as $value){
?>
<link href="<?=base_url();?>assets/admin/global/plugins/<?=$value?>" rel="stylesheet" type="text/css"/>
<?php } ?>

<link href="<?=base_url();?>assets/admin/global/css/components.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/global/css/plugins.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/layout/css/layout.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="<?=base_url();?>assets/admin/layout/css/themes/darkblue.css" rel="stylesheet" type="text/css"/>
<link href="<?=base_url();?>assets/admin/layout/css/custom.css" rel="stylesheet" type="text/css"/>

<link rel="shortcut icon" href="favicon.ico"/>

			<img src="<?=base_url();?>assets/admin/layout/img/logo.png" alt="logo" class="logo-default"/>

					<img alt="" class="img-circle" src="<?=base_url();?>assets/admin/layout/img/avatar3_small.jpg"/>

					Nick

							<a href="<?= base_url()?>admin/adminlogout">
							 Log Out


text:
.. _redisservice:

=============
Redis
=============

Megam offers various services options and it can be selected from Megam Marketplace.
A service can be created alone or can it can be bound to an existing application upon creation.

List of services that are present in Megam Marketplace

- Verify the advanced service settings.

   .. hint:: Your email/api_key will be the authentication parameters for accessing the service

|servicemp|

Create a Key value store:
-------------------------

Click on any services options from the marketplace which pops up a ``Service Dialog Box``

Stand-alone service:
^^^^^^^^^^^^^^^^^^^^^

This article describes the process to create a database on Megam.

click on a service for ``Service Deploy Box``.
You can see the ``Redis logo`` along with other cloud settings, name and create options.

|service dialog box|

Click Create.

Bind an Application:
^^^^^^^^^^^^^^^^^^^^^

A service upon creation can be bound to an application that is already running in Megam.
Megam offers single click, seamless binding option which makes it easier to bind to any existing application.

Select the preferred database and then the ``Services Dialog Box`` pops up.

Select the ``cloud settings`` and pick a suitable name for your db. You can choose to have the auto generated name by us too.

Click on the ``app`` dropdown menu and it will list all the applications that are created by you.

Choose anyone application and press ``create``. You are good to go!

.. |servicemp| image:: /images/servicesmarketplace.png

.. |service dialog box| image:: /images/redis.png


text:
/**
 * Aanwezigheid.js
 *
 * @description :: TODO: You might write a short summary of how this model works and what it represents here.
 * @docs        :: http://sailsjs.org/documentation/concepts/models-and-orm/models
 */

module.exports = {

    attributes: {

  		aanwezigen: {
        	collection: 'user',
        	via: 'aanwezigheidslijst',
            dominant: true
         //   through: 'useraanwezigheid'
    	},

/*status: {
            collection: 'user',
            via: 'userStatus',
            dominant:true,
    		required: true,
    		defaultsTo: false
    	},*/

        planning: {
            model: 'agenda',
            required: true
        },

        statussen: {
            collection: 'aanwezigheidsstatus',
            via: 'aanwezigheidID'
        }

    }
};


text:
<?php

namespace Laminas\Filter;

class Dir extends AbstractFilter
{
    /**
     * Defined by Laminas\Filter\FilterInterface
     *
     * Returns dirname($value)
     *
     * @param  string $value
     * @return string
     */
    public function filter($value)
    {
        if (! is_scalar($value)) {
            return $value;
        }
        $value = (string) $value;

        return dirname($value);
    }
}


text:
Faq's

Question

How do I track my order?

ANSWER

			You can either click the "track your order" link in the email that we sent to you confirming our order or if you're registered with us you can log in and go to "Your Orders" to track your order.


text:
/** HTTP Functions. */
package org.basex.query.func.http;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>{% block title %}gma > {{title}}{% endblock %}</title>
{% block head %}
    {% block preHead %}{% endblock %}
    {% block baseCss %}
	<link rel="stylesheet" type="text/css"        href="/wglemedia/css/base.css" media="all"/>
	{% endblock %}

    {% block extraCss %}
        {% for f in css %}
            <link rel="stylesheet" type="text/css" href="{{f}}"/>
        {% endfor %}
    {% endblock %}

    {% if useStatic %}

    {% else %}
	    {% block libraries %}

	    {% endblock %}

	    {% block mainLibrary %}

	    {% endblock %}

        {% if not compiled %}

            {% block require %}

            {% endblock %}
        {% else %}

        {% endif %}
    {% endif %}

{% endblock %}

{% block extraHead %}{% endblock %}

	    {% block header %} {% endblock %}

	{% block middle %}

        {% block content %}
            {% if errors %}

                {% for error in errors %}

{{error}}

                {% endfor %}

            {% else %}
                {% if message %}

{{message}}

                {% endif %}

                {% block extraContent %}{% endblock %}
                {% block canvas %}

Oh dear, doesn't work :(

                {% endblock %}
            	{% block extraScripts %}{% endblock %}

            {% endif %}
        {% endblock %}

    {% endblock %}

        {% block navigation %}

            {% if title %}

{{title}}

            {% endif %}
            {% if not gettingCoverage %}

                Index

                All Tests

                Coverage

                Docs

            {% if not isCoverage %}

                {% if useStatic %}
                Use Dynamic
                {% else %}
                Use Static
                {% endif %}

            {% endif %}
            {% endif %}

        {% endblock %}

	    {% block footer %} {% endblock %}


text:
"use strict";

const co = require("co");

const ForcePushSpec = require("../util/force_push_spec");

/**
 * This module contains methods for pushing.
 */

/**
 * help text for the `push` command
 * @property {String}
 */
exports.helpText = `Push commits from meta-repo and visible sub-repos.`;

/**
 * description of the `push` command
 * @property {String}
 */
exports.description =`
Push commits from all (visible) sub-repositories and the meta-repository.  By
default, this command pushes from the current branch to a branch with the
same name in the 'origin' repository.  The name of the remote, as well as the
source and target branches may be overridden.  Push synthetic-meta-refs for
each submodule with changes indicated by commits being pushed to the meta-repo.
Don't push to the meta-repo until the submodule pushes finish successfully.  Do
not consult the remotes configured for the submodules; instead, push the
synthetic-meta-ref for each submodule to a URL that is derived by resolving
its configured URL against the URL being pushed to by the meta-repo.`;

exports.configureParser = function (parser) {

    parser.addArgument("repository", {
        type: "string",
        nargs: "?",
        defaultValue: null,
        help: `remote repository that is the destination of a push; can either
be a URL or name of a remote; 'origin' used if not specified`,
    });

    parser.addArgument("refspec", {
        type: "string",
        nargs: "*",
        defaultValue: null,
        help: `(optional) plus, follow by a source ref, (optionally) followed
by a : and a destination ref <dst>; will push branch to destination branch
if not specified.`,
    });

    parser.addArgument(["-f", "--force"], {
        required: false,
        action: "storeConst",
        constant: ForcePushSpec.Force,
        defaultValue: ForcePushSpec.NoForce,
        help: `Attempt to push even if not a fast-forward change.`,
    });

    parser.addArgument(["--force-with-lease"], {
        required: false,
        action: "storeConst",
        constant: ForcePushSpec.ForceWithLease,
        dest: "force",
        help: `Force-push only if the remote ref is in the expected state
(i.e. matches the local version of that ref)`,
    });
};

/**
 * Execute the push command according to the specified `args`.
 *
 * @async
 * @param {Object} args
 * @param {String} args.repository
 * @param {String} [args.refspec]
 */
exports.executeableSubcommand = co.wrap(function *(args) {
    const GitUtil = require("../util/git_util");
    const push = require("../util/push");

    const repo = yield GitUtil.getCurrentRepo();

    // TODO: this all needs to move into the `util` and get a test driver.

    const branch = yield repo.getCurrentBranch();
    const tracking = (yield GitUtil.getTrackingInfo(repo, branch)) || {};

    // The repo is the value passed by the user, the tracking branch's remote,
    // or just "origin", in order of preference.

    const remoteName = args.repository || tracking.pushRemoteName || "origin";

    let strRefspecs = [];
    if (0 === args.refspec.length) {
        // We will use the `push.default` `upstream` strategy for now: (see
        // https://git-scm.com/docs/git-config).
        // That is, if there is a tracking (merge) branch configured, and the
        // remote for that branch is the one we're pushing to, we'll use it.
        // Otherwise, we fall back on the name of the active branch.
        //
        // TODO: read and adhere to the configured value for `push.default`.

        const activeBranchName = branch.shorthand();
        let targetName = activeBranchName;
        if (null !== tracking.branchName &&
            remoteName === tracking.remoteName) {
            targetName = tracking.branchName;
        }
        strRefspecs.push(activeBranchName + ":" + targetName);
    } else {
        strRefspecs = strRefspecs.concat(args.refspec);
    }

    yield strRefspecs.map(co.wrap(function *(strRefspec) {
        const refspec = GitUtil.parseRefspec(strRefspec);
        // Force-push if the refspec explicitly tells us to do so (i.e. is
        // prefixed with a '+').
        const force = refspec.force ? ForcePushSpec.Force : args.force;

        // If 'src' is empty, this is a deletion.  Do not use the normal meta
        // push; there is no need to, e.g., push submodules, in this case.

        if ("" !== refspec.src) {
            yield push.push(repo,
                            remoteName,
                            refspec.src,
                            refspec.dst,
                            force);
        }
        else {
            yield GitUtil.push(repo,
                               remoteName,
                               "",
                               refspec.dst,
                               force);
        }
    }));
});


text:
#include "Node.h"
#include "Link.h"
#include "IPhysicsMovableItem.h"
#include "IPhysicsBody.h"
#include "BoundingBox.h"
#include "MovableItem.h"
#include "BodyPart.h"
#include "Joint.h"
#include "ReceptiveField.h"
#include "ContactSensor.h"
#include "RigidBody.h"
#include "Structure.h"
#include "NeuralModule.h"
#include "Adapter.h"
#include "NervousSystem.h"
#include "Organism.h"
#include "ActivatedItem.h"
#include "ActivatedItemMgr.h"
#include "DataChartMgr.h"
#include "ExternalStimuliMgr.h"
#include "KeyFrame.h"
#include "SimulationRecorder.h"
#include "OdorType.h"
#include "Odor.h"
#include "Light.h"
#include "LightManager.h"
#include "Simulator.h"

namespace AnimatSim
{
	namespace Environment
	{

IMotorizedJoint::IMotorizedJoint(void)
{
}

IMotorizedJoint::~IMotorizedJoint(void)
{
}

	}
}


text:
"""This file is based on the car_dynamics.py in OpenAI's gym.

Description
    We provide some modified CarRacing environments here:
    * CarRacingColor-v0
        Both the lane and the grass colors are perturbed at the env.reset() with scalar noises.
    * CarRacingColor3-v0
        Both the lane and the grass colors are perturbed at the env.reset() with 3d noises.
    * CarRacingBar-v0
        We add vertical bars on the left and right side of the screen.
    * CarRacingBlob-v0
        A red blob that follows the car at a fixed position in the car's frame.
    * CarRacingNoise-v0
        We replace the green background with noise.
    * CarRacingVideo-v0
        We replace the green background with frames from a video, the user is
        responsible for creating these frames and pass the directory.
    These environments were first used in the paper "Neuroevolution of Self-Interpretable Agent"
    https://attentionagent.github.io/

Author
    Yujin Tang (yujintang@google.com)
"""

import numpy as np
import math
import Box2D
from Box2D.b2 import (edgeShape, circleShape, fixtureDef, polygonShape, revoluteJointDef, contactListener, shape)

# Top-down car dynamics simulation.
#
# Some ideas are taken from this great tutorial http://www.iforce2d.net/b2dtut/top-down-car by Chris Campbell.
# This simulation is a bit more detailed, with wheels rotation.
#
# Created by Oleg Klimov. Licensed on the same terms as the rest of OpenAI Gym.

SIZE = 0.02
ENGINE_POWER            = 100000000*SIZE*SIZE
WHEEL_MOMENT_OF_INERTIA = 4000*SIZE*SIZE
FRICTION_LIMIT          = 1000000*SIZE*SIZE     # friction ~= mass ~= size^2 (calculated implicitly using density)
WHEEL_R  = 27
WHEEL_W  = 14
WHEELPOS = [
    (-55,+80), (+55,+80),
    (-55,-82), (+55,-82)
    ]
HULL_POLY1 =[
    (-60,+130), (+60,+130),
    (+60,+110), (-60,+110)
    ]
HULL_POLY2 =[
    (-15,+120), (+15,+120),
    (+20, +20), (-20,  20)
    ]
HULL_POLY3 =[
    (+25, +20),
    (+50, -10),
    (+50, -40),
    (+20, -90),
    (-20, -90),
    (-50, -40),
    (-50, -10),
    (-25, +20)
    ]
HULL_POLY4 =[
    (-50,-120), (+50,-120),
    (+50,-90),  (-50,-90)
    ]

WHEEL_COLOR = (0.0,0.0,0.0)
WHEEL_WHITE = (0.3,0.3,0.3)
MUD_COLOR   = (0.4,0.4,0.0)

class Car:
    def __init__(self, world, init_angle, init_x, init_y, add_blob=False):
        self.world = world

        self.add_blob = add_blob

        fixtures = [
            fixtureDef(shape=polygonShape(
                vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY1 ]), density=1.0),
            fixtureDef(shape=polygonShape(
                vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY2 ]), density=1.0),
            fixtureDef(shape=polygonShape(
                vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY3 ]), density=1.0),
            fixtureDef(shape=polygonShape(
                vertices=[ (x*SIZE,y*SIZE) for x,y in HULL_POLY4 ]), density=1.0),
        ]
        self.hull = self.world.CreateDynamicBody(
            position = (init_x, init_y),
            angle = init_angle,
            fixtures = fixtures,
        )
        self.hull.color = (0.8,0.0,0.0)
        self.wheels = []
        self.fuel_spent = 0.0
        WHEEL_POLY = [
            (-WHEEL_W,+WHEEL_R), (+WHEEL_W,+WHEEL_R),
            (+WHEEL_W,-WHEEL_R), (-WHEEL_W,-WHEEL_R)
            ]
        for wx,wy in WHEELPOS:
            front_k = 1.0 if wy > 0 else 1.0
            w = self.world.CreateDynamicBody(
                position = (init_x+wx*SIZE, init_y+wy*SIZE),
                angle = init_angle,
                fixtures = fixtureDef(
                    shape=polygonShape(vertices=[ (x*front_k*SIZE,y*front_k*SIZE) for x,y in WHEEL_POLY ]),
                    density=0.1,
                    categoryBits=0x0020,
                    maskBits=0x001,
                    restitution=0.0)
                    )
            w.wheel_rad = front_k*WHEEL_R*SIZE
            w.color = WHEEL_COLOR
            w.gas   = 0.0
            w.brake = 0.0
            w.steer = 0.0
            w.phase = 0.0  # wheel angle
            w.omega = 0.0  # angular velocity
            w.skid_start = None
            w.skid_particle = None
            rjd = revoluteJointDef(
                bodyA=self.hull,
                bodyB=w,
                localAnchorA=(wx*SIZE,wy*SIZE),
                localAnchorB=(0,0),
                enableMotor=True,
                enableLimit=True,
                maxMotorTorque=180*900*SIZE*SIZE,
                motorSpeed = 0,
                lowerAngle = -0.4,
                upperAngle = +0.4,
                )
            w.joint = self.world.CreateJoint(rjd)
            w.tiles = set()
            w.userData = w
            self.wheels.append(w)
        self.drawlist =  self.wheels + [self.hull]
        self.particles = []

    def gas(self, gas):
        'control: rear wheel drive'
        gas = np.clip(gas, 0, 1)
        for w in self.wheels[2:4]:
            diff = gas - w.gas
            if diff > 0.1: diff = 0.1  # gradually increase, but stop immediately
            w.gas += diff

    def brake(self, b):
        'control: brake b=0..1, more than 0.9 blocks wheels to zero rotation'
        for w in self.wheels:
            w.brake = b

    def steer(self, s):
        'control: steer s=-1..1, it takes time to rotate steering wheel from side to side, s is target position'
        self.wheels[0].steer = s
        self.wheels[1].steer = s

    def step(self, dt):
        for w in self.wheels:
            # Steer each wheel
            dir = np.sign(w.steer - w.joint.angle)
            val = abs(w.steer - w.joint.angle)
            w.joint.motorSpeed = dir*min(50.0*val, 3.0)

            # Position => friction_limit
            grass = True
            friction_limit = FRICTION_LIMIT*0.6  # Grass friction if no tile
            for tile in w.tiles:
                friction_limit = max(friction_limit, FRICTION_LIMIT*tile.road_friction)
                grass = False

            # Force
            forw = w.GetWorldVector( (0,1) )
            side = w.GetWorldVector( (1,0) )
            v = w.linearVelocity
            vf = forw[0]*v[0] + forw[1]*v[1]  # forward speed
            vs = side[0]*v[0] + side[1]*v[1]  # side speed

            # WHEEL_MOMENT_OF_INERTIA*np.square(w.omega)/2 = E -- energy
            # WHEEL_MOMENT_OF_INERTIA*w.omega * domega/dt = dE/dt = W -- power
            # domega = dt*W/WHEEL_MOMENT_OF_INERTIA/w.omega
            w.omega += dt*ENGINE_POWER*w.gas/WHEEL_MOMENT_OF_INERTIA/(abs(w.omega)+5.0)  # small coef not to divide by zero
            self.fuel_spent += dt*ENGINE_POWER*w.gas

            if w.brake >= 0.9:
                w.omega = 0
            elif w.brake > 0:
                BRAKE_FORCE = 15    # radians per second
                dir = -np.sign(w.omega)
                val = BRAKE_FORCE*w.brake
                if abs(val) > abs(w.omega): val = abs(w.omega)  # low speed => same as = 0
                w.omega += dir*val
            w.phase += w.omega*dt

            vr = w.omega*w.wheel_rad  # rotating wheel speed
            f_force = -vf + vr        # force direction is direction of speed difference
            p_force = -vs

            # Physically correct is to always apply friction_limit until speed is equal.
            # But dt is finite, that will lead to oscillations if difference is already near zero.
            f_force *= 205000*SIZE*SIZE  # Random coefficient to cut oscillations in few steps (have no effect on friction_limit)
            p_force *= 205000*SIZE*SIZE
            force = np.sqrt(np.square(f_force) + np.square(p_force))

            # Skid trace
            if abs(force) > 2.0*friction_limit:
                if w.skid_particle and w.skid_particle.grass==grass and len(w.skid_particle.poly) < 30:
                    w.skid_particle.poly.append( (w.position[0], w.position[1]) )
                elif w.skid_start is None:
                    w.skid_start = w.position
                else:
                    w.skid_particle = self._create_particle( w.skid_start, w.position, grass )
                    w.skid_start = None
            else:
                w.skid_start = None
                w.skid_particle = None

            if abs(force) > friction_limit:
                f_force /= force
                p_force /= force
                force = friction_limit  # Correct physics here
                f_force *= force
                p_force *= force

            w.omega -= dt*f_force*w.wheel_rad/WHEEL_MOMENT_OF_INERTIA

            w.ApplyForceToCenter( (
                p_force*side[0] + f_force*forw[0],
                p_force*side[1] + f_force*forw[1]), True )

    def draw(self, viewer, draw_particles=True):
        if draw_particles:
            for p in self.particles:
                viewer.draw_polyline(p.poly, color=p.color, linewidth=5)
        for obj in self.drawlist:
            for i, f in enumerate(obj.fixtures):
                trans = f.body.transform
                path = [trans*v for v in f.shape.vertices]
                if self.add_blob and i == 3:
                    obj_color = (0.8, 0.0, 0.)
                    offset_x = f.shape.vertices[0][0] + 20
                    offset_y = f.shape.vertices[0][1] + 10
                    width = height = 8
                    blob =[
                        trans * (+offset_x, +offset_y+height),
                        trans * (+offset_x+width, +offset_y+height),
                        trans * (+offset_x+width, +offset_y),
                        trans * (+offset_x, +offset_y),
                    ]
                    viewer.draw_polygon(blob, color=obj_color)
                viewer.draw_polygon(path, color=obj.color)
                if "phase" not in obj.__dict__: continue
                a1 = obj.phase
                a2 = obj.phase + 1.2  # radians
                s1 = math.sin(a1)
                s2 = math.sin(a2)
                c1 = math.cos(a1)
                c2 = math.cos(a2)
                if s1>0 and s2>0: continue
                if s1>0: c1 = np.sign(c1)
                if s2>0: c2 = np.sign(c2)
                white_poly = [
                    (-WHEEL_W*SIZE, +WHEEL_R*c1*SIZE), (+WHEEL_W*SIZE, +WHEEL_R*c1*SIZE),
                    (+WHEEL_W*SIZE, +WHEEL_R*c2*SIZE), (-WHEEL_W*SIZE, +WHEEL_R*c2*SIZE)
                    ]
                viewer.draw_polygon([trans*v for v in white_poly], color=WHEEL_WHITE)

    def _create_particle(self, point1, point2, grass):
        class Particle:
            pass
        p = Particle()
        p.color = WHEEL_COLOR if not grass else MUD_COLOR
        p.ttl = 1
        p.poly = [(point1[0],point1[1]), (point2[0],point2[1])]
        p.grass = grass
        self.particles.append(p)
        while len(self.particles) > 30:
            self.particles.pop(0)
        return p

    def destroy(self):
        self.world.DestroyBody(self.hull)
        self.hull = None
        for w in self.wheels:
            self.world.DestroyBody(w)
        self.wheels = []


text:
package org.jetbrains.lang.manifest.psi;

import com.intellij.lang.ASTNode;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ILeafElementType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.lang.manifest.ManifestLanguage;
import org.jetbrains.lang.manifest.psi.impl.ManifestTokenImpl;

/**
 * @author Robert F. Beeger (robert@beeger.net)
 */
public final class ManifestTokenType extends IElementType implements ILeafElementType {
  public static final ManifestTokenType HEADER_NAME = new ManifestTokenType("HEADER_NAME_TOKEN");
  public static final ManifestTokenType NEWLINE = new ManifestTokenType("NEWLINE_TOKEN");
  public static final ManifestTokenType SECTION_END = new ManifestTokenType("SECTION_END_TOKEN");
  public static final ManifestTokenType COLON = new ManifestTokenType("COLON_TOKEN");
  public static final ManifestTokenType SEMICOLON = new ManifestTokenType("SEMICOLON_TOKEN");
  public static final ManifestTokenType EQUALS = new ManifestTokenType("EQUALS_TOKEN");
  public static final ManifestTokenType COMMA = new ManifestTokenType("COMMA_TOKEN");
  public static final ManifestTokenType QUOTE = new ManifestTokenType("QUOTE_TOKEN");
  public static final ManifestTokenType HEADER_VALUE_PART = new ManifestTokenType("HEADER_VALUE_PART_TOKEN");
  public static final ManifestTokenType SIGNIFICANT_SPACE = new ManifestTokenType("SIGNIFICANT_SPACE_TOKEN");
  public static final ManifestTokenType OPENING_PARENTHESIS_TOKEN = new ManifestTokenType("OPENING_PARENTHESIS_TOKEN");
  public static final ManifestTokenType CLOSING_PARENTHESIS_TOKEN = new ManifestTokenType("CLOSING_PARENTHESIS_TOKEN");
  public static final ManifestTokenType OPENING_BRACKET_TOKEN = new ManifestTokenType("OPENING_BRACKET_TOKEN");
  public static final ManifestTokenType CLOSING_BRACKET_TOKEN = new ManifestTokenType("CLOSING_BRACKET_TOKEN");

  private ManifestTokenType(@NotNull @NonNls String debugName) {
    super(debugName, ManifestLanguage.INSTANCE);
  }

  @NotNull
  @Override
  public ASTNode createLeafNode(CharSequence text) {
    return new ManifestTokenImpl(this, text);
  }
}


text:
#ifndef _WX_DRAWERWINDOW_H_
#define _WX_DRAWERWINDOW_H_

#include "wx/toplevel.h"

//
// NB:  This is currently a private undocumented class -
// it is stable, but the API is not and will change in the
// near future
//

class WXDLLIMPEXP_ADV wxDrawerWindow : public wxTopLevelWindow
{
    DECLARE_DYNAMIC_CLASS(wxDrawerWindow)

public:

    wxDrawerWindow();

    wxDrawerWindow(wxWindow* parent,
                   wxWindowID id,
                   const wxString& title,
                   wxSize size = wxDefaultSize,
                   wxDirection edge = wxLEFT,
                   const wxString& name = wxT("drawerwindow"))
    {
        this->Create(parent, id, title, size, edge, name);
    }

    virtual ~wxDrawerWindow();

    // Create a drawer window.
    // If parent is NULL, create as a tool window.
    // If parent is not NULL, then wxTopLevelWindow::Attach this window to parent.
    bool Create(wxWindow *parent,
     wxWindowID id,
     const wxString& title,
     wxSize size = wxDefaultSize,
     wxDirection edge = wxLEFT,
     const wxString& name = wxFrameNameStr);

    bool Open(bool show = true); // open or close the drawer, possibility for async param, i.e. animate
    bool Close() { return this->Open(false); }
    bool IsOpen() const;

    // Set the edge of the parent where the drawer attaches.
    bool SetPreferredEdge(wxDirection edge);
    wxDirection GetPreferredEdge() const;
    wxDirection GetCurrentEdge() const; // not necessarily the preferred, due to screen constraints
};

#endif // _WX_DRAWERWINDOW_H_


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Delphinium bonvalotii Franch.

### Remarks
null


text:
#ifndef __OS_LINUX_BASE__
#define __OS_LINUX_BASE__

#include <sys/user.h>
#include <sys/param.h>

#if __GNUC__
#define OS_EXPECT(x, v) __builtin_expect((x), (v))
#else
#define OS_EXPECT(x, v) (x)
#endif

#ifndef os_likely
#define os_likely(x) OS_EXPECT(!!(x), 1)
#endif
#ifndef os_unlikely
#define os_unlikely(x) OS_EXPECT(!!(x), 0)
#endif

#if __has_feature(assume_nonnull)
#define OS_ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
#define OS_ASSUME_NONNULL_END   _Pragma("clang assume_nonnull end")
#else
#define OS_ASSUME_NONNULL_BEGIN
#define OS_ASSUME_NONNULL_END
#endif

#if __has_builtin(__builtin_assume)
#define OS_COMPILER_CAN_ASSUME(expr) __builtin_assume(expr)
#else
#define OS_COMPILER_CAN_ASSUME(expr) ((void)(expr))
#endif

#if __has_feature(attribute_availability_swift)
// equivalent to __SWIFT_UNAVAILABLE from Availability.h
#define OS_SWIFT_UNAVAILABLE(_msg) \
		__attribute__((__availability__(swift, unavailable, message=_msg)))
#else
#define OS_SWIFT_UNAVAILABLE(_msg)
#endif

#if __has_attribute(swift_private)
# define OS_REFINED_FOR_SWIFT __attribute__((__swift_private__))
#else
# define OS_REFINED_FOR_SWIFT
#endif

#if __has_attribute(swift_name)
# define OS_SWIFT_NAME(_name) __attribute__((__swift_name__(#_name)))
#else
# define OS_SWIFT_NAME(_name)
#endif

#define __OS_STRINGIFY(s) #s
#define OS_STRINGIFY(s) __OS_STRINGIFY(s)
#define __OS_CONCAT(x, y) x ## y
#define OS_CONCAT(x, y) __OS_CONCAT(x, y)

/*
 * Stub out misc linking and compilation attributes
 */

#ifdef OS_EXPORT
#undef OS_EXPORT
#endif
#define OS_EXPORT

#ifdef OS_WARN_RESULT_NEEDS_RELEASE
#undef OS_WARN_RESULT_NEEDS_RELEASE
#endif

#ifdef OS_WARN_RESULT
#undef OS_WARN_RESULT
#endif
#define OS_WARN_RESULT

#ifdef OS_NOTHROW
#undef OS_NOTHROW
#endif
#define OS_NOTHROW

#endif /* __OS_LINUX_BASE__ */


text:
import os
from setuptools import find_packages, setup

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='djangocms-typedjs',
    version='1.0.0',
    license='MIT License',
    description='A Django CMS plugin that implements the Typed.js jQuery plugin.',
    long_description=README,
    url='https://github.com/tdsymonds/djangocms-typedjs',
    author='Tom Symonds',
    author_email='tdsymonds@hotmail.com',
    keywords='djangocms-typedjs, typedjs, typing, django',
    packages=[
        'djangocms_typedjs',
    ],
    include_package_data=True,
    install_requires=[
        'django-cms>=3.2',
        'djangocms-text-ckeditor',
    ],
    classifiers=[
        'Environment :: Web Environment',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 2.7',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
    ],
)


text:
import datetime

from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.html import strip_tags
from django.utils.translation import ugettext_lazy as _

from contrib.feedparser import feedparser

# Create your models here.

class Cluster(models.Model):
    created = models.DateTimeField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.created = datetime.datetime.now()
        super(Cluster, self).save()

    def get_items(self):
        return News.objects.filter(cluster=self)

    def __unicode__(self):
        return u'%d' % self.pk

class NewsSource(models.Model):
    name = models.CharField(_("Name"), max_length=200)
    url = models.URLField(verify_exists=False)

    def __unicode__(self):
        return self.name

class News(models.Model):
    url = models.URLField(_("URL"), verify_exists=False)
    title = models.CharField(_("Title"), max_length=200)
    body = models.TextField(null=True, blank=True)
    date = models.DateTimeField()
    source = models.ForeignKey(NewsSource)
    cluster = models.ForeignKey(Cluster, null=True, blank=True)

    class Meta:
        verbose_name = _("News")
        verbose_name_plural = _("News")

    def __unicode__(self):
        return self.title

@receiver(post_save, sender=NewsSource)
def create_news_items(sender, instance, created, **kwargs):
    """Create a news items from source"""
    #if created:
    feed = feedparser.parse(instance.url)
    for item in feed.entries:
        try:
            news = News.objects.get(url=item.link)
        except News.DoesNotExist:
            if not hasattr(item, 'updated_parsed'):
                date = datetime.datetime.now()
            else:
                date = datetime.datetime(*item.updated_parsed[:6])
            news = News(url=item.link, title=item.title, body=strip_tags(item.summary),
                        date=date, source=instance)
            news.save()


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/shared/to_a'

describe "String#to_a" do
  it_behaves_like :string_to_a, :to_a
end