text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler

try:
    from ansible.modules.network.fortios import fortios_router_bgp
except ImportError:
    pytest.skip("Could not load required modules for testing", allow_module_level=True)

@pytest.fixture(autouse=True)
def connection_mock(mocker):
    connection_class_mock = mocker.patch('ansible.modules.network.fortios.fortios_router_bgp.Connection')
    return connection_class_mock

fos_instance = FortiOSHandler(connection_mock)

def test_router_bgp_creation(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'router_bgp': {'always_compare_med': 'enable',
                       'as': '4',
                       'bestpath_as_path_ignore': 'enable',
                       'bestpath_cmp_confed_aspath': 'enable',
                       'bestpath_cmp_routerid': 'enable',
                       'bestpath_med_confed': 'enable',
                       'bestpath_med_missing_as_worst': 'enable',
                       'client_to_client_reflection': 'enable',
                       'cluster_id': 'test_value_11',
                       'confederation_identifier': '12',
                       'dampening': 'enable',
                       'dampening_max_suppress_time': '14',
                       'dampening_reachability_half_life': '15',
                       'dampening_reuse': '16',
                       'dampening_route_map': 'test_value_17',
                       'dampening_suppress': '18',
                       'dampening_unreachability_half_life': '19',
                       'default_local_preference': '20',
                       'deterministic_med': 'enable',
                       'distance_external': '22',
                       'distance_internal': '23',
                       'distance_local': '24',
                       'ebgp_multipath': 'enable',
                       'enforce_first_as': 'enable',
                       'fast_external_failover': 'enable',
                       'graceful_end_on_timer': 'enable',
                       'graceful_restart': 'enable',
                       'graceful_restart_time': '30',
                       'graceful_stalepath_time': '31',
                       'graceful_update_delay': '32',
                       'holdtime_timer': '33',
                       'ibgp_multipath': 'enable',
                       'ignore_optional_capability': 'enable',
                       'keepalive_timer': '36',
                       'log_neighbour_changes': 'enable',
                       'network_import_check': 'enable',
                       'router_id': 'test_value_39',
                       'scan_time': '40',
                       'synchronization': 'enable'
                       },
        'vdom': 'root'}

    is_error, changed, response = fortios_router_bgp.fortios_router(input_data, fos_instance)

    expected_data = {'always-compare-med': 'enable',
                     'as': '4',
                     'bestpath-as-path-ignore': 'enable',
                     'bestpath-cmp-confed-aspath': 'enable',
                     'bestpath-cmp-routerid': 'enable',
                     'bestpath-med-confed': 'enable',
                     'bestpath-med-missing-as-worst': 'enable',
                     'client-to-client-reflection': 'enable',
                     'cluster-id': 'test_value_11',
                     'confederation-identifier': '12',
                     'dampening': 'enable',
                     'dampening-max-suppress-time': '14',
                     'dampening-reachability-half-life': '15',
                     'dampening-reuse': '16',
                     'dampening-route-map': 'test_value_17',
                     'dampening-suppress': '18',
                     'dampening-unreachability-half-life': '19',
                     'default-local-preference': '20',
                     'deterministic-med': 'enable',
                     'distance-external': '22',
                     'distance-internal': '23',
                     'distance-local': '24',
                     'ebgp-multipath': 'enable',
                     'enforce-first-as': 'enable',
                     'fast-external-failover': 'enable',
                     'graceful-end-on-timer': 'enable',
                     'graceful-restart': 'enable',
                     'graceful-restart-time': '30',
                     'graceful-stalepath-time': '31',
                     'graceful-update-delay': '32',
                     'holdtime-timer': '33',
                     'ibgp-multipath': 'enable',
                     'ignore-optional-capability': 'enable',
                     'keepalive-timer': '36',
                     'log-neighbour-changes': 'enable',
                     'network-import-check': 'enable',
                     'router-id': 'test_value_39',
                     'scan-time': '40',
                     'synchronization': 'enable'
                     }

    set_method_mock.assert_called_with('router', 'bgp', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert changed
    assert response['status'] == 'success'
    assert response['http_status'] == 200

def test_router_bgp_creation_fails(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'error', 'http_method': 'POST', 'http_status': 500}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'router_bgp': {'always_compare_med': 'enable',
                       'as': '4',
                       'bestpath_as_path_ignore': 'enable',
                       'bestpath_cmp_confed_aspath': 'enable',
                       'bestpath_cmp_routerid': 'enable',
                       'bestpath_med_confed': 'enable',
                       'bestpath_med_missing_as_worst': 'enable',
                       'client_to_client_reflection': 'enable',
                       'cluster_id': 'test_value_11',
                       'confederation_identifier': '12',
                       'dampening': 'enable',
                       'dampening_max_suppress_time': '14',
                       'dampening_reachability_half_life': '15',
                       'dampening_reuse': '16',
                       'dampening_route_map': 'test_value_17',
                       'dampening_suppress': '18',
                       'dampening_unreachability_half_life': '19',
                       'default_local_preference': '20',
                       'deterministic_med': 'enable',
                       'distance_external': '22',
                       'distance_internal': '23',
                       'distance_local': '24',
                       'ebgp_multipath': 'enable',
                       'enforce_first_as': 'enable',
                       'fast_external_failover': 'enable',
                       'graceful_end_on_timer': 'enable',
                       'graceful_restart': 'enable',
                       'graceful_restart_time': '30',
                       'graceful_stalepath_time': '31',
                       'graceful_update_delay': '32',
                       'holdtime_timer': '33',
                       'ibgp_multipath': 'enable',
                       'ignore_optional_capability': 'enable',
                       'keepalive_timer': '36',
                       'log_neighbour_changes': 'enable',
                       'network_import_check': 'enable',
                       'router_id': 'test_value_39',
                       'scan_time': '40',
                       'synchronization': 'enable'
                       },
        'vdom': 'root'}

    is_error, changed, response = fortios_router_bgp.fortios_router(input_data, fos_instance)

    expected_data = {'always-compare-med': 'enable',
                     'as': '4',
                     'bestpath-as-path-ignore': 'enable',
                     'bestpath-cmp-confed-aspath': 'enable',
                     'bestpath-cmp-routerid': 'enable',
                     'bestpath-med-confed': 'enable',
                     'bestpath-med-missing-as-worst': 'enable',
                     'client-to-client-reflection': 'enable',
                     'cluster-id': 'test_value_11',
                     'confederation-identifier': '12',
                     'dampening': 'enable',
                     'dampening-max-suppress-time': '14',
                     'dampening-reachability-half-life': '15',
                     'dampening-reuse': '16',
                     'dampening-route-map': 'test_value_17',
                     'dampening-suppress': '18',
                     'dampening-unreachability-half-life': '19',
                     'default-local-preference': '20',
                     'deterministic-med': 'enable',
                     'distance-external': '22',
                     'distance-internal': '23',
                     'distance-local': '24',
                     'ebgp-multipath': 'enable',
                     'enforce-first-as': 'enable',
                     'fast-external-failover': 'enable',
                     'graceful-end-on-timer': 'enable',
                     'graceful-restart': 'enable',
                     'graceful-restart-time': '30',
                     'graceful-stalepath-time': '31',
                     'graceful-update-delay': '32',
                     'holdtime-timer': '33',
                     'ibgp-multipath': 'enable',
                     'ignore-optional-capability': 'enable',
                     'keepalive-timer': '36',
                     'log-neighbour-changes': 'enable',
                     'network-import-check': 'enable',
                     'router-id': 'test_value_39',
                     'scan-time': '40',
                     'synchronization': 'enable'
                     }

    set_method_mock.assert_called_with('router', 'bgp', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert is_error
    assert not changed
    assert response['status'] == 'error'
    assert response['http_status'] == 500

def test_router_bgp_idempotent(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'error', 'http_method': 'DELETE', 'http_status': 404}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'router_bgp': {'always_compare_med': 'enable',
                       'as': '4',
                       'bestpath_as_path_ignore': 'enable',
                       'bestpath_cmp_confed_aspath': 'enable',
                       'bestpath_cmp_routerid': 'enable',
                       'bestpath_med_confed': 'enable',
                       'bestpath_med_missing_as_worst': 'enable',
                       'client_to_client_reflection': 'enable',
                       'cluster_id': 'test_value_11',
                       'confederation_identifier': '12',
                       'dampening': 'enable',
                       'dampening_max_suppress_time': '14',
                       'dampening_reachability_half_life': '15',
                       'dampening_reuse': '16',
                       'dampening_route_map': 'test_value_17',
                       'dampening_suppress': '18',
                       'dampening_unreachability_half_life': '19',
                       'default_local_preference': '20',
                       'deterministic_med': 'enable',
                       'distance_external': '22',
                       'distance_internal': '23',
                       'distance_local': '24',
                       'ebgp_multipath': 'enable',
                       'enforce_first_as': 'enable',
                       'fast_external_failover': 'enable',
                       'graceful_end_on_timer': 'enable',
                       'graceful_restart': 'enable',
                       'graceful_restart_time': '30',
                       'graceful_stalepath_time': '31',
                       'graceful_update_delay': '32',
                       'holdtime_timer': '33',
                       'ibgp_multipath': 'enable',
                       'ignore_optional_capability': 'enable',
                       'keepalive_timer': '36',
                       'log_neighbour_changes': 'enable',
                       'network_import_check': 'enable',
                       'router_id': 'test_value_39',
                       'scan_time': '40',
                       'synchronization': 'enable'
                       },
        'vdom': 'root'}

    is_error, changed, response = fortios_router_bgp.fortios_router(input_data, fos_instance)

    expected_data = {'always-compare-med': 'enable',
                     'as': '4',
                     'bestpath-as-path-ignore': 'enable',
                     'bestpath-cmp-confed-aspath': 'enable',
                     'bestpath-cmp-routerid': 'enable',
                     'bestpath-med-confed': 'enable',
                     'bestpath-med-missing-as-worst': 'enable',
                     'client-to-client-reflection': 'enable',
                     'cluster-id': 'test_value_11',
                     'confederation-identifier': '12',
                     'dampening': 'enable',
                     'dampening-max-suppress-time': '14',
                     'dampening-reachability-half-life': '15',
                     'dampening-reuse': '16',
                     'dampening-route-map': 'test_value_17',
                     'dampening-suppress': '18',
                     'dampening-unreachability-half-life': '19',
                     'default-local-preference': '20',
                     'deterministic-med': 'enable',
                     'distance-external': '22',
                     'distance-internal': '23',
                     'distance-local': '24',
                     'ebgp-multipath': 'enable',
                     'enforce-first-as': 'enable',
                     'fast-external-failover': 'enable',
                     'graceful-end-on-timer': 'enable',
                     'graceful-restart': 'enable',
                     'graceful-restart-time': '30',
                     'graceful-stalepath-time': '31',
                     'graceful-update-delay': '32',
                     'holdtime-timer': '33',
                     'ibgp-multipath': 'enable',
                     'ignore-optional-capability': 'enable',
                     'keepalive-timer': '36',
                     'log-neighbour-changes': 'enable',
                     'network-import-check': 'enable',
                     'router-id': 'test_value_39',
                     'scan-time': '40',
                     'synchronization': 'enable'
                     }

    set_method_mock.assert_called_with('router', 'bgp', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert not changed
    assert response['status'] == 'error'
    assert response['http_status'] == 404

def test_router_bgp_filter_foreign_attributes(mocker):
    schema_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.schema')

    set_method_result = {'status': 'success', 'http_method': 'POST', 'http_status': 200}
    set_method_mock = mocker.patch('ansible.module_utils.network.fortios.fortios.FortiOSHandler.set', return_value=set_method_result)

    input_data = {
        'username': 'admin',
        'state': 'present',
        'router_bgp': {
            'random_attribute_not_valid': 'tag', 'always_compare_med': 'enable',
            'as': '4',
            'bestpath_as_path_ignore': 'enable',
            'bestpath_cmp_confed_aspath': 'enable',
            'bestpath_cmp_routerid': 'enable',
            'bestpath_med_confed': 'enable',
            'bestpath_med_missing_as_worst': 'enable',
            'client_to_client_reflection': 'enable',
            'cluster_id': 'test_value_11',
            'confederation_identifier': '12',
            'dampening': 'enable',
            'dampening_max_suppress_time': '14',
            'dampening_reachability_half_life': '15',
            'dampening_reuse': '16',
            'dampening_route_map': 'test_value_17',
            'dampening_suppress': '18',
            'dampening_unreachability_half_life': '19',
            'default_local_preference': '20',
            'deterministic_med': 'enable',
            'distance_external': '22',
            'distance_internal': '23',
            'distance_local': '24',
            'ebgp_multipath': 'enable',
            'enforce_first_as': 'enable',
            'fast_external_failover': 'enable',
            'graceful_end_on_timer': 'enable',
            'graceful_restart': 'enable',
            'graceful_restart_time': '30',
            'graceful_stalepath_time': '31',
            'graceful_update_delay': '32',
            'holdtime_timer': '33',
            'ibgp_multipath': 'enable',
            'ignore_optional_capability': 'enable',
            'keepalive_timer': '36',
            'log_neighbour_changes': 'enable',
            'network_import_check': 'enable',
            'router_id': 'test_value_39',
            'scan_time': '40',
            'synchronization': 'enable'
        },
        'vdom': 'root'}

    is_error, changed, response = fortios_router_bgp.fortios_router(input_data, fos_instance)

    expected_data = {'always-compare-med': 'enable',
                     'as': '4',
                     'bestpath-as-path-ignore': 'enable',
                     'bestpath-cmp-confed-aspath': 'enable',
                     'bestpath-cmp-routerid': 'enable',
                     'bestpath-med-confed': 'enable',
                     'bestpath-med-missing-as-worst': 'enable',
                     'client-to-client-reflection': 'enable',
                     'cluster-id': 'test_value_11',
                     'confederation-identifier': '12',
                     'dampening': 'enable',
                     'dampening-max-suppress-time': '14',
                     'dampening-reachability-half-life': '15',
                     'dampening-reuse': '16',
                     'dampening-route-map': 'test_value_17',
                     'dampening-suppress': '18',
                     'dampening-unreachability-half-life': '19',
                     'default-local-preference': '20',
                     'deterministic-med': 'enable',
                     'distance-external': '22',
                     'distance-internal': '23',
                     'distance-local': '24',
                     'ebgp-multipath': 'enable',
                     'enforce-first-as': 'enable',
                     'fast-external-failover': 'enable',
                     'graceful-end-on-timer': 'enable',
                     'graceful-restart': 'enable',
                     'graceful-restart-time': '30',
                     'graceful-stalepath-time': '31',
                     'graceful-update-delay': '32',
                     'holdtime-timer': '33',
                     'ibgp-multipath': 'enable',
                     'ignore-optional-capability': 'enable',
                     'keepalive-timer': '36',
                     'log-neighbour-changes': 'enable',
                     'network-import-check': 'enable',
                     'router-id': 'test_value_39',
                     'scan-time': '40',
                     'synchronization': 'enable'
                     }

    set_method_mock.assert_called_with('router', 'bgp', data=expected_data, vdom='root')
    schema_method_mock.assert_not_called()
    assert not is_error
    assert changed
    assert response['status'] == 'success'
    assert response['http_status'] == 200


text:
package hr.vsite.hive.services.jetty.faces.el;

import java.beans.FeatureDescriptor;
import java.util.Iterator;
import java.util.Map;

import javax.el.ELContext;
import javax.el.ELResolver;
import javax.faces.FacesWrapper;
import javax.faces.context.FacesContext;

import com.google.inject.Injector;

public class HiveGuiceELResolverWrapper extends ELResolver implements FacesWrapper<ELResolver> {

	public HiveGuiceELResolverWrapper(ELResolver wrapped) {
		this.wrapped = wrapped;
	}

	@Override
	public ELResolver getWrapped() {
		return wrapped;
	}

	@Override
	public Object getValue(ELContext context, Object base, Object property) {
        Object obj = getWrapped().getValue(context, base, property);

        if (null != obj) {
            FacesContext fctx = (FacesContext) context.getContext(FacesContext.class);

            if (null != fctx) {

                Map<String, Object> map = fctx.getExternalContext().getApplicationMap();
                Injector injector = (Injector) map.get(Injector.class.getName());
                if (injector == null) {
                    throw new NullPointerException("Could not locate "
                            + "Guice Injector in application scope using"
                            + " key '" + Injector.class.getName() + "'");
                }
                injector.injectMembers(obj);
            }
        }

        return obj;
    }

	@Override
	public Class<?> getType(ELContext context, Object base, Object property) {
		return getWrapped().getType(context, base, property);
	}

	@Override
	public void setValue(ELContext context, Object base, Object property, Object value) {
		getWrapped().setValue(context, base, property, value);
	}

	@Override
	public boolean isReadOnly(ELContext context, Object base, Object property) {
		return getWrapped().isReadOnly(context, base, property);
	}

	@Override
	public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) {
		return getWrapped().getFeatureDescriptors(context, base);
	}

	@Override
	public Class<?> getCommonPropertyType(ELContext context, Object base) {
		return getWrapped().getCommonPropertyType(context, base);
	}

	private ELResolver wrapped;
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

try:
    from django.core.urlresolvers import reverse
except ImportError:
    from django.urls import reverse

from .event_factory import create_event, SetMeUp

class MultipleEventsListViewTest(SetMeUp):
    """
    There's already a test called test_list_view_with_multiple_events
    in test_month_view, but this takes it a step further.
    Created in response to discovering a bug related to repeat_biweekly
    in handlers.py after moving from functions to classes. Noticed that
    it was clearing the counter used to keep track of all events,
    but no tests caught the problem.
    """
    def test_multi(self):
        event1 = create_event(
            start_date=(2014, 5, 28),
            end_date=(2014, 5, 28),
            created_by=self.user,
            title="Whoa",
            description="Ehhh",
            repeat="BIWEEKLY",
        )
        event2 = create_event(
            start_date=(2014, 5, 28),
            end_date=(2014, 5, 28),
            created_by=self.user,
            title="The Coolest",
            description="Cool event dude!",
            repeat="WEEKDAY",
        )

        event3 = create_event(
            start_date=(2014, 5, 26),
            end_date=(2014, 5, 26),
            created_by=self.user,
            title="QWERTY",
            description="ASDFGH",
            repeat="WEEKLY",
        )

        events = {
            event1.title: event1.description,
            event2.title: event2.description,
            event3.title: event3.description,
        }
        for month in ('5', '6'):
            response = self.client.get(reverse(
                'calendar:list', kwargs={'year': '2014', 'month': month}
            ))
            for k, v in events.items():
                self.assertContains(response, k)
                self.assertContains(response, v)


text:
goog.require('axs.AuditRule');
goog.require('axs.AuditRule');
goog.require('axs.AuditRules');
goog.require('axs.constants.Severity');

axs.AuditRule.specs.nonExistentAriaLabelledbyElement = {
    name: 'nonExistentAriaLabelledbyElement',
    severity: axs.constants.Severity.Warning,
    relevantNodesSelector: function(scope) {
        return scope.querySelectorAll('[aria-labelledby]');
    },
    test: function(element) {
        var labelledBy = element.getAttribute('aria-labelledby');
        var labelledByValues = labelledBy.split(/\s+/);
        for (var i = 0; i < labelledByValues.length; i++) {
            var labelElement = document.getElementById(labelledByValues[i]);
            if (!labelElement)
                return true;
        }
        return false;
    },
    code: 'AX_ARIA_02'
};


text:
package com.gumino.pushetta.adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.gumino.pushetta.R;

/**
 * Created by fabrizio on 07/08/15.
 */
public class DrawerMenuAdapter extends RecyclerView.Adapter<DrawerMenuAdapter.ViewHolder> {
    private String[] mDataset;
    private OnItemClickListener mListener;

    /**
     * Interface for receiving click events from cells.
     */
    public interface OnItemClickListener {
        public void onClick(View view, int position);
    }

    /**
     * Custom viewholder for our planet views.
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final TextView mTextView;

        public ViewHolder(TextView v) {
            super(v);
            mTextView = v;
        }
    }

    public DrawerMenuAdapter(String[] myDataset, OnItemClickListener listener) {
        mDataset = myDataset;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater vi = LayoutInflater.from(parent.getContext());

        View v = vi.inflate(R.layout.drawer_list_item, parent, false);
        TextView tv = (TextView) v.findViewById(android.R.id.text1);
        return new ViewHolder(tv);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        holder.mTextView.setText(mDataset[position]);
        holder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mListener.onClick(view, position);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}


text:
package org.kie.workbench.common.stunner.cm.client.command.canvas;

import java.util.Optional;
import java.util.OptionalInt;

import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasCommand;
import org.kie.workbench.common.stunner.core.client.canvas.command.AddCanvasNodeCommand;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.command.impl.CompositeCommand;
import org.kie.workbench.common.stunner.core.graph.Node;

public class CaseManagementAddChildNodeCanvasCommand extends AbstractCanvasCommand {

    private final Node parent;
    private final Node child;
    private final String shapeSetId;
    private final int index;

    public CaseManagementAddChildNodeCanvasCommand(final Node parent,
                                                   final Node child,
                                                   final String shapeSetId,
                                                   final int index) {
        this.parent = parent;
        this.child = child;
        this.shapeSetId = shapeSetId;
        this.index = index;
    }

    @Override
    public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler context) {
        return new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>()
                .addCommand(new AddCanvasNodeCommand(child,
                                                     shapeSetId))
                .addCommand(new CaseManagementSetChildNodeCanvasCommand(parent,
                                                                        child,
                                                                        OptionalInt.of(index),
                                                                        Optional.empty(),
                                                                        OptionalInt.empty()))
                .build()
                .execute(context);
    }

    @Override
    public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler context) {
        return new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>()
                .addCommand(new CaseManagementDeleteCanvasNodeCommand(child,
                                                                      parent,
                                                                      index))
                .build()
                .execute(context);
    }
}


text:
'use strict';

var Crypto = require('crypto'),
	_ = require('underscore');

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('md5versions', 'Building md5 versions', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      punctuation: '.',
      separator: ', '
    });
    // Iterate over all specified file groups.
    this.files.forEach(_.bind(function(f) {
      // Concat specified files.
      var src = f.src.filter(_.bind(function(filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      }, this)).map(_.bind(function(filepath) {
        // Read file source.
        return grunt.file.read(filepath);
      }, this)).join(grunt.util.normalizelf(options.separator));

      // Handle options.
      src += options.punctuation;
			var versions;
			try {
				versions = grunt.file.readJSON(f.dest);
			}
			catch(error) {
				versions = {};
			}
			var md5 = Crypto.createHash('md5');
			md5.update(src);
			var digest = md5.digest('hex');
			if (!versions[options.key]) {
				versions[options.key] = {};
			}
			if (versions[options.key][options.type] !== digest) {
				// Write the destination file.
				versions[options.key][options.type] = digest;
				grunt.file.write(f.dest, JSON.stringify(versions));
				grunt.log.writeln("Digest updated for " + options.key + " to " + digest);
				if (typeof options.on_change == 'function') {
					try {
						var on_change = _.bind(options.on_change,this);
						on_change()
					}
					catch(error) {
						grunt.error("Unable to run on_change function for " + this.target + ": " + error);
					}
				}
			}
    }, this));
  });

};


text:
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using Microsoft.WindowsAzure.Storage.Table;
using Nenuphar.BusinessObjects.Alertes;
using Nenuphar.BusinessObjects.Evenements;
using Nenuphar.Core.Services;
using Nenuphar.Exceptions;
using Nenuphar.Factories;
using Nenuphar.TableEntities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Nenuphar.Services
{
    /// <summary>
    /// Takes care of handling Queue/Topic lifecycle (creation, message add, etc)
    /// </summary>
    public class MessageService : IMessageService
    {
        static List<String> ALLOWED_CORS_ORIGINS = new List<String> { "*" };

        static List<String> ALLOWED_CORS_HEADERS = new List<String> { "Content-Type", "x-ms-blob-type", "x-ms-blob-content-type", "authorization" };
        const CorsHttpMethods ALLOWED_CORS_METHODS = CorsHttpMethods.Delete | CorsHttpMethods.Put;

        public IList<IScheduledAlerte> GetAlertes(string recipientId)
        {
            IList<IScheduledAlerte> scheduledAlertes = new List<IScheduledAlerte>();

            var scheduledEntities = new DataServiceFactory().GetDataService().GetEvenements(recipientId);
            // Print the fields for each customer.
            foreach (NenuEvenementTableEntity scheduledEntity in scheduledEntities)
            {

                var nextScheduledOn = scheduledEntities.SingleOrDefault(x => x.Id == scheduledEntity.Id);
                scheduledAlertes.Add(new ScheduledAlerte(
                    scheduledEntity.CreatedOn,
                    scheduledEntity.NextScheduledOn,
                    scheduledEntity.RecipientEntityId,
                    Guid.Parse(scheduledEntity.Id),
                    scheduledEntity.Status,
                    scheduledEntity.Title,
                    scheduledEntity.Message,
                    scheduledEntity.RelatedEntityId,
                    scheduledEntity.NenuAlerteTypeLabel,
                    scheduledEntity.Periodicity
                    ));
            }
            return scheduledAlertes;
        }
        public IList<IScheduledAlerte> GetScheduledAlertes(string recipientId)
        {
            IList<IScheduledAlerte> scheduledAlertes = new List<IScheduledAlerte>();

            var scheduledEntities = new DataServiceFactory().GetDataService().GetEvenements(recipientId, EvenementState.SCHEDULED);
            // Print the fields for each customer.
            foreach (NenuEvenementTableEntity scheduledEntity in scheduledEntities)
            {
                var nextScheduledOn = scheduledEntities.SingleOrDefault(x => x.Id == scheduledEntity.Id);
                scheduledAlertes.Add(new ScheduledAlerte(
                    scheduledEntity.CreatedOn,
                    scheduledEntity.NextScheduledOn,
                    scheduledEntity.RecipientEntityId,
                    Guid.Parse(scheduledEntity.Id),
                    scheduledEntity.Status,
                    scheduledEntity.Title,
                    scheduledEntity.Message,
                    scheduledEntity.RelatedEntityId,
                    scheduledEntity.NenuAlerteTypeLabel,
                    scheduledEntity.Periodicity
                    ));
            }
            return scheduledAlertes;
        }

        const int ALLOWED_CORS_AGE_DAYS = 5;
        CloudStorageAccount storageAccount;

        public MessageService()
        {
            storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("Storage:ConnectionString"));
        }

        /// <summary>
        /// 1. Generate SAS access for given building's blob container.
        /// 3. Set SAS validity for next hour
        /// </summary>
        /// <param name="bloburi">the blob's uri contains the buildingId and the id of the uploaded file</param>
        /// <param name="method"></param>
        /// <returns></returns>
        //public string GetTableSAS_WD(string bloburi, string method)
        //{
        //    try
        //    {
        //        var credentials = new StorageCredentials(_storageAccountName, _storageAccountKey);
        //        var storageAccount = new CloudStorageAccount(credentials, true);

        //        ConfigureCors(storageAccount);

        //        CloudBlockBlob blob = new CloudBlockBlob(new Uri(bloburi), credentials);
        //        var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy()
        //        {
        //            Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Delete,
        //            SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(60)
        //        });

        //        return string.Format(CultureInfo.InvariantCulture, "{0}{1}", bloburi, sas);
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine(ex);
        //        throw ex;
        //    }
        //}

        //private void ConfigureCors(CloudStorageAccount storageAccount)
        //{
        //    var blobClient = storageAccount.CreateCloudBlobClient();

        //    Debug.WriteLine("Storage Account: " + storageAccount.BlobEndpoint);
        //    var newProperties = CurrentProperties(blobClient);

        //    newProperties.DefaultServiceVersion = "2015-12-11";
        //    blobClient.SetServiceProperties(newProperties);

        //    var addRule = true;
        //    if (addRule)
        //    {
        //        var ruleWideOpenWriter = new CorsRule()
        //        {
        //            AllowedHeaders = ALLOWED_CORS_HEADERS,
        //            AllowedOrigins = ALLOWED_CORS_ORIGINS,
        //            AllowedMethods = ALLOWED_CORS_METHODS,
        //            MaxAgeInSeconds = (int)TimeSpan.FromDays(ALLOWED_CORS_AGE_DAYS).TotalSeconds
        //        };
        //        newProperties.Cors.CorsRules.Clear();
        //        newProperties.Cors.CorsRules.Add(ruleWideOpenWriter);
        //        blobClient.SetServiceProperties(newProperties);

        //        Debug.WriteLine("New Properties:");
        //        CurrentProperties(blobClient);

        //    }
        //}

        private ServiceProperties CurrentProperties(CloudTableClient tableClient)
        {
            var currentProperties = tableClient.GetServiceProperties();
            if (currentProperties != null)
            {
                if (currentProperties.Cors != null)
                {
                    Debug.WriteLine("Cors.CorsRules.Count          : " + currentProperties.Cors.CorsRules.Count);
                    for (int index = 0; index < currentProperties.Cors.CorsRules.Count; index++)
                    {
                        var corsRule = currentProperties.Cors.CorsRules[index];
                        Debug.WriteLine("corsRule[index]              : " + index);
                        foreach (var allowedHeader in corsRule.AllowedHeaders)
                        {
                            Debug.WriteLine("corsRule.AllowedHeaders      : " + allowedHeader);
                        }
                        Debug.WriteLine("corsRule.AllowedMethods      : " + corsRule.AllowedMethods);

                        foreach (var allowedOrigins in corsRule.AllowedOrigins)
                        {
                            Debug.WriteLine("corsRule.AllowedOrigins      : " + allowedOrigins);
                        }
                        foreach (var exposedHeaders in corsRule.ExposedHeaders)
                        {
                            Debug.WriteLine("corsRule.ExposedHeaders      : " + exposedHeaders);
                        }
                        Debug.WriteLine("corsRule.MaxAgeInSeconds     : " + corsRule.MaxAgeInSeconds);
                    }
                }
                Debug.WriteLine("DefaultServiceVersion         : " + currentProperties.DefaultServiceVersion);
                Debug.WriteLine("HourMetrics.MetricsLevel      : " + currentProperties.HourMetrics.MetricsLevel);
                Debug.WriteLine("HourMetrics.RetentionDays     : " + currentProperties.HourMetrics.RetentionDays);
                Debug.WriteLine("HourMetrics.Version           : " + currentProperties.HourMetrics.Version);
                Debug.WriteLine("Logging.LoggingOperations     : " + currentProperties.Logging.LoggingOperations);
                Debug.WriteLine("Logging.RetentionDays         : " + currentProperties.Logging.RetentionDays);
                Debug.WriteLine("Logging.Version               : " + currentProperties.Logging.Version);
                Debug.WriteLine("MinuteMetrics.MetricsLevel    : " + currentProperties.MinuteMetrics.MetricsLevel);
                Debug.WriteLine("MinuteMetrics.RetentionDays   : " + currentProperties.MinuteMetrics.RetentionDays);
                Debug.WriteLine("MinuteMetrics.Version         : " + currentProperties.MinuteMetrics.Version);
            }
            return currentProperties;
        }

        public async Task SendClientAlerteAsync(SerializableEvenement evenement, bool scheduleNextEvent = false)
        {
            Debug.WriteLine(evenement.NenuAlerteTypeLabel + " >> EXECUTING EVENEMENT " + evenement.Id);

            try
            {
                //Console.WriteLine("EXECUTING EVENEMENT " + evenement.Id);
                if (evenement.Medium == MEDIUM.PLATFORM)
                {
                    IClientAlerte alerte = new ClientAlerteTableEntity(evenement)
                    {
                        // the alerte will be send NOW
                        SentOn = DateTime.UtcNow,
                    };

                    Debug.WriteLine("SENDING NEW CLIENT ALERTE " + alerte.TypeId + " : " + alerte.Id);
                    await new DataServiceFactory().GetDataService().AddClientAlerteAsync(alerte);
                }
                else if (evenement.Medium == MEDIUM.EMAIL)
                {
                    await new EmailService().SendAsync(evenement);
                }
                // Mark the corresponding event as executed
                    await MarkAsExecuted(evenement);
                // Schedule the next Event
                if (scheduleNextEvent)
                    await ScheduleNextEvent(evenement);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Console.WriteLine(ex);
                throw ex;
            }

        }

        private static async Task MarkAsExecuted(SerializableEvenement evenement)
        {
            var dataService = new DataServiceFactory().GetDataService();
            var nenuEvent = await dataService.GetEvenementAsync(evenement.RecipientEntityId, evenement.Id);
            if (nenuEvent != null)
            {
                nenuEvent.Status = EvenementState.EXECUTED;
                nenuEvent.ExecutedOn = DateTime.UtcNow;
                //Console.WriteLine("MARKING EVENEMENT " + nenuEvent.Id + " : EXECUTED");
                Debug.WriteLine("UPDATING EVENEMENT " + nenuEvent.Id);
                await dataService.UpdateEvenement(nenuEvent);
            }
            else
                throw new EvenementNotFoundException(nenuEvent.Id);

        }

        private static async Task ScheduleNextEvent(SerializableEvenement evenement)
        {
            if (evenement.Periodicity > 0)// ensure peridiodicity is not 0 to prevent infinite loop
            {
                evenement.NextScheduledOn = DateTime.UtcNow + TimeSpan.FromDays((int)evenement.Periodicity);
                //evenement.NextScheduledOn = DateTime.UtcNow + TimeSpan.FromSeconds(30);// USED FOR DEVELOPMENT ONLY
                evenement.HangfireId = null;
                evenement.Status = EvenementState.SCHEDULED;
                evenement.Id = Guid.NewGuid().ToString();
                await new SchedulerService().PlanifieAsync(evenement);
            }
        }

        //public async Task SendClientAlertesAsync(IList<SerializableEvenement> evenements, bool scheduleNextEvents = false)
        //{
        //    // Create the batch operation.
        //    TableBatchOperation batchOperation = new TableBatchOperation();

        //    // the alerte will be send NOW
        //    foreach (var evenement in evenements)
        //    {
        //        IClientAlerte alerte = new ClientAlerteTableEntity(evenement.RecipientEntityId.ToString(), evenement.Id.ToString(), evenement.NenuAlerteTypeLabel.ToString(), evenement.Title, evenement.Message)
        //        {
        //            // the alerte will be send NOW
        //            SentOn = DateTime.UtcNow
        //        };

        //        // Schedule the next Event
        //        if (scheduleNextEvents && evenement.Periodicity > 0)// ensure peridiodicity is not 0 to prevent infinite loop
        //        {
        //            evenement.NextScheduledOn = DateTime.UtcNow + TimeSpan.FromDays((int)evenement.Periodicity);
        //            await new SchedulerService().PlanifieAsync(evenement, scheduleNextEvents);
        //        }
        //    }

        //    // Execute the insert operation.
        //    await GetTable().ExecuteBatchAsync(batchOperation);

        //}

        public Task MarkAsReadAsync(string id)
        {
            throw new NotImplementedException();
        }

        public Task MarkAsUnReadAsync(string id)
        {
            throw new NotImplementedException();
        }

        public Task DeleteAsync(string id)
        {
            throw new NotImplementedException();
        }

        public Task<IClientAlerte> RetrieveAsync(string id)
        {
            throw new NotImplementedException();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >

    <solid android:color="@color/gray" />
 <!-- this one is ths color of the Rounded Button -->
     <corners
        android:radius="3dp" />

</shape>


text:
namespace Dos.Tools.EntityDesign.Forms
{
    partial class CheckVersion
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CheckVersion));
            this.label3 = new System.Windows.Forms.Label();
            this.linkLabel4 = new System.Windows.Forms.LinkLabel();
            this.label4 = new System.Windows.Forms.Label();
            this.linkLabel2 = new System.Windows.Forms.LinkLabel();
            this.linkLabel1 = new System.Windows.Forms.LinkLabel();
            this.label1 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            //
            // label3
            //
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.label3.Location = new System.Drawing.Point(25, 41);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(496, 16);
            this.label3.TabIndex = 3;
            this.label3.Text = "您的Dos.ORM实体生成器不是最新版本,请更新最新版本,谢谢!";
            //
            // linkLabel4
            //
            this.linkLabel4.AutoSize = true;
            this.linkLabel4.Location = new System.Drawing.Point(246, 163);
            this.linkLabel4.Name = "linkLabel4";
            this.linkLabel4.Size = new System.Drawing.Size(77, 12);
            this.linkLabel4.TabIndex = 17;
            this.linkLabel4.TabStop = true;
            this.linkLabel4.Text = "查看更新日志";
            this.linkLabel4.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel4_LinkClicked);
            //
            // label4
            //
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(92, 117);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 16;
            this.label4.Text = "GitHub:";
            //
            // linkLabel2
            //
            this.linkLabel2.AutoSize = true;
            this.linkLabel2.Location = new System.Drawing.Point(163, 117);
            this.linkLabel2.Name = "linkLabel2";
            this.linkLabel2.Size = new System.Drawing.Size(287, 12);
            this.linkLabel2.TabIndex = 15;
            this.linkLabel2.TabStop = true;
            this.linkLabel2.Text = "https://github.com/itdos/Dos.Tools.EntityDesign";
            this.linkLabel2.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel2_LinkClicked);
            //
            // linkLabel1
            //
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(163, 93);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(311, 12);
            this.linkLabel1.TabIndex = 14;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "http://git.oschina.net/ITdos/Dos.Tools.EntityDesign";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(92, 93);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(59, 12);
            this.label1.TabIndex = 13;
            this.label1.Text = "Git@OSC:";
            //
            // CheckVersion
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(549, 205);
            this.Controls.Add(this.linkLabel4);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.linkLabel2);
            this.Controls.Add(this.linkLabel1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.label3);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "CheckVersion";
            this.Text = "CheckVersion";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.LinkLabel linkLabel4;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.LinkLabel linkLabel2;
        private System.Windows.Forms.LinkLabel linkLabel1;
        private System.Windows.Forms.Label label1;
    }
}


text:
/*
 * EntityFactory.h
 *
 *  Created on: 19/07/2014
 *      Author: vitor
 */

#ifndef ENTITYFACTORY_H_
#define ENTITYFACTORY_H_

#include <math.h>
#include "GameAssets.h"
#include "ecs/VECS.h"
#include "parser/BulletDefinition.h"
#include "components/ActionsComponent.h"
#include "components/PositionComponent.h"
#include "components/VelocityComponent.h"
#include "components/AnimationComponent.h"
#include "components/BoundingCircleComponent.h"
#include "components/ShotComponent.h"
#include "components/marker/UIComponent.h"
#include "components/marker/EnemyMarker.h"
#include "components/marker/BackgroundMarker.h"
#include "components/marker/BulletMarker.h"
#include "components/marker/PlayerMarker.h"

class EntityFactory {
public:
	static EntityPtr create_player(World& world);
	static EntityPtr create_bullet(World& world, PositionComponent* position,
			VelocityComponent* velocity, BulletDefinition bullet_definition);
	static EntityPtr create_test_entity(World& world);
	static EntityPtr create_explosion(World& world,
			PositionComponent* position);
	static EntityPtr create_game_hud(World& world);
	static void create_moving_backgrounds(World& world);
};

#endif /* ENTITYFACTORY_H_ */


text:
/* eslint-env jest */

import React from 'react';
import { shallow } from 'enzyme';

jest.unmock('../index');

import App from '../index';
import Header from '../../../components/Header';

describe('(Container) App', () => {

  it('renders without exploding', () => {
    const wrapper = shallow(<App />);
    expect(wrapper.length).toEqual(1);
  });

  it('renders as a
', () => {
    const wrapper = shallow(<App />);
    expect(wrapper.type()).toEqual('div');
  });

  it('contains class in content', () => {
    const wrapper = shallow(<App />);
    expect(wrapper.is('.app')).toBe(true);
  });

  it('should render children when passed in', () => {
    const wrapper = shallow(
      <App>

      </App>
    );
    expect(wrapper.contains(
)).toEqual(true);
  });

  it('should render an `<Header>`', () => {
    const wrapper = shallow(<App />);
    expect(wrapper.find(Header).length).toEqual(1);

    // expect(wrapper.find(Header)).toBe(true);
  });

});


text:
layout: post
title: mesos-master replicated_log存的是什么?
category: dev
---

目前知道的,mesos master会使用replicated_log保存registry信息,那么这个registry信息以及这个replicated_log到底是什么?
用一种可以理解的方式阐述它们,对于理解mesos-master至关重要。

### mesos-log
偶然发现mesos的一个utility:mesos-log, 这是个命令行工具,可以用来初始化、读取、基准化replicated_log,在src\log目录下应该可以找到我们想要的内容。
我们在src/log/leveldb.cpp中发现:
```
Try<Nothing> LevelDBStorage::persist(const Metadata& metadata)
{
  Stopwatch stopwatch;
  stopwatch.start();

  leveldb::WriteOptions options;
  options.sync = true;

  Record record;
  record.set_type(Record::METADATA);
  record.mutable_metadata()->CopyFrom(metadata);

  string value;

  if (!record.SerializeToString(&value)) {
    return Error("Failed to serialize record");
  }

  leveldb::Status status = db->Put(options, encode(0, false), value);

  if (!status.ok()) {
    return Error(status.ToString());
  }

  LOG(INFO) << "Persisting metadata (" << value.size()
            << " bytes) to leveldb took " << stopwatch.elapsed();

  return Nothing();
}
```
假设replicated_log是使用leveldb持久化的,那么这里,有一个序列化为string的操作,我们可以通过打印出这个string来观察
leveldb里存的是什么。测试思路,添加打印日志,重新编译mesos,手动启动master/agent/framework之后,观察log输出。
重新编译mesos启动master之后,发现打印出的是乱码,追踪到src/messages/log.proto里定义了leveldb.cpp里的两个持久化对象
Metadata/Action, 看不出什么Metadata就是一个uint64?

继续阅读src/log...

### 官方文档
官方文档里说,replicated log里存的是集群状态信息,那么这个cluster state到底包含哪些东西呢?这个是本篇博客的主题。

replicated_log是append-only的,也就是说只支持append操作,append操作的对象是log entry, log entry可以是任何内容。
基本的场景是,多个replicas, 有一个leader,负责append, append的操作会复制到其他replica上,通过Paxos算法保证一致性。

文档里有一句话:"The Mesos master's registry also leverages the replicated log to store information about all agents in the cluster."
由此可以看出,master的replicated_log里存的是agent信息。

官方文档建议关掉replicated_log的自动初始化,因为其逻辑是在多个replica都为空的情况下,自动初始化log。但这种情况
可能出现在一些灾难性的事故中。保守的用户,建议使用手动初始化。

ok, 终于找到了:/src/master/registry.proto里定义了replicated_log里存储的信息:
```
// Most recent leading master.
  optional Master master = 1;

  // All admitted slaves.
  optional Slaves slaves = 2;

  // Holds a list of machines and some status information about each.
  // See comments in `MachineInfo` for more information.
  optional Machines machines = 3;

  // Describes a schedule for taking down specific machines for maintenance.
  // The schedule is meant to give hints to frameworks about potential
  // unavailability of resources.  The `schedules` are related to the status
  // information found in `machines`.
  repeated maintenance.Schedule schedules = 4;

  // A list of recorded quotas in the cluster. It does not hold an actual
  // assignment of resources, a newly elected master shall reconstruct it
  // from the cluster.
  repeated Quota quotas = 5;

  // A list of recorded weights in the cluster, a newly elected master shall
  // reconstruct it from the registry.
  repeated Weight weights = 6;
```
可见,replicated_log/registry里保存了:leading master信息、agents信息、机器信息、Maintenance的Schedule信息、quota信息、
权重信息。

ok,到这里已经大概清楚registry/replicated_log里保存的信息了。


text:
package org.dol.util;

public interface WorkIdGenerator {

    int getWorkId();
    /*public long getWorkId() {
        String ip = IPUtil.getLocalHostIP();
        long l = Math.abs(IPUtil.ip2num(ip) - maxWorkId);
    }*/
   /* public static void main(String[] args) {
        System.out.println(122112 & 1000);
    }*/

}


text:
<?php

namespace Vich\UploaderBundle\EventListener\Propel;

use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * CleanListener
 *
 * Listen to the update event to delete old files accordingly.
 *
 * @author Kévin Gomez <contact@kevingomez.fr>
 */
class CleanListener extends BaseListener
{
    /**
     * The events the listener is subscribed to.
     *
     * @return array The array of events.
     */
    public static function getSubscribedEvents()
    {
        return array(
            'propel.pre_update' => 'onUpload',
        );
    }

    /**
     * @param GenericEvent $event The event.
     */
    public function onUpload(GenericEvent $event)
    {
        $object = $this->adapter->getObjectFromArgs($event);
        $this->handler->clean($object, $this->mapping);
    }
}


text:
package org.postgresql.core;

import org.postgresql.PGNotification;

public class Notification implements PGNotification {

  private final String name;
  private final String parameter;
  private final int pid;

  public Notification(String name, int pid) {
    this(name, pid, "");
  }

  public Notification(String name, int pid, String parameter) {
    this.name = name;
    this.pid = pid;
    this.parameter = parameter;
  }

  /*
   * Returns name of this notification
   */
  public String getName() {
    return name;
  }

  /*
   * Returns the process id of the backend process making this notification
   */
  public int getPID() {
    return pid;
  }

  public String getParameter() {
    return parameter;
  }

}


text:
Deface::Override.new(
  virtual_path: 'spree/admin/orders/edit',
  name: 'add_clone_button_to_orders',
  insert_before: "code[erb-silent]:contains('can?(:admin, Spree::Order)')",
  partial: 'spree/admin/orders/duplicate',
  disabled: false
)


text:
package ca.carleton.gcrc.dbWeb;

import java.util.List;

import ca.carleton.gcrc.auth.common.User;
import ca.carleton.gcrc.dbSec.DbUser;

public class DbUserAdaptor implements DbUser {

	private User user;

	public DbUserAdaptor(User user) {
		this.user = user;
	}

	public List<Integer> getGroups() {
		return user.getGroups();
	}

	public String getVariable(String variableName) {
		if( "id".equals(variableName) ) {
			return ""+user.getId();
		}

		return null;
	}
}


text:
package mdb

/*
#include <stdlib.h>
#include <lmdb.h>
*/
import "C"

import (
	"errors"
	"fmt"
	"syscall"
	"unsafe"
)

const SUCCESS = C.MDB_SUCCESS

// mdb_env Environment Flags
const (
	FIXEDMAP   = C.MDB_FIXEDMAP   // mmap at a fixed address (experimental)
	NOSUBDIR   = C.MDB_NOSUBDIR   // no environment directory
	NOSYNC     = C.MDB_NOSYNC     // don't fsync after commit
	RDONLY     = C.MDB_RDONLY     // read only
	NOMETASYNC = C.MDB_NOMETASYNC // don't fsync metapage after commit
	WRITEMAP   = C.MDB_WRITEMAP   // use writable mmap
	MAPASYNC   = C.MDB_MAPASYNC   // use asynchronous msync when MDB_WRITEMAP is use
	NOTLS      = C.MDB_NOTLS      // tie reader locktable slots to Txn objects instead of threads
	NORDAHEAD  = C.MDB_NORDAHEAD  // turn off readahead
)

type DBI uint

type Errno C.int

// minimum and maximum values produced for the Errno type. syscall.Errnos of
// other values may still be produced.
const minErrno, maxErrno C.int = C.MDB_KEYEXIST, C.MDB_LAST_ERRCODE

func (e Errno) Error() string {
	s := C.GoString(C.mdb_strerror(C.int(e)))
	if s == "" {
		return fmt.Sprint("mdb errno:", int(e))
	}
	return s
}

// for tests that can't import C
func _errno(ret int) error {
	return errno(C.int(ret))
}

func errno(ret C.int) error {
	if ret == C.MDB_SUCCESS {
		return nil
	}
	if minErrno <= ret && ret <= maxErrno {
		return Errno(ret)
	}
	return syscall.Errno(ret)
}

// error codes
const (
	KeyExist        = Errno(C.MDB_KEYEXIST)
	NotFound        = Errno(C.MDB_NOTFOUND)
	PageNotFound    = Errno(C.MDB_PAGE_NOTFOUND)
	Corrupted       = Errno(C.MDB_CORRUPTED)
	Panic           = Errno(C.MDB_PANIC)
	VersionMismatch = Errno(C.MDB_VERSION_MISMATCH)
	Invalid         = Errno(C.MDB_INVALID)
	MapFull         = Errno(C.MDB_MAP_FULL)
	DbsFull         = Errno(C.MDB_DBS_FULL)
	ReadersFull     = Errno(C.MDB_READERS_FULL)
	TlsFull         = Errno(C.MDB_TLS_FULL)
	TxnFull         = Errno(C.MDB_TXN_FULL)
	CursorFull      = Errno(C.MDB_CURSOR_FULL)
	PageFull        = Errno(C.MDB_PAGE_FULL)
	MapResized      = Errno(C.MDB_MAP_RESIZED)
	Incompatibile   = Errno(C.MDB_INCOMPATIBLE)
)

func Version() string {
	var major, minor, patch *C.int
	ver_str := C.mdb_version(major, minor, patch)
	return C.GoString(ver_str)
}

// Env is opaque structure for a database environment.
// A DB environment supports multiple databases, all residing in the
// same shared-memory map.
type Env struct {
	env *C.MDB_env
}

// Create an MDB environment handle.
func NewEnv() (*Env, error) {
	var env *C.MDB_env
	ret := C.mdb_env_create(&env)
	if ret != SUCCESS {
		return nil, errno(ret)
	}
	return &Env{env}, nil
}

// Open an environment handle. If this function fails Close() must be called to discard the Env handle.
func (env *Env) Open(path string, flags uint, mode uint) error {
	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))
	ret := C.mdb_env_open(env.env, cpath, C.uint(flags), C.mdb_mode_t(mode))
	return errno(ret)
}

func (env *Env) Close() error {
	if env.env == nil {
		return errors.New("Environment already closed")
	}
	C.mdb_env_close(env.env)
	env.env = nil
	return nil
}

func (env *Env) Copy(path string) error {
	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))
	ret := C.mdb_env_copy(env.env, cpath)
	return errno(ret)
}

// Statistics for a database in the environment
type Stat struct {
	PSize         uint   // Size of a database page. This is currently the same for all databases.
	Depth         uint   // Depth (height) of the B-tree
	BranchPages   uint64 // Number of internal (non-leaf) pages
	LeafPages     uint64 // Number of leaf pages
	OverflowPages uint64 // Number of overflow pages
	Entries       uint64 // Number of data items
}

func (env *Env) Stat() (*Stat, error) {
	var c_stat C.MDB_stat
	ret := C.mdb_env_stat(env.env, &c_stat)
	if ret != SUCCESS {
		return nil, errno(ret)
	}
	stat := Stat{PSize: uint(c_stat.ms_psize),
		Depth:         uint(c_stat.ms_depth),
		BranchPages:   uint64(c_stat.ms_branch_pages),
		LeafPages:     uint64(c_stat.ms_leaf_pages),
		OverflowPages: uint64(c_stat.ms_overflow_pages),
		Entries:       uint64(c_stat.ms_entries)}
	return &stat, nil
}

type Info struct {
	MapSize    uint64 // Size of the data memory map
	LastPNO    uint64 // ID of the last used page
	LastTxnID  uint64 // ID of the last committed transaction
	MaxReaders uint   // maximum number of threads for the environment
	NumReaders uint   // maximum number of threads used in the environment
}

func (env *Env) Info() (*Info, error) {
	var c_info C.MDB_envinfo
	ret := C.mdb_env_info(env.env, &c_info)
	if ret != SUCCESS {
		return nil, errno(ret)
	}
	info := Info{MapSize: uint64(c_info.me_mapsize),
		LastPNO:    uint64(c_info.me_last_pgno),
		LastTxnID:  uint64(c_info.me_last_txnid),
		MaxReaders: uint(c_info.me_maxreaders),
		NumReaders: uint(c_info.me_numreaders)}
	return &info, nil
}

func (env *Env) Sync(force int) error {
	ret := C.mdb_env_sync(env.env, C.int(force))
	return errno(ret)
}

func (env *Env) SetFlags(flags uint, set bool) error {
	onoff := C.int(0)
	if set {
		onoff = C.int(1)
	}
	ret := C.mdb_env_set_flags(env.env, C.uint(flags), onoff)
	return errno(ret)
}

func (env *Env) Flags() (uint, error) {
	var flags C.uint
	ret := C.mdb_env_get_flags(env.env, &flags)
	if ret != SUCCESS {
		return 0, errno(ret)
	}
	return uint(flags), nil
}

func (env *Env) Path() (string, error) {
	var path string
	cpath := C.CString(path)
	defer C.free(unsafe.Pointer(cpath))
	ret := C.mdb_env_get_path(env.env, &cpath)
	if ret != SUCCESS {
		return "", errno(ret)
	}
	return C.GoString(cpath), nil
}

func (env *Env) SetMapSize(size uint64) error {
	ret := C.mdb_env_set_mapsize(env.env, C.size_t(size))
	return errno(ret)
}

func (env *Env) SetMaxReaders(size uint) error {
	ret := C.mdb_env_set_maxreaders(env.env, C.uint(size))
	return errno(ret)
}

func (env *Env) SetMaxDBs(size DBI) error {
	ret := C.mdb_env_set_maxdbs(env.env, C.MDB_dbi(size))
	return errno(ret)
}

func (env *Env) DBIClose(dbi DBI) {
	C.mdb_dbi_close(env.env, C.MDB_dbi(dbi))
}


text:
using System;
using System.Runtime.InteropServices;
using System.Windows.Controls;
using AvaloniaVS.Models;
using AvaloniaVS.Views;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Serilog;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

namespace AvaloniaVS.Services
{
    /// <summary>
    /// Implements <see cref="IVsEditorFactory"/> to create <see cref="DesignerPane"/>s containing
    /// an Avalonia XAML designer.
    /// </summary>
    internal sealed class EditorFactory : IVsEditorFactory, IDisposable
    {
        private static readonly Guid XmlLanguageServiceGuid = new Guid("f6819a78-a205-47b5-be1c-675b3c7f0b8e");
        private static readonly Guid XamlLanguageServiceGuid = new Guid("cd53c9a1-6bc2-412b-be36-cc715ed8dd41");
        private readonly AvaloniaPackage _package;
        private IOleServiceProvider _oleServiceProvider;
        private ServiceProvider _serviceProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="EditorFactory"/> class.
        /// </summary>
        /// <param name="package">The package that the factory belongs to.</param>
        public EditorFactory(AvaloniaPackage package) => _package = package;

        /// <inheritdoc/>
        public int SetSite(IOleServiceProvider psp)
        {
            _oleServiceProvider = psp;
            _serviceProvider = new ServiceProvider(psp);
            return VSConstants.S_OK;
        }

        /// <inheritdoc/>
        public int MapLogicalView(ref Guid rguidLogicalView, out string pbstrPhysicalView)
        {
            pbstrPhysicalView = null;

            if (rguidLogicalView == VSConstants.LOGVIEWID_Primary ||
                rguidLogicalView == VSConstants.LOGVIEWID_Code ||
                rguidLogicalView == VSConstants.LOGVIEWID_Debugging ||
                rguidLogicalView == VSConstants.LOGVIEWID_TextView ||
                rguidLogicalView == VSConstants.LOGVIEWID_Designer)
            {
                return VSConstants.S_OK;
            }

            return VSConstants.E_NOTIMPL;
        }

        /// <inheritdoc/>
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            IntPtr punkDocDataExisting,
            out IntPtr ppunkDocView,
            out IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out Guid pguidCmdUI,
            out int pgrfCDW)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            Log.Logger.Verbose("Started EditorFactory.CreateEditorInstance({Filename})", pszMkDocument);

            ppunkDocView = IntPtr.Zero;
            ppunkDocData = IntPtr.Zero;
            pguidCmdUI = Guids.AvaloniaDesignerEditorFactory;
            pgrfCDW = 0;
            pbstrEditorCaption = string.Empty;

            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return VSConstants.E_INVALIDARG;
            }

            var project = GetProject(pvHier);

            if (project == null)
            {
                return VSConstants.S_FALSE;
            }

            var textBuffer = GetTextBuffer(pszMkDocument, punkDocDataExisting);
            var (editorWindow, editorControl) = CreateEditorControl(textBuffer);
            var pane = new DesignerPane(project, pszMkDocument, editorWindow, editorControl);
            ppunkDocView = Marshal.GetIUnknownForObject(pane);
            ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);

            Log.Logger.Verbose("Finished EditorFactory.CreateEditorInstance({Filename})", pszMkDocument);
            return VSConstants.S_OK;
        }

        /// <inheritdoc/>
        public int Close() => VSConstants.S_OK;

        /// <inheritdoc/>
        public void Dispose()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            _serviceProvider?.Dispose();
            _serviceProvider = null;
        }

        private IVsTextLines GetTextBuffer(string fileName, IntPtr punkDocDataExisting)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsTextLines result;

            Log.Logger.Verbose("Started EditorFactory.GetTextBuffer({Filename})", fileName);

            if (punkDocDataExisting == IntPtr.Zero)
            {
                // Get an invisible editor over the file. This is much easier than having to
                // manually figure out the right content type and language service, and it will
                // automatically associate the document with its owning project, meaning we will
                // get intellisense in our editor with no extra work.
                var iem = _serviceProvider.GetService<IVsInvisibleEditorManager, SVsInvisibleEditorManager>();

                ErrorHandler.ThrowOnFailure(iem.RegisterInvisibleEditor(
                    fileName,
                    pProject: null,
                    dwFlags: (uint)_EDITORREGFLAGS.RIEF_ENABLECACHING,
                    pFactory: null,
                    ppEditor: out var invisibleEditor));

                var guidIVSTextLines = typeof(IVsTextLines).GUID;
                ErrorHandler.ThrowOnFailure(invisibleEditor.GetDocData(
                    fEnsureWritable: 1,
                    riid: ref guidIVSTextLines,
                    ppDocData: out var docDataPointer));

                result = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);
            }
            else
            {
                result = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;

                if (result == null)
                {
                    ErrorHandler.ThrowOnFailure(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            // Set buffer content type to XML. The default XAML content type will cause blue
            // squiggly lines to be displayed on the elements, as the XAML language service is
            // hard-coded as to the XAML dialects it supports and Avalonia isn't one of them :(
            ErrorHandler.ThrowOnFailure(result.SetLanguageServiceID(XmlLanguageServiceGuid));

            Log.Logger.Verbose("Finished EditorFactory.GetTextBuffer({Filename})", fileName);
            return result;
        }

        private (IVsCodeWindow, IWpfTextViewHost) CreateEditorControl(IVsTextLines bufferAdapter)
        {
            Log.Logger.Verbose("Started EditorFactory.CreateEditorControl()");

            var componentModel = _serviceProvider.GetService<IComponentModel, SComponentModel>();
            var eafs = componentModel.GetService<IVsEditorAdaptersFactoryService>();
            var codeWindow = eafs.CreateVsCodeWindowAdapter(_oleServiceProvider);

            // Disable the splitter control on the editor as leaving it enabled causes a crash if the user
            // tries to use it here.
            ((IVsCodeWindowEx)codeWindow).Initialize(
                (uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER,
                VSUSERCONTEXTATTRIBUTEUSAGE.VSUC_Usage_Filter,
                szNameAuxUserContext: "",
                szValueAuxUserContext: "",
                InitViewFlags: 0,
                pInitView: new INITVIEW[1]);

            // Add metadata to the buffer so we can identify it as containing Avalonia XAML.
            var buffer = eafs.GetDataBuffer(bufferAdapter);
            buffer.Properties.GetOrCreateSingletonProperty(() => new XamlBufferMetadata());

            ErrorHandler.ThrowOnFailure(codeWindow.SetBuffer(bufferAdapter));
            ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out var textViewAdapter));

            // In VS2019 preview 3, the IWpfTextViewHost.HostControl comes parented. Remove the
            // control from its parent otherwise we can't reparent it. This is probably a bug
            // in the preview and can probably be removed later.
            var textViewHost = eafs.GetWpfTextViewHost(textViewAdapter);

            if (textViewHost.HostControl.Parent is Decorator parent)
            {
                parent.Child = null;
            }

            Log.Logger.Verbose("Finished EditorFactory.CreateEditorControl()");
            return (codeWindow, textViewHost);
        }

        private static Project GetProject(IVsHierarchy hierarchy)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(
                VSConstants.VSITEMID_ROOT,
                (int)__VSHPROPID.VSHPROPID_ExtObject,
                out var objProj));
            return objProj as Project;
        }
    }
}


text:
package com.sap.jam.samples.jira.plugin.odata.server.processors;

import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.exception.ODataNotImplementedException;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.processor.ODataSingleProcessor;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo;
import org.apache.olingo.odata2.api.uri.info.PostUriInfo;

import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.applinks.api.ApplicationLinkService;
import com.atlassian.applinks.spi.auth.AuthenticationConfigurationManager;
import com.atlassian.crowd.embedded.api.User;
import com.sap.jam.samples.jira.plugin.ao.OAuth2Token;
import com.sap.jam.samples.jira.plugin.applink.JamApplicationType;
import com.sap.jam.samples.jira.plugin.auth.JamConsumerProviderStore;
import com.sap.jam.samples.jira.plugin.auth.ServiceProvider;

public class JiraODataProcessor extends ODataSingleProcessor {

	private final IssueProcessor issueProcessor;
	private final FilterProcessor filterProcessor;

    public JiraODataProcessor(ODataContext ctx) throws ODataException
	{
    	// Authenticate this user
	    authenticate((HttpServletRequest) ctx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT));

	    issueProcessor   = new IssueProcessor(ctx);
            filterProcessor = new FilterProcessor(ctx);
	}

	@Override
	public ODataResponse readEntity(GetEntityUriInfo uriInfo, String contentType) throws ODataException
	{
		String entitySet = uriInfo.getStartEntitySet().getName();
		if ( entitySet.equals("Issues") ) {
                  return issueProcessor.readEntity(uriInfo, contentType);
		} else if ( entitySet.equals("Filters") ) {
                  return filterProcessor.readEntity(uriInfo, contentType);
		}
		throw new ODataNotImplementedException();
	}

	@Override
	public ODataResponse readEntitySet(GetEntitySetUriInfo uriInfo, String contentType) throws ODataException
	{
		String entitySet = uriInfo.getStartEntitySet().getName();
		if ( entitySet.equals("Issues") ) {
                  return issueProcessor.readEntitySet(uriInfo, contentType);
		} else if ( entitySet.equals("Filters") ) {
                  return filterProcessor.readEntitySet(uriInfo, contentType);
		}
		throw new ODataNotImplementedException();
	}

	@Override
	public ODataResponse createEntity(PostUriInfo uriInfo, InputStream content, String requestContentType, String contentType) throws ODataException
	{
		throw new ODataNotImplementedException();
	}

	private void authenticate(HttpServletRequest request) throws ODataException
	{
        final String authorization = request.getHeader("Authorization");

        if (authorization != null && authorization.startsWith("Bearer "))
        {
            String token = authorization.substring("Bearer".length()).trim();

            // Initialize JIRA services
            AuthenticationConfigurationManager authenticationConfigurationManager = ComponentAccessor.getOSGiComponentInstanceOfType(AuthenticationConfigurationManager.class);
            ApplicationLinkService applicationLinkService = ComponentAccessor.getOSGiComponentInstanceOfType(ApplicationLinkService.class);

            JamConsumerProviderStore jamConsumerProviderStore = new JamConsumerProviderStore(authenticationConfigurationManager);
            ServiceProvider jamServiceProvider = jamConsumerProviderStore.getServiceProvider(applicationLinkService.getPrimaryApplicationLink(JamApplicationType.class));

            if ( jamServiceProvider != null )
            {
                OAuth2Token jamToken = jamServiceProvider.getTokenFromBearerToken(token);
                if ( jamToken != null ) {
                    User user = ComponentAccessor.getUserUtil().getUserObject(jamToken.getUsername());
                    if ( user != null ) {
                        // Set the current user context to this user!
                        ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(user);
                        return;
                    }
                }
            }
        }
    	throw new ODataUnauthorizedException();
    }
}


text:
using namespace std;
using namespace IECore;
using namespace Gaffer;
using namespace GafferUI;
using namespace GafferScene;
using namespace GafferSceneUI;

//////////////////////////////////////////////////////////////////////////
// Implementation of a ParameterisedProcedural wrapping a SceneProcedural.
// We need this to allow us to use the RenderableGadget for doing our
// display.
/// \todo Build our own scene representation.
//////////////////////////////////////////////////////////////////////////

class WrappingProcedural : public IECore::ParameterisedProcedural
{

	public :

		WrappingProcedural( SceneProceduralPtr sceneProcedural )
			:	ParameterisedProcedural( "" ), m_sceneProcedural( sceneProcedural )
		{
		}

	protected :

		virtual Imath::Box3f doBound( ConstCompoundObjectPtr args ) const
		{
			return m_sceneProcedural->bound();
		}

		virtual void doRender( RendererPtr renderer, ConstCompoundObjectPtr args ) const
		{
			m_sceneProcedural->render( renderer );
		}

	private :

		SceneProceduralPtr m_sceneProcedural;

};

IE_CORE_DECLAREPTR( WrappingProcedural );

//////////////////////////////////////////////////////////////////////////
// SceneView implementation
//////////////////////////////////////////////////////////////////////////

IE_CORE_DEFINERUNTIMETYPED( SceneView );

size_t SceneView::g_firstPlugIndex = 0;
SceneView::ViewDescription<SceneView> SceneView::g_viewDescription( GafferScene::ScenePlug::staticTypeId() );

SceneView::SceneView( const std::string &name )
	:	View3D( name, new GafferScene::ScenePlug() ),
		m_renderableGadget( new RenderableGadget )
{

	// add plugs and signal handling for them

	storeIndexOfNextChild( g_firstPlugIndex );

	addChild( new IntPlug( "minimumExpansionDepth", Plug::In, 0, 0, Imath::limits<int>::max(), Plug::Default & ~Plug::AcceptsInputs ) );

	CompoundPlugPtr lookThrough = new CompoundPlug( "lookThrough", Plug::In, Plug::Default & ~Plug::AcceptsInputs );
	lookThrough->addChild( new BoolPlug( "enabled", Plug::In, false, Plug::Default & ~Plug::AcceptsInputs ) );
	lookThrough->addChild( new StringPlug( "camera", Plug::In, "", Plug::Default & ~Plug::AcceptsInputs ) );
	addChild( lookThrough );

	plugSetSignal().connect( boost::bind( &SceneView::plugSet, this, ::_1 ) );

	// set up our gadgets

	viewportGadget()->setChild( m_renderableGadget );

	m_selectionChangedConnection = m_renderableGadget->selectionChangedSignal().connect( boost::bind( &SceneView::selectionChanged, this, ::_1 ) );
	viewportGadget()->keyPressSignal().connect( boost::bind( &SceneView::keyPress, this, ::_1, ::_2 ) );

	m_renderableGadget->baseState()->add( const_cast<IECoreGL::State *>( baseState() ) );
	baseStateChangedSignal().connect( boost::bind( &SceneView::baseStateChanged, this ) );

	//////////////////////////////////////////////////////////////////////////
	// add a preprocessor which monkeys with the scene before it is displayed.
	//////////////////////////////////////////////////////////////////////////

	NodePtr preprocessor = new Node();
	ScenePlugPtr preprocessorInput = new ScenePlug( "in" );
	preprocessor->addChild( preprocessorInput );

	// remove motion blur, because the opengl renderer doesn't support it.

	StandardOptionsPtr standardOptions = new StandardOptions( "disableBlur" );
	standardOptions->optionsPlug()->getChild<CompoundPlug>( "transformBlur" )->getChild<BoolPlug>( "enabled" )->setValue( true );
	standardOptions->optionsPlug()->getChild<CompoundPlug>( "transformBlur" )->getChild<BoolPlug>( "value" )->setValue( false );
	standardOptions->optionsPlug()->getChild<CompoundPlug>( "deformationBlur" )->getChild<BoolPlug>( "enabled" )->setValue( true );
	standardOptions->optionsPlug()->getChild<CompoundPlug>( "deformationBlur" )->getChild<BoolPlug>( "value" )->setValue( false );

	preprocessor->addChild( standardOptions );
	standardOptions->inPlug()->setInput( preprocessorInput );

	// add a node for hiding things

	StandardAttributesPtr hide = new StandardAttributes( "hide" );
	hide->attributesPlug()->getChild<CompoundPlug>( "visibility" )->getChild<BoolPlug>( "enabled" )->setValue( true );
	hide->attributesPlug()->getChild<CompoundPlug>( "visibility" )->getChild<BoolPlug>( "value" )->setValue( false );

	preprocessor->addChild( hide );
	hide->inPlug()->setInput( standardOptions->outPlug() );

	PathFilterPtr hideFilter = new PathFilter( "hideFilter" );
	preprocessor->addChild( hideFilter );
	hide->filterPlug()->setInput( hideFilter->matchPlug() );

	// make the output for the preprocessor

	ScenePlugPtr preprocessorOutput = new ScenePlug( "out", Plug::Out );
	preprocessor->addChild( preprocessorOutput );
	preprocessorOutput->setInput( hide->outPlug() );

	setPreprocessor( preprocessor );
}

SceneView::~SceneView()
{
}

Gaffer::IntPlug *SceneView::minimumExpansionDepthPlug()
{
	return getChild<IntPlug>( g_firstPlugIndex );
}

const Gaffer::IntPlug *SceneView::minimumExpansionDepthPlug() const
{
	return getChild<IntPlug>( g_firstPlugIndex );
}

Gaffer::CompoundPlug *SceneView::lookThroughPlug()
{
	return getChild<CompoundPlug>( g_firstPlugIndex + 1 );
}

const Gaffer::CompoundPlug *SceneView::lookThroughPlug() const
{
	return getChild<CompoundPlug>( g_firstPlugIndex + 1 );
}

Gaffer::BoolPlug *SceneView::lookThroughEnabledPlug()
{
	return lookThroughPlug()->getChild<BoolPlug>( 0 );
}

const Gaffer::BoolPlug *SceneView::lookThroughEnabledPlug() const
{
	return lookThroughPlug()->getChild<BoolPlug>( 0 );
}

Gaffer::StringPlug *SceneView::lookThroughCameraPlug()
{
	return lookThroughPlug()->getChild<StringPlug>( 1 );
}

const Gaffer::StringPlug *SceneView::lookThroughCameraPlug() const
{
	return lookThroughPlug()->getChild<StringPlug>( 1 );
}

GafferScene::PathFilter *SceneView::hideFilter()
{
	return getPreprocessor<Node>()->getChild<PathFilter>( "hideFilter" );
}

const GafferScene::PathFilter *SceneView::hideFilter() const
{
	return getPreprocessor<Node>()->getChild<PathFilter>( "hideFilter" );
}

void SceneView::contextChanged( const IECore::InternedString &name )
{
	if( name.value() == "ui:scene:selectedPaths" )
	{
		// if only the selection has changed then we can just update the selection
		// on our existing scene representation.
		const StringVectorData *sc = getContext()->get<StringVectorData>( "ui:scene:selectedPaths" );
		RenderableGadget::Selection sr;
		sr.insert( sc->readable().begin(), sc->readable().end() );

		BlockedConnection blockedConnection( m_selectionChangedConnection );
		m_renderableGadget->setSelection( sr );
		return;
	}

	if(
		name.value().compare( 0, 3, "ui:" ) == 0 &&
		name.value() != "ui:scene:expandedPaths"
	)
	{
		// if it's just a ui context entry that has changed, and it doesn't
		// affect our expansion, then early out.
		return;
	}

	// the context change might affect the scene itself, so we must
	// schedule an update.
	updateRequestSignal()( this );
}

void SceneView::update()
{
	SceneProceduralPtr p = new SceneProcedural(
		preprocessedInPlug<ScenePlug>(), getContext(), ScenePlug::ScenePath(),
		expandedPaths(), minimumExpansionDepthPlug()->getValue()
	);
	WrappingProceduralPtr wp = new WrappingProcedural( p );

	bool hadRenderable = m_renderableGadget->getRenderable();
	m_renderableGadget->setRenderable( wp );
	if( !hadRenderable )
	{
		viewportGadget()->frame( m_renderableGadget->bound() );
	}

	updateLookThrough();
}

Imath::Box3f SceneView::framingBound() const
{
	Imath::Box3f b = m_renderableGadget->selectionBound();
	if( !b.isEmpty() )
	{
		return b;
	}
	return View3D::framingBound();
}

void SceneView::selectionChanged( GafferUI::RenderableGadgetPtr renderableGadget )
{
	BlockedConnection blockedConnection( contextChangedConnection() );
	transferSelectionToContext();
}

bool SceneView::keyPress( GafferUI::GadgetPtr gadget, const GafferUI::KeyEvent &event )
{
	if( event.key == "Down" )
	{
		expandSelection( event.modifiers & KeyEvent::Shift ? 999 : 1 );
		return true;
	}
	else if( event.key == "Up" )
	{
		collapseSelection();
		return true;
	}

	return false;
}

void SceneView::expandSelection( size_t depth )
{
	Context::Scope scopedContext( getContext() );

	RenderableGadget::Selection &selection = m_renderableGadget->getSelection();
	PathMatcher &expanded = expandedPaths()->writable();

	// must take a copy of the selection to iterate over, because we'll modify the
	// selection inside expandWalk().
	const std::vector<string> toExpand( selection.begin(), selection.end() );

	bool needUpdate = false;
	for( std::vector<string>::const_iterator it = toExpand.begin(), eIt = toExpand.end(); it != eIt; ++it )
	{
		needUpdate |= expandWalk( *it, depth, expanded, selection );
	}

	if( needUpdate )
	{
		// we were naughty and modified the expanded paths in place (to avoid
		// unecessary copying), so the context doesn't know they've changed.
		// so we emit the changed signal ourselves. this will then trigger update()
		// via contextChanged().
		getContext()->changedSignal()( getContext(), "ui:scene:expandedPaths" );
		// and this will trigger a selection update also via contextChanged().
		transferSelectionToContext();
	}
}

bool SceneView::expandWalk( const std::string &path, size_t depth, PathMatcher &expanded, RenderableGadget::Selection &selected )
{
	bool result = false;

	ScenePlug::ScenePath scenePath;
	ScenePlug::stringToPath( path, scenePath );
	ConstInternedStringVectorDataPtr childNamesData = preprocessedInPlug<ScenePlug>()->childNames( scenePath );
	const vector<InternedString> &childNames = childNamesData->readable();

	if( childNames.size() )
	{
		// expand ourselves to show our children, and make sure we're
		// not selected - we only want selection at the leaf levels of
		// our expansion.
		result |= expanded.addPath( path );
		result |= selected.erase( path );
		for( vector<InternedString>::const_iterator cIt = childNames.begin(), ceIt = childNames.end(); cIt != ceIt; cIt++ )
		{
			std::string childPath( path );
			if( *childPath.rbegin() != '/' )
			{
				childPath += '/';
			}
			childPath += cIt->string();
			if( depth == 1 )
			{
				// at the bottom of the expansion - just select the child
				result |= selected.insert( childPath ).second;
			}
			else
			{
				// continue the expansion
				result |= expandWalk( childPath, depth - 1, expanded, selected );
			}
		}
	}
	else
	{
		// we have no children, just make sure we're selected to mark the
		// leaf of the expansion.
		result |= selected.insert( path ).second;
	}

	return result;
}

void SceneView::collapseSelection()
{
	RenderableGadget::Selection &selection = m_renderableGadget->getSelection();
	if( !selection.size() )
	{
		return;
	}

	set<string> pathsToSelect;
	vector<const string *> pathsToDeselect;
	GafferScene::PathMatcherData *expandedData = expandedPaths();
	PathMatcher &expanded = expandedData->writable();

	for( RenderableGadget::Selection::const_iterator it = selection.begin(), eIt = selection.end(); it != eIt; it++ )
	{
		if( !expanded.removePath( *it ) )
		{
			if( *it == "/" )
			{
				continue;
			}
			pathsToDeselect.push_back( &(*it) );
			std::string parentPath( *it, 0, it->rfind( '/' ) );
			if( parentPath == "" )
			{
				parentPath = "/";
			}
			expanded.removePath( parentPath );
			pathsToSelect.insert( parentPath );
		}
	}

	for( set<string>::const_iterator it = pathsToSelect.begin(), eIt = pathsToSelect.end(); it != eIt; it++ )
	{
		selection.insert( *it );
	}
	for( vector<const string *>::const_iterator it = pathsToDeselect.begin(), eIt = pathsToDeselect.end(); it != eIt; it++ )
	{
		selection.erase( **it );
	}

	// see comment in expandSelection().
	getContext()->changedSignal()( getContext(), "ui:scene:expandedPaths" );
	// and this will trigger a selection update also via contextChanged().
	transferSelectionToContext();
}

void SceneView::transferSelectionToContext()
{
	/// \todo If RenderableGadget used PathMatcherData, then we might not need
	/// to copy data here.
	const RenderableGadget::Selection &selection = m_renderableGadget->getSelection();
	StringVectorDataPtr s = new StringVectorData();
	s->writable().insert( s->writable().end(), selection.begin(), selection.end() );
	getContext()->set( "ui:scene:selectedPaths", s.get() );
}

GafferScene::PathMatcherData *SceneView::expandedPaths()
{
	const GafferScene::PathMatcherData *m = getContext()->get<GafferScene::PathMatcherData>( "ui:scene:expandedPaths", 0 );
	if( !m )
	{
		GafferScene::PathMatcherDataPtr rootOnly = new GafferScene::PathMatcherData;
		rootOnly->writable().addPath( "/" );
		BlockedConnection blockedConnection( contextChangedConnection() );
		getContext()->set( "ui:scene:expandedPaths", rootOnly.get() );
		m = getContext()->get<GafferScene::PathMatcherData>( "ui:scene:expandedPaths", 0 );
	}
	return const_cast<GafferScene::PathMatcherData *>( m );
}

void SceneView::baseStateChanged()
{
	/// \todo This isn't transferring the override state properly. Probably an IECoreGL problem.
	m_renderableGadget->baseState()->add( const_cast<IECoreGL::State *>( baseState() ) );
	m_renderableGadget->renderRequestSignal()( m_renderableGadget );
}

void SceneView::plugSet( Gaffer::Plug *plug )
{
	if( plug == minimumExpansionDepthPlug() )
	{
		updateRequestSignal()( this );
	}
	else if( plug == lookThroughPlug() )
	{
		updateLookThrough();
	}
}

void SceneView::updateLookThrough()
{
	Context::Scope scopedContext( getContext() );

	const ScenePlug *scene = preprocessedInPlug<ScenePlug>();
	ConstCompoundObjectPtr globals = scene->globalsPlug()->getValue();

	string cameraPathString;
	IECore::CameraPtr camera;
	if( lookThroughEnabledPlug()->getValue() )
	{
		cameraPathString = lookThroughCameraPlug()->getValue();
		if( cameraPathString.empty() )
		{
			if( const StringData *cameraPathData = globals->member<StringData>( "render:camera" ) )
			{
				cameraPathString = cameraPathData->readable();
			}
		}

		if( !cameraPathString.empty() )
		{
			ScenePlug::ScenePath cameraPath;
			ScenePlug::stringToPath( cameraPathString, cameraPath );

			try
			{
				ConstCameraPtr constCamera = runTimeCast<const IECore::Camera>( scene->object( cameraPath ) );
				if( constCamera )
				{
					camera = constCamera->copy();
					camera->setTransform( new MatrixTransform( scene->fullTransform( cameraPath ) ) );

					// if the camera has an existing screen window, remove it.
					// if we didn't, it would conflict with the resolution we set
					// below, yielding squashed/stretched images.
					/// \todo Properly specify how cameras are represented in Gaffer
					/// (the Cortex representation is very renderer-centric, with no
					/// real world parameters like film back) so that this isn't necessary,
					/// and add nice overlays for resolution gate etc.
					camera->parameters().erase( "screenWindow" );
				}
			}
			catch( ... )
			{
				// if an invalid path has been entered for the camera, computation will fail.
				// we can just ignore that and fall through to lock to the current camera instead.
				cameraPathString = "";
			}
		}

		if( !camera )
		{
			// we couldn't find a render camera to lock to, but we can lock to the current
			// camera instead.
			camera = viewportGadget()->getCamera()->copy();
		}
	}

	if( camera )
	{
		camera->parameters()["resolution"] = new V2iData( viewportGadget()->getViewport() );
		viewportGadget()->setCamera( camera );
		viewportGadget()->setCameraEditable( false );

		StringVectorDataPtr invisiblePaths = new StringVectorData();
		invisiblePaths->writable().push_back( cameraPathString );
		hideFilter()->pathsPlug()->setValue( invisiblePaths );
	}
	else
	{
		viewportGadget()->setCameraEditable( true );
		hideFilter()->pathsPlug()->setToDefault();
	}
}


text:
package com.adms.mglplanlv.dao.salesmglplanlv;

import com.adms.common.dao.generic.GenericDao;
import com.adms.mglplanlv.entity.SalesMglPlanLv;

public interface SalesMglPlanLvDao extends GenericDao<SalesMglPlanLv, Long> {

}


text:
extern size_t
tuklib_mbstr_width(const char *str, size_t *bytes)
{
	const size_t len = strlen(str);
	if (bytes != NULL)
		*bytes = len;

#if !(defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH))
	// In single-byte mode, the width of the string is the same
	// as its length.
	return len;

#else
	mbstate_t state;
	memset(&state, 0, sizeof(state));

	size_t width = 0;
	size_t i = 0;

	// Convert one multibyte character at a time to wchar_t
	// and get its width using wcwidth().
	while (i < len) {
		wchar_t wc;
		const size_t ret = mbrtowc(&wc, str + i, len - i, &state);
		if (ret < 1 || ret > len)
			return (size_t)-1;

		i += ret;

		const int wc_width = wcwidth(wc);
		if (wc_width < 0)
			return (size_t)-1;

		width += wc_width;
	}

	// Require that the string ends in the initial shift state.
	// This way the caller can be combine the string with other
	// strings without needing to worry about the shift states.
	if (!mbsinit(&state))
		return (size_t)-1;

	return width;
#endif
}