text:
const chai = require('chai');
const grandiloquent = require('./../grandiloquent.js');
chai.should();

describe('Pronoun', () => {
  describe('plural to singular', () => {
    it('should convert 3rd person pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('they')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('he');
    });

    it('should convert 3rd person female pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('they')
        .setGender('female')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('she');
    });

    it('should convert 3rd person male or female pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('they')
        .setGender('or')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('he or she');
    });

    it('should convert 3rd person male or female pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('they')
        .setGender('slash')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('he/she');
    });

    it('should convert 1st person pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('we')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('I');
    });

    it('should convert 2nd person pronoun', () => {
      let pronoun = grandiloquent
        .pronoun('you')
        .toSingular()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('you');
    });
  });

  describe('change person', () => {
    it('should convert to 1st person', () => {
      let pronoun = grandiloquent
        .pronoun('he')
        .toFirstPerson()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('I');
    });

    it('should convert to 2nd person', () => {
      let pronoun = grandiloquent
        .pronoun('we')
        .toSecondPerson()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('you');
    });

    it('should convert to 3rd person', () => {
      let pronoun = grandiloquent
        .pronoun('I')
        .setGender('or')
        .toThirdPerson()
        .toString();
      pronoun.should.be.a('string');
      pronoun.should.equal('he or she');
    });
  });

  describe('meta', () => {
    it('should get the gender', () => {
      let pronoun = grandiloquent
        .pronoun('he')
        .getGender();
      pronoun.should.be.a('string');
      pronoun.should.equal('male');
    });

    it('should get the person', () => {
      let pronoun = grandiloquent
        .pronoun('he')
        .getPerson();
      pronoun.should.be.a('number');
      pronoun.should.equal(3);
    });
  });
});


text:
import * as utils from './../utils';
import * as templates from './../templates';
import { messages, events, classTypes } from './../constantes';

export class Presenter {

    constructor(resourceContainer) {

        this.resourceContainer = resourceContainer;
    }

    initialize() {

        this.setMainContentTopMargin();
        this.showFlashMessage();

        this.update();
    }

    setMainContentTopMargin() {

        let menusHeight = $('#menus-bar').height();
        $("#main-content").css('margin-top', menusHeight + 20);
    }

    showFlashMessage() {

        let errorFlashMessage = $(".flash_error").find('p').first();
        let successFlashMessage = $(".flash_success").find('p').first();

        if (errorFlashMessage.length > 0) {
            utils.notify(errorFlashMessage[0].textContent, classTypes.ERROR);
        }

        if (successFlashMessage.length > 0) {
            utils.notify(successFlashMessage[0].textContent);
        }
    }

    update() {

    }

    notifyDeletion() {

        let message = messages.DELETION_SUCCESS;
        utils.notify(message, "success", templates.cancelButton);
    }

    setEmptyMessage() {

        if (0 === $('#empty-message').length) {

            $('#main-content').append(templates.emptyMessage);
        }
    }

    hideElements(elements) {

        utils.hideElements($(elements));
    }

    hideResourcesById(ids) {

        let resources = this.resourceContainer.getResourcesById(ids);
        utils.hideElements($(resources));
    }

    unhideElements(elements) {

        $(elements).each(function () {

            $(this).show();
            $(this).removeAttr('style'); // jquery rajoute un 'display block' qui perturbe les filtres
            utils.animate($(this));
        });

        $(document).trigger(events.DOM_UPDATED);
    }

    showModal(modal) {

        $(document.body).prepend(modal);
        $("#myModal").modal('show');
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file   IConfigurationListener.java
 *
 * @brief  This file provides interface for receiving asynchronous response for
 *        configuration APIs.
 */

package org.iotivity.service.tm;

import java.util.Vector;

import org.iotivity.base.OcHeaderOption;
import org.iotivity.base.OcRepresentation;

/**
 * Provides interface for receiving asynchronous response for
 * configuration APIs.
 */
public interface IConfigurationListener {
    /**
     * Asynchronous response callback for ThingsManager::doBootstrap API.
     */
    public void onBootStrapCallback(Vector<OcHeaderOption> headerOptions,
            OcRepresentation rep, int errorValue);

    /**
     * Asynchronous response callback for ThingsManager::updateConfigurations
     * API.
     */
    public void onUpdateConfigurationsCallback(
            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
            int errorValue);

    /**
     * Asynchronous response callback for ThingsManager::getConfigurations API.
     */
    public void onGetConfigurationsCallback(
            Vector<OcHeaderOption> headerOptions, OcRepresentation rep,
            int errorValue);
}


text:
package org.apache.solr.highlight;

import java.util.HashMap;
import java.util.Map;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.handler.component.HighlightComponent;
import org.junit.BeforeClass;
import org.junit.Test;

public class FastVectorHighlighterTest extends SolrTestCaseJ4 {

  @BeforeClass
  public static void beforeClass() throws Exception {
    initCore("solrconfig.xml", "schema.xml");
  }

  @Test
  public void testConfig() {
    DefaultSolrHighlighter highlighter = getHighlighter();

    // Make sure we loaded one fragListBuilder
    SolrFragListBuilder solrFlbNull = highlighter.fragListBuilders.get(null);
    SolrFragListBuilder solrFlbEmpty = highlighter.fragListBuilders.get("");
    SolrFragListBuilder solrFlbSimple = highlighter.fragListBuilders.get("simple");
    assertSame(solrFlbNull, solrFlbEmpty);
    assertTrue(solrFlbNull instanceof SimpleFragListBuilder);
    assertTrue(solrFlbSimple instanceof SimpleFragListBuilder);

    // Make sure we loaded two fragmentsBuilders
    SolrFragmentsBuilder solrFbNull = highlighter.fragmentsBuilders.get(null);
    SolrFragmentsBuilder solrFbEmpty = highlighter.fragmentsBuilders.get("");
    SolrFragmentsBuilder solrFbSimple = highlighter.fragmentsBuilders.get("simple");
    SolrFragmentsBuilder solrFbSO = highlighter.fragmentsBuilders.get("scoreOrder");
    assertSame(solrFbNull, solrFbEmpty);
    assertTrue(solrFbNull instanceof SimpleFragmentsBuilder);
    assertTrue(solrFbSimple instanceof SimpleFragmentsBuilder);
    assertTrue(solrFbSO instanceof ScoreOrderFragmentsBuilder);

    // Make sure we loaded two boundaryScanners
    SolrBoundaryScanner solrBsNull = highlighter.boundaryScanners.get(null);
    SolrBoundaryScanner solrBsEmpty = highlighter.boundaryScanners.get("");
    SolrBoundaryScanner solrBsSimple = highlighter.boundaryScanners.get("simple");
    SolrBoundaryScanner solrBsBI = highlighter.boundaryScanners.get("breakIterator");
    assertSame(solrBsNull, solrBsEmpty);
    assertTrue(solrBsNull instanceof SimpleBoundaryScanner);
    assertTrue(solrBsSimple instanceof SimpleBoundaryScanner);
    assertTrue(solrBsBI instanceof BreakIteratorBoundaryScanner);
  }

  @Test
  public void test() {
    HashMap<String, String> args = new HashMap<>();
    args.put("hl", "true");
    args.put("hl.fl", "tv_text");
    args.put("hl.snippets", "2");
    args.put("hl.tag.pre", "<fvpre>"); // ... and let post default to </em>. This is just a test.
    if (random().nextBoolean()) {
      args.put("hl.useFastVectorHighlighter", "true"); // old way
    } else {
      args.put("hl.method", "fastVector"); // the new way
    }

    assertU(
        adoc(
            "tv_text", "basic fast vector highlighter test",
            "id", "1"));
    assertU(commit());
    assertU(optimize());
    assertQ(
        "Basic summarization",
        req(new MapSolrParams(args), "q", "tv_text:vector"),
        "//lst[@name='highlighting']/lst[@name='1']",
        "//lst[@name='1']/arr[@name='tv_text']/str[.='basic fast <fvpre>vector</em> highlighter test']");
  }

  private static DefaultSolrHighlighter getHighlighter() {
    var hl =
        (HighlightComponent)
            h.getCore().getSearchComponents().get(HighlightComponent.COMPONENT_NAME);
    return (DefaultSolrHighlighter)
        hl.getHighlighter(new MapSolrParams(Map.of(HighlightParams.METHOD, "fastVector")));
  }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace System.Web.Mvc
{
    public delegate bool ActionSelector(ControllerContext controllerContext);
}


text:
namespace edash_packager {
namespace media {

class AesCbcDecryptor;
class KeySource;
struct EncryptionKey;

namespace wvm {

struct DemuxStreamIdMediaSample {
 public:
  DemuxStreamIdMediaSample();
  ~DemuxStreamIdMediaSample();
  uint32_t demux_stream_id;
  uint32_t parsed_audio_or_video_stream_id;
  scoped_refptr<MediaSample> media_sample;
};

struct PrevSampleData {
 public:
  PrevSampleData();
  ~PrevSampleData();
  void Reset();
  scoped_refptr<MediaSample> audio_sample;
  scoped_refptr<MediaSample> video_sample;
  uint32_t audio_stream_id;
  uint32_t video_stream_id;
  int64_t audio_sample_duration;
  int64_t video_sample_duration;
};

class WvmMediaParser : public MediaParser {
 public:
  WvmMediaParser();
  ~WvmMediaParser() override;

  /// @name MediaParser implementation overrides.
  /// @{
  void Init(const InitCB& init_cb,
            const NewSampleCB& new_sample_cb,
            KeySource* decryption_key_source) override;
  bool Flush() override WARN_UNUSED_RESULT;
  bool Parse(const uint8_t* buf, int size) override WARN_UNUSED_RESULT;
  /// @}

 private:
  enum Tag {
    CypherVersion = 0,
    TrackOffset = 1,
    TrackSize = 2,
    TrackDuration = 3,
    TrackBitRate = 4,
    TrackTrickPlayRate = 5,
    TrackAdaptationInterval = 6,
    TrackFlags = 7,
    VideoType = 8,
    VideoProfile = 9,
    VideoLevel = 10,
    VideoWidth = 11,
    VideoHeight = 12,
    VideoTicksPerFrame = 13,
    VideoBitRate = 14,
    AudioType = 15,
    AudioProfile = 16,
    AudioNumChannels = 17,
    AudioSampleFrequency = 18,
    AudioBitRate = 19,
    TrackVersion = 20,
    Title = 21,
    Copyright = 22,
    ChapterIndex = 23,
    TimeIndex = 24,
    Thumbnail = 25,
    ObjectSeqNum = 26,
    ThumbnailOffset = 27,
    ThumbnailSize = 28,
    NumEntries = 29,
    Chapters = 30,
    VideoPixelWidth = 31,
    VideoPixelHeight = 32,
    FileSize = 33,
    SparseDownloadUrl = 34,
    SparseDownloadRangeTranslations = 35,
    SparseDownloadMap = 36,
    AudioSampleSize = 37,
    Audio_EsDescriptor = 38,
    AVCDecoderConfigurationRecord = 39,
    Audio_EC3SpecificData = 40,
    AudioIdentifier = 41,
    VideoStreamId = 42,
    VideoStreamType = 43,
    AudioStreamId = 44,
    AudioStreamType = 45,
    Audio_DtsSpecificData = 46,
    Audio_AC3SpecificData = 47,
    Unset = 48
  };

  enum State {
    StartCode1 = 0,
    StartCode2,
    StartCode3,
    StartCode4,
    PackHeader1,
    PackHeader2,
    PackHeader3,
    PackHeader4,
    PackHeader5,
    PackHeader6,
    PackHeader7,
    PackHeader8,
    PackHeader9,
    PackHeader10,
    PackHeaderStuffingSkip,
    SystemHeader1,
    SystemHeader2,
    SystemHeaderSkip,
    PesStreamId,
    PesPacketLength1,
    PesPacketLength2,
    PesExtension1,
    PesExtension2,
    PesExtension3,
    Pts1,
    Pts2,
    Pts3,
    Pts4,
    Pts5,
    Dts1,
    Dts2,
    Dts3,
    Dts4,
    Dts5,
    PesHeaderData,
    PesPayload,
    EsPayload,
    PsmPayload,
    EcmPayload,
    IndexPayload,
    Padding,
    ProgramEnd
  };

  bool ProcessEcm();

  // Index denotes 'search index' in the WVM content.
  bool ParseIndexEntry();

  bool DemuxNextPes(bool is_program_end);

  void StartMediaSampleDemux();

  template <typename T>
  Tag GetTag(const uint8_t& tag,
             const uint32_t& length,
             const uint8_t* start_index,
             T* value) {
    if (length == sizeof(uint8_t)) {
      *value = (uint8_t)(*start_index);
    } else if (length == sizeof(int8_t)) {
      *value = (int8_t)(*start_index);
    } else if (length == sizeof(uint16_t)) {
      *value = (uint16_t)(ntohsFromBuffer(start_index));
    } else if (length == sizeof(int16_t)) {
      *value = (int16_t)(ntohsFromBuffer(start_index));
    } else if (length == sizeof(uint32_t)) {
      *value = (uint32_t)(ntohlFromBuffer(start_index));
    } else if (length == sizeof(int32_t)) {
      *value = (int32_t)(ntohlFromBuffer(start_index));
    } else if (length == sizeof(uint64_t)) {
      *value = (uint64_t)(ntohllFromBuffer(start_index));
    } else if (length == sizeof(int64_t)) {
      *value = (int64_t)(ntohllFromBuffer(start_index));
    } else {
      *value = 0;
    }
    return Tag(tag);
  }

  // |must_process_encrypted| setting determines if Output() should attempt
  // to ouput media sample as encrypted.
  bool Output(bool must_process_encrypted);

  bool GetAssetKey(const uint32_t asset_id, EncryptionKey* encryption_key);

  // Callback invoked by the ES media parser
  // to emit a new audio/video access unit.
  bool EmitSample(uint32_t parsed_audio_or_video_stream_id,
                  uint32_t stream_id,
                  scoped_refptr<MediaSample>& new_sample,
                  bool isLastSample);

  bool EmitPendingSamples();

  bool EmitLastSample(uint32_t stream_id,
                      scoped_refptr<MediaSample>& new_sample);

  // List of callbacks.t
  InitCB init_cb_;
  NewSampleCB new_sample_cb_;

  // Whether |init_cb_| has been invoked.
  bool is_initialized_;
  // Internal content parsing state.
  State parse_state_;

  bool is_psm_needed_;
  uint32_t skip_bytes_;
  bool metadata_is_complete_;
  uint8_t current_program_id_;
  uint32_t pes_stream_id_;
  uint32_t prev_pes_stream_id_;
  uint16_t pes_packet_bytes_;
  uint8_t pes_flags_1_;
  uint8_t pes_flags_2_;
  uint8_t prev_pes_flags_1_;
  uint8_t pes_header_data_bytes_;
  uint64_t timestamp_;
  uint64_t pts_;
  uint64_t dts_;
  uint8_t index_program_id_;
  scoped_refptr<MediaSample> media_sample_;
  uint32_t crypto_unit_start_pos_;
  PrevSampleData prev_media_sample_data_;
  H264ByteToUnitStreamConverter byte_to_unit_stream_converter_;

  std::vector<uint8_t, std::allocator<uint8_t> > ecm_;
  std::vector<uint8_t> psm_data_;
  std::vector<uint8_t> index_data_;
  std::map<std::string, uint32_t> program_demux_stream_map_;
  int stream_id_count_;
  std::vector<scoped_refptr<StreamInfo> > stream_infos_;
  std::deque<DemuxStreamIdMediaSample> media_sample_queue_;
  std::vector<uint8_t> sample_data_;
  KeySource* decryption_key_source_;
  scoped_ptr<AesCbcDecryptor> content_decryptor_;

  DISALLOW_COPY_AND_ASSIGN(WvmMediaParser);
};

}  // namespace wvm
}  // namespace media
}  // namespace edash_packager

#endif  // MEDIA_FORMATS_WVM_WVM_MEDIA_PARSER_H_


text:
from __future__ import print_function, division

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from lib import replay_memory
from lib import util
import Tkinter
from PIL import Image, ImageTk
import numpy as np
import cPickle as pickle
import time
import imgaug as ia

EVERY_NTH = 10
ANNOTATIONS_FP = "annotations.pickle"
ZOOM_FACTOR = 4
AUTOSAVE_EVERY = 20

def main():
    print("Loading replay memory...")
    memory = replay_memory.ReplayMemory.create_instance_supervised()

    print("Loading previous annotations...")
    annotations = load_annotations()
    #is_annotated = dict([(str(annotation.idx), True) for annotation in annotations])

    current_state_idx = memory.id_min
    if annotations is not None:
        while current_state_idx < memory.id_max:
            key = str(current_state_idx)
            if not key in annotations:
                break
            current_state_idx += EVERY_NTH
    print("ID of first unannotated state: %d" % (current_state_idx,))

    master = Tkinter.Tk()
    state = memory.get_state_by_id(current_state_idx)
    canvas_height = state.screenshot_rs.shape[0] * ZOOM_FACTOR
    canvas_width = state.screenshot_rs.shape[1] * ZOOM_FACTOR
    print("canvas height, width:", canvas_height, canvas_width)
    canvas = Tkinter.Canvas(master, width=canvas_width, height=canvas_height)
    canvas.pack()
    canvas.focus_set()

    #y = int(canvas_height / 2)
    #w.create_line(0, y, canvas_width, y, fill="#476042")
    message = Tkinter.Label(master, text="Click to draw annotation. Press E to switch to eraser mode. Press S to save. Use Numpad +/- for brush size.")
    message.pack(side=Tkinter.BOTTOM)

    window_state = WindowState(master, canvas, memory, current_state_idx, annotations)

    #canvas.bind("<Button-1>", OnPaint(window_state))
    #master.bind("<Button-1>", lambda event: print(event))
    #master.bind("<Button-3>", lambda event: print("right", event))
    #master.bind("<ButtonPress-1>", lambda event: print("press", event))
    master.bind("<B1-Motion>", OnLeftMouseButton(window_state))
    #master.bind("<ButtonRelease-1>", lambda event: print("release", event))
    master.bind("<B3-Motion>", OnRightMouseButton(window_state))
    canvas.bind("<e>", lambda event: window_state.toggle_eraser())
    canvas.bind("<s>", lambda event: window_state.save_annotations(force=True))
    canvas.bind("<w>", lambda event: window_state.toggle_heatmap())
    canvas.bind("<Left>", lambda event: window_state.previous_state(autosave=True))
    canvas.bind("<Right>", lambda event: window_state.next_state(autosave=True))
    canvas.bind("<KP_Add>", lambda event: window_state.increase_brush_size())
    canvas.bind("<KP_Subtract>", lambda event: window_state.decrease_brush_size())

    Tkinter.mainloop()

def load_annotations():
    if os.path.isfile(ANNOTATIONS_FP):
        return pickle.load(open(ANNOTATIONS_FP, "r"))
    else:
        return None

class WindowState(object):
    def __init__(self, master, canvas, memory, current_state_idx, annotations):
        self.master = master
        self.canvas = canvas
        self.memory = memory
        self.current_state_idx = current_state_idx
        self.annotations = annotations if annotations is not None else dict()
        self.current_annotation = None
        self.background_label = None

        self.switch_to_state(self.current_state_idx, autosave=False)
        self.current_state = memory.get_state_by_id(current_state_idx)

        self.eraser = False
        self.dirty = False
        self.brush_size = 3
        self.heatmap_visible = True
        self.last_autosave = 0

    @property
    def grid(self):
        return self.current_annotation["street_boundary_grid"]

    def toggle_eraser(self):
        self.eraser = not self.eraser
        print("Eraser set to %s" % (self.eraser,))

    def toggle_heatmap(self):
        if self.heatmap_visible:
            self.set_canvas_background(self.current_state.screenshot_rs)
        else:
            self.set_canvas_background(self._generate_heatmap())
        self.heatmap_visible = not self.heatmap_visible

    def increase_brush_size(self):
        self.brush_size = np.clip(self.brush_size+1, 1, 100)
        print("Increased brush size to %d" % (self.brush_size,))

    def decrease_brush_size(self):
        self.brush_size = np.clip(self.brush_size-1, 1, 100)
        print("Decreased brush size to %d" % (self.brush_size,))

    def previous_state(self, autosave):
        print("Switching to previous state...")
        self.current_state_idx -= EVERY_NTH
        assert self.current_state_idx >= self.memory.id_min, "Start of memory reached (%d vs %d)" % (self.current_state_idx, self.memory.id_min)
        self.switch_to_state(self.current_state_idx, autosave=autosave)

    def next_state(self, autosave):
        print("Switching to next state...")
        self.current_state_idx += EVERY_NTH
        assert self.current_state_idx <= self.memory.id_max, "End of memory reached (%d vs %d)" % (self.current_state_idx, self.memory.id_max)
        self.switch_to_state(self.current_state_idx, autosave=autosave)

    def switch_to_state(self, idx, autosave):
        print("Switching to state %d (autosave=%s)..." % (idx, str(autosave)))
        self.current_state = self.memory.get_state_by_id(idx)
        assert self.current_state is not None
        self.current_state_idx = idx

        if autosave:
            if self.last_autosave+1 % AUTOSAVE_EVERY == 0:
                self.save_annotations()
                self.last_autosave = 0
            else:
                self.last_autosave += 1

        key = str(self.current_state_idx)
        if key in self.annotations:
            self.current_annotation = self.annotations[key]
        else:
            img = self.current_state.screenshot_rs
            grid = np.zeros((img.shape[0], img.shape[1]), dtype=np.float32)
            self.current_annotation = {
                "idx": self.current_state_idx,
                "from_datetime": self.current_state.from_datetime,
                "screenshot_rs": self.current_state.screenshot_rs,
                "street_boundary_grid": grid
            }
            self.annotations[key] = self.current_annotation
            print("This state has not yet been annotated.")

        self.update_annotation_grid(self.grid, initial=True)

    def save_annotations(self, force=False):
        #print(self.annotations)
        if self.dirty or force:
            print("Saving...")
            with open(ANNOTATIONS_FP, "w") as f:
                pickle.dump(self.annotations, f, protocol=-1)
            self.dirty = False
            print("Finished saving.")
        else:
            print("Not saved (not marked dirty)")

    """
    def redraw_canvas(self):
        img = generate_canvas_image(self.current_state.screenshot_rs, self.grid)
        self.canvas.delete(Tkinter.ALL)
        self.set_canvas_background(self.canvas, img)
    """

    def update_annotation_grid(self, annotation_grid, initial=False):
        self.current_annotation["street_boundary_grid"] = annotation_grid
        #self.redraw_canvas()
        #img = generate_canvas_image(self.current_state.screenshot_rs, annotation_grid)
        img_heatmap = self._generate_heatmap()
        self.set_canvas_background(img_heatmap)
        self.heatmap_visible = True
        if not initial:
            self.dirty = True

    def set_canvas_background(self, image):
        if self.background_label is None:
            # initialize background image label (first call)
            #img = self.current_state.screenshot_rs
            #bg_img_tk = numpy_to_tk_image(np.zeros(img.shape))
            img_heatmap = self._generate_heatmap()
            img_heatmap_rs = ia.imresize_single_image(img_heatmap, (img_heatmap.shape[0]*ZOOM_FACTOR, img_heatmap.shape[1]*ZOOM_FACTOR), interpolation="nearest")
            bg_img_tk = numpy_to_tk_image(img_heatmap_rs)
            self.background_label = Tkinter.Label(self.canvas, image=bg_img_tk)
            self.background_label.place(x=0, y=0, relwidth=1, relheight=1, anchor=Tkinter.NW)
            self.background_label.image = bg_img_tk

        #print("image size", image.shape)
        #print("image height, width", image.to_array().shape)
        image_rs = ia.imresize_single_image(image, (image.shape[0]*ZOOM_FACTOR, image.shape[1]*ZOOM_FACTOR), interpolation="nearest")
        image_tk = numpy_to_tk_image(image_rs)
        self.background_label.configure(image=image_tk)
        self.background_label.image = image_tk

    def _generate_heatmap(self):
        return util.draw_heatmap_overlay(self.current_state.screenshot_rs, self.grid, alpha=0.3)

def numpy_to_tk_image(image):
    image_pil = Image.fromarray(image)
    image_tk = ImageTk.PhotoImage(image_pil)
    return image_tk

class OnLeftMouseButton(object):
    def __init__(self, window_state):
        self.window_state = window_state

    def __call__(self, event):
        #canvas = event.widget
        x = self.window_state.canvas.canvasx(event.x) / ZOOM_FACTOR
        y = self.window_state.canvas.canvasy(event.y) / ZOOM_FACTOR
        height, width = self.window_state.current_state.screenshot_rs.shape[0:2]
        #x = event.x
        #y = event.y
        #canvas.delete(Tkinter.ALL)

        grid = self.window_state.grid
        normal = draw_normal_distribution(height, width, int(x), int(y), self.window_state.brush_size)
        #normal = np.zeros_like(grid)
        #normal[int(y)-2:int(y)+2, int(x)-2:int(x)+2] = 1.0
        if not self.window_state.eraser:
            #grid = np.clip(grid + normal, 0, 1)
            grid = np.maximum(grid, normal)
        else:
            grid = grid - normal
        grid = np.clip(grid, 0, 1)
        self.window_state.update_annotation_grid(grid)
        #time.sleep(0.1)

class OnRightMouseButton(object):
    def __init__(self, window_state):
        self.window_state = window_state

    def __call__(self, event):
        x = self.window_state.canvas.canvasx(event.x) / ZOOM_FACTOR
        y = self.window_state.canvas.canvasy(event.y) / ZOOM_FACTOR
        height, width = self.window_state.current_state.screenshot_rs.shape[0:2]
        grid = self.window_state.grid
        normal = draw_normal_distribution(height, width, int(x), int(y), self.window_state.brush_size)
        grid = grid - normal
        grid = np.clip(grid, 0, 1)
        self.window_state.update_annotation_grid(grid)

"""
class OnToggleEraser(object):
    def __init__(self, window_state):
        self.window_state = window_state

    def __call__(self, event):
        self.window_state.toggle_eraser(save=True)

class OnPreviousState(object):
    def __init__(self, window_state):
        self.window_state = window_state

    def __call__(self, event):
        self.window_state.previous_state()

class OnNextState(object):
    def __init__(self, window_state):
        self.window_state = window_state

    def __call__(self, event):
        self.window_state.next_state()
"""

def draw_normal_distribution(height, width, x, y, size):
    if 0 <= y < height and 0 <= x < width:
        pad_by = size * 10
        img = np.zeros((pad_by+height+pad_by, pad_by+width+pad_by), dtype=np.float32)
        #img = img.pad(img, ((20, 20), (20, 20)))
        #normal = util.create_2d_gaussian(size=size*2, fwhm=size)
        normal = util.create_2d_gaussian(size=size*4, sigma=size)
        #print(normal)
        normal_h, normal_w = normal.shape
        normal_hh, normal_wh = normal_h//2, normal_w//2
        #print("normal size", normal.shape)
        #print("img.shape", img.shape)
        #print("img[y-normal_hh:y+normal_hh, x-normal_wh:x+normal_wh]", img[y-normal_hh:y+normal_hh, x-normal_wh:x+normal_wh].shape)
        y1 = np.clip(y-normal_hh+pad_by, 0, img.shape[0]-1) #-(2*pad_by))
        y2 = np.clip(y+normal_hh+pad_by, 0, img.shape[0]-1) #-(2*pad_by))
        x1 = np.clip(x-normal_wh+pad_by, 0, img.shape[1]-1) #-(2*pad_by))
        x2 = np.clip(x+normal_wh+pad_by, 0, img.shape[1]-1) #-(2*pad_by))
        if x2 - x1 > 0 and y2 - y1 > 0:
            img[y1:y2, x1:x2] = normal
        return img[pad_by:-pad_by, pad_by:-pad_by]
    else:
        return np.zeros((height, width), dtype=np.float32)

if __name__ == "__main__":
    main()


text:
from .prox_fn import ProxFn
import numpy as np
import matlab.engine
import scipy.io

class matlab_external(ProxFn):
    """The function for matlab prior
    """

    def __init__(self, lin_op, matengine, proxfunc, buffer_name='buffer',
                 evalfunc=None, params=None, **kwargs):

        self.matengine = matengine
        self.params = params
        self.proxfunc = proxfunc
        self.evalfunc = evalfunc
        self.buffer_name = buffer_name
        # Run external matlab method
        self.proxmethod = getattr(self.matengine, self.proxfunc)
        super(matlab_external, self).__init__(lin_op, **kwargs)

    def _prox(self, rho, v, it, *args, **kwargs):
        """ calls matlab proximal function on v
        """
        assert it is not None

        # vmat = matlab.double(v.tolist())
        vmat = self.buffer_name
        scipy.io.savemat(vmat, {'z': v})
        if self.params is None:
            pres = self.proxmethod(vmat, rho, it)
        else:
            paramsmat = matlab.double(self.params.tolist())
            pres = self.proxmethod(vmat, rho, it, paramsmat)

        pres = np.array(pres._data).reshape(v.shape, order='F')
        np.copyto(v, pres)
        return v

    def _eval(self, v):
        """Evaluate the function on v (ignoring parameters).
        """

        if self.evalfunc is None:
            return np.inf
        else:
            evalmethod = getattr(self.matengine, self.evalfunc)

            vmat = matlab.double(v)
            if self.params is None:
                peval = np.float32(evalmethod(vmat))
            else:
                paramsmat = matlab.double(self.params.tolist())
                peval = np.float32(evalmethod(vmat, paramsmat))

            return peval

    def get_data(self):
        """Returns info needed to reconstruct the object besides the args.

        Returns
        -------
        list
        """
        return [self.matengine, self.proxfunc, self.evalfunc, self.params]


text:
<?php

/**
 * Created by JetBrains PhpStorm.
 * User: oli2002
 * Date: 10/4/13
 * Time: 12:56 PM
 * To change this template use File | Settings | File Templates.
 */

namespace App\OrderformBundle\Util;

use App\OrderformBundle\Entity\AccessionListHierarchy;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

use Doctrine\Common\Collections\ArrayCollection;
use App\UserdirectoryBundle\Entity\InstitutionWrapper;
use App\UserdirectoryBundle\Entity\PerSiteSettings;
use Symfony\Component\HttpFoundation\RedirectResponse;

use App\OrderformBundle\Entity\History;
use App\OrderformBundle\Entity\DataQualityMrnAcc;

use App\UserdirectoryBundle\Entity\User;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;

class OrderUtil {

    private $em;
    private $container;
    protected $security;

    public function __construct( EntityManagerInterface $em, ContainerInterface $container, Security $security ) {
        $this->em = $em;
        $this->container = $container;
        $this->security = $security;
    }

    public function redirectOrderByStatus($order,$routeName) {

        if( $order->getMessageCategory()->getName() == "Table-View Scan Order" ) {
            $edit = "table_edit";
            $amend = "table_amend";
            $show = "table_show";
        } else {
            $edit = "multy_edit";
            $amend = "order_amend";
            $show = "multy_show";
        }
        //echo "show=".$show."
";

        $router = $this->container->get('router');

        //if order is not submitted with edit url => change url to edit
        if( $order->getStatus()."" == "Not Submitted" && $routeName != $edit ) {
            return new RedirectResponse( $router->generate($edit,array('id'=>$order->getOid())) );
        }

        //if order is submitted with edit url => change url to show
        if( $order->getStatus()."" != "Not Submitted" && $routeName == $edit ) {
            return new RedirectResponse( $router->generate($show,array('id'=>$order->getOid())) );
        }

        //if order is not submitted with amend url => change url to edit
        if( $order->getStatus()."" == "Not Submitted" && $routeName == $amend ) {
            return new RedirectResponse( $router->generate($edit,array('id'=>$order->getOid())) );
        }

        //if order Filled or Canceled by Processor or Canceled by Submitter or Superseded with amend url => change url to show
        if(
            $routeName == $amend && (
                strpos((string)$order->getStatus()."",'Filled') !== false ||
                strpos((string)$order->getStatus()."",'Canceled') !== false ||
                $order->getStatus()."" == "Superseded"
            )
        ) {
            return new RedirectResponse( $router->generate($show,array('id'=>$order->getOid())) );
        }

        //echo "no redirect
";

        return null;

    }

    public function changeStatus( $id, $status, $user, $swapId=null ) {

        //exit('change status');

        $em = $this->em;

        $entity = $em->getRepository('AppOrderformBundle:Message')->findOneByOid($id);

        if (!$entity) {
            throw new \Exception( 'Unable to find Message entity by id'.$id );
        }

        $securityUtil = $this->container->get('user_security_utility');
        if( !$securityUtil->isUserAllowOrderActions($entity, $user, array('changestatus')) ) {
            $res = array();
            $res['result'] = 'nopermission';
            return $res;
        }

        if( $status == 'Un-Cancel' ) {
            $statusSearch = 'Submit';
        } else {
            $statusSearch = $status;
        }

        //echo "status=".$status."
";
        $status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByAction($statusSearch);
        //echo "status_entity=".$status_entity->getName()."
";
        //exit();

        if( $status_entity == null ) {
            throw new \Exception( 'Unable to find status for status=' . $statusSearch );
        }

        //record history
        $history = new History();
        $eventtype = $em->getRepository('AppOrderformBundle:ProgressCommentsEventTypeList')->findOneByName('Status Changed');
        $history->setEventtype($eventtype);
        $history->setMessage($entity);
        $history->setCurrentid($entity->getOid());
        $history->setCurrentstatus($entity->getStatus());
        $history->setProvider($user);
        $history->setRoles($user->getRoles());

        //change status for all message children to "deleted-by-canceled-order"
        //IF their source is ='scanorder' AND there are no child objects with status == 'valid'
        //AND there are no fields that belong to this object that were added by another order
        if( $status == 'Cancel' ) {

            //exit('case Cancel');

            $fieldStatusStr = "deleted-by-canceled-order";

            if( $entity->getProvider() == $user || $this->security->isGranted("ROLE_SCANORDER_ORDERING_PROVIDER") ) {
                $status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByName("Canceled by Submitter");
            } else
            if( $this->security->isGranted("ROLE_SCANORDER_ADMIN") || $this->security->isGranted("ROLE_SCANORDER_PROCESSOR") ) {
                $status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByName("Canceled by Processor");
            } else {
                $status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByName("Canceled by Submitter");
            }

            if( $status_entity == null ) {
                throw new \Exception( 'Unable to find status for canceled order' );
            }

            $entity->setStatus($status_entity);
            $message = $this->processObjects( $entity, $status_entity, $fieldStatusStr );

            //record history
            $history->setCurrentid($entity->getOid());
            $history->setCurrentstatus($entity->getStatus());

            $em->persist($entity);
            $em->persist($history);
            $em->flush();
            $em->clear();

        } else if( $status == 'Supersede' ) {

            //exit('case Supersede');

            //$status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByName("Superseded");
            $fieldStatusStr = "deleted-by-amended-order";
            $entity->setStatus($status_entity);
            $message = $this->processObjects( $entity, $status_entity, $fieldStatusStr );
            $entity->setOid($swapId);
            //$entity->setCycle("superseded");

            //record history
            $history->setCurrentid($entity->getOid());
            $history->setCurrentstatus($entity->getStatus());

            $router = $this->container->get('router');
            $url = $router->generate( 'multy_show', array('id' => $id) );
            $link = 'order '.$id.'';
            $notemsg = 'This order is an old superseded version of '.$link;
            $history->setNote($notemsg);

            $em->persist($entity);
            $em->persist($history);
            $em->flush();
            //$em->clear();   //testing clear
            //unset($entity);
            //unset($history);
            //gc_collect_cycles();

        } else if( $status == 'Un-Cancel' || $status == 'Submit' ) {  //this is un-cancel action

            //exit('case Un-Cancel or Submit');

            //1) clone message object
            //2) validate MRN-Accession
            //3) change status to 'valid' and 'submit'

//            echo "

newMessage Patient's count=".count($entity->getPatient())."
";
//            echo $entity;
//            foreach( $entity->getPatient() as $patient ) {
//                echo "
--------------------------
";
//                $em->getRepository('AppOrderformBundle:Message')->printTree( $patient );
//                echo "--------------------------
";
//            }
            //exit();

            //VALIDATION Accession-MRN
            $validity = array('valid');
            $conflict = false;
            foreach( $entity->getAccession() as $accession ) {

                //                     procedure    encounter     patient
                $patient = $accession->getParent()->getParent()->getParent();

                $patientKey = $patient->obtainValidKeyField();
                if( !$patientKey ) {
                    throw new \Exception( 'Object does not have a valid key field. Object: '.$patient );
                }

                $accessionKey = $accession->obtainValidKeyField();
                if( !$accessionKey ) {
                    throw new \Exception( 'Object does not have a valid key field. Object: '.$accession );
                }

                //echo "accessionKey=".$accessionKey."
";
                $accessionDb = $em->getRepository('AppOrderformBundle:Accession')->findOneByIdJoinedToField(array($accession->getInstitution()->getId()),$accessionKey,"Accession","accession",$validity, true); //validity was true

                $mrn = $patientKey; //mrn
                $mrnTypeId = $patientKey->getKeytype()->getId();
                //$extra = $patientKey->obtainExtraKey();

                if( $accessionDb ) {
                    //echo "similar accession found=".$accessionDb;
                    $patientDb = $accessionDb->getParent()->getParent();
                    if( $patientDb ) {
                        $mrnDb = $patientDb->obtainValidKeyField();
                        $mrnTypeIdDb = $mrnDb->getKeytype()->getId();

                        //echo $mrn . "?=". $mrnDb ." && ". $mrnTypeId . "==". $mrnTypeIdDb . "
";

                        if( $mrn == $mrnDb && $mrnTypeId == $mrnTypeIdDb ) {
                            //ok
                            //exit("no conflict
");
                        } else {
                            //echo "there is a conflict
";
                            //conflict => render the message in the amend view 'order_amend'
                            //exit('un-canceling order. id='.$entity->getOid());
                            $conflict = true;
                        }
                    }
                }

            }

            if( $conflict ) {

                //exit('conflict un-canceling order. id='.$entity->getOid());

                $res = array();
                $res['result'] = 'conflict';
                $res['oid'] = $entity->getOid();

                return $res;

            } else {
                 //exit("un-cancel no conflict!
");
                //if no conflict: change status without creating new order
                //record new history for modifying Superseded Order
                $entity->setStatus($status_entity);
                $message = $this->processObjects( $entity, $status_entity, 'valid' );
                $history->setCurrentid($entity->getOid());
                $history->setCurrentstatus($entity->getStatus());

                $em->persist($entity);
                $em->persist($history);
                $em->flush();
                $em->clear();

            }

        } else {

            //exit('regular xit');

            //throw new \Exception( 'Status '.$status.' can not be processed' );
            $entity->setStatus($status_entity);

            //record history
            $history->setCurrentid($entity->getOid());
            $history->setCurrentstatus($entity->getStatus());

            $em->persist($entity);
            $em->persist($history);
            $em->flush();
            $em->clear();

        }

        //$message = 'Status of Order '.$id.' has been changed to "'.$status.'"'.$message;
        $message = 'Status of Order '.$id.' succesfully changed to "'.$entity->getStatus()->getName().'"';

        $res = array();
        $res['result'] = 'ok';
        $res['message'] = $message;

        return $res;
    }

//    public function makeMessageClone( $entity, $status_entity, $statusStr ) {
//
//        $em = $this->em;
//
//        if( !$status_entity  ) {
//            $status_entity = $em->getRepository('AppOrderformBundle:Status')->findOneByAction('Submit');
//        }
//
//        //CLONING
//        $oid = $entity->getOid();
//        $oidArr = explode("-", $oid);
//        $originalId = $oidArr[0];
//
//        $newMessage = clone $entity;
//
//        $em->detach($entity);
//        $em->detach($newMessage);
//
//        $newMessage->setStatus($status_entity);
//        //$newMessage->setCycle('submit');
//        $newMessage->setOid($originalId);
//
//        //$newMessage = $this->iterateMessage( $newMessage, $statusStr );
//
//        //change status to valid
//        $message = $this->processObjects( $newMessage, $status_entity, $statusStr );
//
//        $res = array();
//        $res['message'] = $message;
//        $res['message'] = $newMessage;
//
//        return $res;
//    }

    public function processObjects( $entity, $status_entity, $statusStr ) {

        $patients = $entity->getPatient();
        $patCount = $this->iterateEntity( $entity, $patients, $status_entity, $statusStr );

        $procedures = $entity->getProcedure();
        $procCount = $this->iterateEntity( $entity, $procedures, $status_entity, $statusStr );

        $accessions = $entity->getAccession();
        $accCount = $this->iterateEntity( $entity, $accessions, $status_entity, $statusStr );

        $parts = $entity->getPart();
        $partCount = $this->iterateEntity( $entity, $parts, $status_entity, $statusStr );

        $blocks = $entity->getBlock();
        $blockCount = $this->iterateEntity( $entity, $blocks, $status_entity, $statusStr );

        $slides = $entity->getSlide();
        $slideCount = $this->iterateEntity( $entity, $slides, $status_entity, $statusStr );

        return " (changed children: patients ".$patCount.", procedures ".$procCount.", accessions ".$accCount.", parts ".$partCount.", blocks ".$blockCount." slides ".$slideCount.")";
    }

    public function iterateEntity( $message, $children, $status_entity, $statusStr ) {

        $em = $this->em;

        if( !$children->first() ) {
            return 0;
        }

        //echo "iterate children count=".count($children)."
";

        $class = new \ReflectionClass($children->first());
        $className = $class->getShortName();
        //echo "class name=".$className."
";

        //$securityUtil = $this->container->get('user_security_utility');
        //$source = $securityUtil->getDefaultSourceSystem();

        $count = 0;

        foreach( $children as $child ) {

            $noOtherMessage = true;

            //echo "message count=".count($child->getMessage()).", order id=".$child->getMessage()->first()->getId()."
";

            //check if this object is used by any other message (for cancel and amend only)
            //TODO: check all parents too(?)
            if( $statusStr != 'valid' ) {
                foreach( $child->getMessage() as $order ) {
                    //echo "message id=".$order->getId().", oid=".$order->getOid()."
";
                    if( $message->getId() != $order->getId() ) {  //&& $order->getStatus() != $status_entity->getId()  ) {
                        $noOtherMessage = false;
                        break;
                    }
                }
            }

            //echo "noOtherMessage=".$noOtherMessage."
";

            //TODO: is it logical to check if source == scanorder? Why we have to limit to scanorder source?
            //Change status to a new $statusStr if the field is not used by other orders
            //if( $child->getSource()->getId() == $source->getId() && $noOtherMessage ) {
            if( $noOtherMessage ) {
                //echo "change status to (".$statusStr.")
";
                $child->setStatus($statusStr);
                $em->getRepository('AppOrderformBundle:'.$className)->processFieldArrays($child,null,null,$statusStr);
                $count++;
            } else {
                //this entity (i.e. accession object) is used by another order
                //TODO: what should we do? If we don't change the status, then we will have 2 entity with the same name (2 accessions with the same accession name and accession type)
            }

        }

        return $count;
    }

    //$flag = 'admin'-show only comments from users to admin or null-show only comments to the orders belonging to admin
    public function getNotViewedComments($flag=null)
    {
        $repository = $this->em->getRepository('AppOrderformBundle:History');
        $dql =  $repository->createQueryBuilder('history');
        //$dql->select('COUNT(history) as historycount');
        $dql->select('history');
        $dql->leftJoin("history.eventtype", "eventtype");

        $dql->innerJoin("history.message", "message");
        $dql->innerJoin("message.provider", "provider");

        $dql->leftJoin("message.proxyuser", "proxyuserWrapper");
        $dql->leftJoin("proxyuserWrapper.user", "proxyuser");

        //$dql->innerJoin("history.orderProvider", "provider");
        //$dql->leftJoin("history.orderProxyuser", "proxyuser");
        //$dql->leftJoin("history.orderInstitution", "institution");

        $dql->leftJoin("message.institution", "institution");
        $criteriastr = $this->getCommentsCriteriaStr(null, $flag);

        if( $criteriastr == "" ) {
            return null;
        }

        $dql->where($criteriastr);

        $dql->addOrderBy("history.changedate","DESC");

        //echo "
".$flag.": dql=".$dql."
";

        $query = $dql->getQuery();

        $entities = $query->getResult();

        //echo "=> count=".count($entities)."
";
//        foreach( $entities as $ent ) {
//            echo $ent->getId().", provider=".$ent->getProvider()."
";
//        }

        return $entities;
    }

    //$commentFlag = 'admin'-show only comments from users to admin;
    //$commentFlag = null-show only comments to the orders belonging to admin
    public function getCommentsCriteriaStr($flag = 'new_comments', $commentFlag = null) {

        $user = $this->security->getUser();

        if( !$user ) {
            return "";
        }

        if( !is_object($user) ) {
            return "";
        }

//        if( !$this->secTokenStorage->getToken() ) {
//            return "";
//        }

        $criteriastr = "eventtype.name='Comment Added' ";

        if( $flag != 'all_comments' ) {
            $criteriastr = $criteriastr . "AND history.viewed is NULL ";
        } else {
            return $criteriastr;
        }

        $role = "ROLE_SCANORDER_PROCESSOR";
        $role2 = "ROLE_SCANORDER_ADMIN";

        if( $commentFlag && $commentFlag == 'admin' ) {
            //echo "comments to admin only!, userid=".$user->getId()." =>";
            //processor can see all histories created by user without processor role, but not for orders belonging to this processor
            $criteriastr = $criteriastr . " AND history.roles NOT LIKE '%".$role."%' AND history.roles NOT LIKE '%".$role2."%'";

            //comments to admin only: can be addressed by another admin (so any user role) and for orders created by not current user (all new comments for the orders not created by current admin)
            $criteriastr = $criteriastr . " AND history.provider != " . $user->getId() . " AND provider != " . $user->getId();
        } else {
            //echo "comments about my orders only, placed by not me! =>";
            //submitter can see only histories created by user with processor or admin role for history's orders belongs to this user as provider or proxy
            //$criteriastr = $criteriastr . " AND ( history.roles LIKE '%".$role."%' OR history.roles LIKE '%".$role2."%' )";
            //submitters can only see the comments about thier order created by another user
            $criteriastr = $criteriastr . " AND ( (provider = ".$user->getId()." OR proxyuser = ".$user->getId().") AND history.provider != ".$user->getId()." )";
        }

        /////////// institution ///////////
        $criteriastr = $this->addInstitutionQueryCriterion($user,$criteriastr);
        /////////// EOF institution ///////////

        //echo "criteriastr=".$criteriastr."
";

        return $criteriastr;
    }

    //Used by addInstitutionQueryCriterion() here in getCommentsCriteriaStr() and in ScanOrderController in getDql()
    //Used by getUnporcesseOrders and getUnprocessedSlideRequests
    //check if node belongs to the parentNode tree. For example, 1wcmc6->2path5->3inf4 => if inf.lft > wcmc.lft AND inf.rgt < wcmc.rgt => return true.
    //check if user's institution is under message's institution node
    //$collaborationTypesStrArr - array of collaboration types; if null - ignore collaboration
    public function getInstitutionQueryCriterion( $user, $collaborationTypesStrArr=array("Union") ) {
        $securityUtil = $this->container->get('user_security_utility');

        $instStr = "";
        //return $instStr;

        //User's PermittedInstitutions
        $permittedInstitutions = $securityUtil->getUserPermittedInstitutions($user);

        //show institutions including collaborations
        $permittedInstitutions = $this->getAllScopeInstitutions($permittedInstitutions,null,$collaborationTypesStrArr);

        //echo "permittedInstitutions=".count($permittedInstitutions)."
";

        if( $collaborationTypesStrArr && count($collaborationTypesStrArr) > 0 ) {
            $instComparatorDefault = true;  //lft < getId
            $collComparatorDefault = false; //lft > getId

            foreach( $permittedInstitutions as $permittedInstitution ) {

                $institutionAndCollaborationStr = $this->em->getRepository('AppUserdirectoryBundle:Institution')->
                    getCriterionStrForCollaborationsByNode($permittedInstitution,"institution",$collaborationTypesStrArr, $instComparatorDefault, $collComparatorDefault );

                if( $instStr != "" ) {
                    $instStr = $instStr . " OR (" . $institutionAndCollaborationStr . ")";
                } else {
                    $instStr = $institutionAndCollaborationStr;
                }

            }
        }

//if(0){
//        if(1) {
//            foreach( $permittedInstitutions as $permittedInstitution ) {
//                if( $instStr != "" ) {
//                    $instStr = $instStr . " OR ";
//                }
//                $fieldstr = "institution";
//                $instStr .= "(";
//                $instStr .= $fieldstr.".root = " . $permittedInstitution->getRoot();
//                $instStr .= " AND ";
//                $instStr .= $fieldstr.".lft < " . $permittedInstitution->getLft();
//                $instStr .= " AND ";
//                $instStr .= $fieldstr.".rgt > " . $permittedInstitution->getRgt();
//                $instStr .= " OR ";
//                $instStr .= $fieldstr.".id = " . $permittedInstitution->getId();
//                $instStr .= ")";
//            }
//        }
//
//        if(1) {
//            //Collaboration check:
//            //1) find collaboration for each user's permitted institution
//            //2) if collaboration exists, check if message's institution belongs to any institution of this collaboration
//            foreach( $permittedInstitutions as $permittedInstitution ) {
//                $collaborations = $this->em->getRepository('AppUserdirectoryBundle:Institution')->
//                    findCollaborationsByNode( $permittedInstitution, array("Union","Intersection") );
//                foreach( $collaborations as $collaboration ) {
//                    foreach( $collaboration->getInstitutions() as $collaborationInstitution ) {
//                        if( $instStr != "" ) {
//                            $instStr = $instStr . " OR ";
//                        }
//                        $fieldstr = "institution";
//                        $instStr .= "(";
//                        $instStr .= $fieldstr.".root = " . $collaborationInstitution->getRoot();
//                        $instStr .= " AND ";
//                        $instStr .= $fieldstr.".lft > " . $collaborationInstitution->getLft();
//                        $instStr .= " AND ";
//                        $instStr .= $fieldstr.".rgt < " . $collaborationInstitution->getRgt();
//                        $instStr .= " OR ";
//                        $instStr .= $fieldstr.".id = " . $collaborationInstitution->getId();
//                        $instStr .= ")";
//                    }
//                }
//            }
//        }//if
//}

        if( $instStr == "" ) {
            $instStr = "1=0";
        }

        return $instStr;
    }
//    public function getInstitutionQuerySingleMatchCriterion($user) {
//        $securityUtil = $this->container->get('user_security_utility');
//        $institutions = $securityUtil->getUserPermittedInstitutions($user);
//        $instStr = "";
//        foreach( $institutions as $inst ) {
//            if( $instStr != "" ) {
//                $instStr = $instStr . " OR ";
//            }
//            $instStr = $instStr . 'message.institution='.$inst->getId();
//            //$instStr = $instStr . 'institution='.$inst->getId();
//        }
//        if( $instStr == "" ) {
//            $instStr = "1=0";
//        }
//        return $instStr;
//    }

    //$collaborationTypesStrArr: array("Union","Intersection","Untrusted Intersection"). If null => ignore collaboration. Default: array("Union","Intersection")
    public function addInstitutionQueryCriterion( $user, $criteriastr, $collaborationTypesStrArr=array("Union") ) {
        $instStr = $this->getInstitutionQueryCriterion($user,$collaborationTypesStrArr);
        if( $instStr != "" ) {
            if( $criteriastr && $criteriastr != "" ) {
                $criteriastr = $criteriastr . " AND (" . $instStr . ") ";
            } else {
                //$criteriastr = $criteriastr . " (" . $instStr . ") ";
                $criteriastr = $instStr;
            }
        }
        return $criteriastr;
    }

    //$dataqualities is a form data: $dataqualities = $form->get('conflicts')->getData();
    public function setDataQualityAccMrn( $entity, $dataqualities ) {

        $em = $this->em;

        foreach( $dataqualities as $dataquality ) {
//            echo "dataquality description= ".$dataquality['description']."
";
//            echo "dataquality accession= ".$dataquality['accession']."
";
//            echo "dataquality accessiontype= ".$dataquality['accessiontype']."
";
//            echo "dataquality mrn= ".$dataquality['mrn']."
";
//            echo "dataquality mrntype= ".$dataquality['mrntype']."
";

            //set correct mrntype (convert text keytype to the object)
            $mrntype = $em->getRepository('AppOrderformBundle:MrnType')->findOneById( $dataquality['mrntype'] );

            //set correct accessiontype
            $accessiontype = $em->getRepository('AppOrderformBundle:AccessionType')->findOneById( $dataquality['accessiontype'] );

            $dataqualityObj = new DataQualityMrnAcc();
            $dataqualityObj->setDescription($dataquality['description']);
            $dataqualityObj->setMrn($dataquality['mrn']);
            $dataqualityObj->setMrntype($mrntype);
            $dataqualityObj->setAccession($dataquality['accession']);
            $dataqualityObj->setAccessiontype($accessiontype);

            $dataqualityObj->setMessage($entity);
            $dataqualityObj->setProvider($entity->getProvider());
            $dataqualityObj->setStatus('active');

//            echo "dataquality: description=".$dataqualityObj->getDescription()."
";
//            echo "dataquality: accession=".$dataqualityObj->getAccession()."
";
//            echo "dataquality: accessionType=".$dataqualityObj->getAccessiontype()."
";
//            echo "dataquality: mrn=".$dataqualityObj->getMrn()."
";
//            echo "dataquality: mrn text=".$dataqualityObj->getMrntype()."
";

            $entity->addDataqualityMrnAcc($dataqualityObj);
        }

    }

    public function setWarningMessageNoInstitution( $user ) {

        $router = $this->container->get('router');
        $userUrl = $router->generate('scan_showuser', array('id' => $user->getId()),UrlGeneratorInterface::ABSOLUTE_URL);
        $homeUrl = $router->generate('main_common_home',array(),UrlGeneratorInterface::ABSOLUTE_URL);
        $sysemail = $this->container->getParameter('default_system_email');

        $flashBag = $this->container->get('user_utility')->getSession()->getFlashBag();

        if( $this->security->isGranted('ROLE_SCANORDER_PROCESSOR') || $this->security->isGranted('ROLE_SCANORDER_ADMIN') ) {

            $webUserUrl = "profile";
            $msg =  "Please add at least one institution to your user ".$webUserUrl." (in the form field titled 'Order data visible to members of (Institutional PHI Scope)') in order to be able to submit data.";

        } else {

            $webUserUrl = "profile";

            $msg =  'Please contact the System Administrator by emailing '.$sysemail.' and request to add to your '.$webUserUrl.
                    ' the name of the Institution that employs you (such as "Weill Cornell Medical College"). '.
                    'You will not be able to place orders until the system administrator completes this step.';

            //send Email
            $subject = "User ".$user." needs to have an Institution added to their profile";

            $message =  "Please visit the ".$userUrl." of user ".$user.
                        " and add the name of the institution that employs this user to enable her or him to place orders & and to view patient information known to that institution:

".
                        $userUrl."
".
                        "

".
                        "Agent Smith
".
                        "Virtual Keeper of O R D E R: ".$homeUrl."
".
                        "Weill Cornell Medical College";

            $emailUtil = $this->container->get('user_mailer_utility');
            $emailUtil->sendEmail($sysemail, $subject, $message);

        }
        $flashBag->add(
            'warning',
            $msg
        );

    }

    public function addDefaultInstitutionalPhiScope( $user, $session=null ) {

        $permittedInstitutions = $this->getAtleastOneInstitutionPHI($user);
        if( count($permittedInstitutions) > 0 ) {
            return $permittedInstitutions;
        }

        $userSecUtil = $this->container->get('user_security_utility');
        //$enableAutoAssignmentInstitutionalScope = $userSecUtil->getSiteSettingParameter('enableAutoAssignmentInstitutionalScope');
        //$autoAssignInstitution = $userSecUtil->getSiteSettingParameter('autoAssignInstitution');
        $autoAssignInstitution = $userSecUtil->getAutoAssignInstitution();

        if( $autoAssignInstitution ) {
            $userSiteSettings = $user->getPerSiteSettings();
            if( !$userSiteSettings ) {
                //set institution to per site settings
                $userSiteSettings = new PerSiteSettings();
                //$userSiteSettings->setAuthor($creator);
                $systemUser = $userSecUtil->findSystemUser();
                $userSiteSettings->setAuthor($systemUser);
                $userSiteSettings->setUser($user);
                //$this->em->persist($userSiteSettings);
            }
            $userSiteSettings->addPermittedInstitutionalPHIScope($autoAssignInstitution);
            $this->em->flush($userSiteSettings);
            $this->em->flush($user);

            if( $session ) {
                $session->getFlashBag()->add(
                    'notice',
                    "Institutional PHI Scope has been set to ".$autoAssignInstitution
                );
            }
        }

        $permittedInstitutions = $this->getAtleastOneInstitutionPHI($user);

        return $permittedInstitutions;
    }
    public function getAndAddAtleastOneInstitutionPHI( $user, $session=null ) {
        $permittedInstitutions = $this->getAtleastOneInstitutionPHI($user);

        if( count($permittedInstitutions) == 0 ) {
            $permittedInstitutions = $this->addDefaultInstitutionalPhiScope($user,$session);
        }
        //echo "permittedInstitutions count=".count($permittedInstitutions)."
";

        return $permittedInstitutions;
    }
    public function getAtleastOneInstitutionPHI( $user ) {
        $permittedInstitutions = array();
        $securityUtil = $this->container->get('user_security_utility');
        $userSiteSettings = $securityUtil->getUserPerSiteSettings($user);
        if( $userSiteSettings ) {
            $permittedInstitutions = $userSiteSettings->getPermittedInstitutionalPHIScope();
        }
        return $permittedInstitutions;
    }

    public function generateUserFilterOptions( $user ) {

        $choicesInst = array(
            "My Orders"=>"My Orders",
            "Where I am the Submitter"=>"Where I am the Submitter",
            "Where I am the Ordering Provider"=>"Where I am the Ordering Provider",
            "Where I am the Course Director"=>"Where I am the Course Director",
            "Where I am the Principal Investigator"=>"Where I am the Principal Investigator",
            "Where I am the Amendment Author"=>"Where I am the Amendment Author"
        );

        if( is_object($user) && $user instanceof User ) {

            $secUtil = $this->container->get('user_security_utility');

            //service scope
            $userServices = $secUtil->getScanOrdersServicesScope($user);

            //chief scope
            $userSiteSettings = $secUtil->getUserPerSiteSettings($user);
            if( $this->security->isGranted('ROLE_SCANORDER_SERVICE_CHIEF') ) {
                $chiefServices = $userSiteSettings->getChiefServices();
                foreach( $chiefServices as $serv ) {
                    if( !$userServices->contains($serv) ) {
                        //echo "add=".$serv."
";
                        $userServices->add($serv);
                    }
                }
            }

            foreach( $userServices as $userService ) {
                //echo "service=".$userService->getName().'
';
                //$choicesInst[$userService->getId()] = "All ".$userService->getName()." Orders";
                $choicesInst["All ".$userService->getName()." Orders"] = $userService->getId(); //flipped
            }

//            echo "
";
//            print_r($choicesInst);
//            echo "
";

            //add all collaboration institutions
            $securityUtil = $this->container->get('user_security_utility');
            $permittedInstitutions = $securityUtil->getUserPermittedInstitutions($user);
            foreach( $permittedInstitutions as $permittedInstitution ) {

                $collaborations = $this->em->getRepository('AppUserdirectoryBundle:Institution')->
                    findCollaborationsByNode( $permittedInstitution, array("Union","Intersection") );

                foreach( $collaborations as $collaborationInstitution ) {
                    $key = "collaborationkey-".$collaborationInstitution->getId();
                    if( !array_key_exists($key,$choicesInst) ) {
                        //echo "1 Adding Collaborating Inst=".$collaborationInstitution."
";
                        //$choicesInst[$key] = "All ".$collaborationInstitution." Orders";
                        $choicesInst["All ".$collaborationInstitution." Orders"] = $key; //flipped
                    }
                }

                //add all PHI scope institutions, i.e. "All NYP Orders"
                $key = "collaborationkey-".$permittedInstitution->getId();
                if( !array_key_exists($key,$choicesInst) ) {
                    //echo "2 Adding Collaborating Inst=".$collaborationInstitution."
";
                    //$choicesInst[$key] = "All ".$permittedInstitution." Orders";
                    $choicesInst["All ".$permittedInstitution." Orders"] = $key; //flipped
                }
            }//foreach

        }

//        echo "
";
//        print_r($choicesInst);
//        echo "
";

        return $choicesInst;
    }

    //get the last order
    public function getPreviousMessage( $categoryStr=null ) {
        $previousOrder = null;

        $user = $this->security->getUser();

//        $previousOrders = $this->em->getRepository('AppOrderformBundle:Message')->findBy(
//            array('provider'=>$user),
//            array('orderdate' => 'DESC'),
//            1                                   //limit to one result
//        );

        $repository = $this->em->getRepository('AppOrderformBundle:Message');
        $dql =  $repository->createQueryBuilder("message");
        $dql->leftJoin('message.provider','provider');
        $dql->leftJoin('message.messageCategory','category');

        $criteria = "provider=".$user->getId(); //." AND category LIKE '%".$categoryStr."%'";
        if( $categoryStr && $categoryStr != "" ) {
            $criteria = $criteria . " AND category.name LIKE '%".$categoryStr."%'";
        }

        $dql->where($criteria);
        $dql->orderBy('message.orderdate','DESC');

        $query = $this->em->createQuery($dql)->setMaxResults(1);
        $previousOrders = $query->getResult();

        if( $previousOrders && count($previousOrders) > 0 ) {
            $previousOrder = $previousOrders[0];
        }

        //echo "prev order=".$previousOrder."
";

        return $previousOrder;
    }

    public function getOrderReturnLocations( $message, $providerid=null, $proxyid=null ) {

        $provider = null;
        $proxy = null;

        if( $message ) {
            $provider = $message->getProvider();
            $proxys = $message->getProxyuser();
            if( count($proxys) > 0 ) {
                $firstProxyWrapper = $proxys->first();
                if( $firstProxyWrapper ) {
                    $proxy = $firstProxyWrapper->getUser();
                }
            }
        } else {
            if( $providerid && $providerid != "" ) {
                $provider = $this->em->getRepository('AppUserdirectoryBundle:User')->find($providerid);
            }
            if( $proxyid && $proxyid != "" && $proxyid != $providerid ) {
                $proxy = $this->em->getRepository('AppUserdirectoryBundle:User')->find($proxyid);
            }
        }

        //get default returnLocation option
        //the top three choices should be the Submitter's Main Office location (from the user who is logged in; selected by default),
        //followed by the "Filing Room",
        //followed by the Ordering Provider's Main Office location, and then everyone else in alphabetical order.

        $mainOfficeLocation = null;
        $surgicalPathLocation = null;
        $orderingProviderMainOfficeLocation = null;

        //1) get submitter location
        if( $provider ) {
            $mainOfficeLocation = $provider->getMainLocation();
        }

        //2) get "Filing Room" location
        $repository = $this->em->getRepository('AppUserdirectoryBundle:Location');
        $dql =  $repository->createQueryBuilder("location");
        $dql->select('location');
        $dql->leftJoin("location.locationTypes", "locationTypes");
        $dql->where("locationTypes.name = 'Filing Room'");
        $query = $this->em->createQuery($dql);
        $surgicalPathLocations = $query->getResult();
        if( $surgicalPathLocations && count($surgicalPathLocations) == 1 ) {
            $surgicalPathLocation = $surgicalPathLocations[0];
        } else {
            $surgicalPathLocation = null;
        }
        //echo "surgicalPathLocation=".$surgicalPathLocation."
";

        //3) orderring provider location
        if( $proxy ) {
            $orderingProviderMainOfficeLocation = $proxy->getMainLocation();
        }

        if( $mainOfficeLocation ) {
            $defaultLocation = $mainOfficeLocation;
        } else if( $surgicalPathLocation ) {
            $defaultLocation = $surgicalPathLocation;
        } else if( $orderingProviderMainOfficeLocation ) {
            $defaultLocation = $surgicalPathLocation;
        } else {
            $defaultLocation = null;
        }

        $preferredChoices = array();
        if( $mainOfficeLocation ) {
            $preferredChoices[] = $mainOfficeLocation;
        }
        if( $surgicalPathLocation ) {
            $preferredChoices[] = $surgicalPathLocation;
        }
        if( $orderingProviderMainOfficeLocation ) {
            $preferredChoices[] = $orderingProviderMainOfficeLocation;
        }

        //echo "defaultLocation=".$defaultLocation."
";

        $res = array();
        $res['data'] = $defaultLocation;
        $res['preferred_choices'] = $preferredChoices;

        //print_r($res);

        return $res;
    }

    //get ordering provider from the most recent order
    public function setLastOrderWithProxyuser($user,$message=null) {
        $repository = $this->em->getRepository('AppOrderformBundle:Message');
        $dql =  $repository->createQueryBuilder("message");
        $dql->select('message');
        $dql->innerJoin("message.provider", "provider");
        $dql->leftJoin("message.proxyuser", "proxyuser");
        $dql->where("provider=:user AND proxyuser.id IS NOT NULL");
        $dql->orderBy("message.orderdate","DESC");
        $query = $this->em->createQuery($dql)->setParameter('user', $user)->setMaxResults(1);
        $lastOrderWithProxies = $query->getResult();
        //echo "count=".count($lastOrderWithProxies)."
";

        $proxyusers = new ArrayCollection();

        if( $message ) {
            if( count($lastOrderWithProxies) > 0 ) {
                foreach( $lastOrderWithProxies as $order ) {
                    //echo "order=".$order->getId()."
";
                    foreach( $order->getProxyuser() as $proxyuser ) {
                        //echo "proxyuser=".$proxyuser."
";
                        $message->addProxyuser($proxyuser);
                        $proxyusers->add($proxyuser);
                    }
                }
            } else {
                //echo "add [".$user."] as proxyuser
";
                $message->addProxyuserAsUser($user);
                foreach( $message->getProxyuser() as $proxyuser ) {
                    $proxyusers->add($proxyuser);
                }

            }
        }

//        foreach( $proxyusers as $proxyuser ) {
//            echo "[".$proxyuser."] is added as proxyuser
";
//        }

        $res = array(
            'proxyusers' => $proxyusers,
            'orders' => $lastOrderWithProxies
        );

        return $res;
    }

    public function removeAllOrdersPatients() {

        $em = $this->em;

        //find slides using this stain: slide(1)->(n)stain(n)->(1)stainList
//        $repository = $em->getRepository('AppOrderformBundle:Message');
//        $dql =  $repository->createQueryBuilder("message");
//        $dql->select('message');
//        $dql->leftJoin("message.slide","slide");
//        $dql->leftJoin("slide.stain","stain");
//        $dql->leftJoin("stain.field","stainList");
//        $dql->where('stainList.id = :stainid');
//        $query = $em->createQuery($dql)->setParameter('stainid', $stain->getId());
//        $messages = $query->getResult();

        if(1) {
            $patientTypes = $this->em->getRepository('AppOrderformBundle:PatientType')->findAll();
            foreach( $patientTypes as $patientType ) {
                $em->remove($patientType);
            }
            $em->flush();
        }

        $messages = $this->em->getRepository('AppOrderformBundle:Message')->findAll();

        foreach( $messages as $message ) {

            foreach( $message->getPatient() as $patient ) {

                foreach( $patient->getDeceased() as $item ) {
                    //$patient->removeDeceased($item);
                    $em->remove($item);
                }

                foreach( $patient->getRace() as $item ) {
                    //$patient->removeRace($item);
                    $em->remove($item);
                }

                foreach( $patient->getType() as $patientType ) {

//                    $patientType->setProvider(null);
//                    $patientType->setSource(null);
//                    $patientType->setMessage(null);
//                    $patientType->setPatient(null);
//                    $patientType->setField(null);

                    //foreach( $patientType->getSources() as $item ) {
                        //$em->remove($item);
                    //}

                    $patient->removeType($patientType);
                    $em->remove($patientType);
                }

                $em->remove($patient);
            }

            foreach( $message->getEncounter() as $encounter ) {

                foreach( $encounter->getInpatientinfo() as $item ) {
                    //$encounter->removeInpatientinfo($item);
                    $em->remove($item);
                }

                foreach( $encounter->getLocation() as $item ) {
                    //$encounter->removeLocation($item);
                    $em->remove($item);
                }

                $em->remove($encounter);
            }

            foreach( $message->getProcedure() as $procedure ) {

                foreach( $procedure->getLocation() as $item ) {
                    //$procedure->removeLocation($item);
                    $em->remove($item);
                }

                $em->remove($procedure);
            }

            foreach( $message->getAccession() as $item ) {
                $em->remove($item);
            }

            foreach( $message->getPart() as $part ) {

                foreach( $part->getDiseaseType() as $item ) {
                    //$part->removeDiseaseType($item);
                    $em->remove($item);
                }

                $em->remove($part);
            }

            foreach( $message->getBlock() as $item ) {
                $em->remove($item);
            }

            foreach( $message->getSlide() as $slide ) {

                foreach( $slide->getStain() as $stain ) {
                    //$slide->removeStain($stain);
                    //$stain->setSlide(null);
                    $em->remove($stain);
                }

                foreach( $slide->getScan() as $scan ) {
                    //$slide->removeScan($scan);
                    $em->remove($scan);
                }

                foreach( $slide->getRelevantscan() as $relevantscan ) {
                    //$slide->removeRelevantscan($relevantscan);
                    //$relevantscan->setSlide(null);
                    $em->remove($relevantscan);
                }

                $em->remove($slide);
            }

            $em->remove($message);
        } //message

        //$em->remove($stain);
        $em->flush();

        return count($messages);
    }

    public function removeAllStains() {

        $em = $this->em;
        $stains = $em->getRepository('AppOrderformBundle:StainList')->findAll();

        $count = 0;

        //stain depenedencies: scan_stain and scan_blockSpecialStain
        foreach( $stains as $stain ) {
            //echo "stain=".$stain->getId()." ".$stain."
";
            //$em->persist($stain);

//            $original = $stain->getOriginal();
//            if( $original ) {
//                echo "original stain=".$original."
";
//                $em->persist($original);
//                $original->removeSynonym($stain);
//                $stain->setOriginal(null);
//                //$em->remove($original);
//                //$em->flush();
//            }
//
//            foreach( $stain->getSynonyms() as $synonim ) {
//                $stain->removeSynonym($synonim);
//                $synonim->setOriginal(null);
//                $stain->setOriginal(null);
//                $em->persist($synonim);
//                $em->remove($synonim);
//            }

            $em->remove($stain);
            //$em->flush($stain);

            $count++;
        }
        $em->flush();

        return $count;
    }

    //Used in new order field: "Order data visible to members of (Institutional PHI Scope)"
    public function getAllScopeInstitutions( $originalPermittedInstitutions, $message, $collaborationTypesStrArr=array("Union","Intersection","Untrusted Intersection") ) {

        //$permittedInstitutions = $this->getPermittedScopeCollaborations($originalPermittedInstitutions,array("Union","Intersection","Untrusted Intersection"));
        $permittedInstitutions = $this->getPermittedScopeCollaborationInstitutions($originalPermittedInstitutions,$collaborationTypesStrArr);

        //include current message institution to the $permittedInstitutions
        $permittedInstitutions = $this->addPhiScopeCurrentMessageInstitution($permittedInstitutions,$message);

        return $permittedInstitutions;
    }

    //The same as getPermittedScopeCollaborationInstitutions
    //get collaborations in the Institutional tree (i.e. "WCM-NYP Collaboration")
//    public function getPermittedScopeCollaborations( $originalPermittedInstitutions, $collaborationTypesStrArr, $withOriginal=true ) {
//        $permittedInstitutions = new ArrayCollection();
//
//        //include collaboration (any type) institutions by user
//        //permittedInstitutionalPHIScope - institutions
//        foreach( $originalPermittedInstitutions as $originalPermittedInstitution ) {
//
//            //add collaboration institutions
//            foreach( $originalPermittedInstitution->getCollaborationInstitutions() as $collaborationInstitution ) {
//                //echo "collaborationInstitution=".$collaborationInstitution."
";
//                $collaborationObjType = $originalPermittedInstitution->getCollaborationType()."";
//                //echo "collaborationObjType=".$collaborationObjType."
";
//                if( $collaborationObjType && in_array($collaborationObjType, $collaborationTypesStrArr) ) {
//                    if( $collaborationInstitution && !$permittedInstitutions->contains($collaborationInstitution)  ) {
//                        $permittedInstitutions->add($collaborationInstitution);
//                    }
//                }
//            }
//
//            //add original permitted intsitutions
//            if( $withOriginal ) {
//                if( $originalPermittedInstitution && !$permittedInstitutions->contains($originalPermittedInstitution)  ) {
//                    $permittedInstitutions->add($originalPermittedInstitution);
//                }
//            }
//
//        }//foreach
//
//        return $permittedInstitutions;
//    }

    //get collaborations as single institutions
    public function getPermittedScopeCollaborationInstitutions( $originalPermittedInstitutions, $collaborationTypesStrArr, $withOriginal=true ) {

        $permittedInstitutions = new ArrayCollection();

        //include collaboration (any type) institutions by user
        //permittedInstitutionalPHIScope - institutions
        foreach( $originalPermittedInstitutions as $originalPermittedInstitution ) {

            if( $withOriginal ) {
                $permittedInstitutions->add($originalPermittedInstitution);
            }
            //echo "### permittedInstitution=".$originalPermittedInstitution->getId().":".$originalPermittedInstitution->getName()."
";

            //get all collaboration to show them in the Order's Institutional PHI Scope
            $collaborationInstitutions = $this->em->getRepository('AppUserdirectoryBundle:Institution')->
                                findCollaborationsByNode( $originalPermittedInstitution, $collaborationTypesStrArr );

            foreach( $collaborationInstitutions as $collaborationInstitution ) {
                //echo "collaborationInstitution=".$collaborationInstitution."
";

                if( $collaborationInstitution && !$permittedInstitutions->contains($collaborationInstitution) ) {
                    //echo "add collaboration inst=".$collaborationInstitution->getId().":".$collaborationInstitution->getName()."
";
                    //add collaboration institution at the first position, so ->first() will auto-set to "WCM-NYP Collaboration" by default
                    $firstInst = $permittedInstitutions->first();               //1) save the first element
                    $permittedInstitutions->set(0,$collaborationInstitution);   //2) set to the first position
                    $permittedInstitutions->add($firstInst);                    //3) add back the previous first element
                }

            }

        }//foreach

        return $permittedInstitutions;
    }

    public function addPhiScopeCurrentMessageInstitution($permittedInstitutions,$message) {
        //include current message institution to the $permittedInstitutions
        if( $message && $message->getInstitution() && !$permittedInstitutions->contains($message->getInstitution()) ) {
            //echo "add permittedInstitutions=".$message->getInstitution()->getName()."
";
            $permittedInstitutions->add($message->getInstitution());
        }

        return $permittedInstitutions;
    }

    //set Performing organization:
    //"Weill Cornell Medical College > Department of Pathology and Laboratory Medicine > Pathology Informatics > Scanning Service"
    public function setDefaultPerformingOrganization($message) {
//        $mapper = array(
//            'prefix' => 'App',
//            'bundleName' => 'UserdirectoryBundle',
//            'className' => 'Institution'
//        );
//        $wcmc = $this->em->getRepository('AppUserdirectoryBundle:Institution')->findOneByAbbreviation("WCM");
//        $pathology = $this->em->getRepository('AppUserdirectoryBundle:Institution')->findByChildnameAndParent(
//            "Pathology and Laboratory Medicine",
//            $wcmc,
//            $mapper
//        );
//        $pathologyInformatcs = $this->em->getRepository('AppUserdirectoryBundle:Institution')->findByChildnameAndParent(
//            "Pathology Informatics",
//            $pathology,
//            $mapper
//        );
//        $scanningService = $this->em->getRepository('AppUserdirectoryBundle:Institution')->findByChildnameAndParent(
//            "Scanning Service",
//            $pathologyInformatcs,
//            $mapper
//        );

        $userSecUtil = $this->container->get('user_security_utility');
        $scanningService = $userSecUtil->getNotEmptyDefaultSiteParameter('defaultOrganizationRecipient',null);

        if( $scanningService ) {
            $organizationRecipient = new InstitutionWrapper();
            $organizationRecipient->setInstitution($scanningService);
            $message->addOrganizationRecipient($organizationRecipient);
        }
    }

    //get default Accession list objects
    public function getDefaultAccessionLists( $level=1, $accessionListType=null ) {
        //Accession list currently is level=1
        //$level = 1;

        $parent = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchy')->findOneByName("Accession Lists");

        if( $accessionListType ) {
            $repository = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchy');
            $dql = $repository->createQueryBuilder("list");

            $dql->where("list.parent = :parentId AND list.level = :level");
            $parameters['parentId'] = $parent->getId();
            $parameters['level'] = $level;

            $dql->andWhere("(list.type = :typedef OR list.type = :typeadd)");
            $parameters['typedef'] = 'default';
            $parameters['typeadd'] = 'user-added';

            $dql->leftJoin('list.accessionListTypes', 'accessionListTypes');
            $dql->andWhere("accessionListTypes.id = :accessionListTypeId ");
            $parameters['accessionListTypeId'] = $accessionListType->getId();

            $query = $this->em->createQuery($dql);
            $query->setParameters($parameters);
            $accessionLists = $query->getResult();

        } else {
            $accessionLists = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchy')->findBy(
                array(
                    'type' => array('default','user-added'),
                    'level' => $level,
                    'parent' => $parent->getId()
                )
            );
        }

        return $accessionLists;
    }
    public function getDefaultAccessionList() {

        //$userSecUtil = $this->container->get('user_security_utility');
        //$sitename = $this->container->getParameter('crn.sitename');
        //$accessionList = $userSecUtil->getSiteSettingParameter('accessionList',$sitename);

        $accessionList = null;
        //echo "accessionList=".$accessionList."
";

        if( !$accessionList ) {
            $accessionListName = "Accessions for Follow-Up";

            $accessionList = null;

            $accessionLists = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchy')->findBy(
                array(
                    'name'=>$accessionListName,
                    'type'=>array('default','user-added')
                )
            );
            if( count($accessionLists) > 0 ) {
                $accessionList = $accessionLists[0];
            }
        }

        if( !$accessionList ) {
            throw new \Exception( "Accession list is not found by name '".$accessionListName."'" );
        }
        return $accessionList;
    }

    //create a new AccessionListHierarchy node and add as a child to the $accessionList
    public function addToAccessionLists( $accessionListType, $message, $testing ) {

        //echo "accessionList count=".count($crnMessage = $message->getCrnEntryMessage()->getAccessionLists())."
";

        //check if addAccessionToList is checked
        if( $message ) {
            if( !$message->getAddAccessionToList() ) {
                //echo "AddAccessionToList is NULL
";
                return null;
            }
        } else {
            return null;
        }
        //echo "continue addToAccessionLists
";
        //exit('1');

        $accession = null;
        $accessions = $message->getAccession();
        if( count($accessions) > 0 ) {
            $accession = $accessions->first();
            //echo "accession id=".$accession->getId()."
";
        }

        if( !$accession ) {
            return null;
        }

        $accessionLists = $message->getAccessionLists();
        if( count($accessionLists) == 0 ) {
            return null;
        }

        $newListElements = $this->addAccessionToAccessionLists($accession,$accessionLists,$accessionListType,$message,$testing);

        return $newListElements;
    }
    public function addAccessionToAccessionLists( $accession, $accessionLists, $accessionListType, $message=null, $testing=false ) {
        if( !$accession ) {
            return null;
        }
        if( count($accessionLists) == 0 ) {
            return null;
        }

        $newListElementArr = array();

        foreach( $accessionLists as $accessionList ) {
            //echo "accessionList=".$accessionList."
";
            $newListElement = $this->addAccessionToAccessionList($accession,$accessionList,$accessionListType,$message,$testing);
            if( $newListElement ) {
                $newListElementArr[] = $newListElement;
            }
        }

        return $newListElementArr;
    }
    public function addAccessionToAccessionList( $accession, $accessionList, $accessionListType, $message=null, $testing=false ) {

        if( !$accession ) {
            return null;
        }

        if( !$accessionList ) {
            return null;
        }

        $userSecUtil = $this->container->get('user_security_utility');
        $user = $this->security->getUser();

        //add only if the accession does not exists in the list
        $similarAccessions = $this->getSameAccessionsInList($accessionList,$accession);
        if( $similarAccessions && count($similarAccessions) > 0 ) {
            //check and set type to user-added if type is disabled
            foreach( $similarAccessions as $similarAccession ) {
                if( $similarAccession->getType() == 'disabled' ) {
                //$similarType = $similarAccession->getType();
                //if( $similarType != 'default' && $similarType != 'user-added' ) {
                    $similarAccession->setType('user-added');
                    if( !$testing ) {
                        $this->em->flush();
                    }
                    return $similarAccession;
                }
            }
            return null;
        }

        //create a new node in the list AccessionListHierarchyand attach it as a child to the $accessionList
        $newListElement = new AccessionListHierarchy();

        $accessionDescription = "Accession ID# " . $accession->getId() . ": " . $accession->obtainFullValidKeyName(); //obtainFullObjectName
        $accessionName = "Accession ID# " . $accession->getId();
        $count = null;
        $userSecUtil->setDefaultList($newListElement, $count, $user, $accessionName);
        $newListElement->setAccession($accession);
        $newListElement->setDescription($accessionDescription);

        if( $message ) {
            $newListElement->setObject($message);

            //Add message's entry tags as "Accession List Types"
            if( $accessionListType ) {
                if ($accessionListType) {
                    $newListElement->addAccessionListType($accessionListType);
                }
            }
        }

        //tree variables
        //set level
        $level = $accessionList->getLevel();
        if( !$level ) {
            $defaultAccessionList = $this->getDefaultAccessionList();
            if( $defaultAccessionList ) {
                //set level the same as default accession list
                $level = $defaultAccessionList->getLevel();
                $accessionList->setLevel($level);
                //attach this new accession list to the parent of the default accession list
                $defaultAccessionListParent = $defaultAccessionList->getParent();
                if( $defaultAccessionListParent ) {
                    $defaultAccessionListParent->addChild($accessionList);
                }
            }
        }
        //echo "level=$level ";
        $level = $level + 1;
        //echo " (+1)=> $level
";
        $newListElement->setLevel($level);
        //set group
        $group = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchyGroupType')->findOneByName('Accession');
        $newListElement->setOrganizationalGroupType($group);

        $accessionList->addChild($newListElement);

        $this->em->persist($newListElement);

        if( !$testing ) {
            $this->em->flush();
        }

        return $newListElement;
    }
    public function getSameAccessionsInList( $accessionList, $accession ) {
        if( $accessionList && $accessionList->getId() && $accession && $accession->getId() ) {
            //ok continue
        } else {
            return null;
        }
        $repository = $this->em->getRepository('AppOrderformBundle:AccessionListHierarchy');
        $dql = $repository->createQueryBuilder("list");

        $dql->where("list.parent = :parentId AND list.accession = :accessionId");
        $parameters['parentId'] = $accessionList->getId();
        $parameters['accessionId'] = $accession->getId();

        $dql->andWhere("(list.type = :typedef OR list.type = :typeadd)");
        $parameters['typedef'] = 'default';
        $parameters['typeadd'] = 'user-added';

        $query = $this->em->createQuery($dql);
        $query->setParameters($parameters);
        $accessions = $query->getResult();
        if( count($accessions) > 0 ) {
            return $accessions;
        }
        return null;
    }

}


text:
__all__ = ['Source']

class Source(object):
    __slots__ = ['body', 'name']

    def __init__(self, body, name='GraphQL'):
        self.body = body
        self.name = name

    def __eq__(self, other):
        if isinstance(other, Source):
            return self.body == other.body and self.name == other.name
        return False


text:
use phpsandbox;

grant all on phpsandbox.* to 'phpsandbox'@'%' identified by 'phpsandbox';
flush privileges;

drop table if exists photoman_album_image;
drop table if exists photoman_album;
drop table if exists photoman_image;
drop table if exists photoman_user;

create table photoman_user (
	user_id int not null auto_increment,
	username varchar(255) not null,
	password varchar(255) not null,
	access_token varchar(255),
	access_expires int,
	enabled char(1) default 'Y',
	primary key(user_id)
);

create table photoman_album (
	album_id int not null auto_increment,
	user_id int not null,
	name varchar(255) not null,
	primary key (album_id)
);

create index idx_photoman_album_1 on
	photoman_album(user_id, name);

create table photoman_image (
	image_id int not null auto_increment,
	user_id int not null,
	folder varchar(1024) not null,
	filename varchar(255) not null,
	md5sum varchar(100) not null unique,
	primary key (image_id)
);

create index idx_photoman_image_1 on
	photoman_image(user_id, filename);

create table photoman_album_image (
	album_id int not null,
	image_id int not null,
	primary key (album_id, image_id)
);


text:
from neutron_lib.api.definitions import availability_zone
from neutron_lib.api.definitions import network_availability_zone
from neutron_lib.tests.unit.api.definitions import base

class NetworkAvailabilityZoneDefinitionTestCase(base.DefinitionBaseTestCase):
    extension_module = network_availability_zone
    extension_attributes = (availability_zone.AZ_HINTS,
                            availability_zone.COLLECTION_NAME)