text:
package com.blossomproject.core.common.dao;

import com.blossomproject.core.common.entity.AbstractAssociationEntity;
import com.blossomproject.core.common.entity.AbstractEntity;
import java.util.List;

/**
 * Generic DAO interface whose purpose is to manage two {@code AbstractEntity}'s N-N relationships.
 *
 * @param  the first {@code AbstractEntity} type
 * @param  the second {@code AbstractEntity} type
 * @param <ASSOCIATION> the {@code AbstractAssociationEntity} type.
 *
 * @see AbstractAssociationEntity : association entity class
 * @see GenericAssociationDaoImpl : the default implementation
 *
 * @author Maël Gargadennec
 */
public interface AssociationDao<A extends AbstractEntity, B extends AbstractEntity, ASSOCIATION extends AbstractAssociationEntity> {

  /**
   *
Creates a new association between two {@code AbstractEntity}.

   *
If the association already exists, retrieves it.

   *
   * @param a the first {@code AbstractEntity}. If null, throws an {@code IllegalArgumentException}.
   * @param b the second {@code AbstractEntity}. If null, throws an {@code IllegalArgumentException}.
   * @return the created or already existing association
   */
  ASSOCIATION associate(A a, B b);

  /**
   *
Removes and existing association between two {@code AbstractEntity}.

   *
If the association does not exist, this method does nothing.

   *
   * @param a the first {@code AbstractEntity}. If null, throws an {@code IllegalArgumentException}.
   * @param b the second {@code AbstractEntity}. If null, throws an {@code IllegalArgumentException}.
   */
  void dissociate(A a, B b);

  /**
   * Retrieve a {@code List} of all {@code A}/{@code B} associations for a given {@code B} element
   *
   * @param b an {@code AbstractEntity} of parametrized type {@code B}. If null, throws an {@code IllegalArgumentException}.
   * @return the list of all available associations to {@code A} elements
   */
  List<ASSOCIATION> getAllA(B b);

  /**
   * Retrieve a {@code List} of all {@code A}/{@code B} associations for a given {@code A} element
   *
   * @param a an {@code AbstractEntity} of parametrized type {@code A}. If null, throws an {@code IllegalArgumentException}.
   * @return the list of all available associations to {@code B} elements
   */
  List<ASSOCIATION> getAllB(A a);

  /**
   * Get an {@code A}/{@code B} association by its identifier.
   *
   * @param id the association id
   * @return the association, or {@literal null}  if it doesn't exist
   */
  ASSOCIATION getOne(long id);

  /**
   * Get an {@code A}/{@code B} association by its associated entities.
   *
   * @param a an {@code AbstractEntity} of parametrized type {@code A}. If null, throws an {@code IllegalArgumentException}.
   * @param b an {@code AbstractEntity} of parametrized type {@code B}. If null, throws an {@code IllegalArgumentException}.
   * @return the association, or {@literal null} if not found
   */
  ASSOCIATION getOne(A a, B b);
}


text:
S5Server
========

**TODO: Add description**

redpajama_set_name: RedPajamaGithub


text:
package com.redhat.osas.ml.analysis.sources.twitter;

import com.redhat.osas.ml.analysis.model.SourceData;
import com.redhat.osas.ml.analysis.sources.StreamSource;
import org.testng.annotations.Test;

import java.util.List;

public class TwitterTest {
    @Test
    public void testTwitterSearch() {
        StreamSource source=new TwitterStreamSource();
        List<SourceData> data=source.getData("hibernate");
        System.out.println(data);
    }
}


text:
/* Generated by ./xlat/gen.sh from ./xlat/mctl_sync.in; do not edit. */

static const struct xlat mctl_sync[] = {
#if defined(MS_SYNC) || (defined(HAVE_DECL_MS_SYNC) && HAVE_DECL_MS_SYNC)
	XLAT(MS_SYNC),
#endif
#if defined(MS_ASYNC) || (defined(HAVE_DECL_MS_ASYNC) && HAVE_DECL_MS_ASYNC)
	XLAT(MS_ASYNC),
#endif
#if defined(MS_INVALIDATE) || (defined(HAVE_DECL_MS_INVALIDATE) && HAVE_DECL_MS_INVALIDATE)
	XLAT(MS_INVALIDATE),
#endif
	XLAT_END
};


text:
Each Sass navigation partial should refer to its respective pug partial. This makes navigation changes easier down the road.

**Wondering where the nav links are coming from? They are populated using data from configuration.json.**

## Template

In practice, each nav can be fairly unique. For that reason, a template navigation partial was created in order to have a go-to partial to copy into another unique partial for your new nav.

## Main

The main nav usually includes some more complicated styles compared to other navs. Because of this, direct child selectors were used in order to selectively style root links versus child links.


text:
#ifndef itkFastMarchingImageFilterBase_h
#define itkFastMarchingImageFilterBase_h

#include "itkFastMarchingBase.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkNeighborhoodIterator.h"
#include "itkArray.h"
#include <bitset>

namespace itk
{
/**
 * \class FastMarchingImageFilterBase
 * \brief Apply the Fast Marching method to solve an Eikonal equation on an image.
 *
 * The speed function can be specified as a speed image or a
 * speed constant. The speed image is set using the method
 * SetInput(). If the speed image is nullptr, a constant speed function
 * is used and is specified using method the SetSpeedConstant().
 *
 * If the speed function is constant and of value one, fast marching results
 * is an approximate distance function from the initial alive points.
 *
 * There are two ways to specify the output image information
 * (LargestPossibleRegion, Spacing, Origin):
 * \li it is copied directly from the input speed image
 * \li it is specified by the user.
 * Default values are used if the user does not specify all the information.
 *
 * The output information is computed as follows.
 *
 * If the speed image is nullptr or if the OverrideOutputInformation is set to
 * true, the output information is set from user specified parameters. These
 * parameters can be specified using methods
 * \li FastMarchingImageFilterBase::SetOutputRegion(),
 * \li FastMarchingImageFilterBase::SetOutputSpacing(),
 * \li FastMarchingImageFilterBase::SetOutputDirection(),
 * \li FastMarchingImageFilterBase::SetOutputOrigin().
 *
 * Else the output information is copied from the input speed image.
 *
 * Implementation of this class is based on Chapter 8 of
 * "Level Set Methods and Fast Marching Methods", J.A. Sethian,
 * Cambridge Press, Second edition, 1999.
 *
 * For an alternative implementation, see itk::FastMarchingImageFilter.
 *
 * \tparam TTraits traits
 *
 * \sa FastMarchingImageFilter
 * \sa ImageFastMarchingTraits
 * \sa ImageFastMarchingTraits2
 *
 * \ingroup ITKFastMarching
 */
template <typename TInput, typename TOutput>
class ITK_TEMPLATE_EXPORT FastMarchingImageFilterBase : public FastMarchingBase<TInput, TOutput>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(FastMarchingImageFilterBase);

  using Self = FastMarchingImageFilterBase;
  using Superclass = FastMarchingBase<TInput, TOutput>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;
  using typename Superclass::Traits;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(FastMarchingImageFilterBase, FastMarchingBase);

  using InputImageType = typename Superclass::InputDomainType;
  using InputImagePointer = typename Superclass::InputDomainPointer;
  using typename Superclass::InputPixelType;

  using OutputImageType = typename Superclass::OutputDomainType;
  using OutputImagePointer = typename Superclass::OutputDomainPointer;
  using typename Superclass::OutputPixelType;
  using OutputSpacingType = typename OutputImageType::SpacingType;
  using OutputSizeType = typename OutputImageType::SizeType;
  using OutputRegionType = typename OutputImageType::RegionType;
  using OutputPointType = typename OutputImageType::PointType;
  using OutputDirectionType = typename OutputImageType::DirectionType;

  using NodeType = typename Traits::NodeType;
  using NodePairType = typename Traits::NodePairType;
  using NodePairContainerType = typename Traits::NodePairContainerType;
  using NodePairContainerPointer = typename Traits::NodePairContainerPointer;
  using NodePairContainerConstIterator = typename Traits::NodePairContainerConstIterator;

  using typename Superclass::LabelType;

  static constexpr unsigned int ImageDimension = Traits::ImageDimension;

  using LabelImageType = Image<unsigned char, ImageDimension>;
  using LabelImagePointer = typename LabelImageType::Pointer;

  using ConnectedComponentImageType = Image<unsigned int, ImageDimension>;
  using ConnectedComponentImagePointer = typename ConnectedComponentImageType::Pointer;

  using NeighborhoodIteratorType = NeighborhoodIterator<LabelImageType>;
  using NeighborhoodRadiusType = typename NeighborhoodIteratorType::RadiusType;

  class InternalNodeStructure;

  using InternalNodeStructureArray = FixedArray<InternalNodeStructure, ImageDimension>;

  itkGetModifiableObjectMacro(LabelImage, LabelImageType);

  /** The output largest possible, spacing and origin is computed as follows.
   * If the speed image is nullptr or if the OverrideOutputInformation is true,
   * the output information is set from user specified parameters. These
   * parameters can be specified using methods SetOutputRegion(),
   * SetOutputSpacing(), SetOutputDirection(), and SetOutputOrigin().
   * Else if the speed image is not nullptr, the output information
   * is copied from the input speed image. */
  virtual void
  SetOutputSize(const OutputSizeType & size)
  {
    m_OutputRegion = size;
  }
  virtual OutputSizeType
  GetOutputSize() const
  {
    return m_OutputRegion.GetSize();
  }
  itkSetMacro(OutputRegion, OutputRegionType);
  itkGetConstReferenceMacro(OutputRegion, OutputRegionType);
  itkSetMacro(OutputSpacing, OutputSpacingType);
  itkGetConstReferenceMacro(OutputSpacing, OutputSpacingType);
  itkSetMacro(OutputDirection, OutputDirectionType);
  itkGetConstReferenceMacro(OutputDirection, OutputDirectionType);
  itkSetMacro(OutputOrigin, OutputPointType);
  itkGetConstReferenceMacro(OutputOrigin, OutputPointType);
  itkSetMacro(OverrideOutputInformation, bool);
  itkGetConstReferenceMacro(OverrideOutputInformation, bool);
  itkBooleanMacro(OverrideOutputInformation);

protected:
  FastMarchingImageFilterBase();

  ~FastMarchingImageFilterBase() override = default;

  void
  PrintSelf(std::ostream & os, Indent indent) const override;

  OutputRegionType m_BufferedRegion;
  NodeType         m_StartIndex;
  NodeType         m_LastIndex;

  OutputRegionType    m_OutputRegion;
  OutputPointType     m_OutputOrigin;
  OutputSpacingType   m_OutputSpacing;
  OutputDirectionType m_OutputDirection;
  bool                m_OverrideOutputInformation{ false };

  /** Generate the output image meta information. */
  void
  GenerateOutputInformation() override;

  void
  EnlargeOutputRequestedRegion(DataObject * output) override;

  LabelImagePointer              m_LabelImage;
  ConnectedComponentImagePointer m_ConnectedComponentImage;

  IdentifierType
  GetTotalNumberOfNodes() const override;

  void
  SetOutputValue(OutputImageType * oImage, const NodeType & iNode, const OutputPixelType & iValue) override;

  /** Returns the output value for a given node */
  const OutputPixelType
  GetOutputValue(OutputImageType * oImage, const NodeType & iNode) const override;

  /** Returns the label value for a given node */
  unsigned char
  GetLabelValueForGivenNode(const NodeType & iNode) const override;

  /** Set the label value for a given node */
  void
  SetLabelValueForGivenNode(const NodeType & iNode, const LabelType & iLabel) override;

  /** Update values for the neighbors of a given node */
  void
  UpdateNeighbors(OutputImageType * oImage, const NodeType & iNode) override;

  /** Update value for a given node */
  void
  UpdateValue(OutputImageType * oImage, const NodeType & iNode) override;

  /** Make sure the given node does not violate any topological constraint*/
  bool
  CheckTopology(OutputImageType * oImage, const NodeType & iNode) override;
  void
  InitializeOutput(OutputImageType * oImage) override;

  /** Find the nodes were the front will propagate given a node */
  void
  GetInternalNodesUsed(OutputImageType * oImage, const NodeType & iNode, InternalNodeStructureArray & ioNodesUsed);

  /** Solve the quadratic equation */
  double
  Solve(OutputImageType * oImage, const NodeType & iNode, InternalNodeStructureArray & iNeighbors) const;

  //
  // Functions and variables to check for topology changes (2D/3D only).
  //

  // Functions/data for the 2-D case
  void
  InitializeIndices2D();
  bool
  IsChangeWellComposed2D(const NodeType &) const;
  bool
  IsCriticalC1Configuration2D(const std::bitset<9> &) const;
  bool
  IsCriticalC2Configuration2D(const std::bitset<9> &) const;
  bool
  IsCriticalC3Configuration2D(const std::bitset<9> &) const;
  bool
  IsCriticalC4Configuration2D(const std::bitset<9> &) const;

  Array<unsigned char> m_RotationIndices[4];
  Array<unsigned char> m_ReflectionIndices[2];

  // Functions/data for the 3-D case
  void
  InitializeIndices3D();
  bool
  IsCriticalC1Configuration3D(const std::bitset<8> &) const;
  unsigned int
  IsCriticalC2Configuration3D(const std::bitset<8> &) const;
  bool
  IsChangeWellComposed3D(const NodeType &) const;

  Array<unsigned char> m_C1Indices[12];
  Array<unsigned char> m_C2Indices[8];

  // Functions for both 2D/3D cases
  bool
  DoesVoxelChangeViolateWellComposedness(const NodeType &) const;
  bool
  DoesVoxelChangeViolateStrictTopology(const NodeType &) const;

  const InputImageType * m_InputCache;

private:
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkFastMarchingImageFilterBase.hxx"
#endif

#endif // itkFastMarchingImageFilterBase_h


text:
module Azure::Cosmosdb::Mgmt::V2015_04_08
  module Models
    #
    # Cosmos DB SQL database id object
    #
    class SqlDatabaseResource

      include MsRestAzure

      # @return [String] Name of the Cosmos DB SQL database
      attr_accessor :id

      #
      # Mapper for SqlDatabaseResource class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'SqlDatabaseResource',
          type: {
            name: 'Composite',
            class_name: 'SqlDatabaseResource',
            model_properties: {
              id: {
                client_side_validation: true,
                required: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
FROM ubuntu:22.04

ARG PPA_TRACK=stable

# Prevent needing to configure debian packages, stopping the setup of
# the docker container.
RUN echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections

RUN apt-get update && apt-get install -y --no-install-recommends \
  software-properties-common \
  python3-pip \
  python3-wheel \
  python3-setuptools \
  python3-psycopg2 \
  gpg-agent \
  git \
  wget \
  && rm -rf /var/lib/apt/lists/*

# Install Plaso
RUN add-apt-repository -y ppa:gift/$PPA_TRACK
RUN apt-get update && apt-get install -y --no-install-recommends \
  plaso-tools \
  && rm -rf /var/lib/apt/lists/*

# Install timesketch from the current branch (In the context of CI platform)
ADD . /tmp/timesketch
RUN pip3 install -r /tmp/timesketch/requirements.txt
RUN pip3 install /tmp/timesketch && pip3 install /tmp/timesketch/api_client/python && \
  pip3 install /tmp/timesketch/importer_client/python

# Copy Timesketch config files into /etc/timesketch
RUN mkdir /etc/timesketch
RUN cp /tmp/timesketch/data/timesketch.conf /etc/timesketch/
RUN cp /tmp/timesketch/data/ontology.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/tags.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/intelligence_tag_metadata.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/features.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/plaso.mappings /etc/timesketch/
RUN cp /tmp/timesketch/data/generic.mappings /etc/timesketch/
RUN cp /tmp/timesketch/data/sigma_config.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/sigma_rule_status.csv /etc/timesketch/
RUN cp /tmp/timesketch/data/data_finder.yaml /etc/timesketch/
RUN cp /tmp/timesketch/data/bigquery_matcher.yaml /etc/timesketch/
RUN cp -r /tmp/timesketch/data/sigma /etc/timesketch/sigma
RUN chmod -R go+r /etc/timesketch

# Copy the entrypoint script into the container
COPY docker/e2e/docker-entrypoint.sh /
RUN chmod a+x /docker-entrypoint.sh

# Load the entrypoint script to be run later
ENTRYPOINT ["/docker-entrypoint.sh"]

# Invoke the entrypoint script
CMD ["timesketch"]


text:
package io.xdevs23.cornowser.browser.browser.modules.tabs;

import android.app.Activity;
import android.content.Context;

import io.xdevs23.cornowser.browser.browser.xwalk.CrunchyWalkView;

public class Tab {

    protected String tabUrl, tabTitle;
    protected CrunchyWalkView webView;

    public int tabId = 0;

    public Tab() {
        tabUrl      = "";
        tabTitle    = "";
    }

    public Tab(String url) {
        this();
        tabUrl = url;
    }

    public Tab(String url, String title) {
        this(url);
        tabTitle = title;
    }

    public Tab(int tabId) {
        this.tabId = tabId;
    }

    public Tab(TabStorage tabStorage, int tab) {
        this(tabStorage.getTab(tab).tabUrl, tabStorage.getTab(tab).tabTitle);
    }

    public Tab initWithWebRender(Context context, Activity activity) {
        return setWebRender(new CrunchyWalkView(context, activity));
    }

    public Tab setWebRender(CrunchyWalkView view) {
        webView = view;
        return this;
    }

    public String getUrl() {
        return tabUrl;
    }

    public String getTitle() {
        return tabTitle;
    }

    public void setUrl(String url) {
        tabUrl = url;
    }

    public void setTitle(String title) {
        tabTitle = title;
    }

    public Tab setId(int id) {
        tabId = id;
        return this;
    }

    public static String getTabUrl(Tab tab) {
        return tab.getUrl();
    }

    public static String getTabTitle(Tab tab) {
        return tab.getTitle();
    }

}


text:
<?php

namespace Drupal\file\Tests;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\file\Entity\File;

/**
 * Tests validation functions such as file type, max file size, max size per
 * node, and required.
 *
 * @group file
 */
class FileFieldValidateTest extends FileFieldTestBase {

  /**
   * Tests the required property on file fields.
   */
  public function testRequired() {
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
    $type_name = 'article';
    $field_name = strtolower($this->randomMachineName());
    $storage = $this->createFileField($field_name, 'node', $type_name, [], ['required' => '1']);
    $field = FieldConfig::loadByName('node', $type_name, $field_name);

    $test_file = $this->getTestFile('text');

    // Try to post a new node without uploading a file.
    $edit = [];
    $edit['title[0][value]'] = $this->randomMachineName();
    $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
    $this->assertRaw(t('@title field is required.', ['@title' => $field->getLabel()]), 'Node save failed when required file field was empty.');

    // Create a new node with the uploaded file.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $this->assertTrue($nid !== FALSE, format_string('uploadNodeFile(@test_file, @field_name, @type_name) succeeded', ['@test_file' => $test_file->getFileUri(), '@field_name' => $field_name, '@type_name' => $type_name]));

    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);

    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, 'File exists after uploading to the required field.');
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required field.');

    // Try again with a multiple value field.
    $storage->delete();
    $this->createFileField($field_name, 'node', $type_name, ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED], ['required' => '1']);

    // Try to post a new node without uploading a file in the multivalue field.
    $edit = [];
    $edit['title[0][value]'] = $this->randomMachineName();
    $this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
    $this->assertRaw(t('@title field is required.', ['@title' => $field->getLabel()]), 'Node save failed when required multiple value file field was empty.');

    // Create a new node with the uploaded file into the multivalue field.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, 'File exists after uploading to the required multiple value field.');
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading to the required multiple value field.');
  }

  /**
   * Tests the max file size validator.
   */
  public function testFileMaxSize() {
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
    $type_name = 'article';
    $field_name = strtolower($this->randomMachineName());
    $this->createFileField($field_name, 'node', $type_name, [], ['required' => '1']);

    $small_file = $this->getTestFile('text', 131072); // 128KB.
    $large_file = $this->getTestFile('text', 1310720); // 1.2MB

    // Test uploading both a large and small file with different increments.
    $sizes = [
      '1M' => 1048576,
      '1024K' => 1048576,
      '1048576' => 1048576,
    ];

    foreach ($sizes as $max_filesize => $file_limit) {
      // Set the max file upload size.
      $this->updateFileField($field_name, $type_name, ['max_filesize' => $max_filesize]);

      // Create a new node with the small file, which should pass.
      $nid = $this->uploadNodeFile($small_file, $field_name, $type_name);
      $node_storage->resetCache([$nid]);
      $node = $node_storage->load($nid);
      $node_file = File::load($node->{$field_name}->target_id);
      $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) under the max limit (%maxsize).', ['%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize]));
      $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', ['%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize]));

      // Check that uploading the large file fails (1M limit).
      $this->uploadNodeFile($large_file, $field_name, $type_name);
      $error_message = t('The file is %filesize exceeding the maximum file size of %maxsize.', ['%filesize' => format_size($large_file->getSize()), '%maxsize' => format_size($file_limit)]);
      $this->assertRaw($error_message, format_string('Node save failed when file (%filesize) exceeded the max upload size (%maxsize).', ['%filesize' => format_size($large_file->getSize()), '%maxsize' => $max_filesize]));
    }

    // Turn off the max filesize.
    $this->updateFileField($field_name, $type_name, ['max_filesize' => '']);

    // Upload the big file successfully.
    $nid = $this->uploadNodeFile($large_file, $field_name, $type_name);
    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, format_string('File exists after uploading a file (%filesize) with no max limit.', ['%filesize' => format_size($large_file->getSize())]));
    $this->assertFileEntryExists($node_file, format_string('File entry exists after uploading a file (%filesize) with no max limit.', ['%filesize' => format_size($large_file->getSize())]));
  }

  /**
   * Tests file extension checking.
   */
  public function testFileExtension() {
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
    $type_name = 'article';
    $field_name = strtolower($this->randomMachineName());
    $this->createFileField($field_name, 'node', $type_name);

    $test_file = $this->getTestFile('image');
    list(, $test_file_extension) = explode('.', $test_file->getFilename());

    // Disable extension checking.
    $this->updateFileField($field_name, $type_name, ['file_extensions' => '']);

    // Check that the file can be uploaded with no extension checking.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');

    // Enable extension checking for text files.
    $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']);

    // Check that the file with the wrong extension cannot be uploaded.
    $this->uploadNodeFile($test_file, $field_name, $type_name);
    $error_message = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => 'txt']);
    $this->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');

    // Enable extension checking for text and image files.
    $this->updateFileField($field_name, $type_name, ['file_extensions' => "txt $test_file_extension"]);

    // Check that the file can be uploaded with extension checking.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
  }

  /**
   * Checks that a file can always be removed if it does not pass validation.
   */
  public function testFileRemoval() {
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
    $type_name = 'article';
    $field_name = 'file_test';
    $this->createFileField($field_name, 'node', $type_name);

    $test_file = $this->getTestFile('image');

    // Disable extension checking.
    $this->updateFileField($field_name, $type_name, ['file_extensions' => '']);

    // Check that the file can be uploaded with no extension checking.
    $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
    $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $node_file = File::load($node->{$field_name}->target_id);
    $this->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
    $this->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');

    // Enable extension checking for text files.
    $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']);

    // Check that the file can still be removed.
    $this->removeNodeFile($nid);
    $this->assertNoText('Only files with the following extensions are allowed: txt.');
    $this->assertText('Article ' . $node->getTitle() . ' has been updated.');
  }

}


text:
package org.hpp.terrain.libnoise.module;

import org.hpp.terrain.libnoise.Interp;
import org.hpp.terrain.libnoise.Misc;
import org.hpp.terrain.libnoise.exception.ExceptionInvalidParam;

public class Curve extends ModuleBase
{
   /// Noise module that maps the output value from a source module onto an
   /// arbitrary function curve.
   ///
   /// This noise module maps the output value from the source module onto an
   /// application-defined curve.  This curve is defined by a number of
   /// control TerrainPoints; each control TerrainPoint has an input value
   /// that maps to an output value.
   ///
   /// To add the control TerrainPoints to this curve, call the addControlTerrainPoint()
   /// method.  Note that the class ControlTerrainPoint follows the class Curve in
   /// this file.
   ///
   /// Since this curve is a cubic spline, an application must add a minimum
   /// of four control TerrainPoints to the curve.  If this is not done, the
   /// getValue() method fails.  Each control TerrainPoint can have any input and
   /// output value, although no two control TerrainPoints can have the same input
   /// value.  There is no limit to the number of control TerrainPoints that can be
   /// added to the curve.
   ///
   /// This noise module requires one source module

   int controlTerrainPointCount;
   ControlTerrainPoint[] controlTerrainPoints;

   public Curve (ModuleBase sourceModule) throws ExceptionInvalidParam
   {
      super(1);
      setSourceModule(0, sourceModule);
      controlTerrainPointCount = 0;
      controlTerrainPoints= new ControlTerrainPoint[1];
      controlTerrainPoints[0] = new ControlTerrainPoint(0.0, 0.0);
   }

   public void addControlTerrainPoint (double inputValue, double outputValue)
      throws ExceptionInvalidParam
   {
      // Find the insertion TerrainPoint for the new control TerrainPoint and insert the new
      // TerrainPoint at that position.  The control TerrainPoint array will remain sorted by
      // input value.
      int insertionPos = findInsertionPos(inputValue);
      insertAtPos (insertionPos, inputValue, outputValue);
   }

   public void clearAllControlTerrainPoints ()
   {
      controlTerrainPoints = null;
      controlTerrainPointCount = 0;
   }

   public int findInsertionPos (double inputValue) throws ExceptionInvalidParam
   {
      int insertionPos;
      for (insertionPos = 0; insertionPos < controlTerrainPointCount; insertionPos++)
      {
         if (inputValue < controlTerrainPoints[insertionPos].inputValue)
            // We found the array index in which to insert the new control TerrainPoint.
            // Exit now.
            break;
         else if (inputValue == controlTerrainPoints[insertionPos].inputValue)
            // Each control TerrainPoint is required to contain a unique input value, so
            // throw an exception.
            throw new ExceptionInvalidParam("Invalid Parameter in Curve");
      }
      return insertionPos;
   }

   public double getValue (double x, double y, double z)
   {
      assert (sourceModules[0] != null);
      assert (controlTerrainPointCount >= 4);

      // Get the output value from the source module.
      double sourceModuleValue = sourceModules[0].getValue (x, y, z);

      // Find the first element in the control TerrainPoint array that has an input value
      // larger than the output value from the source module.
      int indexPos;
      for (indexPos = 0; indexPos < controlTerrainPointCount; indexPos++)
      {
         if (sourceModuleValue < controlTerrainPoints[indexPos].inputValue)
            break;

      }

      // Find the four nearest control TerrainPoints so that we can perform cubic
      // interpolation.
      int index0 = Misc.ClampValue (indexPos - 2, 0, controlTerrainPointCount - 1);
      int index1 = Misc.ClampValue (indexPos - 1, 0, controlTerrainPointCount - 1);
      int index2 = Misc.ClampValue (indexPos    , 0, controlTerrainPointCount - 1);
      int index3 = Misc.ClampValue (indexPos + 1, 0, controlTerrainPointCount - 1);

      // If some control TerrainPoints are missing (which occurs if the value from the
      // source module is greater than the largest input value or less than the
      // smallest input value of the control TerrainPoint array), get the corresponding
      // output value of the nearest control TerrainPoint and exit now.
      if (index1 == index2) {
         return controlTerrainPoints[index1].outputValue;
      }

      // Compute the alpha value used for cubic interpolation.
      double input0 = controlTerrainPoints[index1].inputValue;
      double input1 = controlTerrainPoints[index2].inputValue;
      double alpha = (sourceModuleValue - input0) / (input1 - input0);

      // Now perform the cubic interpolation given the alpha value.
      return Interp.cubicInterp(
            controlTerrainPoints[index0].outputValue,
            controlTerrainPoints[index1].outputValue,
            controlTerrainPoints[index2].outputValue,
            controlTerrainPoints[index3].outputValue,
            alpha);
   }

   public void insertAtPos (int insertionPos, double inputValue,
         double outputValue)
   {
      // Make room for the new control TerrainPoint at the specified position within the
      // control TerrainPoint array.  The position is determined by the input value of
      // the control TerrainPoint; the control TerrainPoints must be sorted by input value
      // within that array.
      ControlTerrainPoint[] newControlTerrainPoints = new ControlTerrainPoint[controlTerrainPointCount + 1];

      for (int t = 0; t < (controlTerrainPointCount + 1); t++)
         newControlTerrainPoints[t] = new ControlTerrainPoint();

      for (int i = 0; i < controlTerrainPointCount; i++) {
         if (i < insertionPos) {
            newControlTerrainPoints[i] = controlTerrainPoints[i];
         } else {
            newControlTerrainPoints[i + 1] = controlTerrainPoints[i];
         }
      }

      controlTerrainPoints = newControlTerrainPoints;
      ++controlTerrainPointCount;

      // Now that we've made room for the new control TerrainPoint within the array, add
      // the new control TerrainPoint.
      controlTerrainPoints[insertionPos].inputValue  = inputValue;
      controlTerrainPoints[insertionPos].outputValue = outputValue;
   }
}

/// This class defines a control TerrainPoint.
///
/// Control TerrainPoints are used for defining splines.
class ControlTerrainPoint
{
   /// The input value.
   double inputValue;

   /// The output value that is mapped from the input value.
   double outputValue;

   ControlTerrainPoint()
   {
      inputValue = 0.0;
      outputValue = 0.0;
   }

   ControlTerrainPoint(double inputValue, double outputValue)
   {
      this.inputValue = inputValue;
      this.outputValue = outputValue;
   }

}


text:
/**
 * Types below are taken from utility-types package.
 * People who doesn't use TypeScript shouldn't be warned about missing `peerDependencies`.
 * This is the main reason why I didn't want to put utility-types into `peerDependencies`.
 * @source https://github.com/piotrwitek/utility-types
 */

/**
 * Assign
 * @desc From `U` assign properties to `T` (just like object assign)
 * @example
 *   type Props = { name: string; age: number; visible: boolean };
 *   type NewProps = { age: string; other: string };
 *
 *   // Expect: { name: string; age: number; visible: boolean; other: string; }
 *   type ExtendedProps = Assign<Props, NewProps>;
 */
export type Assign<
  T extends object,
  U extends object,
  I = Diff<T, U> & Intersection<U, T> & Diff<U, T>
> = Pick<I, keyof I>;

/**
 * Intersection
 * @desc From `T` pick properties that exist in `U`
 * @example
 *   type Props = { name: string; age: number; visible: boolean };
 *   type DefaultProps = { age: number };
 *
 *   // Expect: { age: number; }
 *   type DuplicateProps = Intersection<Props, DefaultProps>;
 */
export type Intersection<T extends object, U extends object> = Pick<
  T,
  Extract<keyof T, keyof U> & Extract<keyof U, keyof T>
>;

/**
 * Diff
 * @desc From `T` remove properties that exist in `U`
 * @example
 *   type Props = { name: string; age: number; visible: boolean };
 *   type DefaultProps = { age: number };
 *
 *   // Expect: { name: string; visible: boolean; }
 *   type DiffProps = Diff<Props, DefaultProps>;
 */
export type Diff<T extends object, U extends object> = Pick<
  T,
  SetDifference<keyof T, keyof U>
>;

/**
 * Subtract
 * @desc From `T` remove properties that exist in `T1` (`T1` is a subtype of `T`)
 * @example
 *   type Props = { name: string; age: number; visible: boolean };
 *   type DefaultProps = { age: number };
 *
 *   // Expect: { name: string; visible: boolean; }
 *   type RestProps = Subtract<Props, DefaultProps>;
 */
export type Subtract<T extends T1, T1 extends object> = Pick<
  T,
  SetComplement<keyof T, keyof T1>
>;

/**
 * SetDifference (same as Exclude)
 * @desc Set difference of given union types `A` and `B`
 * @example
 *   // Expect: "1"
 *   SetDifference<'1' | '2' | '3', '2' | '3' | '4'>;
 *
 *   // Expect: string | number
 *   SetDifference<string | number | (() => void), Function>;
 */
export type SetDifference<A, B> = A extends B ? never : A;

/**
 * SetComplement
 * @desc Set complement of given union types `A` and (it's subset) `A1`
 * @example
 *   // Expect: "1"
 *   SetComplement<'1' | '2' | '3', '2' | '3'>;
 */
export type SetComplement<A, A1 extends A> = SetDifference<A, A1>;


text:
package diagnostics

import (
	"fmt"
	"io"
	"os"
	"runtime/debug"

	"github.com/spf13/cobra"

	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	kutilerrors "k8s.io/kubernetes/pkg/util/errors"
	"k8s.io/kubernetes/pkg/util/sets"

	"github.com/openshift/origin/pkg/cmd/admin/diagnostics/options"
	"github.com/openshift/origin/pkg/cmd/admin/diagnostics/util"
	"github.com/openshift/origin/pkg/cmd/templates"
	"github.com/openshift/origin/pkg/diagnostics/log"
	poddiag "github.com/openshift/origin/pkg/diagnostics/pod"
	"github.com/openshift/origin/pkg/diagnostics/types"
)

// PodDiagnosticsOptions holds values received from environment variables
// for the command to operate.
type PodDiagnosticsOptions struct {
	// list of diagnostic names to limit what is run
	RequestedDiagnostics []string
	// LogOptions determine globally what the user wants to see and how.
	LogOptions *log.LoggerOptions
	// The Logger is built with the options and should be used for all diagnostic output.
	Logger *log.Logger
}

const (
	// Standard locations for the secrets mounted in pods
	StandardMasterCaPath = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"
	StandardTokenPath    = "/var/run/secrets/kubernetes.io/serviceaccount/token"
	StandardMasterUrl    = "https://kubernetes.default.svc.cluster.local"
)

var longPodDiagDescription = templates.LongDesc(`
	This utility is intended to run diagnostics inside a container and
	log the results so that the calling diagnostic can report them.`)

// NewCommandPodDiagnostics is the command for running pod diagnostics.
func NewCommandPodDiagnostics(name string, out io.Writer) *cobra.Command {
	o := &PodDiagnosticsOptions{
		RequestedDiagnostics: []string{},
		LogOptions:           &log.LoggerOptions{Out: out},
	}

	cmd := &cobra.Command{
		Use:   name,
		Short: "Within a pod, run pod diagnostics",
		Long:  fmt.Sprintf(longPodDiagDescription),
		Run: func(c *cobra.Command, args []string) {
			kcmdutil.CheckErr(o.Complete(args))

			failed, err, warnCount, errorCount := o.BuildAndRunDiagnostics()
			o.Logger.Summary(warnCount, errorCount)

			kcmdutil.CheckErr(err)
			if failed {
				os.Exit(255)
			}

		},
	}
	cmd.SetOutput(out) // for output re: usage / help

	options.BindLoggerOptionFlags(cmd.Flags(), o.LogOptions, options.RecommendedLoggerOptionFlags())

	return cmd
}

// Complete fills in PodDiagnosticsOptions needed if the command is actually invoked.
func (o *PodDiagnosticsOptions) Complete(args []string) error {
	var err error
	o.Logger, err = o.LogOptions.NewLogger()
	if err != nil {
		return err
	}

	o.RequestedDiagnostics = append(o.RequestedDiagnostics, args...)
	if len(o.RequestedDiagnostics) == 0 {
		o.RequestedDiagnostics = availablePodDiagnostics.List()
	}

	return nil
}

// BuildAndRunDiagnostics builds diagnostics based on the options and executes them, returning a summary.
func (o PodDiagnosticsOptions) BuildAndRunDiagnostics() (bool, error, int, int) {
	failed := false
	errors := []error{}
	diagnostics := []types.Diagnostic{}

	func() { // don't trust discovery/build of diagnostics; wrap panic nicely in case of developer error
		defer func() {
			if r := recover(); r != nil {
				failed = true
				stack := debug.Stack()
				errors = append(errors, fmt.Errorf("While building the diagnostics, a panic was encountered.\nThis is a bug in diagnostics. Error and stack trace follow: \n%v\n%s", r, stack))
			}
		}() // deferred panic handler
		podDiags, ok, err := o.buildPodDiagnostics()
		failed = failed || !ok
		if ok {
			diagnostics = append(diagnostics, podDiags...)
		}
		if err != nil {
			errors = append(errors, err...)
		}

	}()

	if failed {
		return failed, kutilerrors.NewAggregate(errors), 0, len(errors)
	}

	failed, err, numWarnings, numErrors := util.RunDiagnostics(o.Logger, diagnostics, 0, len(errors))
	return failed, err, numWarnings, numErrors
}

var (
	// availablePodDiagnostics contains the names of host diagnostics that can be executed
	// during a single run of diagnostics. Add more diagnostics to the list as they are defined.
	availablePodDiagnostics = sets.NewString(poddiag.PodCheckDnsName, poddiag.PodCheckAuthName)
)

// buildPodDiagnostics builds host Diagnostic objects based on the host environment.
// Returns the Diagnostics built, "ok" bool for whether to proceed or abort, and an error if any was encountered during the building of diagnostics.
func (o PodDiagnosticsOptions) buildPodDiagnostics() ([]types.Diagnostic, bool, []error) {
	diagnostics := []types.Diagnostic{}
	err, requestedDiagnostics := util.DetermineRequestedDiagnostics(availablePodDiagnostics.List(), o.RequestedDiagnostics, o.Logger)
	if err != nil {
		return diagnostics, false, []error{err} // don't waste time on discovery
	}
	// TODO: check we're actually in a container

	for _, diagnosticName := range requestedDiagnostics {
		switch diagnosticName {

		case poddiag.PodCheckDnsName:
			diagnostics = append(diagnostics, poddiag.PodCheckDns{})

		case poddiag.PodCheckAuthName:
			diagnostics = append(diagnostics, poddiag.PodCheckAuth{
				MasterCaPath: StandardMasterCaPath,
				TokenPath:    StandardTokenPath,
				MasterUrl:    StandardMasterUrl,
			})

		default:
			return diagnostics, false, []error{fmt.Errorf("unknown diagnostic: %v", diagnosticName)}
		}
	}

	return diagnostics, true, nil
}


text:
import os

from iktomi.forms import *
from iktomi.forms import widgets
from iktomi.ext.filefields import FileFieldSet, FileFieldSetConv, \
                                      TempUploadedFile

import cfg

class MyUploadedFile(TempUploadedFile):

    temp_path = os.path.join(cfg.MEDIA, 'temp')
    temp_url = '/media/temp/'

def check_terms(conv, value):
    if not value:
        raise convs.ValidationError('Please, accept the terms os service')
    return value

class FileForm(Form):

    fields = [
        Field('accept',
              label='I accept the terms of service',
              conv=convs.Bool(check_terms),
              widget=widgets.CheckBox()),
        FileFieldSet('file', label='File',
                     file_cls=MyUploadedFile,
                     conv=FileFieldSetConv(required=True),
                     widget=FileFieldSet.widget(template='fileinput.html')),
    ]

#class OptionalFileForm(Form):
#
#    fields = [
#        Field('accept', label='I accept the terms of service',
#              conv=convs.Bool(required=True),
#              widget=widgets.CheckBox()),
#        FileFieldSet('file', label='File',
#                     file_cls=MyUploadedFile,
#                     conv=FileFieldSetConv(required=False),
#                     template='fileinput.html'),
#    ]

class SimpleFileForm(Form):
    #template='forms/paragraph.html'

    fields = [
        FileField('file', label='File',
                  conv=convs.SimpleFile(),
                  widget=widgets.Widget(template='widgets/file.html')),
    ]


text:
Development has shifted to other, more abstract, project, see-- https://github.com/s-c-p/secure-notes

______________________________

# Command Line Diary-App

Tools to write a personal diary with peace of mind.

> Not secure, OpenSSL writes decrypted files to disk (when you are reading older entries) and not to memory. Although every file is securely over-written by garbage, some backup daemon running in background may compromise your life's details.

## Dependencies:

The following softwares should be installed and their paths known
- OpenSSL
- Git

PolarSSL and other VCS support coming soon.

Usage:

	> py diary.py -h

Don't copy.