text:
__author__ = "Christian Kongsgaard"
__license__ = "MIT"

# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS

# Modules:
import os
import datetime
import time
import shutil
import typing
from mongoengine import Q

# RiBuild Modules:
from delphin_6_automation.database_interactions.db_templates import delphin_entry
from delphin_6_automation.database_interactions import general_interactions as general_interact
from delphin_6_automation.logging.ribuild_logger import ribuild_logger
from delphin_6_automation.backend import simulation_worker

# Logger
logger = ribuild_logger()

# -------------------------------------------------------------------------------------------------------------------- #
# RIBUILD SIMULATION FUNCTIONS AND CLASSES

def download_simulation_result(sim_id: str, download_path: str, raw_or_processed='raw') -> None:
    """
    Downloads Delphin simulation results from the database.

    :param sim_id: Delphin project ID
    :param download_path: Path to download to
    :param raw_or_processed: Whether to download the raw results or the processed ones
    :return: None
    """

    delphin_doc = delphin_entry.Delphin.objects(id=sim_id).first()

    download_extended_path = download_path + '/' + str(sim_id)
    os.mkdir(download_extended_path)

    if raw_or_processed == 'raw':
        result_id = delphin_doc.results_raw
        logger.info(f'Downloads raw result with ID: {result_id} from Delphin project with ID: {sim_id}')
        general_interact.download_raw_result(result_id.id, download_extended_path)

    elif raw_or_processed == 'processed':
        pass
        # TODO - Download processed results from database

    else:
        raise ValueError('raw_or_processed has to be raw or processed. Value given was: ' + str(raw_or_processed))

    return None

def find_next_sim_in_queue() -> typing.Optional[str]:
    """
    Finds the next entry in the simulation queue, which is not yet simulated and has the highest queue priority.

    :return: If a entry is found the id will be returned otherwise None.
    """

    try:
        id_ = delphin_entry.Delphin.objects(simulating=False, simulated=None).order_by('-queue_priority').first().id
        set_simulating(str(id_), True)
        logger.debug(f'Found unsimulated Delphin project with ID: {id_}')
        return str(id_)

    except AttributeError:
        logger.info('All Delphin Projects in the queue are simulated!')
        time.sleep(60)
        return None

def set_simulating(id_: str, set_to: bool) -> str:
    """
    Set the simulating flag of an entry.

    :param id_: ID of the entry
    :param set_to: What to set simulating to. Should be either True or False.
    :return: ID of the entry
    """

    delphin_doc = delphin_entry.Delphin.objects(id=id_).first()

    if set_to:
        delphin_doc.update(set__simulating=datetime.datetime.now())
    else:
        delphin_doc.update(set__simulating=None)
    logger.debug(f'For Delphin project with ID: {id_}, simulating was changed to: {set_to}')

    return delphin_doc.id

def set_simulated(id_: str) -> str:
    """
    Flags an entry for finishing the simulation.

    :param id_: ID of the entry
    :return: ID of the entry
    """

    simulation = delphin_entry.Delphin.objects(id=id_).first()
    simulation.update(set__simulated=datetime.datetime.now())
    set_simulating(id_, False)
    logger.debug(f'For Delphin project with ID: {id_}, simulated was changed to: {datetime.datetime.now()}')

    return simulation.id

def clean_simulation_folder(path: str) -> bool:
    """
    Cleans the simulation folder for content

    :param path: Path to the simulation folder
    :return: True on success
    """

    shutil.rmtree(path)
    logger.debug(f'Deleted {path}')

    return True

def set_simulation_time(sim_id: str, computation_time: datetime.timedelta) -> str:
    """Sets the time it took to simulate Delphin project"""

    delphin_doc = delphin_entry.Delphin.objects(id=sim_id).first()
    delphin_doc.update(set__simulation_time=computation_time.total_seconds())
    logger.debug(f'For Delphin project with ID: {sim_id}, '
                 f'simulation time was changed to: {computation_time.total_seconds()}')

    return sim_id

def set_simulation_time_estimate(sim_id: str, computation_time: int) -> str:
    """Sets the estimate simulation time for a Delphin project"""

    delphin_doc = delphin_entry.Delphin.objects(id=sim_id).first()
    delphin_doc.update(set__estimated_simulation_time=computation_time)
    logger.debug(f'For Delphin project with ID: {sim_id}, '
                 f'simulation time was changed to: {computation_time}')

    return sim_id

def get_simulation_time_estimate(delphin_id: str) -> int:
    """Returns the estimated simulation time of Delphin project, given its ID"""

    delphin_doc = delphin_entry.Delphin.objects(id=delphin_id).first()

    if delphin_doc.estimated_simulation_time:
        return delphin_doc.estimated_simulation_time
    else:
        return general_interact.compute_simulation_time(delphin_id)

def wait_until_simulated(delphin_ids: list, is_sampling_ahead: bool = False) -> bool:
    """
    Wait until all simulations in the given list is simulated.

    :param delphin_ids: List with Delphin database ids
    :return: True
    """

    simulated = [False] * len(delphin_ids)
    logger.info(f'Checking if Delphin projects have been simulated')

    while not all(simulated):
        for index, id_ in enumerate(delphin_ids):
            entry = delphin_entry.Delphin.objects(id=id_).only('simulated').first()

            if entry.simulated:
                simulated[index] = True

        logger.debug(f'Waiting until all projects are simulated. {sum(simulated)}/{len(simulated)} is simulated')

        if all(simulated):
            logger.info('All projects are simulated')
            return True

        if sum(simulated) >= (len(simulated) * 0.9) and not is_sampling_ahead:
            logger.info('90% of projects are simulated')
            return False

        if not all(simulated):
            time.sleep(180)

    logger.info('All projects are simulated')
    return True

def find_exceeded() -> typing.Optional[str]:
    """
    Finds a Delphin project which has exceeded the simulation run time limit.

    :return: If a entry is found the id will be returned otherwise None.
    """

    try:
        id_ = delphin_entry.Delphin.objects(simulating=False,
                                            exceeded_time_limit=True).order_by('-queue_priority').first().id
        set_simulating(str(id_), True)
        logger.debug(f'Found exceeded Delphin project with ID: {id_}')
        return str(id_)

    except AttributeError:
        logger.info('No exceeded Delphin Projects in the database!')
        time.sleep(60)
        return None

def check_simulations(auth_file: str, only_count=False) -> tuple:
    """Checks running simulations on HPC"""

    terminal_call = f"bstat\n"

    client = simulation_worker.connect_to_hpc(auth_file)

    channel = client.invoke_shell()
    time.sleep(0.5)
    channel.send(terminal_call)
    channel_data = get_command_results(channel)

    simulation_data = channel_data.split('hpclogin3')[1]

    channel.close()
    client.close()

    # Process string
    simulation_data = simulation_data.split("\n")[1:]

    count = 0
    p_count = 0
    for data in simulation_data:
        data = data.strip()
        if data and data != '~' and 'JOBID' not in data:
            if "pend" in data.lower():
                p_count += 1
            else:
                count += 1
            if not only_count:
                logger.info(data)

    return count, p_count

def get_command_results(channel):
    ## http://joelinoff.com/blog/?p=905

    interval = 0.1
    maxseconds = 10
    maxcount = maxseconds / interval
    bufsize = 1024

    # Poll until completion or timeout
    # Note that we cannot directly use the stdout file descriptor
    # because it stalls at 64K bytes (65536).
    input_idx = 0
    timeout_flag = False
    start = datetime.datetime.now()
    start_secs = time.mktime(start.timetuple())
    output = ''
    channel.setblocking(0)

    while True:
        if channel.recv_ready():
            data = channel.recv(bufsize).decode('utf-8')
            output += data

        if channel.exit_status_ready():
            break

        # Timeout check
        now = datetime.datetime.now()
        now_secs = time.mktime(now.timetuple())
        et_secs = now_secs - start_secs
        if et_secs > maxseconds:
            timeout_flag = True
            break

        rbuffer = output.rstrip(' ')
        if len(rbuffer) > 0 and (rbuffer[-1] == '#' or rbuffer[-1] == '>'): ## got a Cisco command prompt
            break

        time.sleep(0.2)

    return output

def check_simulating_projects(not_simulating: bool = False) -> None:

    expiry_date = datetime.datetime.now() - datetime.timedelta(minutes=300)
    projects = delphin_entry.Delphin.objects(simulating__lt=expiry_date)

    logger.info(f'There are {projects.count()} projects, which have exceeded their simulation time.')

    if not_simulating and projects.count() > 0:
        logger.info('Setting exceed simulations to not simulating')
        projects.update(simulating=None)

        projects = delphin_entry.Delphin.objects(simulating__lt=expiry_date)
        logger.info(f'There are {projects.count()} projects, which have exceeded their simulation time.')


text:
from functools import partial
import zlib
import json
from io import BytesIO
import sys
import platform

from electrum_arg.plugins import BasePlugin, hook
from electrum_arg_gui.qt.util import WaitingDialog, EnterButton, WindowModalDialog
from electrum_arg.util import print_msg, print_error
from electrum_arg.i18n import _

from PyQt4.QtGui import *
from PyQt4.QtCore import *

try:
    import amodem.audio
    import amodem.main
    import amodem.config
    print_error('Audio MODEM is available.')
    amodem.log.addHandler(amodem.logging.StreamHandler(sys.stderr))
    amodem.log.setLevel(amodem.logging.INFO)
except ImportError:
    amodem = None
    print_error('Audio MODEM is not found.')

class Plugin(BasePlugin):

    def __init__(self, parent, config, name):
        BasePlugin.__init__(self, parent, config, name)
        if self.is_available():
            self.modem_config = amodem.config.slowest()
            self.library_name = {
                'Linux': 'libportaudio.so'
            }[platform.system()]

    def is_available(self):
        return amodem is not None

    def requires_settings(self):
        return True

    def settings_widget(self, window):
        return EnterButton(_('Settings'), partial(self.settings_dialog, window))

    def settings_dialog(self, window):
        d = WindowModalDialog(window, _("Audio Modem Settings"))

        layout = QGridLayout(d)
        layout.addWidget(QLabel(_('Bit rate [kbps]: ')), 0, 0)

        bitrates = list(sorted(amodem.config.bitrates.keys()))

        def _index_changed(index):
            bitrate = bitrates[index]
            self.modem_config = amodem.config.bitrates[bitrate]

        combo = QComboBox()
        combo.addItems(map(str, bitrates))
        combo.currentIndexChanged.connect(_index_changed)
        layout.addWidget(combo, 0, 1)

        ok_button = QPushButton(_("OK"))
        ok_button.clicked.connect(d.accept)
        layout.addWidget(ok_button, 1, 1)

        return bool(d.exec_())

    @hook
    def transaction_dialog(self, dialog):
        b = QPushButton()
        b.setIcon(QIcon(":icons/speaker.png"))

        def handler():
            blob = json.dumps(dialog.tx.as_dict())
            self._send(parent=dialog, blob=blob)
        b.clicked.connect(handler)
        dialog.sharing_buttons.insert(-1, b)

    @hook
    def scan_text_edit(self, parent):
        parent.addButton(':icons/microphone.png', partial(self._recv, parent),
                         _("Read from microphone"))

    @hook
    def show_text_edit(self, parent):
        def handler():
            blob = str(parent.toPlainText())
            self._send(parent=parent, blob=blob)
        parent.addButton(':icons/speaker.png', handler, _("Send to speaker"))

    def _audio_interface(self):
        interface = amodem.audio.Interface(config=self.modem_config)
        return interface.load(self.library_name)

    def _send(self, parent, blob):
        def sender_thread():
            with self._audio_interface() as interface:
                src = BytesIO(blob)
                dst = interface.player()
                amodem.main.send(config=self.modem_config, src=src, dst=dst)

        print_msg('Sending:', repr(blob))
        blob = zlib.compress(blob)

        kbps = self.modem_config.modem_bps / 1e3
        msg = 'Sending to Audio MODEM ({0:.1f} kbps)...'.format(kbps)
        WaitingDialog(parent, msg, sender_thread)

    def _recv(self, parent):
        def receiver_thread():
            with self._audio_interface() as interface:
                src = interface.recorder()
                dst = BytesIO()
                amodem.main.recv(config=self.modem_config, src=src, dst=dst)
                return dst.getvalue()

        def on_finished(blob):
            if blob:
                blob = zlib.decompress(blob)
                print_msg('Received:', repr(blob))
                parent.setText(blob)

        kbps = self.modem_config.modem_bps / 1e3
        msg = 'Receiving from Audio MODEM ({0:.1f} kbps)...'.format(kbps)
        WaitingDialog(parent, msg, receiver_thread, on_finished)

redpajama_set_name: RedPajamaGithub


text: by jake owen. 5th  november 2017


text:
<?php

namespace app\modules;

use Yii;

/**
 * admin module definition class
 */
class AdminModule extends \yii\base\Module {

    /**
     * @inheritdoc
     */
    public $controllerNamespace = 'app\modules\controllers';
    public $layout;
    public $layoutPath;

    /**
     * @inheritdoc
     */
    public function init() {

            $this->layout = '@app/modules/views/layouts/main';
            $this->layoutPath = 'main';
            parent::init();

        // custom initialization code goes here
    }

}


text:
layout: page
title: Cloud Falls Logistics Party
date: 2016-05-24
author: Doris Richardson
tags: weekly links, java
status: published
summary: Sed metus ex, ullamcorper at.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/09/2017
  endDate: 10/12/2017
  ctyhocn: BOSLAHX
  groupCode: CFLP
published: true
---
Sed sagittis ullamcorper dictum. In vitae felis sit amet tortor tincidunt gravida. Integer sed lectus lacus. Fusce nec blandit leo. Integer accumsan sagittis odio, in volutpat ligula varius id. Mauris sit amet lectus lorem. Ut eu ante congue lorem molestie porttitor.

* Fusce luctus mi vestibulum, feugiat metus sit amet, molestie odio.

Sed gravida lorem velit, nec sagittis magna auctor vel. Mauris eu ligula cursus, pellentesque lorem vel, hendrerit odio. Etiam eu purus vel lectus interdum interdum. Etiam vitae scelerisque dolor. Ut et odio tellus. Ut vulputate velit nunc, ut sagittis orci varius eu. Donec bibendum interdum tortor a fermentum. Nullam laoreet mattis orci sed volutpat. Nulla ac ipsum dolor. In hac habitasse platea dictumst. Curabitur euismod quis turpis vitae consequat. Phasellus nec iaculis dolor. In ultricies ex ut lectus dapibus, vel pulvinar nibh cursus. Suspendisse at faucibus nibh.


text:
@interface MyTextField : UITextField<UITextFieldDelegate>

///为了把检测之后的结果显示到view上 需要传入self && 为了弹起视图,需要传入一个Controller
@property (strong, nonatomic) UIViewController *mview;

///输入小数点位数,默认为2位 传3为3位
@property NSInteger numlimit;

///检测输入格式,默认为不检测,传YES为开启检测
@property BOOL isTestFormat;

///传toast位置,默认center
@property (strong, nonatomic) NSString *postion;

///第三方键盘弹出弹起视图
@property (strong, nonatomic) ZYKeyboardUtil *keyboardUtil;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiskGazer.Helper
{
	/// <summary>
	/// OS version information
	/// </summary>
	public static class OsVersion
	{
		/// <summary>
		/// Whether OS is Vista or newer
		/// </summary>
		/// <remarks>Windows Vista = version 6.0</remarks>
		public static bool IsVistaOrNewer
		{
			get => Environment.OSVersion.Version is { Major: >= 6 };
		}

		/// <summary>
		/// Whether OS is Windows 8 or newer
		/// </summary>
		/// <remarks>Windows 8 = version 6.2</remarks>
		public static bool IsEightOrNewer
		{
			get => Environment.OSVersion.Version is { Major: 6, Minor: >= 2 } or { Major: >= 7 };
		}
	}
}


text:
using namespace lldb;
using namespace lldb_private;

SBLineEntry::SBLineEntry() : m_opaque_up() {
  LLDB_RECORD_CONSTRUCTOR_NO_ARGS(SBLineEntry);
}

SBLineEntry::SBLineEntry(const SBLineEntry &rhs) : m_opaque_up() {
  LLDB_RECORD_CONSTRUCTOR(SBLineEntry, (const lldb::SBLineEntry &), rhs);

  m_opaque_up = clone(rhs.m_opaque_up);
}

SBLineEntry::SBLineEntry(const lldb_private::LineEntry *lldb_object_ptr)
    : m_opaque_up() {
  if (lldb_object_ptr)
    m_opaque_up = std::make_unique<LineEntry>(*lldb_object_ptr);
}

const SBLineEntry &SBLineEntry::operator=(const SBLineEntry &rhs) {
  LLDB_RECORD_METHOD(const lldb::SBLineEntry &,
                     SBLineEntry, operator=,(const lldb::SBLineEntry &), rhs);

  if (this != &rhs)
    m_opaque_up = clone(rhs.m_opaque_up);
  return LLDB_RECORD_RESULT(*this);
}

void SBLineEntry::SetLineEntry(const lldb_private::LineEntry &lldb_object_ref) {
  m_opaque_up = std::make_unique<LineEntry>(lldb_object_ref);
}

SBLineEntry::~SBLineEntry() {}

SBAddress SBLineEntry::GetStartAddress() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBLineEntry,
                                   GetStartAddress);

  SBAddress sb_address;
  if (m_opaque_up)
    sb_address.SetAddress(&m_opaque_up->range.GetBaseAddress());

  return LLDB_RECORD_RESULT(sb_address);
}

SBAddress SBLineEntry::GetEndAddress() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBAddress, SBLineEntry, GetEndAddress);

  SBAddress sb_address;
  if (m_opaque_up) {
    sb_address.SetAddress(&m_opaque_up->range.GetBaseAddress());
    sb_address.OffsetAddress(m_opaque_up->range.GetByteSize());
  }
  return LLDB_RECORD_RESULT(sb_address);
}

bool SBLineEntry::IsValid() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBLineEntry, IsValid);
  return this->operator bool();
}
SBLineEntry::operator bool() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(bool, SBLineEntry, operator bool);

  return m_opaque_up.get() && m_opaque_up->IsValid();
}

SBFileSpec SBLineEntry::GetFileSpec() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(lldb::SBFileSpec, SBLineEntry, GetFileSpec);

  SBFileSpec sb_file_spec;
  if (m_opaque_up.get() && m_opaque_up->file)
    sb_file_spec.SetFileSpec(m_opaque_up->file);

  return LLDB_RECORD_RESULT(sb_file_spec);
}

uint32_t SBLineEntry::GetLine() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBLineEntry, GetLine);

  uint32_t line = 0;
  if (m_opaque_up)
    line = m_opaque_up->line;

  return line;
}

uint32_t SBLineEntry::GetColumn() const {
  LLDB_RECORD_METHOD_CONST_NO_ARGS(uint32_t, SBLineEntry, GetColumn);

  if (m_opaque_up)
    return m_opaque_up->column;
  return 0;
}

void SBLineEntry::SetFileSpec(lldb::SBFileSpec filespec) {
  LLDB_RECORD_METHOD(void, SBLineEntry, SetFileSpec, (lldb::SBFileSpec),
                     filespec);

  if (filespec.IsValid())
    ref().file = filespec.ref();
  else
    ref().file.Clear();
}
void SBLineEntry::SetLine(uint32_t line) {
  LLDB_RECORD_METHOD(void, SBLineEntry, SetLine, (uint32_t), line);

  ref().line = line;
}

void SBLineEntry::SetColumn(uint32_t column) {
  LLDB_RECORD_METHOD(void, SBLineEntry, SetColumn, (uint32_t), column);

  ref().line = column;
}

bool SBLineEntry::operator==(const SBLineEntry &rhs) const {
  LLDB_RECORD_METHOD_CONST(
      bool, SBLineEntry, operator==,(const lldb::SBLineEntry &), rhs);

  lldb_private::LineEntry *lhs_ptr = m_opaque_up.get();
  lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_up.get();

  if (lhs_ptr && rhs_ptr)
    return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) == 0;

  return lhs_ptr == rhs_ptr;
}

bool SBLineEntry::operator!=(const SBLineEntry &rhs) const {
  LLDB_RECORD_METHOD_CONST(
      bool, SBLineEntry, operator!=,(const lldb::SBLineEntry &), rhs);

  lldb_private::LineEntry *lhs_ptr = m_opaque_up.get();
  lldb_private::LineEntry *rhs_ptr = rhs.m_opaque_up.get();

  if (lhs_ptr && rhs_ptr)
    return lldb_private::LineEntry::Compare(*lhs_ptr, *rhs_ptr) != 0;

  return lhs_ptr != rhs_ptr;
}

const lldb_private::LineEntry *SBLineEntry::operator->() const {
  return m_opaque_up.get();
}

lldb_private::LineEntry &SBLineEntry::ref() {
  if (m_opaque_up == nullptr)
    m_opaque_up.reset(new lldb_private::LineEntry());
  return *m_opaque_up;
}

const lldb_private::LineEntry &SBLineEntry::ref() const { return *m_opaque_up; }

bool SBLineEntry::GetDescription(SBStream &description) {
  LLDB_RECORD_METHOD(bool, SBLineEntry, GetDescription, (lldb::SBStream &),
                     description);

  Stream &strm = description.ref();

  if (m_opaque_up) {
    char file_path[PATH_MAX * 2];
    m_opaque_up->file.GetPath(file_path, sizeof(file_path));
    strm.Printf("%s:%u", file_path, GetLine());
    if (GetColumn() > 0)
      strm.Printf(":%u", GetColumn());
  } else
    strm.PutCString("No value");

  return true;
}

lldb_private::LineEntry *SBLineEntry::get() { return m_opaque_up.get(); }

namespace lldb_private {
namespace repro {

template <>
void RegisterMethods<SBLineEntry>(Registry &R) {
  LLDB_REGISTER_CONSTRUCTOR(SBLineEntry, ());
  LLDB_REGISTER_CONSTRUCTOR(SBLineEntry, (const lldb::SBLineEntry &));
  LLDB_REGISTER_METHOD(const lldb::SBLineEntry &,
                       SBLineEntry, operator=,(const lldb::SBLineEntry &));
  LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBLineEntry, GetStartAddress,
                             ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBAddress, SBLineEntry, GetEndAddress, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBLineEntry, IsValid, ());
  LLDB_REGISTER_METHOD_CONST(bool, SBLineEntry, operator bool, ());
  LLDB_REGISTER_METHOD_CONST(lldb::SBFileSpec, SBLineEntry, GetFileSpec, ());
  LLDB_REGISTER_METHOD_CONST(uint32_t, SBLineEntry, GetLine, ());
  LLDB_REGISTER_METHOD_CONST(uint32_t, SBLineEntry, GetColumn, ());
  LLDB_REGISTER_METHOD(void, SBLineEntry, SetFileSpec, (lldb::SBFileSpec));
  LLDB_REGISTER_METHOD(void, SBLineEntry, SetLine, (uint32_t));
  LLDB_REGISTER_METHOD(void, SBLineEntry, SetColumn, (uint32_t));
  LLDB_REGISTER_METHOD_CONST(
      bool, SBLineEntry, operator==,(const lldb::SBLineEntry &));
  LLDB_REGISTER_METHOD_CONST(
      bool, SBLineEntry, operator!=,(const lldb::SBLineEntry &));
  LLDB_REGISTER_METHOD(bool, SBLineEntry, GetDescription, (lldb::SBStream &));
}

}
}


text:
id: 704209b1-d218-4bba-8aa3-454ade3ccf0e
post_id: bad142d4-ce4f-46a9-9bb3-eb5b71600d37
draft: false
author:
    name: chaostangent
    email: john.noel@chaostangent.com
    ip: 93.96.16.21
---

Hmm, perhaps not, I can see how her zany antics would appeal. My point really is that there's no depth to her, not even implied. The only things we know about her is she spends her time either stalking Takashi or planning on how to stalk Takashi. Whereas with him we at least find out some of his hobbies, interests and family life.

I guess I find the lack of propriety in Yamada very distasteful without something else in her character to balance it out. In the first three episodes she was just a comedy cudgel being beaten against Takashi, and not a very funny one I found.


text:
using HLife.GameEntities;
using HLife.GameEntities.People;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace HLife
{
    /// <summary>
    /// Interaction logic for PersonInformation.xaml
    /// </summary>
    public partial class PersonInformationWindow : Window
    {
        public PersonInformationWindow()
        {
            InitializeComponent();

            this.CreateStatus();

            this.CreateAttributes();

            // Release the form on close.
            //this.FormClosed += (sender, e) => { Game.Instance.WindowController.Windows.Remove(this); this.Dispose(true); };
        }

        protected void CreateStatus()
        {
            this.wrap_Status.Height = 0;

            foreach (Stat item in Stats.DefaultPersonStatusItems.Where(e => e.Type == "status"))
            {
                GroupBox box = new GroupBox();
                box.Width = this.wrap_Status.Width - 20;
                box.VerticalAlignment = VerticalAlignment.Top;
                box.Header = item.Name;
                this.wrap_Status.Children.Add(box);

                Grid grid = new Grid();
                grid.VerticalAlignment = VerticalAlignment.Top;
                box.Content = grid;

                if (item.ControlType == typeof(ProgressBar))
                {
                    ProgressBar value = (ProgressBar)item.GetControlInstance();
                    value.Margin = new Thickness(0, 2, 0, 0);
                    value.Name = "pgb_" + item.Name;
                    value.Height = 14;

                    ToolTip tip = new System.Windows.Controls.ToolTip();
                    tip.Content = "0";
                    value.ToolTip = tip;

                    grid.Children.Add(value);
                }
                else if (item.ControlType == typeof(CheckBox))
                {
                    CheckBox value = (CheckBox)item.GetControlInstance();
                    value.Margin = new Thickness(0, 2, 0, 0);
                    value.Name = "chk_" + item.Name;
                    value.Height = 14;
                    value.IsEnabled = false;
                    grid.Children.Add(value);
                }

                this.wrap_Status.Height += box.Height;
            }
        }

        protected void CreateAttributes()
        {
            this.stack_Attributes.Height = 0;

            foreach (Stat item in Stats.DefaultPersonStatusItems.Where(e => e.Type == "attribute"))
            {
                GroupBox box = new GroupBox();
                box.Width = this.wrap_Status.Width - 20;
                box.VerticalAlignment = VerticalAlignment.Top;
                box.Header = item.Name;
                this.stack_Attributes.Children.Add(box);

                Grid grid = new Grid();
                grid.VerticalAlignment = VerticalAlignment.Top;
                box.Content = grid;

                if (item.ControlType == typeof(ProgressBar))
                {
                    ProgressBar value = (ProgressBar)item.GetControlInstance();
                    value.Margin = new Thickness(0, 2, 0, 0);
                    value.Name = "pgb_" + item.Name;
                    value.Height = 14;
                    grid.Children.Add(value);
                }
                else if (item.ControlType == typeof(CheckBox))
                {
                    CheckBox value = (CheckBox)item.GetControlInstance();
                    value.Margin = new Thickness(0, 2, 0, 0);
                    value.Name = "chk_" + item.Name;
                    value.Height = 14;
                    value.IsEnabled = false;
                    grid.Children.Add(value);
                }

                this.stack_Attributes.Height += box.Height;
            }
        }

        public void UpdateWindow()
        {
            if (this.Tag != null)
            {
                Person myPerson = (Person)this.Tag;

                this.Title = myPerson.Name;

                ((Image)this.FindName("img_Avatar")).Source = Game.Instance.ResourceController.GetImage(Game.Instance.ResourceController.BuildPath(@"\Assets\Images\Characters\" + myPerson.Image));

                this.UpdateAttributes(myPerson);

                this.UpdateStatus(myPerson);
            }
        }

        protected void UpdateAttributes(Person myPerson)
        {
            int count = 0;

            foreach (Stat item in myPerson.Stats.StatEntries.Where(e => e.Type == "attribute"))
            {
                if (item.ControlType == typeof(ProgressBar))
                {
                    ProgressBar value = (ProgressBar)LogicalTreeHelper.FindLogicalNode(this.tab_Attributes, "pgb_" + item.Name);
                    value.Value = Math.Max(Math.Min((int)(double)item.Value, value.Maximum), value.Minimum);
                }
                else if (item.ControlType == typeof(CheckBox))
                {
                    CheckBox value = (CheckBox)LogicalTreeHelper.FindLogicalNode(this.tab_Attributes, "chk_" + item.Name);
                    value.IsChecked = (bool)item.Value;
                }

                count++;
            }
        }

        protected void UpdateStatus(Person myPerson)
        {
            int count = 0;

            foreach (Stat item in myPerson.Stats.StatEntries.Where(e => e.Type == "status"))
            {
                if (item.ControlType == typeof(ProgressBar))
                {
                    ProgressBar value = (ProgressBar)LogicalTreeHelper.FindLogicalNode(this.tab_Status, "pgb_" + item.Name);

                    if(item.Maximum != null)
                    {
                        if (item.Maximum.Split('.').Count() > 1)
                        {
                            value.Maximum = (double)ReflectionUtilities.GetPropertyValue(myPerson, item.Maximum);
                        }
                        else
                        {
                            value.Maximum = myPerson.Stats.GetValue<double>(item.Maximum);
                        }
                    }

                    try
                    {
                        value.Value = Math.Max(Math.Min((double)item.Value, value.Maximum), value.Minimum);
                    }
                    catch(InvalidCastException)
                    {
                        value.Value = Math.Max(Math.Min((int)item.Value, value.Maximum), value.Minimum);
                    }
                    ((ToolTip)value.ToolTip).Content = value.Value;
                }
                else if (item.ControlType == typeof(CheckBox))
                {
                    CheckBox value = (CheckBox)LogicalTreeHelper.FindLogicalNode(this.tab_Status, "chk_" + item.Name);
                    value.IsChecked = (bool)item.Value;
                }

                count++;
            }
        }

        private void Window_SourceInitialized(object sender, EventArgs e)
        {
            IconHelper.RemoveIcon(this);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Game.Instance.WindowController.Windows.Remove(this);
        }

        private void Window_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            switch(e.Key)
            {
                case Key.S:
                    this.tab_Status.Focus();
                    break;

                case Key.A:
                    this.tab_Attributes.Focus();
                    break;

                case Key.I:
                    this.tab_Inventory.Focus();
                    break;
            }
        }
    }
}


text:
package to.kit.drink.rest;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.api.services.drive.model.Permission;

public class GaDrive extends GaBase {
	private static final String APP_NAME = "drunker";
	private static final String FIELDS = "id,name,description,mimeType,thumbnailLink,webContentLink,webViewLink,permissions";
	protected static final List<String> SCOPES = Arrays.asList(DriveScopes.DRIVE);

	private Permission createPermission(String fileId) throws IOException {
		GoogleCredential credential = authorize().createScoped(SCOPES);
		Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
				.setApplicationName(APP_NAME)
				.build();
		Permission permission = new Permission().setRole("reader").setType("anyone");

		return service.permissions().create(fileId, permission).execute();
	}

	public File create(String name, String description, String type, byte[] bytes) throws IOException {
		GoogleCredential credential = authorize().createScoped(SCOPES);
		Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
				.setApplicationName(APP_NAME)
				.build();
		File file = new File().setName(name).setDescription(description);
		ByteArrayContent mediaContent = new ByteArrayContent(type, bytes);
		File result = service.files()
				.create(file, mediaContent)
				.setIgnoreDefaultVisibility(Boolean.FALSE)
				.execute();
		String fileId = result.getId();

		createPermission(fileId);
//System.out.println(result.toPrettyString());
		return read(fileId);
	}

	public File read(String fileId) throws IOException {
		GoogleCredential credential = authorize().createScoped(SCOPES);
		Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
				.setApplicationName(APP_NAME)
				.build();
		File file = service.files().get(fileId).setFields(FIELDS).execute();

System.out.println(file.toPrettyString());
		return file;
	}

	public void delete(String fileId) throws IOException {
		GoogleCredential credential = authorize().createScoped(SCOPES);
		Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
				.setApplicationName(APP_NAME)
				.build();
		try {
			service.files().delete(fileId).execute();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String list(String spaces) throws IOException {
		GoogleCredential credential = authorize().createScoped(SCOPES);
		Drive service = new Drive.Builder(httpTransport, JSON_FACTORY, credential)
				.setApplicationName(APP_NAME)
				.build();
		String fields = "files(id,name,mimeType,thumbnailLink,webContentLink,webViewLink,permissions)";
		FileList files = service.files()
				.list()
				.setSpaces(spaces)
				.setFields(fields)
				.execute();

		for (File file : files.getFiles()) {
			String msg = file.getId() + ":" + file.getName();
			System.out.println(msg);
			System.out.println(file.toPrettyString());
		}
		return "";
	}

	/**
	 * @param fileId
	 * @return
	 * @throws IOException
	 */
	public byte[] getImage(String fileId) throws IOException {
		File file = read(fileId);
		String link = file.getWebContentLink();
		GenericUrl url = new GenericUrl(link);
		HttpRequestFactory request = httpTransport.createRequestFactory();
		HttpResponse res = request.buildGetRequest(url).execute();

		return IOUtils.toByteArray(res.getContent());
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="IsLessThanFilterRule.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.Management.UI.Internal
{
    using System;
    using System.Diagnostics;

    /// <summary>
    /// The IsLessThanFilterRule class evaluates an IComparable item to
    /// check if it is less than the rule's value.
    /// </summary>
    /// <typeparam name="T">
    /// The generic parameter.
    /// </typeparam>
    [Serializable]
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
    public class IsLessThanFilterRule<T> : SingleValueComparableValueFilterRule<T> where T : IComparable
    {
        /// <summary>
        /// Initializes a new instance of the IsLessThanFilterRule class.
        /// </summary>
        public IsLessThanFilterRule()
        {
            this.DisplayName = UICultureResources.FilterRule_LessThanOrEqual;
        }

        /// <summary>
        /// Determines if item is less than Value.
        /// </summary>
        /// <param name="item">
        /// The data to compare against.
        /// </param>
        /// <returns>
        /// Returns true if data is less than Value.
        /// </returns>
        protected override bool Evaluate(T item)
        {
            Debug.Assert(this.IsValid);

            int result = CustomTypeComparer.Compare<T>(this.Value.GetCastValue(), item);
            return (result >= 0);
        }
    }
}


text:
package java.util;
public abstract class Dictionary {
	public Dictionary() { }
	public abstract java.util.Enumeration elements();
	public abstract java.lang.Object get(java.lang.Object var0);
	public abstract boolean isEmpty();
	public abstract java.util.Enumeration keys();
	public abstract java.lang.Object put(java.lang.Object var0, java.lang.Object var1);
	public abstract java.lang.Object remove(java.lang.Object var0);
	public abstract int size();
}


text:
<?php
session_start();
?>

<?php
$item_name = $_POST['item_name'];
$link = $_POST['link'];
$country = $_POST['country'];
$quantity = $_POST['quantity'];
$cost = $_POST['cost'];
$comission = $_POST['comission'];
$currency = $_POST['currency'];
date_default_timezone_set('Asia/Ho_Chi_Minh');
$datec = date('H:i d-m-Y');
$uid = $_SESSION['id_member'];

// Create connection
$conn = mysqli_connect('localhost', 'root', '', 'pika_shipper') or die ('{error:"bad_request"}');
mysqli_query($conn,"SET NAMES 'UTF8'");
// Check connection
if ($conn->connect_error) {
	die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO buy(uid,item_name,link,country,quantity,cost,comission,currency,datec)
VALUES ($uid,'$item_name','$link','$country',$quantity,$cost,'$comission','$currency','$datec')";

if ($conn->query($sql) === TRUE) {
	echo "Đăng thành công";
} else {
	echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>


text:
import React from "react";
import styled from "styled-components";

const ActionContainer = styled.div`
  display: flex;
  justify-content: space-between;
  background-color: ${props => (props.active ? "wheat" : "#f1f1f1")};
  padding: 5px;
  cursor: pointer;
  margin-bottom: 2px;
  padding-left: 15px;
  margin: 5px;
  height: 55px;
  flex-basis: 48%;
  color: #727e96;
`;

const ActionColumn = styled.div`
  display: flex;
  flex-direction: column;
  align-content: space-between;
`;

const SetArguments = styled.a`font-size: 10px;`;

export default function Action({
  index,
  active,
  action,
  tracker,
  onArgumentClick,
  executeAction
}) {
  return (
    <ActionContainer
      active={active}
      onClick={() => {
        tracker.selectedActionIndex = index;
      }}
    >
      <ActionColumn>

{action.name}

          <SetArguments onClick={onArgumentClick}>Set Arguments</SetArguments>

      </ActionColumn>

         {
            executeAction(
              tracker.id,
              action.name,
              eval(tracker.actionArguments)
            );
          }}
        >
          Execute

    </ActionContainer>
  );
}


text:
package com.ctrip.framework.apollo.portal.enricher.impl;

import com.ctrip.framework.apollo.portal.enricher.AdditionalUserInfoEnricher;
import com.ctrip.framework.apollo.portal.enricher.adapter.UserInfoEnrichedAdapter;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import java.util.Map;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author vdisk <vdisk@foxmail.com>
 */
@Component
public class UserDisplayNameEnricher implements AdditionalUserInfoEnricher {

  @Override
  public void enrichAdditionalUserInfo(UserInfoEnrichedAdapter adapter,
      Map<String, UserInfo> userInfoMap) {
    if (StringUtils.hasText(adapter.getFirstUserId())) {
      UserInfo userInfo = userInfoMap.get(adapter.getFirstUserId());
      if (userInfo != null && StringUtils.hasText(userInfo.getName())) {
        adapter.setFirstUserDisplayName(userInfo.getName());
      }
    }
    if (StringUtils.hasText(adapter.getSecondUserId())) {
      UserInfo userInfo = userInfoMap.get(adapter.getSecondUserId());
      if (userInfo != null && StringUtils.hasText(userInfo.getName())) {
        adapter.setSecondUserDisplayName(userInfo.getName());
      }
    }
    if (StringUtils.hasText(adapter.getThirdUserId())) {
      UserInfo userInfo = userInfoMap.get(adapter.getThirdUserId());
      if (userInfo != null && StringUtils.hasText(userInfo.getName())) {
        adapter.setThirdUserDisplayName(userInfo.getName());
      }
    }
  }
}


text:
package org.apache.metron.enrichment.adapters.host;

import org.apache.metron.enrichment.bolt.CacheKey;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HostFromJSONListAdapter extends AbstractHostAdapter {

  Map<String, JSONObject> _known_hosts = new HashMap<>();

  public HostFromJSONListAdapter(String jsonList) {
    JSONArray jsonArray = (JSONArray) JSONValue.parse(jsonList);
    Iterator jsonArrayIterator = jsonArray.iterator();
    while(jsonArrayIterator.hasNext()) {
      JSONObject jsonObject = (JSONObject) jsonArrayIterator.next();
      String host = (String) jsonObject.remove("ip");
      _known_hosts.put(host, jsonObject);
    }
  }

  @Override
  public boolean initializeAdapter()
  {

    if(_known_hosts.size() > 0)
      return true;
    else
      return false;
  }

  @Override
  public void logAccess(CacheKey value) {

  }

  @SuppressWarnings("unchecked")
  @Override
  public JSONObject enrich(CacheKey k) {
    String metadata = k.getValue();

    if(!_known_hosts.containsKey(metadata))
      return new JSONObject();

    JSONObject enrichment = new JSONObject();
    String prefix = "known_info.";
    JSONObject knownInfo = _known_hosts.get(metadata);
    for(Object key: knownInfo.keySet()) {
      enrichment.put(prefix + key, knownInfo.get(key));
    }
    //enrichment.put("known_info", _known_hosts.get(metadata));
    return enrichment;
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HangfireCourierTest.cs" company="Naos Project">
//    Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Naos.MessageBus.Test
{
    using System;
    using System.Linq;

    using FluentAssertions;

    using Naos.Cron;
    using Naos.MessageBus.Domain;
    using Naos.MessageBus.Hangfire.Sender;

    using OBeautifulCode.Reflection.Recipes;

    using Xunit;

    using static System.FormattableString;

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Hangfire", Justification = "Spelling/name is correct.")]
    public static class HangfireCourierTest
    {
        [Fact]
        public static void ThrowIfInvalidChannel_ValidChannelName_DoesNotThrow()
        {
            var channel = new SimpleChannel("monkeys_are_in_space");
            HangfireCourier.ThrowIfInvalidChannel(channel);

            // if we got here w/out exception then we passed...
        }

        [Fact]
        public static void ThrowIfInvalidChannel_NonSimpleChannelTypeType_Throws()
        {
            // arrange
            var channel = new NullChannel();
            Action testCode = () => HangfireCourier.ThrowIfInvalidChannel(channel);

            // act & assert
            testCode.ShouldThrow<NotSupportedException>().WithMessage("Channel type is not currently supported in Hangfire: Naos.MessageBus.Domain.NullChannel");
        }

        [Fact]
        public static void ThrowIfInvalidChannel_NullChannelName_Throws()
        {
            // arrange
            var channel = new SimpleChannel("Monkey");
            channel.SetPropertyValue(nameof(SimpleChannel.Name), null);
            Action testCode = () => HangfireCourier.ThrowIfInvalidChannel(channel);

            // act & assert
            testCode.ShouldThrow<ArgumentException>().WithMessage("Cannot use null or whitespace channel name.");
        }

        [Fact]
        public static void ThrowIfInvalidChannel_LongChannelName_Throws()
        {
            // arrange
            var channel = new SimpleChannel(new string('a', 21));
            Action testCode = () => HangfireCourier.ThrowIfInvalidChannel(channel);

            // act & assert
            testCode.ShouldThrow<ArgumentException>()
                .WithMessage(Invariant($"Cannot use a channel name longer than 20 characters.  The supplied channel name: {channel.Name} is {channel.Name.Length} characters long."));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "UpperCase", Justification = "Spelling/name is correct.")]
        [Fact]
        public static void ThrowIfInvalidChannel_UpperCaseChannelName_Throws()
        {
            // arrange
            var channel = new SimpleChannel(new string('A', 20));
            Action testCode = () => HangfireCourier.ThrowIfInvalidChannel(channel);

            // act & assert
            testCode.ShouldThrow<ArgumentException>()
                .WithMessage("Channel name must be lowercase alphanumeric with underscores ONLY.  The supplied channel name: " + channel.Name);
        }

        [Fact]
        public static void ThrowIfInvalidChannel_DashesChannelName_Throws()
        {
            // arrange
            var channel = new SimpleChannel("sup-withthis");
            Action testCode = () => HangfireCourier.ThrowIfInvalidChannel(channel);

            // act & assert
            testCode.ShouldThrow<ArgumentException>()
                .WithMessage("Channel name must be lowercase alphanumeric with underscores ONLY.  The supplied channel name: " + channel.Name);
        }

        [Fact]
        public static void ThrowIfInvalidChannel_NonNullSchedule_RecurringMessageInjectedAndChannelReset()
        {
            // arrange
            var envelopeMachine = Factory.GetEnvelopeMachine();
            var courier = new HangfireCourier(new CourierPersistenceConnectionConfiguration(), envelopeMachine);
            var schedule = new DailyScheduleInUtc();
            IChannel channel = new SimpleChannel("channel");
            IChannel defaultChannel = new SimpleChannel("default");

            var parcelIn = new Parcel
                               {
                                   Envelopes = new[]
                                                   {
                                                       new NullMessage { Description = "description" }.ToAddressedMessage(channel).ToEnvelope(envelopeMachine, "id"),
                                                   },
                               };

            var expectedParcelOut = new Parcel
                                        {
                                            Envelopes = new[]
                                                            {
                                                                new RecurringHeaderMessage { Description = "description" }.ToAddressedMessage(channel).ToEnvelope(envelopeMachine, "id"),
                                                                new NullMessage { Description = "description" }.ToAddressedMessage(channel).ToEnvelope(envelopeMachine, "id"),
                                                            },
                                        };

            var crate = new Crate
            {
                Parcel = parcelIn,
                RecurringSchedule = schedule,
            };

            // act
            var actualParcelOut = courier.UncrateParcel(crate, defaultChannel, ref channel);

            // assert
            actualParcelOut.Envelopes.Should().HaveCount(expectedParcelOut.Envelopes.Count);
            actualParcelOut.Envelopes.First().SerializedMessage.PayloadTypeRepresentation.Should().Be(expectedParcelOut.Envelopes.First().SerializedMessage.PayloadTypeRepresentation);
            channel.Should().Be(defaultChannel);
        }

        [Fact]
        public static void ThrowIfInvalidChannel_NullSchedule_NoMessageInjectedChannelUnaffected()
        {
            // arrange
            var envelopeMachine = Factory.GetEnvelopeMachine();
            var courier = new HangfireCourier(new CourierPersistenceConnectionConfiguration(), envelopeMachine);
            var schedule = new NullSchedule();
            IChannel channel = new SimpleChannel("channel");
            IChannel defaultChannel = new SimpleChannel("default");

            var parcelIn = new Parcel
            {
                Id = Guid.NewGuid(),
                Envelopes =
                                       new[]
                                           {
                                               new NullMessage { Description = "description" }.ToAddressedMessage(channel).ToEnvelope(envelopeMachine, "id"),
                                           },
            };

            var expectedParcelOut = new Parcel
            {
                Id = parcelIn.Id,
                Envelopes =
                                                new[]
                                                    {
                                                        new NullMessage { Description = "description" }.ToAddressedMessage(channel).ToEnvelope(envelopeMachine, "id"),
                                                    },
            };

            var crate = new Crate
            {
                Parcel = parcelIn,
                RecurringSchedule = schedule,
            };

            // act
            var actualParcelOut = courier.UncrateParcel(crate, defaultChannel, ref channel);

            // assert
            actualParcelOut.Envelopes.Should().BeEquivalentTo(expectedParcelOut.Envelopes);
            channel.Should().NotBe(defaultChannel);
        }
    }
}


text:
import gql from 'graphql-tag';

export default gql`{
  projects: allProjects {
    id
    name
    environments(type: PRODUCTION) {
      id
      name
      openshiftProjectName
    }
  }
}
`;


text:
dumbo_moveit
============

Overview
---------------------------------------------
MoveIt! packages for CVAP's Dumbo robot

dumbo_moveit_config
---------------------------------------------

Contains configuration files for using Dumbo with MoveIt!.

dumbo_moveit_plugins
---------------------------------------------

Plugins for using Dumbo in MoveIt. An analytics IK solver plugin is provided at the moment.

dumbo_moveit_examples
---------------------------------------------

C++ example code for moving Dumbo's arms using MoveIt!.


text:
/* $This file is distributed under the terms of the license in LICENSE$ */

package edu.cornell.mannlib.vitro.webapp.visualization.coprincipalinvestigator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFService;
import edu.cornell.mannlib.vitro.webapp.rdfservice.RDFServiceException;
import edu.cornell.mannlib.vitro.webapp.rdfservice.ResultSetConsumer;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jena.iri.IRI;
import org.apache.jena.iri.IRIFactory;
import org.apache.jena.iri.Violation;

import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.Syntax;
import org.apache.jena.rdf.model.RDFNode;

import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CoInvestigationData;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaborationData;
import edu.cornell.mannlib.vitro.webapp.visualization.collaborationutils.CollaboratorComparator;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryConstants;
import edu.cornell.mannlib.vitro.webapp.visualization.constants.QueryFieldLabels;
import edu.cornell.mannlib.vitro.webapp.visualization.exceptions.MalformedQueryParametersException;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Activity;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaboration;
import edu.cornell.mannlib.vitro.webapp.visualization.valueobjects.Collaborator;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.QueryRunner;
import edu.cornell.mannlib.vitro.webapp.visualization.visutils.UniqueIDGenerator;
/**
 * @author bkoniden
 * Deepak Konidena
 */
public class CoPIGrantCountQueryRunner implements QueryRunner<CollaborationData> {

	private static final int MAX_PI_PER_GRANT_ALLOWED = 100;

	protected static final Syntax SYNTAX = Syntax.syntaxARQ;

	private String egoURI;

	private RDFService rdfService;
	private VitroRequest vitroRequest;

	private Log log = LogFactory.getLog(CoPIGrantCountQueryRunner.class.getName());

	private long before, after;

	private static final String SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME = ""
		+ 		"OPTIONAL {"
		+ "			?Role core:dateTimeInterval ?dateTimeIntervalValue . "
		+			"?dateTimeIntervalValue core:start ?startDate . "
		+			"?startDate core:dateTime ?startDateTimeValue . "
//		+			"OPTIONAL {"
//		+				"?dateTimeIntervalValue core:end ?endDate . "
//		+				"?endDate core:dateTime ?endDateTimeValue . "
//		+			"}"
		+ 		"} . ";

	private static final String SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME = ""
		+ 		"OPTIONAL {"
		+ "			?Grant core:dateTimeInterval ?dateTimeIntervalValueForGrant . "
		+			"?dateTimeIntervalValueForGrant core:start ?startDateForGrant . "
		+			"?startDateForGrant core:dateTime ?startDateTimeValueForGrant . "
//		+			"OPTIONAL {"
//		+				"?dateTimeIntervalValueForGrant core:end ?endDateForGrant . "
//		+				"?endDateForGrant core:dateTime ?endDateTimeValueForGrant . "
//		+			"}"
		+ 		"}";

	public CoPIGrantCountQueryRunner(String egoURI, VitroRequest vreq, Log log) {

		this.egoURI = egoURI;
		this.rdfService = vreq.getRDFService();
		this.vitroRequest = vreq;
	//	this.log = log;
	}

	private String generateEgoCoPIquery(String queryURI) {

		String sparqlQuery = QueryConstants.getSparqlPrefixQuery()
			+ "SELECT "
			+ "		(str(<" + queryURI + ">) as ?" + QueryFieldLabels.PI_URL + ") "
			+ "		(str(?PILabel) as ?" + QueryFieldLabels.PI_LABEL + ") "
			+ "		(str(?Grant) as ?"	+ QueryFieldLabels.GRANT_URL + ") "
//			+ "		(str(?GrantLabel) as ?" + QueryFieldLabels.GRANT_LABEL + ") "
			+ " 	(str(?startDateTimeValue) as ?grantStartDateLit) "
//			+ "		(str(?endDateTimeValue) as ?grantEndDateLit)  "
			+ " 	(str(?startDateTimeValueForGrant) as ?grantStartDateForGrantLit) "
//			+ "		(str(?endDateTimeValueForGrant) as ?grantEndDateForGrantLit)  "
			+ "		(str(?CoPI) as ?" + QueryFieldLabels.CO_PI_URL + ") "
			+ "		(str(?CoPILabel) as ?" + QueryFieldLabels.CO_PI_LABEL + ") "
			+ "WHERE "
			+ "{ "
			+ 		"<" + queryURI + "> rdfs:label ?PILabel . "
			+  		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
		    +			"?Role rdf:type core:CoPrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:PrincipalInvestigatorRole . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+  		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:CoPrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:InvestigatorRole . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+  		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:CoPrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:CoPrincipalInvestigatorRole  . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:PrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:PrincipalInvestigatorRole  . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
			+			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:PrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:InvestigatorRole  . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:PrincipalInvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:CoPrincipalInvestigatorRole . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:InvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:InvestigatorRole  . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:InvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:CoPrincipalInvestigatorRole  . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
	        +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+		"UNION "
			+		"{ "
			+			"<" + queryURI + "> <http://purl.obolibrary.org/obo/RO_0000053> ?Role . "
	        +			"?Role rdf:type core:InvestigatorRole . "
			+			"?Role core:relatedBy ?Grant . "
			+			"?Grant rdf:type core:Grant . "
			+			"?Grant core:relates ?RelatedRole . "
			+			"?RelatedRole rdf:type core:PrincipalInvestigatorRole . "
			+			"?RelatedRole <http://purl.obolibrary.org/obo/RO_0000052> ?CoPI . "
		    +			"?CoPI rdf:type foaf:Person .	"
			+			"?CoPI rdfs:label ?CoPILabel .	"
			+ 			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_ROLE_DATE_TIME
			+			SPARQL_QUERY_COMMON_OPTIONAL_BLOCK_FOR_GRANT_DATE_TIME
			+ 		"} "
			+ "} ";
		return sparqlQuery;
	}

	public CoInvestigationData getQueryResult()
		throws MalformedQueryParametersException {

		CoInvestigationData data = getCachedData(this.egoURI);
		if (data != null) {
			return data;
		}

		return getQueryResultAndCache();
	}

	private CoInvestigationData getCachedData(String egoURI) {
		CollaborationDataCacheEntry entry = collaborationDataCache.get(egoURI);
		if (entry != null && !entry.hasExpired()) {
			entry.accessTime = new Date().getTime();
			expireCache();
			return entry.data;
		}

		return null;
	}

	private synchronized CoInvestigationData getQueryResultAndCache()
			throws MalformedQueryParametersException {

		CoInvestigationData data = getCachedData(this.egoURI);
		if (data != null) {
			return data;
		}

		if (StringUtils.isNotBlank(this.egoURI)) {
			/*
			 * To test for the validity of the URI submitted.
			 * */
			IRIFactory iRIFactory = IRIFactory.jenaImplementation();
			IRI iri = iRIFactory.create(this.egoURI);
			if (iri.hasViolation(false)) {
				String errorMsg = ((Violation) iri.violations(false).next()).getShortMessage();
				log.error("Ego Co-PI Vis Query " + errorMsg);
				throw new MalformedQueryParametersException(
						"URI provided for an individual is malformed.");
			}
		} else {
			throw new MalformedQueryParametersException("URI parameter is either null or empty.");
		}

		before = System.currentTimeMillis();

		try {
			QueryResultConsumer consumer = new QueryResultConsumer();
			rdfService.sparqlSelectQuery(generateEgoCoPIquery(this.egoURI), consumer);
			if (consumer.egoNode == null) {
				consumer.egoNode = makeEgoNode();
			}
			data = consumer.getData();
		} catch (RDFServiceException e) {
			log.error("Unable to execute query", e);
			throw new RuntimeException(e);
		}
		after = System.currentTimeMillis();

		log.debug("Time taken to execute the SELECT queries is in milliseconds: " + (after - before));

		CollaborationDataCacheEntry newEntry = new CollaborationDataCacheEntry();

		newEntry.uri = this.egoURI;
		newEntry.data = data;
		newEntry.creationTime = newEntry.accessTime = new Date().getTime();

		// Remove dead entries
		expireCache();

		// Cache the new entry
		collaborationDataCache.put(this.egoURI, newEntry);
		return data;
	}

	private Collaborator makeEgoNode() {
		Collaborator collab = new Collaborator(egoURI, new UniqueIDGenerator());
		collab.setCollaboratorName(UtilityFunctions.getIndividualLabelFromDAO(vitroRequest, egoURI));

		return collab;
	}

	private synchronized void expireCache() {
		for (String key : collaborationDataCache.keySet()) {
			CollaborationDataCacheEntry entry = collaborationDataCache.get(key);
			if (entry != null && entry.hasExpired()) {
				collaborationDataCache.remove(key);
			}
		}
	}

	private static final Map<String, CollaborationDataCacheEntry> collaborationDataCache = new ConcurrentHashMap<String, CollaborationDataCacheEntry>();

	private static class CollaborationDataCacheEntry {
		String uri;
		CoInvestigationData data;
		long creationTime;
		long accessTime;

		boolean hasExpired() {
			long now = new Date().getTime();

			// If it's older than five minutes, and it hasn't *just* been accessed, it's expired
			if (creationTime < (now - 300000L) && accessTime < (now - 3000L)) {
				return true;
			}

			// Otherwise, if it is more than 30 seconds old, expire it
			return accessTime < (now - 30000L);
		}
	}

	private static class QueryResultConsumer extends ResultSetConsumer {
		Set<Collaborator> nodes = new HashSet<Collaborator>();

		Map<String, Activity> grantURLToVO = new HashMap<String, Activity>();
		Map<String, Set<Collaborator>> grantURLToCoPIs = new HashMap<String, Set<Collaborator>>();
		Map<String, Collaborator> nodeURLToVO = new HashMap<String, Collaborator>();
		Map<String, Collaboration> edgeUniqueIdentifierToVO = new HashMap<String, Collaboration>();

		Collaborator egoNode = null;

		Set<Collaboration> edges = new HashSet<Collaboration>();

		private UniqueIDGenerator nodeIDGenerator = new UniqueIDGenerator();
		private UniqueIDGenerator edgeIDGenerator = new UniqueIDGenerator();

		private Log log = LogFactory.getLog(CoPIGrantCountQueryRunner.class.getName());

		@Override
		protected void processQuerySolution(QuerySolution qs) {
				/*
				 * We only want to create only ONE ego node.
				 * */
			RDFNode egoPIURLNode = qs.get(QueryFieldLabels.PI_URL);
			if (nodeURLToVO.containsKey(egoPIURLNode.toString())) {

				egoNode = nodeURLToVO.get(egoPIURLNode.toString());

			} else {

				egoNode = new Collaborator(egoPIURLNode.toString(), nodeIDGenerator);
				nodes.add(egoNode);
				nodeURLToVO.put(egoPIURLNode.toString(), egoNode);

				RDFNode authorLabelNode = qs.get(QueryFieldLabels.PI_LABEL);
				if (authorLabelNode != null) {
					egoNode.setCollaboratorName(authorLabelNode.toString());
				}
			}
			log.debug("PI: " + egoNode.getIndividualLabel());

			RDFNode grantNode = qs.get(QueryFieldLabels.GRANT_URL);
			Activity grant;

			if (grantURLToVO.containsKey(grantNode.toString())) {
				grant = grantURLToVO.get(grantNode.toString());
			} else {
				grant = createGrantVO(qs, grantNode.toString());
				grantURLToVO.put(grantNode.toString(), grant);
			}

			egoNode.addActivity(grant);
			log.debug("Adding grant: " + grant.getIndividualLabel());

				/*
				 * After some discussion we concluded that for the purpose of this visualization
				 * we do not want a co-pi node or edge if the grant has only one
				 * pi and that happens to be the ego.
				 * */
			if (qs.get(QueryFieldLabels.PI_URL).toString().equalsIgnoreCase(
					qs.get(QueryFieldLabels.CO_PI_URL).toString())) {
				return;
			}

			Collaborator coPINode;

			RDFNode coPIURLNode = qs.get(QueryFieldLabels.CO_PI_URL);
			if (nodeURLToVO.containsKey(coPIURLNode.toString())) {

				coPINode = nodeURLToVO.get(coPIURLNode.toString());

			} else {

				coPINode = new Collaborator(coPIURLNode.toString(), nodeIDGenerator);
				nodes.add(coPINode);
				nodeURLToVO.put(coPIURLNode.toString(), coPINode);

				RDFNode coPILabelNode = qs.get(QueryFieldLabels.CO_PI_LABEL);
				if (coPILabelNode != null) {
					coPINode.setCollaboratorName(coPILabelNode.toString());
				}
			}

			log.debug("Adding CO-PI: "+ coPINode.getIndividualLabel());
			coPINode.addActivity(grant);

			Set<Collaborator> coPIsForCurrentGrant;

			if (grantURLToCoPIs.containsKey(grant.getActivityURI())) {
				coPIsForCurrentGrant = grantURLToCoPIs.get(grant.getActivityURI());
			} else {
				coPIsForCurrentGrant = new HashSet<Collaborator>();
				grantURLToCoPIs.put(grant.getActivityURI(),
						coPIsForCurrentGrant);
			}

			coPIsForCurrentGrant.add(coPINode);
			log.debug("Co-PI for current grant : " + coPINode.getIndividualLabel());

			Collaboration egoCoPIEdge =
					getExistingEdge(egoNode, coPINode, edgeUniqueIdentifierToVO);
				/*
				 * If "egoCoPIEdge" is null it means that no edge exists in between the egoNode
				 * & current coPINode. Else create a new edge, add it to the edges set & add
				 * the collaborator grant to it.
				 * */
			if (egoCoPIEdge != null) {
				egoCoPIEdge.addActivity(grant);
			} else {
				egoCoPIEdge = new Collaboration(egoNode, coPINode, grant, edgeIDGenerator);
				edges.add(egoCoPIEdge);
				edgeUniqueIdentifierToVO.put(
						getEdgeUniqueIdentifier(egoNode.getCollaboratorID(),
								coPINode.getCollaboratorID()),
						egoCoPIEdge);
			}
		}

		@Override
		protected void endProcessing() {
			super.endProcessing();
			/*
			 * This method takes out all the PIs & edges between PIs that belong to grants
			 * that have more than 100 PIs. We conjecture that these grants do not provide much
			 * insight. However, we have left the grants be.
			 * This method side-effects "nodes" & "edges".
			 * */
			removeLowQualityNodesAndEdges(nodes,
					grantURLToVO,
					grantURLToCoPIs,
					edges);
			/*
			 * We need to create edges between 2 co-PIs. E.g. On a grant there were 3 PI
			 * ego, A & B then we have already created edges like,
			 * 		ego - A
			 * 		ego - B
			 * The below sub-routine will take care of,
			 * 		A - B
			 *
			 * We are side-effecting "edges" here. The only reason to do this is because we are
			 * adding edges en masse for all the co-PIs on all the grants considered so far. The
			 * other reason being we dont want to compare against 2 sets of edges (edges created
			 * before & co-PI edges created during the course of this method) when we are creating
			 * a new edge.
			 * */
			createCoPIEdges(grantURLToVO,
					grantURLToCoPIs,
					edges,
					edgeUniqueIdentifierToVO);
		}

		public CoInvestigationData getData() {
			return new CoInvestigationData(egoNode, nodes, edges, grantURLToVO);
		}

		private void createCoPIEdges(Map<String, Activity> grantURLToVO,
									 Map<String, Set<Collaborator>> grantURLToCoPIs, Set<Collaboration> edges,
									 Map<String, Collaboration> edgeUniqueIdentifierToVO) {

			for (Map.Entry<String, Set<Collaborator>> currentGrantEntry
					: grantURLToCoPIs.entrySet()) {

		/*
		 * If there was only one co-PI (other than ego) then we dont have to create any
		 * edges. so the below condition will take care of that.
		 *
		 * We are restricting edges between co-PI if a particular grant has more than
		 * 100 co-PIs. Our conjecture is that such edges do not provide any good insight
		 * & causes unnecessary computations causing the server to time-out.
		 * */
				if (currentGrantEntry.getValue().size() > 1
						&& currentGrantEntry.getValue().size()
						<= MAX_PI_PER_GRANT_ALLOWED) {

					Set<Collaboration> newlyAddedEdges = new HashSet<Collaboration>();

			/*
			 * In order to leverage the nested "for loop" for making edges between all the
			 * co-PIs we need to create a list out of the set first.
			 * */
					List<Collaborator> coPINodes =
							new ArrayList<Collaborator>(currentGrantEntry.getValue());
					coPINodes.sort(new CollaboratorComparator());

					int numOfCoPIs = coPINodes.size();

					for (int ii = 0; ii < numOfCoPIs - 1; ii++) {
						for (int jj = ii + 1; jj < numOfCoPIs; jj++) {

							Collaborator coPI1 = coPINodes.get(ii);
							Collaborator coPI2 = coPINodes.get(jj);

							Collaboration coPI1_2Edge = getExistingEdge(coPI1,
									coPI2,
									edgeUniqueIdentifierToVO);

							Activity currentGrant = grantURLToVO.get(currentGrantEntry.getKey());

							if (coPI1_2Edge != null) {
								coPI1_2Edge.addActivity(currentGrant);
							} else {
								coPI1_2Edge = new Collaboration(coPI1,
										coPI2,
										currentGrant,
										edgeIDGenerator);
								newlyAddedEdges.add(coPI1_2Edge);
								edgeUniqueIdentifierToVO.put(
										getEdgeUniqueIdentifier(coPI1.getCollaboratorID(),
												coPI2.getCollaboratorID()),
										coPI1_2Edge);
							}
						}
					}
					edges.addAll(newlyAddedEdges);
				}
			}
		}

		private void removeLowQualityNodesAndEdges(Set<Collaborator> nodes,
												   Map<String, Activity> grantURLToVO,
												   Map<String, Set<Collaborator>> grantURLToCoPIs, Set<Collaboration> edges) {

			Set<Collaborator> nodesToBeRemoved = new HashSet<Collaborator>();
			for (Map.Entry<String, Set<Collaborator>> currentGrantEntry
					: grantURLToCoPIs.entrySet()) {

				if (currentGrantEntry.getValue().size() > MAX_PI_PER_GRANT_ALLOWED) {

					Activity currentGrant = grantURLToVO.get(currentGrantEntry.getKey());

					Set<Collaboration> edgesToBeRemoved = new HashSet<Collaboration>();

					for (Collaboration currentEdge : edges) {
						Set<Activity> currentCollaboratorGrants =
								currentEdge.getCollaborationActivities();

						if (currentCollaboratorGrants.contains(currentGrant)) {
							currentCollaboratorGrants.remove(currentGrant);
							if (currentCollaboratorGrants.isEmpty()) {
								edgesToBeRemoved.add(currentEdge);
							}
						}
					}

					edges.removeAll(edgesToBeRemoved);

					for (Collaborator currentCoPI : currentGrantEntry.getValue()) {
						currentCoPI.getCollaboratorActivities().remove(currentGrant);
						if (currentCoPI.getCollaboratorActivities().isEmpty()) {
							nodesToBeRemoved.add(currentCoPI);
						}
					}
				}
			}
			nodes.removeAll(nodesToBeRemoved);

		}

		private Activity createGrantVO(QuerySolution solution, String grantURL) {

			Activity grant = new Activity(grantURL);

//		RDFNode grantLabelNode = solution.get(QueryFieldLabels.GRANT_LABEL);
//		if (grantLabelNode != null) {
//			grant.setIndividualLabel(grantLabelNode.toString());
//		}

			RDFNode grantStartYear = solution.get(QueryFieldLabels.ROLE_START_DATE);
			if (grantStartYear != null) {
				grant.setActivityDate(grantStartYear.toString());
			} else {
				grantStartYear = solution.get(QueryFieldLabels.GRANT_START_DATE);
				if (grantStartYear != null) {
					grant.setActivityDate(grantStartYear.toString());
				}
			}

			//TODO: Verify that grant end date is not required.
		/*
		RDFNode grantEndDate = solution.get(QueryFieldLabels.ROLE_END_DATE);
		if (grantEndDate != null) {
			grant.setGrantEndDate(grantEndDate.toString());
		}else{
			grantEndDate = solution.get(QueryFieldLabels.GRANT_END_DATE);
			if(grantEndDate != null){
				grant.setGrantEndDate(grantEndDate.toString());
			}
		}
		*/

			return grant;
		}

		private Collaboration getExistingEdge(
				Collaborator collaboratingNode1,
				Collaborator collaboratingNode2,
				Map<String, Collaboration> edgeUniqueIdentifierToVO) {

			String edgeUniqueIdentifier = getEdgeUniqueIdentifier(
					collaboratingNode1.getCollaboratorID(),
					collaboratingNode2.getCollaboratorID());

			return edgeUniqueIdentifierToVO.get(edgeUniqueIdentifier);

		}

		private String getEdgeUniqueIdentifier(int nodeID1, int nodeID2) {

			String separator = "*";

			if (nodeID1 < nodeID2) {
				return nodeID1 + separator + nodeID2;
			} else {
				return nodeID2 + separator + nodeID1;
			}

		}

		/** END QUERY RESULT CONSUMER **/
	}
}


text:
// Copyright 2012, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Author: api.anash@gmail.com (Anash P. Oommen)

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.Common.Lib;

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace Google.Api.Ads.AdWords.Examples.CSharp.OAuth {
  /// <summary>
  /// Login and callback page for handling OAuth2 authentication.
  /// </summary>
  public partial class OAuthLogin : Page {
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing
    /// the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      // Create an AdWordsAppConfig object with the default settings in
      // App.config.
      AdWordsAppConfig config = new AdWordsAppConfig();
      if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2) {
        if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
            string.IsNullOrEmpty(config.OAuth2RefreshToken)) {
          DoAuth2Configuration(config);
        }
      }
    }

    private void DoAuth2Configuration(AdWordsAppConfig config) {
      // Since we use this page for OAuth callback also, we set the callback
      // url as the current page. For a non-web application, this will be null.
      config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);

      // Create an OAuth2 object for handling OAuth2 flow.
      OAuth2ProviderForApplications oAuth = new OAuth2ProviderForApplications(config);

      if (Request.Params["state"] == null) {
        // This is the first time this page is being loaded.
        // Set the state variable to any value that helps you recognize
        // when this url will be called by the OAuth2 server.
        oAuth.State = "callback";

        // Create an authorization url and redirect the user to that page.
        Response.Redirect(oAuth.GetAuthorizationUrl());
      } else if (Request.Params["state"] == "callback") {
        // This page was loaded because OAuth server did a callback.
        // Retrieve the authorization code from the url and use it to fetch
        // the access token. This call will also fetch the refresh token if
        // your mode is offline.
        oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);

        // Save the OAuth2 provider for future use. If you wish to save only
        // the values and restore the object later, then save
        // oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        // oAuth.ExpiresIn.
        //
        // You can later restore the values as
        // AdWordsUser user = new AdWordsUser();
        // user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
        // OAuth2ProviderForApplications oAuth =
        //     (user.OAuthProvider as OAuth2ProviderForApplications);
        // oAuth.RefreshToken = xxx;
        // oAuth.AccessToken = xxx;
        // oAuth.UpdatedOn = xxx;
        // oAuth.ExpiresIn = xxx;
        //
        // Note that only oAuth.RefreshToken is mandatory. If you leave
        // oAuth.AccessToken as empty, or if oAuth.UpdatedOn + oAuth.ExpiresIn
        // is in the past, the access token will be refreshed by the library.
        // You can listen to this event as
        //
        // oAuth.OnOAuthTokensObtained += delegate(AdsOAuthProvider provider) {
        //    OAuth2ProviderForApplications oAuth =
        //        (provider as OAuth2ProviderForApplications);
        //    // Save oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
        //    // oAuth.ExpiresIn.
        //};
        Session["OAuthProvider"] = oAuth;
        // Redirect the user to the main page.
        Response.Redirect("Default.aspx");
      } else {
        throw new Exception("Unknown state for OAuth callback.");
      }
    }
  }
}


text:
package be.gest.web.page;

import org.springframework.beans.factory.annotation.Autowired;

import be.gest.dao.AdresseDAO;
import be.gest.dao.FournisseurDAO;
import be.gest.model.Address;
import be.gest.model.Fournisseur;
import be.gest.web.MainUI;

import com.vaadin.data.fieldgroup.BeanFieldGroup;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.ui.Button;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Grid;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import com.vaadin.ui.themes.ValoTheme;

public class FournisseurForm extends FormLayout {

	/**
	 *
	 */
	private static final long serialVersionUID = 2883363833710887547L;
	@Autowired
	private FournisseurDAO fournisseurDAO;
	private Fournisseur fournisseur;
	@Autowired
	private AdresseDAO adresseDAO;
	private Address adresse;

	// private MyUI myUI;
	private MainUI mainUI;
	private TextField nomFour = new TextField("Nom Du Fournisseur");
	private TextField numTva = new TextField("Num de TVA");
	private TextField article = new TextField("Article");
	private TextField numRgistre = new TextField("Num de Rgistre");

	private TextField nomCommune = new TextField("Commune");

	private TextField codePostal = new TextField("code Postal");
	private TextField rue = new TextField("La Rue");
	private TextField numero = new TextField("Numero");

	private TextField numFax = new TextField("Fax");
	private TextField numTel = new TextField("Tel");
	private TextField numGSM = new TextField("GSM");
	private TextField email = new TextField("Email");

	private Button save = new Button("Save");
	private Button delete = new Button("Delete");

	public FournisseurForm(MainUI mainUI) {
		this.mainUI = mainUI;

		save.setClickShortcut(KeyCode.ENTER);
		 save.setStyleName(ValoTheme.BUTTON_PRIMARY);
		 save.addClickListener(e -> this.save());
		 delete.addClickListener(e -> this.delete());
		setSizeUndefined();

	HorizontalLayout buttons = new HorizontalLayout(save, delete);

		buttons.setSpacing(true);

		addComponents(nomFour, numTva, article, numRgistre, nomCommune,
				codePostal, rue, numero, numFax, numTel, numGSM, email, buttons);
	}

	public void setFournisseur(Fournisseur fournisseur) {
		this.fournisseur = fournisseur;
		BeanFieldGroup.bindFieldsUnbuffered(fournisseur, this);

		// Show delete button for only customers already in the database
		delete.setVisible((fournisseur.getId()) != null);
		setVisible(true);
		nomFour.selectAll();
	}

	private void delete() {
		fournisseurDAO.delete(fournisseur);
//		mainUI.buildFournisseur( );
		setVisible(false);
	}

	private void save() {
		fournisseurDAO.save(fournisseur);
//		mainUI.updateListeFour();
		setVisible(false);
	}

}


text:
package collector

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func Pinterest() Platform {
	return Platform{
		enabled:  true,
		name:     "pinterest",
		statsURL: "http://api.pinterest.com/v1/urls/count.json?callback=call&url=%s",
		format:   "jsonp",
		parseWith: func(r *http.Response) (Stat, error) {
			stat := Stat{
				data: map[string]interface{}{"count": 0},
			}

			body, error := ioutil.ReadAll(r.Body)
			if error != nil {
				return stat, error
			}

			jsonBody, error := parseJSONP(body)
			if error != nil {
				return stat, error
			}

			var jsonBlob map[string]interface{}
			if err := json.Unmarshal([]byte(jsonBody), &jsonBlob); err != nil {
				return stat, err
			}

			return Stat{
				data: map[string]interface{}{"count": jsonBlob["count"]},
			}, nil
		}}
}


text:
<form id="searchform" method="get" role="search" action="<?php echo home_url('/'); ?>">

   <?php if (class_exists( 'Bylines\Objects\Byline' )) {
      $terms = get_terms('byline');?>

Author

        <?php _e('Select an Author: ', 'textdomain'); ?>

        <select name="authors" class="custom-select">
          <optgroup label="Authors">
            <option selected value="">All Authors</option>
            <?php foreach ($terms as $byline) {
              if ((get_user_by('ID', $byline->ID)) || get_user_by('slug', $byline->slug)) {
                //
              } else { ?>
                <option value="<?php echo $byline->slug; ?>"><?php echo $byline->name; ?></option>
            <?php  }
            ?>
            <?php }; ?>
          </optgroup>
        </select>

    <?php }?>

    <?php if (post_type_exists( 'session' )) {
      $args = array(
        'post_type'   => 'session',
        'numberposts' => -1,
      	'meta_key'		=> 'date',
      	'orderby'			=> 'meta_value',
      	'order'				=> 'ASC'
      );
      $days = get_posts($args);
      //echo var_dump($days[0]);
    ?>

Day

         <?php _e('Filter by Day: ', 'textdomain'); ?>

         <select name="days" class="custom-select">
           <optgroup label="Authors">
             <option selected value="">All Days</option>
             <?php $yesterday = '';
             foreach ($days as $date) {
               if ($yesterday !== get_field('date', $date->ID)) {
                 echo '<option value="'.get_field('date', $date->ID).'">'.date("F j", strtotime(get_field('date', $date->ID))).'</option>';
                 $yesterday = get_field('date', $date->ID);
               } else {
                 $yesterday = get_field('date', $date->ID);
                 continue;
               }
            }; ?>
           </optgroup>
         </select>

     <?php }?>

    <?php if (post_type_exists( 'session' )) {
      $args = array(
        'post_type'   => 'session',
        'numberposts' => -1,
        'orderby'     => 'title',
        'order'       => 'ASC'
      );
      $sessions = get_posts($args);
    ?>

Session

         <?php _e('Filter by Session: ', 'textdomain'); ?>

         <select name="sessions" class="custom-select">
           <optgroup label="Session">
             <option selected value="">All Sessions</option>
             <?php foreach ($sessions as $sess) { ?>
               <option value="<?php echo $sess->ID; ?>"><?php echo $sess->post_title; ?></option>
             <?php }; ?>
           </optgroup>
         </select>

     <?php }?>

    <?php if (class_exists( 'Bylines\Objects\Byline' )) {
       $terms = get_terms('byline');?>

Proceedings Only

       <input type="checkbox" class="search_proceedings" name="proceeding_only" value='true' />

     <?php }

     ?>

        Search:
        <input type="search" name="s" id="s" class="form-control"
          value="<?php the_search_query(); ?>"
          placeholder="Search for..." />

          <button class="btn btn-secondary search-button" type="submit" value="Search" alt="Search">Search</button>

</form>


text:
'use strict';
(function () {
    angular.module('kingSurvival', ['nywton.chessboard'])
        .service('kingSurvivalGameService', ['$log', function kingSurvivalGameService($log) {

            this.onDragStart = function (gameState, source, piece, position, orientation) {
              //  $log.debug('lift piece ' + piece + ' from ' + source + ' - ' + position + ' - ' + orientation);

                console.log(gameState);
                if (gameState.PlayerFigure !== gameState.gameState ||
                    (gameState.PlayerFigure === 1 && piece !== 'wK') ||
                    (gameState.PlayerFigure === 2 && piece !== 'bP')) {
                    return false;
                }
                return true;
            };

            this.onSnapEnd = function (callback, gameId, playerId, board, source, target, piece) {
                callback(gameId, playerId, source, target);
             //   $log.debug('onSnapEnd ' + piece + ' from ' + source + ' to ' + target);
            };

        }])

        .directive('kingSurvivalGame', ['$window', '$log', 'kingSurvivalGameService', function ($window, $log, kingSurvivalGameService) {

            var directive = {
                restrict: 'E',
                template: '<div>' +
                '<nywton-chessboard  data-board="board" data-draggable="true"  data-position="{ a8: \'bP\',  c8: \'bP\',  e8: \'bP\',  g8: \'bP\',  d1: \'wK\'  }" on-change="onChange" on-drag-start-cb="onDragStart" on-snap-end="onSnapEnd" on-drop="onDrop"></nywton-chessboard>' +
                '</div>',
                replace: false,
                scope: true,
                controller: ['$scope', '$rootScope', function chessgame($scope, $rootScope) {

                    var gameState = $scope.$parent.gameState;

                    $.connection.hub.stop();

                    var kingSurvival = $.connection.kingSurvivalGame;

                    function move(fen) {
                        $scope.board.position(fen)
                    }

                    function updateState(updatedGameState) {
                        console.log(updatedGameState);
                        gameState.gameState = updatedGameState.gameState
                    }

                    kingSurvival.client.move = move;
                    kingSurvival.client.updateGameState = updateState;

                    $.connection.hub.start().done(function () {
                        kingSurvival.server.joinRoom(gameState.Id);
                    }).fail(function (error) {
                        console.log('Invocation of start failed. Error: ' + error)
                    });

                    this.board = function boardF() {
                        return $scope.board;
                    };

                    $scope.onDragStart = function onDragStartF(source, piece, position, orientation) {
                        return kingSurvivalGameService.onDragStart(gameState, source, piece, position, orientation);
                    };
                    $scope.onSnapEnd = function onSnapEndF(source, target, piece) {
                        return kingSurvivalGameService.onSnapEnd(kingSurvival.server.gameEngine, gameState.Id, gameState.playerId, $scope.board, source, target, piece);
                    };
                }]
            };

            return directive;
        }])
})();


text:
using Newtonsoft.Json;

namespace VaultSharp.V1.SecretsEngines.Transit
{
    /// <summary>
    /// Represents the options that will be used to trim the key.
    /// </summary>
    public class TrimKeyRequestOptions
    {
        /// <summary>
        /// Specifies the minimum_available_version.The minimum available
        /// version for the key ring. All versions before this version will be
        /// permanently deleted. This value can at most be equal to the lesser
        /// of min_decryption_version and min_encryption_version.
        /// </summary>
        [JsonProperty(PropertyName = "min_available_version")]
        public int MinimumAvailableVersion { get; set; }
    }
}


text:
class CreateDicts < ActiveRecord::Migration
  def change
    create_table :dicts do |t|
      t.string :name
      t.integer :type

      t.timestamps
    end
  end
end


text:
"""
WSGI config for drunken_platypus project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "drunken_platypus.settings")

application = get_wsgi_application()


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using EasyArchitecture.Plugins.Contracts.Translation;

namespace EasyArchitecture.Plugins.BultIn.Translation
{
    internal class Translator : ITranslator
    {
        private readonly List<TypeMap> _mappedTypes;

        public Translator(List<TypeMap> mappedTypes)
        {
            _mappedTypes = mappedTypes;
        }

        public T1 Translate<T, T1>(T source)
        {
            if (typeof(T).IsValueType || typeof(T1).IsValueType)
                throw new ArgumentException("Just class can be translated", "source");

            if (source == null)
                return default(T1);

            T1 target;

            if (TypeManager.IsGenericList<T>() && TypeManager.IsGenericList<T1>())
            {
                target = TypeManager.CreateGenericList<T1>();

            }
            else
            {
                target = TypeManager.InstanceCreator<T1>();
            }

            return Translate(source, target);
        }

        public T1 Translate<T, T1>(T source, T1 target)
        {
            if (typeof(T).IsValueType || typeof(T1).IsValueType)
                throw new ArgumentException("Just class can be translated", "source");

            if (source == null)
                return target;

            if (TypeManager.IsGenericList<T>() && TypeManager.IsGenericList<T1>())
            {
                var targetList = (IList)target;
                var sourceList = (IEnumerable)source;

                var targetGenericType = ThisIsGenericList(target);
                foreach (var item in sourceList)
                {
                    targetList.Add(TranslateObject(item, TypeManager.InstanceCreator(targetGenericType)));
                }
                target = (T1)targetList;
            }
            else
            {
                target = (T1)TranslateObject(source, target);
            }

            return target;
        }

        private object TranslateObject(object source, object target)
        {
            var typeMap = _mappedTypes.Find(m => m.Source == source.GetType() && m.Target == target.GetType());
            if (typeMap != null)
            {
                var func = typeMap.DeclaredMap;
                return func.GetType().InvokeMember("Invoke", BindingFlags.InvokeMethod, null, func, new object[] { source, target });
            }

            foreach (var property in source.GetType().GetProperties())
            {
                var value = property.GetValue(source, null);
                if (value == null) continue;

                var targetProperty = target.GetType().GetProperty(property.Name);
                if (targetProperty == null) continue;

                value = ConvertValue(property.PropertyType, targetProperty.PropertyType, value);

                targetProperty.SetValue(target, value, null);
            }
            return target;
        }

        private object ConvertValue(Type source, Type target, object value)
        {
            if (ThisIsGenericList(value) != null)
            {
                value = TranslateGenericList(value, target);
                return value;
            }

            if (source == target || source.IsAssignableFrom(target))
            {
                return value;
            }

            if (source == typeof(string) && string.IsNullOrEmpty((string)value))
            {
                value = GetDefaultValue(target);
            }

            if (target.IsGenericType)
            {
                target = target.GetGenericArguments()[0];
            }

            if (target.IsClass && source.IsClass)
            {
                value = TranslateObject(value, TypeManager.InstanceCreator(target));
            }

            value = Convert.ChangeType(value, target);

            return value;
        }

        private static Type ThisIsGenericList(Type type)
        {
            Type typeGeneric = null;

            if (TypeManager.IsGenericList(type))
            {
                var genericTypeDefinition = type.GetGenericTypeDefinition();
                if ((genericTypeDefinition == typeof(IList<>)) || (genericTypeDefinition == typeof(List<>)))
                {
                    typeGeneric = type.GetGenericArguments().FirstOrDefault();
                }
            }

            return typeGeneric;
        }

        private static Type ThisIsGenericList(object obj)
        {
            return ThisIsGenericList(obj.GetType());
        }

        private IList TranslateGenericList(object source, Type target)
        {
            IList targetList = null;

            var sourceGenericType = ThisIsGenericList(source);
            var targetGenericType = ThisIsGenericList(target);
            if (sourceGenericType != null)
            {
                var sourceList = (IEnumerable)source;
                targetList = (IList)TypeManager.CreateGeneric(typeof(List<>), targetGenericType);

                foreach (var item in sourceList)
                {
                    targetList.Add(TranslateObject(item, TypeManager.InstanceCreator(targetGenericType)));
                }
            }
            return targetList;
        }

        private static object GetDefaultValue(Type type)
        {
            return type.IsValueType ? Activator.CreateInstance(type) : null;
        }
    }
}


text:
@interface EMCallInfo : NSObject

@end


text:
#ifndef JavaScript_h
#define JavaScript_h

#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/JSContextRef.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSObjectRef.h>
#include <JavaScriptCore/JSValueRef.h>

#endif /* JavaScript_h */