text:
namespace ExeToProcessWithMultipleNative
{
    using System;

    public class Program
    {
        public static int Main()
        {
            // you can pass ANY valid library here, it's only important that kafka runs it's internal setup :-)
            Confluent.Kafka.Library.Load("librdkafka.dll");

            QueueHelper.SendMessage("test", "message1");

            Console.WriteLine(Guid.NewGuid().ToString());
            QueueHelper.SendMessage("test", "message2");

            return 42;
        }

        public int Test()
        {
            return Main();
        }
    }
}


text:
"""Tests for fairness_indicators.remediation.weight_utils."""

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

import collections

# Standard imports
from fairness_indicators.remediation import weight_utils
import tensorflow.compat.v1 as tf

EvalResult = collections.namedtuple('EvalResult', ['slicing_metrics'])

class WeightUtilsTest(tf.test.TestCase):

  def create_eval_result(self):
    return EvalResult(slicing_metrics=[
        ((), {
            '': {
                '': {
                    'post_export_metrics/negative_rate@0.10': {
                        'doubleValue': 0.08
                    },
                    'accuracy': {
                        'doubleValue': 0.444
                    }
                }
            }
        }),
        ((('gender', 'female'),), {
            '': {
                '': {
                    'post_export_metrics/negative_rate@0.10': {
                        'doubleValue': 0.09
                    },
                    'accuracy': {
                        'doubleValue': 0.333
                    }
                }
            }
        }),
        (((u'gender', u'female'),
          (u'sexual_orientation', u'homosexual_gay_or_lesbian')), {
              '': {
                  '': {
                      'post_export_metrics/negative_rate@0.10': {
                          'doubleValue': 0.1
                      },
                      'accuracy': {
                          'doubleValue': 0.222
                      }
                  }
              }
          }),
    ])

  def create_bounded_result(self):
    return EvalResult(slicing_metrics=[
        ((), {
            '': {
                '': {
                    'post_export_metrics/negative_rate@0.10': {
                        'boundedValue': {
                            'lowerBound': 0.07,
                            'upperBound': 0.09,
                            'value': 0.08,
                            'methodology': 'POISSON_BOOTSTRAP'
                        }
                    },
                    'accuracy': {
                        'boundedValue': {
                            'lowerBound': 0.07,
                            'upperBound': 0.09,
                            'value': 0.444,
                            'methodology': 'POISSON_BOOTSTRAP'
                        }
                    }
                }
            }
        }),
        ((('gender', 'female'),), {
            '': {
                '': {
                    'post_export_metrics/negative_rate@0.10': {
                        'boundedValue': {
                            'lowerBound': 0.07,
                            'upperBound': 0.09,
                            'value': 0.09,
                            'methodology': 'POISSON_BOOTSTRAP'
                        }
                    },
                    'accuracy': {
                        'boundedValue': {
                            'lowerBound': 0.07,
                            'upperBound': 0.09,
                            'value': 0.333,
                            'methodology': 'POISSON_BOOTSTRAP'
                        }
                    }
                }
            }
        }),
        (((u'gender', u'female'),
          (u'sexual_orientation', u'homosexual_gay_or_lesbian')), {
              '': {
                  '': {
                      'post_export_metrics/negative_rate@0.10': {
                          'boundedValue': {
                              'lowerBound': 0.07,
                              'upperBound': 0.09,
                              'value': 0.1,
                              'methodology': 'POISSON_BOOTSTRAP'
                          }
                      },
                      'accuracy': {
                          'boundedValue': {
                              'lowerBound': 0.07,
                              'upperBound': 0.09,
                              'value': 0.222,
                              'methodology': 'POISSON_BOOTSTRAP'
                          }
                      }
                  }
              }
          }),
    ])

  def test_baseline(self):
    test_eval_result = self.create_eval_result()
    self.assertEqual(
        0.08,
        weight_utils.get_baseline_value(
            test_eval_result, 'Overall',
            'post_export_metrics/negative_rate@0.10'))
    self.assertEqual(
        0.09,
        weight_utils.get_baseline_value(
            test_eval_result, (('gender', 'female'),),
            'post_export_metrics/negative_rate@0.10'))
    # Test 'accuracy'.
    self.assertEqual(
        0.444,
        weight_utils.get_baseline_value(test_eval_result, 'Overall',
                                        'accuracy'))
    # Test intersectional metrics.
    self.assertEqual(
        0.222,
        weight_utils.get_baseline_value(
            test_eval_result,
            ((u'gender', u'female'),
             (u'sexual_orientation', u'homosexual_gay_or_lesbian')),
            'accuracy'))
    with self.assertRaises(ValueError):
      # Test slice not found.
      weight_utils.get_baseline_value(test_eval_result,
                                      (('nonexistant', 'slice'),), 'accuracy')
    with self.assertRaises(KeyError):
      # Test metric not found.
      weight_utils.get_baseline_value(test_eval_result, (('gender', 'female'),),
                                      'nonexistent_metric')

  def test_get_metric_value_raise_key_error(self):
    input_dict = {'': {'': {'accuracy': 0.1}}}
    metric_name = 'nonexistent_metric'
    with self.assertRaises(KeyError):
      weight_utils._get_metric_value(input_dict, metric_name)

  def test_get_metric_value_raise_unsupported_value(self):
    input_dict = {
        '': {
            '': {
                'accuracy': {
                    'boundedValue': {1}
                }
            }
        }
    }
    metric_name = 'accuracy'
    with self.assertRaises(TypeError):
      weight_utils._get_metric_value(input_dict, metric_name)

  def test_get_metric_value_raise_empty_dict(self):
    with self.assertRaises(KeyError):
      weight_utils._get_metric_value({}, 'metric_name')

  def test_create_difference_dictionary(self):
    test_eval_result = self.create_eval_result()
    res = weight_utils.create_percentage_difference_dictionary(
        test_eval_result, 'Overall', 'post_export_metrics/negative_rate@0.10')
    self.assertEqual(3, len(res))
    self.assertIn('gender-sexual_orientation', res)
    self.assertIn('gender', res)
    self.assertAlmostEqual(res['gender']['female'], 0.125)
    self.assertAlmostEqual(res[''][''], 0)

  def test_create_difference_dictionary_baseline(self):
    test_eval_result = self.create_eval_result()
    res = weight_utils.create_percentage_difference_dictionary(
        test_eval_result, (('gender', 'female'),),
        'post_export_metrics/negative_rate@0.10')
    self.assertEqual(3, len(res))
    self.assertIn('gender-sexual_orientation', res)
    self.assertIn('gender', res)
    self.assertAlmostEqual(res['gender']['female'], 0)
    self.assertAlmostEqual(res[''][''], -0.11111111)

  def test_create_difference_dictionary_bounded_metrics(self):
    test_eval_result = self.create_bounded_result()
    res = weight_utils.create_percentage_difference_dictionary(
        test_eval_result, 'Overall', 'post_export_metrics/negative_rate@0.10')
    self.assertEqual(3, len(res))
    self.assertIn('gender-sexual_orientation', res)
    self.assertIn('gender', res)
    self.assertAlmostEqual(res['gender']['female'], 0.125)
    self.assertAlmostEqual(res[''][''], 0)

if __name__ == '__main__':
  tf.test.main()

redpajama_set_name: RedPajamaGithub


text:
set -e
set -u
set -o pipefail

declare -g HAVE_LINT_ERRORS=0

run_linter() {
  local -r linter="$1"
  local -r pattern="$2"

  # We only lint the files that have been changed, so not to spam pull requests
  # with unrelated lint issues.
  local -r modified_files="$(git diff --name-only --diff-filter=ACMRTUXB HEAD~ \
    | grep -E "${pattern}" \
    | tr '\n' ' ' \
    || true)"

  if [[ -n "${modified_files}" ]]; then
    echo "${linter} ${modified_files}"
    ${linter} ${modified_files} || HAVE_LINT_ERRORS=1
    echo
  fi
}

main() {
  local -r LINT_KOTLIN="ktlint --experimental --relative"
  run_linter "${LINT_KOTLIN}" '\.kt$'

  local -r LINT_BAZEL="buildifier -mode=check -lint=warn"
  run_linter "${LINT_BAZEL}" '(^|/)BUILD.bazel$|\.bzl$'

  local -r LINT_CC="clang-format --Werror --style=Google --dry-run"
  run_linter "${LINT_CC}" '\.(cc|h)$'
  return ${HAVE_LINT_ERRORS}
}

main "$@"


text:
require 'spec_helper'

describe Puppet::Type.type(:user) do
  before :each do
    @provider_class = described_class.provide(:simple) do
      has_features :manages_expiry, :manages_password_age, :manages_passwords, :manages_solaris_rbac, :manages_shell
      mk_resource_methods
      def create; end
      def delete; end
      def exists?; get(:ensure) != :absent; end
      def flush; end
      def self.instances; []; end
    end
    described_class.stubs(:defaultprovider).returns @provider_class
  end

  it "should be able to create an instance" do
    described_class.new(:name => "foo").should_not be_nil
  end

  it "should have an allows_duplicates feature" do
    described_class.provider_feature(:allows_duplicates).should_not be_nil
  end

  it "should have a manages_homedir feature" do
    described_class.provider_feature(:manages_homedir).should_not be_nil
  end

  it "should have a manages_passwords feature" do
    described_class.provider_feature(:manages_passwords).should_not be_nil
  end

  it "should have a manages_solaris_rbac feature" do
    described_class.provider_feature(:manages_solaris_rbac).should_not be_nil
  end

  it "should have a manages_expiry feature" do
    described_class.provider_feature(:manages_expiry).should_not be_nil
  end

  it "should have a manages_password_age feature" do
    described_class.provider_feature(:manages_password_age).should_not be_nil
  end

  it "should have a system_users feature" do
    described_class.provider_feature(:system_users).should_not be_nil
  end

  it "should have a manages_shell feature" do
    described_class.provider_feature(:manages_shell).should_not be_nil
  end

  describe :managehome do
    let (:provider) { @provider_class.new(:name => 'foo', :ensure => :absent) }
    let (:instance) { described_class.new(:name => 'foo', :provider => provider) }

    it "defaults to false" do
      instance[:managehome].should be_false
    end

    it "can be set to false" do
      instance[:managehome] = 'false'
    end

    it "cannot be set to true for a provider that does not manage homedirs" do
      provider.class.stubs(:manages_homedir?).returns false
      expect { instance[:managehome] = 'yes' }.to raise_error(Puppet::Error, /can not manage home directories/)
    end

    it "can be set to true for a provider that does manage homedirs" do
      provider.class.stubs(:manages_homedir?).returns true
      instance[:managehome] = 'yes'
    end
  end

  describe "instances" do
    it "should delegate existence questions to its provider" do
      @provider = @provider_class.new(:name => 'foo', :ensure => :absent)
      instance = described_class.new(:name => "foo", :provider => @provider)
      instance.exists?.should == false

      @provider.set(:ensure => :present)
      instance.exists?.should == true
    end
  end

  properties = [:ensure, :uid, :gid, :home, :comment, :shell, :password, :password_min_age, :password_max_age, :groups, :roles, :auths, :profiles, :project, :keys, :expiry]

  properties.each do |property|
    it "should have a #{property} property" do
      described_class.attrclass(property).ancestors.should be_include(Puppet::Property)
    end

    it "should have documentation for its #{property} property" do
      described_class.attrclass(property).doc.should be_instance_of(String)
    end
  end

  list_properties = [:groups, :roles, :auths]

  list_properties.each do |property|
    it "should have a list '#{property}'" do
      described_class.attrclass(property).ancestors.should be_include(Puppet::Property::List)
    end
  end

  it "should have an ordered list 'profiles'" do
    described_class.attrclass(:profiles).ancestors.should be_include(Puppet::Property::OrderedList)
  end

  it "should have key values 'keys'" do
    described_class.attrclass(:keys).ancestors.should be_include(Puppet::Property::KeyValue)
  end

  describe "when retrieving all current values" do
    before do
      @provider = @provider_class.new(:name => 'foo', :ensure => :present, :uid => 15, :gid => 15)
      @user = described_class.new(:name => "foo", :uid => 10, :provider => @provider)
    end

    it "should return a hash containing values for all set properties" do
      @user[:gid] = 10
      values = @user.retrieve
      [@user.property(:uid), @user.property(:gid)].each { |property| values.should be_include(property) }
    end

    it "should set all values to :absent if the user is absent" do
      @user.property(:ensure).expects(:retrieve).returns :absent
      @user.property(:uid).expects(:retrieve).never
      @user.retrieve[@user.property(:uid)].should == :absent
    end

    it "should include the result of retrieving each property's current value if the user is present" do
      @user.retrieve[@user.property(:uid)].should == 15
    end
  end

  describe "when managing the ensure property" do
    it "should support a :present value" do
      expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error
    end

    it "should support an :absent value" do
      expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error
    end

    it "should call :create on the provider when asked to sync to the :present state" do
      @provider = @provider_class.new(:name => 'foo', :ensure => :absent)
      @provider.expects(:create)
      described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).sync
    end

    it "should call :delete on the provider when asked to sync to the :absent state" do
      @provider = @provider_class.new(:name => 'foo', :ensure => :present)
      @provider.expects(:delete)
      described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).sync
    end

    describe "and determining the current state" do
      it "should return :present when the provider indicates the user exists" do
        @provider = @provider_class.new(:name => 'foo', :ensure => :present)
        described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).retrieve.should == :present
      end

      it "should return :absent when the provider indicates the user does not exist" do
        @provider = @provider_class.new(:name => 'foo', :ensure => :absent)
        described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).retrieve.should == :absent
      end
    end
  end

  describe "when managing the uid property" do
    it "should convert number-looking strings into actual numbers" do
      described_class.new(:name => 'foo', :uid => '50')[:uid].should == 50
    end

    it "should support UIDs as numbers" do
      described_class.new(:name => 'foo', :uid => 50)[:uid].should == 50
    end

    it "should support :absent as a value" do
      described_class.new(:name => 'foo', :uid => :absent)[:uid].should == :absent
    end
  end

  describe "when managing the gid" do
    it "should support :absent as a value" do
      described_class.new(:name => 'foo', :gid => :absent)[:gid].should == :absent
    end

    it "should convert number-looking strings into actual numbers" do
      described_class.new(:name => 'foo', :gid => '50')[:gid].should == 50
    end

    it "should support GIDs specified as integers" do
      described_class.new(:name => 'foo', :gid => 50)[:gid].should == 50
    end

    it "should support groups specified by name" do
      described_class.new(:name => 'foo', :gid => 'foo')[:gid].should == 'foo'
    end

    describe "when testing whether in sync" do
      it "should return true if no 'should' values are set" do
        # this is currently not the case because gid has no default value, so we would never even
        # call insync? on that property
        if param = described_class.new(:name => 'foo').parameter(:gid)
          param.must be_safe_insync(500)
        end
      end

      it "should return true if any of the specified groups are equal to the current integer" do
        Puppet::Util.expects(:gid).with("foo").returns 300
        Puppet::Util.expects(:gid).with("bar").returns 500
        described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid).must be_safe_insync(500)
      end

      it "should return false if none of the specified groups are equal to the current integer" do
        Puppet::Util.expects(:gid).with("foo").returns 300
        Puppet::Util.expects(:gid).with("bar").returns 500
        described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid).must_not be_safe_insync(700)
      end
    end

    describe "when syncing" do
      it "should use the first found, specified group as the desired value and send it to the provider" do
        Puppet::Util.expects(:gid).with("foo").returns nil
        Puppet::Util.expects(:gid).with("bar").returns 500

        @provider = @provider_class.new(:name => 'foo')
        resource = described_class.new(:name => 'foo', :provider => @provider, :gid => [ 'foo', 'bar' ])

        @provider.expects(:gid=).with 500
        resource.parameter(:gid).sync
      end
    end
  end

  describe "when managing groups" do
    it "should support a singe group" do
      expect { described_class.new(:name => 'foo', :groups => 'bar') }.to_not raise_error
    end

    it "should support multiple groups as an array" do
      expect { described_class.new(:name => 'foo', :groups => [ 'bar' ]) }.to_not raise_error
      expect { described_class.new(:name => 'foo', :groups => [ 'bar', 'baz' ]) }.to_not raise_error
    end

    it "should not support a comma separated list" do
      expect { described_class.new(:name => 'foo', :groups => 'bar,baz') }.to raise_error(Puppet::Error, /Group names must be provided as an array/)
    end

    it "should not support an empty string" do
      expect { described_class.new(:name => 'foo', :groups => '') }.to raise_error(Puppet::Error, /Group names must not be empty/)
    end

    describe "when testing is in sync" do

      before :each do
        # the useradd provider uses a single string to represent groups and so does Puppet::Property::List when converting to should values
        @provider = @provider_class.new(:name => 'foo', :groups => 'a,b,e,f')
      end

      it "should not care about order" do
        @property = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ]).property(:groups)
        @property.must be_safe_insync([ 'a', 'b', 'c' ])
        @property.must be_safe_insync([ 'a', 'c', 'b' ])
        @property.must be_safe_insync([ 'b', 'a', 'c' ])
        @property.must be_safe_insync([ 'b', 'c', 'a' ])
        @property.must be_safe_insync([ 'c', 'a', 'b' ])
        @property.must be_safe_insync([ 'c', 'b', 'a' ])
      end

      it "should merge current value and desired value if membership minimal" do
        @instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
        @instance[:membership] = :minimum
        @instance[:groups].should == 'a,b,c,e,f'
      end

      it "should not treat a subset of groups insync if membership inclusive" do
        @instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
        @instance[:membership] = :inclusive
        @instance[:groups].should == 'a,b,c'
      end
    end
  end

  describe "when managing expiry" do
    it "should fail if given an invalid date" do
      expect { described_class.new(:name => 'foo', :expiry => "200-20-20") }.to raise_error(Puppet::Error, /Expiry dates must be YYYY-MM-DD/)
    end
  end

  describe "when managing minimum password age" do
    it "should accept a negative minimum age" do
      expect { described_class.new(:name => 'foo', :password_min_age => '-1') }.to_not raise_error
    end

    it "should fail with an empty minimum age" do
      expect { described_class.new(:name => 'foo', :password_min_age => '') }.to raise_error(Puppet::Error, /minimum age must be provided as a number/)
    end
  end

  describe "when managing maximum password age" do
    it "should accept a negative maximum age" do
      expect { described_class.new(:name => 'foo', :password_max_age => '-1') }.to_not raise_error
    end

    it "should fail with an empty maximum age" do
      expect { described_class.new(:name => 'foo', :password_max_age => '') }.to raise_error(Puppet::Error, /maximum age must be provided as a number/)
    end
  end

  describe "when managing passwords" do
    before do
      @password = described_class.new(:name => 'foo', :password => 'mypass').parameter(:password)
    end

    it "should not include the password in the change log when adding the password" do
      @password.change_to_s(:absent, "mypass").should_not be_include("mypass")
    end

    it "should not include the password in the change log when changing the password" do
      @password.change_to_s("other", "mypass").should_not be_include("mypass")
    end

    it "should redact the password when displaying the old value" do
      @password.is_to_s("currentpassword").should =~ /^\[old password hash redacted\]$/
    end

    it "should redact the password when displaying the new value" do
      @password.should_to_s("newpassword").should =~ /^\[new password hash redacted\]$/
    end

    it "should fail if a ':' is included in the password" do
      expect { described_class.new(:name => 'foo', :password => "some:thing") }.to raise_error(Puppet::Error, /Passwords cannot include ':'/)
    end

    it "should allow the value to be set to :absent" do
      expect { described_class.new(:name => 'foo', :password => :absent) }.to_not raise_error
    end
  end

  describe "when managing comment on Ruby 1.9", :if => String.method_defined?(:encode) do
    it "should force value encoding to ASCII-8BIT" do
      value = 'abcd™'
      value.encoding.should == Encoding::UTF_8
      user = described_class.new(:name => 'foo', :comment => value)
      user[:comment].encoding.should == Encoding::ASCII_8BIT
      user[:comment].should == value.force_encoding(Encoding::ASCII_8BIT)
    end
  end

  describe "when manages_solaris_rbac is enabled" do
    it "should support a :role value for ensure" do
      expect { described_class.new(:name => 'foo', :ensure => :role) }.to_not raise_error
    end
  end

  describe "when user has roles" do
    it "should autorequire roles" do
      testuser = described_class.new(:name => "testuser", :roles => ['testrole'] )
      testrole = described_class.new(:name => "testrole")

      config = Puppet::Resource::Catalog.new :testing do |conf|
        [testuser, testrole].each { |resource| conf.add_resource resource }
      end
      Puppet::Type::User::ProviderDirectoryservice.stubs(:get_macosx_version_major).returns "10.5"

      rel = testuser.autorequire[0]
      rel.source.ref.should == testrole.ref
      rel.target.ref.should == testuser.ref
    end
  end

  describe "when setting shell" do
    before :each do
      @shell_provider_class = described_class.provide(:shell_manager) do
        has_features :manages_shell
        mk_resource_methods
        def create; check_valid_shell;end
        def shell=(value); check_valid_shell; end
        def delete; end
        def exists?; get(:ensure) != :absent; end
        def flush; end
        def self.instances; []; end
        def check_valid_shell; end
      end

      described_class.stubs(:defaultprovider).returns @shell_provider_class
    end

    it "should call :check_valid_shell on the provider when changing shell value" do
      @provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :present)
      @provider.expects(:check_valid_shell)
      resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
      Puppet::Util::Storage.stubs(:load)
      Puppet::Util::Storage.stubs(:store)
      catalog = Puppet::Resource::Catalog.new
      catalog.add_resource resource
      catalog.apply
    end

    it "should call :check_valid_shell on the provider when changing ensure from present to absent" do
      @provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :absent)
      @provider.expects(:check_valid_shell)
      resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
      Puppet::Util::Storage.stubs(:load)
      Puppet::Util::Storage.stubs(:store)
      catalog = Puppet::Resource::Catalog.new
      catalog.add_resource resource
      catalog.apply
    end
  end

  describe "when purging ssh keys" do
    it "should not accept a keyfile with a relative path" do
      expect {
        described_class.new(:name => "a", :purge_ssh_keys => "keys")
      }.to raise_error(Puppet::Error, /Paths to keyfiles must be absolute, not keys/)
    end

    context "with a home directory specified" do
      it "should accept true" do
        described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => true)
      end
      it "should accept the ~ wildcard" do
        described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "~/keys")
      end
      it "should accept the %h wildcard" do
        described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "%h/keys")
      end
      it "raises when given a relative path" do
        expect {
          described_class.new(:name => "a", :home => "/tmp", :purge_ssh_keys => "keys")
        }.to raise_error(Puppet::Error, /Paths to keyfiles must be absolute/)
      end
    end

    context "with no home directory specified" do
      it "should not accept true" do
        expect {
          described_class.new(:name => "a", :purge_ssh_keys => true)
        }.to raise_error(Puppet::Error, /purge_ssh_keys can only be true for users with a defined home directory/)
      end
      it "should not accept the ~ wildcard" do
        expect {
          described_class.new(:name => "a", :purge_ssh_keys => "~/keys")
        }.to raise_error(Puppet::Error, /meta character ~ or %h only allowed for users with a defined home directory/)
      end
      it "should not accept the %h wildcard" do
        expect {
          described_class.new(:name => "a", :purge_ssh_keys => "%h/keys")
        }.to raise_error(Puppet::Error, /meta character ~ or %h only allowed for users with a defined home directory/)
      end
    end

    context "with a valid parameter" do
      let(:paths) do
        [ "/dev/null", "/tmp/keyfile" ].map { |path| File.expand_path(path) }
      end
      subject do
        res = described_class.new(:name => "test", :purge_ssh_keys => paths)
        res.catalog = Puppet::Resource::Catalog.new
        res
      end
      it "should not just return from generate" do
        subject.expects :find_unmanaged_keys
        subject.generate
      end
      it "should check each keyfile for readability" do
        paths.each do |path|
          File.expects(:readable?).with(path)
        end
        subject.generate
      end
    end

    describe "generated keys" do
      subject do
        res = described_class.new(:name => "test_user_name", :purge_ssh_keys => purge_param)
        res.catalog = Puppet::Resource::Catalog.new
        res
      end
      context "when purging is disabled" do
        let(:purge_param) { false }
        its(:generate) { should be_empty }
      end
      context "when purging is enabled" do
        let(:purge_param) { my_fixture('authorized_keys') }
        let(:resources) { subject.generate }
        it "should contain a resource for each key" do
          names = resources.collect { |res| res.name }
          names.should include("key1 name")
          names.should include("keyname2")
        end
        it "should not include keys in comment lines" do
          names = resources.collect { |res| res.name }
          names.should_not include("keyname3")
        end
        it "should generate names for unnamed keys" do
          names = resources.collect { |res| res.name }
          fixture_path = File.join(my_fixture_dir, 'authorized_keys')
          names.should include("#{fixture_path}:unnamed-1")
        end
        it "should each have a value for the user property" do
          resources.map { |res|
            res[:user]
          }.reject { |user_name|
            user_name == "test_user_name"
          }.should be_empty
        end
      end
    end
  end
end


text:
"""
tests desispec.fibercrosstalk
"""

import unittest

import numpy as np
from pkg_resources import resource_filename

from desispec.fibercrosstalk import correct_fiber_crosstalk
from desispec.frame import Frame
from desispec.io import empty_fibermap,read_xytraceset
from desispec.resolution import Resolution

class TestSky(unittest.TestCase):

    #- Create unique test filename in a subdirectory
    def setUp(self):
        #- Create a fake sky
        self.nspec = 20
        self.wave = np.arange(4000, 4502)
        self.nwave = len(self.wave)
        self.flux = np.zeros(self.nwave)
        for i in range(0, self.nwave, 20):
            self.flux[i] = i
        self.ivar = np.ones(self.flux.shape)
        self.psffile = resource_filename('specter', 'test/t/psf-monospot.fits')

    def _get_spectra(self,with_gradient=False):
        #- Setup data for a Resolution matrix
        sigma2 = 4.0
        ndiag = 21
        xx = np.linspace(-(ndiag-1)/2.0, +(ndiag-1)/2.0, ndiag)
        Rdata = np.zeros( (self.nspec, ndiag, self.nwave) )
        for i in range(self.nspec):
            kernel = np.exp(-(xx+float(i)/self.nspec*0.3)**2/(2*sigma2))
            #kernel = np.exp(-xx**2/(2*sigma2))
            kernel /= sum(kernel)
            for j in range(self.nwave):
                Rdata[i,:,j] = kernel

        flux = np.zeros((self.nspec, self.nwave),dtype=float)
        ivar = np.ones((self.nspec, self.nwave),dtype=float)
        # Add a random component
        for i in range(self.nspec) :
            ivar[i] += 0.4*np.random.uniform(size=self.nwave)

        mask = np.zeros((self.nspec, self.nwave), dtype=int)

        fibermap = empty_fibermap(self.nspec, 1500)
        fibermap['OBJTYPE'][0::2] = 'SKY'

        x=fibermap["FIBERASSIGN_X"]
        y=fibermap["FIBERASSIGN_Y"]
        x = x-np.mean(x)
        y = y-np.mean(y)
        if np.std(x)>0 : x /= np.std(x)
        if np.std(y)>0 : y /= np.std(y)
        w = (self.wave-self.wave[0])/(self.wave[-1]-self.wave[0])*2.-1
        for i in range(self.nspec):
            R = Resolution(Rdata[i])

            if with_gradient :
                scale = 1.+(0.1*x[i]+0.2*y[i])*(1+0.4*w)
                flux[i] = R.dot(scale*self.flux)
            else :
                flux[i] = R.dot(self.flux)
        meta={"camera":"r2"}
        return Frame(self.wave, flux, ivar, mask, Rdata, spectrograph=2, fibermap=fibermap,meta=meta)

    def test_fiber_crosstalk(self):
        #- Just a functional test
        spectra = self._get_spectra()

        xyset = read_xytraceset(self.psffile)
        correct_fiber_crosstalk(spectra,xyset=xyset)

if __name__ == '__main__':
    unittest.main()


text:
<?php
/**
* Auto generated from DiadocMessage-PostApi.proto
*
 * Diadoc.Api.Proto.Events package
 */

namespace Diadoc\Api\Proto\Events {
/**
 * DocumentSignature message
 */
class DocumentSignature extends \ProtobufMessage
{
    /* Field index constants */
    const PARENTENTITYID = 1;
    const SIGNATURE = 2;
    const SIGNWITHTESTSIGNATURE = 4;
    const ISAPPROVEMENTSIGNATURE = 5;
    const SIGNATURENAMEONSHELF = 6;
    const PATCHEDCONTENTID = 7;

    /* @var array Field descriptors */
    protected static $fields = array(
        self::PARENTENTITYID => array(
            'name' => 'ParentEntityId',
            'required' => true,
            'type' => \ProtobufMessage::PB_TYPE_STRING,
        ),
        self::SIGNATURE => array(
            'name' => 'Signature',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_STRING,
        ),
        self::SIGNWITHTESTSIGNATURE => array(
            'default' => false,
            'name' => 'SignWithTestSignature',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_BOOL,
        ),
        self::ISAPPROVEMENTSIGNATURE => array(
            'default' => false,
            'name' => 'IsApprovementSignature',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_BOOL,
        ),
        self::SIGNATURENAMEONSHELF => array(
            'name' => 'SignatureNameOnShelf',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_STRING,
        ),
        self::PATCHEDCONTENTID => array(
            'name' => 'PatchedContentId',
            'required' => false,
            'type' => \ProtobufMessage::PB_TYPE_STRING,
        ),
    );

    /**
     * Constructs new message container and clears its internal state
     */
    public function __construct()
    {
        $this->reset();
    }

    /**
     * Clears message values and sets default ones
     *
     * @return null
     */
    public function reset()
    {
        $this->values[self::PARENTENTITYID] = null;
        $this->values[self::SIGNATURE] = null;
        $this->values[self::SIGNWITHTESTSIGNATURE] = self::$fields[self::SIGNWITHTESTSIGNATURE]['default'];
        $this->values[self::ISAPPROVEMENTSIGNATURE] = self::$fields[self::ISAPPROVEMENTSIGNATURE]['default'];
        $this->values[self::SIGNATURENAMEONSHELF] = null;
        $this->values[self::PATCHEDCONTENTID] = null;
    }

    /**
     * Returns field descriptors
     *
     * @return array
     */
    public function fields()
    {
        return self::$fields;
    }

    /**
     * Sets value of 'ParentEntityId' property
     *
     * @param string $value Property value
     *
     * @return null
     */
    public function setParentEntityId($value)
    {
        return $this->set(self::PARENTENTITYID, $value);
    }

    /**
     * Returns value of 'ParentEntityId' property
     *
     * @return string
     */
    public function getParentEntityId()
    {
        $value = $this->get(self::PARENTENTITYID);
        return $value === null ? (string)$value : $value;
    }

    /**
     * Sets value of 'Signature' property
     *
     * @param string $value Property value
     *
     * @return null
     */
    public function setSignature($value)
    {
        return $this->set(self::SIGNATURE, $value);
    }

    /**
     * Returns value of 'Signature' property
     *
     * @return string
     */
    public function getSignature()
    {
        $value = $this->get(self::SIGNATURE);
        return $value === null ? (string)$value : $value;
    }

    /**
     * Sets value of 'SignWithTestSignature' property
     *
     * @param boolean $value Property value
     *
     * @return null
     */
    public function setSignWithTestSignature($value)
    {
        return $this->set(self::SIGNWITHTESTSIGNATURE, $value);
    }

    /**
     * Returns value of 'SignWithTestSignature' property
     *
     * @return boolean
     */
    public function getSignWithTestSignature()
    {
        $value = $this->get(self::SIGNWITHTESTSIGNATURE);
        return $value === null ? (boolean)$value : $value;
    }

    /**
     * Sets value of 'IsApprovementSignature' property
     *
     * @param boolean $value Property value
     *
     * @return null
     */
    public function setIsApprovementSignature($value)
    {
        return $this->set(self::ISAPPROVEMENTSIGNATURE, $value);
    }

    /**
     * Returns value of 'IsApprovementSignature' property
     *
     * @return boolean
     */
    public function getIsApprovementSignature()
    {
        $value = $this->get(self::ISAPPROVEMENTSIGNATURE);
        return $value === null ? (boolean)$value : $value;
    }

    /**
     * Sets value of 'SignatureNameOnShelf' property
     *
     * @param string $value Property value
     *
     * @return null
     */
    public function setSignatureNameOnShelf($value)
    {
        return $this->set(self::SIGNATURENAMEONSHELF, $value);
    }

    /**
     * Returns value of 'SignatureNameOnShelf' property
     *
     * @return string
     */
    public function getSignatureNameOnShelf()
    {
        $value = $this->get(self::SIGNATURENAMEONSHELF);
        return $value === null ? (string)$value : $value;
    }

    /**
     * Sets value of 'PatchedContentId' property
     *
     * @param string $value Property value
     *
     * @return null
     */
    public function setPatchedContentId($value)
    {
        return $this->set(self::PATCHEDCONTENTID, $value);
    }

    /**
     * Returns value of 'PatchedContentId' property
     *
     * @return string
     */
    public function getPatchedContentId()
    {
        $value = $this->get(self::PATCHEDCONTENTID);
        return $value === null ? (string)$value : $value;
    }
}
}


text:
package com.google.web.bindery.requestfactory.shared.messages;

public class MessageFactoryImpl extends com.google.web.bindery.autobean.gwt.client.impl.AbstractAutoBeanFactory implements com.google.web.bindery.requestfactory.shared.messages.MessageFactory {
  @Override protected void initializeCreatorMap(com.google.web.bindery.autobean.gwt.client.impl.JsniCreatorMap map) {
    map.add(com.google.web.bindery.requestfactory.shared.messages.ServerFailureMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_ServerFailureMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.IdMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_IdMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.InvocationMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_InvocationMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.JsonRpcRequest.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_JsonRpcRequest());
    map.add(com.google.web.bindery.requestfactory.shared.messages.OperationMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_OperationMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.RequestMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_RequestMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.ResponseMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_ResponseMessage());
    map.add(com.google.web.bindery.requestfactory.shared.messages.ViolationMessage.class, getConstructors_com_google_web_bindery_requestfactory_shared_messages_ViolationMessage());
    map.add(java.util.List.class, getConstructors_java_util_List());
    map.add(java.util.Set.class, getConstructors_java_util_Set());
    map.add(java.util.Map.class, getConstructors_java_util_Map());
    map.add(java.util.Iterator.class, getConstructors_java_util_Iterator());
    map.add(java.util.ListIterator.class, getConstructors_java_util_ListIterator());
    map.add(java.util.Map.Entry.class, getConstructors_java_util_Map_Entry());
    map.add(java.util.Collection.class, getConstructors_java_util_Collection());
  }
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_ServerFailureMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.ServerFailureMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.ServerFailureMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/ServerFailureMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_IdMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.IdMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.IdMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/IdMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_InvocationMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.InvocationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.InvocationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/InvocationMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_JsonRpcRequest() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.JsonRpcRequestAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.JsonRpcRequestAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/JsonRpcRequest;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_OperationMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.OperationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.OperationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/OperationMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_RequestMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.RequestMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.RequestMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/RequestMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_ResponseMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.ResponseMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.ResponseMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/ResponseMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_com_google_web_bindery_requestfactory_shared_messages_ViolationMessage() /*-{
    return [
      @com.google.web.bindery.requestfactory.shared.messages.ViolationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;),
      @com.google.web.bindery.requestfactory.shared.messages.ViolationMessageAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Lcom/google/web/bindery/requestfactory/shared/messages/ViolationMessage;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_List() /*-{
    return [
      ,
      @emul.java.util.ListAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/List;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_Set() /*-{
    return [
      ,
      @emul.java.util.SetAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/Set;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_Map() /*-{
    return [
      ,
      @emul.java.util.MapAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/Map;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_Iterator() /*-{
    return [
      ,
      @emul.java.util.IteratorAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/Iterator;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_ListIterator() /*-{
    return [
      ,
      @emul.java.util.ListIteratorAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/ListIterator;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_Map_Entry() /*-{
    return [
      ,
      @emul.java.util.Map_EntryAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/Map$Entry;)
    ];
  }-*/;
  private native com.google.gwt.core.client.JsArray<com.google.gwt.core.client.JavaScriptObject> getConstructors_java_util_Collection() /*-{
    return [
      ,
      @emul.java.util.CollectionAutoBean::new(Lcom/google/web/bindery/autobean/shared/AutoBeanFactory;Ljava/util/Collection;)
    ];
  }-*/;
  @Override protected void initializeEnumMap() {
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.PERSISTED, "0");
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.EPHEMERAL, "1");
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.SYNTHETIC, "2");
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.WriteOperation.PERSIST, "PERSIST");
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.WriteOperation.UPDATE, "UPDATE");
    enumToStringMap.put(com.google.web.bindery.requestfactory.shared.WriteOperation.DELETE, "DELETE");
    stringsToEnumsMap.put("UPDATE", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.WriteOperation.UPDATE));
    stringsToEnumsMap.put("2", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.SYNTHETIC));
    stringsToEnumsMap.put("1", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.EPHEMERAL));
    stringsToEnumsMap.put("0", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.messages.IdMessage.Strength.PERSISTED));
    stringsToEnumsMap.put("DELETE", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.WriteOperation.DELETE));
    stringsToEnumsMap.put("PERSIST", java.util.Collections.<java.lang.Enum<?>> singletonList(com.google.web.bindery.requestfactory.shared.WriteOperation.PERSIST));
  }
  public com.google.web.bindery.autobean.shared.AutoBean failure() {
    return new com.google.web.bindery.requestfactory.shared.messages.ServerFailureMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean id() {
    return new com.google.web.bindery.requestfactory.shared.messages.IdMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean invocation() {
    return new com.google.web.bindery.requestfactory.shared.messages.InvocationMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean jsonRpcRequest() {
    return new com.google.web.bindery.requestfactory.shared.messages.JsonRpcRequestAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean operation() {
    return new com.google.web.bindery.requestfactory.shared.messages.OperationMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean request() {
    return new com.google.web.bindery.requestfactory.shared.messages.RequestMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean response() {
    return new com.google.web.bindery.requestfactory.shared.messages.ResponseMessageAutoBean(MessageFactoryImpl.this);
  }
  public com.google.web.bindery.autobean.shared.AutoBean violation() {
    return new com.google.web.bindery.requestfactory.shared.messages.ViolationMessageAutoBean(MessageFactoryImpl.this);
  }
}


text:
'use strict';

module.exports = function(gulp) {
  var _ = require('underscore');

  gulp.task('watch', function() {
    var staticSources = [];
    _.each(gulp.cfg.static, function(source){
      staticSources.push(source.src);
    });

    gulp.plugin.util.log(`Watching static sources`);
    gulp.watch( staticSources, ['static'] );

    _.each(gulp.cfg.watch, (item, key) => {
      gulp.plugin.util.log(`Watching ${key}`);
      gulp.watch(item.src, item.tasks);
    });
  });
};


text:
package io.agrest.runtime.processor.update.stage;

import io.agrest.processor.Processor;
import io.agrest.processor.ProcessorOutcome;
import io.agrest.runtime.processor.update.UpdateContext;

/**
 * @since 5.0
 */
public class UpdateStartStage implements Processor<UpdateContext<?>> {

    @Override
    public ProcessorOutcome execute(UpdateContext<?> context) {
        return ProcessorOutcome.CONTINUE;
    }
}


text:
require 'spec_helper'

describe RequestLogAnalyzer::LineDefinition do

  before(:each) do
    @line_definition = RequestLogAnalyzer::LineDefinition.new(:test, {
      :teaser   => /Testing /,
      :regexp   => /Testing (\w+), tries\: (\d+)/,
      :captures => [{ :name => :what, :type => :string }, { :name => :tries, :type => :integer }]
    })
  end

  describe '#matches' do

    it "should return false on an unmatching line" do
      @line_definition.matches("nonmatching").should be_false
    end

    it "should return false when only the teaser matches" do
      @line_definition.matches("Testing LineDefinition").should be_false
    end

    it "should parse a line and capture the expected values" do
      @line_definition.matches("Testing LineDefinition, tries: 123").should == {:line_definition => @line_definition, :captures => ['LineDefinition', '123'] }
    end

    it "should know which names it can capture" do
      @line_definition.captures?(:what).should be_true
      @line_definition.captures?(:tries).should be_true
      @line_definition.captures?(:bogus).should be_false
    end

  end

  describe '#convert_captured_values' do

    before(:each) do
      @request = mock('request')
      @request.stub!(:convert_value).and_return('foo')
    end

    it "should call convert_value for every captured value" do
      @request.should_receive(:convert_value).twice
      @line_definition.convert_captured_values(['test', '123'], @request)
    end

    it "should set the converted values" do
      @line_definition.convert_captured_values(['test', '123'], @request).should == {:what => 'foo', :tries => 'foo'}
    end

    context 'when using :provides option' do
      before(:each) do
        @ld = RequestLogAnalyzer::LineDefinition.new(:test, :regexp   => /Hash\: (\{.+\})/,
            :captures => [{ :name => :hash, :type => :hash, :provides => {:bar => :string}}])

        @request = mock('request')

        @request.stub!(:convert_value).with("{:bar=>'baz'}", anything).and_return(:bar => 'baz')
        @request.stub!(:convert_value).with('baz', anything).and_return('foo')
      end

      it "should call Request#convert_value for the initial hash and the value in the hash" do
        @request.should_receive(:convert_value).with("{:bar=>'baz'}", anything).and_return(:bar => 'baz')
        @request.should_receive(:convert_value).with("baz", anything)
        @ld.convert_captured_values(["{:bar=>'baz'}"], @request)
      end

      it "should set the provides fields" do
        # The captures field must be set and converted as well
        @ld.convert_captured_values(["{:bar=>'baz'}"], @request)[:bar].should eql('foo')
      end
    end

  end
end


text:
=encoding utf8

=head1 Acme-MetaSyntactic-mlpfim

=head2 About

This is a Perl 5 CPAN distribution which provides a
L<My Little Pony - Friendship is Magic|http://mlp.wikia.com/> characters'
theme for L<Acme::MetaSyntactic|https://metacpan.org/pod/Acme::MetaSyntactic>
.

More information can be found on its MetaCPAN page:

=over 4

=item * L<http://metacpan.org/release/Acme-MetaSyntactic-mlpfim>

=back

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2015 by Shlomi Fish.

This is free software, licensed under:

  The MIT (X11) License

Note however that it contains a list of names of characters that may be
governed by copyrights and/or trademarks laws by the copyright holders of
the I<My Little Pony - Friendship is Magic> franchise.

=cut


text:
import copy

import ispyb.interface.core
from ispyb.strictordereddict import StrictOrderedDict

class Core(ispyb.interface.core.IF):
    """Core provides methods to store and retrieve data in the core tables."""

    def __init__(self):
        pass

    _proposal_params = StrictOrderedDict(
        [
            ("id", None),
            ("person_id", None),
            ("title", None),
            ("proposal_code", None),
            ("proposal_number", None),
            ("proposal_type", None),
            ("external_pk_uuid", None),
        ]
    )

    _session_for_proposal_code_number_params = StrictOrderedDict(
        [
            ("id", None),
            ("proposal_code", None),
            ("proposal_number", None),
            ("visit_number", None),
            ("beamline_setup_id", None),
            ("start_date", None),
            ("end_date", None),
            ("beamline_name", None),
            ("title", None),
            ("beamline_operator", None),
            ("nb_shifts", None),
            ("scheduled", None),
            ("used_flag", None),
            ("comments", None),
            ("external_pk_id", None),
            ("external_pk_uuid", None),
        ]
    )

    _person_params = StrictOrderedDict(
        [
            ("id", None),
            ("laboratory_id", None),
            ("family_name", None),
            ("given_name", None),
            ("title", None),
            ("email_address", None),
            ("phone_number", None),
            ("login", None),
            ("external_pk_id", None),
            ("external_pk_uuid", None),
        ]
    )

    _proposal_has_person_params = StrictOrderedDict(
        [("id", None), ("proposal_id", None), ("person_id", None), ("role", None)]
    )

    _session_has_person_params = StrictOrderedDict(
        [("session_id", None), ("person_id", None), ("role", None), ("remote", None)]
    )

    _sample_params = StrictOrderedDict(
        [
            ("id", None),
            ("authLogin", None),
            ("crystalid", None),
            ("containerid", None),
            ("name", None),
            ("code", None),
            ("location", None),
            ("holder_length", None),
            ("loop_length", None),
            ("loop_type", None),
            ("wire_width", None),
            ("comments", None),
            ("status", None),
            ("is_in_sc", None),
        ]
    )

    @classmethod
    def get_proposal_params(cls):
        return copy.deepcopy(cls._proposal_params)

    @classmethod
    def get_session_for_proposal_code_number_params(cls):
        return copy.deepcopy(cls._session_for_proposal_code_number_params)

    @classmethod
    def get_person_params(cls):
        return copy.deepcopy(cls._person_params)

    @classmethod
    def get_proposal_has_person_params(cls):
        return copy.deepcopy(cls._proposal_has_person_params)

    @classmethod
    def get_session_has_person_params(cls):
        return copy.deepcopy(cls._session_has_person_params)

    @classmethod
    def get_sample_params(cls):
        return copy.deepcopy(cls._sample_params)

    def upsert_proposal(self, values):
        """Insert or update a proposal"""
        return self.get_connection().call_sp_write(
            procname="upsert_proposal", args=values
        )

    def upsert_session_for_proposal_code_number(self, values):
        """Insert or update a session for a certain proposal with given proposal code and number."""
        return self.get_connection().call_sp_write(
            procname="upsert_session_for_proposal_code_number", args=values
        )

    def upsert_person(self, values):
        """Insert or update a person"""
        return self.get_connection().call_sp_write(
            procname="upsert_person", args=values
        )

    def upsert_session_has_person(self, values):
        """Insert or update a session-person association"""
        return self.get_connection().call_sp_write(
            procname="upsert_session_has_person", args=values
        )

    def upsert_proposal_has_person(self, values):
        """Insert or update a proposal-person association"""
        return self.get_connection().call_sp_write(
            procname="upsert_proposal_has_person", args=values
        )

    def upsert_sample(self, values):
        """Insert or update sample."""
        return self.get_connection().call_sp_write(
            procname="upsert_sample", args=values
        )

    def retrieve_samples_not_loaded_for_container_reg_barcode(self, barcode):
        """Retrieve the not-yet loaded samples in the most recent container that corresponds with the given container registry barcode"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_samples_not_loaded_for_container_reg_barcode",
            args=(barcode,),
        )

    def retrieve_visit_id(self, visit):
        """Get the database ID for a visit on the form mx1234-5."""
        return self.get_connection().call_sf_retrieve(
            funcname="retrieve_visit_id", args=(visit,)
        )

    def retrieve_datacollection_id(self, img_filename, img_fileloc):
        """Get the database ID for the data collection corresponding to the given diffraction image file."""
        return self.get_connection().call_sf_retrieve(
            funcname="retrieve_datacollection_id", args=(img_filename, img_fileloc)
        )

    def retrieve_current_sessions(self, beamline, tolerance_mins=0):
        """Get a result-set with the currently active sessions on the given beamline."""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_current_sessions", args=(beamline, tolerance_mins)
        )

    def retrieve_sessions_for_beamline_and_run(self, beamline, run):
        """Get a result-set with the sessions associated with the given beamline/instrument and run."""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_sessions_for_beamline_and_run", args=(beamline, run)
        )

    def retrieve_sessions_for_person_login(self, login):
        """Get a result-set with the sessions associated with the given unique person login."""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_sessions_for_person_login", args=(login,)
        )

    def retrieve_current_sessions_for_person(self, beamline, fed_id, tolerance_mins=0):
        """Get a result-set with the currently active sessions on the given beamline."""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_current_sessions_for_person",
            args=(beamline, fed_id, tolerance_mins),
        )

    def retrieve_most_recent_session(self, beamline, proposal_code):
        """Get a result-set with the most recent session on the given beamline for the given proposal code"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_most_recent_session", args=(beamline, proposal_code)
        )

    def retrieve_expired_sessions_for_instrument_and_period(
        self, instrument, start_date, end_date
    ):
        """Returns a multi-row result-set with the sessions that ended within the window defined by start_ate and end_date on instrument given by p_instrument (can contain database wildcards)"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_expired_sessions_for_instrument_and_period",
            args=(instrument, start_date, end_date),
        )

    def retrieve_persons_for_proposal(self, proposal_code, proposal_number):
        """Get a result-set with the persons associated with a given proposal specified by proposal code, proposal_number"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_persons_for_proposal",
            args=(proposal_code, proposal_number),
        )

    def retrieve_persons_for_session(
        self, proposal_code, proposal_number, visit_number
    ):
        """Get a result-set with the persons associated with a given session specified by proposal code, proposal_number, visit_number"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_persons_for_session",
            args=(proposal_code, proposal_number, visit_number),
        )

    def retrieve_current_cm_sessions(self, beamline):
        """Get a result-set with the currently active commissioning (cm) sessions on the given beamline."""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_current_cm_sessions", args=(beamline,)
        )

    def retrieve_active_plates(self, beamline):
        """Get a result-set with the submitted plates not yet in local storage on a given beamline"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_containers_submitted_non_ls", args=(beamline,)
        )

    def retrieve_proposal_title(self, proposal_code, proposal_number, auth_login=None):
        """Get the title of a given proposal"""
        return self.get_connection().call_sp_retrieve(
            procname="retrieve_proposal_title",
            args=(proposal_code, proposal_number, auth_login),
        )


text:
#import "CCNode+NodeInfo.h"
#import "NodeInfo.h"
#import "PlugInNode.h"
#import "SequencerNodeProperty.h"
#import "SequencerKeyframe.h"
#import "SequencerKeyframeEasing.h"
#import "AppDelegate.h"
#import "SequencerHandler.h"
#import "SequencerSequence.h"
#import "PositionPropertySetter.h"
#import "TexturePropertySetter.h"
#import "CCBDictionaryWriter.h"
#import "CCBDictionaryReader.h"
#import "CCBDocument.h"
#import "CustomPropSetting.h"
#import "CocosScene.h"
#import "NodePhysicsBody.h"
#import "PhysicsHandler.h"
#import "InspectorController.h"

NSString * kAnimationOfPhysicsWarning = @"kAnimationOfPhysicsWarning";

@implementation CCNode (NodeInfo)

- (void) setExtraProp:(id)prop forKey:(NSString *)key
{
    NodeInfo* info = self.userObject;
    if (prop)
    {
        [info.extraProps setObject:prop forKey:key];
    }
    else
    {
        [info.extraProps removeObjectForKey:key];
    }
}

- (void)removeExtraPropForKey:(NSString*)key
{
    NodeInfo* info = self.userObject;
    [info.extraProps removeObjectForKey:key];
}

- (id) extraPropForKey:(NSString *)key
{
    NodeInfo* info = self.userObject;
    return [info.extraProps objectForKey:key];
}

- (void) setSeqExpanded:(BOOL)seqExpanded
{
    [self setExtraProp:[NSNumber numberWithBool:seqExpanded] forKey:@"seqExpanded"];
}

- (BOOL) seqExpanded
{
    return [[self extraPropForKey:@"seqExpanded"] boolValue];
}

- (void) setLocked:(BOOL)locked
{
    [self setExtraProp:[NSNumber numberWithBool:locked] forKey:@"locked"];
}

- (BOOL) locked
{
    return [[self extraPropForKey:@"locked"] boolValue];
}

- (void) setHidden:(BOOL)hidden
{
    [self setExtraProp:[NSNumber numberWithBool:hidden] forKey:@"hidden"];
}

- (BOOL) hidden
{
    return [[self extraPropForKey:@"hidden"] boolValue];
}

- (BOOL) parentHidden
{
    CCNode * parent = self.parent;
    while(parent)
    {
        if(parent.hidden)
            return YES;

        parent = parent.parent;
    }

    return NO;
}

-(NSUInteger)UUID
{
    return [[self extraPropForKey:@"UUID"] unsignedIntegerValue];
}

-(void)setUUID:(NSUInteger)_UUID
{
    [self setExtraProp:@(_UUID) forKey:@"UUID"];
}

- (PlugInNode*) plugIn
{
    NodeInfo* info = self.userObject;
    return info.plugIn;
}

- (id) baseValueForProperty:(NSString*)name
{
    NodeInfo* info = self.userObject;
    return [info.baseValues objectForKey:name];
}

- (void) setBaseValue:(id)value forProperty:(NSString*)name
{
    NodeInfo* info = self.userObject;
    [info.baseValues setObject:value forKey:name];
}

- (SequencerNodeProperty*) sequenceNodeProperty:(NSString*)name sequenceId:(int)seqId
{
    NodeInfo* info = self.userObject;
    NSDictionary* dict = [info.animatableProperties objectForKey:[NSNumber numberWithInt:seqId]];
    return [dict objectForKey:name];
}

- (void) enableSequenceNodeProperty:(NSString*)name sequenceId:(int)seqId
{
    // Check if animations are already enabled for this node property
    if ([self sequenceNodeProperty:name sequenceId:seqId])
    {
        return;
    }

    // Get the right seqence, create one if neccessary
    NodeInfo* info = self.userObject;
    NSMutableDictionary* sequences = [info.animatableProperties objectForKey:[NSNumber numberWithInt:seqId]];
    if (!sequences)
    {
        sequences = [NSMutableDictionary dictionary];
        [info.animatableProperties setObject:sequences forKey:[NSNumber numberWithInt:seqId]];
    }

    id baseValue = [self valueForProperty:name atTime:0 sequenceId:seqId];

    SequencerNodeProperty* seqNodeProp = [[SequencerNodeProperty alloc] initWithProperty:name node:self];
    if (![info.baseValues objectForKey:name])
    {
        [info.baseValues setObject:baseValue forKey:name];
    }

    [sequences setObject:seqNodeProp forKey:name];
}

- (void) addKeyframe:(SequencerKeyframe*)keyframe forProperty:(NSString*)name atTime:(float)time sequenceId:(int)seqId
{
    // Check so we are not adding a keyframe out of bounds
    NSArray* seqs = [AppDelegate appDelegate].currentDocument.sequences;
    SequencerSequence* seq = NULL;
    for (SequencerSequence* seqt in seqs)
    {
        if (seqt.sequenceId == seqId)
        {
            seq = seqt;
            break;
        }
    }
    if (time > seq.timelineLength) return;

    //If not supported as animatable type, don't add.
    if(![[self.plugIn animatablePropertiesForNode:self] containsObject:name])
    {
        return;
    }

    // Save undo state
    [[AppDelegate appDelegate] saveUndoStateWillChangeProperty:@"*addkeyframe"];

    // Make sure timeline is enabled for this property
    [self enableSequenceNodeProperty:name sequenceId:seqId];

    // Add the keyframe
    SequencerNodeProperty* seqNodeProp = [self sequenceNodeProperty:name sequenceId:seqId];
    keyframe.parent = seqNodeProp;
    [seqNodeProp setKeyframe:keyframe];

    // Update property inspector
    [[InspectorController sharedController] updateInspectorFromSelection];
    [[SequencerHandler sharedHandler] redrawTimeline];
    [self updateProperty:name time:[SequencerHandler sharedHandler].currentSequence.timelinePosition sequenceId:seqId];

	[[AppDelegate appDelegate].physicsHandler willChangeValueForKey:@"selectedNodeHasKeyframes"];
	[[AppDelegate appDelegate].physicsHandler didChangeValueForKey:@"selectedNodeHasKeyframes"];
}

-(void)customVisit:(__unsafe_unretained CCRenderer *)renderer parentTransform:(const GLKMatrix4 *)parentTransform
{
    if([self.userObject isKindOfClass:[NodeInfo class]] &&  self.hidden)
        return;

    [self performSelector:@selector(oldVisit:parentTransform:) withObject:renderer withObject:(__bridge id)(parentTransform)];
}

- (SequencerKeyframe*) addDefaultKeyframeForProperty:(NSString*)name atTime:(float)time sequenceId:(int)seqId
{
    // Get property type
    NSString* propType = [self.plugIn propertyTypeForProperty:name];
    kCCBKeyframeType keyframeType = [SequencerKeyframe keyframeTypeFromPropertyType:propType];

    // Ensure that the keyframe type is supported
    if (keyframeType == kCCBKeyframeTypeUndefined)
    {
        return nil;
    }

    // Ensure that the keyframe type is animated
    if (![[self.plugIn animatablePropertiesForNode:self] containsObject:name])
    {
        return nil;
    }

    // Do not add keyframes for disabled properties
    if ([self shouldDisableProperty:name] || [self shouldDisableKeyframe:name])
        return nil;

    // Create keyframe
    SequencerKeyframe* keyframe = [[SequencerKeyframe alloc] init];
    keyframe.time = time;
    keyframe.type = keyframeType;
    keyframe.name = name;

    if (![keyframe supportsFiniteTimeInterpolations])
    {
        keyframe.easing.type = kCCBKeyframeEasingInstant;
    }

    if (keyframeType == kCCBKeyframeTypeToggle)
    {
        // Values for toggle keyframes are ignored (each keyframe toggles the state)
        keyframe.value = [NSNumber numberWithBool:YES];
    }
    else
    {
        // Get the interpolated value
        keyframe.value = [self valueForProperty:name atTime:time sequenceId:seqId];
    }

    [self addKeyframe:keyframe forProperty:name atTime:time sequenceId:seqId];
    return keyframe;
}

- (void) duplicateKeyframesFromSequenceId:(int)fromSeqId toSequenceId:(int)toSeqId
{
    NodeInfo* info = self.userObject;

    NSMutableDictionary* fromNodeProps = [info.animatableProperties objectForKey:[NSNumber numberWithInt:fromSeqId]];
    if (fromNodeProps)
    {
        for (NSString* propName in fromNodeProps)
        {
            SequencerNodeProperty* fromSeqNodeProp = [fromNodeProps objectForKey:propName];
            SequencerNodeProperty* toSeqNodeProp = [fromSeqNodeProp duplicate];

            [self enableSequenceNodeProperty:propName sequenceId:toSeqId];

            NSMutableDictionary* toNodeProps = [info.animatableProperties objectForKey:[NSNumber numberWithInt:toSeqId]];
            [toNodeProps setObject:toSeqNodeProp forKey:propName];
        }
    }

    // Also do for children
    for (CCNode* child in self.children)
    {
        [child duplicateKeyframesFromSequenceId:fromSeqId toSequenceId:toSeqId];
    }
}

- (id) valueForProperty:(NSString*)name atTime:(float)time sequenceId:(int)seqId
{
    SequencerNodeProperty* seqNodeProp = [self sequenceNodeProperty:name sequenceId:seqId];

    kCCBKeyframeType type = [SequencerKeyframe keyframeTypeFromPropertyType:[self.plugIn propertyTypeForProperty:name]];

    // Check that type is supported
    NSAssert(type, @"Unsupported animated property type (%@)",[self.plugIn propertyTypeForProperty:name]);

    id seqValue = NULL;
    if (seqNodeProp)
    {
        seqValue = [seqNodeProp valueAtTime:time];
    }
    if (seqValue)
        return seqValue;

    // Check for base value
    NodeInfo* info = self.userObject;

    id baseValue = [info.baseValues objectForKey:name];
    if (baseValue)
    {
        return baseValue;
    }

    // Just use standard value
    if (type == kCCBKeyframeTypeDegrees
        || type == kCCBKeyframeTypeByte
        || type == kCCBKeyframeTypeFloat)
    {
        return [self valueForKey:name];
    }
    else if (type == kCCBKeyframeTypePosition)
    {
        NSPoint pos = [PositionPropertySetter positionForNode:self prop:name];
        return [NSArray arrayWithObjects:
                [NSNumber numberWithFloat:pos.x],
                [NSNumber numberWithFloat:pos.y],
                nil];
    }
    else if (type == kCCBKeyframeTypeScaleLock)
    {
        float x = [PositionPropertySetter scaleXForNode:self prop:name];
        float y = [PositionPropertySetter scaleYForNode:self prop:name];
        return [NSArray arrayWithObjects:
                [NSNumber numberWithFloat:x],
                [NSNumber numberWithFloat:y],
                nil];
    }
    else if (type == kCCBKeyframeTypeToggle)
    {
        return [self valueForKey:name];
    }
    else if (type == kCCBKeyframeTypeColor3)
    {
        CCColor* colorValue = [self valueForKey:name];
        return [CCBDictionaryWriter serializeColor4:colorValue];
    }
    else if (type == kCCBKeyframeTypeSpriteFrame)
    {
        //[TexturePropertySetter
        NSString* sprite = [self extraPropForKey:name];
        NSString* sheet = [self extraPropForKey:[name stringByAppendingString:@"Sheet"]];

        return [NSArray arrayWithObjects:sprite, sheet, nil];
    }
    else if (type == kCCBKeyframeTypeFloatXY)
    {
        float x = [[self valueForKey:[name stringByAppendingString:@"X"]] floatValue];
        float y = [[self valueForKey:[name stringByAppendingString:@"Y"]] floatValue];
        return [NSArray arrayWithObjects:
                [NSNumber numberWithFloat:x],
                [NSNumber numberWithFloat:y],
                nil];
    }

    return NULL;
}

- (void) updateProperty:(NSString*) propName time:(float)time sequenceId:(int)seqId
{
    kCCBKeyframeType type = [SequencerKeyframe keyframeTypeFromPropertyType:[self.plugIn propertyTypeForProperty:propName]];

    if (!type) return;

    id value = [self valueForProperty:propName atTime:time sequenceId:seqId];

    if (type == kCCBKeyframeTypeDegrees)
    {
        [self setValue:value forKey:propName];
    }
    else if (type == kCCBKeyframeTypePosition)
    {
        NSPoint pos = NSZeroPoint;
        pos.x = [[value objectAtIndex:0] floatValue];
        pos.y = [[value objectAtIndex:1] floatValue];

        [PositionPropertySetter setPosition: pos forNode:self prop:propName];
    }
    else if (type == kCCBKeyframeTypeScaleLock)
    {
        float x = [[value objectAtIndex:0] floatValue];
        float y = [[value objectAtIndex:1] floatValue];
        int type = [PositionPropertySetter scaledFloatTypeForNode:self prop:propName];

        [PositionPropertySetter setScaledX:x Y:y type:type forNode:self prop:propName];
    }
    else if (type == kCCBKeyframeTypeToggle)
    {
        [self setValue:value forKey:propName];
    }
    else if (type == kCCBKeyframeTypeColor3)
    {
        CCColor* colorValue = [CCBDictionaryReader deserializeColor4:value];
        [self setValue:colorValue forKey:propName];

    }
    else if (type == kCCBKeyframeTypeSpriteFrame)
    {
        NSString* sprite = [value objectAtIndex:0];
        NSString* sheet = [value objectAtIndex:1];

        [TexturePropertySetter setSpriteFrameForNode:self andProperty:propName withFile:sprite andSheetFile:sheet];
    }
    else if (type == kCCBKeyframeTypeByte
             ||type == kCCBKeyframeTypeFloat)
    {
        [self setValue:value forKey:propName];
    }
    else if (type == kCCBKeyframeTypeFloatXY)
    {
        float x = [[value objectAtIndex:0] floatValue];
        float y = [[value objectAtIndex:1] floatValue];

        [self setValue:[NSNumber numberWithFloat:x] forKey:[propName stringByAppendingString:@"X"]];
        [self setValue:[NSNumber numberWithFloat:y] forKey:[propName stringByAppendingString:@"Y"]];
    }

}

- (void) updatePropertiesTime:(float)time sequenceId:(int)seqId
{
    NSArray* animatableProps = [self.plugIn animatablePropertiesForNode:self];
    for (NSString* propName in animatableProps)
    {
        [self updateProperty:propName time:time sequenceId:seqId];
    }
}

- (void) deselectAllKeyframes
{
    NodeInfo* info = self.userObject;

    NSEnumerator* animPropEnum = [info.animatableProperties objectEnumerator];
    NSDictionary* seq;
    while ((seq = [animPropEnum nextObject]))
    {
        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* prop;
        while ((prop = [seqEnum nextObject]))
        {
            [prop deselectKeyframes];
        }
    }
}

- (void) addSelectedKeyframesToArray:(NSMutableArray*)keyframes
{
    NodeInfo* info = self.userObject;

    NSEnumerator* animPropEnum = [info.animatableProperties objectEnumerator];
    NSDictionary* seq;
    while ((seq = [animPropEnum nextObject]))
    {
        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* prop;
        while ((prop = [seqEnum nextObject]))
        {
            for (SequencerKeyframe* keyframe in prop.keyframes)
            {
                if (keyframe.selected)
                {
                    [keyframes addObject:keyframe];
                }
            }
        }
    }
}

- (void) deleteSequenceId:(int) seqId
{
    NodeInfo* info = self.userObject;
    [info.animatableProperties removeObjectForKey:[NSNumber numberWithInt:seqId]];

    // Also remove for children
    for (CCNode* child in self.children)
    {
        [child deleteSequenceId:seqId];
    }
}

- (BOOL) deleteSelectedKeyframesForSequenceId:(int)seqId
{
    [[AppDelegate appDelegate] saveUndoStateWillChangeProperty:@"*deletekeyframes"];

    BOOL deletedKeyframe = NO;

    NodeInfo* info = self.userObject;
    NSMutableDictionary* seq = [info.animatableProperties objectForKey:[NSNumber numberWithInt:seqId]];
    if (seq)
    {
        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* prop;
        NSMutableArray* emptyProps = [NSMutableArray array];
        while ((prop = [seqEnum nextObject]))
        {
            for (int i = prop.keyframes.count - 1; i >= 0; i--)
            {
                SequencerKeyframe* keyframe = [prop.keyframes objectAtIndex:i];
                if (keyframe.selected)
                {
                    [prop.keyframes removeObjectAtIndex:i];
                    deletedKeyframe = YES;
                }
            }
            if (prop.keyframes.count == 0)
            {
                [emptyProps addObject:prop.propName];
            }
        }

        // Remove empty seq node props
        for (NSString* propName in emptyProps)
        {
            [seq removeObjectForKey:propName];
        }
    }

    // Also remove keyframes for children
    for (CCNode* child in self.children)
    {
        if ([child deleteSelectedKeyframesForSequenceId:seqId])
        {
            deletedKeyframe = YES;
        }
    }

	[[AppDelegate appDelegate].physicsHandler willChangeValueForKey:@"selectedNodeHasKeyframes"];
	[[AppDelegate appDelegate].physicsHandler didChangeValueForKey:@"selectedNodeHasKeyframes"];

    return deletedKeyframe;
}

- (BOOL) deleteDuplicateKeyframesForSequenceId:(int)seqId
{
    BOOL deletedKeyframe = NO;

    NodeInfo* info = self.userObject;
    NSMutableDictionary* seq = [info.animatableProperties objectForKey:[NSNumber numberWithInt:seqId]];
    if (seq)
    {
        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* seqNodeProp;
        while ((seqNodeProp = [seqEnum nextObject]))
        {
            if ([seqNodeProp deleteDuplicateKeyframes])
            {
                deletedKeyframe = YES;
            }
        }
    }

    // Also remove keyframes for children
    for (CCNode* child in self.children)
    {
        if ([child deleteDuplicateKeyframesForSequenceId:seqId])
        {
            deletedKeyframe = YES;
        }
    }
    return deletedKeyframe;
}

- (void) deleteKeyframesAfterTime:(float)time sequenceId:(int)seqId
{
    [[AppDelegate appDelegate] saveUndoStateWillChangeProperty:@"*deletekeyframes"];

    NodeInfo* info = self.userObject;
    NSMutableDictionary* seq = [info.animatableProperties objectForKey:[NSNumber numberWithInt:seqId]];

    if (seq)
    {

        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* seqNodeProp;
        NSMutableArray* emptyProps = [NSMutableArray array];

        while ((seqNodeProp = [seqEnum nextObject]))
        {
            [seqNodeProp deleteKeyframesAfterTime:time];

            if (seqNodeProp.keyframes.count == 0)
            {
                [emptyProps addObject:seqNodeProp.propName];
            }

        }

        // Remove empty seq node props
        for (NSString* propName in emptyProps)
        {
            [seq removeObjectForKey:propName];
        }
    }
    // Also remove keyframes for children
    for (CCNode* child in self.children)
    {
        [child deleteKeyframesAfterTime:time sequenceId:seqId];
    }
}

- (NSArray*) keyframesForProperty:(NSString*) prop
{
    NSMutableArray* keyframes = [NSMutableArray array];

    NodeInfo* info = self.userObject;

    NSEnumerator* animPropEnum = [info.animatableProperties objectEnumerator];
    NSDictionary* seq;
    while ((seq = [animPropEnum nextObject]))
    {
        SequencerNodeProperty* seqNodeProp = [seq objectForKey:prop];
        if (seqNodeProp)
        {
            [keyframes addObjectsFromArray:seqNodeProp.keyframes];
        }
    }
    return keyframes;
}

- (BOOL) hasKeyframesForProperty:(NSString*) prop
{
    NodeInfo* info = self.userObject;

    NSEnumerator* animPropEnum = [info.animatableProperties objectEnumerator];
    NSDictionary* seq;
    while ((seq = [animPropEnum nextObject]))
    {
        SequencerNodeProperty* seqNodeProp = [seq objectForKey:prop];
        if (seqNodeProp)
        {
            if ([seqNodeProp.keyframes count]) return YES;
        }
    }
    return NO;
}

-(BOOL)hasKeyframes
{
	NodeInfo* info = self.userObject;

	NSEnumerator* animPropEnum = [info.animatableProperties objectEnumerator];
    NSDictionary* seq;
    while ((seq = [animPropEnum nextObject]))
    {
        NSEnumerator* seqEnum = [seq objectEnumerator];
        SequencerNodeProperty* prop;
        while ((prop = [seqEnum nextObject]))
        {
			if(prop.keyframes.count > 0)
				return YES;
        }
    }

	return NO;
}

- (id) serializeAnimatedProperties
{
    NodeInfo* info = self.userObject;
    NSMutableDictionary* animatableProps = info.animatableProperties;
    if (!animatableProps.count)
    {
        return NULL;
    }

    NSMutableDictionary* serAnimatableProps = [NSMutableDictionary dictionaryWithCapacity:animatableProps.count];
    for (NSNumber* seqId in animatableProps)
    {
        NSMutableDictionary* properties = [animatableProps objectForKey:seqId];
        NSMutableDictionary* serProperties = [NSMutableDictionary dictionaryWithCapacity:animatableProps.count];

        for (NSString* propName in properties)
        {
            BOOL useFlashSkews = [self usesFlashSkew];
            if (useFlashSkews && [propName isEqualToString:@"rotation"]) continue;
            if (!useFlashSkews && [propName isEqualToString:@"rotationalSkewX"]) continue;
            if (!useFlashSkews && [propName isEqualToString:@"rotationalSkewY"]) continue;

            SequencerNodeProperty* seqNodeProp = [properties objectForKey:propName];
            [serProperties setObject:[seqNodeProp serialization] forKey:propName];
        }

        [serAnimatableProps setObject:serProperties forKey:[seqId stringValue]];
    }

    return serAnimatableProps;
}

- (void) loadAnimatedPropertiesFromSerialization:(id)ser
{
    NodeInfo* info = self.userObject;

    if (!ser)
    {
        info.animatableProperties = [NSMutableDictionary dictionary];
        return;
    }

    NSMutableDictionary* serAnimatableProps = ser;
    NSMutableDictionary* animatableProps = [NSMutableDictionary dictionaryWithCapacity:serAnimatableProps.count];

    for (NSString* seqId in serAnimatableProps)
    {
        NSMutableDictionary* serProperties = [serAnimatableProps objectForKey:seqId];
        NSMutableDictionary* properties = [NSMutableDictionary dictionaryWithCapacity:serProperties.count];

        for (NSString* propName in serProperties)
        {
            SequencerNodeProperty* seqNodeProp = [[SequencerNodeProperty alloc] initWithSerialization:[serProperties objectForKey:propName]];
            [properties setObject:seqNodeProp forKey:propName];
        }

        NSNumber* seqIdNum = [NSNumber numberWithInt:[seqId intValue]];

        [animatableProps setObject:properties forKey:seqIdNum];
    }

    info.animatableProperties = animatableProps;
}

- (NSString*) displayName
{
    CCNode* node = self;
    NodeInfo* info = node.userObject;

    if (info.displayName && ![info.displayName isEqualToString:@""]) return info.displayName;

    if (node.name != nil && ![node.name isEqualToString:@""]) return node.name;

    // Get class name
    NSString* className = @"";
    NSString* customClass = [node extraPropForKey:@"customClass"];
    if (customClass && ![customClass isEqualToString:@""]) className = customClass;
    else className = info.plugIn.nodeClassName;

    return className;
}

- (void) setDisplayName:(NSString *)displayName
{
    NodeInfo* info = self.userObject;
    info.displayName = displayName;
}

- (NSMutableArray*) customProperties
{
    NodeInfo* info = self.userObject;
    return info.customProperties;
}

- (void) setCustomProperties:(NSMutableArray *)customProperties
{
    NodeInfo* info = self.userObject;
    info.customProperties = customProperties;
}

- (NSString*) customPropertyNamed:(NSString*)name
{
    for (CustomPropSetting* setting in self.customProperties)
    {
        if ([setting.name isEqualToString:name])
        {
            return setting.value;
        }
    }
    return NULL;
}

- (void) setCustomPropertyNamed:(NSString*)name value:(NSString*)value
{
    for (CustomPropSetting* setting in self.customProperties)
    {
        if ([setting.name isEqualToString:name])
        {
            setting.value = value;
        }
    }
}

- (id) serializeCustomProperties
{
    if ([self.customProperties count] == 0)
    {
        return NULL;
    }

    NSMutableArray* ser = [NSMutableArray array];

    for (CustomPropSetting* setting in self.customProperties)
    {
        [ser addObject:[setting serialization]];
    }

    return ser;
}

- (void) loadCustomPropertiesFromSerialization:(id)ser
{
    if (!ser) return;

    NSMutableArray* customProps = [NSMutableArray array];

    for (id serSetting in ser)
    {
        [customProps addObject:[[CustomPropSetting alloc] initWithSerialization:serSetting]];
    }

    self.customProperties = customProps;
}

- (void) loadCustomPropertyValuesFromSerialization:(id)ser
{
    if (!ser) return;

    for (id serSetting in ser)
    {
        CustomPropSetting* setting = [[CustomPropSetting alloc] initWithSerialization:serSetting];
        [self setCustomPropertyNamed:setting.name value:setting.value];
    }
}

- (BOOL) shouldDisableProperty:(NSString*) prop
{
    // Disable properties on root node
    if (self == [CocosScene cocosScene].rootNode)
    {
        if ([prop isEqualToString:@"position"]) return YES;
        else if ([prop isEqualToString:@"scale"]) return YES;
        else if ([prop isEqualToString:@"rotation"]) return YES;
        else if ([prop isEqualToString:@"tag"]) return YES;
        else if ([prop isEqualToString:@"visible"]) return YES;
        else if ([prop isEqualToString:@"skew"]) return YES;
    }

    //If I'm locked.
    if(self.locked)
        return YES;

    //If this is a joint and its parent is locked. (joints inherit locked behavior from the SequencerJoints object.
    if(self.plugIn.isJoint && self.parent.locked)
        return YES;

    // Disable position property for nodes handled by layouts
    if ([self.parent isKindOfClass:[CCLayout class]] && [prop isEqualToString:@"position"])
    {
        return YES;
    }

    return NO;
}

- (BOOL)shouldDisableKeyframe:(NSString*) prop
{
    // Disable properties on root node
    if (self.nodePhysicsBody.dynamic)
    {
        if ([prop isEqualToString:@"position"]) return YES;
        else if ([prop isEqualToString:@"scale"]) return YES;
        else if ([prop isEqualToString:@"rotation"]) return YES;
        else if ([prop isEqualToString:@"skew"]) return YES;
    }

    return NO;
}

- (GLKMatrix4) startMatrix;
{
    NodeInfo* info = self.userObject;
    return info.startMatrix;
}

-(CGAffineTransform)startTransform
{
    GLKMatrix4 m = self.startMatrix;
    return CGAffineTransformMake(m.m[0], m.m[1], m.m[4], m.m[5], m.m[12], m.m[13]);
}

- (CGPoint) transformStartPosition
{
    NodeInfo* info = self.userObject;
    CGPoint anchor = self.anchorPointInPoints;
    GLKVector4 p = GLKMatrix4MultiplyVector4(info.startMatrix, GLKVector4Make(anchor.x, anchor.y, 0.0, 1.0));

    // Ignore z and perspective divide?
    return CGPointMake(p.x, p.y);
}

- (CGPoint) startAnchorPoint
{
    NodeInfo* info = self.userObject;
    return info.startAnchorPoint;
}

- (void) cacheStartTransformAndAnchor
{
    NodeInfo* info = self.userObject;
    info.startMatrix = self.nodeToWorldMatrix;
    info.startAnchorPoint = self.anchorPoint;
}

- (void) setUsesFlashSkew:(BOOL)seqExpanded
{
    [self setExtraProp:[NSNumber numberWithBool:seqExpanded] forKey:@"usesFlashSkew"];
}

- (BOOL) usesFlashSkew
{
    return [[self extraPropForKey:@"usesFlashSkew"] boolValue];
}

- (void) setNodePhysicsBody:(NodePhysicsBody *)nodePhysicsBody
{
    [self setExtraProp:nodePhysicsBody forKey:@"nodePhysicsBody"];
}

- (NodePhysicsBody*) nodePhysicsBody
{
    return [self extraPropForKey:@"nodePhysicsBody"];
}

-(void)postDeserializationFixup
{

}

-(void)postCopyFixup
{

}

- (BOOL) keyframesCanBeEdited
{
    BOOL isRootNode = [CocosScene cocosScene].rootNode == self;

    if (!isRootNode) return YES;
    if ([self.plugIn.nodeClassName isEqualToString:@"CCSprite"]) return YES;

    return NO;
}

@end


text:
layout: post
title: How to query your csv files using sqlite
---

### Prerequistes
* Make sure Sqlite3 is already installed
    * for linux: `sudo apt-get install sqlite3 libsqlite3-dev`
    * for mac: `brew install sqlite3`

start sqllite3 shell by running
``
sqlite3
``

use the `.mode` command as follows to set it to csv:

`````
.mode csv
`````
 use the `.import FILE TABLE` command to import the data from the city.csv file into the cities table.

[Clone my repo for csv files](https://github.com/rdhariwal/csvTosqlQ)

 `````
.import city.csv cities
`````
If the table does not previously exist, the first row of the CSV file is interpreted to be column names and the actual data starts on the second row of the CSV file.

To verify the import, you use the `.schema` command to display the structure of the cities table.
`````
.schema cities
`````

Query against the imported table by:
````
SELECT name, population FROM cities;
````
See if you can spot the problem between these two group of queries (hint: is population order by working?):
````
SELECT name, population FROM cities order by population desc;
SELECT name, population FROM cities order by population asc;

SELECT name, population FROM cities order by name asc;
SELECT name, population FROM cities order by name desc;
````

Drop table by:
````
DROP TABLE cities;
````

Create cities table again table:
````
CREATE TABLE cities (
  name Varchar,
  population Int
);
````

Import csv file again but now in an existing table with population as Int and no headers (if table already exists then first row of csv becomes first data row of the table)
````
.import city_no_headers.csv cities
````

Try these queries again. because the table existed with population as Int the `order by` behaviour is correct:
````
SELECT name, population FROM cities order by population desc;
SELECT name, population FROM cities order by population asc;

SELECT name, population FROM cities order by name asc;
SELECT name, population FROM cities order by name desc;
````

For more sql syntax see documentation [here](https://www.w3schools.com/sql/sql_syntax.asp)


text:
package com.saradhi;

/**
 *
 * Mediator encapsulates how set of objects (PartyMember) interact. Instead of
 * referring to each other directly they use the mediator (Party) interface.
 *
 */
public class App {

	public static void main(String[] args) {
		Party party = new PartyImpl();
		Hobbit hobbit = new Hobbit();
		Wizard wizard = new Wizard();
		Rogue rogue = new Rogue();
		Hunter hunter = new Hunter();

		party.addMember(hobbit);
		party.addMember(wizard);
		party.addMember(rogue);
		party.addMember(hunter);

		hobbit.act(Action.ENEMY);
		wizard.act(Action.TALE);
		rogue.act(Action.GOLD);
		hunter.act(Action.HUNT);
	}
}


text:
import moment from "moment";
import defaultRegex from "../regex/defaults";

const creditCard = value => {
  const replaceValue = value.replace(/-/g, "");

  if (defaultRegex.startOfVisa.test(replaceValue)) {
    const regex = /^4[0-9]{12}(?:[0-9]{3})?$/;

    return regex.test(replaceValue);
  } else if (defaultRegex.startOfMastercard.test(replaceValue)) {
    const regex = /^5[1-5][0-9]{14}$/;
    return regex.test(replaceValue);
  } else if (defaultRegex.startOfAmEx.test(replaceValue)) {
    const regex = /^3[47][0-9]{13}$/;
    return regex.test(replaceValue);
  } else if (defaultRegex.startOfDiscover.test(replaceValue)) {
    const regex = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
    return regex.test(replaceValue);
  }
  return false;
};

const creditExpiry = value => {
  let d;

  if (value.length <= 3) {
    d = value.replace(/\D/g, "");
    d = moment(value, "MM");
  } else {
    d = moment(value, "MM/YY");
    if (d.isBefore(moment().subtract(1, "month")) || d.isAfter(moment().add(15, "years"))) {
      return false;
    }
  }

  if (d == null || !d.isValid()) return false;
  return true;
};

const creditCVV = value => {
  const regex = /^[0-9]{3,4}$/;
  return regex.test(value);
};

export { creditCard, creditExpiry, creditCVV };