text:
var get = Ember.get, set = Ember.set;

var stateManager, loadingState, loadedState, stateEventStub = {
  entered: 0,
  enter: function() {
    this.entered++;
  },

  exited: 0,
  exit: function() {
    this.exited++;
  },

  reset: function() {
    this.entered = 0;
    this.exited = 0;
  }
};

module("Ember.StateManager", {
  setup: function() {
    loadingState = Ember.State.create(stateEventStub);
    loadedState = Ember.State.create(stateEventStub, {
      empty: Ember.State.create(stateEventStub)
    });

    stateManager = Ember.StateManager.create({
      loadingState: loadingState,
      loadedState: loadedState
    });
  },

  teardown: function() {
    Ember.run(function() {
      if (stateManager) {
        stateManager.destroy();
      }
    });
  }
});

test("it exists", function() {
  ok(Ember.Object.detect(Ember.StateManager), "Ember.StateManager is an Ember.Object");
});

test("it discovers states set in its state property", function() {
  var states = {
    loading: Ember.State.create(),
    loaded: Ember.State.create()
  };

  stateManager = Ember.StateManager.create({
    states: states
  });

  equal(states, stateManager.get('states'), "reports same states as were set");
});

test("it discovers states that are properties of the state manager", function() {
  stateManager = Ember.StateManager.create({
    loading: Ember.State.create(),
    loaded: Ember.State.create()
  });

  var states = stateManager.get('states');
  ok(get(states, 'loading'), "found loading state");
  ok(get(states, 'loaded'), "found loaded state");
});

test("it reports its current state", function() {
  ok(get(stateManager, 'currentState') === null, "currentState defaults to null if no state is specified");

  stateManager.transitionTo('loadingState');
  ok(get(stateManager, 'currentState') === loadingState, "currentState changes after transitionTo() is called");

  stateManager.transitionTo('loadedState');
  ok(get(stateManager, 'currentState') === loadedState, "currentState can change to a sibling state");
});

test("it reports its current state path", function() {
  strictEqual(get(stateManager, 'currentPath'), null, "currentPath defaults to null if no state is specified");

  stateManager.transitionTo('loadingState');
  equal(get(stateManager, 'currentPath'), 'loadingState', "currentPath changes after transitionTo() is called");

  stateManager.transitionTo('loadedState');
  equal(get(stateManager, 'currentPath'), 'loadedState', "currentPath can change to a sibling state");
});

test("it sends enter and exit events during state transitions", function() {
  stateManager.transitionTo('loadingState');

  equal(loadingState.entered, 1, "state should receive one enter event");
  equal(loadingState.exited, 0, "state should not have received an exit event");
  equal(loadedState.entered, 0, "sibling state should not have received enter event");
  equal(loadedState.exited, 0, "sibling state should not have received exited event");

  loadingState.reset();
  loadedState.reset();

  stateManager.transitionTo('loadedState');
  equal(loadingState.entered, 0, "state should not receive an enter event");
  equal(loadingState.exited, 1, "state should receive one exit event");
  equal(loadedState.entered, 1, "sibling state should receive one enter event");
  equal(loadedState.exited, 0, "sibling state should not have received exited event");

  loadingState.reset();
  loadedState.reset();

  stateManager.transitionTo('loadingState');

  equal(loadingState.entered, 1, "state should receive one enter event");
  equal(loadingState.exited, 0, "state should not have received an exit event");
  equal(loadedState.entered, 0, "sibling state should not have received enter event");
  equal(loadedState.exited, 1, "sibling state should receive one exit event");
});

test("it accepts absolute paths when changing states", function() {
  var emptyState = loadedState.empty;

  stateManager.transitionTo('loadingState');

  stateManager.transitionTo('loadedState.empty');

  equal(emptyState.entered, 1, "sends enter event to substate");
  equal(emptyState.exited, 0, "does not send exit event to substate");
  ok(stateManager.get('currentState') === emptyState, "updates currentState property to state at absolute path");
});

test("it does not enter an infinite loop in transitionTo", function() {
  var emptyState = loadedState.empty;

  stateManager.transitionTo('loadedState.empty');

  stateManager.transitionTo('');
  ok(stateManager.get('currentState') === emptyState, "transitionTo does nothing when given empty name");

  expectAssertion(function() {
    stateManager.transitionTo('nonexistentState');
  }, 'Could not find state for path: "nonexistentState"');

  ok(stateManager.get('currentState') === emptyState, "transitionTo does not infinite loop when given nonexistent State");
});

test("it automatically transitions to a default state", function() {
  stateManager = Ember.StateManager.create({
    start: Ember.State.create({
      isStart: true
    })
  });

  ok(get(stateManager, 'currentState').isStart, "automatically transitions to start state");
});

test("it automatically transitions to a default state that is an instance", function() {
  stateManager = Ember.StateManager.create({
    states: {
      foo: Ember.State.create({
        start: Ember.State.extend({
          isStart: true
        })
      })
    }
  });

  stateManager.transitionTo('foo');
  ok(get(stateManager, 'currentState').isStart, "automatically transitions to start state");
});

test("on a state manager, it automatically transitions to a default state that is an instance", function() {
  stateManager = Ember.StateManager.create({
    states: {
      start: Ember.State.extend({
        isStart: true
      })
    }
  });

  ok(get(stateManager, 'currentState').isStart, "automatically transitions to start state");
});

test("it automatically transitions to a default state specified using the initialState property", function() {
  stateManager = Ember.StateManager.create({
    initialState: 'beginning',

    beginning: Ember.State.create({
      isStart: true
    })
  });

  ok(get(stateManager, 'currentState').isStart, "automatically transitions to beginning state");
});

test("it automatically transitions to a default substate specified using the initialState property", function() {
  stateManager = Ember.StateManager.create({
    start: Ember.State.create({
      initialState: 'beginningSubstate',

      beginningSubstate: Ember.State.create({
        isStart: true
      })
    })
  });

  ok(get(stateManager, 'currentState').isStart, "automatically transitions to beginning substate");
});

test("it automatically synchronously transitions into initialState in an event", function() {
  var count = 0;

  stateManager = Ember.StateManager.create({
    root: Ember.State.create({
      original: Ember.State.create({
        zomgAnEvent: function(manager) {
          manager.transitionTo('nextState');
          manager.send('zomgAnotherEvent');
        }
      }),

      nextState: Ember.State.create({
        initialState: 'begin',

        begin: Ember.State.create({
          zomgAnotherEvent: function(manager) {
            count++;
          }
        })
      })
    })
  });

  Ember.run(function() {
    stateManager.transitionTo('root.original');
  });

  Ember.run(function() {
    stateManager.send('zomgAnEvent');
    equal(count, 1, "the initialState was synchronously effective");
  });
});

test("it automatically transitions to multiple substates specified using either start or initialState property", function() {
  stateManager = Ember.StateManager.create({
    start: Ember.State.create({
      initialState: 'beginningSubstate',

      beginningSubstate: Ember.State.create({
        start: Ember.State.create({
          initialState: 'finalSubstate',

          finalSubstate: Ember.State.create({
            isStart: true
          })
        })
      })
    })
  });

  ok(get(stateManager, 'currentState').isStart, "automatically transitions to final substate");
});

test("it triggers setup on initialSubstate", function() {
  var parentSetup = false,
      childSetup = false,
      grandchildSetup = false;

  stateManager = Ember.StateManager.create({
    start: Ember.State.create({
      setup: function() { parentSetup = true; },

      initialState: 'childState',

      childState: Ember.State.create({
        setup: function() { childSetup = true; },

        initialState: 'grandchildState',

        grandchildState: Ember.State.create({
          setup: function() { grandchildSetup = true; }
        })
      })
    })
  });

  ok(parentSetup, "sets up parent");
  ok(childSetup, "sets up child");
  ok(grandchildSetup, "sets up grandchild");
});

test("it throws an assertion error when the initialState does not exist", function() {
  expectAssertion(function() {
    Ember.StateManager.create({
      initialState: 'foo',
      bar: Ember.State.create()
    });
  });
});

module("Ember.StateManager - Transitions on Complex State Managers");

/**
            SM
          /    \
     Login      Redeem
    /    |        |    \
  Start  Pending Start  Pending

  * Transition from Login.Start to Redeem
    - Login.Start and Login should receive exit events
    - Redeem should receiver enter event
*/

test("it sends exit events to nested states when changing to a top-level state", function() {
  var stateManager = Ember.StateManager.create({
    login: Ember.State.create(stateEventStub, {
      start: Ember.State.create(stateEventStub),
      pending: Ember.State.create(stateEventStub)
    }),

    redeem: Ember.State.create(stateEventStub, {
      isRedeem: true,
      start: Ember.State.create(),
      pending: Ember.State.create()
    })
  });

  stateManager.transitionTo('login');
  equal(stateManager.login.entered, 1, "precond - it enters the login state");
  equal(stateManager.login.start.entered, 1, "automatically enters the start state");
  ok(stateManager.get('currentState') === stateManager.login.start, "automatically sets currentState to start state");

  stateManager.login.reset();
  stateManager.login.start.reset();

  stateManager.transitionTo('redeem');

  equal(stateManager.login.exited, 1, "login state is exited once");
  equal(stateManager.login.start.exited, 1, "start state is exited once");

  equal(stateManager.redeem.entered, 1, "redeemed state is entered once");
});

test("it sends exit events in the correct order when changing to a top-level state", function() {
  var exitOrder = [],
      stateManager = Ember.StateManager.create({
        start: Ember.State.create({
          outer: Ember.State.create({
            inner: Ember.State.create({
              exit: function() { exitOrder.push('exitedInner'); }
            }),
            exit: function() { exitOrder.push('exitedOuter'); }
          })
        })
      });

  stateManager.transitionTo('start.outer.inner');
  stateManager.transitionTo('start');
  equal(exitOrder.length, 2, "precond - it calls both exits");
  equal(exitOrder[0], 'exitedInner', "inner exit is called first");
  equal(exitOrder[1], 'exitedOuter', "outer exit is called second");
});

test("it sends exit events in the correct order when changing to a state multiple times", function() {
  var exitOrder = [],
      stateManager = Ember.StateManager.create({
        start: Ember.State.create({
          outer: Ember.State.create({
            inner: Ember.State.create({
              exit: function() { exitOrder.push('exitedInner'); }
            }),
            exit: function() { exitOrder.push('exitedOuter'); }
          })
        })
      });

  stateManager.transitionTo('start.outer.inner');
  stateManager.transitionTo('start');
  stateManager.transitionTo('start.outer.inner');
  exitOrder = [];
  stateManager.transitionTo('start');
  equal(exitOrder.length, 2, "precond - it calls both exits");
  equal(exitOrder[0], 'exitedInner', "inner exit is called first");
  equal(exitOrder[1], 'exitedOuter', "outer exit is called second");
});

var passedContext, passedContexts, loadingEventCalled, loadedEventCalled, eventInChildCalled;
loadingEventCalled = loadedEventCalled = eventInChildCalled = 0;

module("Ember.StateManager - Event Dispatching", {
  setup: function() {
    stateManager = Ember.StateManager.create({
      loading: Ember.State.create({
        anEvent: function(manager, context) {
          loadingEventCalled++;
          passedContext = context;
          passedContexts = [].slice.call(arguments, 1);
        }
      }),

      loaded: Ember.State.create({
        anEvent: function() {
          loadedEventCalled++;
        },

        eventInChild: function() {
          eventInChildCalled++;
        },

        empty: Ember.State.create({
          eventInChild: function() {
            eventInChildCalled++;
          }
        })
      })
    });

    stateManager.transitionTo('loading');
  }
});

test("it dispatches events to the current state", function() {
  stateManager.send('anEvent');

  equal(loadingEventCalled, 1, "event was triggered");
});

test("it dispatches events to a parent state if the child state does not respond to it", function() {
  stateManager.transitionTo('loaded.empty');
  stateManager.send('anEvent');

  equal(loadedEventCalled, 1, "parent state receives event");
});

test("it does not dispatch events to parents if the child responds to it", function() {
  stateManager.transitionTo('loaded.empty');
  stateManager.send('eventInChild');

  equal(eventInChildCalled, 1, "does not dispatch event to parent");
});

test("it supports arguments to events", function() {
  stateManager.send('anEvent', { context: true });
  equal(passedContext.context, true, "send passes along a context");
});

test("it supports multiple arguments to events", function() {
  stateManager.send('anEvent', {name: 'bestie'}, {name: 'crofty'});
  equal(passedContexts[0].name, 'bestie', "send passes along the first context");
  equal(passedContexts[1].name, 'crofty', "send passes along the second context");
});

test("it throws an exception if an event is dispatched that is unhandled", function() {
  raises(function() {
    stateManager.send('unhandledEvent');
  }, Error, "exception was raised");

  stateManager = Ember.StateManager.create({
    initialState: 'loading',
    errorOnUnhandledEvent: false,
    loading: Ember.State.create({
      anEvent: function() {}
    })
  });

  stateManager.send('unhandledEvent');
  ok(true, "does not raise exception when errorOnUnhandledEvent is set to false");
});

test("it looks for unhandledEvent handler in the currentState if event is not handled by named handler", function() {
  var wasCalled = 0,
      evt = "foo",
      calledWithOriginalEventName,
      calledWithEvent;
  stateManager = Ember.StateManager.create({
    initialState: 'loading',
    loading: Ember.State.create({
      unhandledEvent: function(manager, originalEventName, event) {
        wasCalled = true;
        calledWithOriginalEventName = originalEventName;
        calledWithEvent = event;
      }
    })
  });
  stateManager.send("somethingUnhandled", evt);
  ok(wasCalled);
  equal(calledWithOriginalEventName, 'somethingUnhandled');
  equal(calledWithEvent, evt);
});

test("it looks for unhandledEvent handler in the stateManager if event is not handled by named handler", function() {
  var wasCalled = 0,
      evt = "foo",
      calledWithOriginalEventName,
      calledWithEvent;
  stateManager = Ember.StateManager.create({
    initialState: 'loading',
    unhandledEvent: function(manager, originalEventName, event) {
      wasCalled = true;
      calledWithOriginalEventName = originalEventName;
      calledWithEvent = event;
    },
    loading: Ember.State.create({})
  });
  stateManager.send("somethingUnhandled", evt);
  ok(wasCalled);
  equal(calledWithOriginalEventName, 'somethingUnhandled');
  equal(calledWithEvent, evt);
});

module("Ember.Statemanager - Pivot states", {
  setup: function() {
    var State = Ember.State.extend(stateEventStub);

    stateManager = Ember.StateManager.create(stateEventStub, {
      grandparent: State.create({
        parent: State.create({
          child: State.create(),
          sibling: State.create()
        }),
        cousin: State.create()
      })
    });
  }
});

test("transitionTo triggers all enter states", function() {
  stateManager.transitionTo('grandparent.parent.child');
  equal(stateManager.grandparent.entered, 1, "the top level should be entered");
  equal(stateManager.grandparent.parent.entered, 1, "intermediate states should be entered");
  equal(stateManager.grandparent.parent.child.entered, 1, "the final state should be entered");

  stateManager.transitionTo('grandparent.parent.sibling');
  equal(stateManager.grandparent.entered, 1, "the top level should not be re-entered");
  equal(stateManager.grandparent.parent.entered, 1, "intermediate states should not be re-entered");
  equal(stateManager.grandparent.parent.child.entered, 1, "the final state should not be re-entered");

  equal(stateManager.grandparent.parent.child.exited, 1, "the child should have exited");
  equal(stateManager.grandparent.exited, 0, "the top level should not have have exited");
  equal(stateManager.grandparent.parent.exited, 0, "intermediate states should not have exited");
});

test("transitionTo with current state does not trigger enter or exit", function() {
  stateManager.transitionTo('grandparent.parent.child');
  stateManager.transitionTo('grandparent.parent.child');
  equal(stateManager.grandparent.entered, 1, "the top level should only be entered once");
  equal(stateManager.grandparent.parent.entered, 1, "intermediate states should only be entered once");
  equal(stateManager.grandparent.parent.child.entered, 1, "the final state should only be entered once");
  equal(stateManager.grandparent.parent.child.exited, 0, "the final state should not be exited");
});

module("Transition contexts");

test("if a context is passed to a transition, the state's setup event is triggered after the transition has completed", function() {
  expect(1);
  var context = {};

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create({
        goNext: function(manager, context) {
          manager.transitionTo('next', context);
        }
      }),

      next: Ember.State.create({
        setup: function(manager, passedContext) {
          equal(context, passedContext, "The context is passed through");
        }
      })
    });
  });

  stateManager.send('goNext', context);
});

test("if a context is passed to a transition and the path is to the current state, the state's setup event is triggered again", function() {
  expect(2);
  var counter = 0;

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create({
        goNext: function(manager, context) {
          counter++;
          manager.transitionTo('foo.next', counter);
        }
      }),

      foo: Ember.State.create({
        next: Ember.State.create({
          goNext: function(manager, context) {
            counter++;
            manager.transitionTo('next', counter);
          },

          setup: function(manager, context) {
            equal(context, counter, "The context is passed through");
          }
        })
      })
    });
  });

  stateManager.send('goNext', counter);
  stateManager.send('goNext', counter);
});

test("if no context is provided, setup is triggered with an undefined context", function() {
  expect(1);

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create({
        goNext: function(manager) {
          manager.transitionTo('next');
        },

        next: Ember.State.create({
          setup: function(manager, context) {
            equal(context, undefined, "setup is called with no context");
          }
        })
      })
    });
  });

  stateManager.send('goNext');
});

test("multiple contexts can be provided in a single transitionTo", function() {
  expect(2);

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create(),

      planters: Ember.State.create({
        setup: function(manager, context) {
          deepEqual(context, { company: true });
        },

        nuts: Ember.State.create({
          setup: function(manager, context) {
            deepEqual(context, { product: true });
          }
        })
      })
    });
  });

  stateManager.transitionTo('planters.nuts', { company: true }, { product: true });
});

test("multiple contexts only apply to states that need them", function() {
  expect(4);

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create(),

      parent: Ember.State.create({
        hasContext: false,

        setup: function(manager, context) {
          equal(context, undefined);
        },

        child: Ember.State.create({
          setup: function(manager, context) {
            equal(context, 'one');
          },

          grandchild: Ember.State.create({
            initialState: 'greatGrandchild',

            setup: function(manager, context) {
              equal(context, 'two');
            },

            greatGrandchild: Ember.State.create({
              setup: function(manager, context) {
                equal(context, undefined);
              }
            })
          })
        })
      })
    });
  });

  stateManager.transitionTo('parent.child.grandchild', 'one', 'two');
});

test("transitionEvent is called for each nested state", function() {
  expect(4);

  var calledOnParent = false,
      calledOnChild = true;

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create(),

      planters: Ember.State.create({
        setup: function(manager, context) {
          calledOnParent = true;
        },

        nuts: Ember.State.create({
          setup: function(manager, context) {
            calledOnChild = true;
          }
        })
      })
    });
  });

  stateManager.transitionTo('planters.nuts');

  ok(calledOnParent, 'called transitionEvent on parent');
  ok(calledOnChild, 'called transitionEvent on child');

  // repeat the test now that the path is cached

  stateManager.transitionTo('start');

  calledOnParent = false;
  calledOnChild = false;

  stateManager.transitionTo('planters.nuts');

  ok(calledOnParent, 'called transitionEvent on parent');
  ok(calledOnChild, 'called transitionEvent on child');
});

test("transitionEvent is called for each nested state with context", function() {
  expect(8);

  var calledOnParent = false,
      calledOnChild = true;

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create(),

      planters: Ember.State.create({
        setup: function(manager, context) {
          calledOnParent = true;
          ok(!context, 'single context is not called on parent');
        },

        nuts: Ember.State.create({
          setup: function(manager, context) {
            calledOnChild = true;
            equal(context, 'context', 'child gets context');
          }
        })
      })
    });
  });

  stateManager.transitionTo('planters.nuts', 'context');

  ok(calledOnParent, 'called transitionEvent on parent');
  ok(calledOnChild, 'called transitionEvent on child');

  // repeat the test now that the path is cached

  stateManager.transitionTo('start');

  calledOnParent = false;
  calledOnChild = false;

  stateManager.transitionTo('planters.nuts', 'context');

  ok(calledOnParent, 'called transitionEvent on parent');
  ok(calledOnChild, 'called transitionEvent on child');
});

test("nothing happens if transitioning to a parent state when the current state is also the initial state", function() {
  var calledOnParent = 0,
      calledOnChild = 0;

  Ember.run(function() {
    stateManager = Ember.StateManager.create({
      start: Ember.State.create({
        initialState: 'first',

        setup: function() {
          calledOnParent++;
        },

        first: Ember.State.create({
          setup: function() {
            calledOnChild++;
          }
        })
      })
    });
  });

  equal(calledOnParent, 1, 'precond - setup parent');
  equal(calledOnChild, 1, 'precond - setup child');
  equal(stateManager.get('currentState.path'), 'start.first', 'precond - is in expected state');

  stateManager.transitionTo('start');

  equal(calledOnParent, 1, 'does not transition to parent again');
  equal(calledOnChild, 1, 'does not transition to child again');
  equal(stateManager.get('currentState.path'), 'start.first', 'does not change state');

});

test("StateManagers can use `create`d states from mixins", function() {
  var statesMixin,
    firstManagerClass, secondManagerClass,
    firstManager, secondManager,
    firstCount = 0, secondCount = 0;

  statesMixin = Ember.Mixin.create({
    initialState: 'ready',
    ready: Ember.State.create({
      startUpload: function(manager) {
        manager.transitionTo('uploading');
      }
    })
  });

  firstManagerClass = Ember.StateManager.extend(statesMixin, {
    uploading: Ember.State.create({
      enter: function() { firstCount++; }
    })
  });

  secondManagerClass = Ember.StateManager.extend(statesMixin, {
    uploading: Ember.State.create({
      enter: function() { secondCount++; }
    })
  });

  firstManager  = firstManagerClass.create();
  firstManager.send('startUpload');

  secondManager = secondManagerClass.create();
  secondManager.send('startUpload');

  equal(firstCount, 1, "The first state manager's uploading state was entered once");
  equal(secondCount, 1, "The second state manager's uploading state was entered once");
});


text:
"""Tests for image preprocessing utils."""

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

import os
import shutil
import tempfile

import numpy as np

from tensorflow.python import keras
from tensorflow.python.platform import test

try:
  import PIL  # pylint:disable=g-import-not-at-top
except ImportError:
  PIL = None

def _generate_test_images():
  img_w = img_h = 20
  rgb_images = []
  gray_images = []
  for _ in range(8):
    bias = np.random.rand(img_w, img_h, 1) * 64
    variance = np.random.rand(img_w, img_h, 1) * (255 - 64)
    imarray = np.random.rand(img_w, img_h, 3) * variance + bias
    im = keras.preprocessing.image.array_to_img(imarray, scale=False)
    rgb_images.append(im)

    imarray = np.random.rand(img_w, img_h, 1) * variance + bias
    im = keras.preprocessing.image.array_to_img(imarray, scale=False)
    gray_images.append(im)

  return [rgb_images, gray_images]

class TestImage(test.TestCase):

  def test_image_data_generator(self):
    if PIL is None:
      return  # Skip test if PIL is not available.

    for test_images in _generate_test_images():
      img_list = []
      for im in test_images:
        img_list.append(keras.preprocessing.image.img_to_array(im)[None, ...])

      images = np.vstack(img_list)
      generator = keras.preprocessing.image.ImageDataGenerator(
          featurewise_center=True,
          samplewise_center=True,
          featurewise_std_normalization=True,
          samplewise_std_normalization=True,
          zca_whitening=True,
          rotation_range=90.,
          width_shift_range=0.1,
          height_shift_range=0.1,
          shear_range=0.5,
          zoom_range=0.2,
          channel_shift_range=0.,
          brightness_range=(1, 5),
          fill_mode='nearest',
          cval=0.5,
          horizontal_flip=True,
          vertical_flip=True)
      # Basic test before fit
      x = np.random.random((32, 10, 10, 3))
      generator.flow(x)

      # Fit
      generator.fit(images, augment=True)

      for x, _ in generator.flow(
          images,
          np.arange(images.shape[0]),
          shuffle=True):
        self.assertEqual(x.shape[1:], images.shape[1:])
        break

  def test_image_data_generator_with_split_value_error(self):
    with self.assertRaises(ValueError):
      keras.preprocessing.image.ImageDataGenerator(validation_split=5)

  def test_image_data_generator_invalid_data(self):
    generator = keras.preprocessing.image.ImageDataGenerator(
        featurewise_center=True,
        samplewise_center=True,
        featurewise_std_normalization=True,
        samplewise_std_normalization=True,
        zca_whitening=True,
        data_format='channels_last')

    # Test fit with invalid data
    with self.assertRaises(ValueError):
      x = np.random.random((3, 10, 10))
      generator.fit(x)
    # Test flow with invalid data
    with self.assertRaises(ValueError):
      generator.flow(np.arange(5))
    # Invalid number of channels: will work but raise a warning
    x = np.random.random((32, 10, 10, 5))
    generator.flow(x)

    with self.assertRaises(ValueError):
      generator = keras.preprocessing.image.ImageDataGenerator(
          data_format='unknown')

    generator = keras.preprocessing.image.ImageDataGenerator(
        zoom_range=(2, 2))

  def test_image_data_generator_fit(self):
    generator = keras.preprocessing.image.ImageDataGenerator(
        featurewise_center=True,
        samplewise_center=True,
        featurewise_std_normalization=True,
        samplewise_std_normalization=True,
        zca_whitening=True,
        data_format='channels_last')
    # Test grayscale
    x = np.random.random((32, 10, 10, 1))
    generator.fit(x)
    # Test RBG
    x = np.random.random((32, 10, 10, 3))
    generator.fit(x)
    generator = keras.preprocessing.image.ImageDataGenerator(
        featurewise_center=True,
        samplewise_center=True,
        featurewise_std_normalization=True,
        samplewise_std_normalization=True,
        zca_whitening=True,
        data_format='channels_first')
    # Test grayscale
    x = np.random.random((32, 1, 10, 10))
    generator.fit(x)
    # Test RBG
    x = np.random.random((32, 3, 10, 10))
    generator.fit(x)

  def test_directory_iterator(self):
    if PIL is None:
      return  # Skip test if PIL is not available.

    num_classes = 2

    temp_dir = self.get_temp_dir()
    self.addCleanup(shutil.rmtree, temp_dir)

    # create folders and subfolders
    paths = []
    for cl in range(num_classes):
      class_directory = 'class-{}'.format(cl)
      classpaths = [
          class_directory, os.path.join(class_directory, 'subfolder-1'),
          os.path.join(class_directory, 'subfolder-2'), os.path.join(
              class_directory, 'subfolder-1', 'sub-subfolder')
      ]
      for path in classpaths:
        os.mkdir(os.path.join(temp_dir, path))
      paths.append(classpaths)

    # save the images in the paths
    count = 0
    filenames = []
    for test_images in _generate_test_images():
      for im in test_images:
        # rotate image class
        im_class = count % num_classes
        # rotate subfolders
        classpaths = paths[im_class]
        filename = os.path.join(classpaths[count % len(classpaths)],
                                'image-{}.jpg'.format(count))
        filenames.append(filename)
        im.save(os.path.join(temp_dir, filename))
        count += 1

    # Test image loading util
    fname = os.path.join(temp_dir, filenames[0])
    _ = keras.preprocessing.image.load_img(fname)
    _ = keras.preprocessing.image.load_img(fname, grayscale=True)
    _ = keras.preprocessing.image.load_img(fname, target_size=(10, 10))
    _ = keras.preprocessing.image.load_img(fname, target_size=(10, 10),
                                           interpolation='bilinear')

    # create iterator
    generator = keras.preprocessing.image.ImageDataGenerator()
    dir_iterator = generator.flow_from_directory(temp_dir)

    # check number of classes and images
    self.assertEqual(len(dir_iterator.class_indices), num_classes)
    self.assertEqual(len(dir_iterator.classes), count)
    self.assertEqual(set(dir_iterator.filenames), set(filenames))

    def preprocessing_function(x):
      """This will fail if not provided by a Numpy array.

      Note: This is made to enforce backward compatibility.

      Args:
          x: A numpy array.

      Returns:
          An array of zeros with the same shape as the given array.
      """
      self.assertEqual(x.shape, (26, 26, 3))
      self.assertIs(type(x), np.ndarray)
      return np.zeros_like(x)

    # Test usage as Sequence
    generator = keras.preprocessing.image.ImageDataGenerator(
        preprocessing_function=preprocessing_function)
    dir_seq = generator.flow_from_directory(
        str(temp_dir),
        target_size=(26, 26),
        color_mode='rgb',
        batch_size=3,
        class_mode='categorical')
    self.assertEqual(len(dir_seq), count // 3 + 1)
    x1, y1 = dir_seq[1]
    self.assertEqual(x1.shape, (3, 26, 26, 3))
    self.assertEqual(y1.shape, (3, num_classes))
    x1, y1 = dir_seq[5]
    self.assertTrue((x1 == 0).all())

  def directory_iterator_with_validation_split_test_helper(
      self, validation_split):
    if PIL is None:
      return  # Skip test if PIL is not available.

    num_classes = 2
    tmp_folder = tempfile.mkdtemp(prefix='test_images')

    # create folders and subfolders
    paths = []
    for cl in range(num_classes):
      class_directory = 'class-{}'.format(cl)
      classpaths = [
          class_directory,
          os.path.join(class_directory, 'subfolder-1'),
          os.path.join(class_directory, 'subfolder-2'),
          os.path.join(class_directory, 'subfolder-1', 'sub-subfolder')
      ]
      for path in classpaths:
        os.mkdir(os.path.join(tmp_folder, path))
      paths.append(classpaths)

    # save the images in the paths
    count = 0
    filenames = []
    for test_images in _generate_test_images():
      for im in test_images:
        # rotate image class
        im_class = count % num_classes
        # rotate subfolders
        classpaths = paths[im_class]
        filename = os.path.join(classpaths[count % len(classpaths)],
                                'image-{}.jpg'.format(count))
        filenames.append(filename)
        im.save(os.path.join(tmp_folder, filename))
        count += 1

    # create iterator
    generator = keras.preprocessing.image.ImageDataGenerator(
        validation_split=validation_split)

    with self.assertRaises(ValueError):
      generator.flow_from_directory(tmp_folder, subset='foo')

    num_validation = int(count * validation_split)
    num_training = count - num_validation
    train_iterator = generator.flow_from_directory(
        tmp_folder, subset='training')
    self.assertEqual(train_iterator.samples, num_training)

    valid_iterator = generator.flow_from_directory(
        tmp_folder, subset='validation')
    self.assertEqual(valid_iterator.samples, num_validation)

    # check number of classes and images
    self.assertEqual(len(train_iterator.class_indices), num_classes)
    self.assertEqual(len(train_iterator.classes), num_training)
    self.assertEqual(
        len(set(train_iterator.filenames) & set(filenames)), num_training)

    shutil.rmtree(tmp_folder)

  def test_directory_iterator_with_validation_split_25_percent(self):
    self.directory_iterator_with_validation_split_test_helper(0.25)

  def test_directory_iterator_with_validation_split_40_percent(self):
    self.directory_iterator_with_validation_split_test_helper(0.40)

  def test_directory_iterator_with_validation_split_50_percent(self):
    self.directory_iterator_with_validation_split_test_helper(0.50)

  def test_img_utils(self):
    if PIL is None:
      return  # Skip test if PIL is not available.

    height, width = 10, 8

    # Test channels_first data format
    x = np.random.random((3, height, width))
    img = keras.preprocessing.image.array_to_img(
        x, data_format='channels_first')
    self.assertEqual(img.size, (width, height))
    x = keras.preprocessing.image.img_to_array(
        img, data_format='channels_first')
    self.assertEqual(x.shape, (3, height, width))
    # Test 2D
    x = np.random.random((1, height, width))
    img = keras.preprocessing.image.array_to_img(
        x, data_format='channels_first')
    self.assertEqual(img.size, (width, height))
    x = keras.preprocessing.image.img_to_array(
        img, data_format='channels_first')
    self.assertEqual(x.shape, (1, height, width))

    # Test channels_last data format
    x = np.random.random((height, width, 3))
    img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')
    self.assertEqual(img.size, (width, height))
    x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')
    self.assertEqual(x.shape, (height, width, 3))
    # Test 2D
    x = np.random.random((height, width, 1))
    img = keras.preprocessing.image.array_to_img(x, data_format='channels_last')
    self.assertEqual(img.size, (width, height))
    x = keras.preprocessing.image.img_to_array(img, data_format='channels_last')
    self.assertEqual(x.shape, (height, width, 1))

  def test_batch_standardize(self):
    if PIL is None:
      return  # Skip test if PIL is not available.

    # ImageDataGenerator.standardize should work on batches
    for test_images in _generate_test_images():
      img_list = []
      for im in test_images:
        img_list.append(keras.preprocessing.image.img_to_array(im)[None, ...])

      images = np.vstack(img_list)
      generator = keras.preprocessing.image.ImageDataGenerator(
          featurewise_center=True,
          samplewise_center=True,
          featurewise_std_normalization=True,
          samplewise_std_normalization=True,
          zca_whitening=True,
          rotation_range=90.,
          width_shift_range=0.1,
          height_shift_range=0.1,
          shear_range=0.5,
          zoom_range=0.2,
          channel_shift_range=0.,
          brightness_range=(1, 5),
          fill_mode='nearest',
          cval=0.5,
          horizontal_flip=True,
          vertical_flip=True)
      generator.fit(images, augment=True)

      transformed = np.copy(images)
      for i, im in enumerate(transformed):
        transformed[i] = generator.random_transform(im)
      transformed = generator.standardize(transformed)

  def test_img_transforms(self):
    x = np.random.random((3, 200, 200))
    _ = keras.preprocessing.image.random_rotation(x, 20)
    _ = keras.preprocessing.image.random_shift(x, 0.2, 0.2)
    _ = keras.preprocessing.image.random_shear(x, 2.)
    _ = keras.preprocessing.image.random_zoom(x, (0.5, 0.5))
    _ = keras.preprocessing.image.apply_channel_shift(x, 2, 2)
    _ = keras.preprocessing.image.apply_affine_transform(x, 2)
    with self.assertRaises(ValueError):
      keras.preprocessing.image.random_zoom(x, (0, 0, 0))
    _ = keras.preprocessing.image.random_channel_shift(x, 2.)

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

redpajama_set_name: RedPajamaGithub


text:
/**
 * Pipeline step to generate electron platform configuration.
 */
import { IFileSystem } from "unitejs-framework/dist/interfaces/IFileSystem";
import { ILogger } from "unitejs-framework/dist/interfaces/ILogger";
import { UniteConfiguration } from "../../configuration/models/unite/uniteConfiguration";
import { EngineVariables } from "../../engine/engineVariables";
import { PipelineStepBase } from "../../engine/pipelineStepBase";
export declare class Electron extends PipelineStepBase {
    private static readonly PLATFORM;
    private static readonly FILENAME;
    private static readonly FILENAME_MAIN_DEV;
    private static readonly FILENAME_MAIN_PROD;
    mainCondition(uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables): boolean | undefined;
    configure(logger: ILogger, fileSystem: IFileSystem, uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables, mainCondition: boolean): Promise<number>;
    finalise(logger: ILogger, fileSystem: IFileSystem, uniteConfiguration: UniteConfiguration, engineVariables: EngineVariables, mainCondition: boolean): Promise<number>;
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using log4net.Config;
using log4net.Repository.Hierarchy;

namespace HSLProcessor
{
    internal class Program
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

        public static int Main(string[] args)
        {
            try
            {
                // Configuration for logging
                var log4NetConfig = new XmlDocument();

                using (var reader = new StreamReader(new FileStream("log4net.config", FileMode.Open, FileAccess.Read)))
                {
                    log4NetConfig.Load(reader);
                }

                var rep = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(Hierarchy));
                XmlConfigurator.Configure(rep, log4NetConfig["log4net"]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Loggng error");
                Console.WriteLine(ex.Message);
                return -1;
            }

            try
            {
                Log.Debug("Starting the process.");

                // No argument
                if (args.Length == 0)
                {
                    Log.Error("Missing arguments!");
                    Console.WriteLine(
                        "Options are: importcsv, importxml, importseriescsv, exportxml, exportjson, generatehtml, generatesitemap, deleteitem, and list");
                    return -1;
                }

                switch (args[0])
                {
                    // Import
                    case "importcsv":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }

                        var result = Importer.ImportCsv(new FileInfo(args[1]));

                        if (result == Importer.ImportResult.Failed)
                        {
                            Log.Error("Import failed");

                            return -1;
                        }

                        break;
                    }

                    // List
                    case "list":
                    {
                        Lister.List();
                        break;
                    }

                    // Export to XML
                    case "exportxml":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }
                        Exporter.ExportXml(new FileInfo(args[1]));
                        break;
                    }

                    case "exportjson":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }

                        Exporter.ExportJson(new FileInfo(args[1]));
                        break;
                    }

                    case "generatesitemap":
                    {
                        if (args.Length < 3)
                        {
                            Log.Error("Missing arguments.\nUsage: file urlbase");
                            return -1;
                        }

                        PageGenerator.ExportSitemap(new FileInfo(args[1]), args[2]);
                        break;
                    }

                    // Import XML
                    case "importxml":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }
                        Importer.ImportXml(new FileInfo(args[1]));
                        break;
                    }

                    case "importseriescsv":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }
                        Importer.ImportSourceSeriesCsv(new FileInfo(args[1]));
                        break;
                    }

                    // Search
                    case "search":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }

                        // Get information for all
                        var (result1, hit1) = Searcher.Search(args[1], Searcher.SearchType.Title);
                        var (result2, hit2) = Searcher.Search(args[1], Searcher.SearchType.Artist);
                        var (result3, hit3) = Searcher.Search(args[1], Searcher.SearchType.Source);

                        // Merge the list
                        var hit = new List<Song>();
                        if (result1 == Searcher.SearchResult.Success &&
                            result1 == result2 &&
                            result2 == result3)
                        {
                            hit.AddRange(hit1);
                            hit.AddRange(hit2);
                            hit.AddRange(hit3);
                        }

                        // Uniquify + Sort
                        var uniqueList = hit.GroupBy(song => song.TitleId).Select(group => group.First()).ToList();
                        uniqueList = uniqueList.OrderBy(list => list.Title).ToList();
                        Lister.List(uniqueList.ToList());
                        break;
                    }

                    // Generate HTML static pages
                    case "generatehtml":
                    {
                        if (args.Length < 3)
                        {
                            Log.Error("Missing template and  file name.");
                            return -1;
                        }
                        PageGenerator.Generate(new DirectoryInfo(args[1]), new DirectoryInfo(args[2]));
                        break;
                    }

                    case "deleteitem":
                    {
                        if (args.Length < 2)
                        {
                            Log.Error("Missing file name.");
                            return -1;
                        }
                        Updater.Delete(new Guid(args[1]));
                        break;
                    }

                    // Other (invalid) options
                    default:
                    {
                        Log.Error("Unknown option.");
                        return -1;
                    }
                }

                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex.Message);
                Log.Debug(ex.StackTrace);
                return -1;
            }
        }
    }
}


text:
package org.thingsboard.server.dao.service;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.oauth2.MapperType;
import org.thingsboard.server.common.data.oauth2.OAuth2BasicMapperConfig;
import org.thingsboard.server.common.data.oauth2.OAuth2ClientRegistrationTemplate;
import org.thingsboard.server.common.data.oauth2.OAuth2MapperConfig;
import org.thingsboard.server.dao.exception.DataValidationException;
import org.thingsboard.server.dao.oauth2.OAuth2ConfigTemplateService;

import java.util.Arrays;
import java.util.UUID;

public abstract class BaseOAuth2ConfigTemplateServiceTest extends AbstractServiceTest {

    @Autowired
    protected OAuth2ConfigTemplateService oAuth2ConfigTemplateService;

    @Before
    public void beforeRun() throws Exception {
        Assert.assertTrue(oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().isEmpty());
    }

    @After
    public void after() throws Exception {
        oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().forEach(clientRegistrationTemplate -> {
            oAuth2ConfigTemplateService.deleteClientRegistrationTemplateById(clientRegistrationTemplate.getId());
        });

        Assert.assertTrue(oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().isEmpty());
    }

    @Test(expected = DataValidationException.class)
    public void testSaveDuplicateProviderId() {
        OAuth2ClientRegistrationTemplate first = validClientRegistrationTemplate("providerId");
        OAuth2ClientRegistrationTemplate second = validClientRegistrationTemplate("providerId");
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(first);
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(second);
    }

    @Test
    public void testCreateNewTemplate() {
        OAuth2ClientRegistrationTemplate clientRegistrationTemplate = validClientRegistrationTemplate(UUID.randomUUID().toString());
        OAuth2ClientRegistrationTemplate savedClientRegistrationTemplate = oAuth2ConfigTemplateService.saveClientRegistrationTemplate(clientRegistrationTemplate);

        Assert.assertNotNull(savedClientRegistrationTemplate);
        Assert.assertNotNull(savedClientRegistrationTemplate.getId());
        clientRegistrationTemplate.setId(savedClientRegistrationTemplate.getId());
        clientRegistrationTemplate.setCreatedTime(savedClientRegistrationTemplate.getCreatedTime());
        Assert.assertEquals(clientRegistrationTemplate, savedClientRegistrationTemplate);
    }

    @Test
    public void testFindTemplate() {
        OAuth2ClientRegistrationTemplate clientRegistrationTemplate = validClientRegistrationTemplate(UUID.randomUUID().toString());
        OAuth2ClientRegistrationTemplate savedClientRegistrationTemplate = oAuth2ConfigTemplateService.saveClientRegistrationTemplate(clientRegistrationTemplate);

        OAuth2ClientRegistrationTemplate foundClientRegistrationTemplate = oAuth2ConfigTemplateService.findClientRegistrationTemplateById(savedClientRegistrationTemplate.getId());
        Assert.assertEquals(savedClientRegistrationTemplate, foundClientRegistrationTemplate);
    }

    @Test
    public void testFindAll() {
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(validClientRegistrationTemplate(UUID.randomUUID().toString()));
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(validClientRegistrationTemplate(UUID.randomUUID().toString()));

        Assert.assertEquals(2, oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().size());
    }

    @Test
    public void testDeleteTemplate() {
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(validClientRegistrationTemplate(UUID.randomUUID().toString()));
        oAuth2ConfigTemplateService.saveClientRegistrationTemplate(validClientRegistrationTemplate(UUID.randomUUID().toString()));
        OAuth2ClientRegistrationTemplate saved = oAuth2ConfigTemplateService.saveClientRegistrationTemplate(validClientRegistrationTemplate(UUID.randomUUID().toString()));

        Assert.assertEquals(3, oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().size());
        Assert.assertNotNull(oAuth2ConfigTemplateService.findClientRegistrationTemplateById(saved.getId()));

        oAuth2ConfigTemplateService.deleteClientRegistrationTemplateById(saved.getId());

        Assert.assertEquals(2, oAuth2ConfigTemplateService.findAllClientRegistrationTemplates().size());
        Assert.assertNull(oAuth2ConfigTemplateService.findClientRegistrationTemplateById(saved.getId()));
    }

    private OAuth2ClientRegistrationTemplate validClientRegistrationTemplate(String providerId) {
        OAuth2ClientRegistrationTemplate clientRegistrationTemplate = new OAuth2ClientRegistrationTemplate();
        clientRegistrationTemplate.setProviderId(providerId);
        clientRegistrationTemplate.setAdditionalInfo(mapper.createObjectNode().put(UUID.randomUUID().toString(), UUID.randomUUID().toString()));
        clientRegistrationTemplate.setMapperConfig(OAuth2MapperConfig.builder()
                .type(MapperType.BASIC)
                .basic(OAuth2BasicMapperConfig.builder()
                        .firstNameAttributeKey("firstName")
                        .lastNameAttributeKey("lastName")
                        .emailAttributeKey("email")
                        .tenantNamePattern("tenant")
                        .defaultDashboardName("Test")
                        .alwaysFullScreen(true)
                        .build()
                )
                .build());
        clientRegistrationTemplate.setAuthorizationUri("authorizationUri");
        clientRegistrationTemplate.setAccessTokenUri("tokenUri");
        clientRegistrationTemplate.setScope(Arrays.asList("scope1", "scope2"));
        clientRegistrationTemplate.setUserInfoUri("userInfoUri");
        clientRegistrationTemplate.setUserNameAttributeName("userNameAttributeName");
        clientRegistrationTemplate.setJwkSetUri("jwkSetUri");
        clientRegistrationTemplate.setClientAuthenticationMethod("clientAuthenticationMethod");
        clientRegistrationTemplate.setComment("comment");
        clientRegistrationTemplate.setLoginButtonIcon("icon");
        clientRegistrationTemplate.setLoginButtonLabel("label");
        clientRegistrationTemplate.setHelpLink("helpLink");
        return clientRegistrationTemplate;
    }
}


text:
package org.apache.spark.sql.execution.datasources.jdbc

/**
 * Options for the JDBC data source.
 */
private[jdbc] class JDBCOptions(
    @transient private val parameters: Map[String, String])
  extends Serializable {

  // a JDBC URL
  val url = parameters.getOrElse("url", sys.error("Option 'url' not specified"))
  // name of table
  val table = parameters.getOrElse("dbtable", sys.error("Option 'dbtable' not specified"))
  // the column used to partition
  val partitionColumn = parameters.getOrElse("partitionColumn", null)
  // the lower bound of partition column
  val lowerBound = parameters.getOrElse("lowerBound", null)
  // the upper bound of the partition column
  val upperBound = parameters.getOrElse("upperBound", null)
  // the number of partitions
  val numPartitions = parameters.getOrElse("numPartitions", null)
}


text:
export const TAB_MAX_WIDTH = 240;
export const TAB_MIN_WIDTH = 72;
export const TAB_PINNED_WIDTH = 40;
export const TAB_ANIMATION_DURATION = 200;
export const TABS_PADDING = 2;


text: mongod --config C:\data\mongo\cfg\cfg_cnf\cfg_1.conf


text:
/**
 * index route
 */
'use strict';
var router = require('koa-router')();
var ctrls = require('../controllers');
var logger = require('../logger');
var redis = require('../db/redis').redis;
var _ = require('lodash');
var CONSTANTS = require('../const');
var filter = require('../middlewares/filter');

module.exports = function (app) {
  router.get('/', function *() {
    this.body = "Hello welcome to the <%- project_name %>";
  });
  router.get('/api/version', ctrls.version);

  app.use(router.middleware());
};


text:
Basic community patch for fixing a crash occuring during multiplayer games in
Heroes of Might and Magic HD Edition. CRT not used, compiles to a ~5KB .exe

#### How to use
1. Start HD Edition
2. Start hde_mp_crashfix.exe
3. Play multiplayer

### Disclaimer
This patch is not official and is not endorsed by anyone.

Heroes, Might and Magic, Heroes of Might and Magic, Ubisoft and the Ubisoft
logo are trademarks of Ubisoft Entertainment in the U.S. and/or other countries.


text:
require 'hanitizer/generator'

module Hanitizer
  RSpec.describe Generator::Address1 do
    subject(:generator) { described_class.new }

    describe '#generate' do
      let(:row) { Hash.new }

      it 'generates a fake address (line1)' do
        expect(Faker::Address).to receive(:street_address)
        generator.generate(row)
      end
    end
  end
end


text:
"""
This is an example that demonstrates how to use a
servo with BreakfastSerial. It assumes you have a
servo wired up to pin 10.
"""
from BreakfastSerial import Arduino, Servo
from time import sleep

board = Arduino()
servo = Servo(board,10)

servo.set_position(180)
sleep(2)
servo.move(-135)
sleep(2)
servo.center()
sleep(2)
servo.reset()

# Run an interactive shell so you can play (not required)
import code
code.InteractiveConsole(locals=globals()).interact()


text:
using namespace IMPL;
using namespace EVENT;

namespace UTIL{

  enum ObjectType {
    Cluster = 1 ,
    ReconstructedParticle
  } ;

  PIDHandler::PIDHandler( LCCollection* col ) :
    _col( col) ,
    _cpm( "PIDAlgorithmTypeName",  "PIDAlgorithmTypeID" ,  col ),
    _type(-1) ,
    _maxID(-1) {

    init( col ) ;
  }

  PIDHandler::PIDHandler(  const LCCollection* col ) :
    _col( 0 ) , // not needed
    _cpm( "PIDAlgorithmTypeName",  "PIDAlgorithmTypeID" ,  col ),
    _type(-1) ,
    _maxID(-1) {

    init( col ) ;
  }

 void  PIDHandler::init(  const LCCollection* col ) {

    // ---- get the information on existing ParticleID objects ----------

    for( CPM::map_type::iterator it = _cpm.map().begin() ; it != _cpm.map().end() ; ++it) {

      int id = it->second ;

      const std::string& aName =  it->first ;

      if( id > _maxID )
	_maxID = id ;

      // ensure id is unique for collection
      PNM::iterator nit = _pNames.find( id ) ;

      if( nit != _pNames.end() ){

	std::stringstream sstr ;

	sstr << " PIDHandler::PIDHandler() - duplicate algorithm type IDs: "
	     <<  aName << " [" << id << "] " ;

	throw Exception( sstr.str() ) ;

      }

      // get parameter names

      StringVec pNames ;

      col->getParameters().getStringVals( std::string( "ParameterNames_" + aName   ) , pNames ) ;

      _pNames[ id ] = pNames ;  // save a copy of parameter names for algorithm with id

      _ids.push_back( id ) ;

      //   save inverse map for lookup algoName from algoID

      _cpmInv.insert( std::make_pair( id  , aName )  ) ;

    }

    //------------------------------------------------

    // determine LCCollection type
    std::string colType = col->getTypeName()  ;

    //  arghhh ...
    if( colType == LCIO::RECONSTRUCTEDPARTICLE ) {

      _type = ReconstructedParticle ;

    } else if( colType == LCIO::CLUSTER ){

      _type = Cluster ;

    } else {

      throw Exception( "PIDHandler::PIDHandler() "
		       " collection type is neither Cluster nor ReconstructedParticle ") ;
    }
  }

  PIDHandler::~PIDHandler() {

    if (_col != 0 ) {
      // save the collection parameters

      for( PNM::iterator pnm = _pNames.begin() ; pnm != _pNames.end() ; ++pnm) {

	int id = pnm->first ;

	_col->parameters().setValues( std::string( "ParameterNames_" + _cpmInv[id]  ) ,
				      pnm->second ) ;
      }
    }
  }

  int PIDHandler::addAlgorithm( const std::string& algoName, const StringVec& pNames ) {

    CPM::map_type& map = _cpm.map() ;

    CPM::map_type::iterator it = map.find( algoName ) ;

    if( it != map.end() ){

      std::stringstream sstr ;

      sstr << " PIDHandler::addAlgorithm() - duplicate algorithm name: "
	   <<  algoName ;

      throw Exception( sstr.str() ) ;
    }

    int id  =  nextID() ;

    map.insert( std::make_pair( algoName , id ) ) ;

    // inverse map:
    _cpmInv.insert( std::make_pair( id  , algoName )  ) ;

    // save parameter names
    _pNames[ id ] = pNames ;

    _ids.push_back( id ) ;

    return id ;
  }

  int PIDHandler::getAlgorithmID( const std::string& algoName ) {

    CPM::map_type::iterator it = _cpm.map().find( algoName ) ;

    if( it == _cpm.map().end() ){

      throw UnknownAlgorithm(  algoName ) ;
    }

    return it->second ;
  }

  const std::string& PIDHandler::getAlgorithmName(  int algoID ) {

    CPMINV::iterator it = _cpmInv.find( algoID ) ;

    if( it == _cpmInv.end() ){

      std::stringstream ss ; ss << algoID ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    return it->second ;
  }

  int PIDHandler::getParameterIndex( int algorithmID, const std::string& name ) {

    PNM::iterator nit = _pNames.find( algorithmID ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << algorithmID ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }
    // brute force search:

    const StringVec& names =  nit->second ;

    unsigned n = names.size() ;

    for(unsigned i=0 ; i<n ; ++i){

      if( names[i] == name )

	return i ;
    }

    return -1 ; // or better throw sth. ?
  }

  const StringVec&  PIDHandler::getParameterNames( int id  ) {

    PNM::iterator nit = _pNames.find( id ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << id ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    return nit->second ;
  }

  const IntVec& PIDHandler::getAlgorithmIDs() {

    return _ids ;
  }

  void PIDHandler::setParticleIDUsed(  ReconstructedParticleImpl* p , int id  ) {

    PNM::iterator nit = _pNames.find( id ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << id ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    ParticleID* pid = 0 ;

//     const ParticleIDVec* idv = 0 ;
//     if( _type == ReconstructedParticle  ){

//       idv = &( static_cast< ReconstructedParticleImpl* >(p)->getParticleIDs()  ) ;
//     }
//     else if( _type == Cluster  ){

//       idv = &( static_cast< ClusterImpl* >(p)->getParticleIDs()  ) ;
//     }
//     const ParticleIDVec& pidV = *idv ;

    const ParticleIDVec& pidV = p->getParticleIDs() ;

    unsigned nPid = pidV.size() ;

    for(unsigned i=0; i<nPid; ++i ) {

      if( pidV[i]->getAlgorithmType() == id ) {

	pid = pidV[i]  ;
	break ;

      }
    }

    if( pid == 0 ) {
      std::stringstream err ;
      err << "pid object not found in particle for algorithmId: "<< id ;
      throw UnknownAlgorithm( err.str() ) ;
    }

    p->setParticleIDUsed( pid ) ;

  }

  ParticleIDVec PIDHandler::getParticleIDs( LCObject* p , int id ) {

    PNM::iterator nit = _pNames.find( id ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << id ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    const ParticleIDVec* idv = 0 ;

    if( _type == ReconstructedParticle  ){

      idv = &( static_cast< ReconstructedParticleImpl* >(p)->getParticleIDs()  ) ;
    }
    else if( _type == Cluster  ){

      idv = &( static_cast< ClusterImpl* >(p)->getParticleIDs()  ) ;
    }
    else{

      throw Exception("PIDHandler::getParticleID LCObject is neither  ReconstructedParticleImpl nor ClusterImpl !") ;
    }

    const ParticleIDVec& pidV = *idv ;

    ParticleIDVec pidVID ;

    unsigned nPid = pidV.size() ;

    for(unsigned i=0; i<nPid; ++i ) {

      if( pidV[i]->getAlgorithmType() == id )

	pidVID.push_back( pidV[i] ) ;

    }

    return pidVID ;
  }

  const ParticleID& PIDHandler::getParticleID( LCObject* p , int id ) {

    PNM::iterator nit = _pNames.find( id ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << id ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    const ParticleIDVec* idv = 0 ;

    if( _type == ReconstructedParticle  ){

      idv = &( static_cast< ReconstructedParticleImpl* >(p)->getParticleIDs()  ) ;
    }
    else if( _type == Cluster  ){

      idv = &( static_cast< ClusterImpl* >(p)->getParticleIDs()  ) ;
    }
    else{

      throw Exception("PIDHandler::getParticleID LCObject is neither  ReconstructedParticleImpl nor ClusterImpl !") ;
    }

    const ParticleIDVec& pidV = *idv ;

    unsigned nPid = pidV.size() ;

    for(unsigned i=0; i<nPid; ++i ) {

      if( pidV[i]->getAlgorithmType() == id )

	return *pidV[i] ;

    }

    // nothing found - return a dummy ParticleID object

    static const ParticleIDImpl dummyPID ;
    return dummyPID ;
  }

  void PIDHandler::setParticleID( LCObject* p ,
				  int userType,
				  int PDG,
				  float likelihood,
				  int id,
				  const FloatVec& params ) {

    PNM::iterator nit = _pNames.find( id ) ;

    if( nit == _pNames.end() ){

      std::stringstream ss ; ss << id ;
      throw UnknownAlgorithm( ss.str().c_str()  ) ;
    }

    // ---- check paramaters size -----
    unsigned nParam =  params.size()  ;

    if( nParam != _pNames[ id ].size() ) {

      std::stringstream sstr ;

      sstr << " PIDHandler::setParticleID() - wrong parmeter size specified: "
	   <<  nParam << " - expected " << _pNames[ id ].size()  ;

      throw Exception( sstr.str() ) ;

    }

    ParticleIDImpl* pid = 0 ;

    const ParticleIDVec* idv = 0 ;

    if( _type == ReconstructedParticle  ){

      idv = &( static_cast< ReconstructedParticleImpl* >(p)->getParticleIDs()  ) ;
    }
    else if( _type == Cluster  ){

      idv = &( static_cast< ClusterImpl* >(p)->getParticleIDs()  ) ;
    }
    else{

      throw Exception("PIDHandler::setParticleID LCObject is neither  ReconstructedParticleImpl nor ClusterImpl !") ;
    }

    const ParticleIDVec& pidV = *idv ;

    unsigned nPid = pidV.size() ;

    for(unsigned i=0; i<nPid; ++i ) {

      if( pidV[i]->getAlgorithmType() == id ) {

	pid = static_cast<ParticleIDImpl*>( pidV[i] ) ;
	break ;

      }
    }

    // if nothing found we create a new object

    bool isNewPID = false ;

    if( pid == 0 ) {

      pid = new ParticleIDImpl ;

      isNewPID = true ;

    }

    // ---- now set the PID data ------------

    pid->setLikelihood( likelihood ) ;

    pid->setType( userType ) ;

    pid->setPDG( PDG ) ;

    pid->setAlgorithmType( id ) ;

    FloatVec& ps = pid->parameters() ;

    ps.resize( nParam ) ;

    for(unsigned k=0; k< nParam  ; k++){

      ps[ k ] = params[ k ] ;
    }

    // ----------------------------------------

    if( isNewPID ) { // need to add it to the particle/cluster

      if( _type == ReconstructedParticle  ){

	static_cast< ReconstructedParticleImpl* >(p)->addParticleID( pid ) ;
      }
      else if( _type == Cluster  ){

	static_cast< ClusterImpl* >(p)->addParticleID( pid )  ;
      }
    }

  }
}


text:
package org.consumersunion.stories.dashboard.client.application.questionnaire;

import org.consumersunion.stories.dashboard.client.application.questionnaire.ui.QuestionnaireUiModule;
import org.consumersunion.stories.dashboard.client.application.questionnaire.widget.QuestionnaireWidgetModule;

import com.gwtplatform.mvp.client.gin.AbstractPresenterModule;

public class QuestionnaireModule extends AbstractPresenterModule {
    @Override
    protected void configure() {
        install(new QuestionnaireUiModule());
        install(new QuestionnaireWidgetModule());
    }
}


text:
    <?php
    $this->widget('zii.widgets.CMenu',array(
        'htmlOptions' => array('class' => 'nav nav-pills nav-stacked hidden-print'),
        'activeCssClass'	=> 'active',
        'submenuHtmlOptions' => array('class' => 'dropdown-menu'),
        'encodeLabel' => false,
        'items'=>array(
            array('label'=>'Ordenes', 'url'=>array('report/ordenes')),
            array('label'=>'Placas', 'url'=>array('report/placas')),
            array('label'=>'Deudas', 'url'=>array('report/deuda')),
        )));
    ?>


text:
package org.neo4j.driver.internal.cluster;

import static org.neo4j.driver.Values.parameters;
import static org.neo4j.driver.internal.DatabaseNameUtil.defaultDatabase;
import static org.neo4j.driver.internal.handlers.pulln.FetchSizeUtil.UNLIMITED_FETCH_SIZE;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import org.neo4j.driver.AccessMode;
import org.neo4j.driver.Bookmark;
import org.neo4j.driver.Query;
import org.neo4j.driver.Record;
import org.neo4j.driver.TransactionConfig;
import org.neo4j.driver.async.ResultCursor;
import org.neo4j.driver.exceptions.ClientException;
import org.neo4j.driver.exceptions.FatalDiscoveryException;
import org.neo4j.driver.internal.DatabaseName;
import org.neo4j.driver.internal.async.connection.DirectConnection;
import org.neo4j.driver.internal.messaging.BoltProtocolVersion;
import org.neo4j.driver.internal.spi.Connection;
import org.neo4j.driver.internal.util.Futures;

/**
 * This implementation of the {@link RoutingProcedureRunner} works with single database versions of Neo4j calling
 * the procedure `dbms.cluster.routing.getRoutingTable`
 */
public class SingleDatabaseRoutingProcedureRunner implements RoutingProcedureRunner {
    static final String ROUTING_CONTEXT = "context";
    static final String GET_ROUTING_TABLE = "CALL dbms.cluster.routing.getRoutingTable($" + ROUTING_CONTEXT + ")";

    final RoutingContext context;

    public SingleDatabaseRoutingProcedureRunner(RoutingContext context) {
        this.context = context;
    }

    @Override
    public CompletionStage<RoutingProcedureResponse> run(
            Connection connection, DatabaseName databaseName, Set<Bookmark> bookmarks, String impersonatedUser) {
        DirectConnection delegate = connection(connection);
        Query procedure = procedureQuery(connection.protocol().version(), databaseName);
        return runProcedure(delegate, procedure, adaptBookmarks(bookmarks))
                .thenCompose(records -> releaseConnection(delegate, records))
                .handle((records, error) -> processProcedureResponse(procedure, records, error));
    }

    DirectConnection connection(Connection connection) {
        return new DirectConnection(connection, defaultDatabase(), AccessMode.WRITE, null);
    }

    Query procedureQuery(BoltProtocolVersion protocolVersion, DatabaseName databaseName) {
        if (databaseName.databaseName().isPresent()) {
            throw new FatalDiscoveryException(String.format(
                    "Refreshing routing table for multi-databases is not supported over Bolt protocol lower than 4.0. "
                            + "Current protocol version: %s. Database name: '%s'",
                    protocolVersion, databaseName.description()));
        }
        return new Query(GET_ROUTING_TABLE, parameters(ROUTING_CONTEXT, context.toMap()));
    }

    Set<Bookmark> adaptBookmarks(Set<Bookmark> bookmarks) {
        return Collections.emptySet();
    }

    CompletionStage<List<Record>> runProcedure(Connection connection, Query procedure, Set<Bookmark> bookmarks) {
        return connection
                .protocol()
                .runInAutoCommitTransaction(
                        connection,
                        procedure,
                        bookmarks,
                        (ignored) -> {},
                        TransactionConfig.empty(),
                        UNLIMITED_FETCH_SIZE)
                .asyncResult()
                .thenCompose(ResultCursor::listAsync);
    }

    private CompletionStage<List<Record>> releaseConnection(Connection connection, List<Record> records) {
        // It is not strictly required to release connection after routing procedure invocation because it'll
        // be released by the PULL_ALL response handler after result is fully fetched. Such release will happen
        // in background. However, releasing it early as part of whole chain makes it easier to reason about
        // rediscovery in stub server tests. Some of them assume connections to instances not present in new
        // routing table will be closed immediately.
        return connection.release().thenApply(ignore -> records);
    }

    private static RoutingProcedureResponse processProcedureResponse(
            Query procedure, List<Record> records, Throwable error) {
        Throwable cause = Futures.completionExceptionCause(error);
        if (cause != null) {
            return handleError(procedure, cause);
        } else {
            return new RoutingProcedureResponse(procedure, records);
        }
    }

    private static RoutingProcedureResponse handleError(Query procedure, Throwable error) {
        if (error instanceof ClientException) {
            return new RoutingProcedureResponse(procedure, error);
        } else {
            throw new CompletionException(error);
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class WarriorWhirlwind : AbilityScript {

    public float rotationVel = 720.0f;
    public float actionDuration = 1.0f;
    public float cooldownDuration = 0.3f;
    public bool firstFrameActivation;

    Quaternion targetRotation;
    BoxCollider whirlwindCollider;
    Transform whirlwindTransform;
    PlayerController playerController;
  public  float cooldownTimer;
    float actionTimer;
    public int inUse_ready_onCooldown;

    Animator anim;

    void Start()
    {
        if (GameObject.FindGameObjectWithTag("WarriorWhirlwindCollider"))
        {
            whirlwindTransform = GameObject.FindGameObjectWithTag("WarriorWhirlwindCollider").GetComponent<Transform>();

            if (GameObject.FindGameObjectWithTag("WarriorWhirlwindCollider").GetComponent<BoxCollider>())
            {
                whirlwindCollider = GameObject.FindGameObjectWithTag("WarriorWhirlwindCollider").GetComponent<BoxCollider>();
            }
            else
                Debug.LogError("The object tagged WarriorWhirlwindCollider needs a box collider component.");
        }
        else
            Debug.LogError("There needs to be an object tagged WarriorWhirlwindCollider in the scene.");

        if (GetComponent<PlayerController>())
        {
            playerController = GetComponent<PlayerController>();
        }
        else
            Debug.LogError("The unit with this script attached needs to have a player controller.");

        if (GetComponent<Animator>())
            anim = GetComponent<Animator>();

        targetRotation = whirlwindTransform.rotation;

    }

    void Update()
    {
        if (inUse_ready_onCooldown == 1)
            UpdateActionTimer();
        if (inUse_ready_onCooldown == -1)
            UpdateCooldownTimer();
    }

    void FixedUpdate()
    {
        Run();
    }

    void Run()
    {
        if (firstFrameActivation && inUse_ready_onCooldown == 0)
            ActivateAction();
        else if (inUse_ready_onCooldown == 1)
        {
            targetRotation *= Quaternion.AngleAxis(rotationVel * Time.deltaTime, Vector3.up);
            whirlwindTransform.rotation = targetRotation;
        }
    }

    void ActivateAction()
    {
        FindObjectOfType<SwordController>().dynamicCollider = false;
        FindObjectOfType<ComboSystem>().EndSlash3();
        inUse_ready_onCooldown = 1;
        whirlwindCollider.enabled = true;
        firstFrameActivation = false;

        anim.Play(Animator.StringToHash("Base Layer.Whirlwind1"));

        playerController.getInput = false;
    }

    void FinishAction()
    {
        inUse_ready_onCooldown = -1;
        whirlwindCollider.enabled = false;
        whirlwindTransform.rotation = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
        cooldownTimer = 0.0f;
        actionTimer = 0.0f;

        playerController.getInput = true;
    }

    void UpdateActionTimer()
    {
        actionTimer += Time.deltaTime;
        if (actionTimer >= actionDuration)
        {
            FinishAction();
        }
    }

    void UpdateCooldownTimer()
    {
        cooldownTimer += Time.deltaTime;

        if (cooldownTimer >= cooldownDuration)
        {
            inUse_ready_onCooldown = 0;
            firstFrameActivation = false;
            cooldownTimer = 0;
        }
    }
}


text:
'use strict';

module.exports = function (grunt, sharedConfig) {

    var _utilities = require('./utilities')(grunt, sharedConfig);
    var _js = require('./javascript')(grunt, sharedConfig);
    var _css = require('./css')(grunt, sharedConfig);
    var _images = require('./images')(grunt, sharedConfig);
    var _server = require('./server')(grunt, sharedConfig);

    /**
    * Watch
    * https://github.com/gruntjs/grunt-contrib-watch
    * Watches your scss, js etc for changes and compiles them
    */
    var _config = {

        watch: {

            js : {
                files : [_js.paths.distDir + _js.paths.distFile],
                tasks : _js.tasks.compile.test.concat(_utilities.tasks.copy.statix.js)
            },

            testJs : {
                files : [_js.paths.testBinDir + _js.paths.testSpecFile],
                tasks : _js.tasks.test.all
            },

            scss : {
                files : [_css.paths.srcDir + '**/*.scss'],
                tasks : _css.tasks.compile.dev.concat(_utilities.tasks.copy.statix.css),
                options: {
                    interrupt: true,
                    // spawn: false
                }
            },

            images : {
                files : [
                    _images.paths.srcDir + '**/*.{svg,png,jpg,gif}',
                    '!' + _images.paths.grunticonSrcDir + '**/*' // ignore the grunticon directory
                ],
                tasks : _images.tasks.compile.images.dev.concat(_utilities.tasks.copy.statix.img),
                options: {
                    interrupt: true
                }
            },

            grunticon : {
                files : [
                    _images.paths.grunticonSrcDir + '**/*.{svg,png,jpg,gif}',
                    '_grunt-configs/images.js'
                ],
                tasks : _images.tasks.compile.icons.dev.concat(_utilities.tasks.copy.statix.img),
                options: {
                    interrupt: true
                }
            },

            grunt : {
                files : ['_grunt-configs/*.js', 'Gruntfile.js'],
                options: {
                    reload: true
                }
            },

            assemble : {
                files : [_server.paths.statixTemplatesDir + '**/*.{hbs,md}'],
                tasks : _server.tasks.compile.statix.dev,//.concat(_utilities.tasks.copy.statix.dev),

                options: {
                    livereload: true
                }
            }
        }
    };

    return {
        config : _config
    };
};


text:
package gram_zico.artist;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import java.util.ArrayList;

import gram_zico.artist.Model.IntentDataModel;

/**
 * Created by root1 on 2017. 9. 11..
 */

public class BaseActivity extends AppCompatActivity {
    public void goNextActivity(Class nextClass, @Nullable ArrayList<IntentDataModel> datas){
        Intent intent = new Intent(this, nextClass);
        if(datas != null){
            for(IntentDataModel data : datas){
                intent.putExtra(data.getKey(), data.getValue());
            }
        }
        startActivity(intent);
        this.finish();
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        showToast("뒤로가기를 하실 수 없습니다.");
    }

    public void showToast(String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public  <T> T setViewById (int id){
        return (T)findViewById(id);
    }
}


text:
import { describe, it } from 'mocha';
import { expectPassesRule, expectFailsRule } from './harness';
import {
  NoUnusedFragments,
  unusedFragMessage,
} from '../rules/NoUnusedFragments';

function unusedFrag(fragName, line, column) {
  return {
    message: unusedFragMessage(fragName),
    locations: [{ line, column }],
    path: undefined,
  };
}

describe('Validate: No unused fragments', () => {
  it('all fragment names are used', () => {
    expectPassesRule(
      NoUnusedFragments,
      `
      {
        human(id: 4) {
          ...HumanFields1
          ... on Human {
            ...HumanFields2
          }
        }
      }
      fragment HumanFields1 on Human {
        name
        ...HumanFields3
      }
      fragment HumanFields2 on Human {
        name
      }
      fragment HumanFields3 on Human {
        name
      }
    `,
    );
  });

  it('all fragment names are used by multiple operations', () => {
    expectPassesRule(
      NoUnusedFragments,
      `
      query Foo {
        human(id: 4) {
          ...HumanFields1
        }
      }
      query Bar {
        human(id: 4) {
          ...HumanFields2
        }
      }
      fragment HumanFields1 on Human {
        name
        ...HumanFields3
      }
      fragment HumanFields2 on Human {
        name
      }
      fragment HumanFields3 on Human {
        name
      }
    `,
    );
  });

  it('contains unknown fragments', () => {
    expectFailsRule(
      NoUnusedFragments,
      `
      query Foo {
        human(id: 4) {
          ...HumanFields1
        }
      }
      query Bar {
        human(id: 4) {
          ...HumanFields2
        }
      }
      fragment HumanFields1 on Human {
        name
        ...HumanFields3
      }
      fragment HumanFields2 on Human {
        name
      }
      fragment HumanFields3 on Human {
        name
      }
      fragment Unused1 on Human {
        name
      }
      fragment Unused2 on Human {
        name
      }
    `,
      [unusedFrag('Unused1', 22, 7), unusedFrag('Unused2', 25, 7)],
    );
  });

  it('contains unknown fragments with ref cycle', () => {
    expectFailsRule(
      NoUnusedFragments,
      `
      query Foo {
        human(id: 4) {
          ...HumanFields1
        }
      }
      query Bar {
        human(id: 4) {
          ...HumanFields2
        }
      }
      fragment HumanFields1 on Human {
        name
        ...HumanFields3
      }
      fragment HumanFields2 on Human {
        name
      }
      fragment HumanFields3 on Human {
        name
      }
      fragment Unused1 on Human {
        name
        ...Unused2
      }
      fragment Unused2 on Human {
        name
        ...Unused1
      }
    `,
      [unusedFrag('Unused1', 22, 7), unusedFrag('Unused2', 26, 7)],
    );
  });

  it('contains unknown and undef fragments', () => {
    expectFailsRule(
      NoUnusedFragments,
      `
      query Foo {
        human(id: 4) {
          ...bar
        }
      }
      fragment foo on Human {
        name
      }
    `,
      [unusedFrag('foo', 7, 7)],
    );
  });
});


text:
title: "ZDISCORDS"
layout: function
desc: "Detects discords in a standardized Geo Time Series."
category: "reference"
---

The `ZDISCORDS` function detects discords in a standardized Geo Time Series. The discord detection algorithm is based on identifying outlier patterns in the Geo Time Series. Outliers are patterns which differ significantly from their nearest neighbor.

The function expects a distance ratio on top of the stack, this ratio is used to ignore patterns whose distance to their nearest neighbor is less than 1/ratio that of the previously selected pattern. This parameter is for advanced users, it is safe to leave it to 0.0.

The next parameter expected is a boolean flag indicating whether or not the `DISCORDS` function should report overlapping discords.

The next parameter is the maximum number of discords to identify.

The next parameters are identical to those of [PATTERNS]({{site.baseurl}}/reference/functions/function_PATTERNS), a *window size* which is the width of each interval on which the pattern extraction should be performed, a *pattern length* which will determine how the window is segmented, and lastly a *quantization scale* which will determine how many different buckets will be used to ventilate the series values.

The following constraints are enforced:

* *pattern length* must divide *wind ow size*
* *quantization scale* must be a power of two from 2 to 65536
* `DISCORDS` can only be applied to numeric Geo Time Series which are bucketized and filled (*i.e.* no bucket with missing values).

The result of the discord detection is a Geo Time Series whose ticks are those where discords were detected. The value, location and elevation at each tick are those of the input Geo Time Series.

Given the `ZDISCORDS` expects the Geo Time Series it operates on to be standardized, the discord detection algorithm is more sensitive than that of [`DISCORDS`]({{site.baseurl}}/reference/functions/function_DISCORDS)..

## Example ##

{% raw %}
<warp10-warpscript-widget backend="{{backend}}"  exec-endpoint="{{execEndpoint}}">NEWGTS
1 7200
// Add datapoint, with 0.1% of anomalies
<% DUP 2 * PI * 360 / SIN <% RAND 0.01 < %> <% 0.001 + %> IFT NaN DUP DUP 4 ROLL ADDVALUE %> FOR
[ SWAP bucketizer.last 720 1 0 ] BUCKETIZE
STANDARDIZE
32 8 16 5 false 0.0 ZDISCORDS
</warp10-warpscript-widget>
{% endraw %}


text:
{% extends 'admin/change_list.html' %}

{% load prefixed_i18n %}

{% block object-tools-items %}
    {% include 'themes/suit/base/mtr/sync/admin/object_tools.html' with version='1.6' admin=cl.model_admin %}
    {{ block.super }}
{% endblock %}