text:
<?php

class NodeattachmentHelper extends AppHelper {

       /**
        * Used helpers
        *
        * @var array
        */
       public $helpers = array(
           'Js' => array('Jquery'),
           'Html',
           'Layout',
           'Image2',
       );

       /**
        * Attachment types
        *
        * @var array
        */
       public $attachment_types = array(
           'video',
           'audio',
           'application',
           'text',
           'image'
       );

       /**
        * Nodeattachment
        *
        * @var array
        */
       public $nodeattachment = array();

       /**
        * Before render callback
        *
        * @return void
        */
       public function beforeRender($viewFile) {

              $this->conf = Configure::read('Nodeattachment');
       }

       /**
        * After set node callback
        * Set all attachments by types
        *
        * @return void
        */
       public function afterSetNode() {

              foreach ($this->attachment_types as $type) {
                     $attachments[$type] = $this->extractMimeType($this->Layout->node, $type);
              }
              $this->Layout->node['Nodeattachments'] = $attachments;
       }

       /**
        * Process loading image
        *
        * @param string $effect Can be: fadeIn, fadeOut, show, hide, slideIn, slideOut
        * @param string $selector Selector of load image element
        * @return string Formatted javascript code
        */
       public function requestOptions($options = array()) {

              $_options = array(
                  'update' => '#attachments-listing',
                  'before' => $this->Js->get('#loading')->effect('fadeIn', array('buffer' => false)),
                  'complete' => $this->Js->get('#loading')->effect('hide', array('buffer' => false))
              );
              $options = Set::merge($_options, $options);
              return $options;
       }

       /**
        * Node thumb
        *
        * @param string $field Filed of attachment to return
        * @return string Url of the thumb image
        */
       public function nodeThumb($width, $height, $method = 'resizeRatio', $options = array()) {

              $attachment = Set::extract('/Nodeattachment/.[1]', $this->Layout->node);
              if (empty($attachment)) {
                return false;
              }
              $this->setNodeattachment($attachment[0]);
              if (!empty($this->nodeattachment)) {
                     return $this->Image2->resize($this->field('thumb_path'), $width, $height, $method, $options, FALSE, $this->field('server_thumb_path'));
              }
              return false;
       }

       /**
        * Set nodeattachment
        *
        * @param array $var
        * @return void
        */
       public function setNodeattachment($nodeattachment) {

              $model = 'Nodeattachment';
              if (isset($nodeattachment['id'])) {
                     $data = $nodeattachment;
              }
              if (isset($nodeattachment[$model]['id'])) {
                     $data = $nodeattachment[$model];
              }

              if (isset($data)) {
                     $this->nodeattachment[$model] = $data;
                     $this->__thumb();
                     $this->__flv();
              } else {
                     $this->nodeattachment = false;
              }
       }

       /**
        * If file (video) has flv variant
        *
        * @return void
        */
       private function __flv() {

              $is_video = strpos($this->field('mime_type'), 'video');
              if ($is_video === 0) {
                     $file_name = explode('.', $this->field('slug'));

                     $flv_file = $this->conf['flvDir'] . DS . $file_name[0] . '.flv';
                     if (file_exists($flv_file)) {
                            $this->setField('flv_path', '/nodeattachment/flv/' . $file_name[0] . '.flv'
                            );
                            return;
                     }

                     if ($file_name[1] == 'flv') {
                            $this->setField('flv_path', $this->field('path')
                            );
                     }
              }
       }

       /**
        * Thumbnails
        *
        * @param array $var
        * @return array
        */
       private function __thumb() {

              $data = $this->nodeattachment['Nodeattachment'];

              $file_type = explode('/', $data['mime_type']);
              $file_name = explode('.', $data['slug']);

              // image
              if ($file_type[0] == 'image') {
                     $data['thumb_path'] = $data['path'];
                     $data['server_thumb_path'] = ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS . $data['path'];
                     $this->nodeattachment['Nodeattachment'] = $data;
                     return;
              }

              // check if exists thumb with original filename
              $thumb_filename = $file_name[0] . '.' . Configure::read('Nodeattachment.thumbnailExt');
              if (file_exists($this->conf['thumbDir'] . DS . $thumb_filename)) {
                     $data['thumb_path'] = '/nodeattachment/img/tn/' . $thumb_filename;
                     $data['server_thumb_path'] = $this->conf['thumbDir'] . DS . $thumb_filename;
                     $this->nodeattachment['Nodeattachment'] = $data;
                     return;
              }

              // check if exists thumb with mime type filename
              $thumb_filename = 'thumb_' . $file_type[0] . '.' . Configure::read('Nodeattachment.thumbnailExt');
              if (file_exists($this->conf['iconDir'] . DS . $thumb_filename)) {
                     $data['thumb_path'] = '/nodeattachment/img/' . $thumb_filename;
                     $data['server_thumb_path'] = $this->conf['iconDir'] . DS . $thumb_filename;
                     $this->nodeattachment['Nodeattachment'] = $data;
                     return;
              } else {
                     $data['thumb_path'] = '/nodeattachment/img/thumb_default.' . $this->conf['thumbExt'];
                     $data['server_thumb_path'] = $this->conf['iconDir'] . DS .
                             'thumb_default.' . $this->conf['thumbExt'];
                     $this->nodeattachment['Nodeattachment'] = $data;
                     return;
              }
       }

       /**
        * Get field from nodeattachment data
        *
        * @param string $field
        * @return void
        */
       public function field($field_name = 'id') {

              $model = 'Nodeattachment';
              if (isset($this->nodeattachment[$model][$field_name])) {
                     return $this->nodeattachment[$model][$field_name];
              } else {
                     return false;
              }
       }

       /**
        * Set nodeattachment field
        *
        * @param string $field_name
        * @param void $value
        * @return boolean
        */
       public function setField($field_name, $value) {

              $model = 'Nodeattachment';
              $this->nodeattachment[$model][$field_name] = $value;
       }

       /**
        * Extract mime types from
        *
        * @param string $type Mime type
        * @return array
        */
       public function filterMime($type = 'image') {

              return $this->extractMimeType($this->Layout->node, $type);
       }

       /**
        * Extract type of attachment
        *
        * @param string $type
        * @return array
        */
       public function filterType($type = 'Gallery') {

              $nodeattachments = Set::extract('/Nodeattachment[type=/' . $type . '/]', $this->Layout->node);
              return $nodeattachments;
       }

       /**
        * DEPRECATED!!!  use filterMime instead
        * Get attachments
        *
        * @param string $type mime type
        * @return array
        */
       public function getAttachments($type = 'image') {

              return $this->Layout->node['Nodeattachments'][$type];
       }

       /**
        * Extract mime types
        *
        * @param array $node
        * @param string $type Mime Type to extract
        * @return array
        */
       private function extractMimeType($node, $type = 'image') {
              $nodeattachments = Set::extract('/Nodeattachment[mime_type=/' . $type . '(.*)/]', $node);
              return $nodeattachments;
       }

}


text:
package com.amazonaws.services.simpleemail.model;

/**
 *
 */
public enum IdentityType {

    EmailAddress("EmailAddress"),
    Domain("Domain");

    private String value;

    private IdentityType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return IdentityType corresponding to the value
     */
    public static IdentityType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        } else if ("EmailAddress".equals(value)) {
            return EmailAddress;
        } else if ("Domain".equals(value)) {
            return Domain;
        } else {
            throw new IllegalArgumentException("Cannot create enum from "
                    + value + " value!");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
int main(int argc, char const *argv[])
{
  timer timer;
  std::cout << "Transforming Raw Data" << std::endl;

  auto um_data_path = "raw_data/um/all.dta";
  auto um_index_path = "raw_data/um/all.idx";
  auto um_bin_prefix = "data/um/";
  std::vector<int*> um_datasets;

  auto mu_data_path = "raw_data/mu/all.dta";
  auto mu_index_path = "raw_data/mu/all.idx";
  auto mu_bin_prefix = "data/mu/";
  std::vector<int*> mu_datasets;

  std::vector<std::string> bin_suffixes = {"base.bin", "valid.bin", "hidden.bin",
    "probe.bin", "qual.bin"};

  data_loader::split_data(um_data_path, um_index_path, um_datasets);
  data_loader::split_data(mu_data_path, mu_index_path, mu_datasets);

  for (auto i = 0; i < bin_suffixes.size(); i++) {
    data_loader::save_data(um_bin_prefix + bin_suffixes[i], um_datasets[i],
      DATA_SIZES[i] * COL_SIZE);
    data_loader::save_data(mu_bin_prefix + bin_suffixes[i], mu_datasets[i],
      DATA_SIZES[i] * COL_SIZE);
  }

  timer.stop();
  timer.duration();
  return 0;
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Prestigio PSP5454DUO
 *
 * DEVICE: PSP5454DUO
 * MODEL: PSP5454DUO
 */
final class psp5454duo_psp5454duo {
    public static final String DATA = "Prestigio|PSP5454DUO|";
}


text:
@interface RCDGroupMembersTableViewController ()

@property (nonatomic, strong) RCDUIBarButtonItem *leftBtn;

@end

@implementation RCDGroupMembersTableViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Uncomment the following line to preserve selection between presentations.
  // self.clearsSelectionOnViewWillAppear = NO;

  // Uncomment the following line to display an Edit button in the navigation
  // bar for this view controller.
  // self.navigationItem.rightBarButtonItem = self.editButtonItem;
  self.tableView.tableFooterView = [UIView new];

  self.title = [NSString stringWithFormat:@"群组成员(%lu)",
                                          (unsigned long)[_GroupMembers count]];

  self.leftBtn =
  [[RCDUIBarButtonItem alloc] initContainImage:[UIImage imageNamed:@"navigator_btn_back"]
                                imageViewFrame:CGRectMake(-6, 4, 10, 17)
                                   buttonTitle:@"返回"
                                    titleColor:[UIColor whiteColor]
                                    titleFrame:CGRectMake(9, 4, 85, 17)
                                   buttonFrame:CGRectMake(0, 6, 87, 23)
                                        target:self
                                        action:@selector(clickBackBtn)];
  self.navigationItem.leftBarButtonItem = self.leftBtn;
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return 1;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section {
  return [_GroupMembers count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *reusableCellWithIdentifier = @"RCDContactTableViewCell";
  RCDContactTableViewCell *cell = [self.tableView
      dequeueReusableCellWithIdentifier:reusableCellWithIdentifier];
  if (cell == nil) {
    cell = [[RCDContactTableViewCell alloc] init];
  }
  // Configure the cell...
  RCDUserInfo *user = _GroupMembers[indexPath.row];
  if ([user.portraitUri isEqualToString:@""]) {
    DefaultPortraitView *defaultPortrait =
        [[DefaultPortraitView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [defaultPortrait setColorAndLabel:user.userId Nickname:user.name];
    UIImage *portrait = [defaultPortrait imageFromView];
    cell.portraitView.image = portrait;
  } else {
    [cell.portraitView sd_setImageWithURL:[NSURL URLWithString:user.portraitUri]
                         placeholderImage:[UIImage imageNamed:@"contact"]];
  }
  cell.portraitView.layer.masksToBounds = YES;
  cell.portraitView.layer.cornerRadius = 5.f;
  cell.portraitView.contentMode = UIViewContentModeScaleAspectFill;

  cell.nicknameLabel.font = [UIFont systemFontOfSize:15.f];
  cell.nicknameLabel.text = user.name;
  cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  cell.selectionStyle = UITableViewCellSelectionStyleNone;
  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView
    heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 70.0;
}

- (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  RCUserInfo *user = _GroupMembers[indexPath.row];
  BOOL isFriend = NO;
  NSArray *friendList = [[RCDataBaseManager shareInstance] getAllFriends];
  for (RCDUserInfo *friend in friendList) {
    if ([user.userId isEqualToString:friend.userId] &&
        [friend.status isEqualToString:@"20"]) {
      isFriend = YES;
    }
  }
  if (isFriend == YES || [user.userId isEqualToString:[RCIM sharedRCIM].currentUserInfo.userId]) {
      RCDPersonDetailViewController *detailViewController =
      [[RCDPersonDetailViewController alloc]init];

    [self.navigationController pushViewController:detailViewController
                                         animated:YES];
    RCUserInfo *user = _GroupMembers[indexPath.row];
    detailViewController.userId = user.userId;
  } else {
      RCDAddFriendViewController *addViewController = [[RCDAddFriendViewController alloc]init];
    addViewController.targetUserInfo = _GroupMembers[indexPath.row];
    [self.navigationController pushViewController:addViewController
                                         animated:YES];
  }
}

- (void)clickBackBtn {
  [self.navigationController popViewControllerAnimated:YES];
}

@end


text:
package com.sezar.model.security;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;

@Entity
@Table(name = "AUTHORITY")
public class Authority {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
//    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "authority_seq")
//    @SequenceGenerator(name = "authority_seq", sequenceName = "authority_seq", allocationSize = 1)
    private Long id;

    @Column(name = "NAME", length = 50)
    @NotNull
    @Enumerated(EnumType.STRING)
    private AuthorityName name;

//    @ManyToMany
    @ManyToMany(fetch = FetchType.LAZY)
//    @JoinTable(
//            name = "USER_AUTHORITY",
//            joinColumns = {@JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")},
//            inverseJoinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "ID")})
    private List<User> users;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public AuthorityName getName() {
        return name;
    }

    public void setName(AuthorityName name) {
        this.name = name;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}


text:
#ifndef HELIUM_FILEIO_MOLECULEFILE_H
#define HELIUM_FILEIO_MOLECULEFILE_H

#include <Helium/molecule.h>
#include <Helium/util.h>
#include <Helium/fileio/file.h>
#include <Helium/json/json.h>

#include <boost/iostreams/device/mapped_file.hpp>

namespace Helium {

  /**
   * @file fileio/moleculefile.h
   * @brief Classes for reading and writing molecule files.
   */

  /**
   * @brief Read a molecule from a STL input stream.
   *
   * @param is The input stream.
   * @param mol The molecule.
   *
   * @return True if successful.
   */
  template<typename EditableMoleculeType>
  bool read_molecule(std::istream &is, EditableMoleculeType &mol)
  {
    typedef typename molecule_traits<EditableMoleculeType>::atom_type atom_type;
    typedef typename molecule_traits<EditableMoleculeType>::bond_type bond_type;

    clear_molecule(mol);

    if (!is)
      return false;

    // read number of atoms and bonds
    unsigned short numAtoms, numBonds;
    read16(is, numAtoms);
    read16(is, numBonds);

    if (!is)
      return false;

    unsigned char element, cyclic, aromatic, mass, hydrogens;
    signed char charge;
    for (int i = 0; i < numAtoms; ++i) {
      // read the element
      read8(is, element);
      read8(is, cyclic);
      read8(is, aromatic);
      read8(is, mass);
      read8(is, hydrogens);
      read8(is, charge);

      // create the atom
      atom_type atom = add_atom(mol);
      // set the atom properties
      set_aromatic(mol, atom, aromatic);
      set_element(mol, atom, element);
      set_mass(mol, atom, mass);
      set_hydrogens(mol, atom, hydrogens);
      set_charge(mol, atom, charge);
    }

    unsigned short source, target;
    unsigned char props;
    for (int i = 0; i < numBonds; ++i) {
      // source and target indices
      read16(is, source);
      read16(is, target);
      // read remaining properties: cyclic, aromatic & bond order
      read8(is, props);

      // get the atoms
      atom_type s = get_atom(mol, source);
      atom_type t = get_atom(mol, target);

      // create the bond
      bond_type bond = add_bond(mol, s, t);
      // set the bond properties
      set_aromatic(mol, bond, props & 128);
      set_order(mol, bond, props & 63);
    }

    return true;
  }

  /**
   * @brief Read a molecule from a memory location.
   *
   * @param data Pointer to the memory.
   * @param mol The molecule.
   *
   * @return True if successful.
   */
  template<typename EditableMoleculeType>
  bool read_molecule(const char *data, EditableMoleculeType &mol)
  {
    typedef typename molecule_traits<EditableMoleculeType>::atom_type atom_type;
    typedef typename molecule_traits<EditableMoleculeType>::bond_type bond_type;

    clear_molecule(mol);

    // read number of atoms and bonds
    unsigned short numAtoms = *reinterpret_cast<const unsigned short*>(data);
    unsigned short numBonds = *reinterpret_cast<const unsigned short*>(data + sizeof(unsigned short));

    unsigned char element, aromatic, mass, hydrogens;
    signed char charge;
    for (int i = 0; i < numAtoms; ++i) {
      unsigned int offset = 2 * sizeof(unsigned short) + 6 * i;
      // read the element
      element = *reinterpret_cast<const unsigned char*>(data + offset);
      aromatic = *reinterpret_cast<const unsigned char*>(data + offset + 2);
      mass = *reinterpret_cast<const unsigned char*>(data + offset + 3);
      hydrogens = *reinterpret_cast<const unsigned char*>(data + offset + 4);
      charge = *reinterpret_cast<const signed char*>(data + offset + 5);

      // create the atom
      atom_type atom = add_atom(mol);
      // set the atom properties
      set_aromatic(mol, atom, aromatic);
      set_element(mol, atom, element);
      set_mass(mol, atom, mass);
      set_hydrogens(mol, atom, hydrogens);
      set_charge(mol, atom, charge);
    }

    unsigned short source, target;
    unsigned char props;
    for (int i = 0; i < numBonds; ++i) {
      unsigned int offset = 2 * sizeof(unsigned short) + 6 * numAtoms + 5 * i;
      // source and target indices
      source = *reinterpret_cast<const unsigned short*>(data + offset);
      target = *reinterpret_cast<const unsigned short*>(data + offset + sizeof(unsigned short));
      // read remaining properties: cyclic, aromatic & bond order
      props = *reinterpret_cast<const unsigned char*>(data + offset + 2 * sizeof(unsigned short));

      // get the atoms
      atom_type s = get_atom(mol, source);
      atom_type t = get_atom(mol, target);

      // create the bond
      bond_type bond = add_bond(mol, s, t);
      // set the bond properties
      set_aromatic(mol, bond, props & 128);
      set_order(mol, bond, props & 63);
    }

    return true;
  }

  /**
   * @brief Write a molecule to an STL output stream.
   *
   * @param os The STL output stream.
   * @param mol The molecule to write.
   */
  template<typename MoleculeType>
  void write_molecule(std::ostream &os, const MoleculeType &mol)
  {
    // hydrogen atoms are not written to the file
    // create a map to map atom indices & count the number of heavy atoms
    std::vector<unsigned short> indices(num_atoms(mol));
    unsigned short numAtoms = 0;
    for (auto &atom : get_atoms(mol)) {
      indices[get_index(mol, atom)] = numAtoms;
      if (!is_hydrogen(mol, atom))
        ++numAtoms;
    }

    // count the number of bonds between heavy atoms
    unsigned short numBonds = 0;
    for (auto &bond : get_bonds(mol))
      if (!is_hydrogen(mol, get_source(mol, bond)) && !is_hydrogen(mol, get_target(mol, bond)))
        ++numBonds;

    // write the number of atoms & bonds
    write16<unsigned short>(os, numAtoms);
    write16<unsigned short>(os, numBonds);

    // write atoms (6 byte / atom)
    for (auto &atom : get_atoms(mol)) {
      if (is_hydrogen(mol, atom))
        continue;

      // write the element
      write8<unsigned char>(os, get_element(mol, atom));
      // write cyclic property
      write8<unsigned char>(os, 0);
      // write aromatic property
      write8<unsigned char>(os, is_aromatic(mol, atom));
      // write isotope
      write8<unsigned char>(os, get_mass(mol, atom));
      // write hydrogen count
      write8<unsigned char>(os, get_hydrogens(mol, atom) + get_degree(mol, atom) - get_heavy_degree(mol, atom));
      // write formal charge
      write8<signed char>(os, get_charge(mol, atom));
    }

    // write bonds (5 byte / bond
    for (auto &bond : get_bonds(mol)) {
      if (is_hydrogen(mol, get_source(mol, bond)) || is_hydrogen(mol, get_target(mol, bond)))
        continue;

      // write source & target indices
      write16<unsigned short>(os, indices[get_index(mol, get_source(mol, bond))]);
      write16<unsigned short>(os, indices[get_index(mol, get_target(mol, bond))]);
      // write bond order + aromatic & cyclic properties
      unsigned char props = get_order(mol, bond);
      if (is_aromatic(mol, bond))
        props |= 128;
      //if (bond->IsInRing())
      //  props |= 64;
      write8<unsigned char>(os, props);
    }
  }

  /**
   * @class MoleculeOutputFile fileio/moleculefile.h <Helium/fileio/moleculefile.h>
   * @brief Class for writing molecule files.
   */
  class MoleculeOutputFile
  {
    public:
      /**
       * @brief Constructor.
       *
       * @param filename The filename.
       */
      MoleculeOutputFile(const std::string &filename) : m_file(filename)
      {
      }

      ~MoleculeOutputFile()
      {
        // save the stream position where the molecule positions are stored
        Json::UInt64 positionsPos = m_file.stream().tellp();

        // write the molecule positions to the file
        m_file.write(&m_positions[0], m_positions.size() * sizeof(std::size_t));

        // create JSON header
        Json::Value data;
        data["filetype"] = "molecules";
        data["num_molecules"] = Json::UInt64(m_positions.size());
        data["molecule_indexes"] = positionsPos;

        // write JSON header
        Json::StyledWriter writer;
        m_file.writeHeader(writer.write(data));
      }

      /**
       * @brief Write a molecule to the file.
       *
       * @param mol The molecule to write.
       */
      template<typename MoleculeType>
      bool writeMolecule(const MoleculeType &mol)
      {
        m_positions.push_back(m_file.stream().tellp());
        write_molecule(m_file.stream(), mol);
        return true;
      }

      /**
       * @brief Get the last error.
       *
       * @return The last error.
       */
      const Error& error() const
      {
        return m_file.error();
      }

    private:
      BinaryOutputFile m_file; //!< The binary output file.
      std::vector<std::size_t> m_positions; //!< The molecule positions in the file.
      Error m_error; //!< The last error.
  };

  /**
   * @class MoleculeFile fileio/moleculefile.h <Helium/fileio/moleculefile.h>
   * @brief Class for reading molecules from Helium binary file.
   *
   * When load() is called, this class reads the file header and loads the
   * position index for fast random access to molecules.
   */
  class MoleculeFile
  {
    public:
      /**
       * @brief Constructor.
       */
      MoleculeFile() : m_numMolecules(0), m_positionsPos(0)
      {
      }

      /**
       * @brief Constructor.
       *
       * @param filename The filename.
       */
      MoleculeFile(const std::string &filename)
      {
        load(filename);
      }

      /**
       * @brief Load a file.
       *
       * This function reads the file header and prepares the file for use.
       *
       * @param filename The filename.
       */
      bool load(const std::string &filename)
      {
        TIMER("MoleculeFile::load():");

        // reset error
        m_error = Error();

        if (!m_file.open(filename)) {
          m_error = m_file.error();
          return false;
        }

        // read the josn header
        Json::Reader reader;
        Json::Value data;
        if (!reader.parse(m_file.header(), data)) {
          m_error = Error(reader.getFormattedErrorMessages());
          return false;
        }

        // make sure the required attributes are present
        if (!data.isMember("filetype") || data["filetype"].asString() != "molecules") {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'filetype' attribute or is not 'molecules'"));
          return false;
        }
        if (!data.isMember("num_molecules")) {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'num_molecules' attribute"));
          return false;
        }
        if (!data.isMember("molecule_indexes")) {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'molecule_indexes' attribute"));
          return false;
        }

        // extract needed attributes
        m_numMolecules = data["num_molecules"].asUInt();
        m_positionsPos = data["molecule_indexes"].asUInt64();

        // read the molecule indexes
        m_positions.resize(m_numMolecules);
        m_file.stream().seekg(m_positionsPos);
        m_file.read(&m_positions[0], m_positions.size() * sizeof(uint64_t));

        // reset stream position to read first molecule
        m_file.seek(0);

        return true;
      }

      /**
       * @brief Get the number of molecules.
       *
       * @return The number of molecules.
       */
      unsigned int numMolecules() const
      {
        return m_numMolecules;
      }

      /**
       * Read the next molecule from the file.
       *
       * @return True if successfull.
       */
      template<typename EditableMoleculeType>
      bool readMolecule(EditableMoleculeType &mol)
      {
        if (!(bool)m_file)
          return false;
        return Helium::read_molecule(m_file.stream(), mol);
      }

      /**
       * Read the molecule with the specified index from the file.
       *
       * @return True if successfull.
       */
      template<typename EditableMoleculeType>
      bool readMolecule(unsigned int index, EditableMoleculeType &mol)
      {
        if (!(bool)m_file)
          return false;
        m_file.stream().seekg(m_positions[index]);
        return Helium::read_molecule(m_file.stream(), mol);
      }

      /**
       * @brief Get the STL input stream.
       *
       * @return The STL input stream.
       */
      std::ifstream& stream()
      {
        return m_file.stream();
      }

      /**
       * @brief Get the stream positions of the molecules.
       *
       * @return The stream positions of the molecules.
       */
      std::vector<uint64_t> positions() const
      {
        return m_positions;
      }

      /**
       * @brief Get the stream position of the molecule position index.
       *
       * @return The stream position of the molecule position index.
       */
      Json::UInt64 positionsPos() const
      {
        return m_positionsPos;
      }

      /**
       * @brief Close the file.
       */
      void close()
      {
        m_file.close();
        m_positions.clear();
        m_numMolecules = 0;
        m_positionsPos = 0;
      }

      /**
       * @brief Get the last error.
       *
       * @return The last error.
       */
      const Error& error() const
      {
        return m_error;
      }

    private:
      BinaryInputFile m_file; //!< The binary file.
      std::vector<uint64_t> m_positions; //!< The molecule positions.
      unsigned int m_numMolecules; //!< The number of molecules.
      Json::UInt64 m_positionsPos; //!< Position of molecule positions index.
      Error m_error; //!< The last error.
  };

  /**
   * @class MemoryMappedMoleculeFile fileio/moleculefile.h <Helium/fileio/moleculefile.h>
   * @brief Class for reading molecules from Helium binary file.
   */
  class MemoryMappedMoleculeFile
  {
    public:
      /**
       * @brief Constructor.
       */
      MemoryMappedMoleculeFile() : m_numMolecules(0)
      {
      }

      /**
       * @brief Constructor.
       *
       * @param filename The filename.
       */
      MemoryMappedMoleculeFile(const std::string &filename)
      {
        load(filename);
      }

      /**
       * @brief Load a file.
       *
       * This function reads the file header and prepares the file for use.
       *
       * @param filename The filename.
       */
      bool load(const std::string &filename)
      {
        TIMER("MemoryMappedMoleculeFile::load():");

        // reset error
        m_error = Error();

        // use a temporary BinaryInputFile to easily read the header
        BinaryInputFile file(filename);
        if (file.error()) {
          m_error = file.error();
          return false;
        }

        // read the josn header
        Json::Reader reader;
        Json::Value data;
        if (!reader.parse(file.header(), data)) {
          m_error = Error(reader.getFormattedErrorMessages());
          return false;
        }

        // make sure the required attributes are present
        if (!data.isMember("filetype") || data["filetype"].asString() != "molecules") {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'filetype' attribute or is not 'molecules'"));
          return false;
        }
        if (!data.isMember("num_molecules")) {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'num_molecules' attribute"));
          return false;
        }
        if (!data.isMember("molecule_indexes")) {
          m_error = Error(make_string("JSON header for file ", filename, " does not contain 'molecule_indexes' attribute"));
          return false;
        }

        // extract needed attributes
        m_numMolecules = data["num_molecules"].asUInt();
        Json::UInt64 positionsPos = data["molecule_indexes"].asUInt64();

        // open the memory mapped file
        m_mappedFile.open(filename);
        assert(m_mappedFile.is_open());
        assert(m_mappedFile.data());

        // read the molecule indexes
        m_positions.resize(m_numMolecules);
        for (unsigned int i = 0; i < m_positions.size(); ++i)
          m_positions[i] = *reinterpret_cast<const uint64_t*>(m_mappedFile.data() + positionsPos + i * sizeof(uint64_t));

        return true;
      }

      /**
       * @brief Get the number of molecules.
       *
       * @return The number of molecules.
       */
      unsigned int numMolecules() const
      {
        return m_numMolecules;
      }

      /**
       * Read the molecule with the specified index from the file.
       *
       * @return True if successfull.
       */
      template<typename MoleculeType>
      bool readMolecule(unsigned int index, MoleculeType &mol)
      {
        Helium::read_molecule(m_mappedFile.data() + m_positions[index], mol);
        return true;
      }

      /**
       * @brief Get the last error.
       *
       * @return The last error.
       */
      const Error& error() const
      {
        return m_error;
      }

    private:
      boost::iostreams::mapped_file_source m_mappedFile; //!< The memory mapped file.
      std::vector<uint64_t> m_positions; //!< The positions of the molecules in the file.
      unsigned int m_numMolecules; //!< The number of molecules in the file.
      Error m_error; //!< The last error.
  };

}

#endif


text:
var fs = require('fs')
var stripJSON = require('strip-json-comments')

function requireJSON (file, ignoreExtension) {
  if (!ignoreExtension && !/\.json$/.test(file)) {
    file += '.json'
  }
  return parseJSON(fs.readFileSync(file, 'utf-8'))
}

function parseJSON (string, whitespace) {
  whitespace = whitespace || true
  return JSON.parse(stripJSON(string, whitespace))
}

exports.requireJSON = requireJSON
exports.parseJSON = parseJSON


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txv_mytextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txv_mytextview_state_start" />

    <Button
        android:id="@+id/btn_mybutton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_mybutton1" />

    <Button
        android:id="@+id/btn_mybutton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_mybutton2" />
</LinearLayout>


text:
require_relative '../../spec_helper'
require_lib 'reek/smells/too_many_statements'
require_relative 'smell_detector_shared'

RSpec.describe Reek::Smells::TooManyStatements do
  it 'should not report short methods' do
    src = 'def short(arga) alf = f(1);@bet = 2;@cut = 3;@dit = 4; @emp = 5;end'
    expect(src).not_to reek_of(:TooManyStatements)
  end

  it 'should report long methods' do
    src = 'def long() alf = f(1);@bet = 2;@cut = 3;@dit = 4; @emp = 5;@fry = 6;end'
    expect(src).to reek_of(:TooManyStatements)
  end

  it 'should not report initialize' do
    src = <<-EOS
      def initialize(arga)
        alf = f(1); @bet = 2; @cut = 3; @dit = 4; @emp = 5; @fry = 6
      end
    EOS
    expect(src).not_to reek_of(:TooManyStatements)
  end

  it 'should report long inner block' do
    src = <<-EOS
      def long()
        f(3)
        self.each do |xyzero|
          xyzero = 1
          xyzero = 2
          xyzero = 3
          xyzero = 4
          xyzero = 5
          xyzero = 6
        end
      end
    EOS
    expect(src).to reek_of(:TooManyStatements)
  end
end

RSpec.describe Reek::Smells::TooManyStatements do
  let(:detector) { build(:smell_detector, smell_type: :TooManyStatements) }

  it_should_behave_like 'SmellDetector'

  context 'when the method has 30 statements' do
    let(:num_statements) { 30 }
    let(:smells) do
      ctx = double('method_context').as_null_object
      expect(ctx).to receive(:num_statements).and_return(num_statements)
      expect(ctx).to receive(:config_for).with(described_class).and_return({})
      detector.inspect(ctx)
    end

    it 'reports only 1 smell' do
      expect(smells.length).to eq(1)
    end

    it 'reports the number of statements' do
      expect(smells[0].parameters[:count]).to eq(num_statements)
    end

    it 'reports the correct smell sub class' do
      expect(smells[0].smell_type).to eq(described_class.smell_type)
    end
  end
end


text:
published: true
title: Viagem México
layout: post
---

![](https://github.com/MikhailKoslowski/MikhailKoslowski.github.io/raw/master/_imgs/mex/mex01.JPG)

# Resumo

Viajamos do dia 19/01/2015 ao dia 02/02/2015.

Fiz uma tabela pra dar uma ideia de onde estavamos ou para onde estavamos indo em cada dia.

Do dia 24 ao dia 31 estavamos de carro, então era muito fácil ir de um lado para o outro na costa do Caribe.

|  Data | Manhã | Tarde | Noite |
|-------|:-----:|:-----:|:-----:|
| 19/01 | | Vôo de ida, CWB->GRU->MEX|--|
| 20/01 | México DF | -- | -- |
| 21/01 | Ônibus Teotihuacán (07:30) | Retorno DF (17:00) | Ônibus Puebla (21:00) |
| 22/01 | Puebla |--|--|
| 23/01 | Ônibus Cholula | Retorno Puebla | Retorno DF, Vôo Mérida |
| 24/01 | Mérida, estamos de carro! | -- | Bike em Mérida |
| 25/01 | Chichen Itza | -- | Tulum |
| 26/01 | Tulum | -- | -- |
| 27/01 | XCacel | Akumal | Playa del Carmen |
| 28/01 | Playa del Carmen | Puerto Morelos | Playa del Carmen
| 29/01 | Paa Mul | Puerto Morelos | Cancun |
| 30/01 | Isla Mujeres | Cancun | Cirque du Soleil |
| 31/01 | Vôo de volta CAN->MEX | México DF | -- |
| 01/02 | -- | Vôo de volta MEX->GRU->CWB | -- |
| 02/02 | Em casa! | | |

# Por que o México?

Boa pergunta!

# Horário

A cidade do México está no fuso GMT-6, então dependendo se estamos ou não em horário de verão a diferença é de 3h ou 4h para o Brasil.
Nas praias do Caribe esta diferença é de 1h a menos, já que lá é GMT-5.

**Atenção:** Lembrar de acertar o horário dos relógios e celulares para evitar acordar de madrugada com o despertador!

# Dinheiro

O Dólar Americano na época estava R$ 2,80.
O Peso Mexicano (MXN) na casa de câmbio Confidênce estava R$ 0,25.

Levamos ao todo US$ 1500,00 e MXN 300,00 em espécie e US$ 500,00 em VTM.
Os MXN e o VTM eram uma forma de segurança, mas ambos acabaram não sendo necessários.
É muito fácil trocar dólar lá pois existem diversas casas de câmbio por toda parte.

Em Cancún o dólar "é aceito" no comercio, mas em geral pagar com dólar é pagar muito mais caro. (Além de outras malandragens na hora da negociação...)

Curiosamente os melhores valores de câmbio que conseguimos foram nos aeroportos do DF e de Cancún.

O valor "final" do Câmbio foi cerca de R$ 0,14 já incluindo todos os impostos e taxas (comprando dólar no Brasil e trocando por Peso no México).

Sacamos dinheiro do VTM para pagar o hotel em Tulum pois não aceitavam cartão. E utilizamos cartão de crédito apenas para pagar gastos que exigiam pagamento antecipado ou alguma garantia, basicamente hotel e aluguel de carro.

Levamos dinheiro, cartões e documentos naqueles [*money belt*](https://www.google.com.br/search?q=money+belt) para não chamar a atenção. Na maior parte das vezes saíamos apenas com um pouco mais do que o necessário (No máximo uns US$ 200,00), e o resto ficava escondido nos fundos das malas no hotel.
Não tivemos qualquer tipo de problema com relação a roubo, mas também não ficavamos dando sopa!

Obs: Os valores de câmbio já estão com o IOF de 0,38% ou 6,38% inclusos, de acordo com o caso.

**Atenção:** Lembrar de tirar o *money belt* quando for nadar/mergulhar! Assim evita gastar algumas horas secando os documentos, dinheiro e o que mais estiver junto.

# Documentos

[Desde 2013 não é necessário ter visto para ir ao México a passeio (menos de 180 dias). Também não é necessário vacina contra febre amarela.](http://consulmex.sre.gob.mx/riodejaneiro/index.php/perguntas-frequentes)

Ao chegar no México é necessário preencher um formulário informando local de estadia, data de partida prevista, se tiver algum tipo de bagagem declarável e algumas outras informações pessoais.
Com este formulário e o seu passaporte eles fazem algumas consultas nos sistemas (para ver se você não está sendo procurado pela Interpol ou pelo FBI!) e se tudo estiver Ok você recebe um papel que deverá ser guardado até o dia da sua partida. Se não estiver tudo Ok eu não sei o que acontece.
Caso o papel seja extraviado será cobrada uma multa ao deixar o país. (Na época era algo em torno de US$ 200,00)

O meu papel estava junto com o Passaporte quando eu entrei na água com os documentos e não foi danificado, não precisei pagar multa!

# [Transporte](/2016/02/18/transporte.html)

# Atrações

[Plaza Garibaldi](/2016/02/18/plaza-garibaldi.html)

# Hospedagem

Separar por cidade, de preferência na ordem da tabela.

- Vouchers dos hotéis no Dropbox
- Hotel de Tulum foi reservado via Booking/Hoteles.com, não lembro o nome mas era do Italiano..

# Alimentação

Aqui tem muuuita coisa pra colocar! Melhor colocar separado por lugar e em ordem de preferência.

- Tenampas
- El Camelo Jr
- Chaya Maya
- ...

# Lugares

## Museus

## Ruínas

## Cenotes

## Praias

# [Foto 3D!](https://github.com/MikhailKoslowski/MikhailKoslowski.github.io/raw/master/_imgs/mex/3d2.jpg)


text:
<?php

namespace RR\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @Vich\Uploadable
 * @ORM\HasLifecycleCallbacks()
 */
class UserImage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="RR\UserBundle\Entity\User")
     * @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
     */
    private $user;
    // ..... other fields

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTime('now');
        }
    }

    /**
     * @return File
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;
    }

    /**
     * @return string
     */
    public function getImageName()
    {
        return $this->imageName;
    }

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

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return UserImage
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set user
     *
     * @param \RR\UserBundle\Entity\User $user
     *
     * @return UserImage
     */
    public function setUser(\RR\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \RR\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
<?php
    session_start();
    require('../config/config.php');
    require('mysqlCNX.php');
    // base framework
    require(dirname(__FILE__).'/lib/mysql_db.php');
    require(dirname(__FILE__).'/lib/application_controller.php');
    require(dirname(__FILE__).'/lib/model.php');
    require(dirname(__FILE__).'/lib/request.php');
    require(dirname(__FILE__).'/lib/response.php');

    // require /models (Should iterate app/models and auto-include all files there)
    require(dirname(__FILE__).'/app/models/user.php');
    require(dirname(__FILE__).'/app/models/itadmin.php');
    require(dirname(__FILE__).'/app/models/hradmin.php');
    require(dirname(__FILE__).'/app/models/company.php');

    // Fake a database connection using _SESSION
    $dbh = new mySQLDB();


text:
/**
 * Supporting network code for JMS appenders.
 *
 *
Note that you can use JmsQueueReceiver or JmsTopicReceiver as executable main classes to receive log events over
 * JMS (sent via the appropriate JMS appender) that can be subsequently logged according to the configuration given to
 * the running process. Of course, use of these classes as standalone executables are entirely optional and can
 * be used directly in your application (e.g., through your Spring {@code beans.xml} configuration).

 */
package org.apache.logging.log4j.core.net.mom.jms;


text:
<?php
namespace Szyman\ObjectService\Propel;

use Propel\Runtime\Connection\ConnectionInterface;
use Szyman\ObjectService\Service;

final class TransactionFactory implements Service\TransactionFactory
{
    /** @var ConnectionInterface */
    private $con;

    public function __construct(ConnectionInterface $connection)
    {
        $this->con = $connection;
    }

    /** @inheritdoc */
	public function newTransaction()
    {
        return new Transaction($this->con);
    }
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.paintpreview.player;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.base.test.util.CallbackHelper;

/**
 * Tests for the {@link PlayerUserFrustrationDetector} class
 */
@RunWith(BaseRobolectricTestRunner.class)
public class PlayerUserFrustrationDetectorTest {
    @Test
    public void testConsecutiveTapDetection() {
        CallbackHelper detectionCallback = new CallbackHelper();
        PlayerUserFrustrationDetector detector =
                new PlayerUserFrustrationDetector(detectionCallback::notifyCalled);

        final int tapsWindow = PlayerUserFrustrationDetector.CONSECUTIVE_SINGLE_TAP_WINDOW_MS;
        final int tapsCount = PlayerUserFrustrationDetector.CONSECUTIVE_SINGLE_TAP_COUNT;
        long startTime = System.currentTimeMillis();

        // Record |tapsCount| consecutive taps in shorter than |tapsWindow| intervals. This should
        // trigger the detection.
        Assert.assertEquals("Frustration callback shouldn't have been called", 0,
                detectionCallback.getCallCount());
        for (int i = 0; i < tapsCount; i++) {
            detector.recordUnconsumedTap(startTime + i * tapsWindow);
        }
        Assert.assertEquals("Frustration callback should have been called once", 1,
                detectionCallback.getCallCount());

        // A new tap, even if it's within the window, should not trigger the callback.
        detector.recordUnconsumedTap(startTime + tapsCount * tapsWindow);
        Assert.assertEquals("Frustration callback shouldn't have been called", 1,
                detectionCallback.getCallCount());

        // Perform |tapsCount - 1| series of consecutive taps. Each time, delay one of the taps
        // so it's out of the |tapsWindow|.
        // None of these should result in a frustration trigger.
        for (int i = 1; i < tapsCount; i++) {
            // Increment start time so it won't be within a valid window with the previous tap.
            startTime += (tapsCount + 2) * tapsWindow;
            for (int j = 0; j < tapsCount; j++) {
                int delay = i == j ? 10 : 0;
                detector.recordUnconsumedTap(startTime + j * tapsWindow + delay);
            }
            Assert.assertEquals("Frustration callback shouldn't have been called", 1,
                    detectionCallback.getCallCount());
        }

        // Perform a valid tap sequence.
        startTime += (tapsCount + 2) * tapsWindow;
        for (int i = 0; i < tapsCount; i++) {
            detector.recordUnconsumedTap(startTime + i * tapsWindow);
        }
        Assert.assertEquals("Frustration callback should have been called once", 2,
                detectionCallback.getCallCount());
    }
}


text:
package opennlp.tools.formats.letsmt;

import java.io.File;
import java.io.IOException;

import opennlp.tools.cmdline.ArgumentParser;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.StreamFactoryRegistry;
import opennlp.tools.cmdline.TerminateToolException;
import opennlp.tools.cmdline.params.BasicFormatParams;
import opennlp.tools.formats.AbstractSampleStreamFactory;
import opennlp.tools.sentdetect.SentenceSample;
import opennlp.tools.tokenize.DetokenizationDictionary;
import opennlp.tools.tokenize.Detokenizer;
import opennlp.tools.tokenize.DictionaryDetokenizer;
import opennlp.tools.util.ObjectStream;

public class LetsmtSentenceStreamFactory<P> extends AbstractSampleStreamFactory<SentenceSample, P> {

  interface Parameters extends BasicFormatParams {
    @ArgumentParser.ParameterDescription(valueName = "dictionary",
        description = "specifies the file with detokenizer dictionary.")
    @ArgumentParser.OptionalParameter
    File getDetokenizer();
  }

  public static void registerFactory() {
    StreamFactoryRegistry.registerFactory(SentenceSample.class,
        "letsmt", new LetsmtSentenceStreamFactory<>(
        LetsmtSentenceStreamFactory.Parameters.class));
  }

  protected LetsmtSentenceStreamFactory(Class<P> params) {
    super(params);
  }

  @Override
  public ObjectStream<SentenceSample> create(String[] args) {

    Parameters params = ArgumentParser.parse(args, Parameters.class);

    CmdLineUtil.checkInputFile("Data", params.getData());

    LetsmtDocument letsmtDoc = null;
    try {
      letsmtDoc = LetsmtDocument.parse(params.getData());
    } catch (IOException ex) {
      CmdLineUtil.handleCreateObjectStreamError(ex);
    }

    // TODO:
    // Implement a filter stream to remove splits which are not at an eos char

    ObjectStream<SentenceSample> samples = new LetsmtSentenceStream(letsmtDoc);

    if (params.getDetokenizer() != null) {
      try {
        Detokenizer detokenizer = new DictionaryDetokenizer(
            new DetokenizationDictionary(params.getDetokenizer()));

        samples = new DetokenizeSentenceSampleStream(detokenizer, samples);
      } catch (IOException e) {
        throw new TerminateToolException(-1, "Failed to load detokenizer rules!", e);
      }
    }

    return samples;
  }
}


text:
<!DOCTYPE html>

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

    <meta charset="utf-8">

AWS OpsWorks ChefConfiguration Type

Describes the Chef configuration for the AWS::OpsWorks::Stack resource type. For more information, see
                        ChefConfiguration in
                        the AWS OpsWorks Stacks API Reference.

Syntax

JSON

{
  "BerkshelfVersion" : String,
  "ManageBerkshelf" : Boolean
}

YAML

BerkshelfVersion: String
ManageBerkshelf: Boolean

Properties

BerkshelfVersion

The Berkshelf version.

Required: No

Type: String

ManageBerkshelf

Whether to enable Berkshelf.

Required: No

Type: Boolean


text:
package bug_regression_jdk7.javassist.asm;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Woonduk Kang(emeroad)
 */
public class BytecodeVerifyTestClassVisitor extends ClassVisitor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String name;

    public BytecodeVerifyTestClassVisitor(final ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public void visit(final int version, final int access, final String name,
                      final String signature, final String superName,
                      final String[] interfaces) {
        this.name = name;
        super.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public MethodVisitor visitMethod(final int access, final String name,
                                     final String desc, final String signature, final String[] exceptions) {

        MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
        logger.debug("mv:{}", mv);
        logger.debug("name:{}", name);
        logger.debug("desc:{}", desc);
        logger.debug("signature:{}", signature);
        if (name.contains("bytecodeVerifyError")) {
            return new AddIntVariableMethodAdapter(mv, Opcodes.ACC_PUBLIC, name, "()V");
        }
        return mv;
    }
}


text:
function [v_mean, v_space, S] = uncert(avail,miss,iptrn,Cf,D,w)
% uncert.m
% Computes the variance of the space average of the prediction from GraphEM
% Input: avail, miss, iptrn =  pattens of missing values (output of GraphEM)
%        Cf = residual covariance matrix of the model (output of GraphEM)
%              note: must use the unitless C (Cf)!!!
%        D = scale factors for matrix C (output of GraphEM)
%        w = vector of weights used to compute a weighted space average
%        of the temperature field (generally cos(latitude))
% Output: v_mean = variance of the temperature average over time predicted by the
% multivariate normal model.
%         v_space = spatial variance at each time
%         S = covariance

npatterns = length(miss);
nyears = length(iptrn);
ntemp = length(w);  % number of temperature locations
v1 = zeros(npatterns,1);
S1 = cell(npatterns,1);
v_space = zeros(nyears,ntemp);
v_mean  = zeros(nyears,1);

% Compute variance for each pattern of missing values
for i=1:npatterns
    [~,S] = ols(Cf,avail{i},miss{i});

    % Restore original scaling to residual covariance matrix
    pm    = length(miss{i}); % number of missing values in this pattern
    S     = S .* repmat(D(miss{i})', pm, 1) .* repmat(D(miss{i}), 1, pm);

    [ind_i,imiss] = intersect(miss{i},1:ntemp);
    wi = w(ind_i);

    % Restrict S to missing temperature points
    Si = S(imiss, imiss);
    % Si = S{i}(imiss,imiss);                           %
    S1{i} = diag(Si);
    v1(i) = wi.'*Si*wi;
end

% Store the variance for each year
for i=1:nyears
    pati = iptrn(i);
    v_mean(i) = v1(pati);
    [~,~,itemp] = intersect(miss{pati},1:ntemp);
    v_space(i,itemp) = S1{pati};
end

end


text:
package org.encuestame.test.business.service;

import org.encuestame.core.service.imp.IPictureService;
import org.encuestame.core.service.startup.DirectorySetupOperations;
import org.encuestame.persistence.domain.security.UserAccount;
import org.encuestame.test.business.security.AbstractSpringSecurityContext;
import org.encuestame.utils.categories.test.DefaultTest;
import org.encuestame.utils.enums.PictureType;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;

import java.io.File;
import java.util.Locale;

/**
 * Created by jpicado on 04/12/14.
 */
@Category(DefaultTest.class)
public class TestPictureService extends AbstractSpringSecurityContext {

    /**
     *
     */
    @Autowired
    IPictureService pictureService;

    /** {@link org.encuestame.persistence.domain.security.UserAccount}. **/
    private UserAccount secondary;

    /**
     * Mock HttpServletRequest.
     */
    MockHttpServletRequest request;

    /**
     *
     */
    @Before
    public void initData(){
        this.secondary = createUserAccount("juanpicado", createAccount());
        request = new MockHttpServletRequest();
        request.addPreferredLocale(Locale.ENGLISH);
    }

    /**
     *
     * @throws Exception
     */
    @Test
    public void testggetGravatarPicture() throws Exception {
       final String picture = this.pictureService.getAccountUserPicturePath(this.secondary);
       Assert.assertNotNull(picture);
    }

    /**
     *
     * @throws Exception
     */
    @Test
    public void testgetProfilePicture() throws Exception {
        final byte[] t = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.DEFAULT);
        //System.out.println(t);
        Assert.assertNotNull(t);
        final byte[] t1 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.ICON);
        final byte[] t2 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.PREVIEW);
        final byte[] t3 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.PROFILE);
        final byte[] t4 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.THUMBNAIL);
        Assert.assertNotNull(t1);
        Assert.assertNotNull(t2);
        Assert.assertNotNull(t3);
        Assert.assertNotNull(t4);
        this.secondary.setPictureSource(UserAccount.PictureSource.UPLOADED);
        this.getAccountDao().saveOrUpdate(this.secondary);
        new File(DirectorySetupOperations.getHomeDirectory() + "/pictures").mkdirs();
        new File(DirectorySetupOperations.getHomeDirectory() + "/pictures/"+this.secondary.getUid()).mkdirs();
        new File(DirectorySetupOperations.getHomeDirectory() + "/pictures/"+this.secondary.getUid() + "/file_64.jpg").createNewFile();
        final byte[] t5 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.THUMBNAIL);
        Assert.assertNotNull(t5);
        this.secondary.setPictureSource(UserAccount.PictureSource.GRAVATAR);
        this.getAccountDao().saveOrUpdate(this.secondary);
        final byte[] t6 = this.pictureService.getProfilePicture(this.secondary.getUsername(), PictureType.THUMBNAIL);
        Assert.assertNotNull(t6);
    }

    /**
     *
     * @return
     */
    public IPictureService getPictureService() {
        return pictureService;
    }

    /**
     *
     * @param pictureService
     */
    public void setPictureService(IPictureService pictureService) {
        this.pictureService = pictureService;
    }
}


text:
package com.sleepycat.je.cleaner;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.DbInternal;
import com.sleepycat.je.dbi.CursorImpl;
import com.sleepycat.je.dbi.DatabaseImpl;
import com.sleepycat.je.dbi.DbTree;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.dbi.SortedLSNTreeWalker;
import com.sleepycat.je.dbi.SortedLSNTreeWalker.TreeNodeProcessor;
import com.sleepycat.je.log.LogEntryType;
import com.sleepycat.je.log.UtilizationFileReader;
import com.sleepycat.je.tree.LN;
import com.sleepycat.je.tree.MapLN;
import com.sleepycat.je.tree.Node;
import com.sleepycat.je.txn.LockType;
import com.sleepycat.je.utilint.DbLsn;

/**
 * Verify cleaner data structures
 */
public class VerifyUtils {

    private static final boolean DEBUG = false;

    /**
     * Compare the LSNs referenced by a given Database to the lsns held
     * in the utilization profile. Assumes that the database and
     * environment is quiescent, and that there is no current cleaner
     * activity.
     */
    public static void checkLsns(Database db)
        throws DatabaseException {
        checkLsns(DbInternal.dbGetDatabaseImpl(db), System.out);
    }

    /**
     * Compare the lsns referenced by a given Database to the lsns held
     * in the utilization profile. Assumes that the database and
     * environment is quiescent, and that there is no current cleaner
     * activity.
     */
    public static void checkLsns(DatabaseImpl dbImpl,
                                 PrintStream out)
        throws DatabaseException {

        /* Get all the LSNs in the database. */
        GatherLSNs gatherLsns = new GatherLSNs();
        long rootLsn = dbImpl.getTree().getRootLsn();
        List<DatabaseException> savedExceptions =
            new ArrayList<DatabaseException>();

        SortedLSNTreeWalker walker =
            new SortedLSNTreeWalker(dbImpl,
                                    false, // don't set db state
                                    rootLsn,
                                    gatherLsns,
                                    savedExceptions,
				    null);
        walker.walk();

        /* Print out any exceptions seen during the walk. */
        if (savedExceptions.size() > 0) {
            out.println(savedExceptions.size() +
                        " problems seen during tree walk for checkLsns");
            Iterator<DatabaseException> iter = savedExceptions.iterator();
            while (iter.hasNext()) {
                out.println("  " + iter.next());
            }
        }

        Set<Long> lsnsInTree = gatherLsns.getLsns();
        if (rootLsn != DbLsn.NULL_LSN) {
            lsnsInTree.add(rootLsn);
        }

        /* Get all the files used by this database. */
        Iterator<Long> iter = lsnsInTree.iterator();
        Set<Long> fileNums = new HashSet<Long>();

        while (iter.hasNext()) {
            long lsn = iter.next();
            fileNums.add(DbLsn.getFileNumber(lsn));
        }

        /* Gather up the obsolete lsns in these file summary lns */
        iter = fileNums.iterator();
        Set<Long> obsoleteLsns = new HashSet<Long>();
        UtilizationProfile profile =
            dbImpl.getDbEnvironment().getUtilizationProfile();

        while (iter.hasNext()) {
            Long fileNum = iter.next();

            PackedOffsets obsoleteOffsets = new PackedOffsets();
            @SuppressWarnings("unused")
            TrackedFileSummary tfs =
                profile.getObsoleteDetail(fileNum,
                                          obsoleteOffsets,
                                          false /* logUpdate */);
            PackedOffsets.Iterator obsoleteIter = obsoleteOffsets.iterator();
            while (obsoleteIter.hasNext()) {
        	long offset = obsoleteIter.next();
        	Long oneLsn = Long.valueOf(DbLsn.makeLsn(fileNum.longValue(),
                                                         offset));
                obsoleteLsns.add(oneLsn);
                if (DEBUG) {
                    out.println("Adding 0x" +
                                Long.toHexString(oneLsn.longValue()));
                }
            }
        }

        /* Check than none the lsns in the tree is in the UP. */
        boolean error = false;
        iter = lsnsInTree.iterator();
        while (iter.hasNext()) {
            Long lsn = iter.next();
            if (obsoleteLsns.contains(lsn)) {
                out.println("Obsolete LSN set contains valid LSN " +
                            DbLsn.getNoFormatString(lsn.longValue()));
                error = true;
            }
        }

        /*
         * Check that none of the lsns in the file summary ln is in the
         * tree.
         */
        iter = obsoleteLsns.iterator();
        while (iter.hasNext()) {
            Long lsn = iter.next();
            if (lsnsInTree.contains(lsn)) {
                out.println("Tree contains obsolete LSN " +
                            DbLsn.getNoFormatString(lsn.longValue()));
                error = true;
            }
        }

        if (error) {
            throw new DatabaseException("Lsn mismatch");
        }

        if (savedExceptions.size() > 0) {
            throw new DatabaseException("Sorted LSN Walk problem");
        }
    }

    private static class GatherLSNs implements TreeNodeProcessor {
        private Set<Long> lsns = new HashSet<Long>();

        public void processLSN(long childLSN,
			       LogEntryType childType,
			       Node ignore,
			       byte[] ignore2)
	    throws DatabaseException {

            lsns.add(childLSN);
        }

	/* ignore */
        public void processDirtyDeletedLN(long childLsn, LN ln, byte[] lnKey)
	    throws DatabaseException {
        }

	/* ignore */
        public void processDupCount(int ignore) {
	}

        public Set<Long> getLsns() {
            return lsns;
        }
    }

    /**
     * Compare utilization as calculated by UtilizationProfile to utilization
     * as calculated by UtilizationFileReader.  Also check that per-database
     * and per-file utilization match.
     * @throws IllegalStateException if there are mismatches
     */
    public static void verifyUtilization(EnvironmentImpl envImpl,
                                         boolean expectAccurateObsoleteLNCount,
                                         boolean expectAccurateObsoleteLNSize,
                                         boolean expectAccurateDbUtilization)
        throws DatabaseException {

        Map<Long,FileSummary> profileMap = envImpl.getCleaner()
            .getUtilizationProfile()
            .getFileSummaryMap(true);

        /* Flush the log before reading. */
        envImpl.getLogManager().flushNoSync();

        /* Create per-file map of recalculated utilization info. */
        Map<Long,FileSummary> recalcMap;
        try {
            recalcMap = UtilizationFileReader.calcFileSummaryMap(envImpl);
        } catch (IOException e) {
            throw new DatabaseException(e);
        }
        /* Create per-file map derived from per-database utilization. */
        Map<Long,DbFileSummary> dbDerivedMap = null;
        if (expectAccurateDbUtilization) {
            dbDerivedMap = calcDbDerivedUtilization(envImpl);
        }

        /*
         * Loop through each file in the per-file profile, checking it against
         * the recalculated map and database derived maps.
         */
        Iterator<Map.Entry<Long,FileSummary>> i =
            profileMap.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<Long,FileSummary> entry = i.next();
            Long file = entry.getKey();
            String fileStr = file.toString();
            FileSummary profileSummary = entry.getValue();
            FileSummary recalcSummary = recalcMap.remove(file);
            check(fileStr, recalcSummary != null);
            /*
            if (expectAccurateObsoleteLNCount &&
                profileSummary.obsoleteLNCount !=
                recalcSummary.obsoleteLNCount) {
                System.out.println("file=" + file);
                System.out.println("profile=" + profileSummary);
                System.out.println("recalc=" + recalcSummary);
            }
            //*/
            check(fileStr,
                  recalcSummary.totalCount == profileSummary.totalCount);
            check(fileStr,
                  recalcSummary.totalSize == profileSummary.totalSize);
            check(fileStr,
                  recalcSummary.totalINCount == profileSummary.totalINCount);
            check(fileStr,
                  recalcSummary.totalINSize == profileSummary.totalINSize);
            check(fileStr,
                  recalcSummary.totalLNCount == profileSummary.totalLNCount);
            check(fileStr,
                  recalcSummary.totalLNSize == profileSummary.totalLNSize);

            /*
             * Currently we cannot verify obsolete INs because
             * UtilizationFileReader does not count them accurately.
             */
            if (false) {
                check(fileStr,
                      recalcSummary.obsoleteINCount ==
                      profileSummary.obsoleteINCount);
            }

            /*
             * The obsolete LN count/size is inaccurate when a deleted LN is
             * not counted properly by recovery because its parent INs were
             * flushed and the obsolete LN was not found in the tree.
             */
            if (expectAccurateObsoleteLNCount) {
                check(fileStr,
                      recalcSummary.obsoleteLNCount ==
                      profileSummary.obsoleteLNCount);

                /*
                 * The obsoletely LN size is inaccurate when a tree walk is
                 * performed for truncate/remove or an abortLsn is counted by
                 * recovery
                 */
                if (expectAccurateObsoleteLNSize) {
                    check(fileStr,
                          recalcSummary.getObsoleteLNSize() ==
                          profileSummary.obsoleteLNSize);
                }
            }

            /*
             * The per-database and per-file info normally match.  It does not
             * match, and expectAccurateDbUtilization is false, when we have
             * truncated or removed a database, since that database information
             * is now gone.
             */
            if (expectAccurateDbUtilization) {
                DbFileSummary dbSummary =
                    (DbFileSummary) dbDerivedMap.remove(file);
                if (dbSummary == null) {
                    dbSummary = new DbFileSummary();
                }
                check(fileStr,
                      profileSummary.totalINCount == dbSummary.totalINCount);
                check(fileStr,
                      profileSummary.totalLNCount == dbSummary.totalLNCount);
                check(fileStr,
                      profileSummary.totalINSize == dbSummary.totalINSize);
                check(fileStr,
                      profileSummary.totalLNSize == dbSummary.totalLNSize);
                check(fileStr,
                      profileSummary.obsoleteINCount ==
                      dbSummary.obsoleteINCount);
                if (expectAccurateObsoleteLNCount) {
                    check(fileStr,
                          profileSummary.obsoleteLNCount ==
                          dbSummary.obsoleteLNCount);
                    if (expectAccurateObsoleteLNSize) {
                        check(fileStr,
                              profileSummary.obsoleteLNSize ==
                              dbSummary.obsoleteLNSize);
                        check(fileStr,
                              profileSummary.obsoleteLNSizeCounted ==
                              dbSummary.obsoleteLNSizeCounted);
                    }
                }
            }
        }
        check(recalcMap.toString(), recalcMap.isEmpty());
        if (expectAccurateDbUtilization) {
            check(dbDerivedMap.toString(), dbDerivedMap.isEmpty());
        }
    }

    private static void check(String errorMessage, boolean checkIsTrue) {
        if (!checkIsTrue) {
            throw new IllegalStateException(errorMessage);
        }
    }

    /**
     * Adds up the per-file totals from the utilization information for each
     * database to make a total per-file count.
     *
     * @return aggregation of per-file information.
     */
    private static Map<Long,DbFileSummary> calcDbDerivedUtilization
                                               (EnvironmentImpl envImpl)
        throws DatabaseException {

        final Map<Long,DbFileSummary> grandTotalsMap = new HashMap<Long,DbFileSummary>();

        DbTree dbTree = envImpl.getDbTree();

        /* Add in the special id and name database. */
        addDbDerivedTotals(dbTree.getDb(DbTree.ID_DB_ID), grandTotalsMap);
        addDbDerivedTotals(dbTree.getDb(DbTree.NAME_DB_ID), grandTotalsMap);

        /* Walk through all the regular databases. */
        CursorImpl.traverseDbWithCursor(dbTree.getDb(DbTree.ID_DB_ID),
                                        LockType.NONE,
                                        true /*allowEviction*/,
                                        new CursorImpl.WithCursor() {
            public boolean withCursor(CursorImpl cursor,
                                      DatabaseEntry key,
                                      DatabaseEntry data)
                throws DatabaseException {

                MapLN mapLN = (MapLN) cursor.getCurrentLN(LockType.NONE);
                addDbDerivedTotals(mapLN.getDatabase(), grandTotalsMap);
                return true;
            }
        });
        return grandTotalsMap;
    }

    /**
     * Walk through the DbFileSummaryMap associated with a single database and
     * aggregate all the per-file/per db information into a single per-file
     * grandTotals map.
     */
    private static void addDbDerivedTotals
        (DatabaseImpl dbImpl,
         Map<Long,DbFileSummary> grandTotalsMap) {
        Iterator<Map.Entry<Long,DbFileSummary>> entries =
            dbImpl.getDbFileSummaries().entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<Long,DbFileSummary> entry = entries.next();
            Long fileNum = entry.getKey();
            DbFileSummary dbTotals = entry.getValue();
            DbFileSummary grandTotals = grandTotalsMap.get(fileNum);
            if (grandTotals == null) {
                grandTotals = new DbFileSummary();
                grandTotalsMap.put(fileNum, grandTotals);
            }
            grandTotals.add(dbTotals);
        }
    }

}


text:
var _curry2 = require('./internal/_curry2');

/**
 * Wraps a function of any arity (including nullary) in a function that accepts exactly `n`
 * parameters. Unlike `nAry`, which passes only `n` arguments to the wrapped function,
 * functions produced by `arity` will pass all provided arguments to the wrapped function.
 *
 * @func
 * @memberOf R
 * @sig (Number, (* -> *)) -> (* -> *)
 * @category Function
 * @param {Number} n The desired arity of the returned function.
 * @param {Function} fn The function to wrap.
 * @return {Function} A new function wrapping `fn`. The new function is
 *         guaranteed to be of arity `n`.
 * @example
 *
 *      var takesTwoArgs = function(a, b) {
 *        return [a, b];
 *      };
 *      takesTwoArgs.length; //=> 2
 *      takesTwoArgs(1, 2); //=> [1, 2]
 *
 *      var takesOneArg = R.arity(1, takesTwoArgs);
 *      takesOneArg.length; //=> 1
 *      // All arguments are passed through to the wrapped function
 *      takesOneArg(1, 2); //=> [1, 2]
 */
module.exports = _curry2(function(n, fn) {
  switch (n) {
    case 0: return function() {return fn.apply(this, arguments);};
    case 1: return function(a0) {void a0; return fn.apply(this, arguments);};
    case 2: return function(a0, a1) {void a1; return fn.apply(this, arguments);};
    case 3: return function(a0, a1, a2) {void a2; return fn.apply(this, arguments);};
    case 4: return function(a0, a1, a2, a3) {void a3; return fn.apply(this, arguments);};
    case 5: return function(a0, a1, a2, a3, a4) {void a4; return fn.apply(this, arguments);};
    case 6: return function(a0, a1, a2, a3, a4, a5) {void a5; return fn.apply(this, arguments);};
    case 7: return function(a0, a1, a2, a3, a4, a5, a6) {void a6; return fn.apply(this, arguments);};
    case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) {void a7; return fn.apply(this, arguments);};
    case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) {void a8; return fn.apply(this, arguments);};
    case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {void a9; return fn.apply(this, arguments);};
    default: throw new Error('First argument to arity must be a non-negative integer no greater than ten');
  }
});


text:
<!doctype html>

    <title>Code coverage report for src/features/rekit-cmds/DialogPlace.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / src/features/rekit-cmds DialogPlace.js

        33.33%
        Statements
        4/12

        50%
        Branches
        2/4

        14.29%
        Functions
        1/7

        33.33%
        Lines
        4/12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

1x

1x
1x
1x

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { autobind } from 'core-decorators';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Modal } from 'antd';
import * as actions from './redux/actions';
import { CmdForm, cmdSuccessNotification, LogViewerDialog } from './';

const displayName = _.flow(_.lowerCase, _.upperFirst);

export class DialogPlace extends Component {
  static propTypes = {
    rekitCmds: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
  };

  @autobind
  handleCmdDialogDone(dialogType) {
    this.props.actions.hideDialog(dialogType);
  }

  @autobind
  handleCmdSuccess(dialogType) {
    this.props.actions.hideCmdDialog(dialogType);
    const { args } = this.props.rekitCmds.execCmdResult;
    cmdSuccessNotification(args, this.props.actions.showCmdDialog);
  }

  render() {
    const { rekitCmds } = this.props;
    const { hideCmdDialog } = this.props.actions;
    return (
      <div className="rekit-cmds-dialog-place">
        {rekitCmds.cmdDialogVisible &&
          <Modal
            visible
            maskClosable={false}
            footer=""
            wrapClassName="rekit-cmds-cmd-dialog"
            title={displayName(rekitCmds.cmdArgs.type)}
            onClose={() => hideCmdDialog('cmd')}
            {...this.props}
          >
            <CmdForm
              onCancel={() => hideCmdDialog('cmd')}
              onDone={() => this.handleCmdSuccess('cmd')}
            />
          </Modal>
        }
        {rekitCmds.logViewerDialogVisible &&
          <LogViewerDialog onClose={() => hideCmdDialog('logViewer')} />
        }
      </div>
    );
  }
}

/* istanbul ignore next */
function mapStateToProps(state) {
  return {
    rekitCmds: state.rekitCmds,
  };
}

/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ ...actions }, dispatch)
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(DialogPlace);

  Code coverage
  generated by istanbul at Mon Jan 22 2018 13:11:26 GMT+0800 (CST)


text:
#ifndef __OJ_READER_H__
#define __OJ_READER_H__

typedef struct _Reader {
    char	base[0x00001000];
    char	*head;
    char	*end;
    char	*tail;
    char	*read_end;	/* one past last character read */
    char	*pro;		/* protection start, buffer can not slide past this point */
    char	*str;		/* start of current string being read */
    int		line;
    int		col;
    int		free_head;
    int		(*read_func)(struct _Reader *reader);
    union {
	int		fd;
	VALUE		io;
	const char	*in_str;
    };
} *Reader;

extern void	oj_reader_init(Reader reader, VALUE io, int fd);
extern int	oj_reader_read(Reader reader);

static inline char
reader_get(Reader reader) {
    //printf("*** drive get from '%s'  from start: %ld	buf: %p	 from read_end: %ld\n", reader->tail, reader->tail - reader->head, reader->head, reader->read_end - reader->tail);
    if (reader->read_end <= reader->tail) {
	if (0 != oj_reader_read(reader)) {
	    return '\0';
	}
    }
    if ('\n' == *reader->tail) {
	reader->line++;
	reader->col = 0;
    }
    reader->col++;

    return *reader->tail++;
}

static inline void
reader_backup(Reader reader) {
    reader->tail--;
    reader->col--;
    if (0 >= reader->col) {
	reader->line--;
	// allow col to be negative since we never backup twice in a row
    }
}

static inline void
reader_protect(Reader reader) {
    reader->pro = reader->tail;
    reader->str = reader->tail; // can't have str before pro
}

static inline void
reader_release(Reader reader) {
    reader->pro = 0;
}

/* Starts by reading a character so it is safe to use with an empty or
 * compacted buffer.
 */
static inline char
reader_next_non_white(Reader reader) {
    char	c;

    while ('\0' != (c = reader_get(reader))) {
	switch(c) {
	case ' ':
	case '\t':
	case '\f':
	case '\n':
	case '\r':
	    break;
	default:
	    return c;
	}
    }
    return '\0';
}

/* Starts by reading a character so it is safe to use with an empty or
 * compacted buffer.
 */
static inline char
reader_next_white(Reader reader) {
    char	c;

    while ('\0' != (c = reader_get(reader))) {
	switch(c) {
	case ' ':
	case '\t':
	case '\f':
	case '\n':
	case '\r':
	case '\0':
	    return c;
	default:
	    break;
	}
    }
    return '\0';
}

static inline int
reader_expect(Reader reader, const char *s) {
    for (; '\0' != *s; s++) {
	if (reader_get(reader) != *s) {
	    return -1;
	}
    }
    return 0;
}

static inline void
reader_cleanup(Reader reader) {
    if (reader->free_head && 0 != reader->head) {
	xfree(reader->head);
	reader->head = 0;
	reader->free_head = 0;
    }
}

static inline int
is_white(char c) {
    switch(c) {
    case ' ':
    case '\t':
    case '\f':
    case '\n':
    case '\r':
	return 1;
    default:
	break;
    }
    return 0;
}

#endif /* __OJ_READER_H__ */


text:
package com.tenable.io.api.agentGroups;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tenable.io.api.ApiWrapperBase;
import com.tenable.io.api.agentGroups.models.AgentGroup;
import com.tenable.io.core.exceptions.TenableIoException;
import com.tenable.io.core.services.AsyncHttpService;
import com.tenable.io.core.services.HttpFuture;
import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.List;

public class AgentGroupsApi extends ApiWrapperBase {
    private static int DEFAULT_SCANNER_ID = 1;

    /**
     * Instantiates a new Agent groups api.
     *
     * @param asyncHttpService the async http service
     * @param apiScheme        the api scheme
     * @param ApiHost          the api host
     */
    public AgentGroupsApi( AsyncHttpService asyncHttpService, String apiScheme, String ApiHost ) {
        super( asyncHttpService, apiScheme, ApiHost );
    }

    /**
     * Returns the agent groups for the default scanner.
     *
     * @return the agent groups for the default scanner
     * @throws TenableIoException the tenable IO exception
     */
    public List<AgentGroup> list() throws TenableIoException {
        return list( DEFAULT_SCANNER_ID );
    }

    /**
     * Returns the agent groups for the given scanner.
     *
     * @param scannerId The id of the scanner to query for agent groups.
     * @return the agent groups for the given scanner
     * @throws TenableIoException the tenable IO exception
     */
    protected List<AgentGroup> list( int scannerId ) throws TenableIoException {
        HttpFuture httpFuture = asyncHttpService.doGet( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups" ).build() );
        return httpFuture.getAsType( new TypeReference<List<AgentGroup>>() {}, "groups" );
    }

    /**
     * Details agent group.
     *
     * @param groupId the group id
     * @return the agent group
     * @throws TenableIoException the tenable io exception
     */
    public AgentGroup details( int groupId ) throws TenableIoException {
        return details( DEFAULT_SCANNER_ID, groupId, new ArrayList<NameValuePair>() );
    }

    /**
     * Returns details for the given agent group.
     *
     * @param groupId   The id of the agent group to query
     * @param filtering the filtering
     * @return details for the given agent group
     * @throws TenableIoException the tenable IO exception
     */
    public AgentGroup details( int groupId, List<NameValuePair> filtering ) throws TenableIoException {
        return details( DEFAULT_SCANNER_ID, groupId, filtering );
    }

    /**
     * Returns details for the given agent group.
     *
     * @param scannerId The id of the scanner
     * @param groupId   The id of the agent group to query
     * @param filtering the filtering
     * @return details for the given agent group
     * @throws TenableIoException the tenable IO exception
     */
    protected AgentGroup details( int scannerId, int groupId, List<NameValuePair> filtering ) throws TenableIoException {
        HttpFuture httpFuture = asyncHttpService.doGet( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups/" + groupId ).addParameters( filtering ).build() );
        return httpFuture.getAsType( AgentGroup.class );
    }

    /**
     * Deletes an agent from the given agent group.
     *
     * @param groupId The id of the agent group.
     * @param agentId The id of the agent to remove.
     * @throws TenableIoException the tenable IO exception
     */
    public void deleteAgent( int groupId, int agentId ) throws TenableIoException {
        deleteAgent( DEFAULT_SCANNER_ID, groupId, agentId );
    }

    /**
     * Deletes an agent from the given agent group.
     *
     * @param scannerId The id of the scanner.
     * @param groupId   The id of the agent group.
     * @param agentId   The id of the agent to remove.
     * @throws TenableIoException the tenable IO exception
     */
    protected void deleteAgent( int scannerId, int groupId, int agentId ) throws TenableIoException {
        HttpFuture httpFuture = asyncHttpService.doDelete( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups/" + groupId + "/agents/" + agentId ).build() );
        httpFuture.get();
    }

    /**
     * Deletes an agent group from the default scanner.
     *
     * @param groupId The id of the agent group to delete.
     * @throws TenableIoException the tenable IO exception
     */
    public void delete( int groupId ) throws TenableIoException {
        delete( DEFAULT_SCANNER_ID, groupId );
    }

    /**
     * Deletes an agent group from the given scanner.
     *
     * @param scannerId The id of the scanner.
     * @param groupId   The id of the agent group to delete.
     * @throws TenableIoException the tenable IO exception
     */
    protected void delete( int scannerId, int groupId ) throws TenableIoException {
        HttpFuture httpFuture = asyncHttpService.doDelete( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups/" + groupId ).build() );
        httpFuture.get();
    }

    /**
     * Creates an agent group on the default scanner.
     *
     * @param name The name of the agent group.
     * @return the agent group
     * @throws TenableIoException the tenable IO exception
     */
    public AgentGroup create( String name ) throws TenableIoException {
        return create( DEFAULT_SCANNER_ID, name );
    }

    /**
     * Creates an agent group on the given scanner.
     *
     * @param scannerId The id of the scanner to add the agent group to.
     * @param name      The name of the agent group.
     * @return the agent group
     * @throws TenableIoException the tenable IO exception
     */
    protected AgentGroup create( int scannerId, String name ) throws TenableIoException {
        CreateAgentGroupRequest request = new CreateAgentGroupRequest();
        request.setName( name );
        HttpFuture httpFuture = asyncHttpService.doPost( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups" ).build(), request );
        return httpFuture.getAsType( AgentGroup.class );
    }

    /**
     * Changes the name of the given agent group.
     *
     * @param groupId The id of the agent group to change
     * @param name    The name for the agent group
     * @throws TenableIoException the tenable IO exception
     */
    public void configure( int groupId, String name ) throws TenableIoException {
        configure( DEFAULT_SCANNER_ID, groupId, name );
    }

    /**
     * Changes the name of the given agent group.
     *
     * @param scannerId The id of the scanner.
     * @param groupId   The id of the agent group to change
     * @param name      The name for the agent group
     * @throws TenableIoException the tenable IO exception
     */
    protected void configure( int scannerId, int groupId, String name ) throws TenableIoException {
        ConfigureAgentGroupRequest request = new ConfigureAgentGroupRequest();
        request.setName( name );
        HttpFuture httpFuture = asyncHttpService.doPut( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups/" + groupId ).build(), request );
        httpFuture.get();
    }

    /**
     * Adds an agent to the given agent group
     *
     * @param groupId The id of the agent group
     * @param agentId The id of the agent to add
     * @throws TenableIoException the tenable IO exception
     */
    public void addAgent( int groupId, int agentId ) throws TenableIoException {
        addAgent( DEFAULT_SCANNER_ID, groupId, agentId );
    }

    /**
     * Adds an agent to the given agent group
     *
     * @param scannerId The id of the scanner
     * @param groupId   The id of the agent group
     * @param agentId   The id of the agent to add
     * @throws TenableIoException the tenable IO exception
     */
    protected void addAgent( int scannerId, int groupId, int agentId ) throws TenableIoException {
        HttpFuture httpFuture = asyncHttpService.doPut( createBaseUriBuilder( "/scanners/" + scannerId +
                "/agent-groups/" + groupId + "/agents/" + agentId ).build(), null );
        httpFuture.get();
    }

    private class CreateAgentGroupRequest {
        private String name;

        /**
         * Gets name.
         *
         * @return the name
         */
        public String getName() {
            return name;
        }

        /**
         * Sets name.
         *
         * @param name the name
         */
        public void setName( String name ) {
            this.name = name;
        }
    }

    private class ConfigureAgentGroupRequest {
        private String name;

        /**
         * Gets name.
         *
         * @return the name
         */
        public String getName() {
            return name;
        }

        /**
         * Sets name.
         *
         * @param name the name
         */
        public void setName( String name ) {
            this.name = name;
        }
    }

}


text:
package pg

import (
	"io"
	"net"

	"gopkg.in/pg.v5/internal"
)

var (
	ErrNoRows    = internal.ErrNoRows
	ErrMultiRows = internal.ErrMultiRows

	errSSLNotSupported = internal.Errorf("pg: SSL is not enabled on the server")

	errClosed         = internal.Errorf("pg: database is closed")
	errTxDone         = internal.Errorf("pg: transaction has already been committed or rolled back")
	errStmtClosed     = internal.Errorf("pg: statement is closed")
	errListenerClosed = internal.Errorf("pg: listener is closed")
)

type Error interface {
	Field(byte) string
	IntegrityViolation() bool
}

var _ Error = (*internal.PGError)(nil)

func isBadConn(err error, allowTimeout bool) bool {
	if err == nil {
		return false
	}
	if _, ok := err.(internal.Error); ok {
		return false
	}
	if pgErr, ok := err.(Error); ok && pgErr.Field('S') != "FATAL" {
		return false
	}
	if allowTimeout {
		if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
			return false
		}
	}
	return true
}

func isNetworkError(err error) bool {
	if err == io.EOF {
		return true
	}
	_, ok := err.(net.Error)
	return ok
}


text:
@echo off
rem Copyright 1999-2018 Alibaba Group Holding Ltd.
rem Licensed under the Apache License, Version 2.0 (the "License");
rem you may not use this file except in compliance with the License.
rem You may obtain a copy of the License at
rem
rem      http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
if not exist "%JAVA_HOME%\bin\jps.exe" echo Please set the JAVA_HOME variable in your environment, We need java(x64)! jdk8 or later is better! & EXIT /B 1

setlocal

set "PATH=%JAVA_HOME%\bin;%PATH%"

echo killing nacos server

for /f "tokens=1" %%i in ('jps -m ^| find "nacos.nacos"') do ( taskkill /F /PID %%i )

echo Done!


text:
"""Package version and other metadata"""
__author__ = 'ThreatConnect (support@threatconnect.com)'
__author_email__ = 'support@threatconnect.com'
__description__ = 'ThreatConnect Exchange App Framework'
__license__ = 'Apache License, Version 2'
__package_name__ = 'tcex'
__url__ = 'https://github.com/ThreatConnect-Inc/tcex'
__version__ = '3.0.5'
__download_url__ = f'https://github.com/ThreatConnect-Inc/tcex/tarball/{__version__}'