text:
enum ConvTensorLayout
{
    NCHW,
    NHWC,
    CHWN,
    NCHWc,
    NHWCc
};

template <typename... InDesc,
          typename... WeiDesc,
          typename ConvStrides,
          typename ConvDilations,
          typename LeftPads,
          typename RightPads>
constexpr auto get_convolution_output_default_4d_tensor_descriptor(
    const ck::TensorDescriptor<InDesc...>& in_desc,
    const ck::TensorDescriptor<WeiDesc...>& wei_desc,
    const ConvStrides& conv_strides,
    const ConvDilations conv_dilations,
    const LeftPads& left_pads,
    const RightPads& right_pads)
{
    using namespace ck;

    constexpr auto I0 = Number<0>{};
    constexpr auto I1 = Number<1>{};
    constexpr auto I2 = Number<2>{};
    constexpr auto I3 = Number<3>{};

    assert(in_desc.GetNumOfDimension() == 4);
    assert(wei_desc.GetNumOfDimension() == 4);
    assert(in_desc.GetLength(I1) == wei_desc.GetLength(I1));

    const auto N  = in_desc.GetLength(I0);
    const auto Hi = in_desc.GetLength(I2);
    const auto Wi = in_desc.GetLength(I3);

    const auto K = wei_desc.GetLength(I0);
    const auto Y = wei_desc.GetLength(I2);
    const auto X = wei_desc.GetLength(I3);

    const auto LeftPadH = left_pads[I0];
    const auto LeftPadW = left_pads[I1];

    const auto RightPadH = right_pads[I0];
    const auto RightPadW = right_pads[I1];

    const auto YEff = (Y - I1) * conv_dilations[I0] + I1;
    const auto XEff = (X - I1) * conv_dilations[I1] + I1;

    const auto Ho = (Hi + LeftPadH + RightPadH - YEff) / conv_strides[I0] + I1;
    const auto Wo = (Wi + LeftPadW + RightPadW - XEff) / conv_strides[I1] + I1;

    return make_naive_tensor_descriptor_packed(make_tuple(N, K, Ho, Wo));
}

template <class InDesc, class WeiDesc, class OutDesc>
constexpr std::size_t
calculate_convolution_flops(const InDesc&, const WeiDesc& wei_desc, const OutDesc& out_desc)
{
    using namespace ck;

    constexpr auto I0 = Number<0>{};
    constexpr auto I1 = Number<1>{};
    constexpr auto I2 = Number<2>{};
    constexpr auto I3 = Number<3>{};

    const index_t N  = out_desc.GetLength(I0);
    const index_t K  = out_desc.GetLength(I1);
    const index_t Ho = out_desc.GetLength(I2);
    const index_t Wo = out_desc.GetLength(I3);

    const index_t C = wei_desc.GetLength(I1);
    const index_t Y = wei_desc.GetLength(I2);
    const index_t X = wei_desc.GetLength(I3);

    return std::size_t(2) * N * K * Ho * Wo * C * Y * X;
}

#endif


text:
<?php
class xyb_test_model extends core_store{

	public function getOne($where){
		return $this->where($where)->select();
	}

    public function insertOne(){
	    $data =array(
	        array('val' => 123,'content' => 'abc'),
            array('val' => 124,'content' => 'abc'),
            array('val' => 125,'content' => 'abc'),
        );
        return $this->save($data);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package dynamiccertificates

import (
	"bytes"
)

// certKeyContent holds the content for the cert and key
type certKeyContent struct {
	cert []byte
	key  []byte
}

func (c *certKeyContent) Equal(rhs *certKeyContent) bool {
	if c == nil || rhs == nil {
		return c == rhs
	}

	return bytes.Equal(c.key, rhs.key) && bytes.Equal(c.cert, rhs.cert)
}

// sniCertKeyContent holds the content for the cert and key as well as any explicit names
type sniCertKeyContent struct {
	certKeyContent
	sniNames []string
}

func (c *sniCertKeyContent) Equal(rhs *sniCertKeyContent) bool {
	if c == nil || rhs == nil {
		return c == rhs
	}

	if len(c.sniNames) != len(rhs.sniNames) {
		return false
	}

	for i := range c.sniNames {
		if c.sniNames[i] != rhs.sniNames[i] {
			return false
		}
	}

	return c.certKeyContent.Equal(&rhs.certKeyContent)
}


text:
function printUser(user) {
	print("User: " + user.name);
	print("Pois: " + pois.size());
}


text:
require "json"

class E2E
  class << self
    def run?
      # Only run end-to-end tests when E2E environment variable is set to TRUE
      ENV["E2E"] == "true"
    end

    def check
      if @url.nil?
        test_dir = ENV["TEST_DIR"]

        if test_dir.nil?
          # we are missing arguments to deploy to e2e
          raise "cannot run e2e tests - missing required test_dir"
        end

        if @attempted
          # we've tried to run the tests and failed
          raise "cannot run e2e tests - deployment failed"
        end

        @attempted = true
        build_id = ENV["BUILD_ID"]
        deploy test_dir, build_id
      end
    end

    def deploy test_dir, build_id = nil
      build_id ||= rand 1000..9999

      test_name = versionize test_dir
      version = "#{test_name}-#{build_id}"

      # read in our credentials file
      key_path = File.expand_path ENV["GOOGLE_APPLICATION_CREDENTIALS"], __FILE__
      key_file = File.read key_path
      key_json = JSON.parse key_file

      account_name = key_json["client_email"]
      project_id = ENV["E2E_GOOGLE_CLOUD_PROJECT"]

      # authenticate with gcloud using our credentials file
      exec "gcloud config set project #{project_id}"
      exec "gcloud config set account #{account_name}"

      # deploy this test_dir to gcloud
      # try 3 times in case of intermittent deploy error
      app_yaml_path = File.expand_path "../../#{test_dir}/app.yaml", __FILE__
      (0..3).each do |_attempt|
        exec "gcloud app deploy #{app_yaml_path} --version=#{version} -q --no-promote"
        break if $CHILD_STATUS.to_i.zero?
      end

      # if status is not 0, we tried 3 times and failed
      if $CHILD_STATUS.to_i != 0
        output "Failed to deploy to gcloud"
        return $CHILD_STATUS.to_i
      end

      # sleeping 10 to ensure URL is callable
      sleep 10

      # run the specs for the step, but use the remote URL
      @url = "https://#{version}-dot-#{project_id}.appspot.com"

      # return 0, no errors
      0
    end

    def cleanup test_dir, build_id = nil
      return nil unless ENV["E2E"]
      # determine build number
      build_id ||= ENV["BUILD_ID"]
      if build_id.nil?
        output "you must pass a build ID or define ENV[\"BUILD_ID\"]"
        return 1
      end

      # run gcloud command
      test_name = versionize test_dir
      exec "gcloud app versions delete #{test_name}-#{build_id} -q"

      # return the result of the gcloud delete command
      if $CHILD_STATUS.to_i != 0
        output "Failed to delete e2e version"
        return $CHILD_STATUS.to_i
      end

      # return 0, no errors
      0
    end

    def versionize name
      version_name = name.tr "^A-Za-z0-9", ""
      name_length  = 11

      version_name[-name_length, name_length] || version_name
    end

    def url
      return unless run?
      check
      @url
    end

    def exec cmd
      output "> #{cmd}"
      output `#{cmd}`
    end

    def output line
      puts line
    end
  end
end


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'emberui',

  included: function(app) {
    this._super.included(app);

    app.import(app.bowerDirectory + '/moment/moment.js');
    app.import(app.bowerDirectory + '/twix/bin/twix.js');
  }
};


text:
youtube iOS app template written in swift 3.

Fully working video player, and animations

Thanks to Brian Voong for helping me

Follow @buildthatapp


text:
class Admin::MainController < AdminController
  before_action :authenticate_user!
  layout "admin"

  def index
  end

  def options
  end
end


text:
=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=cut

use strict;
use warnings;

use Getopt::Long;
use DBH;

use Bio::EnsEMBL::Mapper::RangeRegistry;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Variation::DBSQL::DBAdaptor;
use ImportUtils qw(debug);

my ($TMP_DIR, $TMP_FILE); #global variables for the tmp files and folder
my $range_registry = []; #reference to an array containing an rr for each of the possible levels (from 1-6)
#hash that, for a given individual_name, returns the individual_id in the database, if present. The last 4 samples are defined individuals in dbSNP
#with a predefined id that do not change
my %individual_id = ();
my ($chost, $cport, $cdbname, $cuser, $cpass,
    $vhost, $vport, $vdbname, $vuser, $vpass,
    $read_file, $max_level,
    $ind_file);

  GetOptions('chost=s'     => \$chost,
             'cuser=s'     => \$cuser,
             'cpass=s'     => \$cpass,
             'cport=i'     => \$cport,
             'cdbname=s'   => \$cdbname,
	     'vhost=s'     => \$vhost,
             'vuser=s'     => \$vuser,
             'vpass=s'     => \$vpass,
             'vport=i'     => \$vport,
             'vdbname=s'   => \$vdbname,
             'tmpdir=s'    => \$ImportUtils::TMP_DIR,
             'tmpfile=s'   => \$ImportUtils::TMP_FILE,
	     'readfile=s'  => \$read_file,
	     'maxlevel=i'  => \$max_level,
	     'indfile=s'   => \$ind_file);

#added default options
$chost    ||= 'ecs2';
$cuser    ||= 'ensro';
$cport    ||= 3364;

usage('-vdbname argument is required') if(!$vdbname);
usage('-cdbname argument is required') if(!$cdbname);
usage('-readfile argument is required (name of file with read information)') if (!$read_file);
usage('-maxlevel argument is required (max level coverage calculated)') if (!$max_level);

my $dbCore = Bio::EnsEMBL::DBSQL::DBAdaptor->new
    (-host   => $chost,
     -user   => $cuser,
     -pass   => $cpass,
     -port   => $cport,
     -dbname => $cdbname);

my $dbVar = Bio::EnsEMBL::Variation::DBSQL::DBAdaptor->new
    (-host   => $vhost,
     -user   => $vuser,
     -pass   => $vpass,
     -port   => $vport,
     -dbname => $vdbname
     );

$TMP_DIR  = $ImportUtils::TMP_DIR;
$TMP_FILE = $ImportUtils::TMP_FILE;

if ($ind_file)
{
    open IND, $ind_file;

    my ($ind_name, $ind_id);

    foreach my $ind_line (<IND>)
    {
        chomp $ind_line;

        ($ind_name, $ind_id) = split /\t/, $ind_line;

        $individual_id{$ind_name} = $ind_id;
    }

    close IND;
}

&load_individuals($dbVar,\%individual_id); #first of all, load the hash with the individual_id
&initialize_range_registry($range_registry, $max_level);
my $pair; #reference to an array with id,start,end format
$read_file =~ /^.*\/(.*)\.mapped$/;  #extract the chromosome from the file name
my $region = $1;print "the region is $region\n";
my $individuals = {}; #reference to a hash containing all individuals present in the chromosome
open IN, "$read_file" or die "Could not open file $read_file with read information in the format seq_region_id\tstart\tend:$!\n";
while (<IN>){
    chomp;  #remove the last \n
    #line format
    #LIB     ID_read start   end

    #NA17109 7495470 1833    2533
    #TSC     8093917 617     957
    ($pair) = [split /\t/];
#    splice @{$pair},1,1;    #we need to get rid of the second column, ID_read
    if ($pair->[0] eq ''){$pair->[0] = 'Unknown'}
    &register_range_level($range_registry,$pair,1,$individuals,$max_level);
}
close IN;

#get the dbID for the region where getting the reads
my $slice_adaptor = $dbCore->get_SliceAdaptor;
my $slice = $slice_adaptor->fetch_by_region('toplevel',$region);
my $seq_region_id = $slice->get_seq_region_id();

&import_data(1,$range_registry,"read_coverage",$individuals,$seq_region_id,\%individual_id);
&import_data($max_level,$range_registry,"read_coverage",$individuals,$seq_region_id,\%individual_id);
&update_meta_table($dbVar,$max_level);

debug("File $read_file finished");

sub initialize_range_registry{
    my $range_registry = shift;
    my $max_level = shift;
    foreach my $level (1..$max_level){
	$range_registry->[$level] = Bio::EnsEMBL::Mapper::RangeRegistry->new();
    }

    return;
}

#for a given range and the one covered, returns the inverted
sub invert_pair{
    my $range = shift; #initial range of the array
    my $pairs = shift; #listref with the pairs that have been added to the range

    my @inverted_pairs;
    my $inverted;

    my $rr = Bio::EnsEMBL::Mapper::RangeRegistry->new();

    foreach my $pair (@{$pairs}){
	$rr->check_and_register(1,$pair->[0],$pair->[1]);
    }
    return $rr->check_and_register(1,$range->[0],$range->[1]); #register again the range
}

sub register_range_level{
    my $range_registry = shift;
    my $range = shift;
    my $level = shift;
    my $individuals = shift;
    my $max_level = shift;

    my $individual_name = shift @{$range}; #get the individual from the array
    return if ($level > $max_level);
    $individuals->{$individual_name}++;
    my $rr = $range_registry->[$level];
    my $pair = $rr->check_and_register($individual_name,$range->[0],$range->[1]);
    my $pair_inverted = &invert_pair($range,$pair);
    return if (!defined $pair_inverted);
    foreach my $inverted_range (@{$pair_inverted}){
	unshift @{$inverted_range},$individual_name; #add again the name of the individual
	&register_range_level($range_registry,$inverted_range,$level+1,$individuals,$max_level);
    }
}

#loads a table in the database with the read coverage data
sub import_data{
    my $coverage_level = shift;
    my $range_registry = shift;
    my $table = shift;
    my $individuals = shift; #reference to a hash containing the individuals in the chromosome
    my $seq_region_id = shift;
    my $individual_id = shift;

    open FH,">>$TMP_DIR/$TMP_FILE";
    foreach my $individual_name (keys %{$individuals}){
	if ($individual_name ne '' && defined $range_registry->[$coverage_level]->get_ranges($individual_name)){
	    foreach my $range (@{$range_registry->[$coverage_level]->get_ranges($individual_name)}){
		print FH join("\t",$seq_region_id,$range->[0],$range->[1],$coverage_level,$individual_id->{$individual_name}),"\n";
	    }
	}
    }
    close FH;
}

#will be necessary to load the hash with the relation individual_name => individual_id at the beginning of the script. Some of the individuals in
#Sanger data are already defined in the database, and the ID is permanent. Others, will be necessary to be added (if not already) in the database
sub load_individuals{
    my $dbVar = shift;
    my $individual_id = shift;

    #first, get the individuals that need to be loaded from the database
    foreach my $individual_name (keys %{$individual_id}){
	#only load ones without individual_id
	if ($individual_id->{$individual_name} eq ''){
	    my $individualAdaptor = $dbVar->get_IndividualAdaptor();
	    my $individual = ($individualAdaptor->fetch_all_by_name($individual_name))->[0];
	    my ($sample_id);
	    #the individual is not in the database, will need to create it
	    if (!defined $individual){
		#insert the sample
		$dbVar->dbc()->do(qq{INSERT INTO sample (name,description) VALUES ("$individual_name",'Individuals used to get read information')});
		$sample_id = $dbVar->dbc()->db_handle->{'mysql_insertid'}; #get the id inserted
		#insert the individual
		$dbVar->dbc()->do(qq{INSERT INTO individual (sample_id,gender) VALUES ("$sample_id",'Unknown')});
		#get the population. We will used Unknown, since the origin it is not clear
		my $population_adaptor = $dbVar->get_PopulationAdaptor();
		my $population = $population_adaptor->fetch_by_name('UNKNOWN');
		my $population_id = $population->dbID();
		#insert the relation individual-population
		$dbVar->dbc()->do(qq{INSERT INTO individual_population (individual_sample_id,population_sample_id) VALUES ("$sample_id","$population_id")});
	    }
	    else{
		$sample_id = $individual->dbID();
	    }
	    $individual_id->{$individual_name} = $sample_id;
	}
    }
}

#
# updates the meta table
#
sub update_meta_table {
  my $dbVar  = shift;
  my $max_level = shift;

  #find out if the meta table has been updated with the coverage levels calculated
  my $rca = $dbVar->get_ReadCoverageAdaptor();
  my $levels = $rca->get_coverage_levels();

  my $sth = $dbVar->dbc->prepare
    ('INSERT INTO meta (meta_key,meta_value) VALUES (?,?)');

  foreach (1,$max_level){
      my $cur_level = $_;
      if ((grep {$cur_level eq $_} @{$levels}) == 0){
	  $sth->execute('read_coverage.coverage_level',$_);
      }
  }

  $sth->finish();

  return;
}

sub usage {
  my $msg = shift;

  print STDERR <<EOF;

usage: perl read_coverage.pl <options>

options:
    -chost <hostname>    hostname of core Ensembl MySQL database (default = ecs2)
    -cuser <user>        username of core Ensembl MySQL database (default = ensro)
    -cpass <pass>        password of core Ensembl MySQL database
    -cport <port>        TCP port of core Ensembl MySQL database (default = 3364)
    -cdbname <dbname>    dbname of core Ensembl MySQL database
    -vhost <hostname>    hostname of variation MySQL database to write to
    -vuser <user>        username of variation MySQL database to write to (default = ensadmin)
    -vpass <pass>        password of variation MySQL database to write to
    -vport <port>        TCP port of variation MySQL database to write to (default = 3306)
    -vdbname <dbname>    dbname of variation MySQL database to write to
    -tmpdir <dir>        temp directory to use (with lots of space!)
    -tmpfile <filename>  name of temp file to use
    -readfile <filename> name of file with read information
    -maxlevel <number>   max level of coverage calculated
EOF

  die("\n$msg\n\n");
}


text:
+function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['ember'], function(Ember) { return factory(Ember); });
  } else if (typeof exports === 'object') {
    module.exports = factory(require('ember'));
  } else {
    root.ic = root.ic || {};
    root.ic.MenuComponent = factory(Ember);
  }
}(this, function(Ember) {

  var MenuComponent = Ember.Component.extend({

    tagName: 'ic-menu',

    classNameBindings: ['isOpen:is-open:is-closed'],

    list: null,

    listTrigger: null,

    isOpen: function() {
      return this.get('list.isOpen');
    }.property('list.isOpen'),

    registerList: function(list) {
      this.set('list', list);
    },

    registerTrigger: function(trigger) {
      this.set('listTrigger', trigger);
    },

    openList: function() {
      this.get('list').open();
    }

  });

  return MenuComponent;

});


text:
<?php
$fromusername = $_GET['fromusername'];
$desc = $_GET['desc'];
$part_name=$_GET['partname'];
$creation_date=$_GET['creationdate'];
$part_type=$_GET['parttype'];
$results=$_GET['results'];
$status=$_GET['status'];
$author=$_GET['author'];

include "top.html";

$addtime=0;
function addfirst($sql,$add){
	$sql=$sql.$add;
	$addtime++;
	return $sql;
}

function addsql($sql,$add){
	$sql=$sql."AND".$add;
	return $sql;
}

if(1){    //search all
	$con = mysql_connect('localhost','root','root');
	if (!$con){
		die('Could not connect: ' . mysql_error());
	}

	$sql = "SELECT *
FROM  `parts_bbdb`.`haowanbu`
WHERE (
CONVERT(  `part_name` USING utf8 ) LIKE  '%".$part_name."%'
AND  CONVERT(`part_type` USING utf8) LIKE '%".$part_type."%'
AND  CONVERT(`description` USING utf8) LIKE '%".$desc."%'
AND  CONVERT(`creation_date` USING utf8) LIKE '%".$creation_date."%'
AND  CONVERT(`results` USING utf8) LIKE '%".$results."%'
AND  CONVERT(`status` USING utf8) LIKE '%".$status."%'
AND  CONVERT(`author` USING utf8) LIKE '%".$author."%'

)";

	$result=mysql_query($sql,$con);
	if($result === FALSE) {
		die(mysql_error()); // TODO: better error handling
	}

			echo "

Search Result

					BACK

";
	while($row=mysql_fetch_array($result)){
		$partname=$row['part_name'];
		$shortdesc=$row['short_desc'];
		$parttype=$row['part_type'];

		echo "

$partname

                  $shortdesc
                  Part Type:$parttype

		";

	}

mysql_close($con);
}

/*
echo "

Featured Articles

Integrating WordPress with Your Website

                                                                                25 Feb, 2013 in Server & Database
                                                                                66

WordPress Site Maintenance

                                                                                24 Feb, 2013 in Website Dev
                                                                                15

Meta Tags in WordPress

                                                                                23 Feb, 2013 in Website Dev
                                                                                8

WordPress in Your Language

                                                                                22 Feb, 2013 in Advanced Techniques
                                                                                6

Know Your Sources

                                                                                22 Feb, 2013 in Website Dev
                                                                                2

Validating a Website

                                                                                21 Feb, 2013 in Website Dev
                                                                                3

Latest Articles

Integrating WordPress with Your Website

                                                                                25 Feb, 2013 in Server & Database
                                                                                66

Using Javascript

                                                                                25 Feb, 2013 in Advanced Techniques
                                                                                18

Using Images

                                                                                25 Feb, 2013 in Designing in WordPress
                                                                                7

Using Video

                                                                                24 Feb, 2013 in WordPress Plugins
                                                                                7

WordPress Site Maintenance

                                                                                24 Feb, 2013 in Website Dev
                                                                                15

WordPress CSS Information and Techniques

                                                                                24 Feb, 2013 in Theme Development
                                                                                1

'
*/
?>


text:
Originally published: 2012-11-29 17:27:19
Last updated: 2012-11-29 17:27:20
Author: John Brearley

Here is a demo script for others to reuse / learn from. The server process hands out work assignments to multiple children process to do load balancing across multiple CPUs / hosts. The children process in this sample script dont do any real work, but occasionally create an error to demonstrate the error handling and recovery. Enjoy!


text:
@interface SearchViewController () <UITableViewDelegate, UITableViewDataSource, SearchTextDelegate, SearchResultDelegate>{
    NSArray * _keywordArray;
    UITableView *_historyTableView;
    NSMutableArray *_historyArray;
    SearchTextField * _searchField;
    SearchResultTableView * _searchResultView;
}

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithWhite:0.931 alpha:1.000];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self createNavView]];

    [self createHotKeywordView];
    [self createHistoryView];

    [self createResultView];

    // 设置成为第一响应者
    [_searchField becomeFirstResponder];

    // 加载搜索历史记录
    _historyArray = [[NSMutableArray alloc] init];
    [self initHistoryData];
}

-(void)initHistoryData{
    [_historyArray addObject:@"米其林轮胎"];
    [_historyArray addObject:@"随便看看"];

    _historyTableView.hidden = NO;
}

-(void)createResultView{

    _searchResultView = [[SearchResultTableView alloc] initWithFrame:CGRectMake(0, 0, SELF_SIZE_WIDTH, SELF_SIZE_HEIGHT)];

    _searchResultView.resultDelegate = self;

    [self.view addSubview:_searchResultView];
}

-(void)createHistoryView{
    _historyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 185, SELF_SIZE_WIDTH, SELF_SIZE_HEIGHT - 185) style:UITableViewStyleGrouped ];

    _historyTableView.backgroundColor = [UIColor clearColor];
    _historyTableView.delegate = self;
    _historyTableView.dataSource = self;
    _historyTableView.hidden = YES;
    [self.view addSubview: _historyTableView];
}

-(void) createHotKeywordView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SELF_SIZE_WIDTH, 170)];
    view.backgroundColor = [UIColor colorWithWhite:0.942 alpha:1.000];
    [view addBottomBorderWithColor:[UIColor colorWithWhite:0.872 alpha:1.000]  andWidth:.7];

    UILabel *hotTitle = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, SELF_SIZE_WIDTH, 40)];
    hotTitle.text = @"热门搜索";
    hotTitle.textColor = THEME_DFAULT_TITLE_COLOR_OBJ;
    hotTitle.font = [UIFont systemFontOfSize:13];

    // 根据数据动态创建可点击的按钮
    _keywordArray = @[@"黄壳",@"火花塞",@"滤清器",@"蓄电池",@"红壳",@"蓝壳",@"金嘉护",@"刹车片",@"柴机油",@"Test",@"AAAA"];
    long limit = 9, pages = _keywordArray.count / limit + (_keywordArray.count % limit != 0 ? 1 : 0);
    JLCarouselView *keywordView = [[JLCarouselView alloc] initWithFrame:CGRectMake(15, 40, SELF_SIZE_WIDTH - 30, 136) withPages:pages];

    long cols = 3, padding = 5, btnWidth = keywordView.frame.size.width / cols - padding, btnHeight = 32;
    for(long p = 0; p < pages; p++){
        UIView *pageView = [[UIView alloc] initWithFrame:CGRectMake(p * keywordView.frame.size.width, 0, keywordView.frame.size.width, 100)];
        for (long start = p * limit, i = start; i < start + limit && i < _keywordArray.count; i++) {
            long currentCol = (i - start) % cols, currentRow = (i - start)/ cols;
            long posX = (currentCol == 0) ? 0 : btnWidth * currentCol + padding * currentCol;
            long posY = (currentRow == 0) ? 0 : btnHeight * currentRow + padding * currentRow;
            UIButton *btn = [ViewUtils buttonWithTitle:_keywordArray[i] withFrame:CGRectMake(posX, posY, btnWidth, btnHeight)];
            //[btn addTarget:self action:@selector(togglePosition:) forControlEvents:UIControlEventTouchUpInside];
            [pageView addSubview:btn];
        }
        [keywordView addToScrollView:pageView];
    }

    [view addSubview:hotTitle];
    [view addSubview:keywordView];
    [self.view addSubview:view];
}

-(UIView *) createNavView{
    CGSize navSize = self.navigationController.navigationBar.frame.size;
    UIView *navBodyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, navSize.width, navSize.height)];

    NavBackButton *backBtn = [NavBackButton buttonWithNavigation:self.navigationController withFrame:CGRectMake(-5, 12, 22, 22)];
    int padding = 30;

    _searchField = [[SearchTextField alloc] initWithFrame:CGRectMake(padding, 10, navSize.width - padding * 2.5, 26) withPlaceholder:@"输入宝贝名称、型号、品牌"];
    _searchField.searchDelegate = self;

    [navBodyView addSubview:backBtn];
    [navBodyView addSubview:_searchField];

    return navBodyView;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_searchField resignFirstResponder];
}

#pragma mark 搜索协议
-(void)searchTextBeginSearch:(NSString *)keyword target:(SearchTextField *)searchField{
    if(keyword.length == 0){
        _searchResultView.hidden = YES;
    }else{
        //FIXME: 通过远程加载数据,这里仅仅是模拟一些数据
        [_searchResultView.dataArray removeAllObjects];
        [_searchResultView.dataArray addObject:@"马牌 轮胎 205/55R16 91V CC5"];
        [_searchResultView.dataArray addObject:@"米其林 国产轮胎 韧悦 195/65R15 91V Energy XM2"];
        [_searchResultView.dataArray addObject:@"固特异 轮胎 配套大师 195/65R15 91V Eagle NCT5"];
        [_searchResultView.dataArray addObject:@"普利司通 轮胎 泰然者 215/60R16 95V ER33UZ"];
        [_searchResultView.dataArray addObject:@"普利司通 轮胎 绿歌伴 205/55R16 91V EP200"];
        [_searchResultView.dataArray addObject:@"普利司通 轮胎 绿歌伴 195/60R15 88H EP150"];
        [_searchResultView.dataArray addObject:@"普利司通 轮胎 泰然者 245/45R18 96V EL400"];
        [_searchResultView.dataArray addObject:@"米其林 轮胎 揽途 225/65R17 102T Latitude Tour 公路"];
        [_searchResultView.dataArray addObject:@"米其林 轮胎 博悦 235/55R17 99H Primacy LC PC"];
        [_searchResultView.dataArray addObject:@"韩泰 轮胎 205/55R16 91V K407"];

        [_searchResultView reloadData];
        _searchResultView.hidden = NO;
    }
}

//FIXME: 跳转页面
-(void)searchTextReturn:(NSString *)keyword target:(SearchTextField *)searchField{

}
-(void)tableView:(UITableView *)tableView didSelectRowAtData:(id)indexData{
    NSLog(@"点击了行:%@", indexData);
    _searchField.text = indexData;

    [_historyArray insertObject:indexData atIndex:0];
    [_historyTableView reloadData];
    _historyTableView.hidden = NO;
    // 跳转页面

}

#pragma mark TableView协议实现
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _historyArray.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40.0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 40.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellId = @"SingleRowTableViewCell";
    SingleRowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

    if(!cell){
        cell = [[[NSBundle mainBundle] loadNibNamed:cellId owner:nil options:nil] lastObject];
        cell.iconImageView.image = [UIImage imageNamed:@"icon_search_history"];
        cell.subTitleLabel.text = @"";

    }
    cell.titleLabel.text = _historyArray[indexPath.row];

    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, tableView.rowHeight)];
    view.backgroundColor = [UIColor whiteColor];

    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    delBtn.frame = CGRectMake(0, 0, tableView.frame.size.width, 40);
    [delBtn setTitle:@"清除历史记录" forState:UIControlStateNormal];
    delBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [delBtn setTitleColor:THEME_COLOR_NORMAL_OBJ forState:UIControlStateNormal];
    [view addSubview:delBtn];

    [delBtn addTarget:self action:@selector(deleteHistoryRecords) forControlEvents: UIControlEventTouchUpInside];
    return view;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //NSLog(@"点击了:%ld" , indexPath.row);
}

-(void)deleteHistoryRecords{
    [_historyArray removeAllObjects];
    _historyTableView.hidden = YES;
    // [_historyTableView reloadData];
}

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

@end


text:
package org.spincast.plugins.gson.serializers;

import java.lang.reflect.Type;
import java.time.Instant;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class InstantSerializer implements JsonSerializer<Instant> {

    @Override
    public JsonElement serialize(Instant instant,
                                 Type typeOfSrc,
                                 JsonSerializationContext context) {
        if (instant == null) {
            return null;
        }

        return new JsonPrimitive(instant.toString());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/F:/UVA/Work%20with%20professor%20wang/Projects/AOL%20Query%20Log%20Analysis/src/edu/virginia/cs/main/NERTagger.java</file>
            <file>file:/F:/UVA/Work%20with%20professor%20wang/Projects/AOL%20Query%20Log%20Analysis/src/edu/virginia/cs/main/Main.java</file>
        </group>
    </open-files>
</project-private>


text:
/*-------------------------------------------------------------------------//
//                                                                         //
//      INCLUDES                                                           //
//                                                                         //
//-------------------------------------------------------------------------*/

#include <string.h>

#ifndef GUCEF_CORE_CCOREGLOBAL_H
#include "gucefCORE_CCoreGlobal.h"
#define GUCEF_CORE_CCOREGLOBAL_H
#endif /* GUCEF_CORE_CCOREGLOBAL_H ? */

#ifndef GUCEF_CORE_CGUCEFAPPLICATION_H
#include "CGUCEFApplication.h"
#define GUCEF_CORE_CGUCEFAPPLICATION_H
#endif /* GUCEF_CORE_CGUCEFAPPLICATION_H ? */

#ifndef GUCEF_CORE_LOGGING_H
#include "gucefCORE_Logging.h"
#define GUCEF_CORE_LOGGING_H
#endif /* GUCEF_CORE_LOGGING_H ? */

#ifndef GUCEF_LOGSERVICELIB_CILOGSVCSERVERLOGGER_H
#include "GucefLogServiceLib_CILogSvcServerLogger.h"
#define GUCEF_LOGSERVICELIB_CILOGSVCSERVERLOGGER_H
#endif /* GUCEF_LOGSERVICELIB_CILOGSVCSERVERLOGGER_H ? */

#ifndef GUCEF_LOGSERVICELIB_PROTOCOL_H
#include "GucefLogServiceLib_protocol.h"
#define GUCEF_LOGSERVICELIB_PROTOCOL_H
#endif /* GUCEF_LOGSERVICELIB_PROTOCOL_H ? */

#ifndef GUCEF_LOGSERVICELIB_CCLIENTINITMESSAGE_H
#include "GucefLogServiceLib_CClientInitMessage.h"
#define GUCEF_LOGSERVICELIB_CCLIENTINITMESSAGE_H
#endif /* GUCEF_LOGSERVICELIB_CCLIENTINITMESSAGE_H ? */

#include "GucefLogServiceLib_CLogSvcServer.h"

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

namespace GUCEF {
namespace LOGSERVICELIB {

/*-------------------------------------------------------------------------//
//                                                                         //
//      CONSTANTS                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

//                              1024 *  1KB = 1MB * 10 = 10MB
////10 * 1024 * 1024
#define MAX_ACCEPTED_MSGLENGTH  2048

/*-------------------------------------------------------------------------//
//                                                                         //
//      UTILITIES                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

CLogSvcServer::CLogSvcServer( void )
    : CORE::CObservingNotifier()                                               ,
      m_tcpServer( CORE::CCoreGlobal::Instance()->GetPulseGenerator(), false ) ,
      m_clientInfoMap()                                                        ,
      m_loggers()
{GUCEF_TRACE;

    RegisterServerSocketEventHandlers();
}

/*-------------------------------------------------------------------------*/

CLogSvcServer::CLogSvcServer( const CORE::PulseGeneratorPtr& pulseGenerator )
    : CORE::CObservingNotifier()           ,
      m_tcpServer( pulseGenerator, false ) ,
      m_clientInfoMap()                    ,
      m_loggers()
{GUCEF_TRACE;

    RegisterServerSocketEventHandlers();
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::RegisterServerSocketEventHandlers( void )
{
    TEventCallback callback( this, &CLogSvcServer::OnServerSocketClientConnected );
    SubscribeTo( &m_tcpServer                                    ,
                 COMCORE::CTCPServerSocket::ClientConnectedEvent ,
                 callback                                        );
    TEventCallback callback2( this, &CLogSvcServer::OnServerSocketClientDisconnected );
    SubscribeTo( &m_tcpServer                                       ,
                 COMCORE::CTCPServerSocket::ClientDisconnectedEvent ,
                 callback2                                          );
    TEventCallback callback3( this, &CLogSvcServer::OnServerSocketClientError );
    SubscribeTo( &m_tcpServer                                ,
                 COMCORE::CTCPServerSocket::ClientErrorEvent ,
                 callback3                                   );
    TEventCallback callback4( this, &CLogSvcServer::OnServerSocketServerSocketClosed );
    SubscribeTo( &m_tcpServer                                       ,
                 COMCORE::CTCPServerSocket::ServerSocketClosedEvent ,
                 callback4                                          );
    TEventCallback callback5( this, &CLogSvcServer::OnServerSocketServerSocketError );
    SubscribeTo( &m_tcpServer                                      ,
                 COMCORE::CTCPServerSocket::ServerSocketErrorEvent ,
                 callback5                                         );
    TEventCallback callback6( this, &CLogSvcServer::OnServerSocketServerSocketClientError );
    SubscribeTo( &m_tcpServer                                            ,
                 COMCORE::CTCPServerSocket::ServerSocketClientErrorEvent ,
                 callback6                                               );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::RegisterClientConnectionEventHandlers( COMCORE::CTCPServerConnection* connection )
{GUCEF_TRACE;

    TEventCallback callback( this, &CLogSvcServer::OnClientConnectionDataReceived );
    SubscribeTo( connection                                       ,
                 COMCORE::CTCPServerConnection::DataRecievedEvent ,
                 callback                                         );

    //static const CORE::CEvent ConnectedEvent;
    //static const CORE::CEvent DisconnectedEvent;
    //static const CORE::CEvent DataSentEvent;
    //static const CORE::CEvent SocketErrorEvent;
}

/*-------------------------------------------------------------------------*/

CLogSvcServer::~CLogSvcServer()
{GUCEF_TRACE;

    m_tcpServer.Close();
}

/*-------------------------------------------------------------------------*/

const CORE::CString&
CLogSvcServer::GetClassTypeName( void ) const
{GUCEF_TRACE;

    static CORE::CString classTypeName = "GUCEF::LOGSERVICELIB::CLogSvcServer";
    return classTypeName;
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::RegisterLogger( CILogSvcServerLogger* logger )
{GUCEF_TRACE;

    m_loggers.insert( logger );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::UnregisterLogger( CILogSvcServerLogger* logger )
{GUCEF_TRACE;

    m_loggers.erase( logger );
}

/*-------------------------------------------------------------------------*/

bool
CLogSvcServer::ListenOnPort( CORE::UInt16 port )
{GUCEF_TRACE;

    return m_tcpServer.ListenOnPort( port );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::ProcessReceivedMessage( TClientInfo& clientInfo                   ,
                                       COMCORE::CTCPServerConnection* connection ,
                                       const CORE::CDynamicBuffer& messageBuffer )
{GUCEF_TRACE;

    try
    {
        // First read the message type and handle accordingly
        CORE::UInt8 msgType = messageBuffer.AsConstType< CORE::UInt8 >( 0 );
        switch ( msgType )
        {
            case LOGSVCMSGTYPE_CLIENTINFO:
            {
                CClientInitMessage initMessage;
                if ( initMessage.ReadFromBuffer( messageBuffer, false ) )
                {
                    clientInfo.logClientVersion = initMessage.GetClientVersion();
                    clientInfo.appName = initMessage.GetApplicationName();
                    clientInfo.processId = initMessage.GetProcessId();
                    clientInfo.processName = initMessage.GetProcessName();

                    // Set the client's address and port for easy unique addressability
                    clientInfo.addressAndPort = connection->GetRemoteIP().AddressAndPortAsString();

                    // If we got here without an exception then the we successfully received all info required to
                    // consider the connection as initialized.
                    clientInfo.initialized = true;

                    // tell the loggers we have a new client for which we can begin logging
                    TLoggerList::iterator i = m_loggers.begin();
                    while ( i != m_loggers.end() )
                    {
                        (*i)->StartOfLoggingForClient( clientInfo );
                        ++i;
                    }

                    // Send notification to the client that the initialization was successfull
                    CORE::UInt8 statusCode = LOGSVCMSGTYPE_INITIALIZED;
                    connection->Send( &statusCode, 1 );
                }
                else
                {
                    // Something is wrong with this msg buffer, kill the connection
                    connection->Close();
                }
                break;
            }
            case LOGSVCMSGTYPE_FLUSHLOG:
            {
                // We are being asked to flush the log
                TLoggerList::iterator i = m_loggers.begin();
                while ( i != m_loggers.end() )
                {
                    (*i)->FlushLog( clientInfo );
                    ++i;
                }
                break;
            }
            case LOGSVCMSGTYPE_LOGMSG:
            {
                // This is what its all about, we have been given a log message.
                // Parse the log message from the transmission
                CORE::UInt32 offset = 1;
                CILogSvcServerLogger::TLogMsgType logMsgTypeValue = (CILogSvcServerLogger::TLogMsgType) messageBuffer.AsConstType< CORE::Int16 >( offset );
                offset += 2;
                CORE::Int32 logLevel = messageBuffer.AsConstType< CORE::Int32 >( offset );
                offset += 4;
                CORE::UInt32 threadId = messageBuffer.AsConstType< CORE::UInt32 >( offset );
                offset += 4;
                CORE::UInt64 unixEpochDt = messageBuffer.AsConstType< CORE::UInt64 >( offset );
                offset += 8;
                CORE::CDateTime dt;
                dt.FromUnixEpochBasedTicksInMillisecs( unixEpochDt );
                CORE::CString logMessage;
                CORE::UInt32 strLength = messageBuffer.GetDataSize() - offset;
                logMessage.Set( messageBuffer.AsConstTypePtr< char >( offset, strLength ), strLength );

                // Now send the log message to all loggers
                TLoggerList::iterator i = m_loggers.begin();
                while ( i != m_loggers.end() )
                {
                    (*i)->Log( clientInfo, logMsgTypeValue, logLevel, logMessage, threadId, dt );
                    ++i;
                }
                break;
            }
            default:
            {
                // We should not get here if the protocol is correctly adhered to and there is no
                // corruption in the stream. This is a fatal error for the connection.
                connection->Close();
            }
        }
    }
    catch ( CORE::CDynamicBuffer::EIllegalCast& )
    {
        // Something is wrong with this msg buffer, kill the connection
        connection->Close();
    }
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::ProcessReceivedData( TClientInfo& clientInfo                   ,
                                    COMCORE::CTCPServerConnection* connection )
{GUCEF_TRACE;

    // Cycle as long as we have buffered data and no errors occur
    bool noError = true;
    while ( clientInfo.receiveBuffer.HasBufferedData() )
    {
        // First read the message delimiter if its fully available
        char msgDelimterHeader[ 5 ];
        if ( 5 == clientInfo.receiveBuffer.PeekElement( msgDelimterHeader, 5 ) )
        {
            if ( msgDelimterHeader[ 0 ] == LOGSVCMSGTYPE_DELIMITER )
            {
                // Get the total message length from the delimiter header
                CORE::UInt32 msgLength = 0;
                memcpy( &msgLength, msgDelimterHeader+1, 4 );

                // Perform a sanity check
                // Server side we limit the length of the message we will accept from the client
                if ( msgLength <= MAX_ACCEPTED_MSGLENGTH )
                {
                    // Check to see if the buffer actually has the data available already to form the complete message
                    if ( msgLength+5 <= clientInfo.receiveBuffer.GetBufferedDataSizeInBytes() )
                    {
                        // Since we already got he header data via a Peek() we will skip that data now
                        if ( 5 != clientInfo.receiveBuffer.SkipRead( 5 ) )
                        {
                            // This should not happen
                            GUCEF_ERROR_LOG( CORE::LOGLEVEL_BELOW_NORMAL, "CLogSvcServer: Unable to Skip buffered data" );
                            connection->Close();
                            return;
                        }

                        // Make a buffer for this message and read it from the receive buffer
                        CORE::CDynamicBuffer messageBuffer( msgLength, false );
                        if ( msgLength == clientInfo.receiveBuffer.Read( messageBuffer.GetBufferPtr(), msgLength, 1 ) )
                        {
                            // Set the size of usefull data in the buffer
                            messageBuffer.SetDataSize( msgLength );

                            // Process this single message
                            ProcessReceivedMessage( clientInfo    ,
                                                    connection    ,
                                                    messageBuffer );
                        }
                        else
                        {
                            // This should not happen
                            GUCEF_ERROR_LOG( CORE::LOGLEVEL_NORMAL, "CLogSvcServer: Unable to Read() buffered data" );
                            connection->Close();
                            return;
                        }
                    }
                    else
                    {
                        // We don't have all the data yet to read this message, we will wait for more data to come in
                        return;
                    }
                }
                else
                {
                    // This connection is misbehaving
                    GUCEF_ERROR_LOG( CORE::LOGLEVEL_NORMAL, "CLogSvcServer: A message was received which exceeded the max msg size, disconnecting client" );
                    connection->Close();
                    return;
                }
            }
        }
    }
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnClientConnectionDataReceived( CORE::CNotifier* notifier    ,
                                               const CORE::CEvent& eventid  ,
                                               CORE::CICloneable* eventdata )
{GUCEF_TRACE;

    // Get access to the event data
    COMCORE::CTCPServerConnection::TDataRecievedEventData* eData = static_cast< COMCORE::CTCPServerConnection::TDataRecievedEventData* >( eventdata );
    const CORE::CDynamicBuffer& buffer = eData->GetData();

    // Get access to the connection object & client info
    COMCORE::CTCPServerConnection* connection = static_cast< COMCORE::CTCPServerConnection* >( notifier );
    TClientInfo& clientInfo = m_clientInfoMap[ connection->GetConnectionIndex() ];

    // Handle the tcp stream, take into account message concatonation
    // First we copy the data recieved into our recieve buffer where we
    // can properly segment data because we retain whatever data we need
    if ( !( buffer.GetDataSize() == clientInfo.receiveBuffer.Write( buffer, 0 ) ) )
    {
        GUCEF_ERROR_LOG( CORE::LOGLEVEL_IMPORTANT, "Failed to write all data recieved into a receive buffer for processsing" );
    }

    // Use the received data as a trigger to process whatever we can on this connection
    ProcessReceivedData( clientInfo ,
                         connection );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketClientConnected( CORE::CNotifier* notifier    ,
                                              const CORE::CEvent& eventid  ,
                                              CORE::CICloneable* eventdata )
{GUCEF_TRACE;

    // Get access to the event data
    COMCORE::CTCPServerSocket::TClientConnectedEventData* eData = static_cast< COMCORE::CTCPServerSocket::TClientConnectedEventData* >( eventdata );
    COMCORE::CTCPServerSocket::TConnectionInfo& eventData = eData->GetData();

    // Build an initialization structure
    TClientInfo initialClientInfo;
    initialClientInfo.appName = "Unknown";
    initialClientInfo.processId = "Unknown";
    initialClientInfo.processName = "Unknown";
    initialClientInfo.logClientVersion = "Unknown";
    initialClientInfo.initialized = false;
    initialClientInfo.connected = true;

    m_clientInfoMap[ eventData.connectionIndex ] = initialClientInfo;

    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "CLogSvcServer: Client connected from " + eventData.connection->GetRemoteIP().AddressAndPortAsString() );

    RegisterClientConnectionEventHandlers( eventData.connection );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketClientDisconnected( CORE::CNotifier* notifier    ,
                                                 const CORE::CEvent& eventid  ,
                                                 CORE::CICloneable* eventdata )
{GUCEF_TRACE;

    // Get access to the event data
    COMCORE::CTCPServerSocket::TClientDisconnectedEventData* eData = static_cast< COMCORE::CTCPServerSocket::TClientDisconnectedEventData* >( eventdata );
    COMCORE::CTCPServerSocket::TConnectionInfo& connectionInfo = eData->GetData().connectionInfo;

    TClientInfo& clientInfo = m_clientInfoMap[ connectionInfo.connectionIndex ];
    clientInfo.connected = false;

    // tell the loggers we should stop logging for this client
    TLoggerList::iterator i = m_loggers.begin();
    while ( i != m_loggers.end() )
    {
        (*i)->EndOfLoggingForClient( clientInfo );
        ++i;
    }

    GUCEF_LOG( CORE::LOGLEVEL_NORMAL, "CLogSvcServer: Client from " + connectionInfo.hostAddress.HostnameAndPortAsString() + " disconnected" );
}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketClientError( CORE::CNotifier* notifier    ,
                                          const CORE::CEvent& eventid  ,
                                          CORE::CICloneable* eventdata )
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketServerSocketClosed( CORE::CNotifier* notifier    ,
                                                 const CORE::CEvent& eventid  ,
                                                 CORE::CICloneable* eventdata )
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketServerSocketError( CORE::CNotifier* notifier    ,
                                                const CORE::CEvent& eventid  ,
                                                CORE::CICloneable* eventdata )
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------*/

void
CLogSvcServer::OnServerSocketServerSocketClientError( CORE::CNotifier* notifier    ,
                                                      const CORE::CEvent& eventid  ,
                                                      CORE::CICloneable* eventdata )
{GUCEF_TRACE;

}

/*-------------------------------------------------------------------------//
//                                                                         //
//      NAMESPACE                                                          //
//                                                                         //
//-------------------------------------------------------------------------*/

}; /* namespace LOGSERVICELIB */
}; /* namespace GUCEF */

/*-------------------------------------------------------------------------*/


text:
using SQLRefactor;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;

namespace TestProject
{

	///
	///This is a test class for QueryDataTest and is intended
	///to contain all QueryDataTest Unit Tests
	///
	[TestClass ()]
	public class QueryDataTest
	{

		private TestContext testContextInstance;

		///
		///Gets or sets the test context which provides
		///information about and functionality for the current test run.
		///
		public TestContext TestContext
		{
			get
			{
				return testContextInstance;
			}
			set
			{
				testContextInstance = value;
			}
		}

		///
		///A test for GetDifference_RowCol
		///
		[TestMethod ()]
		public void GetDifferences_NoDiff ()
		{
			QueryData target = new QueryData ();
			QueryData obj = new QueryData ();

			target.Add ( new object[] { "a", 1, "c" } );
			obj.Add ( new object[] { "a", 1, "c" } );

			target.Add ( new object[] { "x", 2, "z" } );
			obj.Add ( new object[] { "x", 2, "z" } );

			Assert.AreEqual ( 0, target.GetDifferences ( obj ).Count () );
		}

		[TestMethod ()]
		public void GetDifferences_Diff ()
		{
			QueryData target = new QueryData ();
			QueryData obj = new QueryData ();

			target.Add ( new object[] { "a", 1, "c" } );
			obj.Add ( new object[] { "a", 1, "c" } );

			target.Add ( new object[] { "x", 2, "z" } );
			obj.Add ( new object[] { "x", 2, "a" } );

			Assert.AreEqual ( 1, target.GetDifferences ( obj ).Count () );
		}
	}
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See https://javaee.github.io/jaxb-v2/
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2022.06.28 at 02:49:33 PM PDT
//

package com.intuit.ipp.data;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.HashCode2;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 *
 * 				Product: ALL
 * 				Description: Contains Bank Account details to process the batch payment for Vendors. Applicable for AU region only..
 *
 *
 *
Java class for VendorBankAccountDetail complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="VendorBankAccountDetail">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="BankBranchIdentifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="BankAccountNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="BankAccountName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="StatementText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "VendorBankAccountDetail", propOrder = {
    "bankBranchIdentifier",
    "bankAccountNumber",
    "bankAccountName",
    "statementText"
})
public class VendorBankAccountDetail implements Serializable, Equals2, HashCode2
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "BankBranchIdentifier")
    protected String bankBranchIdentifier;
    @XmlElement(name = "BankAccountNumber")
    protected String bankAccountNumber;
    @XmlElement(name = "BankAccountName")
    protected String bankAccountName;
    @XmlElement(name = "StatementText")
    protected String statementText;

    /**
     * Gets the value of the bankBranchIdentifier property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBankBranchIdentifier() {
        return bankBranchIdentifier;
    }

    /**
     * Sets the value of the bankBranchIdentifier property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBankBranchIdentifier(String value) {
        this.bankBranchIdentifier = value;
    }

    /**
     * Gets the value of the bankAccountNumber property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBankAccountNumber() {
        return bankAccountNumber;
    }

    /**
     * Sets the value of the bankAccountNumber property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBankAccountNumber(String value) {
        this.bankAccountNumber = value;
    }

    /**
     * Gets the value of the bankAccountName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getBankAccountName() {
        return bankAccountName;
    }

    /**
     * Sets the value of the bankAccountName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setBankAccountName(String value) {
        this.bankAccountName = value;
    }

    /**
     * Gets the value of the statementText property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getStatementText() {
        return statementText;
    }

    /**
     * Sets the value of the statementText property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setStatementText(String value) {
        this.statementText = value;
    }

    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
        if ((object == null)||(this.getClass()!= object.getClass())) {
            return false;
        }
        if (this == object) {
            return true;
        }
        final VendorBankAccountDetail that = ((VendorBankAccountDetail) object);
        {
            String lhsBankBranchIdentifier;
            lhsBankBranchIdentifier = this.getBankBranchIdentifier();
            String rhsBankBranchIdentifier;
            rhsBankBranchIdentifier = that.getBankBranchIdentifier();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "bankBranchIdentifier", lhsBankBranchIdentifier), LocatorUtils.property(thatLocator, "bankBranchIdentifier", rhsBankBranchIdentifier), lhsBankBranchIdentifier, rhsBankBranchIdentifier, (this.bankBranchIdentifier!= null), (that.bankBranchIdentifier!= null))) {
                return false;
            }
        }
        {
            String lhsBankAccountNumber;
            lhsBankAccountNumber = this.getBankAccountNumber();
            String rhsBankAccountNumber;
            rhsBankAccountNumber = that.getBankAccountNumber();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "bankAccountNumber", lhsBankAccountNumber), LocatorUtils.property(thatLocator, "bankAccountNumber", rhsBankAccountNumber), lhsBankAccountNumber, rhsBankAccountNumber, (this.bankAccountNumber!= null), (that.bankAccountNumber!= null))) {
                return false;
            }
        }
        {
            String lhsBankAccountName;
            lhsBankAccountName = this.getBankAccountName();
            String rhsBankAccountName;
            rhsBankAccountName = that.getBankAccountName();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "bankAccountName", lhsBankAccountName), LocatorUtils.property(thatLocator, "bankAccountName", rhsBankAccountName), lhsBankAccountName, rhsBankAccountName, (this.bankAccountName!= null), (that.bankAccountName!= null))) {
                return false;
            }
        }
        {
            String lhsStatementText;
            lhsStatementText = this.getStatementText();
            String rhsStatementText;
            rhsStatementText = that.getStatementText();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "statementText", lhsStatementText), LocatorUtils.property(thatLocator, "statementText", rhsStatementText), lhsStatementText, rhsStatementText, (this.statementText!= null), (that.statementText!= null))) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(Object object) {
        final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE;
        return equals(null, null, object, strategy);
    }

    public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
        int currentHashCode = 1;
        {
            String theBankBranchIdentifier;
            theBankBranchIdentifier = this.getBankBranchIdentifier();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "bankBranchIdentifier", theBankBranchIdentifier), currentHashCode, theBankBranchIdentifier, (this.bankBranchIdentifier!= null));
        }
        {
            String theBankAccountNumber;
            theBankAccountNumber = this.getBankAccountNumber();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "bankAccountNumber", theBankAccountNumber), currentHashCode, theBankAccountNumber, (this.bankAccountNumber!= null));
        }
        {
            String theBankAccountName;
            theBankAccountName = this.getBankAccountName();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "bankAccountName", theBankAccountName), currentHashCode, theBankAccountName, (this.bankAccountName!= null));
        }
        {
            String theStatementText;
            theStatementText = this.getStatementText();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "statementText", theStatementText), currentHashCode, theStatementText, (this.statementText!= null));
        }
        return currentHashCode;
    }

    public int hashCode() {
        final HashCodeStrategy2 strategy = JAXBHashCodeStrategy.INSTANCE;
        return this.hashCode(null, strategy);
    }

}


text:
require "rails_helper"

RSpec.describe UserMailer, type: :mailer do
  describe 'share_submitted' do
    let(:user) { create :user }
    let(:share) { create :share }
    let(:mail) { UserMailer.share_submitted(share, user) }

    it 'renders the subject' do
      expect(mail.subject).to eq 'New Share/Community Contribution'
    end

    it 'renders the receiver email' do
      expect(mail.to).to eq [user.email]
    end

    it 'renders the sender email' do
      expect(mail.from).to eq ['ojibwe.dictionary@gmail.com']
    end

    it 'assigns @description' do
      expect(mail.body.encoded).to match(share.description)
    end

    it 'assigns @email' do
      expect(mail.body.encoded).to match(share.email)
    end
  end
end


text:
require('proof')(5, function (ok, equal) {
  var router = require('../..').createRouter();
  router.get('/user/:name', function (object) {
    equal(object.params.name, 'alan');
  });
  router.get('/post/:name/:id', function (object) {
    equal(object.params.name, 'alan');
    equal(object.params.id, '1');
  });
  ok(router.route('GET', '/user/alan', {}), 'matched one parameter');
  ok(router.route('GET', '/post/alan/1', {}), 'matched two parameters');
});


text:
define([
    'jquery',
    'Magento_Ui/js/modal/modalToggle',
    'mage/translate'
], function ($, modalToggle) {
    'use strict';

    return function (config, deleteButton) {
        config.buttons = [
            {
                text: $.mage.__('Cancel'),
                class: 'action secondary cancel'
            }, {
                text: $.mage.__('Delete'),
                class: 'action primary',

                /**
                 * Default action on button click
                 */
                click: function (event) { //eslint-disable-line no-unused-vars
                    deleteButton.form.submit();
                }
            }
        ];

        modalToggle(config, deleteButton);
    };
});


text:
class ISetScore {
public:
	virtual void setNowSpeed(double now_speed) = 0;
	virtual void addSwingCount() = 0;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpKit.JavaScript;

namespace THREE
{
    [JsType(JsMode.Prototype, Export = false)]
    public class UV
    {
        public UV() { }
        public UV(JsNumber u) { }
        public UV(JsNumber u, JsNumber v) { }

        public UV set(JsNumber u, JsNumber v) { return null; }
        public UV copy(UV uv) { return null; }
        public UV lerpSelf(UV uv, JsNumber alpha) { return null; }
        public UV clone() { return null; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using OMV = OpenMetaverse;

namespace OpenSim.Region.Physics.BulletSPlugin
{
// Classes to allow some type checking for the API
// These hold pointers to allocated objects in the unmanaged space.
// These classes are subclassed by the various physical implementations of
// objects. In particular, there is a version for physical instances in
// unmanaged memory ("unman") and one for in managed memory ("XNA").

// Currently, the instances of these classes are a reference to a
// physical representation and this has no releationship to other
// instances. Someday, refarb the usage of these classes so each instance
// refers to a particular physical instance and this class controls reference
// counts and such. This should be done along with adding BSShapes.

public class BulletWorld
{
    public BulletWorld(uint worldId, BSScene bss)
    {
        worldID = worldId;
        physicsScene = bss;
    }
    public uint worldID;
    // The scene is only in here so very low level routines have a handle to print debug/error messages
    public BSScene physicsScene;
}

// An allocated Bullet btRigidBody
public class BulletBody
{
    public BulletBody(uint id)
    {
        ID = id;
        collisionType = CollisionType.Static;
    }
    public uint ID;
    public CollisionType collisionType;

    public virtual void Clear() { }
    public virtual bool HasPhysicalBody { get { return false; } }

    // Apply the specificed collision mask into the physical world
    public virtual bool ApplyCollisionMask(BSScene physicsScene)
    {
        // Should assert the body has been added to the physical world.
        // (The collision masks are stored in the collision proxy cache which only exists for
        //    a collision body that is in the world.)
        return physicsScene.PE.SetCollisionGroupMask(this,
                                BulletSimData.CollisionTypeMasks[collisionType].group,
                                BulletSimData.CollisionTypeMasks[collisionType].mask);
    }

    // Used for log messages for a unique display of the memory/object allocated to this instance
    public virtual string AddrString
    {
        get { return "unknown"; }
    }

    public override string ToString()
    {
        StringBuilder buff = new StringBuilder();
        buff.Append("<id=");
        buff.Append(ID.ToString());
        buff.Append(",p=");
        buff.Append(AddrString);
        buff.Append(",c=");
        buff.Append(collisionType);
        buff.Append(">");
        return buff.ToString();
    }
}

public class BulletShape
{
    public BulletShape()
    {
        shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN;
        shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE;
        isNativeShape = false;
    }
    public BSPhysicsShapeType shapeType;
    public System.UInt64 shapeKey;
    public bool isNativeShape;

    public virtual void Clear() { }
    public virtual bool HasPhysicalShape { get { return false; } }

    // Make another reference to this physical object.
    public virtual BulletShape Clone() { return new BulletShape(); }

    // Return 'true' if this and other refer to the same physical object
    public virtual bool ReferenceSame(BulletShape xx) { return false; }

    // Used for log messages for a unique display of the memory/object allocated to this instance
    public virtual string AddrString
    {
        get { return "unknown"; }
    }

    public override string ToString()
    {
        StringBuilder buff = new StringBuilder();
        buff.Append("<p=");
        buff.Append(AddrString);
        buff.Append(",s=");
        buff.Append(shapeType.ToString());
        buff.Append(",k=");
        buff.Append(shapeKey.ToString("X"));
        buff.Append(",n=");
        buff.Append(isNativeShape.ToString());
        buff.Append(">");
        return buff.ToString();
    }
}

// An allocated Bullet btConstraint
public class BulletConstraint
{
    public BulletConstraint()
    {
    }
    public virtual void Clear() { }
    public virtual bool HasPhysicalConstraint { get { return false; } }

    // Used for log messages for a unique display of the memory/object allocated to this instance
    public virtual string AddrString
    {
        get { return "unknown"; }
    }
}

// An allocated HeightMapThing which holds various heightmap info.
// Made a class rather than a struct so there would be only one
//      instance of this and C# will pass around pointers rather
//      than making copies.
public class BulletHMapInfo
{
    public BulletHMapInfo(uint id, float[] hm) {
        ID = id;
        heightMap = hm;
        terrainRegionBase = OMV.Vector3.Zero;
        minCoords = new OMV.Vector3(100f, 100f, 25f);
        maxCoords = new OMV.Vector3(101f, 101f, 26f);
        minZ = maxZ = 0f;
        sizeX = sizeY = 256f;
    }
    public uint ID;
    public float[] heightMap;
    public OMV.Vector3 terrainRegionBase;
    public OMV.Vector3 minCoords;
    public OMV.Vector3 maxCoords;
    public float sizeX, sizeY;
    public float minZ, maxZ;
    public BulletShape terrainShape;
    public BulletBody terrainBody;
}

// The general class of collsion object.
public enum CollisionType
{
    Avatar,
    Groundplane,
    Terrain,
    Static,
    Dynamic,
    VolumeDetect,
    // Linkset, // A linkset should be either Static or Dynamic
    LinksetChild,
    Unknown
};

// Hold specification of group and mask collision flags for a CollisionType
public struct CollisionTypeFilterGroup
{
    public CollisionTypeFilterGroup(CollisionType t, uint g, uint m)
    {
        type = t;
        group = g;
        mask = m;
    }
    public CollisionType type;
    public uint group;
    public uint mask;
};

public static class BulletSimData
{

// Map of collisionTypes to flags for collision groups and masks.
// An object's 'group' is the collison groups this object belongs to
// An object's 'filter' is the groups another object has to belong to in order to collide with me
// A collision happens if ((obj1.group & obj2.filter) != 0) || ((obj2.group & obj1.filter) != 0)
//
// As mentioned above, don't use the CollisionFilterGroups definitions directly in the code
//     but, instead, use references to this dictionary. Finding and debugging
//     collision flag problems will be made easier.
public static Dictionary<CollisionType, CollisionTypeFilterGroup> CollisionTypeMasks
            = new Dictionary<CollisionType, CollisionTypeFilterGroup>()
{
    { CollisionType.Avatar,
                new CollisionTypeFilterGroup(CollisionType.Avatar,
                                (uint)CollisionFilterGroups.BCharacterGroup,
                                (uint)CollisionFilterGroups.BAllGroup)
    },
    { CollisionType.Groundplane,
                new CollisionTypeFilterGroup(CollisionType.Groundplane,
                                (uint)CollisionFilterGroups.BGroundPlaneGroup,
                                // (uint)CollisionFilterGroups.BAllGroup)
                                (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
    },
    { CollisionType.Terrain,
                new CollisionTypeFilterGroup(CollisionType.Terrain,
                                (uint)CollisionFilterGroups.BTerrainGroup,
                                (uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup))
    },
    { CollisionType.Static,
                new CollisionTypeFilterGroup(CollisionType.Static,
                                (uint)CollisionFilterGroups.BStaticGroup,
                                (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
    },
    { CollisionType.Dynamic,
                new CollisionTypeFilterGroup(CollisionType.Dynamic,
                                (uint)CollisionFilterGroups.BSolidGroup,
                                (uint)(CollisionFilterGroups.BAllGroup))
    },
    { CollisionType.VolumeDetect,
                new CollisionTypeFilterGroup(CollisionType.VolumeDetect,
                                (uint)CollisionFilterGroups.BSensorTrigger,
                                (uint)(~CollisionFilterGroups.BSensorTrigger))
    },
    { CollisionType.LinksetChild,
                new CollisionTypeFilterGroup(CollisionType.LinksetChild,
                                (uint)CollisionFilterGroups.BLinksetChildGroup,
                                (uint)(CollisionFilterGroups.BNoneGroup))
                                // (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
    },
};

}
}


text:
package org.opennars.ops;

import org.junit.Test;
import org.opennars.entity.Sentence;
import org.opennars.interfaces.NarseseConsumer;
import org.opennars.io.events.AnswerHandler;
import org.opennars.language.Term;
import org.opennars.main.Nar;

import static org.junit.Assert.assertTrue;

/**
 * (integration) testing of the ^system op
 */
public class TestSystemOperator {
    @Test
    public void testOpCall() throws Exception {
        { // 0 parameters, boolean result
            Nar nar = new Nar();
            nar.addPlugin(new org.opennars.operator.misc.System());
            test0Ret(nar, "bool");
            nar.cycles(500);

            // check result of call
            MyAnswerHandler handler = new MyAnswerHandler();
            nar.ask("<{?0}-->res>",handler);
            nar.cycles(100);
            assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
        }

        { // 1 parameters, boolean result
            Nar nar = new Nar();
            nar.addPlugin(new org.opennars.operator.misc.System());
            test1Ret(nar, "bool");
            nar.cycles(500);

            // check result of call
            MyAnswerHandler handler = new MyAnswerHandler();
            nar.ask("<{?0}-->res>",handler);
            nar.cycles(100);
            assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
        }

        { // 2 parameters, boolean result
            Nar nar = new Nar();
            nar.addPlugin(new org.opennars.operator.misc.System());
            test2Ret(nar, "bool");
            nar.cycles(500);

            // check result of call
            MyAnswerHandler handler = new MyAnswerHandler();
            nar.ask("<{?0}-->res>",handler);
            nar.cycles(100);
            assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
        }

        { // 3 parameters, boolean result
            Nar nar = new Nar();
            nar.addPlugin(new org.opennars.operator.misc.System());
            test3Ret(nar, "bool");
            nar.cycles(700);

            // check result of call
            MyAnswerHandler handler = new MyAnswerHandler();
            nar.ask("<{?0}-->res>",handler);
            nar.cycles(200);
            assertTrue(handler.lastAnswerTerm.toString().equals("<{true} --> res>"));
        }
    }

    /**
     *
     * @param consumer
     * @param expectedResultType datatype of the expected result
     */
    private static void test0Ret(NarseseConsumer consumer, String expectedResultType) {
        //consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ls, $ret)) =/> <{$ret}-->res>>.");
        consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, $ret)) =/> <{$ret}-->res>>.");
        consumer.addInput("<cond0-->Cond0>. :|:");
        consumer.addInput("<{#0}-->res>!");
    }

    private static void test1Ret(NarseseConsumer consumer, String expectedResultType) {
        consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, $ret)) =/> <{$ret}-->res>>.");
        consumer.addInput("<cond0-->Cond0>. :|:");
        consumer.addInput("<{#0}-->res>!");
    }

    private static void test2Ret(NarseseConsumer consumer, String expectedResultType) {
        consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, Arg1, $ret)) =/> <{$ret}-->res>>.");
        consumer.addInput("<cond0-->Cond0>. :|:");
        consumer.addInput("<{#0}-->res>!");
    }

    private static void test3Ret(NarseseConsumer consumer, String expectedResultType) {
        consumer.addInput("<(&/, <cond0-->Cond0>, (^system, {SELF}, ./src/main/resources/unittest/TestscriptRet"+expectedResultType+".sh, Arg0, Arg1, Arg2, $ret)) =/> <{$ret}-->res>>.");
        consumer.addInput("<cond0-->Cond0>. :|:");
        consumer.addInput("<{#0}-->res>!");
    }

    static class MyAnswerHandler extends AnswerHandler {
        public Term lastAnswerTerm = null;

        @Override
        public void onSolution(Sentence belief) {
            lastAnswerTerm = belief.term;
        }
    }
}


text:
<?php
namespace Echosign\RequestBuilders;

use Echosign\Interfaces\RequestBuilder;

/**
 * Class AgreementStatusUpdateInfo
 * @package Echosign\RequestBuilders
 */
class AgreementStatusUpdateInfo implements RequestBuilder
{
    protected $value = 'CANCEL';
    protected $comment;
    protected $notifySigner = false;

    /**
     * @param string $comment
     * @param bool $notifySigner
     */
    public function __construct( $comment = null, $notifySigner = false )
    {
        $this->comment      = $comment;
        $this->notifySigner = $notifySigner;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        return [
            'value'        => $this->value,
            'comment'      => $this->comment,
            'notifySigner' => $this->notifySigner
        ];
    }
}


text:
struct Vector
{
	float		x;
	float		y;

	Vector operator+( const Vector & rhs ) const
	{
		Vector vector;
		vector.x = x + rhs.x;
		vector.y = y + rhs.y;
		return vector;
	}

	Vector operator-( const Vector & rhs ) const
	{
		Vector vector;
		vector.x = x - rhs.x;
		vector.y = y - rhs.y;
		return vector;
	}

	float operator*( const Vector & position ) const
	{
		return ( x * position.x + y * position.y );
	}

	Vector operator*( const float ratio ) const
	{
		Vector vector;
		vector.x = x * ratio;
		vector.y = y * ratio;
		return vector;
	}

	Vector & operator+=( const Vector & rhs )
	{
		x += rhs.x;
		y += rhs.y;
	}

	Vector & operator-=( const Vector & rhs )
	{
		x -= rhs.x;
		y -= rhs.y;
	}
};

struct Position : public Vector
{
	Position operator+( const Vector & rhs ) const
	{
		Position position;
		position.x = x + rhs.x;
		position.y = y + rhs.y;
		return position;
	}
};

template< typename Type >
float GetDistance( Type startX, Type startY, Type targetX, Type targetY )
{
	float diffX = static_cast<float>( targetX - startX );
	float diffY = static_cast<float>( targetY - startY );

	return sqrt( pow( diffX, 2 ) + pow( diffY, 2 ) );
}

static inline float GetDistance( Position start, Position end )
{
	return GetDistance( start.x, start.y, end.x, end.y );
}


text: do let x; while (false);


text:
<!DOCTYPE html>

    <title>{% if page.title %}{{ page.title }} – {% endif %}{{ site.name }} – {{ site.description }}</title>

    {% include meta.html %}

    <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/style.css" />
    <link rel="alternate" type="application/rss+xml" title="{{ site.name }} - {{ site.description }}" href="{{ site.baseurl }}/feed.xml" />

    <link rel="apple-touch-icon" sizes="57x57" href="/assets/images/favicon/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/assets/images/favicon/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/assets/images/favicon/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/assets/images/favicon/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/assets/images/favicon/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/assets/images/favicon/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/assets/images/favicon/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/assets/images/favicon/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/assets/images/favicon/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/assets/images/favicon/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/assets/images/favicon/favicon-194x194.png" sizes="194x194">
    <link rel="icon" type="image/png" href="/assets/images/favicon/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/assets/images/favicon/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/assets/images/favicon/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/assets/images/favicon/manifest.json">
    <link rel="shortcut icon" href="/assets/images/favicon/favicon.ico">
    <meta name="msapplication-TileColor" content="#dddddd">
    <meta name="msapplication-TileImage" content="/assets/images/favicon/mstile-144x144.png">
    <meta name="msapplication-config" content="/assets/images/favicon/browserconfig.xml">
    <meta name="theme-color" content="#ffffff">

{{ site.name }}

{{ site.description }}

            Blog
            About

      {{ content }}

          {% include svg-icons.html %}

    {% include analytics.html %}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include <vespa/vespalib/util/rand48.h>
#include <vector>
#include <vespa/searchlib/queryeval/searchiterator.h>
#include <vespa/searchlib/bitcompression/compression.h>
#include <vespa/searchlib/bitcompression/posocccompression.h>

#include <vespa/searchlib/fef/termfieldmatchdata.h>
#include <vespa/searchlib/fef/termfieldmatchdataarray.h>
#include <vespa/searchlib/diskindex/fieldreader.h>
#include <vespa/searchlib/diskindex/fieldwriter.h>

namespace search::fakedata {

/**
 * General representation of a faked word, containing all features used
 * by any of the candidate posting list formats.
 */
class FakeWord
{
public:
    typedef bitcompression::PosOccFieldsParams PosOccFieldsParams;

    class DocWordPosFeature
    {
    public:
        uint32_t _elementId;
        uint32_t _wordPos;
        int32_t _elementWeight;
        uint32_t _elementLen;

        bool operator<(const DocWordPosFeature &rhs) const {
            if (_elementId != rhs._elementId)
                return _elementId < rhs._elementId;
            return _wordPos < rhs._wordPos;
        }

        DocWordPosFeature();
        ~DocWordPosFeature();
    };

    typedef std::vector<DocWordPosFeature> DocWordPosFeatureList;

    class DocWordCollapsedFeature
    {
    public:
        uint32_t _field_len;
        uint32_t _num_occs;

        DocWordCollapsedFeature();
        ~DocWordCollapsedFeature();
    };

    class DocWordFeature
    {
    public:
        uint32_t _docId;
        DocWordCollapsedFeature _collapsedDocWordFeatures;
        uint32_t _positions;
        uint32_t _accPositions; // accumulated positions for previous words

        DocWordFeature();
        ~DocWordFeature();
    };

    typedef std::vector<DocWordFeature> DocWordFeatureList;

    class Randomizer
    {
    public:
        uint32_t _random;
        int32_t _ref;

        Randomizer() : _random(0), _ref(0) {}

        bool operator<(const Randomizer &rhs) const {
            if (_random != rhs._random)
                return _random < rhs._random;
            return _ref < rhs._ref;
        }

        bool operator==(const Randomizer &rhs) const {
            return _random == rhs._random && _ref == rhs._ref;
        }

        bool isExtra() const { return _ref < 0; }

        bool isRemove() const { return isExtra() && (_ref & 1) == 0; }
        uint32_t extraIdx() const { return (~_ref) >> 1; }
    };

    class RandomizedWriter
    {
    public:
        virtual~RandomizedWriter();

        virtual void add(uint32_t wordIdx, index::DocIdAndFeatures &features) = 0;

        virtual void remove(uint32_t wordIdx, uint32_t docId) = 0;
    };

    class RandomizedReader
    {
        Randomizer _r;
        const FakeWord *_fw;
        uint32_t _wordIdx;
        bool _valid;
        std::vector<Randomizer>::const_iterator _ri;
        std::vector<Randomizer>::const_iterator _re;
        index::DocIdAndPosOccFeatures _features;
    public:
        RandomizedReader();
        void read();

        void
        write(RandomizedWriter &writer)
        {
            const FakeWord::DocWordFeature &d = _fw->getDocWordFeature(_r);
            if (_r.isRemove()) {
                writer.remove(_wordIdx, d._docId);
            } else {
                const DocWordPosFeature *p = _fw->getDocWordPosFeature(_r, d);
                FakeWord::setupFeatures(d, p, _features);
                writer.add(_wordIdx, _features);
            }
        }

        bool isValid() const { return _valid; }

        bool operator<(const RandomizedReader &rhs) const
        {
            if (_r < rhs._r)
                return true;
            if (!(_r == rhs._r))
                return false;
            return _wordIdx < rhs._wordIdx;
        }

        void setup(const FakeWord *fw, uint32_t wordIdx);
    };

    DocWordFeatureList _postings;
    DocWordPosFeatureList _wordPosFeatures;
    DocWordFeatureList _extraPostings;
    DocWordPosFeatureList _extraWordPosFeatures;
    std::vector<Randomizer> _randomizer;
    uint32_t _docIdLimit;   // Documents in index
    std::string _name;
    const PosOccFieldsParams &_fieldsParams;
    uint32_t _packedIndex;

    void
    fakeup(search::BitVector &bitmap,
           vespalib::Rand48 &rnd,
           DocWordFeatureList &postings,
           DocWordPosFeatureList &wordPosFeatures);

    void
    fakeupTemps(vespalib::Rand48 &rnd,
                uint32_t docIdLimit,
                uint32_t tempWordDocs);

    void setupRandomizer(vespalib::Rand48 &rnd);

    const DocWordFeature &
    getDocWordFeature(const Randomizer &r) const
    {
        if (r.isExtra()) {
            assert(r.extraIdx() < _extraPostings.size());
            return _extraPostings[r.extraIdx()];
        }
        assert(static_cast<uint32_t>(r._ref) < _postings.size());
        return _postings[r._ref];
    }

    const
    DocWordPosFeature *
    getDocWordPosFeature(const Randomizer &r, const DocWordFeature &d) const
    {
        if (r.isExtra()) {
            assert(d._accPositions + d._positions <=
                   _extraWordPosFeatures.size());
            return &_extraWordPosFeatures[d._accPositions];
        }
        assert(d._accPositions + d._positions <=
               _wordPosFeatures.size());
        return &_wordPosFeatures[d._accPositions];
    }

    static void
    setupFeatures(const DocWordFeature &d,
                  const DocWordPosFeature *p,
                  index::DocIdAndPosOccFeatures &features)
    {
        unsigned int positions = d._positions;
        features.clear(d._docId);
        for (unsigned int t = 0; t < positions; ++t) {
            features.addNextOcc(p->_elementId, p->_wordPos,
                                p->_elementWeight, p->_elementLen);
            ++p;
        }
        features.set_field_length(d._collapsedDocWordFeatures._field_len);
        features.set_num_occs(d._collapsedDocWordFeatures._num_occs);
    }

public:

    FakeWord(uint32_t docIdLimit,
             const std::vector<uint32_t> & docIds,
             const std::string &name,
             const PosOccFieldsParams &fieldsParams,
             uint32_t packedIndex);

    FakeWord(uint32_t docIdLimit,
             uint32_t wordDocs,
             uint32_t tempWordDocs,
             const std::string &name,
             vespalib::Rand48 &rnd,
             const PosOccFieldsParams &fieldsParams,
             uint32_t packedIndex);

    FakeWord(uint32_t docIdLimit,
             uint32_t wordDocs,
             uint32_t tempWordDocs,
             const std::string &name,
             const FakeWord &otherWord,
             size_t overlapDocs,
             vespalib::Rand48 &rnd,
             const PosOccFieldsParams &fieldsParams,
             uint32_t packedIndex);

    ~FakeWord();

    bool
    validate(search::queryeval::SearchIterator *iterator,
             const fef::TermFieldMatchDataArray &matchData,
             uint32_t stride,
             bool unpack_normal_features,
             bool unpack_interleaved_features,
             bool verbose) const;

    bool
    validate(search::queryeval::SearchIterator *iterator,
             const fef::TermFieldMatchDataArray &matchData,
             bool unpack_normal_features,
             bool unpack_interleaved_features,
             bool verbose) const;

    bool validate(search::queryeval::SearchIterator *iterator,
                  bool verbose) const;

    bool
    validate(search::diskindex::FieldReader &fieldReader,
             uint32_t wordNum,
             const fef::TermFieldMatchDataArray &matchData,
             bool decode_interleaved_features,
             bool verbose) const;

    void validate(const std::vector<uint32_t> &docIds) const;
    void validate(const BitVector &bv) const;

    bool
    dump(search::diskindex::FieldWriter &fieldWriter,
         bool verbose) const;

    const std::string &getName() const { return _name; }
    uint32_t getDocIdLimit() const { return _docIdLimit; }
    const PosOccFieldsParams &getFieldsParams() const { return _fieldsParams; }
    uint32_t getPackedIndex() const { return _packedIndex; }
    void addDocIdBias(uint32_t docIdBias);
};

}


text:
<html>

<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
<meta http-equiv="refresh" content="0; URL=http://www.pageflakes.com/">
</head>

<body>
</body>

</html>


text:
layout: post
title: Designing My Life
date: 2019-08-20 14:43 +0000
tags:
  - thoughts
---

<https://tim.blog/2018/06/21/the-tim-ferriss-show-transcripts-debbie-millman/>
<https://www.douban.com/note/720724313/>

> He had us do an exercise in that class where we had to envision the life that we could have if we pursued everything that we wanted with the certainty that whatever it is that we wanted, we would succeed.
>
> I wrote an essay in July of 2005. It was supposed to be a five-year plan. **He asked us to dream big, and not to edit and said that it had a bit of a magical quality that he experienced with his students over and over so, to be careful what we wished for.** I created this essay with these long ranging, far fetched goals that I can tell you now, 12 years later, have almost all come true. It is spooky, spooky. And so, that's an exercise I do now with my students. Milton has had one of the most
> profound impacts on my life, aside from the profound impact he's had on the world. I feel really, really lucky that I have been a student of his and have gotten to interview him now numerous times.
>
> So, let's say it is winter, 2027. What does your life look like? What are you doing? Where are you living? Who are you living with? Do you have pets? What kind of house are you in? is it an apartment? Are you in the city? Are you in the country? What does your furniture look like? What is your bed like? What are your sheets like? What kind of clothes do you wear? What kind of hair do you have? Tell me about your pets. Tell me about your significant other.
>
> Do you have children? Do you have a car? Do you have a boat? Talk about your career. What do you want? What are you reading? What are you making?
>
> What excites you? What is your health like? And write this day, this one day ten years from now. So, one day in the winter of 2027; what does your whole day look like? Start from the minute you wake up, brush your teeth, have your coffee or tea, all the way through until when you tuck yourself in at night. What is that day like for you? **Dream big. Dream without any fear. Write it all down. You don't have to share it with anyone other than yourself. Put your whole heart into it and write like
> there's no tomorrow. Write like your life depends on it because it does. And then, read it once a year and see what happens.** It's magic. It's magic, Tim.

It's an ordinary winter night, 2027. \\
I stay with my wife and my children, sitting in front of the television. There is a big mat with fantastic figures on it. I like it, as I liked the big oval mat during my childhood, which had blue strips surrounding the edge, which I used to pretend it's ocean and on which my battleship models sailed.

I will have a wife, yes, and one or two children. A boy and a girl, perhaps. They are still young and haven't reached the age for primary school.

That is an ordinary early night, so I am just sparing time with the family. Later when the kids go to bed, I turn on the computer to reply mails from work.

I still live in Shanghai, somewhere close to my old home. It's an apartment of a not-so-old neighbourhood. There are many trees and birds there. I hear bird singing every morning.\\
We live with ourselves, but very close to our parents.\\
We have a cat, older than our kids.

We have a car (or two). A boat? No. But we do spend time by the sea from time to time. (of course not the sea near Shanghai.)

The sheets, clothes are just ordinary as today. Nothing changes much. Hair? Oh, I still have plenty of hair 😁

She is a good wife. Pretty. Smart. Kind. She can speak more languages than I do. I am still trying to learn new languages (not programming ones...) We both work hard and play hard. Family takes priorities in our life. We both like music, movies, etc. We go to concerts once a month or two.

I am still in the semiconductor industry. I have experienced projects from architecture modeling to high performance software designing. I am proud of the chips we made, and the software stacks we built.
In fact, I have participated in some robot projects that use the chips from our company. Really fancy bots! (four-legged with strong ... emmm everything ...)

The world still is in short of computing power. Our efforts make the world a better place.

-----

So this is my dream, a dream cannot be accomplished by one.


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

#include "mldb/utils/environment.h"

namespace MLDB {

// everything included in arch/environment_static.cc

} // namespace MLDB