text:
require 'rails_helper'

# Tests for the settings plans
RSpec.describe Settings::PlansController, type: :controller do
  describe 'GET #edit' do
    before(:each) do
      @plan = FactoryGirl.create(:plan, currency: 'USD')
      @plan1 = FactoryGirl.create(:plan, currency: 'USD')
      @account = FactoryGirl.create(:account, plan: @plan)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to be_success
        expect(response).to have_http_status(:success)
      end

      it 'sets the sidebar_item to plans' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the edit template' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to render_template('edit')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns a edit account' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        a = assigns(:account)
        expect(a).to_not be_nil
        expect(a.id).to eq @account.id
        expect(a.plan_id).to eq @plan1.id
      end
    end

    context 'as super admin user' do
      before(:each) do
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to be_success
        expect(response).to have_http_status(:success)
      end

      it 'sets the sidebar_item to plans' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the edit template' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        expect(response).to render_template('edit')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns a edit account' do
        get :edit, path: @account.to_param, id: @plan1.to_param
        a = assigns(:account)
        expect(a).to_not be_nil
        expect(a.id).to eq @account.id
        expect(a.plan_id).to eq @plan1.id
      end
    end
  end

  describe 'GET #show' do
    before(:each) do
      @plan = FactoryGirl.create(:plan, currency: 'USD')
      @account = FactoryGirl.create(:account, plan: @plan)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        get :show, path: @account.to_param
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        get :show, path: @account.to_param
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        get :show, path: @account.to_param
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        @plan1 = FactoryGirl.create(:plan, currency: 'USD')
        @plan2 = FactoryGirl.create(:plan, currency: 'USD')
        @plan3 = FactoryGirl.create(:plan, currency: 'AUD')
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :show, path: @account.to_param
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'sets the sidebar_item to plans' do
        get :show, path: @account.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the show template' do
        get :show, path: @account.to_param
        expect(response).to render_template('show')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns the plans' do
        get :show, path: @account.to_param
        plans = assigns(:plans)
        expect(plans).to_not be_nil
        expect(plans.count).to eq 3
        expect(plans).to include @plan
        expect(plans).to include @plan1
        expect(plans).to include @plan2
      end
    end

    context 'as super admin user' do
      before(:each) do
        @plan1 = FactoryGirl.create(:plan, currency: 'USD')
        @plan2 = FactoryGirl.create(:plan, currency: 'USD')
        @plan3 = FactoryGirl.create(:plan, currency: 'AUD')
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :show, path: @account.to_param
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'sets the sidebar_item to plans' do
        get :show, path: @account.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the show template' do
        get :show, path: @account.to_param
        expect(response).to render_template('show')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns the plans' do
        get :show, path: @account.to_param
        plans = assigns(:plans)
        expect(plans).to_not be_nil
        expect(plans.count).to eq 3
        expect(plans).to include @plan
        expect(plans).to include @plan1
        expect(plans).to include @plan2
      end
    end
  end

  describe 'PATCH #update' do
    before(:each) do
      @plan = FactoryGirl.create(:plan, currency: 'USD')
      @plan1 = FactoryGirl.create(:plan, currency: 'USD')
      @account = FactoryGirl.create(:account, plan: @plan)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      context 'with valid attributes' do
        it 'sets the sidebar_item to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(response).to be_redirect
          expect(response).to redirect_to(settings_root_path)
        end

        it 'sets a notice' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(request.flash[:notice]).to eq 'Plan was successfully updated.'
        end
      end

      context 'with invalid attributes' do
        it 'sets the sidebar_item to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the errors/not_found template' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          expect(response).to render_template('errors/not_found')
          expect(response).to render_template('layouts/errors')
        end

        it 'it pass an existing account' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          account = assigns(:account)
          expect(account).to_not be_nil
          expect(account).to_not be_new_record
        end
      end
    end

    context 'as super admin user' do
      before(:each) do
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      context 'with valid attributes' do
        it 'sets the sidebar_item to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(response).to be_redirect
          expect(response).to redirect_to(settings_root_path)
        end

        it 'sets a notice' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: @plan1.id)
          expect(request.flash[:notice]).to eq 'Plan was successfully updated.'
        end
      end

      context 'with invalid attributes' do
        it 'sets the sidebar_item to plans' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the errors/not_found template' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          expect(response).to render_template('errors/not_found')
          expect(response).to render_template('layouts/errors')
        end

        it 'it pass an existing account' do
          patch :update, path: @account.to_param, account: FactoryGirl.attributes_for(:account, plan_id: nil)
          account = assigns(:account)
          expect(account).to_not be_nil
          expect(account).to_not be_new_record
        end
      end
    end
  end

  describe 'GET #cancel' do
    before(:each) do
      @plan = FactoryGirl.create(:plan, currency: 'USD')
      @account = FactoryGirl.create(:account, plan: @plan)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        get :cancel, path: @account.to_param
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        get :cancel, path: @account.to_param
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        get :cancel, path: @account.to_param
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :cancel, path: @account.to_param
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'sets the sidebar_item to plans' do
        get :cancel, path: @account.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the cancel template' do
        get :cancel, path: @account.to_param
        expect(response).to render_template('cancel')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns the account' do
        get :cancel, path: @account.to_param
        account = assigns(:account)
        expect(account).to_not be_nil
        expect(account).to eq @account
      end
    end

    context 'as super admin user' do
      before(:each) do
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      it 'responds successfully with an HTTP 200 status code' do
        get :cancel, path: @account.to_param
        expect(response).to be_success
        expect(response).to have_http_status(200)
      end

      it 'sets the sidebar_item to plans' do
        get :cancel, path: @account.to_param
        expect(assigns(:sidebar_item)).to eq :settings_plan
      end

      it 'renders the cancel template' do
        get :cancel, path: @account.to_param
        expect(response).to render_template('cancel')
        expect(response).to render_template('layouts/application')
      end

      it 'assigns the account' do
        get :cancel, path: @account.to_param
        account = assigns(:account)
        expect(account).to_not be_nil
        expect(account).to eq @account
      end
    end
  end

  describe 'PATCH #pause' do
    before(:each) do
      @paused_plan = FactoryGirl.create(:plan, currency: 'USD')
      @plan = FactoryGirl.create(:plan, currency: 'USD', paused_plan: @paused_plan)
      @account = FactoryGirl.create(:account, plan: @plan)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        patch :pause, path: @account.to_param
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        patch :pause, path: @account.to_param
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        patch :pause, path: @account.to_param
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      context 'is pausable' do
        it 'sets the sidebar_item to plans' do
          patch :pause, path: @account.to_param
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to the root path' do
          patch :pause, path: @account.to_param
          expect(response).to be_redirect
          expect(response).to redirect_to(root_path)
        end

        it 'sets a notice' do
          patch :pause, path: @account.to_param
          expect(request.flash[:notice]).to eq 'Account paused.'
        end
      end

      context 'is not pausable' do
        before :each do
          @plan.update_attributes(paused_plan: nil)
        end

        it 'sets the sidebar_item to plans' do
          patch :pause, path: @account.to_param
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the errors/cancel template' do
          patch :pause, path: @account.to_param
          expect(response).to render_template('cancel')
          expect(response).to render_template('layouts/application')
        end

        it 'sets a notice' do
          patch :pause, path: @account.to_param
          expect(request.flash[:alert]).to eq 'Unable to pause the account.'
        end

        it 'it pass an existing account' do
          patch :pause, path: @account.to_param
          account = assigns(:account)
          expect(account).to_not be_nil
          expect(account).to_not be_new_record
        end
      end
    end

    context 'as super admin user' do
      before(:each) do
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      context 'is pausable' do
        it 'sets the sidebar_item to plans' do
          patch :pause, path: @account.to_param
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to the root path' do
          patch :pause, path: @account.to_param
          expect(response).to be_redirect
          expect(response).to redirect_to(root_path)
        end

        it 'sets a notice' do
          patch :pause, path: @account.to_param
          expect(request.flash[:notice]).to eq 'Account paused.'
        end
      end

      context 'is not pausable' do
        before :each do
          @plan.update_attributes(paused_plan: nil)
        end

        it 'sets the sidebar_item to plans' do
          patch :pause, path: @account.to_param
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the errors/cancel template' do
          patch :pause, path: @account.to_param
          expect(response).to render_template('cancel')
          expect(response).to render_template('layouts/application')
        end

        it 'sets a notice' do
          patch :pause, path: @account.to_param
          expect(request.flash[:alert]).to eq 'Unable to pause the account.'
        end

        it 'it pass an existing account' do
          patch :pause, path: @account.to_param
          account = assigns(:account)
          expect(account).to_not be_nil
          expect(account).to_not be_new_record
        end
      end
    end
  end

  describe 'DELETE #destroy' do
    before(:each) do
      @account = FactoryGirl.create(:account)
    end

    context 'as anonymous user' do
      it 'redirects to login page' do
        cancellation_category = FactoryGirl.create(:cancellation_category)
        delete :destroy, path: @account.to_param, account: { cancellation_category_id: cancellation_category.id,
                                                             cancellation_message: '',
                                                             cancellation_reason_id: nil }
        expect(response).to be_redirect
        expect(response).to redirect_to(new_user_session_path)
      end
    end

    context 'as unauthorized users' do
      before(:each) do
        @cancellation_category = FactoryGirl.create(:cancellation_category)
        user = FactoryGirl.create(:user)
        sign_in :user, user
      end

      it 'responds with forbidden' do
        delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                             cancellation_message: '',
                                                             cancellation_reason_id: nil }
        expect(response).to be_forbidden
      end

      it 'renders the forbidden' do
        delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                             cancellation_message: '',
                                                             cancellation_reason_id: nil }
        expect(response).to render_template('errors/forbidden')
        expect(response).to render_template('layouts/errors')
      end
    end

    context 'as account admin user' do
      before(:each) do
        @cancellation_category = FactoryGirl.create(:cancellation_category)
        user = FactoryGirl.create(:user)
        FactoryGirl.create(:user_permission, account: @account, user: user, account_admin: true)
        sign_in :user, user
      end

      context 'with valid attributes' do
        it 'sets the sidebar_item to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(response).to be_redirect
          expect(response).to redirect_to(root_path)
        end

        it 'sets a notice' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(request.flash[:notice]).to eq 'Account cancelled.'
        end
      end

      context 'with invalid attributes' do
        it 'sets the sidebar_item to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the cancel template' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(response).to render_template('cancel')
          expect(response).to render_template('layouts/application')
        end

        it 'sets an alert' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(request.flash[:alert]).to eq 'Unable to cancel the account.'
        end

        it 'it pass an existing account' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          account = assigns(:account)
          expect(account).to eq @account
        end
      end
    end

    context 'as super admin user' do
      before(:each) do
        @cancellation_category = FactoryGirl.create(:cancellation_category)
        admin = FactoryGirl.create(:admin)
        sign_in :user, admin
      end

      context 'with valid attributes' do
        it 'sets the sidebar_item to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it redirects to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(response).to be_redirect
          expect(response).to redirect_to(root_path)
        end

        it 'sets a notice' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: @cancellation_category.id,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(request.flash[:notice]).to eq 'Account cancelled.'
        end
      end

      context 'with invalid attributes' do
        it 'sets the sidebar_item to plans' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(assigns(:sidebar_item)).to eq :settings_plan
        end

        it 'it renders the cancel template' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(response).to render_template('cancel')
          expect(response).to render_template('layouts/application')
        end

        it 'sets an alert' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          expect(request.flash[:alert]).to eq 'Unable to cancel the account.'
        end

        it 'it pass an existing account' do
          delete :destroy, path: @account.to_param, account: { cancellation_category_id: nil,
                                                               cancellation_message: '',
                                                               cancellation_reason_id: nil }
          account = assigns(:account)
          expect(account).to eq @account
        end
      end
    end
  end
end


text:
<?php
return [
    '@class' => 'Grav\\Common\\File\\CompiledYamlFile',
    'filename' => '/home/ubuntu/workspace/user/config/site.yaml',
    'modified' => 1476642974,
    'data' => [
        'title' => 'GLUG-NITH',
        'author' => [
            'name' => 'GLUG - NITH Community',
            'email' => 'lokeshhsharma@gmail.com'
        ],
        'taxonomies' => [
            0 => 'category',
            1 => 'tag'
        ],
        'metadata' => [
            'description' => 'GLUG NITH is a moniker for the GNU/Linux User Group of National Institute of Technology, Hamirpur. Our GLUG is mainly designed to cater to the GNU/Linux related needs of the students, faculty, staff, and anybody else belonging to NIT Hamirpur. We are a heterogeneous mixture of people ranging from the beta testers and kernel hackers to the fresh-faced newbies, held together together by a common love for GNU/Linux in particular and Free Software in general.',
            'author' => 'GLUG - NITH Community',
            'keywords' => 'LUG, LUG India, GLUG, NITH, Linux User Groups, Ubuntu Mirrors, fedora mirrors, LDP mirror, Linux, Unix, Glug, Hamirpur, NIT, NIT Hamirpur, LUG Shimla, NIT club, Glug community, Open source'
        ],
        'summary' => [
            'enabled' => true,
            'format' => 'short',
            'size' => 300,
            'delimiter' => '==='
        ],
        'blog' => [
            'route' => '/blog'
        ]
    ]
];

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Mvvm;
using Prism.Regions;

namespace Get.the.solution.Prism.Modul
{
    /// <summary>
    /// Provides logical functionality for a view.
    /// </summary>
    [Export]
    public class UserControl2ViewModel : BindableBase
    {
        public UserControl2ViewModel()
        {
            Text = "UserControl2ViewModel";
        }
        private string _text;

        public string Text
        {
            get { return _text; }
            set
            {
                _text = value;
                OnPropertyChanged("Text");
            }
        }
    }
}


text:
#ifndef ALITRACKCOMPARISON_H
#define ALITRACKCOMPARISON_H

//-------------------------------------------------------------------
// Base class to test the extrapolation performance from TPC to outer
// detectors. Several member functions AddTracks() with different
// arguments can be called to execute extrapolation and several
// THnSparse are filled with residuls and basic track information
//
// Anthor: R.Ma, M.Ivanov 02/04/2011
//--------------------------------------------------------------------

#include "TNamed.h"
#include "TMatrixDfwd.h"
class THnSparse;
class TCollection;
class AliExternalTrackParam;
class AliTrackPointArray;
class AliTrackPoint;
class TParticle;
class AliTrackReference;
class TObjArray;
class TTreeSRedirector;

class AliTrackComparison:public TNamed {
public:
  AliTrackComparison();
  AliTrackComparison(const Text_t *name, const Text_t *title);
  AliTrackComparison(const AliTrackComparison& comp);
  AliTrackComparison& operator=(const AliTrackComparison& comp);
  virtual ~AliTrackComparison();
  //Make histograms
  void Init();

  //Main process functions
  Int_t AddTracks(AliExternalTrackParam *param0,  AliExternalTrackParam *param1, Double_t mass);
  Int_t AddTracks(AliTrackReference *ref0,  AliTrackReference *ref1, Double_t mass, Int_t charge);
  Int_t AddTracks(AliExternalTrackParam *param0,  AliTrackPoint *point1, Double_t mass, Double_t energy, Double_t *vxyz);
  AliExternalTrackParam *MakeTrack(const AliTrackReference *ref, Int_t charge);
  Bool_t PropagateToPoint(AliExternalTrackParam *param0,AliExternalTrackParam *param1, Double_t mass);

  //Set the step used in extrapolatoin
  void SetStep(Double_t step){fStep=step;}

  //Set the range of the first bins of the THnSparse
  void SetRangeDY(Double_t lowBinDY, Double_t upBinDY) {fLowBinDY=lowBinDY,fUpBinDY=upBinDY;}
  void SetRangeDZ(Double_t lowBinDZ, Double_t upBinDZ) {fLowBinDZ=lowBinDZ,fUpBinDZ=upBinDZ;}
  void SetRangeDSnp(Double_t lowBinDSnp, Double_t upBinDSnp){fLowBinDSnp=lowBinDSnp;fUpBinDSnp=upBinDSnp;}
  void SetRangeDTheta(Double_t lowBinDTheta, Double_t upBinDTheta) {fLowBinDTheta=lowBinDTheta;fUpBinDTheta=upBinDTheta;}
  void SetRange1Pt(Double_t lowBin1Pt, Double_t upBin1Pt) {fLowBin1Pt=lowBin1Pt;fUpBin1Pt=upBin1Pt;}
  void SetRange1PtLoss(Double_t lowBin1PtLoss, Double_t upBin1PtLoss) {fLowBin1PtLoss=lowBin1PtLoss;fUpBin1PtLoss=upBin1PtLoss;}

  //Set number of bins
  void SetNBins(Int_t nBinsDY, Int_t nBinsDZ, Int_t nBinsDSnp, Int_t nBinsDTheta, Int_t nBins1Pt, Int_t nBins1PtLoss)
  {
    fNBinsDY=nBinsDY;
    fNBinsDZ=nBinsDZ;
    fNBinsDSnp=nBinsDSnp;
    fNBinsDTheta=nBinsDTheta;
    fNBins1Pt=nBins1Pt;
    fNBins1PtLoss=nBins1PtLoss;
  }

  //Set the layer ID of the detectors. Refer to AliGeomManager.h
  void SetLayerID(Double_t layerID) {fLayerID=layerID;}

  //Set the flag to fill all the THnSparse's. By default it is kTURE
  void SetFillAll(Bool_t fillAll) {fFillAll=fillAll;}

  //Fill the THnSparse
  void FillHistos(AliExternalTrackParam *param0, AliExternalTrackParam *param1, Double_t tr1Pt);

  //Getter
  THnSparse *GetHnSparse(Int_t index) {return fResolHisto[index];}

  //Used to redirect the output THnSparse into TTreeSRedirector
  void MakeDistortionMap(Double_t refX, Int_t type);

  //Set number of bins used to combine statistics
  void SetNCombineBin(Int_t nCombineBin) {fNCombineBin=nCombineBin;}

  virtual Long64_t       Merge(TCollection *const li);
  virtual void           Add(AliTrackComparison *const comp);
  void Analyze(); //Not implemented

protected:
  void    MakeHistos();     //Initialize all the THnSparse
  Double_t fStep;           //Step used in extrapolation
  Double_t fLowBinDY;       //First bin of residual in Y
  Double_t fUpBinDY;        //Last bin of residual in Y
  Double_t fLowBinDZ;       //First bin of residual in Z
  Double_t fUpBinDZ;        //Last bin of residual in Z
  Double_t fLowBinDSnp;     //First bin of residual in sin(phi)
  Double_t fUpBinDSnp;      //Last bin of residual in sin(phi)
  Double_t fLowBinDTheta;   //First bin of residual in Theta
  Double_t fUpBinDTheta;    //Last bin of residual in Theta
  Double_t fLowBin1Pt;      //First bin of residual in 1/pT
  Double_t fUpBin1Pt;       //Last bin of residual in 1/pT
  Double_t fLowBin1PtLoss;  //First bin of corrected energy loss
  Double_t fUpBin1PtLoss;   //Last bin of corrected energy loss
  Int_t fNBinsDY;           //NBins of residual in Y
  Int_t fNBinsDZ;           //NBins of residual in Z
  Int_t fNBinsDSnp;         //NBins of residual in sin(phi)
  Int_t fNBinsDTheta;       //NBins of residual in Theta
  Int_t fNBins1Pt;          //NBins of residual in 1/pT
  Int_t fNBins1PtLoss;      //NBins of corrected energy loss
  Double_t fLayerID;        //Detector layer ID
  Bool_t fFillAll;          //Flag to fill all the THnSparse
  Int_t fNCombineBin;       //Number of bins used to combine statistics in MakeDistortionMap()

  THnSparse *fResolHisto[6];//Output THnSparse

  ClassDef(AliTrackComparison, 4);
};

#endif


text:
<?php
namespace Df\Framework\Plugin\Data\Form\Element;
use Df\Config\Backend as B;
use Df\Framework\Form\ElementI as El;
use Magento\Framework\Data\Form\Element\Fieldset as Sb;
# 2016-08-03
class Fieldset {
	/**
	 * 2016-08-03
	 * Начиная с Magento 2.1.0 backend model создаётся только если данные присутствуют в базе данных
	 * для конкретной области действия настроек (scope и scopeId).
	 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Config/Block/System/Config/Form.php#L309-L327
	 * Если данные отсутстствуют в БД для конкретной области действия настроек,
	 * то backend model вообще не создаётся,
	 * однако данные всё равно извлекаются из БД из общей области действия настроек:
	 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Config/Block/System/Config/Form.php#L323-L327
	 * Видимо, такое поведение дефектно: данные могут попасть в форму
	 * в обход обработки и валидации их в backend model.
	 *
	 * Ранее (до версии 2.1.0) backend model создавалась в любом случае:
	 * такое поведение я считаю более верным:
	 * https://github.com/magento/magento2/blob/2.0.8/app/code/Magento/Config/Block/System/Config/Form.php#L330-L342
	 *
	 * В плагин мы попадаем отсюда: @see \Magento\Config\Block\System\Config\Form::_initElement()
	 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Config/Block/System/Config/Form.php#L347-L367
	 *
	 * @see \Magento\Framework\Data\Form\Element\Fieldset::addField()
	 * @param array(string => mixed) $config
	 * @return array(string|bool|array(string => mixed))
	 */
	function beforeAddField(
		Sb $sb, string $elementId, string $type, array $config, bool $after = false, bool $isAdvanced = false
	):array {
		$fc = dfa($config, 'field_config'); /** @var array(string => mixed)|null $fc */
		# 2016-09-27
		# Модуль Unirgy Dropship ошибочно пихает в $fc объект класса stdClass вместо массива:
		# https://code.dmitry-fedyuk.com/m2e/stripe/issues/5
		if ($fc && is_array($fc)) {
			$path = df_cc_path(dfa($fc, 'path'), dfa($fc, 'id')); /** @var string|null $path */
			$backendC = dfa($fc, 'backend_model'); /** @var string|null $backendC */
			/**
			 * 2016-08-03
			 * Конкретное значение тега «type» из system.xml можно получить вызовом dfa($fc, 'type')
			 * Однако нам это не нужно: достаточно использовать аргумент $type:
			 * @see \Magento\Config\Model\Config\Structure\Element\Field::getType()
			 */
			$value = dfa($config, 'value'); /** @var mixed|null $value */
			if ($path && $backendC && !B::processed($path) && is_a($type, El::class, true) && !is_null($value)) {
				/**
				 * 2016-08-03
				 * By analogy with @see \Magento\Config\Block\System\Config\Form::_initElement()
				 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Config/Block/System/Config/Form.php#L314-L320
				 */
				$b = df_new_om($backendC); /** @var B $b */
				$b->setPath($path);
				$b->setValue($value);
				/** 2016-08-03 By analogy with @see \Magento\Config\Block\System\Config\Form::getWebsiteCode() */
				$b->setWebsite(df_request('website', ''));
				/** 2016-08-03 By analogy with @see \Magento\Config\Block\System\Config\Form::getStoreCode() */
				$b->setStore(df_request('store', ''));
				$b->afterLoad();
				$config['value'] = $b->getValue();
			}
		}
		return [$elementId, $type, $config, $after, $isAdvanced];
	}
}


text:
\h1{Рандомизированная un montón de}

Рандомизированная un montón (aleatorios heap) --- esto es un montón, que mediante el uso de un generador de números aleatorios permite realizar todas las operaciones necesarias por logarítmica de la hora prevista.

\bf{un Montón de} se llama árbol binario, para cualquier picos que con razón, que el valor en la cima, menos o igual que los valores en todos sus descendientes (esto es un montón de mínimo; por supuesto, de forma simétrica, se puede determinar el montón de máximo). Por lo tanto, en la raíz de la pila, se encuentra siempre el mínimo.

Estándar de un conjunto de operaciones definido por montones, es la siguiente:
\ul{
\li Adición de un elemento de
\li Encontrar el mínimo
\li Extracción mínimo (eliminación de la madera y el reembolso de su valor)
\li Fusión de dos de los montones (se devuelve el montón que contiene elementos de las dos montones; duplicados no se borran)
\li Eliminación arbitraria de un elemento al punto conocido en el árbol)
}

Рандомизированная un montón permite realizar todas estas operaciones por hora prevista de $O(\log n)$ de muy fácil aplicación.

\h2{Estructura de datos}

En seguida describiremos la estructura de datos que describe binaria de un montón:
\code
struct tree {
T value;
tree * l, * r;
};
\endcode
En la parte superior del árbol se almacena el valor de $\rm value$ un $\rm T$, para el que se define el operador de comparación ($\rm operator\ <$). Además, se almacenan punteros a izquierda y derecha de los hijos (que son iguales a 0, si el hijo no está disponible).

\h2{la Ejecución de las operaciones}

Es fácil comprender que todas las operaciones sobre el montón se reducen a una sola operación: \bf{fusionar} dos montones en una sola. De hecho, la adición de un elemento en una pila equivalente a la fusión de este montón de un montón formado por un único elemento que se debe añadir. Encontrar el mínimo no requiere ninguna acción --- el mínimo es simplemente la raíz de la pila. Extracción de un mínimo equivalente a la que la pila se reemplaza por el resultado de la fusión de la izquierda y la derecha en el subárbol de la raíz. Por último, la eliminación arbitraria de un elemento como el de eliminar el mínimo: todo el subárbol con raíz en la cima, se reemplaza por el resultado de la fusión de dos subárboles hijos de esta cima.

Entonces, tenemos en realidad es necesario realizar la operación de la fusión de dos de los montones de todas las demás operaciones trivial se reducen a esta operación.

Que se dan las dos de la pila $T_1$ y $T_2$, desea volver a su unificación. Está claro que en la raíz de cada uno de estos montones se encuentran sus mínimos, por lo tanto, en la raíz de la resultante de la pila será el mínimo de los dos valores. Así, comparamos, en la raíz de cuál de los montones se encuentra en un valor inferior, lo colocamos en la raíz de un resultado, y ahora tenemos que unir a los hijos el vértice seleccionado con el resto de su montón. Si nosotros por cualquier motivo a elegir uno de los dos hijos, entonces necesitamos combinar simplemente un subárbol en la raíz de este hijo con un montón de. Por lo tanto, hemos llegado de nuevo a la operación de combinación de correspondencia. Tarde o temprano, este proceso se detiene (se necesitará, por supuesto, no es más que la suma de las alturas de pilas).

Por lo tanto, para lograr una асимптотики en promedio, necesitamos especificar el método de selección de uno de los dos hijos, con el fin de, en promedio, la longitud de tratamiento camino resultaba sería del orden del logaritmo del número de elementos en la pila. Es fácil adivinar que producir esta opción vamos a \bf{accidentalmente}, por lo tanto, la aplicación de la operación de fusión se obtiene es:

\code
tree * merge (tree * t1, tree * t2) {
if (!t1 || !t2)
return t1 ? t1 : t2;
if (t2->value < t1->value)
swap (t1, t2);
if (rand() & 1)
swap (t1->l, t1->r);
t1->l = merge (t1->l, t2);
return t1;
}
\endcode

Aquí, primero se comprueba si al menos uno de los montones está vacía, entonces ninguna acción de la fusión de producir no es necesario. De lo contrario, nos hacemos un montón de $\rm t1$ era un montón de menor valor en la raíz (que alquilamos $\rm t1,$ y $\rm t2$, si es necesario). Por último, consideramos que la segunda un montón de $\rm t2$ vamos a fusionar con el hijo izquierdo de la raíz de la pila $\rm t1$, por lo que nos aleatoriamente alquilamos izquierdo y derecho de los hijos, y a continuación, hacemos la fusión de la izquierda del hijo, y del segundo montón.

\h2{Asíntotas}

Introducimos accidental de la cantidad de $h(T)$ y que indica \bf{longitud aleatoria camino} desde la raíz hasta la hoja de cálculo (la longitud de las aristas). Está claro que el algoritmo de $\rm merge$ se $O(h(T1)+h(T2))$ de operaciones. Por lo tanto, para el estudio de асимптотики algoritmo es necesario explorar accidental de la cantidad de $h(T)$.

\h3{expectativa}

Se afirma que la expectativa $h(T)$ se estima superior логарифмом del número $n$ vértices en este montón:
$$ Eh(T) \le \log(n+1) $$

Se demuestra esto fácilmente por inducción. Que $L$ y $R$ - - -, respectivamente, la izquierda y la derecha subárboles de la raíz de la pila $T$, y $n_L$ y $n_R$ --- el número de vértices en ellos (es claro que $n = n_L+n_R+1$).

Entonces es justo:
$$ Eh(T) = 1 + \frac{1}{2}(Eh(L) + Eh(R)) \le 1 + \frac{1}{2}(\log(n_L+1) + \log(n_R+1)) = $$
$$ = 1 + \log \sqrt{ (n_L+1)(n_R+1) } = \log 2 \sqrt{ (n_L+1)(n_R+1) } \le $$
$$ \le \log \frac{ 2 ((n_L+1) + (n_R+1)) }{ 2 } = \log (n_L + n_R + 2) = \log(n+1) $$
que se quería demostrar.

\h3{Exceso esperado de la evaluación}

Demostramos que la probabilidad de exceder un recibida por encima de evaluación de la pequeña:
$$ P\{ h(T) > (c+1) \log n \} < \frac{1}{n^c} $$
para cualquier constante positiva $c$.

Se denota por $P$ muchos de los caminos desde la raíz de la pila de hojas, longitud supera $(c+1) \log n$. Tenga en cuenta que para cualquier ruta $p$ de longitud $|p|$ la probabilidad como accidental de la ruta será el elegido fue él, es de $2^{-|p|}$. Entonces obtenemos:
$$ P\{ h(T) > (c+1) \log n \} = \sum_{p \in P} 2^{-|p|} < \sum_{p \in P} 2^{-(c+1) \log n} = |P| n^{-(c+1)} \le n^{c} $$
que se quería demostrar.

\h3{Asíntotas algoritmo}

Por lo tanto, el algoritmo de $\rm merge$, y, por tanto, todos los demás se expresan a través de él, la operación se lleva a cabo en $O(\log n)$ en promedio.

Además, para cualquier constante positiva $\epsilon$ hay tal positiva constante $c$, que la probabilidad de que la operación requiere de más de $c \log n$ de las operaciones, menos de $n^{-\epsilon}$ (esto es, en cierto sentido, describe el peor comportamiento del algoritmo).


text:
import datetime
from pprint import pprint

from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone

from fo2.connections import db_cursor_so

from utils.functions.models.dictlist import dictlist_lower
from utils.functions.queries import debug_cursor_execute
import logistica.models as models

class Command(BaseCommand):
    help = 'BUG CORRECT TO: ' \
        'Repair zeroed SEQUENCIA_ESTAGIO field in PCPC_040 TABLE.'

    def handle(self, *args, **options):
        self.stdout.write('---\n{}'.format(datetime.datetime.now()))
        # try:
        cursor = db_cursor_so()

        # get primeira OP com mais de um padrão de SEQUENCIA_ESTAGIO
        sql_get = '''
            SELECT
              oo.*
            FROM (
              SELECT
                oe.OP
              , count(*)
              FROM (
                SELECT DISTINCT
                  le.ORDEM_PRODUCAO OP
                , le.SEQUENCIA_ESTAGIO SEQEST
                , le.CODIGO_ESTAGIO
                FROM pcpc_040 le
                WHERE le.SEQUENCIA_ESTAGIO = 1
                --  AND le.ORDEM_PRODUCAO = 1637
              ) oe
              GROUP BY
                oe.OP
              , oe.SEQEST
              HAVING
                count(*) > 1
              ORDER BY
                2 DESC
              , 1
            ) oo
            WHERE rownum <= 10
        '''
        cudebug_cursor_execute(cursor, sql_get)
        ops = dictlist_lower(cursor)
        # self.stdout.write('len(ops) = {}'.format(len(ops)))
        # self.stdout.write('op = {}'.format(ops[0]['op']))
        for opr in ops:
            op = opr['op']
            self.stdout.write('--- op = {}'.format(op))

            # get lotes dessa OP
            sql_get = '''
                SELECT DISTINCT
                  le.PERIODO_PRODUCAO PERIODO
                , le.ORDEM_CONFECCAO OC
                FROM pcpc_040 le
                WHERE le.ORDEM_PRODUCAO = %s
                --  AND rownum = 1
                ORDER BY
                  le.PERIODO_PRODUCAO
                , le.ORDEM_CONFECCAO
            '''
            cursor.debug_cursor_execute(cursor, sql_get, [op])
            lotes = dictlist_lower(cursor)
            self.stdout.write('len(lotes) = {}'.format(len(lotes)))
            # pprint(lotes)

            # get new value to SEQUENCIA_ESTAGIO based in
            # SEQ_OPERACAO and ROWIDs
            sql_seq = '''
                SELECT
                  s.*
                FROM (
                  SELECT
                    ROW_NUMBER() OVER (
                      PARTITION BY le.ORDEM_CONFECCAO
                      ORDER BY le.SEQ_OPERACAO, le.ROWID
                    ) SEQ
                  , le.SEQUENCIA_ESTAGIO
                  , le.SEQ_OPERACAO
                  , le.ROWID RID
                  FROM pcpc_040 le
                  WHERE le.PERIODO_PRODUCAO = %s
                    AND le.ORDEM_CONFECCAO = %s
                  ORDER BY
                    le.SEQ_OPERACAO
                  , le.ROWID
                ) s
                WHERE s.SEQ <> s.SEQUENCIA_ESTAGIO
            '''
            for lote in lotes:
                # self.stdout.write(str([lote['periodo'], lote['oc']]))
                debug_cursor_execute(cursor, sql_seq, [lote['periodo'], lote['oc']])
                seqs = dictlist_lower(cursor)
                # self.stdout.write('len(seqs) = {}'.format(len(seqs)))
                # pprint(seqs)
                if len(seqs) == 0:
                    continue
                self.stdout.write(str(lote))

                sql_setseq = '''
                    UPDATE pcpc_040 le
                    SET
                      le.SEQUENCIA_ESTAGIO = %s
                    WHERE le.ROWID = %s
                '''
                for seq in seqs:
                    self.stdout.write(str([seq['rid'], seq['seq']]))
                    # self.stdout.write(str(seq))
                    debug_cursor_execute(cursor, sql_setseq, [seq['seq'], seq['rid']])
                # return

        # except Exception as e:
        #     raise CommandError(
        #         'Error repairing SEQUENCIA_ESTAGIO ({})'.format(e))


text:
package org.assertj.core.api.objectarray;

import static org.mockito.Mockito.verify;

import org.assertj.core.api.ObjectArrayAssert;
import org.assertj.core.api.ObjectArrayAssertBaseTest;

/**
 * Tests for <code>{@link ObjectArrayAssert#hasSize(int)}</code>.
 *
 * @author Alex Ruiz
 * @author Mikhail Mazursky
 */
class ObjectArrayAssert_hasSize_Test extends ObjectArrayAssertBaseTest {

  @Override
  protected ObjectArrayAssert<Object> invoke_api_method() {
    return assertions.hasSize(6);
  }

  @Override
  protected void verify_internal_effects() {
    verify(arrays).assertHasSize(getInfo(assertions), getActual(assertions), 6);
  }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Boundaries** | [**CarrierRouteBoundaries**](CarrierRouteBoundaries.md) |  | [optional]
**CarrierRoute** | [**List<CarrierRouteResponse>**](CarrierRouteResponse.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
/* -*-  mode: c++; indent-tabs-mode: nil -*- */

/*
  Evaluates the conductivity of surface flow.

  Authors: Ethan Coon (ecoon@lanl.gov)
*/

#include "Mesh_Algorithms.hh"
#include "overland_conductivity_evaluator.hh"
#include "manning_conductivity_model.hh"

namespace Amanzi {
namespace Flow {

OverlandConductivityEvaluator::OverlandConductivityEvaluator(Teuchos::ParameterList& plist)
    : EvaluatorSecondaryMonotypeCV(plist)
{
  Key domain = Keys::getDomain(my_keys_.front().first);
  Tag tag = my_keys_.front().second;

  if (plist_.isParameter("height key") ||
      plist_.isParameter("ponded depth key") ||
      plist_.isParameter("depth key") ||
      plist_.isParameter("height key suffix") ||
      plist_.isParameter("ponded depth key suffix") ||
      plist_.isParameter("depth key suffix")) {
    Errors::Message message("OverlandConductivity: only use \"mobile depth key\" or \"mobile depth key suffix\", not \"height key\" or \"ponded depth key\" or \"depth key\".");
    Exceptions::amanzi_throw(message);
  }

  mobile_depth_key_ = Keys::readKey(plist_, domain, "mobile depth", "ponded_depth");
  dependencies_.insert(KeyTag{mobile_depth_key_, tag});

  slope_key_ = Keys::readKey(plist_, domain, "slope", "slope_magnitude");
  dependencies_.insert(KeyTag{slope_key_, tag});

  coef_key_ = Keys::readKey(plist_, domain, "coefficient", "manning_coefficient");
  dependencies_.insert(KeyTag{coef_key_, tag});

  dt_swe_factor_ = plist_.get<double>("dt factor [s]", -1);
  if (dt_swe_factor_ > 0) {
    double swe_factor = plist_.get<double>("swe density factor [-]", 10.0);
    dt_swe_factor_ *= swe_factor;
  }

  dens_ = plist_.get<bool>("include density", true);
  if (dens_) {
    dens_key_ = Keys::readKey(plist_, domain, "molar density liquid", "molar_density_liquid");
    dependencies_.insert(KeyTag{dens_key_, tag});
  }

  // create the model
  Teuchos::ParameterList& sublist = plist_.sublist("overland conductivity model");
  model_ = Teuchos::rcp(new ManningConductivityModel(sublist));
}

Teuchos::RCP<Evaluator>
OverlandConductivityEvaluator::Clone() const
{
  return Teuchos::rcp(new OverlandConductivityEvaluator(*this));
}

// Required methods from EvaluatorSecondaryMonotypeCV
void OverlandConductivityEvaluator::Evaluate_(const State& S,
        const std::vector<CompositeVector*>& result)
{
  Tag tag = my_keys_.front().second;
  Teuchos::RCP<const CompositeVector> depth = S.GetPtr<CompositeVector>(mobile_depth_key_, tag);
  Teuchos::RCP<const CompositeVector> slope = S.GetPtr<CompositeVector>(slope_key_, tag);
  Teuchos::RCP<const CompositeVector> coef = S.GetPtr<CompositeVector>(coef_key_, tag);

#ifdef ENABLE_DBC
  double min_coef = 1.;
  coef->MinValue(&min_coef);
  if (min_coef <= 1.e-12) {
    Errors::Message message("Overland Conductivity Evaluator: Manning coeficient has at least one value that is non-positive.  Perhaps you forgot to set the \"boundary_face\" component?");
    Exceptions::amanzi_throw(message);
  }
#endif

  // Note, the logic here splits vectors into two groups -- those that will be
  // defined on all components and those that do not make sense to define on
  // not-cells.  These vectors are used in a wierd way on boundary faces,
  // getting the internal cell and using that.  This currently cannot be used
  // on any other components than "cell" and "boundary_face".
  const AmanziMesh::Mesh& mesh = *result[0]->Mesh();
  for (const auto& comp : *result[0]) {
    AMANZI_ASSERT(comp == "cell" || comp == "boundary_face");
    bool is_internal_comp = comp == "boundary_face";
    Key internal_comp = is_internal_comp ? "cell" : comp;

    const Epetra_MultiVector& slope_v = *slope->ViewComponent(internal_comp,false);
    const Epetra_MultiVector& coef_v = *coef->ViewComponent(internal_comp,false);

    const Epetra_MultiVector& depth_v = *depth->ViewComponent(comp,false);
    Epetra_MultiVector& result_v = *result[0]->ViewComponent(comp,false);

    int ncomp = result[0]->size(comp, false);
    if (dt_swe_factor_ > 0) {
      for (int i=0; i!=ncomp; ++i) {
        int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
        double new_snow = dt_swe_factor_ * depth_v[0][i];
        result_v[0][i] = model_->Conductivity(new_snow, slope_v[0][ii], coef_v[0][ii]);
      }
    } else {
      for (int i=0; i!=ncomp; ++i) {
        int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
        result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][ii], coef_v[0][ii]);
      }
    }

    if (dens_) {
      const Epetra_MultiVector& dens_v = *S.Get<CompositeVector>(dens_key_, tag).ViewComponent(comp,false);
      for (int i=0; i!=ncomp; ++i) result_v[0][i] *= dens_v[0][i];
    }
  }
}

void
OverlandConductivityEvaluator::EvaluatePartialDerivative_(const State& S,
        const Key& wrt_key, const Tag& wrt_tag, const std::vector<CompositeVector*>& result)
{
  // NOTE, we can only differentiate with respect to quantities that exist on
  // all entities, not just cell entities.
  Tag tag = my_keys_.front().second;
  Teuchos::RCP<const CompositeVector> depth = S.GetPtr<CompositeVector>(mobile_depth_key_, tag);
  Teuchos::RCP<const CompositeVector> slope = S.GetPtr<CompositeVector>(slope_key_, tag);
  Teuchos::RCP<const CompositeVector> coef = S.GetPtr<CompositeVector>(coef_key_, tag);

  const AmanziMesh::Mesh& mesh = *result[0]->Mesh();

  if (wrt_key == mobile_depth_key_) {
    for (const auto& comp : *result[0]) {
      AMANZI_ASSERT(comp == "cell" || comp == "boundary_face");
      bool is_internal_comp = comp == "boundary_face";
      Key internal_comp = is_internal_comp ? "cell" : comp;

      const Epetra_MultiVector& slope_v = *slope->ViewComponent(internal_comp,false);
      const Epetra_MultiVector& coef_v = *coef->ViewComponent(internal_comp,false);

      const Epetra_MultiVector& depth_v = *depth->ViewComponent(comp,false);
      Epetra_MultiVector& result_v = *result[0]->ViewComponent(comp,false);

      int ncomp = result[0]->size(comp, false);
      if (dt_swe_factor_ > 0.) {
        for (int i=0; i!=ncomp; ++i) {
          int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
          double new_snow = dt_swe_factor_ * depth_v[0][i];
          result_v[0][i] = model_->DConductivityDDepth(new_snow, slope_v[0][ii], coef_v[0][ii])
                           * dt_swe_factor_;
        }
      } else {
        for (int i=0; i!=ncomp; ++i) {
          int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
          result_v[0][i] = model_->DConductivityDDepth(depth_v[0][i], slope_v[0][ii], coef_v[0][ii]);
        }
      }

      if (dens_) {
        const Epetra_MultiVector& dens_v = *S.Get<CompositeVector>(dens_key_, tag).ViewComponent(comp,false);
        for (int i=0; i!=ncomp; ++i) {
          result_v[0][i] *= dens_v[0][i];
        }
      }
    }

  } else if (wrt_key == dens_key_) {
    AMANZI_ASSERT(dens_);

    for (const auto& comp : *result[0]) {
      AMANZI_ASSERT(comp == "cell" || comp == "boundary_face");
      bool is_internal_comp = comp == "boundary_face";
      Key internal_comp = is_internal_comp ? "cell" : comp;

      const Epetra_MultiVector& slope_v = *slope->ViewComponent(internal_comp,false);
      const Epetra_MultiVector& coef_v = *coef->ViewComponent(internal_comp,false);

      const Epetra_MultiVector& depth_v = *depth->ViewComponent(comp,false);
      Epetra_MultiVector& result_v = *result[0]->ViewComponent(comp,false);

      int ncomp = result[0]->size(comp, false);
      if (dt_swe_factor_ > 0.) {
        for (int i=0; i!=ncomp; ++i) {
          int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
          double new_snow = dt_swe_factor_ * depth_v[0][i];
          result_v[0][i] = model_->Conductivity(new_snow, slope_v[0][ii], coef_v[0][ii]);
        }
      } else {
        for (int i=0; i!=ncomp; ++i) {
          int ii = is_internal_comp ? AmanziMesh::getBoundaryFaceInternalCell(mesh, i) : i;
          result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][ii], coef_v[0][ii]);
        }
      }
    }

  } else {
    // FIX ME -- need to add derivatives of conductivity model wrt slope, coef --etc
    result[0]->PutScalar(0.);
  }
}

void OverlandConductivityEvaluator::EnsureCompatibility_ToDeps_(State& S)
{
  // Ensure my field exists.  Requirements should be already set.
  const auto& my_fac = S.Require<CompositeVector, CompositeVectorSpace>(
    my_keys_.front().first, my_keys_.front().second);

  // If my requirements have not yet been set, we'll have to hope they
  // get set by someone later.  For now just defer.
  if (my_fac.Mesh() != Teuchos::null) {
    // Create an unowned factory to check my dependencies.
    Teuchos::RCP<CompositeVectorSpace> dep_fac =
        Teuchos::rcp(new CompositeVectorSpace(my_fac));
    dep_fac->SetOwned(false);

    Teuchos::RCP<CompositeVectorSpace> no_bf_dep_fac;
    if (dep_fac->HasComponent("boundary_face")) {
      no_bf_dep_fac = Teuchos::rcp(new CompositeVectorSpace());
      no_bf_dep_fac->SetMesh(dep_fac->Mesh())
        ->SetGhosted(true)
        ->AddComponent("cell", AmanziMesh::Entity_kind::CELL, 1);
    } else {
      no_bf_dep_fac = dep_fac;
    }

    // Loop over my dependencies, ensuring they meet the requirements.
    for (const auto& key_tag : dependencies_) {
      if (key_tag.first == coef_key_ || key_tag.first == slope_key_) {
        S.Require<CompositeVector, CompositeVectorSpace>(key_tag.first, key_tag.second)
          .Update(*no_bf_dep_fac);
      } else {
        S.Require<CompositeVector, CompositeVectorSpace>(key_tag.first, key_tag.second)
          .Update(*dep_fac);
      }
    }
  }
}

} //namespace
} //namespace


text:
#ifndef CustomElement_h
#define CustomElement_h

#include "core/dom/custom/CustomElementDefinition.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicString.h"

namespace blink {

class CustomElementMicrotaskImportStep;
class Document;
class Element;
class HTMLImportChild;

class CustomElement {
public:
    enum NameSet {
        EmbedderNames = 1 << 0,
        StandardNames = 1 << 1,
        AllNames = EmbedderNames | StandardNames
    };
    static bool isValidName(const AtomicString& name, NameSet validNames = AllNames);
    static void addEmbedderCustomElementName(const AtomicString& name);

    // API to notify of document-level changes
    static CustomElementMicrotaskImportStep* didCreateImport(HTMLImportChild*);
    static void didFinishLoadingImport(Document& master);

    // API for registration contexts
    static void define(Element*, PassRefPtr<CustomElementDefinition>);

    // API for Element to kick off changes

    static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
    static void didEnterDocument(Element*, const Document&);
    static void didLeaveDocument(Element*, const Document&);
    static void wasDestroyed(Element*);

private:
    CustomElement();

    static Vector<AtomicString>& embedderCustomElementNames();
};

}

#endif // CustomElement_h


text:
vue-loadmore is a two-direction mobile pull-to-refresh component for vue.js.

# Installation
```bash
$ npm install vue-loadmore
```

# Usage
Import `vue-loadmore` to your project:
```Javascript
// ES6 mudule
import Loadmore from 'vue-loadmore';

// CommonJS
const Loadmore = require('vue-loadmore').default;
```

Register component:
```Javascript
Vue.component('loadmore', Loadmore);
```

Then use it:
```html
<loadmore :top-method="loadTop" :bottom-method="loadBottom" :bottom-all-loaded="allLoaded">
  ...
</loadmore>
```

# Example

```html
<mt-loadmore :top-method="loadTop" :bottom-method="loadBottom" :bottom-all-loaded="allLoaded" ref="loadmore">
  <ul>
    <li v-for="item in list">{{ item }}</li>
  </ul>
</mt-loadmore>
```

Take upward direction for example: pull the component `topDistance` pixels away from the top and then release it, the function you appointed as `top-method` will run

```javascript
loadTop(id) {
  ...// load more data
  this.$refs.loadmore.onTopLoaded(id);
}
```
At the end of your `top-method`, don't forget to manually execute the `onTopLoaded` event so that `mint-loadmore` removes `topLoadingText`. Note that a parameter called `id` is passed to `loadTop` and `onTopLoaded`. This is because after the top data is loaded, some reposition work is performed inside a `mint-loadmore` instance, and `id` simply tells the component which instance should be repositioned. You don't need to do anything more than passing `id` to `onTopLoaded` just as shown above.

For downward direction, things are similar. To invoke `bottom-method`, just pull the component `bottomDistance` pixels away from the bottom and then release it

```javascript
loadBottom(id) {
  ...// load more data
  this.allLoaded = true;// if all data are loaded
  this.$refs.loadmore.onBottomLoaded(id);
}
```
The only difference is that after all data are fetched, you can set `bottom-all-loaded` to `true` so that `bottom-method` will not run any more.

The ratio between the distance that your finger moves and the distance that the component actually scrolls can be defined using `distance-index`, whose default value is 2。

## Custom HTML templates

You can customize the top and bottom DOM using an HTML template
```html
<mt-loadmore :top-method="loadTop" :top-status.sync="topStatus">
  <ul>
    <li v-for="item in list">{{ item }}</li>
  </ul>
  <div slot="top" class="mint-loadmore-top">
    <span v-show="topStatus !== 'loading'" :class="{ 'rotate': topStatus === 'drop' }">↓</span>
    <span v-show="topStatus === 'loading'">Loading...</span>
  </div>
</mt-loadmore>
```
For example, to customize the top DOM, you'll need to write your template with a `slot` attribute set to `top` and `class` set to `mint-loadmore-top`. When the component is scrolled, it will be in one of the three status below
*  `pull`: if the component is being pulled yet not ready to drop (top distance is within the distance threshold defined by `topDistance`)
*  `drop`: if the component is ready to drop
*  `loading`: if `topMethod` is running
Every time the status changes, an event named `top-status-change` fires with a parameter indicating the current status of the component. So you can handle this change with a `handleTopChange` method just as the above example shows.

## Configure texts in top and bottom DOM
If you decide not to customize HTML templates, you can configure the texts that comes with `loadmore`. Take the top DOM for example, corresponding to the three `top-status` states, configurable options are: `topPullText`, `topDropText` and `topLoadingText`. And `bottomPullText`, `bottomDropText` and `bottomLoadingText` are for the bottom DOM.

## Auto fill
Upon loaded, `loadmore` will automatically check if it is tall enough to fill its container. If not, `bottom-method` will run until its container is filled. Turn off `auto-fill` if you'd rather handle this manually.

## API
| option | description | type | acceptable values | default |
|------|-------|---------|-------|--------|
| autoFill | if `true`, `loadmore` will check and fill its container | Boolean | | true |
| distanceIndex | the ratio between the distance of the finger moves and the component scrolls | Number | | 2 |
| maxDistance | maximum distance(in pixel) the component can scroll. Can be disabled by setting it to 0 | Number | | 0 |
| topPullText | top text when the component is being pulled down | String | | '下拉刷新' |
| topDropText | top text when the component is ready to drop | String | | '释放更新' |
| topLoadingText | top text while `topMethod` is running | String | | '加载中...' |
| topDistance | distance threshold that triggers `topMethod`(in pixel) | Number | | 70 |
| topMethod | upward load-more function | Function | | |
| bottomPullText | bottom text when the component is being pulled up | String | | '上拉刷新' |
| bottomDropText | bottom text when the component is ready to drop | String | | '释放更新' |
| bottomLoadingText | bottom text while `bottomMethod` is running | String | | '加载中...' |
| bottomDistance | distance threshold that triggers `bottomMethod`(in pixel) | Number | | 70 |
| bottomMethod | downward load-more function | Function | | |
| bottomAllLoaded | if `true`, `bottomMethod` can no longer be triggered | Boolean | | false |

## Events
| event name | description | parameters |
|------|-------|---------|
| top-status-change | the callback when the component's top status changes | current top status |
| bottom-status-change | the callback when the component's bottom status changes | current bottom status |

## Slot
| name | description |
|------|--------|
| - | data list |
| top | custom top HTML template |
| bottom | custom bottom HTML template |

# License
MIT


text:
#include "platform/CCDevice.h"
#include "CCStdC.h"

NS_CC_BEGIN

int CCDevice::getDPI()
{
	static const float dipsPerInch = 96.0f;
	return floor(Windows::Graphics::Display::DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer.
}

NS_CC_END


text:
import { Migrations } from '../../../app/migrations';
import { Uploads, Messages } from '../../../app/models';

Migrations.add({
	version: 113,
	up() {
		if (Uploads && Messages) {
			const fileQuery = {
				userId: null,
			};

			const filesToUpdate = Uploads.find(fileQuery);
			filesToUpdate.forEach((file) => {
				const messageQuery = {
					'file._id': file._id,
				};
				const message = Messages.findOne(messageQuery);
				if (message) {
					const filter = {
						_id: file._id,
					};

					const update = {
						$set: {
							userId: message.u._id,
						},
					};

					Uploads.model.direct.update(filter, update);
				}
			});
		}
	},
});


text:
author: Matthew Taylor
description:
date: 2017/05/05
event:
  what: "The Biological Path Towards Strong AI"
  when:
    begin: 2017/05/03
    end: 2017/05/05
  where:
    desc: Hynes Convention Center
    city: Boston
    state: MA
    country: USA
    web: https://www.odsc.com/training/portfolio/biological-path-towards-strong-ai
  who: Matthew Taylor
  why: Speaking
image: ../images/ODSC.png
org: HTM Community Leader
tags: strong ai artificial intelligence biological htm hierarchical temporal memory computing like the brain
title: ODSC East
type: post
---

## Talk Abstract

### The Biological Path Towards Strong AI

Today's wave of AI technology is still being driven by the ANN neuron
pioneered decades ago. Hierarchical Temporal Memory (HTM) is a realistic
biologically-constrained model of the pyramidal neuron reflecting
today's most recent neocortical research. This talk will describe and
visualize core HTM concepts like sparse distributed representations,
spatial pooling and temporal memory. Strong AI is a common goal of many
computer scientists. So far, machine learning techniques have created
amazing results in narrow fields, but haven't produced something we
could all call "intelligent". Given recent advances in neuroscience
research, we know a lot more about how neurons work together now than we
did when ANNs were created. We believe systems with a more realistic
neuronal model will be more likely to produce Strong AI. Hierarchical
Temporal Memory is a theory of intelligence based upon neuroscience
research. The neocortex is the seat of intelligence in the brain, and it
is structurally homogeneous throughout. This means a common algorithm is
processing all your sensory input, no matter which sense. We believe we
have discovered some of the foundational algorithms of the neocortex,
and we've implemented them in software. I'll show you how they work with
detailed dynamic visualizations of Sparse Distributed Representations,
Spatial Pooling, and Temporal Memory.