text:
require 'digest'

module WebShield
  class Shield
    attr_reader :id, :shield_path, :path_matcher, :options, :config

    class << self
      def allowed_option_keys
        @allowed_option_keys ? @allowed_option_keys.dup : []
      end

      private

      def allow_option_keys(*keys)
        @allowed_option_keys = keys.map(&:to_sym)
      end
    end

    def initialize(id, shield_path, options, config)
      @id = id
      @shield_path = shield_path
      @path_matcher = build_path_matcher(shield_path)
      @options = hash_to_symbol_keys(options)
      @config = config

      check_options(@options)
    end

    # Returns: :pass, :block, [:response, rack_response], nil
    def filter(request)
      raise Error, "implement me"
    end

    def dictatorial?
      @options[:dictatorial]
    end

    def write_log(severity, msg)
      case svrt = severity.to_sym
      when :debug, :info, :warn, :error
        config.logger.send(svrt, "#{shield_name} #{msg}")
      else
        raise "Invalid log severity '#{svrt}'"
      end
    end

    def shield_name
      self.class.name.split('::', 2).last + "\##{id}"
    end

    private

    # Support symbols: :name, (), *
    def build_path_matcher(path)
      regexp_str = Regexp.escape(path)
      regexp_str.gsub!(/\\\((.+)\\\)/, '(\1)?')
      regexp_str.gsub!(/:[^\/\)]+(\)|\/)?/) {|str| "[^/]+#{$1 ? $1 : nil}" }
      regexp_str.gsub!(/\/$/, '/?')
      regexp_str.gsub!("\\*", '.*')
      Regexp.new("\\A#{regexp_str}\\z", 'i')
    end

    def hash_to_symbol_keys(hash)
      hash.each_with_object({}) do |kv, result|
        key, val = kv[0].to_sym, kv[1]
        result[key] = val
      end
    end

    def check_options(options)
      options.each do |key, val|
        unless self.class.allowed_option_keys.include?(key)
          raise Error, "Invalid shield option '#{key}'"
        end
      end
    end

    def generate_store_key(suffix)
     ['WS', "#{self.class.name.split('::').last}\##{id}", suffix.to_s].join(':')
    end
  end
end


text:
"""Creates an analysis VM and copies Azure disks to it for analysis."""

from typing import List, Optional

from libcloudforensics.providers.azure import forensics as az_forensics
from libcloudforensics.providers.azure.internal import account
from libcloudforensics.providers.azure.internal import compute

from dftimewolf.lib import module
from dftimewolf.lib.containers import containers
from dftimewolf.lib.modules import manager as modules_manager
from dftimewolf.lib.state import DFTimewolfState

class AzureCollector(module.BaseModule):
  """Microsoft Azure Collector.

  Attributes:
    remote_profile_name (str): The Azure account in which the disk(s)
        exist(s). This is the profile name that is defined in your credentials
        file.
    source_account (AZAccount): The AZAccount object that represents the
        source account in which the disk(s) exist(s).
    incident_id (str): Incident identifier used to name the analysis VM.
    remote_instance_name (str): Instance ID that needs forensicating.
    disk_names (list[str]): List of disk names to copy.
    all_disks (bool): True if all disk attached to the source
        instance should be copied.
    analysis_profile_name (str): The Azure account in which to create the
        analysis VM. This is the profile name that is defined in your
        credentials file.
    analysis_region (str): The Azure region in which to create the VM.
    analysis_resource_group_name (str): The Azure resource group name in
        which to create the VM.
    analysis_vm (AZVirtualMachine): Analysis VM to which the disk copy will be
        attached.
  """

  _ANALYSIS_VM_CONTAINER_ATTRIBUTE_NAME = 'Analysis VM'
  _ANALYSIS_VM_CONTAINER_ATTRIBUTE_TYPE = 'text'

  def __init__(self,
               state: DFTimewolfState,
               name: Optional[str]=None,
               critical: bool=False) -> None:
    """Initializes a Microsoft Azure collector.

    Args:
      state (DFTimewolfState): recipe state.
      name (Optional[str]): The module's runtime name.
      critical (Optional[bool]): True if the module is critical, which causes
          the entire recipe to fail if the module encounters an error.
    """
    super(AzureCollector, self).__init__(state, critical=critical)
    self.remote_profile_name = str()
    self.source_account = None  # type: account.AZAccount
    self.incident_id = str()
    self.remote_instance_name = str()  # type: Optional[str]
    self.disk_names = []  # type: List[str]
    self.all_disks = False
    self.analysis_profile_name = str()
    self.analysis_region = str()  # type: Optional[str]
    self.analysis_resource_group_name = str()
    self.analysis_vm = None  # type: compute.AZComputeVirtualMachine

  def Process(self) -> None:
    """Copies a disk to the analysis account."""
    for disk in self._FindDisksToCopy():
      self.logger.info('Disk copy of {0:s} started...'.format(disk.name))
      new_disk = az_forensics.CreateDiskCopy(
          self.analysis_resource_group_name,
          disk_name=disk.name,
          region=self.analysis_region,
          src_profile=self.remote_profile_name,
          dst_profile=self.analysis_profile_name
      )
      self.PublishMessage(
          f'Disk {disk.name} successfully copied to {new_disk.name}')
      self.analysis_vm.AttachDisk(new_disk)
      container = containers.ForensicsVM(
          name=self.analysis_vm.name,
          evidence_disk=new_disk,
          platform='azure')
      self.state.StoreContainer(container)

  # pylint: disable=arguments-differ,too-many-arguments
  def SetUp(self,
            remote_profile_name: str,
            analysis_resource_group_name: str,
            incident_id: str,
            ssh_public_key: str,
            remote_instance_name: Optional[str]=None,
            disk_names: Optional[str]=None,
            all_disks: bool=False,
            analysis_profile_name: Optional[str]=None,
            analysis_region: Optional[str]=None,
            boot_disk_size: int=50,
            cpu_cores: int=4,
            memory_in_mb: int=8192) -> None:
    """Sets up a Microsoft Azure collector.

    This method creates and starts an analysis VM in the analysis account and
    selects disks to copy from the remote account.

    If disk_names is specified, it will copy the corresponding disks from the
    account, ignoring disks belonging to any specific instances.

    If remote_instance_name is specified, two behaviors are possible:
    * If no other parameters are specified, it will select the instance's boot
      disk
    * if all_disks is set to True, it will select all disks in the account
      that are attached to the instance

    disk_names takes precedence over instance_names

    Args:
      remote_profile_name (str): The Azure account in which the disk(s)
          exist(s). This is the profile name that is defined in your credentials
          file.
      analysis_resource_group_name (str): The Azure resource group name in
          which to create the VM.
      incident_id (str): Incident identifier used to name the analysis VM.
      ssh_public_key (str): The public SSH key to attach to the instance.
      remote_instance_name (str): Instance ID that needs forensicating.
      disk_names (str): Comma-separated list of disk names to copy.
      all_disks (bool): True if all disk attached to the source
          instance should be copied.
      analysis_profile_name (str): The Azure account in which to create the
          analysis VM. This is the profile name that is defined in your
          credentials file.
      analysis_region (str): The Azure region in which to create the VM.
      boot_disk_size (int): Optional. The size (in GB) of the boot disk
          for the analysis VM. Default is 50 GB.
      cpu_cores (int): Optional. The number of CPU cores to use for the
          analysis VM. Default is 4.
      memory_in_mb (int): Optional. The amount of memory in mb to use for the
          analysis VM. Default is 8Gb.
    """
    if not (remote_instance_name or disk_names):
      self.ModuleError(
          'You need to specify at least an instance name or disks to copy',
          critical=True)
      return

    if not ssh_public_key:
      self.ModuleError('You need to specify a SSH public key to add to the '
                       'VM.', critical=True)
      return

    if not (remote_profile_name and analysis_resource_group_name):
      self.ModuleError('You must specify "remote_profile_name" and '
                       '"analysis_resource_group_name" parameters',
                       critical=True)
      return

    self.remote_profile_name = remote_profile_name
    self.analysis_resource_group_name = analysis_resource_group_name
    self.source_account = account.AZAccount(
        self.analysis_resource_group_name,
        profile_name=self.remote_profile_name)

    self.incident_id = incident_id
    self.remote_instance_name = remote_instance_name

    self.disk_names = disk_names.split(',') if disk_names else []
    self.all_disks = all_disks
    self.analysis_region = analysis_region
    self.analysis_profile_name = analysis_profile_name or remote_profile_name

    analysis_vm_name = 'azure-forensics-vm-{0:s}'.format(self.incident_id)
    print('Your analysis VM will be: {0:s}'.format(analysis_vm_name))
    self.state.StoreContainer(
        containers.TicketAttribute(
            name=self._ANALYSIS_VM_CONTAINER_ATTRIBUTE_NAME,
            type_=self._ANALYSIS_VM_CONTAINER_ATTRIBUTE_TYPE,
            value=analysis_vm_name))
    self.analysis_vm, _ = az_forensics.StartAnalysisVm(
        self.analysis_resource_group_name,
        analysis_vm_name,
        boot_disk_size,
        ssh_public_key=ssh_public_key,
        cpu_cores=cpu_cores,
        memory_in_mb=memory_in_mb,
        region=self.analysis_region,
        dst_profile=self.analysis_profile_name,
    )

  def _GetDisksFromNames(self,
                         disk_names: List[str]) -> List[compute.AZComputeDisk]:
    """Gets disks from an Azure account by disk name.

    Args:
      disk_names (list[str]): List of disk names to get from the account.

    Returns:
      list[AZDisk]: List of AZDisk objects to copy.
    """
    disks = []
    for name in disk_names:
      try:
        disks.append(self.source_account.compute.GetDisk(name))
      except RuntimeError:
        self.ModuleError(
            'Disk "{0:s}" was not found in subscription {1:s}'.format(
                name, self.source_account.subscription_id),
            critical=True)
        return []
    return disks

  def _GetDisksFromInstance(self,
                            instance_name: str,
                            all_disks: bool) -> List[compute.AZComputeDisk]:
    """Gets disks to copy based on an instance name.

    Args:
      instance_name (str): Name of the instance to get the disks from.
      all_disks (bool): If set, get all disks attached to the instance. If
          False, get only the instance's boot disk.

    Returns:
      list[AZDisk]: List of AZDisk objects to copy.
    """
    try:
      remote_instance = self.source_account.compute.GetInstance(instance_name)
    except RuntimeError as exception:
      self.ModuleError(str(exception), critical=True)
      return []

    if all_disks:
      return list(remote_instance.ListDisks().values())
    return [remote_instance.GetBootDisk()]

  def _FindDisksToCopy(self) -> List[compute.AZComputeDisk]:
    """Determines which disks to copy depending on object attributes.

    Returns:
      list[AZDisk]: the disks to copy to the
          analysis project.
    """
    if not (self.remote_instance_name or self.disk_names):
      self.ModuleError(
          'You need to specify at least an instance name or disks to copy',
          critical=True)

    disks_to_copy = []

    if self.disk_names:
      disks_to_copy = self._GetDisksFromNames(self.disk_names)

    elif self.remote_instance_name:
      disks_to_copy = self._GetDisksFromInstance(self.remote_instance_name,
                                                 self.all_disks)

    if not disks_to_copy:
      self.ModuleError('Could not find any disks to copy', critical=True)
      return []

    return disks_to_copy

modules_manager.ModulesManager.RegisterModule(AzureCollector)

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using UnityEditor;

public class HorizontalPaneState {
  public const int SPLITTER_WIDTH = 9;
  public int id = 0;
  public bool isDraggingSplitter = false,
              isPaneWidthChanged = false;
  public float leftPaneWidth        = -1,
               initialLeftPaneWidth = -1,
               lastAvailableWidth   = -1,
               availableWidth       = 0,
               minPaneWidthLeft     = 75,
               minPaneWidthRight    = 75;

  /*
  * Unity can, apparently, recycle state objects.  In that event we want to
  * wipe the slate clean and just start over to avoid wackiness.
  */
  protected virtual void Reset(int newId) {
    id                    = newId;
    isDraggingSplitter    = false;
    isPaneWidthChanged    = false;
    leftPaneWidth         = -1;
    initialLeftPaneWidth  = -1;
    lastAvailableWidth    = -1;
    availableWidth        = 0;
    minPaneWidthLeft      = 75;
    minPaneWidthRight     = 75;
  }

  /*
  * Some aspects of our state are really just static configuration that
  * shouldn't be modified by the control, so we blindly set them if we have a
  * prototype from which to do so.
  */
  protected virtual void InitFromPrototype(int newId, HorizontalPaneState prototype) {
    id                    = newId;
    initialLeftPaneWidth  = prototype.initialLeftPaneWidth;
    minPaneWidthLeft      = prototype.minPaneWidthLeft;
    minPaneWidthRight     = prototype.minPaneWidthRight;
  }

  /*
  * This method takes care of guarding against state object recycling, and
  * ensures we pick up what we need, when we need to, from the prototype state
  * object.
  */
  public void ResolveStateToCurrentContext(int currentId, HorizontalPaneState prototype) {
    if(id != currentId)
      Reset(currentId);
    else if(prototype != null)
      InitFromPrototype(currentId, prototype);
  }
}

public static class EditorGUILayoutHorizontalPanes {
  // TODO: This makes it impossible to nest pane sets!
  private static HorizontalPaneState hState;

  public static void Begin() { Begin(null); }

  public static void Begin(HorizontalPaneState prototype) {
    int id = GUIUtility.GetControlID(FocusType.Passive);
    hState = (HorizontalPaneState)GUIUtility.GetStateObject(typeof(HorizontalPaneState), id);
    hState.ResolveStateToCurrentContext(id, prototype);

    // *INDENT-OFF*
    Rect totalArea = EditorGUILayout.BeginHorizontal();
      hState.availableWidth = totalArea.width - HorizontalPaneState.SPLITTER_WIDTH;
      hState.isPaneWidthChanged = false;
      if(totalArea.width > 0) {
        if(hState.leftPaneWidth < 0) {
          if(hState.initialLeftPaneWidth < 0)
            hState.leftPaneWidth = hState.availableWidth * 0.5f;
          else
            hState.leftPaneWidth = hState.initialLeftPaneWidth;
          hState.isPaneWidthChanged = true;
        }
        if(hState.lastAvailableWidth < 0)
          hState.lastAvailableWidth = hState.availableWidth;
        if(hState.lastAvailableWidth != hState.availableWidth) {
          hState.leftPaneWidth = hState.availableWidth * (hState.leftPaneWidth / hState.lastAvailableWidth);
          hState.isPaneWidthChanged = true;
        }
        hState.lastAvailableWidth = hState.availableWidth;
      }

      GUILayout.BeginHorizontal(GUILayout.Width(hState.leftPaneWidth));
    // *INDENT-ON*
  }

  public static void Splitter() {
    GUILayout.EndHorizontal();

    float availableWidthForOnePanel = hState.availableWidth - (1 + hState.minPaneWidthRight);
    Rect drawableSplitterArea = GUILayoutUtility.GetRect(GUIHelper.NoContent, HorizontalPaneStyles.Splitter, GUILayout.Width(1f), GUIHelper.ExpandHeight);
    Rect splitterArea = new Rect(drawableSplitterArea.xMin - (int)(HorizontalPaneState.SPLITTER_WIDTH * 0.5f), drawableSplitterArea.yMin, HorizontalPaneState.SPLITTER_WIDTH, drawableSplitterArea.height);
    switch(Event.current.type) {
    case EventType.MouseDown:
      if(splitterArea.Contains(Event.current.mousePosition)) {
        hState.isDraggingSplitter = true;
        GUIUtility.hotControl     = hState.id;
        Event.current.Use();
      }
      break;
    case EventType.MouseDrag:
      if(hState.isDraggingSplitter && hState.id == GUIUtility.hotControl) {
        hState.leftPaneWidth     += Event.current.delta.x;
        hState.leftPaneWidth      = Mathf.Round(hState.leftPaneWidth);
        hState.isPaneWidthChanged = true;
        Event.current.Use();
      }
      break;
    case EventType.MouseUp:
      hState.isDraggingSplitter = false;
      if(hState.id == GUIUtility.hotControl) {
        GUIUtility.hotControl = 0;
        Event.current.Use();
      }
      break;
    }

    if(hState.isPaneWidthChanged) {
      if(hState.leftPaneWidth < hState.minPaneWidthLeft)
        hState.leftPaneWidth = hState.minPaneWidthLeft;
      if(hState.leftPaneWidth >= availableWidthForOnePanel)
        hState.leftPaneWidth = availableWidthForOnePanel;
      if(EditorWindow.focusedWindow != null)
        EditorWindow.focusedWindow.Repaint();
    }
    GUI.Label(drawableSplitterArea, GUIHelper.NoContent, HorizontalPaneStyles.Splitter);
    EditorGUIUtility.AddCursorRect(splitterArea, MouseCursor.ResizeHorizontal);
  }

  public static void End() { EditorGUILayout.EndHorizontal(); }
}

public static class HorizontalPaneStyles {
  private static Texture2D SplitterImage;

  static HorizontalPaneStyles() {
    // TODO: Change the image color based on chosen editor skin.
    SplitterImage = new Texture2D(1, 1, TextureFormat.ARGB32, false) {
      hideFlags   = HideFlags.HideAndDontSave,
      anisoLevel  = 0,
      filterMode  = FilterMode.Point,
      wrapMode    = TextureWrapMode.Clamp
    };
    SplitterImage.SetPixels(new Color[] { Color.gray });
    SplitterImage.Apply();
  }

  private static GUIStyle _Splitter = null;

  public static GUIStyle Splitter {
    get {
      if(_Splitter == null) {
        // *INDENT-OFF*
        _Splitter = new GUIStyle() {
          normal        = new GUIStyleState() { background = SplitterImage },
          imagePosition = ImagePosition.ImageOnly,
          wordWrap      = false,
          alignment     = TextAnchor.MiddleCenter,
        }
          .Named("HSplitter")
          .Size(1, 0, false, true)
          .ResetBoxModel()
          .Margin(3, 3, 0, 0)
          .ClipText();
        // *INDENT-ON*
      }
      return _Splitter;
    }
  }
}


text:
#include "CCPACSTransformation.h"
#include "tiglcommonfunctions.h"
#include "CTiglError.h"

namespace tigl
{

CCPACSTransformation::CCPACSTransformation(CCPACSEnginePosition* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSEnginePylon* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSFuselage* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSDuct* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSDuctAssembly* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSFuselageSectionElement* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSFuselageSection* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSExternalObject* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSGenericSystem* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSLandingGearBase* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSNacelleSection* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSRotor* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSRotorHinge* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSWing* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSWingSectionElement* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CCPACSWingSection* parent, CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation(parent, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{
}

CCPACSTransformation::CCPACSTransformation(CTiglUIDManager* uidMgr)
    : generated::CPACSTransformation((CCPACSWingSection*)nullptr, uidMgr)
    , _transformationMatrix(*this, &CCPACSTransformation::updateMatrix)
{}

void CCPACSTransformation::reset()
{
    if (m_scaling) {
        m_scaling->SetAsPoint(CTiglPoint(1, 1, 1));
    }
    if (m_rotation) {
        m_rotation->SetAsPoint(CTiglPoint(0, 0, 0));
    }
    if (m_translation) {
        m_translation->SetAsPoint(CTiglPoint(0, 0, 0));
        m_translation->SetRefType(boost::optional<ECPACSTranslationType>());
    }
}

CCPACSTransformation &CCPACSTransformation::operator =(const CCPACSTransformation &trafo)
{
    m_scaling = trafo.m_scaling;
    m_rotation = trafo.m_rotation;
    m_translation = trafo.m_translation;

    _transformationMatrix.clear();

    return *this;
}

void CCPACSTransformation::setTranslation(const CTiglPoint & translation)
{
    GetTranslation(CreateIfNotExists).SetAsPoint(translation);
}

void CCPACSTransformation::setTranslation(const CTiglPoint& translation, ECPACSTranslationType type)
{
    CCPACSPointAbsRel& t = GetTranslation(CreateIfNotExists);
    t.SetAsPoint(translation);
    t.SetRefType(type);
}

void CCPACSTransformation::setRotation(const CTiglPoint& rotation)
{
    if (!m_rotation) {
        m_rotation = boost::in_place(this, m_uidMgr);
    }
    m_rotation->SetAsPoint(rotation);
}

void CCPACSTransformation::setScaling(const CTiglPoint& scale)
{
    if (!m_scaling) {
        m_scaling = boost::in_place(this, m_uidMgr);
    }
    m_scaling->SetAsPoint(scale);
}

void CCPACSTransformation::setTransformationMatrix(const CTiglTransformation& matrix)
{
    // decompose matrix into scaling, rotation and translation
    double scale[3];
    double rotation[3];
    double translation[3];
    matrix.Decompose(&scale[0], &rotation[0], &translation[0]);

    if (!m_translation) {
        m_translation = boost::in_place(this, m_uidMgr);
    }
    m_translation->SetX(translation[0]);
    m_translation->SetY(translation[1]);
    m_translation->SetZ(translation[2]);

    if (!m_scaling) {
        m_scaling = boost::in_place(this, m_uidMgr);
    }
    m_scaling->SetX(scale[0]);
    m_scaling->SetY(scale[1]);
    m_scaling->SetZ(scale[2]);

    if (!m_rotation) {
        m_rotation = boost::in_place(this, m_uidMgr);
    }
    m_rotation->SetX(rotation[0]);
    m_rotation->SetY(rotation[1]);
    m_rotation->SetZ(rotation[2]);
    if (m_uidMgr) {
        Invalidate();
    }
}

void CCPACSTransformation::updateMatrix(CTiglTransformation& cache) const
{
    cache.SetIdentity();
    if (m_scaling) {
        const CTiglPoint& s = m_scaling->AsPoint();
        cache.AddScaling(s.x, s.y, s.z);
    }
    if (m_rotation) {
        const CTiglPoint& r = m_rotation->AsPoint();
        cache.AddRotationZ(r.z);
        cache.AddRotationY(r.y);
        cache.AddRotationX(r.x);
    }
    if (m_translation) {
        const CTiglPoint& t = m_translation->AsPoint();
        cache.AddTranslation(t.x, t.y, t.z);
    }
}

CTiglPoint CCPACSTransformation::getTranslationVector() const
{
    return m_translation ? m_translation->AsPoint() : CTiglPoint(0, 0, 0);
}

CTiglPoint CCPACSTransformation::getRotation() const
{
    return m_rotation ? m_rotation->AsPoint() : CTiglPoint(0, 0, 0);
}

CTiglPoint CCPACSTransformation::getScaling() const
{
    return m_scaling ? m_scaling->AsPoint() : CTiglPoint(1, 1, 1);
}

ECPACSTranslationType CCPACSTransformation::getTranslationType() const
{
    if (m_translation) {
        return m_translation->GetRefDefaultedType();
    }
    else {
        return CCPACSPointAbsRel::defaultTranslationType;
    }
}

CTiglTransformation CCPACSTransformation::getTransformationMatrix() const
{
    return *_transformationMatrix;
}

void CCPACSTransformation::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string& transformationXPath)
{
    generated::CPACSTransformation::ReadCPACS(tixiHandle, transformationXPath);
}

void CCPACSTransformation::InvalidateImpl(const boost::optional<std::string>& source) const
{
    _transformationMatrix.clear();
    // invalidate parent
    const CTiglUIDObject* parent = GetNextUIDParent();
    if (parent) {
        parent->Invalidate(GetUID());
    }
}

} // namespace tigl


text:
#include "Registry.h"
#include <WinReg.h>

namespace pGina
{
	namespace Registry
	{
		std::wstring GetString(const wchar_t * keyName, const wchar_t * defaultValue)
		{
			std::wstring result = GetString(HKEY_LOCAL_MACHINE, L"SOFTWARE\\pGina3", keyName);

			if( result.length() == 0 ) result = defaultValue;

			return result;
		}

		DWORD GetDword(const wchar_t * keyName, DWORD defaultValue)
		{
			DWORD result = defaultValue;
			DWORD tmpResult = defaultValue;
			HKEY hKey = NULL;

			if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"Software\\pGina3", 0, KEY_READ, &hKey) == ERROR_SUCCESS)
			{
				DWORD dataLength = sizeof(tmpResult);
				if(RegQueryValueEx(hKey, keyName, 0, NULL, (LPBYTE) &tmpResult, &dataLength) == ERROR_SUCCESS)
				{
					result = tmpResult;
				}
				RegCloseKey(hKey);
			}

			return result;
		}

		bool GetBool(const wchar_t * keyName, bool defaultValue)
		{
			std::wstring v = defaultValue ? L"True" : L"False";
			v = GetString(keyName, v.c_str());
			if(_wcsicmp(v.c_str(), L"True") == 0)
				return true;
			if(_wcsicmp(v.c_str(), L"False") == 0)
				return false;

			return defaultValue;
		}

		// Returns true if the value exists and is set to something other than L"0".
		// Note that a zero length string is treated as a non-existent value (returns false)
		// Assumes the type is REG_SZ
		bool StringValueExistsAndIsNonZero( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName )
		{
			std::wstring result = GetString(base, subKeyName, valueName);
			if( result.length() == 0 ) return false;  // empty implies that the value does not exist
			return wcscmp(L"0", result.c_str()) != 0;
		}

		// Returns empty (zero-length) string if the value does not exist (assumes REG_SZ)
		std::wstring GetString( HKEY base, const wchar_t * subKeyName, const wchar_t *valueName )
		{
			std::wstring result = L"";	// Do not assign NULL!
			HKEY hKey = NULL;

			if(RegOpenKeyEx(base, subKeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
			{
				DWORD dataLength = 0;
				if(RegQueryValueEx(hKey, valueName, 0, NULL, NULL, &dataLength) == ERROR_SUCCESS)
				{
					int bufferSize = dataLength + sizeof(wchar_t);
					wchar_t * buffer = (wchar_t *) malloc(bufferSize);
					memset(buffer, 0, bufferSize);

					if(RegQueryValueEx(hKey, valueName, 0, NULL, (LPBYTE) buffer, &dataLength) == ERROR_SUCCESS)
					{
						result = buffer;
					}

					free(buffer);
				}

				RegCloseKey(hKey);
			}

			return result;
		}

		std::vector<std::wstring> GetStringArray( const wchar_t *subKeyName )
		{
			return GetStringArray(HKEY_LOCAL_MACHINE, L"SOFTWARE\\pGina3", subKeyName);
		}

		std::vector<std::wstring> GetStringArray( HKEY base, const wchar_t *subKeyName, const wchar_t *valueName )
		{
			std::vector<std::wstring> result;
			HKEY hKey = NULL;

			if( RegOpenKeyEx(base, subKeyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
			{
				DWORD dataLength = 0;
				if(RegQueryValueEx(hKey, valueName, 0, NULL, NULL, &dataLength) == ERROR_SUCCESS)
				{
					int bufferSize = dataLength + 2*sizeof(wchar_t);
					int buffLength = bufferSize / sizeof(wchar_t);
					wchar_t * buffer = (wchar_t *) malloc(bufferSize);
					ZeroMemory(buffer, bufferSize);

					if(RegQueryValueEx(hKey, valueName, 0, NULL, (LPBYTE) buffer, &dataLength) == ERROR_SUCCESS)
					{
						std::wstring str;
						size_t index = 0;
						size_t len = wcsnlen(&buffer[index], buffLength);

						while(len > 0 && len < buffLength - index)
						{
							str = &buffer[index];
							result.push_back(str);
							index += len + 1;
							len = wcsnlen(&buffer[index], buffLength - index);
						}
					}
					free(buffer);
				}
				RegCloseKey(hKey);
			}
			return result;
		}
	}
}


text:
package com.orientechnologies.orient.core.record.impl;

import com.orientechnologies.orient.core.collate.OCollate;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.BytesContainer;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.OBinaryComparator;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.OBinaryField;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ODocumentSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary;
import org.junit.Assert;

public abstract class AbstractComparatorTest {

  protected ODocumentSerializer serializer =
      ORecordSerializerBinary.INSTANCE.getCurrentSerializer();
  protected OBinaryComparator comparator = serializer.getComparator();

  protected void testEquals(OType sourceType) {
    OType[] numberTypes =
        new OType[] {OType.BYTE, OType.DOUBLE, OType.FLOAT, OType.SHORT, OType.INTEGER, OType.LONG};

    for (OType t : numberTypes) {
      testEquals(t, sourceType);
    }

    for (OType t : numberTypes) {
      testEquals(sourceType, t);
    }
  }

  protected void testEquals(OType sourceType, OType destType) {
    try {
      Assert.assertTrue(comparator.isEqual(field(sourceType, 10), field(destType, 10)));
      Assert.assertFalse(comparator.isEqual(field(sourceType, 10), field(destType, 9)));
      Assert.assertFalse(comparator.isEqual(field(sourceType, 10), field(destType, 11)));
    } catch (AssertionError e) {
      System.out.println("ERROR: testEquals(" + sourceType + "," + destType + ")");
      throw e;
    }
  }

  protected OBinaryField field(final OType type, final Object value) {
    return field(type, value, null);
  }

  protected OBinaryField field(final OType type, final Object value, OCollate collate) {
    BytesContainer bytes = new BytesContainer();
    bytes.offset = serializer.serializeValue(bytes, value, type, null, null, null);
    return new OBinaryField(null, type, bytes, collate);
  }
}


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1">
                Toggle navigation
            </button>
            Sails Angular

                      {{navItem.title}}

 About

 Sign in

 Register

                    User Name

 Profile

 Settings

 Logout


text:
/* 按钮 */
a.btn {
    display: inline-block; *display: inline; *zoom: 1;
	padding: .2em 1em;
	margin:0 .2em;
    line-height: 2em;
	color: #333;
    font-weight: bold;
    text-shadow: 0 1px #fff;
	background-image: -webkit-linear-gradient(top, #fff, #ccc); /* Chrome 10+, Saf5.1+ */
	background-image:    -moz-linear-gradient(top, #fff, #ccc); /* FF3.6 */
	background-image:     -ms-linear-gradient(top, #fff, #ccc); /* IE10+ */
	background-image:      -o-linear-gradient(top, #fff, #ccc); /* Opera 11.10+ */
	background-image:         linear-gradient(top, #fff, #ccc);
	          filter: progid:DXImageTransform.Microsoft.Gradient(startColorstr='#ffffff', endColorstr='#cccccc',GradientType=0); /* IE6–IE9 */
	border: 1px solid;
	border-color: #ccc #aaa #aaa #ccc;
	-moz-border-radius: 3px;
	border-radius: 3px;
}
a.btn:hover{
	color: #000;
	text-decoration: none;
	background-image: -webkit-linear-gradient(top, #fff, #bbb); /* Chrome 10+, Saf5.1+ */
	background-image:    -moz-linear-gradient(top, #fff, #bbb); /* FF3.6+ */
	background-image:     -ms-linear-gradient(top, #fff, #bbb); /* IE10+ */
	background-image:      -o-linear-gradient(top, #fff, #bbb); /* Opera 11.10+ */
	background-image:         linear-gradient(top, #fff, #bbb);
	          filter: progid:DXImageTransform.Microsoft.Gradient(startColorstr='#ffffff', endColorstr='#bbbbbb',GradientType=0); /* IE6–IE9 */
	border-color: #aaa #888 #888 #aaa;
}
a.btn:active {
	background-image: -webkit-linear-gradient(top, #bbb, #fff); /* Chrome 10+, Saf5.1+ */
	background-image:    -moz-linear-gradient(top, #bbb, #fff); /* FF3.6 */
	background-image:     -ms-linear-gradient(top, #bbb, #fff); /* IE10 */
	background-image:      -o-linear-gradient(top, #bbb, #fff); /* Opera 11.10+ */
	background-image:         linear-gradient(top, #bbb, #fff);
	          filter: progid:DXImageTransform.Microsoft.Gradient(startColorstr='#bbbbbb', endColorstr='#ffffff',GradientType=0); /* IE6–IE9 */
	border-color: #888 #aaa #aaa #888;
}

input[type='text'],
input[type='tel'],
input[type='url'],
input[type='email'],
input[type='password'],
input[type='number'],
input[type^='date'],
input[type='month'],
input[type='week'],
input[type='time'],
textarea {
	padding: .2em;
	height:18px;
	line-height:18px;
	color: #555;
	border: 1px solid #BDBDBD;
	-moz-border-radius: 3px;
	border-radius: 3px;
}

input[type='text']:focus,
input[type='tel']:focus,
input[type='url']:focus,
input[type='email']:focus,
input[type='password']:focus,
input[type='number']:focus,
input[type^='date']:focus,
input[type='month']:focus,
input[type='week']:focus,
input[type='time']:focus,
a.btn:focus,
textarea:focus {
	border-color: #54A1CB;
	color: #000;
	outline:0 none;
	-moz-box-shadow: 0 0 4px rgba(84,161,203,.5);
	box-shadow: 0 0 4px rgba(84,161,203,.5);
	-webkit-transition:box-shadow .2s linear 0s;
	-moz-transition:box-shadow .3s linear 0s;
	-ms-transition:box-shadow .3s linear 0s;
	-o-transition:box-shadow .3s linear 0s;
	transition:box-shadow .3s linear 0s;
}

input[disabled],
select[disabled],
textarea[disabled],
input[readonly],
select[readonly],
textarea[readonly] {
  background-color: #f5f5f5;
  border-color: #ddd;
}

textarea {height:6em}
input.text {height:18px;}
.text {padding:.2em; line-height:18px; outline:0; color: #555; border: 1px solid #BDBDBD;}
input.focus,textarea.focus {padding:.2em; border: 1px solid #54A1CB; color: #000;}

:-moz-placeholder {color:#A9A9A9;}
input.placeholder {color:#A9A9A9;}


text:
<?php

/**
 * opCommunityTopicPluginTopicCommentActions
 *
 * @package    OpenPNE
 * @subpackage communityTopic
 * @author     Kousuke Ebihara <ebihara@tejimaya.com>
 * @author     Rimpei Ogawa <ogawa@tejimaya.com>
 * @author     Shogo Kawahara <kawahara@tejimaya.net>
 * @author     tunn <tunn@tejimaya.com>
 */
abstract class opCommunityTopicPluginTopicCommentActions extends sfActions
{
  /**
   * preExecute
   */
  public function preExecute()
  {
    $object = $this->getRoute()->getObject();

    if ($object instanceof CommunityTopic)
    {
      $this->communityTopic = $object;
      $this->community = $this->communityTopic->getCommunity();
    }
    elseif ($object instanceof CommunityTopicComment)
    {
      $this->communityTopicComment = $object;
      $this->communityTopic = $this->communityTopicComment->getCommunityTopic();
      $this->community = $this->communityTopic->getCommunity();
    }
  }

  /**
   * Executes create action
   *
   * @param sfRequest $request A request object
   */
  public function executeCreate($request)
  {
    $this->forward404Unless($this->communityTopic->isCreatableCommunityTopicComment($this->getUser()->getMemberId()));

    $this->form = new CommunityTopicCommentForm();
    $this->form->getObject()->setMemberId($this->getUser()->getMemberId());
    $this->form->getObject()->setCommunityTopic($this->communityTopic);
    $this->form->bind($request->getParameter($this->form->getName()), $request->getFiles($this->form->getName()));

    if ($this->form->isValid())
    {
      $this->form->save();
      $this->redirect('@communityTopic_show?id='.$this->communityTopic->getId());
    }

    $this->setTemplate('../../communityTopic/templates/show');

    return sfView::SUCCESS;
  }

  /**
   * Executes delete confirm action
   *
   * @param sfRequest $request A redirect object
   */
  public function executeDeleteConfirm($request)
  {
    $this->forward404Unless($this->communityTopicComment->isDeletable($this->getUser()->getMemberId()));

    $this->form = new sfForm();

    return sfView::SUCCESS;
  }

  /**
   * Executes delete action
   *
   * @param sfRequest $request A redirect object
   */
  public function executeDelete($request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($this->communityTopicComment->isDeletable($this->getUser()->getMemberId()));

    $this->communityTopicComment->delete();

    $this->getUser()->setFlash('notice', 'The comment was deleted successfully.');

    $this->redirect('@communityTopic_show?id='.$this->communityTopic->getId());
  }
}


text:
<?php
/*
 * proto float cos(float number)
 * Function is implemented in ext/standard/math.c
*/

$arg_0 = 1.0;
$extra_arg = 1;

echo "\nToo many arguments\n";
var_dump(cos($arg_0, $extra_arg));

echo "\nToo few arguments\n";
var_dump(cos());

?>


text:
layout: page
title: Light Cloud Air Seminar
date: 2016-05-24
author: Stephanie Gilbert
tags: weekly links, java
status: published
summary: Pellentesque massa risus, tristique at diam.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 11/26/2019
  endDate: 11/29/2019
  ctyhocn: BDTNJHX
  groupCode: LCAS
published: true
---
Nam condimentum lorem sed arcu malesuada rhoncus. Phasellus viverra ipsum ut metus lacinia, eget ullamcorper erat dapibus. Quisque interdum lacus a laoreet efficitur. Integer a varius magna. In tempor, nulla sit amet rutrum pharetra, neque nunc scelerisque magna, quis sodales diam felis at felis. Integer suscipit sapien ut quam laoreet ornare. Suspendisse commodo ullamcorper neque, id blandit justo condimentum sed. Mauris quam massa, consectetur quis sagittis et, cursus sit amet magna. Etiam eget neque at nisi pulvinar ullamcorper quis luctus felis. Phasellus non vestibulum ipsum, et sollicitudin nisl. Vivamus volutpat facilisis metus. Maecenas mattis fermentum nisl suscipit convallis. Donec vitae mauris ligula. Mauris nunc ipsum, malesuada in nisi sed, aliquet volutpat augue.

* Integer rhoncus leo eget massa molestie pretium.

Mauris varius fermentum mi vitae dictum. Maecenas ultricies finibus enim, nec hendrerit urna consequat in. Nulla at viverra ante. Sed metus lorem, pretium sed dictum vitae, pretium id erat. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In tempus commodo justo ut cursus. Cras porttitor ipsum vitae orci elementum, eget imperdiet urna dignissim. Nunc congue, felis sed tristique elementum, nibh diam euismod ex, at facilisis eros odio a elit. Donec nec ligula vitae velit hendrerit dictum id ac elit. Duis eu nisl eu justo eleifend egestas. Sed magna elit, laoreet at nibh ac, elementum tincidunt est.


text:
namespace Khnumdev.TwitBot.Data.DWH.Repositories
{
    using Model.Dimensions;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Threading.Tasks;
    using System;

    public class DWHRepository : IDWHRepository
    {

        public async Task<int> AddAsync<T>(T entity)
            where T : class, IDimension
        {
            int result = 0;
            using (var context = new DWHContext())
            {
                context.Set<T>().Add(entity);
                await context.SaveChangesAsync();
                result = entity.Id;

                return result;
            }
        }

        public async Task AddFactAsync<T>(T entity) where T : class
        {
            using (var context = new DWHContext())
            {
                context.Set<T>().Add(entity);
                await context.SaveChangesAsync();
            }
        }

        async Task<int> Save<T>(DWHContext context, T existingEntity, T entity)
            where T : class, IDimension
        {
            int result = 0;

            if (existingEntity == null)
            {
                context.Set<T>().Add(entity);
                await context.SaveChangesAsync();
                result = entity.Id;
            }
            else
            {
                result = existingEntity.Id;
            }

            return result;
        }

        public async Task UpsertAsync(List<Channel> entities)
        {
            var distinctEntities = entities
                .Select(i => i.Name)
                .Distinct()
                .Select(i => new Channel { Name = i });

            var allEntities = await GetAllAsync<Channel>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Name == i.Name));

            using (var context = new DWHContext())
            {
                context.Set<Channel>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<ConversationTrack> entities)
        {
            var distinctEntities = entities
               .Select(i => i.ConversationId)
               .Distinct()
               .Select(i => new ConversationTrack { ConversationId = i });

            var allEntities = await GetAllAsync<ConversationTrack>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.ConversationId == i.ConversationId));

            using (var context = new DWHContext())
            {
                context.Set<ConversationTrack>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<Language> entities)
        {
            var distinctEntities = entities
               .Select(i => i.Name)
               .Distinct()
               .Select(i => new Language { Name = i });

            var allEntities = await GetAllAsync<Language>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Name == i.Name));

            using (var context = new DWHContext())
            {
                context.Set<Language>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<MessageSource> entities)
        {
            var distinctEntities = entities
               .Select(i => i.Source)
               .Distinct()
               .Select(i => new MessageSource { Source = i });

            var allEntities = await GetAllAsync<MessageSource>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Source == i.Source));

            using (var context = new DWHContext())
            {
                context.Set<MessageSource>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<MessageType> entities)
        {
            var distinctEntities = entities
                .Select(i => i.Name)
                .Distinct()
                .Select(i => new MessageType { Name = i });

            var allEntities = await GetAllAsync<MessageType>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Name == i.Name));

            using (var context = new DWHContext())
            {
                context.Set<MessageType>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<User> entities)
        {
            var distinctEntities = entities
               .Select(i => new { i.UserId, i.Name })
               .Distinct()
               .Select(i => new User { UserId = i.UserId , Name = i.Name });

            var allEntities = await GetAllAsync<User>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.UserId == i.UserId));

            using (var context = new DWHContext())
            {
                context.Set<User>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<SingleWord> entities)
        {
            var distinctEntities = entities
               .Select(i => i.Text)
               .Distinct()
               .Select(i => new SingleWord { Text = i });

            var allEntities = await GetAllAsync<SingleWord>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Text == i.Text));

            using (var context = new DWHContext())
            {
                context.Set<SingleWord>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<TrendingTopic> entities)
        {
            var distinctEntities = entities
               .Select(i => new { i.Name, i.IsPromoted })
               .Distinct()
               .Select(i => new TrendingTopic { Name = i.Name, IsPromoted = i.IsPromoted });

            var allEntities = await GetAllAsync<TrendingTopic>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Name == i.Name ));

            using (var context = new DWHContext())
            {
                context.Set<TrendingTopic>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task UpsertAsync(List<Geography> entities)
        {
            var distinctEntities = entities
               .Select(i => i.Name)
               .Distinct()
               .Select(i => new Geography { Name = i });

            var allEntities = await GetAllAsync<Geography>();

            var newEntities = distinctEntities
                .Where(i => !allEntities.Any(j => j.Name == i.Name));

            using (var context = new DWHContext())
            {
                context.Set<Geography>().AddRange(newEntities);
                await context.SaveChangesAsync();
            }
        }

        public async Task<List<T>> GetAllAsync<T>()
            where T : class, IDimension
        {
            using (var context = new DWHContext())
            {
                return await context
                    .Set<T>()
                    .ToListAsync();
            };
        }
    }
}


text:
class AsyncChainTask : public QObject, public BaseTask
{
    Q_OBJECT

public:
    AsyncChainTask(ApplicationContext* appContext);

    virtual void Run() = 0;
    virtual int GetSubtasksCount() const;

    //this signal is used only by AsyncChainTaskProcessor
    //later AsyncChainProcessor and AsyncChainTask must be replaced by std::function
    //it must be done when launcher will be able to start multiple tasks at once
signals:
    void Finished() const;

    void ChildStarted(const BaseTask* task);
    void ChildProgress(const BaseTask* task, quint32 progress);
    void ChildFinished(const BaseTask* task);

protected:
    //this receiver resend data to users
    Receiver transparentReceiver;

private:
    eTaskType GetTaskType() const override;
};


text:
package com.example.test4txmap;

import android.app.Application;
import android.content.Context;

/**
 * Class description
 *
 * @author houshengyong
 * @since 2015-5-27
 */

public class EsApp extends Application {

    public static Context sAppContext;

    /*
     * (non-Javadoc)
     *
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate() {
        super.onCreate();
        sAppContext = this;
    }

}


text:
package es.rocasan.vigojug.reto201710;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Unit Test for Jug Class
 * @author Santiago Rodríguez
 */
public class JugTest {

    @Test
    public void createJugWithPositiveCapacityTest() {
		Jug jug = new Jug(2);
		assertEquals(jug.getCapacity(), new Integer(2));
    }

	@Test (expected = IllegalArgumentException.class)
    public void createJugWithNoCapacityShouldThrowExceptionTest() {
		Jug jug = new Jug(0);
    }

	@Test (expected = IllegalArgumentException.class)
    public void createJugWithNegativeCapacityShouldThrowExceptionTest() {
		Jug jug = new Jug(-2);
    }

	@Test (expected = IllegalArgumentException.class)
    public void createJugWithInitalNegativeAmountShouldThrowExceptionTest() {
		Jug jug = new Jug(5,-1);
    }

	@Test (expected = IllegalArgumentException.class)
    public void createJugWithInitalAmountGreaterThanCapacityShouldThrowExceptionTest() {
		Jug jug = new Jug(5,10);
    }

	@Test
    public void createJugWithInitalAmountBetweenZeroAndCapacityTest() {
		Jug jug1 = new Jug(5,0);
		Jug jug2 = new Jug(5,5);
		Jug jug3 = new Jug(5,3);
		assertEquals(jug1.getAmount(), new Integer(0));
		assertEquals(jug2.getAmount(), new Integer(5));
		assertEquals(jug2.getAmount(), jug2.getCapacity());
		assertEquals(jug3.getAmount(), new Integer(3));
    }

}


text:
class ISocket : public QObject {
    Q_OBJECT
public:
    enum CloseCode {
        CloseCodeNormal
    };
    ~ISocket() = default;

public slots:
    virtual void open(const QUrl & url) =0;
    virtual void close(ISocket::CloseCode closeCode = ISocket::CloseCodeNormal, const QString & reason = QString()) = 0;

    virtual void sendBinaryMessage(QByteArray message) = 0;
    virtual QAbstractSocket::SocketState state() const = 0;
signals:
    void stateChanged(QAbstractSocket::SocketState);
    void opened();
    void closed();
    void error(QAbstractSocket::SocketError error);

    void binaryMessageReceived(QByteArray bm);
};


text:
"""
Deployment for SUMO in production.

Requires commander (https://github.com/oremj/commander) which is installed on
the systems that need it.
"""

import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from commander.deploy import task, hostgroups  # noqa
import commander_settings as settings  # noqa

# Setup virtualenv path.
venv_bin_path = os.path.join(settings.SRC_DIR, 'virtualenv', 'bin')
os.environ['PATH'] = venv_bin_path + os.pathsep + os.environ['PATH']
os.environ['DJANGO_SETTINGS_MODULE'] = 'kitsune.settings_local'

@task
def update_code(ctx, tag):
    with ctx.lcd(settings.SRC_DIR):
        ctx.local("git fetch")
        ctx.local("git checkout -f %s" % tag)
        ctx.local("find -name '*.pyc' -delete")

@task
def update_locales(ctx):
    with ctx.lcd(os.path.join(settings.SRC_DIR, 'locale')):
        ctx.local("svn up")

    # Run the script that lints the .po files and compiles to .mo the
    # the ones that don't have egregious errors in them. This prints
    # stdout to the deploy log and also to media/postatus.txt so
    # others can see what happened.
    with ctx.lcd(settings.SRC_DIR):
        ctx.local('date > media/postatus.txt')
        ctx.local('./scripts/compile-linted-mo.sh | /usr/bin/tee -a media/postatus.txt')
        ctx.local('python2.7 manage.py compilejsi18n')

@task
def update_assets(ctx):
    with ctx.lcd(settings.SRC_DIR):
        ctx.local("git clean -fxd -- static")
        ctx.local("python2.7 manage.py nunjucks_precompile")
        ctx.local("./node_modules/.bin/bower install --allow-root")
        ctx.local("python2.7 manage.py collectstatic --noinput")

@task
def db_migrations(ctx):
    with ctx.lcd(settings.SRC_DIR):
        ctx.local('python2.7 manage.py migrate --noinput')

@task
def install_cron(ctx):
    with ctx.lcd(settings.SRC_DIR):
        ctx.local("python2.7 ./scripts/crontab/gen-crons.py -k %s -u apache > /etc/cron.d/.%s" %
                  (settings.WWW_DIR, settings.CRON_NAME))
        ctx.local("mv /etc/cron.d/.%s /etc/cron.d/%s" % (settings.CRON_NAME, settings.CRON_NAME))

@task
def checkin_changes(ctx):
    # Touching the wsgi file forces the app to reload.
    with ctx.lcd(settings.SRC_DIR):
        ctx.local('touch wsgi/kitsune.wsgi')

    ctx.local(settings.DEPLOY_SCRIPT)

@hostgroups(settings.WEB_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def deploy_app(ctx):
    ctx.remote(settings.REMOTE_UPDATE_SCRIPT)

    # Instead of restarting apache, we just touch the wsgi file in `checkin_changes()`
    # ctx.remote('service httpd graceful')

@hostgroups(settings.CELERY_HOSTGROUP, remote_kwargs={'ssh_key': settings.SSH_KEY})
def update_celery(ctx):
    ctx.remote(settings.REMOTE_UPDATE_SCRIPT)
    ctx.remote('/sbin/service %s restart' % settings.CELERY_SERVICE)

@task
def update_info(ctx):
    with ctx.lcd(settings.SRC_DIR):
        ctx.local("date")
        ctx.local("git branch")
        ctx.local("git log -3")
        ctx.local("git status")
        ctx.local("git submodule status")
        ctx.local("python2.7 manage.py migrate --list")
        with ctx.lcd("locale"):
            ctx.local("svn info")
            ctx.local("svn status")

        ctx.local("git rev-parse HEAD > media/revision.txt")

@task
def setup_dependencies(ctx):
    with ctx.lcd(settings.SRC_DIR):
        # Creating a virtualenv tries to open virtualenv/bin/python for
        # writing, but because virtualenv is using it, it fails.
        # So we delete it and let virtualenv create a new one.
        ctx.local('rm -f virtualenv/bin/python virtualenv/bin/python2.7')
        ctx.local('virtualenv-2.7 --no-site-packages virtualenv')

        # Activate virtualenv to append to the correct path to $PATH.
        activate_env = os.path.join(settings.SRC_DIR, 'virtualenv', 'bin', 'activate_this.py')
        execfile(activate_env, dict(__file__=activate_env))

        ctx.local('pip --version')
        ctx.local('./peep.sh install -r requirements/default.txt')
        # Make the virtualenv relocatable
        ctx.local('virtualenv-2.7 --relocatable virtualenv')

        # Fix lib64 symlink to be relative instead of absolute.
        ctx.local('rm -f virtualenv/lib64')
        with ctx.lcd('virtualenv'):
            ctx.local('ln -s lib lib64')

        # Install Node dependencies
        ctx.local('npm install --production --unsafe-perm')

@task
def pre_update(ctx, ref=settings.UPDATE_REF):
    update_code(ref)
    setup_dependencies()
    update_info()

@task
def update(ctx):
    update_assets()
    update_locales()
    db_migrations()

@task
def deploy(ctx):
    install_cron()
    checkin_changes()
    deploy_app()
    update_celery()

@task
def update_sumo(ctx, tag):
    """Do typical sumo update"""
    pre_update(tag)
    update()


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//Tigris//DTD XHTML 1.0 Transitional//EN"
"http://style.tigris.org/tigris_transitional.dtd">

<link rel="stylesheet" type="text/css" href="css/print.css" media="print" />
 <title>OOTP Fantasy Leagues: Release Notes</title>

OOTP Fantasy Leagues: Release Notes

Product Release Information

   Product:
   OOTP Fantasy Leagues

   Release Number:

     1.0.1

   Release Date:

     Monday February 13, 2012

   Support:
   For more information or support, please visit the
      OOTP Fantasy League Support Forum

Introduction

This document contains the release notes for OOTP Fantasy Leagues 1.0.1.  The following sections describe the release in detail and
 provide late-breaking or other information that supplements the
 main documentation.

This is the final 1.0 production release. Users of previous versions of the mod are encouraged to upgrade their installation with the provided upgrade script.

Please see below for a list of bug fixes and enhancements found in this release. Your feedback is appreciated either through the official online forum, our online contact form or by filing a bug in the public bug submission tool..

What's New?

 Enhancements

Added ability to uninstall fantasy database tables

Added OOTP Version field to install and options

Bug Fixes

Fixed bug where player state/territory of birth was resolving incorrectly for OOTP 12 games

Installation and Upgrade Notes

Upgrading

You may upgrade from version 1.0 Final usnig the provided upgrade script. To upgrade:.

Browse to http://[yoursiteURL.com]/[fantasy directory]/install/upgrade.php

Click the Upgrade Now button

Login and continue to use your league.

Manifest

This release consists of the following items:

Source code

Administrators Guide PDF

Commissioner'e Guide PDF

Release notes (this file)

Minimum System Requirements

Web Server:	 LAMP (Linux/Apache/PHP/MySQL) recommended

Server Disk Space:	 500mb (1.5GB recommended)

PHP:	Version 4.32 minimum, 5.2.6 Recommended

MySQL:	Version 5.0 minimum

PHP Memory:	16MB minimum, 64MB Recommended

MySQL Memeory:	8MB minimum, 32MB Recommended

    Software:

Out of the Park Baseball

Version 10 or up (12 recommended)

Version Compatibility

This release is backwards compatible with version 1.0 Final only. Users of any previous versions must upgrade to version 1.0 or
 or use the full installation version.

Aeolian Digital Studios

 Copyright © 2010-12 Jeff Fox, Aeolian Digital Studios.  All rights reserved.


text:
namespace solar {

	class win32_directory_change_watcher : public directory_change_watcher {
	private:
		using watchers_type = std::vector<std::unique_ptr<win32_single_directory_change_watcher>>;

	private:
		watchers_type _watchers;

	public:
		win32_directory_change_watcher();
		virtual ~win32_directory_change_watcher();

		virtual void begin_watching_directory(const std::string& dir_path, bool is_recursive) override;
		virtual void end_watching_directory(const std::string& dir_path) override;
		virtual bool try_pop_directory_change(directory_change& change) override;
	};

}


text:
package cn.ly.client;

import cn.ly.pojo.Efile;
import cn.ly.pojo.Fwqpz;
import cn.ly.services.i.EfileService;
import com.caucho.hessian.client.HessianProxyFactory;

import java.net.MalformedURLException;
import java.util.Map;
import java.util.Set;

/**
 * Created by luyuwww on 2015-08-19.
 */
public class CallHessianServlet {
    //调用hessian自己的servlet的方法
    public static void main(String[] args) {
        String url="http://localhost/SpringmvcHessian/hs/efService.hs";
        HessianProxyFactory factory=new HessianProxyFactory();
        factory.setOverloadEnabled(true);
        try {
            Fwqpz fwpz = new Fwqpz();
            fwpz.setPort(591);
            fwpz.setDataPath("c:/temp/sdfs/sdw/斯蒂芬莫");
            EfileService remote =(EfileService) factory.create(EfileService.class, url);
            Efile efile = remote.getEfile("this is test call" , fwpz);
            System.out.println(efile.getFileName());
            Map<String, Fwqpz> map = efile.getFwqpzMap();
            Set<String> set = map.keySet();
            for (String key : set) {
                System.out.println(map.get(key).getDataPath());
            }
            System.out.println(efile.getMd5());
//            System.out.println(say.getStudent("luyu", "你比的大学"));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}


text:
===========
Wraptor
===========

.. image:: https://github.com/carlsverre/wraptor/raw/master/docs/images/raptor.jpg

Testing
=======

.. image:: https://travis-ci.org/carlsverre/wraptor.png
    :target: https://travis-ci.org/carlsverre/wraptor

Run tests by executing :code:`make test`.

Decorators
==========

Memoize
-------
Add a cache to a function such that multiple calls with the same args
will return cached results.  Supports an optional cache timeout which
will flush items from the cache after a set interval for
recomputation.

.. code:: python

    from wraptor.decorators import memoize

    @memoize()
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(3, 4)
    # prints (3, 4)
    foo(1, 2)
    # no-op

Supports timeouts!

.. code:: python

    @memoize(timeout=.5)
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(1, 2)
    # no-op

    import time
    time.sleep(2)

    foo(1, 2)
    # prints (1, 2)

Supports attaching to an instance method!

.. code:: python

    class foo(object):
        @memoize(instance_method=True)
        def bar(self, a, b):
            return random()

    f = foo()
    f2 = foo()

    # they don't share a cache!
    f.bar(1,2) != f2.bar(1,2)

Throttle
--------
Throttle a function to firing at most 1 time per interval.  The function
is fired on the forward edge (meaning it will fire the first time you
call it).

.. code:: python

    from wraptor.decorators import throttle
    import time

    @throttle(.5)
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(3, 4)
    # no-op
    time.sleep(1)
    foo(5, 6)
    # prints (1, 2)

Supports attaching to an instance method!

.. code:: python

    arr = []

    class foo(object):
        @throttle(1, instance_method=True)
        def bar(self):
            arr.append(1)

    x = foo()
    x2 = foo()

    x.bar()
    x2.bar()

    # they don't share the same throttle!
    assert arr == [1, 1]

By default throttle passes through the return value of the wrapped
function if it was called, or None if the def was not called. Use
`return_throttle_result=True` to instead return a `bool`:

.. code:: python

    @throttle(1, return_throttle_result=True)
    def foo():
        pass

    assert foo() is True, 'True means "called"'
    assert foo() is False, 'False means "not called" (throttled)'

Timeout
-------
Timeout uses signal under the hood to allow you to add timeouts to any
function.  The only caveat is that `signal.alarm` can only be used in the
main thread of execution (so multi-threading programs can't use this
decorator in sub-threads).

The timeout value must be a positive integer.

.. code:: python

    from wraptor.decorators import timeout, TimeoutException
    import time

    @timeout(1)
    def heavy_workload():
        # simulate heavy work
        time.sleep(10)

    try:
        heavy_workload()
    except TimeoutException:
        print('workload timed out')

You can also catch the timeout exception from inside the function:

.. code:: python

    @timeout(1)
    def heavy_workload():
        try:
            # simulate heavy work
            time.sleep(10)
        except TimeoutException:
            print('workload timed out')

Exception Catcher
-----------------
`exception_catcher` is a helpful method for dealing with threads that
may raise an exception.  It is especially useful for testing.

.. code:: python

    from wraptor.decorators import exception_catcher

    @exception_catcher
    def work():
        raise Exception()

    t = threading.Thread(target=work)
    t.start()
    t.join()

    try:
        work.check()
    except Exception as e:
        print e

Context Managers
================

Throttle
--------
Throttle a with statement to executing its body at most 1 time per
interval.  The body is fired on the forward edge (meaning it will
fire the first time you call it).

.. code:: python

    from wraptor.context import throttle
    import time

    throttler = throttle(seconds=3)

    def foo():
        with throttler:
            print 'bar'

    foo()
    # prints bar
    sleep(2)
    foo()
    # does nothing
    sleep(2)
    foo()
    # prints bar

Maybe
-----
Execute a with block based on the results of a predicate.

.. code:: python

    from wraptor.context import maybe

    def foo(cond):
        with maybe(lambda: cond == 5):
            print 'bar'

    foo(5)
    # prints bar
    foo(3)
    # does nothing

Timer
-----
Time a block of code.

.. code:: python

    from wraptor.context import timer

    def foo(cond):
        with timer('my slow method') as t:
            expensive_stuff()
        print t

    foo()
    # prints "my slow method took 435.694 ms"


text:
import statistics

from nlp_service.services import ml_service, fact_service

def generate_report(conversation, ml_prediction, similar_precedents, probabilities_dict):
    """
    Generates a report for a prediction based on ML input
    :param conversation: The current Conversation
    :param ml_prediction: A dictionary of outcomes for the conversation received from ml_service
    :param similar_precedents: A list of dicts containing precedents similar to the current case
    :param probabilities_dict: A dict of probabilities for every outcome classifier
    :return: A dict of a report detailing the prediction made by the ml_service
    """

    report = {}
    ml_statistics = ml_service.get_statistics()
    conversation_facts = fact_service.get_resolved_fact_keys(conversation)

    # Prediction accuracy
    report['accuracy'] = 0

    relevant_probabilities_dict = {k: v for k, v in probabilities_dict.items() if k in ml_prediction}
    accuracy_mean = statistics.mean([float(v) for k, v in relevant_probabilities_dict.items()])
    report['accuracy'] = accuracy_mean

    # Data set size
    report['data_set'] = ml_statistics['data_set']['size']

    # Similar case count
    report['similar_case'] = len(similar_precedents)

    # Curves
    report['curves'] = {}

    possible_curve_outcomes = ml_statistics['regressor']
    for outcome in ml_prediction:
        if outcome in possible_curve_outcomes:
            report['curves'][outcome] = dict(possible_curve_outcomes[outcome])
            report['curves'][outcome]['outcome_value'] = ml_prediction[outcome]

    # Outcomes
    report['outcomes'] = {}

    for outcome in ml_prediction:
        if int(ml_prediction[outcome]) == 1:
            report['outcomes'][outcome] = True
        elif int(ml_prediction[outcome]) == 0:
            report['outcomes'][outcome] = False
        else:
            report['outcomes'][outcome] = ml_prediction[outcome]

    # Similar Precedents
    report['similar_precedents'] = []

    # Filter out all facts and outcomes that don't matter from precedents
    for precedent in similar_precedents:
        filtered_fact_dict = {k: v for k, v in precedent['facts'].items() if k in conversation_facts}
        precedent['facts'] = __dict_values_to_int(filtered_fact_dict)
        filtered_outcome_dict = {k: v for k, v in precedent['outcomes'].items() if k in ml_prediction}
        precedent['outcomes'] = __dict_values_to_int(filtered_outcome_dict)
        report['similar_precedents'].append(precedent)

    return report

def __dict_values_to_int(dict):
    for key in dict:
        if isinstance(dict[key], str):
            try:
                dict[key] = int(float(dict[key]))
            except ValueError:
                pass
    return dict


text:
package br.com.ufv.projeto_loja.Entidades;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
 *
 * @author ROMULO-NOTE
 */
@Entity
//@PrimaryKeyJoinColumn(name="idPessoa")
public class Endereco {

	@Id
	@GeneratedValue
	private int idEndereco;

	@Column
	private String rua;

	@Column
	private String numero;

	@Column
	private String bairro;

	@Column
	private String cidade;

	@Column
	private String estado;

	@Column
	private String cep;

	@ManyToOne
	private Funcionario funcionario;

	@ManyToOne
	private Cliente cliente;

	public int getIdEndereco() {
		return idEndereco;
	}

	public void setIdEndereco(int idEndereco) {
		this.idEndereco = idEndereco;
	}

	public String getRua() {
		return rua;
	}

	public void setRua(String rua) {
		this.rua = rua;
	}

	public String getNumero() {
		return numero;
	}

	public void setNumero(String numero) {
		this.numero = numero;
	}

	public String getBairro() {
		return bairro;
	}

	public void setBairro(String bairro) {
		this.bairro = bairro;
	}

	public String getCidade() {
		return cidade;
	}

	public void setCidade(String cidade) {
		this.cidade = cidade;
	}

	public String getEstado() {
		return estado;
	}

	public void setEstado(String estado) {
		this.estado = estado;
	}

	public String getCep() {
		return cep;
	}

	public void setCep(String cep) {
		this.cep = cep;
	}

	public Funcionario getFuncionario() {
		return funcionario;
	}

	public void setFuncionario(Funcionario funcionario) {
		this.funcionario = funcionario;
	}

	public Cliente getCliente() {
		return cliente;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

}


text:
@implementation RZCollectionListSectionNotification

- (id)init
{
    if ((self = [super init]))
    {
        [self clear];
    }
    return self;
}

- (void)clear
{
    self.sectionInfo = nil;
    self.type = RZCollectionListChangeInvalid;
    self.sectionIndex = NSNotFound;
    self.sourceList = nil;
}

- (void)sendToObservers:(NSArray*)observers fromCollectionList:(id<RZCollectionList>)list
{
    [observers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj conformsToProtocol:@protocol(RZCollectionListObserver)])
        {
            [obj collectionList:list didChangeSection:self.sectionInfo atIndex:self.sectionIndex forChangeType:self.type];
        }

    }];
}

- (NSString*)description
{
    return [NSString stringWithFormat:@"%@ Section Info: %@ Section Index: %ld Type %d", [super description], self.sectionInfo, (unsigned long)self.sectionIndex, self.type];
}

@end

@implementation RZCollectionListObjectNotification

- (id)init
{
    if ((self = [super init]))
    {
        [self clear];
    }
    return self;
}

- (void)clear
{
    self.object = nil;
    self.indexPath = nil;
    self.nuIndexPath = nil;
    self.type = RZCollectionListChangeInvalid;
    self.sourceList = nil;
}

- (void)sendToObservers:(NSArray*)observers fromCollectionList:(id<RZCollectionList>)list
{
    [observers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj conformsToProtocol:@protocol(RZCollectionListObserver)])
        {
            [obj collectionList:list didChangeObject:self.object atIndexPath:self.indexPath forChangeType:self.type newIndexPath:self.nuIndexPath];
        }

    }];
}

- (NSString*)description
{
    return [NSString stringWithFormat:@"%@ Object: %@ Index Path: %@ New Index Path: %@ Type: %d", [super description], self.object, self.indexPath, self.nuIndexPath, self.type];
}

@end


text:
<?php

/**
 * Podium Module
 * Yii 2 Forum Module
 * @author Paweł Bizley Brzozowski <pb@human-device.com>
 * @since 0.1
 */

$this->title = Yii::t('podium/view', 'You have been banned!');

?>

<?= $this->title ?>

<?= Yii::t('podium/view', 'Contact the administrator if you would like to get more details about your ban.') ?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `SignedInt` trait in crate `core`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, SignedInt">

    <title>core::num::SignedInt - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

core::<wbr>num

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait core::<wbr>num::<wbr>SignedInt<wbr>Stable
            [-] [+]
        [src]

pub trait SignedInt: Int + Neg<Output=Self> {
    fn abs(self) -> Self;
    fn signum(self) -> Self;
    fn is_positive(self) -> bool;
    fn is_negative(self) -> bool;
}

A built-in two's complement integer.

Required Methods

fn abs(self) -> Self

Computes the absolute value of self. Int::min_value() will be
returned if the number is Int::min_value().

fn signum(self) -> Self

Returns a number representing sign of self.

0 if the number is zero

1 if the number is positive

-1 if the number is negative

fn is_positive(self) -> bool

Returns true if self is positive and false if the number
is zero or negative.

fn is_negative(self) -> bool

Returns true if self is negative and false if the number
is zero or positive.

Implementors

impl SignedInt for i8

impl SignedInt for i16

impl SignedInt for i32

impl SignedInt for i64

impl SignedInt for isize

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
package org.DitaSemia.Oxygen;

import javax.swing.JButton;
import javax.swing.border.EmptyBorder;

import ro.sync.exml.view.graphics.Dimension;
import ro.sync.exml.view.graphics.Point;
import ro.sync.exml.view.graphics.Rectangle;
import ro.sync.ecss.component.editor.ButtonEditor;
import ro.sync.ecss.extensions.api.editor.AuthorInplaceContext;
import ro.sync.ecss.extensions.api.editor.RendererLayoutInfo;

public class NoBorderButtonEditor extends ButtonEditor {

  @Override
  public Object getRendererComponent(AuthorInplaceContext context) {
    JButton button = (JButton)super.getRendererComponent(context);
    button.setBorder(new EmptyBorder(0, 0, 0, 0));
    return button;
  }

  @Override
  public Object getEditorComponent(AuthorInplaceContext context, Rectangle allocation, Point mouseLocation) {
	  JButton button = (JButton)super.getRendererComponent(context);
	  button.setBorder(new EmptyBorder(0, 0, 0, 0));
	  return button;
  }

  @Override
  public RendererLayoutInfo getRenderingInfo(AuthorInplaceContext context) {
	  JButton button = (JButton) getRendererComponent(context);
	  final java.awt.Dimension preferredSize = button.getPreferredSize();

	  return new RendererLayoutInfo(
		  0/*button.getBaseline(preferredSize.width, preferredSize.height)*/,
		  new Dimension(preferredSize.width, preferredSize.height));
  }

}


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

using NSubstitute;
using NUnit.Framework;
using Shouldly;

using Mulder.Base.Domain;

namespace Mulder.Tests.Base.Domain
{
	public class SiteTests
	{
		[TestFixture]
		public class when_creating_new_site
		{
			DateTime modificationTime;
			Site site;

			[SetUp]
			public void SetUp()
			{
				modificationTime = DateTime.UtcNow;

				var configuration = Substitute.For<IConfiguration>();
				var items = CreateItems(modificationTime);
				var layouts = Substitute.For<IEnumerable<Layout>>();
				var compileRules = Substitute.For<IEnumerable<CompileRule>>();
				var routeRules = Substitute.For<IEnumerable<RouteRule>>();
				var layoutRules = Substitute.For<IEnumerable<LayoutRule>>();

				site = new Site(configuration, items, layouts, compileRules, routeRules, layoutRules);
			}

			[Test]
			public void should_create_parent_and_child_links_on_each_item()
			{
				var actualItems = site.Items.ToList();
				var expectedItems = CreateExpectedItems();

				for (int i = 0; i < actualItems.Count; i++) {
					var actualItem = actualItems[i];
					var expectedItem = expectedItems[i];

					actualItem.Parent.ShouldBe(expectedItem.Parent);
					actualItem.Children.ShouldBe(expectedItem.Children);
				}
			}

			IEnumerable<Item> CreateItems(DateTime modificationTime)
			{
				var content = "";
				var meta = Substitute.For<IDictionary<string, object>>();

				return new List<Item> {
					new Item("/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/a/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/a/b/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/a/b/c/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/b/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/b/a/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/b/a/b/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/b/a/b/c/",
						false,
						content,
						meta,
						modificationTime),
					new Item("/binary/",
						true,
						content,
						meta,
						modificationTime)
				};
			}

			List<Item> CreateExpectedItems()
			{
				var items = CreateItems(modificationTime).ToList();

				var root = items[0];
				var a = items[1];
				var ab = items[2];
				var abc = items[3];
				var b = items[4];
				var ba = items[5];
				var bab = items[6];
				var babc = items[7];
				var binary = items[8];

				root.Parent = null;
				root.AddChild(a);
				root.AddChild(b);
				root.AddChild(binary);

				a.Parent = root;
				a.AddChild(ab);
				ab.Parent = a;
				ab.AddChild(abc);
				abc.Parent = ab;

				b.Parent = root;
				b.AddChild(ba);
				ba.Parent = b;
				ba.AddChild(bab);
				bab.Parent = ba;
				bab.AddChild(babc);
				babc.Parent = bab;

				binary.Parent = root;

				return items;
			}
		}
	}
}


text:
package net.sf.jasperreports.web.util;

/**
 * @author Teodor Danciu (teodord@users.sourceforge.net)
 * @version $Id: JacksonMapping.java 7199 2014-08-27 13:58:10Z teodord $
 */
public class JacksonMapping
{
	private String name;
	private String className;

	/**
	 *
	 */
	public JacksonMapping(String name, String className)
	{
		this.name = name;
		this.className = className;
	}

	/**
	 *
	 */
	public String getName()
	{
		return name;
	}

	/**
	 *
	 */
	public void setName(String name)
	{
		this.name = name;
	}

	/**
	 *
	 */
	public String getClassName()
	{
		return className;
	}

	/**
	 *
	 */
	public void setClassName(String className)
	{
		this.className = className;
	}
}


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>CMAKE_GNUtoMS — CMake 3.8.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE" href="CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE.html" />
    <link rel="prev" title="CMAKE_Fortran_MODULE_DIRECTORY" href="CMAKE_Fortran_MODULE_DIRECTORY.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-variables(7) »

CMAKE_GNUtoMS¶

Convert GNU import libraries (.dll.a) to MS format (.lib).

This variable is used to initialize the GNUtoMS property on
targets when they are created.  See that target property for additional
information.

Previous topic

CMAKE_Fortran_MODULE_DIRECTORY

Next topic

CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.2 Documentation »

cmake-variables(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
/* Script Generado por Evolution - Editor de Formulación de Planillas. 16-01-2017 12:26 PM */

begin transaction

delete from [sal].[fcu_formulacion_cursores] where [fcu_codpai] = 'pa' and [fcu_nombre] = 'Emp_OtrosIngresos';

insert into [sal].[fcu_formulacion_cursores] ([fcu_codpai],[fcu_proceso],[fcu_nombre],[fcu_descripcion],[fcu_select_edit],[fcu_select_run],[fcu_field_codemp],[fcu_field_codppl],[fcu_modo_asociacion_tpl],[fcu_loop_calculo],[fcu_updatable]) values ('pa','Planilla','Emp_OtrosIngresos','Emp_OtrosIngresos','select *
from sal.oin_otros_ingresos
where oin_codppl < 0','select *
from sal.oin_otros_ingresos
where oin_estado = ''Autorizado''
and oin_ignorar_en_planilla = 0
and oin_codppl = $$CODPPL$$','oin_codemp','oin_codppl','TodosExcluyendo',0,1);

commit transaction;


text:
package android.support.v7.internal.view.menu;

import android.os.Build;
import android.support.v4.internal.view.SupportMenu;
import android.support.v4.internal.view.SupportMenuItem;
import android.support.v4.internal.view.SupportSubMenu;
import android.view.Menu;
import android.view.MenuItem;

/**
 * @hide
 */
public final class MenuWrapperFactory {
    private MenuWrapperFactory() {
    }

    public static Menu createMenuWrapper(android.view.Menu frameworkMenu) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new MenuWrapperICS(frameworkMenu);
        }
        return frameworkMenu;
    }

    public static MenuItem createMenuItemWrapper(android.view.MenuItem frameworkMenuItem) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return new MenuItemWrapperJB(frameworkMenuItem);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new MenuItemWrapperICS(frameworkMenuItem);
        }
        return frameworkMenuItem;
    }

    public static SupportMenu createSupportMenuWrapper(android.view.Menu frameworkMenu) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new MenuWrapperICS(frameworkMenu);
        }
        throw new UnsupportedOperationException();
    }

    public static SupportSubMenu createSupportSubMenuWrapper(
            android.view.SubMenu frameworkSubMenu) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new SubMenuWrapperICS(frameworkSubMenu);
        }
        throw new UnsupportedOperationException();
    }

    public static SupportMenuItem createSupportMenuItemWrapper(
            android.view.MenuItem frameworkMenuItem) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            return new MenuItemWrapperJB(frameworkMenuItem);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return new MenuItemWrapperICS(frameworkMenuItem);
        }
        throw new UnsupportedOperationException();
    }

    public static MenuItem unwrap(MenuItem item) {
        while(item instanceof  MenuItemWrapperICS) {
            item = ((MenuItemWrapperICS) item).getWrappedObject();
        }
        return item;
    }
}


text:
package coyote.commons.network.http.auth;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import coyote.commons.ByteUtil;
import coyote.commons.CipherUtil;
import coyote.commons.StringUtil;
import coyote.commons.network.http.HTTP;
import coyote.commons.network.http.HTTPD;
import coyote.commons.network.http.HTTPSession;
import coyote.commons.network.http.SessionProfile;
import coyote.commons.network.http.SessionProfileManager;
import coyote.dataframe.DataField;
import coyote.dataframe.DataFrame;
import coyote.dataframe.DataFrameException;
import coyote.loader.Loader;
import coyote.loader.cfg.Config;
import coyote.loader.log.Log;

/**
 * This is the default authentication and authorization component for the HTTP
 * service.
 *
 *
Passwords are read and stored in memory as a multi-round MD5 digest. The
 * number of rounds is chosen pseudo-randomly. This is done to protect
 * passwords from malicious components, core dumps and follows recommended
 * safe coding practices for password handling.
 *
 *
NOTE: User and Group name matching is case-sensitive. It is
 * recommended to normalize all user and group names by hand. (e.g. always
 * specify names in lower case.)
 */
public class GenericAuthProvider implements AuthProvider {
  public static final String ALLOW_NO_SSL = "AllowUnsecuredConnections";
  public static final String AUTH_SECTION = "Auth";
  public static final String GROUPS = "Groups";
  public static final String NAME = "Name";
  public static final String PASSWORD = "Password";
  public static final String SEND_AUTH_ON_FAILURE = "SendAuthRequestOnFailure";
  public static final String USER_SECTION = "Users";
  private static final String MD5 = "MD5";
  private static final String UTF8 = "UTF8";
  public final List<User> userList = new ArrayList<User>();
  private boolean allowNoSSL = false;

  private int digestRounds = 1;
  private boolean sendAuthRequest = false;

  static {
    try {
      MessageDigest.getInstance(MD5);
    } catch (final NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    try {
      UTF8.getBytes(UTF8);
    } catch (final UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }

  public GenericAuthProvider() {
    final Random rand = new Random();
    digestRounds = rand.nextInt((5 - 1) + 1) + 1;
  }

  /**
   * @param cfg the configuration for this provider
   */
  public GenericAuthProvider(final Config cfg) {
    if (cfg != null) {
      for (final DataField field : cfg.getFields()) {
        if (GenericAuthProvider.USER_SECTION.equalsIgnoreCase(field.getName()) && field.isFrame()) {
          configUsers((DataFrame)field.getObjectValue());
        }
      }

      try {
        if (cfg.getAsBoolean(ALLOW_NO_SSL)) {
          Log.append(HTTPD.EVENT, "NOTICE: SSL checks will be ignored in this server instance. Sensitive data may traverse unencrypted connections.");
          allowNoSSL = true;
        }
      } catch (final DataFrameException e) {}

      try {
        if (cfg.getAsBoolean(SEND_AUTH_ON_FAILURE)) {
          Log.append(HTTPD.EVENT, "NOTICE: The WWW-Authenticate header will be sent on failed authentication requests. This allows the user to enter basic auth credentials on most browsers. This may be used as an attack vector (Brute Force & DoS).");
          sendAuthRequest = true;
        }
      } catch (final DataFrameException e) {}
    }

  }

  /**
   * @see coyote.commons.network.http.auth.AuthProvider#isAuthenticated(coyote.commons.network.http.HTTPSession)
   */
  @Override
  public boolean isAuthenticated(final HTTPSession session) {
    boolean retval = false;

    // Make sure there is a session assigned to this request
    SessionProfile profile = SessionProfileManager.retrieveOrCreateProfile(session);
    retval = setUserData(profile, session);

    // all headers are stored in lower case since browsers use different case
    final String authHeader = session.getRequestHeaders().get(HTTP.HDR_AUTHORIZATION.toLowerCase());
    if (StringUtil.isNotBlank(authHeader)) {
      String[] tokens = authHeader.split(" ");
      if ((tokens != null) && (tokens.length > 0)) {
        final String authType = tokens[0];
        Log.append(HTTPD.EVENT, "Received Auth Type of '" + authType + "'");

        // Assume Basic Auth
        if (tokens.length > 1) {
          final byte[] data = ByteUtil.fromBase64(tokens[1].trim());
          final String authPair = new String(data);
          tokens = authPair.split(":");

          String username;
          String password;

          if (tokens != null) {
            if (tokens.length > 0) {
              username = tokens[0];
            } else {
              username = null;
            }
            if (tokens.length > 1) {
              password = tokens[1];
            } else {
              password = null;
            }

            Map<String, String> creds = new HashMap<String, String>();
            creds.put(AuthProvider.USERNAME, username);
            creds.put(AuthProvider.PASSWORD, password);

            retval = authenticate(session, creds);

          } // null tokens???
        } else {
          Log.append(HTTPD.EVENT, "No authentication data received for '" + authType + "' from " + session.getRemoteIpAddress() + ":" + session.getRemoteIpPort());
        }
      } else {
        // No auth header
      }
    }

    if (!retval && sendAuthRequest) {
      session.getResponseHeaders().put(HTTP.HDR_WWW_AUTHENTICATE, HTTP.BASIC + " realm=\"HTTP Server\"");
    }

    return retval;
  }

  /**
   * @see coyote.commons.network.http.auth.AuthProvider#authenticate(coyote.commons.network.http.HTTPSession, java.util.Map)
   */
  @Override
  public boolean authenticate(HTTPSession session, Map<String, String> credentials) {
    boolean retval = false;
    String username = credentials.get(AuthProvider.USERNAME);
    String password = credentials.get(AuthProvider.PASSWORD);

    SessionProfile profile = SessionProfileManager.retrieveOrCreateProfile(session);

    // find the user with the given name
    final User user = getUser(username);
    if (user != null && StringUtil.isNotBlank(password)) {
      try {
        // digest the given password
        final byte[] barray = digest(password.getBytes(UTF8));

        if (user.passwordMatches(barray)) {
          Log.append(HTTPD.EVENT, "Successful authentication for '" + username + "'");
          // add the user and groups to the session
          session.setUserName(user.getName());
          session.setUserGroups(user.getGroups());
          // ... and the profile so we can cache the authenticated username and groups
          if (profile != null) {
            profile.set(AuthProvider.USERNAME, user.getName());
            profile.set(AuthProvider.USERGROUPS, user.getGroups().toArray(new String[0]));
          }
          retval = true;
        }
      } catch (final UnsupportedEncodingException e) {
        e.printStackTrace(); // should never happen, tested in static init
      }

    } // we found a user with that name

    return retval;
  }

  /**
   * Copy the user and groups data from the current session profile to the
   * HTTP session.
   *
   * @param profile the profile retrieved from the session cookie
   * @param session the session to contain the username and groups
   *
   * @return true if there is a username associated with the given profile,
   *         false if there is no authenticated user data.
   */
  private boolean setUserData(SessionProfile profile, HTTPSession session) {
    boolean retval = false;
    if (profile != null && session != null) {
      Serializable object = profile.get(USERNAME);
      if (object != null && object instanceof String) {
        session.setUserName((String)object);
        if (StringUtil.isNotBlank(session.getUserName())) {
          retval = true;
        }
      }

      object = profile.get(USERGROUPS);
      if (object != null && object instanceof String[]) {
        session.setUserGroups(Arrays.asList((String[])object));
      }
    }
    return retval;
  }

  /**
   * @see coyote.commons.network.http.auth.AuthProvider#isAuthorized(coyote.commons.network.http.HTTPSession, java.lang.String)
   */
  @Override
  public boolean isAuthorized(final HTTPSession session, final String groups) {
    final String username = session.getUserName();
    final User user = getUser(username);
    if (user != null) {
      final String[] tokens = groups.split(",");
      for (final String token : tokens) {
        if (user.memberOf(token.trim())) {
          return true;
        }
      }
    }

    return false;
  }

  /**
   * @see coyote.commons.network.http.auth.AuthProvider#isSecureConnection(coyote.commons.network.http.HTTPSession)
   */
  @Override
  public boolean isSecureConnection(final HTTPSession session) {
    // we can configure the auth provider to ignore the SSL check on many of
    // the responders when the deployment does not have valid SSL certificates,
    // such as in development and testing.
    if (allowNoSSL) {
      return true;
    }

    return session.isSecure();
  }

  /**
   * @param cfg a configuration for a list of users
   */
  private void configUsers(final DataFrame cfg) {
    for (final DataField field : cfg.getFields()) {
      if (field.isFrame()) {
        final DataFrame userframe = (DataFrame)field.getObjectValue();
        final User user = new User();

        for (final DataField userfield : userframe.getFields()) {
          if (userfield.getName() != null) {
            if (userfield.getName().endsWith(NAME)) {
              if (userfield.getName().startsWith(Loader.ENCRYPT_PREFIX)) {
                user.setName(CipherUtil.decryptString(userfield.getStringValue()));
              } else {
                user.setName(userfield.getStringValue());
              }
            } else if (userfield.getName().endsWith(PASSWORD)) {
              String passwd;
              if (userfield.getName().startsWith(Loader.ENCRYPT_PREFIX)) {
                passwd = CipherUtil.decryptString(userfield.getStringValue());
              } else {
                passwd = userfield.getStringValue();
              }
              try {
                user.setPassword(digest(passwd.getBytes(UTF8)));
              } catch (final UnsupportedEncodingException e) {}
            } else if (userfield.getName().endsWith(GROUPS)) {
              String groups;
              if (userfield.getName().startsWith(Loader.ENCRYPT_PREFIX)) {
                groups = CipherUtil.decryptString(userfield.getStringValue());
              } else {
                groups = userfield.getStringValue();
              }
              final String[] tokens = groups.split(",");
              for (final String token : tokens) {
                user.addGroup(token.trim());
              }
            }
          }
        }

        userList.add(user);
      }
    }
  }

  /**
   * Perform multi-round MD5 digest of given bytes.
   *
   * @param data the bytes to digest
   *
   * @return digest of the given data
   */
  byte[] digest(final byte[] data) {
    byte[] val = data;
    if (digestRounds > 0) {
      MessageDigest md = null;
      try {
        md = MessageDigest.getInstance(MD5);
      } catch (final NoSuchAlgorithmException e) {}

      if (md != null) {
        for (int x = 0; x < digestRounds; x++) {
          val = md.digest(val);
        }
      }
    }
    return val;
  }

  /**
   * @return the number of digest rounds
   */
  int getDigestRounds() {
    return digestRounds;
  }

  /**
   * Get a user record by its name.
   *
   * @param name The name of the user to retrieve.
   *
   * @return the first user with the given name or null if not found.
   */
  User getUser(final String name) {
    if (StringUtil.isNotEmpty(name)) {
      for (final User user : userList) {
        if (name.equals(user.getName())) {
          return user;
        }
      }
    }
    return null;
  }

  /**
   * @param rounds
   */
  void setDigestRounds(final int rounds) {
    digestRounds = rounds;
  }

  /**
  * Class to hold user data
  */
  class User {
    private final List<String> groups = new ArrayList<String>();
    private String name = null;
    private byte[] pass = null;

    public boolean memberOf(final String group) {
      for (final String groupname : groups) {
        if (groupname.equals(group)) {
          return true;
        }
      }
      return false;
    }

    void addGroup(final String groupname) {
      groups.add(groupname);
    }

    List<String> getGroups() {
      return groups;
    }

    String getName() {
      return name;
    }

    byte[] getPassword() {
      return pass;
    }

    boolean passwordMatches(final byte[] data) {
      return Arrays.equals(data, pass);
    }

    void setName(final String name) {
      this.name = name;
    }

    void setPassword(final byte[] pass) {
      this.pass = pass;
    }

  }

}


text:
package org.systemsbiology.addama.registry;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author hrovira
 */
public class SetContentMockFilterChain implements FilterChain {
    private final Integer contentLength;

    public SetContentMockFilterChain(Integer contentLength) {
        this.contentLength = contentLength;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
            throws IOException, ServletException {
        OutputStream outputStream = servletResponse.getOutputStream();
        for (int i = 0; i < contentLength; i++) {
            outputStream.write(1);
        }
    }
}