text:
from tepmodel import OptModels as opt
from tepmodel import OpfModels as opf
import pyomo.environ as pyo
import powersys.PowerSystemPlanning as pwsp
import Utils
import plotly
from plotly.graph_objs import Scatter, Layout
import pandas as pd
import xlsxwriter
import collections
import logging
import time
from datetime import timedelta
import random

class TepModelParameters(object):
    def __init__(self, opf_model_params=opf.OpfModelParameters(),
                 investment_costs_multiplier=1, operation_costs_multiplier=1,
                 disjunctive_parameter=1e10):
        self.investment_costs_multiplier = investment_costs_multiplier
        self.operation_costs_multiplier = operation_costs_multiplier
        self.disjunctive_parameter = disjunctive_parameter
        self.opf_model_params = opf_model_params

    @staticmethod
    def import_from_excel(excel_filepath):
        dict_params = Utils.excel_worksheet_to_dict(excel_filepath, 'Parameters')
        return TepModelParameters.import_from_dict(dict_params)

    @staticmethod
    def import_from_dict(dict_params):
        tep_params = TepModelParameters()
        for key, value in dict_params.items():
            if key.startswith('tep_params'):
                opf_param_name = key[key.find('.') + 1:]
                if opf_param_name == 'slack_bus_name' and isinstance(value, float):
                    value = str(int(value))
                setattr(tep_params, opf_param_name, value)
        tep_params.opf_model_params = opf.OpfModelParameters.import_from_dict(dict_params)
        return tep_params

class TepScenariosModel(object):
    def __init__(self, tep_system,
                 tep_scenarios_model_parameters=TepModelParameters()):
        # type: (powersys.PowerSystemPlanning.PowerSystemTransmissionPlanning, TepModelParameters, gurobipy.Model) -> None
        self.tep_system = tep_system  # type: PowerSystemPlanning.PowerSystemTransmissionPlanning
        self.tep_scenarios_model_parameters = tep_scenarios_model_parameters

    @staticmethod
    def import_from_excel(excel_filepath):
        imported_tep_system = pwsp.PowerSystemTransmissionPlanning.import_from_excel(excel_filepath)
        tep_scenarios_model_parameters = TepModelParameters.import_from_excel(excel_filepath)
        imported_tep_model = TepScenariosModel(imported_tep_system, tep_scenarios_model_parameters)
        return imported_tep_model

    def evaluate_plan(self, plan, tep_scenarios_model_parameters=None):
        # type: (StaticTePlan) -> [dict[powersys.PowerSystemScenario.PowerSystemScenario, float], dict[powersys.PowerSystemScenario.PowerSystemScenario, float], TepScenariosModelParameters]
        params = tep_scenarios_model_parameters
        if params is None:
            params = self.tep_scenarios_model_parameters
        total_costs = collections.OrderedDict()
        investment_cost = plan.get_total_investment_cost()
        # modify all scenarios so as to build lines in the provided plan
        # AFFECTS ALL REFERENCES TO THE PowerSystemTransmissionPlanning INSTANCE!
        self.tep_system.commit_build_lines(plan.candidate_lines_built)
        # simulate operation under each scenario
        scenario_simulation_model = opf.ScenariosOpfModel(self.tep_system.scenarios,
                                                          params.opf_model_params)
        operation_costs = scenario_simulation_model.solve()
        # total costs = operation + investment costs (with multipliers)
        investment_cost *= params.investment_costs_multiplier
        op_multiplier = params.operation_costs_multiplier
        for scenario in self.tep_system.scenarios:
            total_costs[scenario] = op_multiplier * operation_costs[scenario] + investment_cost
        return [scenario_simulation_model, total_costs, operation_costs]

class StaticTePlan(object):
    """A static transmission expansion plan (which lines to build, all simultaneously)"""

    def __init__(self, tep_model, candidate_lines_built=[]):
        # type: (TepScenariosModel, List[CandidateTransmissionLine]) -> None
        self.tep_model = tep_model  # type: TepScenariosModel
        self.candidate_lines_built = candidate_lines_built
        [self.scenario_simulation_model, self.total_costs, self.operation_costs] = self.tep_model.evaluate_plan(self)

    # region plan representation
    @staticmethod
    def from_str_repr(tep_model, str_repr):
        """Builds a transmission expansion plan provided the list of built lines in the plan.
        Used for interaction with the user and loading plans from excel files (string generated by to_str_repr).

        :param tep_model: The TEP model
        :param str_repr: A string with the list of the names of the transmission lines built, e.g. "['TL1_TC1', 'TL10_TC1', 'TL11_TC1']"
        :return: The newly created transmission expansion plan
        """
        # type: (TepScenariosModel, str) -> StaticTePlan
        plan_built_lines = []
        if str_repr != '':
            plan_built_lines_names = (s.strip(" '") for s in str_repr.strip(" '[]").split(','))
            plan_built_lines = [tep_model.tep_system.find_candidate_line_by_name(lname)
                                for lname in plan_built_lines_names]
        plan = StaticTePlan(tep_model, candidate_lines_built=plan_built_lines)
        return plan

    def to_str_repr(self):
        """Generates a string representation of this transmission expansion plan in terms of built lines' names
        The string is the list of names of built lines, for example: "['TL1_TC1', 'TL10_TC1', 'TL11_TC1']" """
        return ','.join(str(l) for l in self.candidate_lines_built)

    def to_str_nodes(self):
        """Generates a string representation of this transmission expansion plan in terms of node pairs
        The string is the list of node pairs of built lines, for example: "[(1,2), (1,15), (23,4)]" """
        return ','.join(l.to_str_nodes() for l in self.candidate_lines_built)

    @staticmethod
    def from_integer_gene(tep_model, candidate_lines_integer_gene):
        """Builds a transmission expansion plan provided the integer gene representation for built lines.
        Used for genetic algorithms.

        :param tep_model: The TEP model
        :param candidate_lines_integer_gene: A list of integers representing the number of transmission lines built in each corridor (first 0-1 for lines in new corridors; then number of new lines in existing corridors 0-1-2-...-N)
        :return: The newly created transmission expansion plan
        """
        # type: (TepScenariosModel, List) -> StaticTePlan
        built_lines = []
        tep_definition = tep_model.tep_system
        for idx, i in enumerate(candidate_lines_integer_gene):
            # up to 'i' lines can be built
            for j in range(i):
                built_lines.append(tep_definition.candidate_lines_groups[idx][j])
        return StaticTePlan(tep_model, built_lines)

    def to_integer_gene(self):
        int_gene = []
        tep_definition = self.tep_model.tep_system
        for idx, lines_group in enumerate(tep_definition.candidate_lines_groups):
            built_lines_count = 0  # number of lines built in this corridor
            for line in lines_group:
                if line in self.candidate_lines_built:
                    built_lines_count += 1
            int_gene.append(built_lines_count)
        return int_gene

    def __str__(self):
        return self.to_str_repr()

    # endregion

    def get_plan_summary(self, name=None):
        # type: () -> OrderedDict
        # Basic info on this plan
        plan_summary = collections.OrderedDict()
        if name is not None:
            plan_summary['Plan Name'] = name
        # self.plan_summary['Kind'] = -- set elsewhere
        plan_summary['Number of Built Lines'] = len(self.candidate_lines_built)
        plan_summary['Built Lines'] = self.to_str_repr()
        plan_summary['Built Lines (nodes)'] = self.to_str_nodes()
        plan_summary['Investment Cost [MMUS$]'] = self.get_total_investment_cost()
        plan_summary['Scaled Investment Cost [MMUS$]'] = plan_summary[
                                                             'Investment Cost [MMUS$]'] * self.tep_model.tep_scenarios_model_parameters.investment_costs_multiplier
        # Operation costs under each scenario
        for scenario in self.tep_model.tep_system.scenarios:
            plan_summary['Operation Costs {0} [MMUS$]'.format(scenario.name)] = self.operation_costs[scenario]
            plan_summary['Scaled Operation Costs {0} [MMUS$]'.format(scenario.name)] = self.operation_costs[
                                                                                scenario] * self.tep_model.tep_scenarios_model_parameters.operation_costs_multiplier
            plan_summary['Total Costs {0} [MMUS$]'.format(scenario.name)] = self.total_costs[scenario]
        return plan_summary

    def get_total_investment_cost(self):
        return sum(line.investment_cost for line in self.candidate_lines_built)

    def dominates(self, other_plan):
        # from https://github.com/DEAP/deap/blob/master/deap/base.py
        not_equal = False
        for self_wvalue, other_wvalue in zip(self.total_costs.values(), other_plan.total_costs.values()):
            if self_wvalue < other_wvalue:
                not_equal = True
            elif self_wvalue > other_wvalue:
                return False
        return not_equal

    def is_nondominated(self, other_plans):
        for other_plan in other_plans:
            if other_plan != self and not self.dominates(other_plan):
                return False
        return True

    def regret(self, optimal_plan, scenario):
        """Calculates the regret of this expansion plan in a given scenario, provided the optimal plan for that scenario

        :param optimal_plan: Optimal plan under the provided scenario
        :param scenario: The scenario for which regret is calculated
        :return:The regret (lost opportunity cost)
        """
        # type: (StaticTePlan, powersys.PowerSystemScenario) -> float
        return self.total_costs[scenario] - optimal_plan.total_costs[scenario]

    def max_regret(self, optimal_plans):
        """Calculates the maximum regret for this plan among all scenarios

        :param optimal_plans: The set of optimal plans for each scenario
        :return: The maximum regret of this transmission expansion plan
        """
        # type: (Dict[powersys.PowerSystemScenario, StaticTePlan]) -> float
        return max(self.regret(optimal_plans[scenario], scenario)
                   for scenario in self.tep_model.tep_system.scenarios)

    def is_equivalent(self, other_plan):
        # type: (StaticTePlan) -> bool
        candidate_lines = self.tep_model.tep_system.candidate_lines
        for lines_group in pwsp.PowerSystemTransmissionPlanning.get_sets_of_equivalent_lines_idx(candidate_lines):
            number_of_built_lines_in_group_self = sum((candidate_lines[i] in self.candidate_lines_built)
                                                      for i in lines_group)
            number_of_built_lines_in_group_other = sum((candidate_lines[i] in other_plan.candidate_lines_built)
                                                       for i in lines_group)
            if number_of_built_lines_in_group_self != number_of_built_lines_in_group_other:
                return False
        return True

class StaticTePlanDetails(object):
    """Details for a given static transmission expansion plan, mainly performance assessment under scenarios"""

    def __init__(self, plan, plan_name="UnnamedPlan"):
        self.plan = plan  # type: StaticTePlan
        # plan summary
        self.plan_name = plan_name
        self.plan_summary = self.plan.get_plan_summary(name=self.plan_name)
        self.plan_df_summary = pd.DataFrame(self.plan_summary, index=[self.plan_name])
        # Details on the operation under each scenario
        self.scenarios_results = opf.ScenariosOpfModelResults(self.plan.scenario_simulation_model)
        for scenario in self.scenarios_results.scenarios:
            scenario_result = self.scenarios_results.scenarios_models_results[scenario]
            self.plan_summary['Relative Load Shedding Costs {0} [%]'.format(scenario.name)] = \
                scenario_result.summary_sol['Relative Load Shedding Costs [%]']
            self.plan_summary['Relative Energy Shed {} [%]'.format(scenario.name)] = \
                scenario_result.summary_sol['Relative Energy Shed [%]']
            self.plan_summary['Congestion Rents / Operation Costs {} [%]'.format(scenario.name)] = \
                scenario_result.summary_sol['Congestion Rents / Operation Costs [%]']
            self.plan_summary['Loss of Load {} [hours]'.format(scenario.name)] = \
                scenario_result.summary_sol['Loss of Load [hours]']

    def to_excel(self, filename):
        writer = pd.ExcelWriter(filename, engine='xlsxwriter')
        self.to_excel_sheets(writer)
        # Close the Pandas Excel writer and output the Excel file.
        writer.save()

    def to_excel_sheets(self, writer):
        sheetname_summary = self.plan_name
        Utils.df_to_excel_sheet_autoformat(self.plan_df_summary, writer, sheetname_summary)
        self.scenarios_results.to_excel_sheets(writer, recursive=True)

class ScenariosTepParetoFrontBuilder(object):
    def __init__(self, tep_model):
        # type: (TepScenariosModel) -> None
        self.tep_model = tep_model
        # Plans in pareto front, set by function 'build_pareto_front'
        self.efficient_alternatives = []  # type: list[StaticTePlan]
        # Optimal plan for each scenario, set by function 'build_pareto_front'
        self.optimal_plans = collections.OrderedDict()
        for scenario in self.tep_model.tep_system.scenarios:
            self.optimal_plans[scenario] = None
        # Summary: these are filled in the function 'summarize',
        # which must be called upon completion of 'build_pareto_front' by implementing classes
        self.start_time = None
        self.elapsed_seconds = None
        self.summary_pareto_front = collections.OrderedDict()
        self.df_summary_pareto_front = None
        self.minimax_cost = float('inf')
        self.minimax_cost_plan = None
        self.minimax_regret = float('inf')
        self.minimax_regret_plan = None
        self.df_efficient_alternatives = None  # set by function 'summarize_efficient_alternatives'

    def execute_build_pareto_front(self):
        self.start_time = time.clock()
        self.build_pareto_front()
        self.elapsed_seconds = time.clock() - self.start_time
        logging.info(("Finished building pareto front (elapsed={}): {} efficient alternatives were found. "
                      "Proceeding to summarize results...").
                     format(str(timedelta(seconds=self.elapsed_seconds)), len(self.efficient_alternatives))
                     )
        self.summarize()

    def build_pareto_front(self):
        # type: () -> List[StaticTePlan]
        pass

    def summarize(self):
        self.summary_pareto_front['Elapsed time'] = str(timedelta(seconds=self.elapsed_seconds))
        self.summary_pareto_front['Number of Efficient Alternatives'] = len(self.efficient_alternatives)
        for scenario in self.tep_model.tep_system.scenarios:
            self.summary_pareto_front['Optimal Plan {}'.format(scenario.name)] = str(self.optimal_plans[scenario])
            self.summary_pareto_front['Optimal Cost {}'.format(scenario.name)] = \
                self.optimal_plans[scenario].total_costs[scenario]
        # Process and summarize efficient alternatives
        self.summarize_efficient_alternatives()
        self.summary_pareto_front['Minimax Cost Plan'] = str(self.minimax_cost_plan)
        self.summary_pareto_front['Minimax Cost'] = self.minimax_cost
        self.summary_pareto_front['Minimax Regret Plan'] = str(self.minimax_regret_plan)
        self.summary_pareto_front['Minimax Regret'] = self.minimax_regret
        self.df_summary_pareto_front = pd.DataFrame(self.summary_pareto_front, index=['Value']).transpose()

    def summarize_efficient_alternatives(self):
        # type: (List[StaticTePlan], List[StaticTePlan], float, bool) -> object
        # TODO save details for each plan in the pareto solver, do not construct details again (it's idiotic)
        list_summaries_alternatives = []
        for idx, alternative in enumerate(self.efficient_alternatives):
            summary = StaticTePlanDetails(alternative, plan_name=idx).plan_summary
            summary['Kind'] = 'Efficient'  # if alternative in efficient_alternatives else 'Dominated'
            # summary = pd.DataFrame(summary, index=['Plan{0}'.format(summary['Plan ID'])])
            summary = pd.DataFrame(summary, index=['Plan{0}'.format(idx)])
            list_summaries_alternatives.append(summary)
            # updates minimax cost
            max_cost_this_alternative = max(alternative.total_costs.values())
            if max_cost_this_alternative < self.minimax_cost:
                self.minimax_cost = max_cost_this_alternative
                self.minimax_cost_plan = alternative
            # updates minimax regret
            max_regret_this_alternative = alternative.max_regret(self.optimal_plans)
            if max_regret_this_alternative < self.minimax_regret:
                self.minimax_regret = max_regret_this_alternative
                self.minimax_regret_plan = alternative
        self.df_efficient_alternatives = pd.concat(list_summaries_alternatives)

    def to_excel(self, excel_filename, sheetname=['ParetoAlternatives', 'ParetoSummary']):
        writer = pd.ExcelWriter(excel_filename, engine='xlsxwriter')
        self.to_excel_sheet(writer, sheetname=sheetname)
        writer.save()

    def to_excel_sheet(self, writer, sheetname=['ParetoAlternatives', 'ParetoSummary']):
        Utils.df_to_excel_sheet_autoformat(self.df_summary_pareto_front, writer, sheetname[1])
        Utils.df_to_excel_sheet_autoformat(self.df_efficient_alternatives, writer, sheetname[0])

    @staticmethod
    def alternatives_to_plot_list(s1, s2, alternatives):
        x = list(alternative.total_costs[s1]
                 for alternative in alternatives)
        y = list(alternative.total_costs[s2]
                 for alternative in alternatives)
        tags = range(len(alternatives))
        return [x, y, tags]

    def build_plot_alternatives(self):
        assert len(self.tep_model.tep_system.scenarios) == 2
        first_scenario = self.tep_model.tep_system.scenarios[0]
        second_scenario = self.tep_model.tep_system.scenarios[1]
        # plot efficient alternatives with frontier
        # efficient_alts = sorted(self.efficient_alternatives, key=lambda a: a.total_costs[first_scenario])
        [x_efficient, y_efficient, tags_efficient] = ScenariosTepParetoFrontBuilder.alternatives_to_plot_list(
            first_scenario, second_scenario,
            self.efficient_alternatives)
        trace_efficient = Scatter(x=x_efficient,
                                  y=y_efficient,
                                  name='Efficient',
                                  mode='lines+markers',
                                  marker=dict(size=10),
                                  text=range(len(self.efficient_alternatives))  # tags_efficient)
                                  )
        self.data_plotly = [trace_efficient]
        # render plot
        show_grid_lines = True
        self.plot_layout = Layout(
            title="Pareto Front for TEP under Scenarios",
            hovermode='closest',
            xaxis=dict(
                title='Total Cost Scenario 1',
                showgrid=show_grid_lines
            ),
            yaxis=dict(
                title='Total Cost Scenario 2',
                showgrid=show_grid_lines
            )
        )

    def plot_alternatives_offline(self, filename):
        plotly.offline.plot({"data": self.data_plotly,
                             "layout": self.plot_layout},
                            filename=filename)

# TODO fix brute force solver
# for enumeration:
# indices=[2,3,2]
# l=map(range,indices)
# list(itertools.product(*l))
class ScenariosTepParetoFrontByBruteForceParams(object):
    def __init__(self, save_extra_alternatives=False,
                 save_alternative_handle=None, save_alternative_handle_params=None,
                 plans_processed_for_reporting=None):
        # type: (bool, object, object, int) -> None
        """Parameters for brute-force construction of pareto front

        :param save_extra_alternatives: True if all alternatives are to be saved, following some filtering criteria
        :param save_alternative_handle: Function handle to filter which alternatives to save
        :param save_alternative_handle_params: Parameters for the filtering function
        :param plans_processed_for_reporting: Number of plans that must be processed before reporting progress
        """
        self.save_extra_alternatives = save_extra_alternatives
        self.save_alternative_handle = save_alternative_handle
        self.save_alternative_handle_params = save_alternative_handle_params
        self.plans_processed_for_reporting = plans_processed_for_reporting

    def save_alternative(self, pareto_brute, alternative):
        """Determines whether the given alternative must be recorded while building the pareto front

        :param pareto_brute: The Brute-force pareto builder instance
        :param alternative: The alternative transmission expansion plan
        :return: True if the alternative should be recorded, false otherwise
        """
        return self.save_alternative_handle(pareto_brute, alternative, self.save_alternative_handle_params)

    @staticmethod
    def save_all_alternatives(pareto_brute, alternative, options=None):
        # type: (ScenariosTepParetoFrontByBruteForce, StaticTePlan, object) -> bool
        return True

    @staticmethod
    def save_random_alternatives(pareto_brute, alternative, options=0.2):
        # type: (ScenariosTepParetoFrontByBruteForce, StaticTePlan, float) -> bool
        return random.random() > options

    @staticmethod
    def save_maxrandom_alternatives(pareto_brute, alternative, options=[0.1, 200]):
        # type: (ScenariosTepParetoFrontByBruteForce, StaticTePlan, float) -> bool
        # r = random.random()
        # b = len(pareto_brute.extra_alternatives) < options[1] and r < options[0]
        # if b:
        #     logging.info("Recording extra plan {} ({} plans currently recorded), r={}".
        #                  format(alternative.get_plan_id(), len(pareto_brute.extra_alternatives), r)
        #                  )
        return len(pareto_brute.extra_alternatives) < options[1] and random.random() < options[0]

    @staticmethod
    def save_alternatives_in_range(pareto_brute, alternative, options=None):
        # type: (ScenariosTepParetoFrontByBruteForce, StaticTePlan, Dict[PowerSystemScenario, List[float]]) -> bool
        assert options is not None
        for scenario in pareto_brute.tep_model.tep_system.scenarios:
            obj_range = options[scenario]
            obj_plan = alternative.total_costs[scenario]
            if min(obj_range) > obj_plan or max(obj_range) < obj_plan:
                return False
        return True

class ScenariosTepParetoFrontByBruteForce(ScenariosTepParetoFrontBuilder):
    def __init__(self, tep_model,
                 pareto_brute_force_params=ScenariosTepParetoFrontByBruteForceParams()):
        # type: (TepScenariosModel, ScenariosTepParetoFrontByBruteForceParams) -> None
        ScenariosTepParetoFrontBuilder.__init__(self, tep_model)
        self.pareto_brute_force_params = pareto_brute_force_params
        if self.pareto_brute_force_params.save_extra_alternatives:
            self.extra_alternatives = []  # type: list[StaticTePlan]
        # enumerate and evaluate all possible alternatives
        self.number_of_maximum_possible_plans = self.tep_model.get_numberof_possible_expansion_plans()
        self.number_of_processed_plans = 0

    def build_pareto_front(self):
        # type: () -> List[StaticTePlan]
        equivalent_lines_idx = pwsp.PowerSystemTransmissionPlanning.get_sets_of_equivalent_lines_idx(
            self.tep_model.tep_system.candidate_lines)
        iterator_plan_ids = (i for i in range(self.number_of_maximum_possible_plans)
                             if StaticTePlan.is_first_unique_by_id(i, equivalent_lines_idx))
        for plan_id in iterator_plan_ids:
            # build and solve plan
            alternative = StaticTePlan.from_id(self.tep_model, plan_id)
            # update set of efficient plans with the newly created plan
            self.update_set_of_efficient_plans(alternative)
            # record plan anyway if all alternatives are being saved
            if self.pareto_brute_force_params.save_extra_alternatives \
                    and self.pareto_brute_force_params.save_alternative(self, alternative):
                self.extra_alternatives.append(alternative)
            # report progress
            self.number_of_processed_plans += 1
            if (self.number_of_processed_plans % self.pareto_brute_force_params.plans_processed_for_reporting) == 0:
                self.elapsed_seconds = time.clock() - self.start_time
                logging.info("Processed {0} alternatives (elapsed: {3}; current ID={1} / {2})...".
                             format(self.number_of_processed_plans,
                                    plan_id, self.number_of_maximum_possible_plans,
                                    str(timedelta(seconds=self.elapsed_seconds))
                                    )
                             )
        return self.efficient_alternatives

    def update_set_of_efficient_plans(self, alternative):
        dominated_to_remove = []
        alternative_is_efficient = True
        for idx, other_alt in enumerate(self.efficient_alternatives):
            if other_alt.dominates(alternative):
                alternative_is_efficient = False
                break
            elif alternative.dominates(other_alt):
                dominated_to_remove.append(other_alt)
        self.efficient_alternatives = [a for a in self.efficient_alternatives
                                       if a not in dominated_to_remove]
        if alternative_is_efficient:
            self.efficient_alternatives.append(alternative)
            # update best plan for each scenario
            for scenario in self.tep_model.tep_system.scenarios:
                if self.optimal_plans[scenario] is None \
                        or alternative.total_costs[scenario] < self.optimal_plans[scenario].total_costs[scenario]:
                    self.optimal_plans[scenario] = alternative

    def get_dominated_alternatives(self):
        return (alt for alt in self.extra_alternatives if alt not in self.efficient_alternatives)

    def summarize(self):
        ScenariosTepParetoFrontBuilder.summarize(self)
        # Summarize extra alternatives
        self.df_extra_alternatives = None
        if self.pareto_brute_force_params.save_extra_alternatives:
            list_summaries_extra_alternatives = []
            logging.info("Proceeding to summarize {} extra alternatives".format(len(self.extra_alternatives)))
            startsumm = time.clock()
            for idx, alternative in enumerate(self.extra_alternatives):
                summary = StaticTePlanDetails(alternative).plan_summary
                summary['Kind'] = 'Efficient' if alternative in self.efficient_alternatives else 'Dominated'
                summary = pd.DataFrame(summary, index=['Plan{0}'.format(summary['Plan ID'])])
                list_summaries_extra_alternatives.append(summary)
                if idx % 100 == 0:
                    elapsed_secs = time.clock() - startsumm
                    logging.info("Summarized {} / {} extra alternatives (elapsed: {})".
                                 format(idx, len(self.extra_alternatives), timedelta(seconds=elapsed_secs))
                                 )
            self.df_extra_alternatives = pd.concat(list_summaries_extra_alternatives)

    def to_excel(self, excel_filename, sheetname=['ParetoAlternatives', 'ParetoSummary', 'DominatedAlternatives']):
        ScenariosTepParetoFrontBuilder.to_excel(self, excel_filename, sheetname)

    def to_excel_sheet(self, writer, sheetname=['ParetoAlternatives', 'ParetoSummary', 'DominatedAlternatives']):
        ScenariosTepParetoFrontBuilder.to_excel_sheet(self, writer, sheetname[0:2])
        if self.df_extra_alternatives is not None:
            Utils.df_to_excel_sheet_autoformat(self.df_extra_alternatives, writer, sheetname[2])

    def build_plot_alternatives(self):
        ScenariosTepParetoFrontBuilder.build_plot_alternatives(self)
        # plot dominated alternatives, if all alternatives were recorded
        if self.pareto_brute_force_params.save_extra_alternatives:
            first_scenario = self.tep_model.tep_system.scenarios[0]
            second_scenario = self.tep_model.tep_system.scenarios[1]
            dominated_alternatives = list(self.get_dominated_alternatives())
            [x_dominated, y_dominated, tags_dominated] = ScenariosTepParetoFrontBuilder.alternatives_to_plot_list(
                first_scenario, second_scenario, dominated_alternatives)
            trace_dominated = Scatter(x=x_dominated,
                                      y=y_dominated,
                                      mode='markers',
                                      name='Dominated',
                                      marker=dict(size=3, color='rgb(200,200,200)'),
                                      text=tags_dominated)
            self.data_plotly.append(trace_dominated)

class TepModelOneState(opf.OpfModel):
    """A MILP-based deterministic TEP model for a particular state of a power system.

    Inheriting from opf.OpfModel allows using the summary class opf.OpfModelResults"""

    def __init__(self, state, tep_system,
                 line_investment_vars=None,
                 tep_model_params=TepModelParameters(),
                 model=pyo.ConcreteModel('UnnamedTepOpfModel')):
        opf.OpfModel.__init__(self,
                              state,
                              opf_model_params=tep_model_params.opf_model_params,
                              model=model)
        self.tep_system = tep_system  # type: pwsp.PowerSystemTransmissionPlanning
        self.tep_model_params = tep_model_params
        # Model variables: line investment is the only new variable w/r to OPF
        self.line_investment_vars = line_investment_vars
        # Model constraints: power flow in candidate lines are the only two new constraints w/r to OPF
        self.max_power_flow_candidates = {}
        self.dc_power_flow_candidates = {}

    def create_grb_vars(self):
        super(TepModelOneState, self).create_grb_vars()
        self.create_grb_vars_transmission_investment()

    def create_grb_vars_transmission_investment(self):
        if self.line_investment_vars is None:
            # Create line investment variables if they weren't provided
            self.line_investment_vars = {}
            for candidate_line in self.candidate_lines_flat_list:
                self.line_investment_vars[candidate_line] = \
                    self.model.addVar(
                        obj=candidate_line.investment_cost * self.tep_model_params.investment_costs_multiplier,
                        vtype=pyo.Binary,
                        name='y_{}'.format(candidate_line.transmission_line.name)
                    )
            self.model.update()  # Update model to integrate new variables

    def create_grb_constraints(self):
        super(TepModelOneState, self).create_grb_constraints()
        self.create_grb_constraints_dc_power_flow_disjunctive()

    def create_grb_constraints_dc_power_flow(self, transmission_lines_states=None):
        """Creates DC power flow constraints in terms of bus angles

        :param transmission_lines_states: A subset of the transmission lines for which the constraints will be generated. If None, the constraints will be generated for all transmission lines states in the model
        :return: None
        """
        if transmission_lines_states is None:
            transmission_lines_states = (line_state for line_state in self.state.transmission_lines_states
                                         if not
                                         self.tep_system.transmission_line_is_candidate(line_state.transmission_line))
        super(TepModelOneState, self).create_grb_constraints_dc_power_flow(
            transmission_lines_states=transmission_lines_states)

    def create_grb_constraints_dc_power_flow_disjunctive(self, transmission_lines_states=None):
        """Creates disjunctive DC power flow constraints in terms of bus angles

        :param transmission_lines_states: A subset of the transmission lines for which the constraints will be generated. If None, the constraints will be generated for all transmission lines states in the model
        :return: None
        """
        # TODO Angular difference among bus pairs is not enforced for these new lines
        if transmission_lines_states is None:
            transmission_lines_states = (line_state for line_state in self.state.transmission_lines_states
                                         if
                                         self.tep_system.transmission_line_is_candidate(line_state.transmission_line))
        for line_state in transmission_lines_states:
            bus_angle_from = self.bus_angle[line_state.node_from_state]
            bus_angle_to = self.bus_angle[line_state.node_to_state]
            # unavailable transmission lines are deactivated but included in the model
            susceptance = line_state.isavailable * line_state.transmission_line.susceptance * self.opf_model_params.base_mva
            lhs = self.power_flow[line_state] - susceptance * (bus_angle_from - bus_angle_to)
            candidate_line_investment_var = next(line_var for key, line_var in self.line_investment_vars.iteritems()
                                                 if key.transmission_line == line_state.transmission_line)
            rhs = self.tep_model_params.disjunctive_parameter * (1 - candidate_line_investment_var)
            self.dc_power_flow_candidates[line_state] = \
                self.create_grb_abs_constraint_pair(lhs, rhs, name='DCFlowDisj{}'.format(line_state))
            # max power flow binary formulation
            self.max_power_flow_candidates[line_state] = \
                self.create_grb_abs_constraint_pair(
                    self.power_flow[line_state],
                    line_state.transmission_line.thermal_capacity * candidate_line_investment_var,
                    name='MaxFlow{}'.format(line_state)
                )

    def get_investment_vars_value(self):
        return self.get_grb_vars_solution(self.line_investment_vars)

class TepModelOneScenario(opf.ScenarioOpfModel):
    """A MILP-based deterministic TEP model for a particular scenario of a power system.
    A scenario is understood as a static collection of power system states
    (for example, hourly states for a full year under some set of assumptions)

    Inheriting from opf.ScenarioOpfModel allows using the summary class opf.ScenarioOpfModelResults"""

    def __init__(self, scenario,
                 tep_system,
                 line_investment_vars=None,
                 tep_model_params=TepModelParameters(),
                 model=pyo.ConcreteModel('UnnamedTepOneScenarioModel')):
        # type: (powersys.PowerSystemScenario.PowerSystemScenario, OpfModelParameters, gurobipy.Model) -> None
        opf.ScenarioOpfModel.__init__(self, scenario,
                                      opf_model_params=tep_model_params.opf_model_params,
                                      model=model)
        self.tep_system = tep_system
        self.tep_model_params = tep_model_params
        # Line investment variables
        self.line_investment_vars = line_investment_vars

    def build_model(self):
        if self.line_investment_vars is None:
            # Create line investment variables if they weren't provided
            self.line_investment_vars = {}
            for candidate_line in self.tep_system.candidate_lines_flat_list:
                self.line_investment_vars[candidate_line] = \
                    self.model.addVar(
                        obj=candidate_line.investment_cost * self.tep_model_params.investment_costs_multiplier,
                        vtype=pyo.Binary,
                        name='y_{}'.format(candidate_line.transmission_line.name)
                    )
            self.model.update()  # Update model to integrate new variables
        super(TepModelOneScenario, self).build_model()

    def build_opf_model_one_state(self, state):
        """Overrides base method in order to minimize code modifications
        (this method will be called by opf.ScenarioOpfModel.__init__)"""
        tep_model = TepModelOneState(state, self.tep_system,
                                     line_investment_vars=self.line_investment_vars,
                                     tep_model_params=self.tep_model_params,
                                     model=self.model)
        tep_model.build_model()
        return tep_model

    def get_optimal_plan(self, tep_model):
        investment_vars_value = self.get_grb_vars_solution(self.line_investment_vars)
        built_lines = list(candidate_line for candidate_line in self.tep_system.candidate_lines_flat_list
                           if investment_vars_value[candidate_line])
        plan = StaticTePlan(tep_model, built_lines)
        return plan


text:
'use strict';

exports.__esModule = true;

var _ActorAppDispatcher = require('../dispatcher/ActorAppDispatcher');

var _ActorAppConstants = require('../constants/ActorAppConstants');

var _ActorClient = require('../utils/ActorClient');

var _ActorClient2 = _interopRequireDefault(_ActorClient);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var DialogInfoActionCreators = {
  changeNotificationsEnabled: function changeNotificationsEnabled(peer, isEnabled) {
    _ActorClient2.default.changeNotificationsEnabled(peer, isEnabled);
    (0, _ActorAppDispatcher.dispatch)(_ActorAppConstants.ActionTypes.NOTIFICATION_CHANGE, { peer: peer, isEnabled: isEnabled });
  }
};

exports.default = DialogInfoActionCreators;
//# sourceMappingURL=NotificationsActionCreators.js.map

redpajama_set_name: RedPajamaGithub


text:
namespace RangeIt.Tests.Iterators.Adapters.Const
{
    using FluentAssertions;
    using RangeIt.Iterators;
    using System.Collections.Generic;
    using Traits;
    using Xunit;

    [Category("Iterators.Adapters.Const.DictionaryConstIteratorAdapter<T, U>")]
    public class DictionaryConstIteratorAdapter_2_Tests
    {
        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_Begin_Ctor_WithEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>();
            ConstIterator<string, int> it = dictionary.ConstBegin();

            it.Should().NotBeNull();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_End_Ctor_WithEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>();
            ConstIterator<string, int> it = dictionary.ConstEnd();

            it.Should().NotBeNull();
            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_Begin_Iteration_WithEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>();
            ConstIterator<string, int> it = dictionary.ConstBegin();

            it.Next().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            it.Previous().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_End_Iteration_WithEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>();
            ConstIterator<string, int> it = dictionary.ConstEnd();

            it.Next().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            it.Previous().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_Begin_Ctor_WithNotEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstBegin();

            it.Should().NotBeNull();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_End_Ctor_WithNotEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstEnd();

            it.Should().NotBeNull();
            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_Begin_Iteration_WithNotEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstBegin();

            // 1. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(0);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("one");
            it.Value.Should().Be(1);

            // 1. back iteration
            it.Previous().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            // 1. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(0);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("one");
            it.Value.Should().Be(1);

            // 2. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(1);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("two");
            it.Value.Should().Be(2);

            // 3. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(2);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("three");
            it.Value.Should().Be(3);

            // 4. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(3);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("four");
            it.Value.Should().Be(4);

            // 5. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(4);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("five");
            it.Value.Should().Be(5);

            // 6. iteration
            it.Next().Should().BeFalse();
            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(dictionary.Count);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            // 1. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(4);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("five");
            it.Value.Should().Be(5);

            // 2. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(3);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("four");
            it.Value.Should().Be(4);

            // 3. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(2);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("three");
            it.Value.Should().Be(3);

            // 4. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(1);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("two");
            it.Value.Should().Be(2);

            // 5. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(0);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("one");
            it.Value.Should().Be(1);

            // 6. back iteration
            it.Previous().Should().BeFalse();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_End_Iteration_WithNotEmptyDictionary()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstEnd();

            // 1. iteration
            it.Next().Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            // 1. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(4);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("five");
            it.Value.Should().Be(5);

            // 2. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(3);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("four");
            it.Value.Should().Be(4);

            // 3. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(2);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("three");
            it.Value.Should().Be(3);

            // 4. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(1);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("two");
            it.Value.Should().Be(2);

            // 5. back iteration
            it.Previous().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(0);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("one");
            it.Value.Should().Be(1);

            // 6. back iteration
            it.Previous().Should().BeFalse();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(-1);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);

            // 1. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(0);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("one");
            it.Value.Should().Be(1);

            // 2. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(1);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("two");
            it.Value.Should().Be(2);

            // 3. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(2);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("three");
            it.Value.Should().Be(3);

            // 4. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(3);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("four");
            it.Value.Should().Be(4);

            // 5. iteration
            it.Next().Should().BeTrue();
            it.Index.Should().Be(4);
            it.Current.Should().NotBeNull();
            it.Key.Should().NotBeNull().And.Be("five");
            it.Value.Should().Be(5);

            // 6. iteration
            it.Next().Should().BeFalse();
            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(dictionary.Count);
            it.Current.Should().NotBeNull();
            it.Key.Should().BeNull();
            it.Value.Should().Be(0);
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_Begin_IsValid()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstBegin();

            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(-1);
            it.IsValid.Should().BeFalse();

            // 1. iteration
            it.Next().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(0);
            it.IsValid.Should().BeTrue();

            // 2. iteration
            it.Next().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(1);
            it.IsValid.Should().BeTrue();

            // 3. iteration
            it.Next().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(2);
            it.IsValid.Should().BeTrue();

            // 4. iteration
            it.Next().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(3);
            it.IsValid.Should().BeTrue();

            // 5. iteration
            it.Next().Should().BeTrue();
            it.IsEndIterator.Should().BeFalse();
            it.Index.Should().Be(4);
            it.IsValid.Should().BeTrue();

            // 6. iteration
            it.Next().Should().BeFalse();
            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(5);
            it.IsValid.Should().BeFalse();
        }

        [Fact]
        public void Test_DictionaryConstIteratorAdapter_2_End_IsValid()
        {
            var dictionary = new Dictionary<string, int>
            {
                ["one"] = 1,
                ["two"] = 2,
                ["three"] = 3,
                ["four"] = 4,
                ["five"] = 5
            };

            ConstIterator<string, int> it = dictionary.ConstEnd();

            it.IsEndIterator.Should().BeTrue();
            it.Index.Should().Be(-1);
            it.IsValid.Should().BeFalse();
        }
    }
}


text:
#pragma once
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
	struct Interval {
		int start;
		int end;
		Interval() : start(0), end(0) {}
		Interval(int s, int e) : start(s), end(e) {}
	};

	vector<Interval> merge(vector<Interval>& intervals) {
		// sort intervals by start
		sort(intervals.begin(), intervals.end(), [](const Interval& lhs, const Interval& rhs) {
			return lhs.start < rhs.start;
		});

		int index = 0;
		while (index < int(intervals.size()) - 1) {    // size() returns unsigned zero if vector is empty
			if (intervals[index].end >= intervals[index + 1].start) {
				intervals[index].end < intervals[index + 1].end
					? intervals[index].end = intervals[index + 1].end
					: true;
				intervals.erase(intervals.begin() + index + 1);
			}
			else {
				index++;
			}
		}

		return intervals;
	}

	vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
		if (intervals.size() == 0) {
			intervals.push_back(newInterval);
		}
		for (int i = 0; i < intervals.size(); i++) {
			if (intervals[i].start >= newInterval.start) {
				intervals.insert(intervals.begin() + i, newInterval);
				break;
			}
			if (i == intervals.size() - 1) {
				intervals.push_back(newInterval);
				break;
			}
		}
		return merge(intervals);
	}

	void call() {
		/*vector<Interval> intervals{
			Interval(1, 2), Interval(3, 5), Interval(6, 7), Interval(8, 10), Interval(12, 16)
		};*/
		vector<Interval> intervals{
			Interval(1, 5)
		};
		// vector<Interval> intervals{};
		auto result = insert(intervals, Interval(2, 7));
	}
};


text:
package com.altova.text.edi;

import java.io.IOException;
import com.altova.text.ITextNode;
import com.altova.text.Generator;

public class Composite extends StructureItem {
	public Composite (String name, Particle[] children) {
		super (name, ITextNode.Composite, children);
	}

	public boolean read (Parser.Context context) {
		context.getScanner().moveToNextSignificantChar();
		if (context.getScanner().isAtAnySeparator() &&
			!context.getScanner().isAtSeparator(ServiceChars.ComponentSeparator))
				return false;

		context.mParser.resetComponentDataElementPos(); // reset composite data element pos to 0

		Generator generator = context.getGenerator();
		generator.enterElement (context.getParticle().getName(), mNodeClass);
		if (!readChildren (context, ServiceChars.ComponentSeparator))
		{
			generator.leaveElement (context.getParticle().getName());
			return false;
		}
		generator.leaveElement (context.getParticle().getName());
		return true;
	}

	public void write (Writer writer, ITextNode node, Particle particle)  throws IOException {
		writeChildren (writer, node, ServiceChars.ComponentSeparator);
	}
}


text:
namespace SmashForge
{
    partial class UiPreview
    {
        /// <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()
        {
            this.chr_00_renderer = new OpenTK.GLControl();
            this.chr_11_renderer = new OpenTK.GLControl();
            this.chr_13_renderer = new OpenTK.GLControl();
            this.stock_90_renderer = new OpenTK.GLControl();
            this.SuspendLayout();
            //
            // chr_00_renderer
            //
            this.chr_00_renderer.BackColor = System.Drawing.Color.Black;
            this.chr_00_renderer.Location = new System.Drawing.Point(12, 82);
            this.chr_00_renderer.Name = "chr_00_renderer";
            this.chr_00_renderer.Size = new System.Drawing.Size(128, 128);
            this.chr_00_renderer.TabIndex = 0;
            this.chr_00_renderer.VSync = false;
            this.chr_00_renderer.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drag_Enter);
            this.chr_00_renderer.Paint += new System.Windows.Forms.PaintEventHandler(this.chr_00_renderer_Paint);
            //
            // chr_11_renderer
            //
            this.chr_11_renderer.BackColor = System.Drawing.Color.Black;
            this.chr_11_renderer.Location = new System.Drawing.Point(12, 216);
            this.chr_11_renderer.Name = "chr_11_renderer";
            this.chr_11_renderer.Size = new System.Drawing.Size(192, 192);
            this.chr_11_renderer.TabIndex = 1;
            this.chr_11_renderer.VSync = false;
            this.chr_11_renderer.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drag_Enter);
            this.chr_11_renderer.Paint += new System.Windows.Forms.PaintEventHandler(this.chr_11_renderer_Paint);
            //
            // chr_13_renderer
            //
            this.chr_13_renderer.BackColor = System.Drawing.Color.Black;
            this.chr_13_renderer.Location = new System.Drawing.Point(12, 414);
            this.chr_13_renderer.Name = "chr_13_renderer";
            this.chr_13_renderer.Size = new System.Drawing.Size(224, 224);
            this.chr_13_renderer.TabIndex = 2;
            this.chr_13_renderer.VSync = false;
            this.chr_13_renderer.DragDrop += new System.Windows.Forms.DragEventHandler(this.chr_13_renderer_DragDrop);
            this.chr_13_renderer.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drag_Enter);
            this.chr_13_renderer.Paint += new System.Windows.Forms.PaintEventHandler(this.chr_13_renderer_Paint);
            //
            // stock_90_renderer
            //
            this.stock_90_renderer.BackColor = System.Drawing.Color.Black;
            this.stock_90_renderer.Location = new System.Drawing.Point(12, 12);
            this.stock_90_renderer.Name = "stock_90_renderer";
            this.stock_90_renderer.Size = new System.Drawing.Size(64, 64);
            this.stock_90_renderer.TabIndex = 3;
            this.stock_90_renderer.VSync = false;
            this.stock_90_renderer.DragEnter += new System.Windows.Forms.DragEventHandler(this.Drag_Enter);
            this.stock_90_renderer.Paint += new System.Windows.Forms.PaintEventHandler(this.stock_90_renderer_Paint);
            //
            // UIPreview
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(254, 647);
            this.Controls.Add(this.stock_90_renderer);
            this.Controls.Add(this.chr_13_renderer);
            this.Controls.Add(this.chr_11_renderer);
            this.Controls.Add(this.chr_00_renderer);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "UiPreview";
            this.Text = "UIPreview";
            this.ResumeLayout(false);

        }

        #endregion

        private OpenTK.GLControl chr_00_renderer;
        private OpenTK.GLControl chr_11_renderer;
        private OpenTK.GLControl chr_13_renderer;
        private OpenTK.GLControl stock_90_renderer;
    }
}


text:
//
// @author raver119@gmail.com
//

#ifndef LIBND4J_SPECIAL_RANDOM_OPS_H
#define LIBND4J_SPECIAL_RANDOM_OPS_H

#include <ops/random_ops.h>

namespace randomOps {

    template<typename T>
    class Choice {
    public:

        method_idx
        method_X
        method_XY

        static const bool requiresSpecial = true;

#ifdef __CUDACC__
        __device__ static inline void specialOpCuda(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            /**
             * X holds data,
             * Y holds probabilities
             * Z will hold results
             */

            // TODO: we probably might want to skip this sum, and state that probabilities array should be real probabilities, i.e. should sum to 1.0
            //T probSum = extraArguments[0];

            __shared__ Nd4jIndex xLength;
            __shared__ Nd4jIndex yLength;
            __shared__ Nd4jIndex zLength;

            __shared__ int xEWS;
            __shared__ int yEWS;
            __shared__ int zEWS;

            __shared__ nd4j::random::RandomBuffer *buffer;
            __shared__ unsigned char *cB;
            __shared__ unsigned char *dB;
            __shared__ nd4j::random::RandomBuffer *devBuffer;
            if (threadIdx.x == 0) {
                extern __shared__ unsigned char shmem[];
                buffer = (nd4j::random::RandomBuffer *) shmem;
                cB = shmem;
                devBuffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);
                dB = reinterpret_cast<unsigned char *> (state);

                xLength = shape::length(xShapeBuffer);
                yLength = shape::length(yShapeBuffer);
                zLength = shape::length(zShapeBuffer);

                xEWS = shape::elementWiseStride(xShapeBuffer);
                yEWS = shape::elementWiseStride(yShapeBuffer);
                zEWS = shape::elementWiseStride(zShapeBuffer);
            }
            __syncthreads();

            // using this loop instead of memcpy
            for (int e = threadIdx.x; e < sizeof(nd4j::random::RandomBuffer); e+= blockDim.x) {
                cB[e] = dB[e];
            }
            __syncthreads();

            int tid = blockIdx.x * blockDim.x + threadIdx.x;

            if (zEWS >= 1 && xEWS >= 1 && yEWS >= 1) {
                for (Nd4jIndex e = tid; e < zLength; e+=blockDim.x * gridDim.x) {
                    T prob = buffer->relativeT<T>(e);
                    T cumProb = (T) 0.0f;
                    for (Nd4jIndex f = 0; f < yLength; f++) {
                        T relProb = y[f * yEWS];
                        cumProb += relProb;

                        if (prob <= cumProb || f == yLength - 1) {
                            z[e * zEWS] = x[f * xEWS];
                            f += yLength;
                        }
                        __syncthreads();
                    }
                    __syncthreads();
                }
            } else {
                int xCoord[MAX_RANK];
                int yCoord[MAX_RANK];
                int zCoord[MAX_RANK];

                __shared__ int xRank;
                __shared__ int yRank;
                __shared__ int zRank;

                __shared__ int *xShape;
                __shared__ int *yShape;
                __shared__ int *zShape;

                __shared__ int *xStride;
                __shared__ int *yStride;
                __shared__ int *zStride;

                __shared__ int xOffset;
                __shared__ int yOffset;
                __shared__ int zOffset;

                if (threadIdx.x == 0) {
                    xRank = shape::rank(xShapeBuffer);
                    yRank = shape::rank(yShapeBuffer);
                    zRank = shape::rank(zShapeBuffer);

                    xShape = shape::shapeOf(xShapeBuffer);
                    yShape = shape::shapeOf(yShapeBuffer);
                    zShape = shape::shapeOf(zShapeBuffer);

                    xStride = shape::stride(xShapeBuffer);
                    yStride = shape::stride(yShapeBuffer);
                    zStride = shape::stride(zShapeBuffer);

                    xOffset = shape::offset(xShapeBuffer);
                    yOffset = shape::offset(yShapeBuffer);
                    zOffset = shape::offset(zShapeBuffer);
                }
                __syncthreads();

                for (Nd4jIndex i = tid; i < zLength; i+=blockDim.x * gridDim.x) {
                    shape::ind2sub(zRank, zShape, i, zCoord);

                    Nd4jIndex zOffset2 = shape::getOffset(zOffset, zShape, zStride, zCoord, zRank);

                    T prob = buffer->relativeT<T>(i);
                    T cumProb = (T) 0.0f;
                    for (Nd4jIndex f = 0; f < yLength; f++) {
                        shape::ind2sub(yRank, yShape, i, yCoord);
                        Nd4jIndex yOffset2 = shape::getOffset(yOffset, yShape, yStride, yCoord, yRank);

                        T relProb = y[yOffset2];
                        cumProb += relProb;

                        if (prob <= cumProb || f == yLength - 1) {
                            shape::ind2sub(xRank, xShape, f, xCoord);
                            Nd4jIndex xOffset2 = shape::getOffset(xOffset, xShape, xStride, xCoord, xRank);

                            z[zOffset2] = x[xOffset2];
                            f += yLength;
                        }
                        __syncthreads();
                    }
                    __syncthreads();
                }
            }

            __syncthreads();
            devBuffer->rewind(zLength);
        }
#endif

        static inline void specialOp(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            /**
             * X holds data,
             * Y holds probabilities
             * Z will hold results
             */

            nd4j::random::RandomBuffer *buffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);

            // TODO: we probably might want to skip this sum, and state that probabilities array should be real probabilities, i.e. should sum to 1.0
            //T probSum = extraArguments[0];

            Nd4jIndex yLength = shape::length(yShapeBuffer);
            Nd4jIndex zLength = shape::length(zShapeBuffer);

            int xEWS = shape::elementWiseStride(xShapeBuffer);
            int yEWS = shape::elementWiseStride(yShapeBuffer);
            int zEWS = shape::elementWiseStride(zShapeBuffer);

            int elementsPerThread = zLength / TAD_THRESHOLD;
            int _threads = nd4j::math::nd4j_max<int>(1, elementsPerThread);
            _threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());

            if (zEWS >= 1 && xEWS >= 1 && yEWS >= 1) {
#pragma omp parallel for num_threads(_threads) if (_threads > 1) schedule(guided)
                for (Nd4jIndex e = 0; e < zLength; e++) {
                    T prob = buffer->relativeT<T>(e);
                    T cumProb = (T) 0.0f;
                    for (Nd4jIndex f = 0; f < yLength; f++) {
                        T relProb = y[f * yEWS];
                        cumProb += relProb;

                        if (prob <= cumProb || f == yLength - 1) {
                            z[e * zEWS] = x[f * xEWS];
                            f += yLength;
                        }
                    }
                }
            } else {
                int xCoord[MAX_RANK];
                int yCoord[MAX_RANK];
                int zCoord[MAX_RANK];

                int xRank = shape::rank(xShapeBuffer);
                int yRank = shape::rank(yShapeBuffer);
                int zRank = shape::rank(zShapeBuffer);

                int *xShape = shape::shapeOf(xShapeBuffer);
                int *yShape = shape::shapeOf(yShapeBuffer);
                int *zShape = shape::shapeOf(zShapeBuffer);

                int *xStride = shape::stride(xShapeBuffer);
                int *yStride = shape::stride(yShapeBuffer);
                int *zStride = shape::stride(zShapeBuffer);

                int xOffset = shape::offset(xShapeBuffer);
                int yOffset = shape::offset(yShapeBuffer);
                int zOffset = shape::offset(zShapeBuffer);

#pragma omp parallel for num_threads(_threads) if (_threads > 1) schedule(guided)
                for (Nd4jIndex i = 0; i < zLength; i++) {
                    shape::ind2sub(zRank, zShape, i, zCoord);

                    Nd4jIndex zOffset2 = shape::getOffset(zOffset, zShape, zStride, zCoord, zRank);

                    T prob = buffer->relativeT<T>(i);
                    T cumProb = (T) 0.0f;
                    for (Nd4jIndex f = 0; f < yLength; f++) {
                        shape::ind2sub(yRank, yShape, i, yCoord);
                        Nd4jIndex yOffset2 = shape::getOffset(yOffset, yShape, yStride, yCoord, yRank);

                        T relProb = y[yOffset2];
                        cumProb += relProb;

                        if (prob <= cumProb || f == yLength - 1) {
                            shape::ind2sub(xRank, xShape, f, xCoord);
                            Nd4jIndex xOffset2 = shape::getOffset(xOffset, xShape, xStride, xCoord, xRank);

                            z[zOffset2] = x[xOffset2];
                            f += yLength;
                        }
                    }
                }
            }

            // update rng state
            buffer->rewindH(zLength);
        }
    };

    /**
    * This Op produces random values within specified boundaries. Distribuion is Gaussian
    */
    template<typename T>
    class GaussianDistribution {
    public:

        method_XY
        method_X
        method_idx

        static const bool requiresSpecial = true;

#ifdef __CUDACC__
        __device__ static inline void specialOpCuda(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            // FIXME: we use cuRAND for this op, due to undesired code branching
            __shared__ T epsilon;
            __shared__ T two_pi;

            __shared__ Nd4jIndex zLength;
            __shared__ int zEWS;
            __shared__ int yEWS;
            __shared__ T mean;
            __shared__ T stddev;
            __shared__ int step;

            __shared__ T *tZ;

            __shared__ nd4j::random::RandomBuffer *buffer;
            __shared__ unsigned char *cB;
            __shared__ unsigned char *dB;
            __shared__ nd4j::random::RandomBuffer *devBuffer;

            if (threadIdx.x == 0) {
                extern __shared__ unsigned char shmem[];
                buffer = (nd4j::random::RandomBuffer *) shmem;
                cB = shmem;
                devBuffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);
                dB = reinterpret_cast<unsigned char *> (state);

                tZ = (T *) (shmem + sizeof(nd4j::random::RandomBuffer));

                zLength = shape::length(zShapeBuffer);
                zEWS = shape::elementWiseStride(zShapeBuffer);
                yEWS = shape::elementWiseStride(yShapeBuffer);

                epsilon = (T) 1e-5;
                two_pi = (T) 2.0 * (T) 3.14159265358979323846;

                mean = extraArguments[0];
                stddev = extraArguments[1];

                step = (blockDim.x * gridDim.x);
            }
            __syncthreads();

            // using this loop instead of memcpy
            for (int e = threadIdx.x; e < sizeof(nd4j::random::RandomBuffer); e+= blockDim.x) {
                cB[e] = dB[e];
            }
            __syncthreads();

            int tid = blockIdx.x * blockDim.x + threadIdx.x;

            for (Nd4jIndex e = tid; e < zLength; e += step) {
                // we need to get random values

                tZ[threadIdx.x] = buffer->relativeT<T>(e, epsilon, (T) 1.0f);

                // fix for "next rng value"
                if (e + 1 >= zLength && e % 2 == 0) {
                    tZ[threadIdx.x+1] = buffer->relativeT<T>(e+1, epsilon, (T) 1.0f);
                }

                T realMean = y == z ? mean : y[e * yEWS];

                __syncthreads();

                if (e % 2 == 0)
                    z[e *zEWS] =  (nd4j::math::nd4j_sqrt<T>((T) -2.0f * nd4j::math::nd4j_log<T>(tZ[threadIdx.x])) * nd4j::math::nd4j_cos<T>(two_pi * tZ[threadIdx.x+1])) * stddev + realMean;
                else
                    z[e *zEWS] =  (nd4j::math::nd4j_sqrt<T>((T) -2.0f * nd4j::math::nd4j_log<T>(tZ[threadIdx.x-1])) * nd4j::math::nd4j_sin<T>(two_pi * tZ[threadIdx.x])) * stddev + realMean;
                __syncthreads();
            }

            __syncthreads();
            devBuffer->rewind(zLength);
        }
#endif

        static inline void
        specialOp(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            const T two_pi = (T) 2.0 * 3.14159265358979323846;

            Nd4jIndex zLength = shape::length(zShapeBuffer);
            int yEWS = shape::elementWiseStride(yShapeBuffer);
            int zEWS = shape::elementWiseStride(zShapeBuffer);

            int elementsPerThread = zLength / TAD_THRESHOLD;
            int _threads = nd4j::math::nd4j_max<int>(1, elementsPerThread);
            _threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());

            int span = (zLength / _threads) + 8;

            nd4j::random::RandomBuffer *buffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);

            T mean = extraArguments[0];
            T stddev = extraArguments[1];

#pragma omp parallel num_threads(_threads) if (_threads > 1) proc_bind(spread)
            {
                int tid = omp_get_thread_num();
                Nd4jIndex start = span * tid;
                Nd4jIndex end = span * (tid + 1);
                if (end > zLength) end = zLength;

                T z0, z1;
                T u0, u1;

                bool generated = false;

                for (Nd4jIndex e = start; e < end; e++) {
                    if (!generated) {
                        /*
                         * Since box-muller transform expects non-zero u0 value, we'll just use rng with boundaries
                         */
                        u0 = buffer->relativeT<T>(e, (T) 1e-5f, (T) 1.0f);
                        u1 = buffer->relativeT<T>((e + 1), (T) 1e-5f, (T) 1.0f);

                        z0 = nd4j::math::nd4j_sqrt<T>((T) -2.0f * nd4j::math::nd4j_log<T>(u0)) * nd4j::math::nd4j_cos<T>(two_pi * u1);
                        z1 = nd4j::math::nd4j_sqrt<T>((T) -2.0f * nd4j::math::nd4j_log<T>(u0)) * nd4j::math::nd4j_sin<T>(two_pi * u1);

                        generated = true;

                        T realMean = y == z ? mean : y[e * yEWS];

                        z[e * zEWS] = z0 * stddev + realMean;
                    } else {
                        T realMean = y == z ? mean : y[e * yEWS];

                        z[e * zEWS] = z1 * stddev + realMean;

                        generated = false;
                    }
                }
            }

            // update rng state
            buffer->rewindH(zLength);

        }
    };

    /**
    * This Op produces random values within [0..N], Distribuion is binomial
    */
    template<typename T>
    class BinomialDistribution {
    public:

        method_XY
        method_X
        method_idx

        static const bool requiresSpecial = true;

#ifdef __CUDACC__
        __device__ static inline void specialOpCuda(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            int trials = (int) extraArguments[0];
            T prob = extraArguments[1];

            __shared__ Nd4jIndex zLength;
            __shared__ int yEWS;
            __shared__ int zEWS;

            __shared__ nd4j::random::RandomBuffer *buffer;
            __shared__ unsigned char *cB;
            __shared__ unsigned char *dB;
            __shared__ nd4j::random::RandomBuffer *devBuffer;
            if (threadIdx.x == 0) {
                extern __shared__ unsigned char shmem[];
                buffer = (nd4j::random::RandomBuffer *) shmem;
                cB = shmem;
                devBuffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);
                dB = reinterpret_cast<unsigned char *> (state);

                zLength = shape::length(zShapeBuffer);
                yEWS = shape::elementWiseStride(yShapeBuffer);
                zEWS = shape::elementWiseStride(zShapeBuffer);
            }
            __syncthreads();

            // using this loop instead of memcpy
            for (int e = threadIdx.x; e < sizeof(nd4j::random::RandomBuffer); e+= blockDim.x) {
                cB[e] = dB[e];
            }
            __syncthreads();

            int tid = blockIdx.x * blockDim.x + threadIdx.x;

            for (Nd4jIndex e = tid; e < zLength; e += blockDim.x * gridDim.x) {
                int success = 0;
                for (int t = 1; t <= trials; t++) {
                    T randVal = buffer->relativeT<T>((e+1) * t);
                    if (y != z) {
                        // we're using external probs
                        prob = y[(t-1) * yEWS];
                    }

                    if (randVal < prob)
                        success++;
                }

                // we need this, to eliminate excessive code branching in runtime
                __syncthreads();

                // if trials is set to 0, effectively we just have successful memset
                z[e * zEWS] = (T) success;
            }

            __syncthreads();
            if (trials > 0)
                devBuffer->rewind(zLength * trials);
        }
#endif

        static inline void specialOp(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            int trials = (int) extraArguments[0];

            Nd4jIndex zLength = shape::length(zShapeBuffer);

            int yEWS = shape::elementWiseStride(yShapeBuffer);
            int zEWS = shape::elementWiseStride(zShapeBuffer);

            int elementsPerThread = zLength / TAD_THRESHOLD;
            int _threads = nd4j::math::nd4j_max<int>(1, elementsPerThread);
            _threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());

            int span = (zLength / _threads) + 8;

            nd4j::random::RandomBuffer *buffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);

#pragma omp parallel num_threads(_threads) if (_threads > 1) proc_bind(spread)
            {
                int tid = omp_get_thread_num();
                Nd4jIndex start = span * tid;
                Nd4jIndex end = span * (tid + 1);
                if (end > zLength) end = zLength;

                T prob = extraArguments[1];

                for (Nd4jIndex e = start; e < end; e++) {

                    int success = 0;
                    for (int t = 1; t <= trials; t++) {
                        T randVal = buffer->relativeT<T>((e+1) * t);
                        if (y != z) {
                            // we're using external probs
                            prob = y[(t-1) * yEWS];
                        }

                        if (randVal < prob)
                            success++;
                    }

                    // if trials is set to 0, effectively we just have successful memset
                    z[e * zEWS] = (T) success;
                }
            }

            // update rng state
            if (trials > 0)
                buffer->rewindH(zLength * trials);
        }
    };

    /**
    * This Op produces random values within [0..N], Distribuion is binomial
    */
    template<typename T>
    class BinomialDistributionEx {
    public:

        method_XY
        method_X
        method_idx

        static const bool requiresSpecial = true;

#ifdef __CUDACC__
        __device__ static inline void specialOpCuda(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            int trials = (int) extraArguments[0];
            T prob = extraArguments[1];

            __shared__ Nd4jIndex zLength;
            __shared__ int yEWS;
            __shared__ int zEWS;

            __shared__ nd4j::random::RandomBuffer *buffer;
            __shared__ unsigned char *cB;
            __shared__ unsigned char *dB;
            __shared__ nd4j::random::RandomBuffer *devBuffer;
            if (threadIdx.x == 0) {
                extern __shared__ unsigned char shmem[];
                buffer = (nd4j::random::RandomBuffer *) shmem;
                cB = shmem;
                devBuffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);
                dB = reinterpret_cast<unsigned char *> (state);

                zLength = shape::length(zShapeBuffer);
                yEWS = shape::elementWiseStride(yShapeBuffer);
                zEWS = shape::elementWiseStride(zShapeBuffer);
            }
            __syncthreads();

            // using this loop instead of memcpy
            for (int e = threadIdx.x; e < sizeof(nd4j::random::RandomBuffer); e+= blockDim.x) {
                cB[e] = dB[e];
            }
            __syncthreads();

            int tid = blockIdx.x * blockDim.x + threadIdx.x;

            for (Nd4jIndex e = tid; e < zLength; e += blockDim.x * gridDim.x) {
                int success = 0;
                for (int t = 1; t <= trials; t++) {
                    T randVal = buffer->relativeT<T>((e+1) * t);
                    if (y != z) {
                        // we're using external probs
                        prob = y[e * yEWS];
                    }

                    if (randVal < prob)
                        success++;
                }

                // we need this, to eliminate excessive code branching in runtime
                __syncthreads();

                // if trials is set to 0, effectively we just have successful memset
                z[e * zEWS] = (T) success;
            }

            __syncthreads();
            if (trials > 0)
                devBuffer->rewind(zLength * trials);
        }
#endif

        static inline void specialOp(Nd4jPointer state, T *x, int *xShapeBuffer, T *y, int *yShapeBuffer, T *z, int *zShapeBuffer, T *extraArguments) {
            int trials = (int) extraArguments[0];

            Nd4jIndex zLength = shape::length(zShapeBuffer);

            int yEWS = shape::elementWiseStride(yShapeBuffer);
            int zEWS = shape::elementWiseStride(zShapeBuffer);

            int elementsPerThread = zLength / TAD_THRESHOLD;
            int _threads = nd4j::math::nd4j_max<int>(1, elementsPerThread);
            _threads = nd4j::math::nd4j_min<int>(_threads, omp_get_max_threads());

            int span = (zLength / _threads) + 8;

            nd4j::random::RandomBuffer *buffer = reinterpret_cast<nd4j::random::RandomBuffer *> (state);

#pragma omp parallel num_threads(_threads) if (_threads > 1) proc_bind(spread)
            {
                int tid = omp_get_thread_num();
                Nd4jIndex start = span * tid;
                Nd4jIndex end = span * (tid + 1);
                if (end > zLength) end = zLength;

                T prob = extraArguments[1];

                for (Nd4jIndex e = start; e < end; e++) {

                    int success = 0;
                    for (int t = 1; t <= trials; t++) {
                        T randVal = buffer->relativeT<T>((e+1) * t);
                        if (y != z) {
                            // we're using external probs
                            prob = y[e * yEWS];
                        }

                        if (randVal < prob)
                            success++;
                    }

                    // if trials is set to 0, effectively we just have successful memset
                    z[e * zEWS] = (T) success;
                }
            }

            // update rng state
            if (trials > 0)
                buffer->rewindH(zLength * trials);
        }
    };
}

#endif //LIBND4J_SPECIAL_RANDOM_OPS_H


text:
@interface ShrinkFadeAnimatedTransition : NSObject <UIViewControllerAnimatedTransitioning>
@end

@interface GrowFadeAnimatedTransition : NSObject <UIViewControllerAnimatedTransitioning>
@end

@interface ViewController ()< RBSwappableContainerDelegate >

@property (strong, nonatomic) RBSwappableContainerViewController * swapVC;
@property (strong, nonatomic) NSArray * comicData;
@property (strong, nonatomic) NSDictionary * currentComic;
@property (assign, nonatomic) NSInteger currentIndex;

@property (strong, nonatomic) IBOutlet UILabel * titleLabel;
@property (strong, nonatomic) IBOutlet UILabel * attributionLabel;
@property (strong, nonatomic) IBOutlet UIButton * imageBtn;
@property (strong, nonatomic) IBOutlet UIButton * detailBtn;
@property (strong, nonatomic) IBOutlet UIButton * priceBtn;

@property (strong, nonatomic) ComicImageViewController * comicImageVC;
@property (strong, nonatomic) ComicDescriptionViewController * comicDescVC;
@property (strong, nonatomic) ComicPriceTableViewController * comicPriceTVC;

@end

@implementation ViewController

#pragma mark - View Lifecycle

- (void)viewDidLoad
{
    self.comicData = [ComicData data][@"data"][@"results"];
    self.currentIndex = 0;
    self.currentComic = self.comicData[self.currentIndex];
    self.attributionLabel.text = [ComicData data][@"attributionText"];

    [self loadContainedViewControllers];

    self.imageBtn.enabled = NO;
    self.imageBtn.titleLabel.font = [UIFont fontWithName:@"swappable_demo" size:17];
    [self.imageBtn setTitle:[NSString iconPicture] forState:UIControlStateNormal];

    self.detailBtn.titleLabel.font = [UIFont fontWithName:@"swappable_demo" size:17];
    [self.detailBtn setTitle:[NSString iconDocText] forState:UIControlStateNormal];

    self.priceBtn.titleLabel.font = [UIFont fontWithName:@"swappable_demo" size:17];
    [self.priceBtn setTitle:[NSString iconDollar] forState:UIControlStateNormal];

    [self updateViewControllers];
}

#pragma mark - Helper Methods

- (void)loadContainedViewControllers
{
    if (self.comicImageVC == nil) self.comicImageVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Image"];
    if (self.comicDescVC == nil) self.comicDescVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Description"];
    if (self.comicPriceTVC == nil) self.comicPriceTVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Prices"];
}

- (NSURL *)imageURL
{
    // Get Image URL
    NSString * imagePath = self.currentComic[@"thumbnail"][@"path"];
    imagePath = [imagePath stringByAppendingString:@"/portrait_uncanny."];
    imagePath = [imagePath stringByAppendingString:self.currentComic[@"thumbnail"][@"extension"]];
    return [NSURL URLWithString:imagePath];
}

- (void)updateViewControllers
{
    self.titleLabel.text = self.currentComic[@"title"];

    [self.comicImageVC setImageURL:[self imageURL]];
    [self.comicDescVC setComicData:self.currentComic];
    [self.comicPriceTVC setComicData:self.currentComic];
}

#pragma mark - IBActions

- (IBAction)showImage:(id)sender
{
    self.swapVC.selectedIndex = 0;
    self.imageBtn.enabled = NO;
    self.detailBtn.enabled = YES;
    self.priceBtn.enabled = YES;
}

- (IBAction)showDetail:(id)sender
{
    self.swapVC.selectedIndex = 1;
    self.imageBtn.enabled = YES;
    self.detailBtn.enabled = NO;
    self.priceBtn.enabled = YES;
}

- (IBAction)showPrice:(id)sender
{
    self.swapVC.selectedIndex = 2;
    self.imageBtn.enabled = YES;
    self.detailBtn.enabled = YES;
    self.priceBtn.enabled = NO;
}

- (IBAction)previous:(id)sender
{
    self.currentIndex--;
    if (self.currentIndex < 0)
    {
        self.currentIndex = [self.comicData count] - 1;
    }

    self.currentComic = self.comicData[self.currentIndex];
    [self updateViewControllers];
}

- (IBAction)next:(id)sender
{
    self.currentIndex++;
    if (self.currentIndex >= [self.comicData count])
    {
        self.currentIndex = 0;
    }

    self.currentComic = self.comicData[self.currentIndex];
    [self updateViewControllers];
}

#pragma mark - RBSwappableContainerViewController Delegate

- (void)animationEndedForcontainerViewController:(RBSwappableContainerViewController *)containerViewController
{
}

- (id<UIViewControllerAnimatedTransitioning>)containerViewController:(RBSwappableContainerViewController *)containerViewController animationControllerForTransitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController
{
    if (fromViewController == self.comicImageVC)
    {
        return [[ShrinkFadeAnimatedTransition alloc] init];
    }

    if (toViewController == self.comicImageVC)
    {
        return [[GrowFadeAnimatedTransition alloc] init];
    }

    return nil;
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"embedSwappableViewController"])
    {
        [self loadContainedViewControllers];

        RBSwappableContainerViewController * swapVC = segue.destinationViewController;

        swapVC.selectedIndex = 0;
        swapVC.delegate = self;
        swapVC.viewControllers = @[
            self.comicImageVC,
            self.comicDescVC,
            self.comicPriceTVC,
        ];

        self.swapVC = swapVC;
    }

}

@end

#pragma mark - Custom Animations -

static CGFloat const kDamping = 0.75;
static CGFloat const kInitialSpringVelocity = 0.5;

@implementation ShrinkFadeAnimatedTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 1;
}

/// Slide views horizontally, with a bit of space between, while fading out and in.
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {

    UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.1, 0.1);

    [[transitionContext containerView] addSubview:toViewController.view];
    toViewController.view.alpha = 0;

    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:kDamping initialSpringVelocity:kInitialSpringVelocity options:0x00 animations:^{
        fromViewController.view.transform = scaleTransform;
        fromViewController.view.alpha = 0;
        toViewController.view.alpha = 1;
    } completion:^(BOOL finished) {
        fromViewController.view.transform = CGAffineTransformIdentity;
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

@end

@implementation GrowFadeAnimatedTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 1;
}

/// Slide views horizontally, with a bit of space between, while fading out and in.
- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {

    UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];

    CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.1, 0.1);

    [[transitionContext containerView] addSubview:toViewController.view];
    toViewController.view.alpha = 0;
    toViewController.view.transform = scaleTransform;

    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 usingSpringWithDamping:kDamping initialSpringVelocity:kInitialSpringVelocity options:0x00 animations:^{
        fromViewController.view.alpha = 1;
        toViewController.view.transform = CGAffineTransformIdentity;
        toViewController.view.alpha = 2;
    } completion:^(BOOL finished) {
        fromViewController.view.alpha = 1;
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

@end


text:
package space.spacelift.mq.proxy.patterns

import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import space.spacelift.mq.proxy.Delivery

object RpcClient {
  case class Request(publish: List[Delivery], numberOfResponses: Int = 1)

  object Request {
    def apply(publish: Delivery): Request = new Request(List(publish), 1)
  }

  case class Response(deliveries: List[Delivery])

  case class Undelivered(msg: AnyRef)

  private[proxy] case class RpcResult(destination: ActorRef, expected: Int, deliveries: scala.collection.mutable.ListBuffer[Delivery])
}

trait RpcClient extends Actor with ActorLogging {
  import RpcClient._

  var counter: Int = 0
  var correlationMap = scala.collection.mutable.Map.empty[String, RpcResult]
}


text:
const { GraphQLList, GraphQLString } = require('graphql')
const mongoose = require('mongoose')
const { outputType } = require('../../types/UserGroups')
const getProjection = require('../../get-projection')

const UserGroup = mongoose.model('UserGroup')

module.exports = {
  type: new GraphQLList(outputType),
  args: {
    status: {
      name: 'status',
      type: GraphQLString
    }
  },
  resolve (root, args, ctx, ast) {
    const projection = getProjection(ast)

    return UserGroup
      .find(args)
      .sort({ dateCreated: 1 })
      .select(projection)
      .exec()
  }
}


text:
package edu.chapman.manusync.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.parse.ParseException;

import edu.chapman.manusync.R;
import edu.chapman.manusync.adapter.IssueListAdapter;
import edu.chapman.manusync.dao.IssueDAO;
import edu.chapman.manusync.dto.IssueDTO;
import edu.chapman.manusync.dto.LotDTO;

/**
 * Created by niccorder - corde116@mail.chapman.edu on 11/16/15.
 */
public class IssueDialog extends Dialog {

    private ListView issueListView;
    private IssueDAO issueProvider;
    private IssueListAdapter adapter;
    private LotDTO lot;

    public IssueDialog(Context context, LotDTO lot) {
        super(context);
        this.lot = lot;

        /* this does not let the user cancel the dialog when clicked outside, you must select an issue */
        setCanceledOnTouchOutside(false);

        setContentView(R.layout.dialog_issue);
        issueProvider = new IssueDAO();
        try {
            adapter = new IssueListAdapter(context,
                    R.layout.item_spinner, issueProvider.getAllIssues());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        issueListView = (ListView) findViewById(R.id.issue_lv);
        issueListView.setAdapter(adapter);
        issueListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                IssueDTO issue = (IssueDTO) issueListView.getItemAtPosition(position);
                issueProvider.logIssue(IssueDialog.this.lot, issue);
                IssueDialog.this.dismiss();
            }
        });
    }
}