text:
using KPComponents.KPSecurity;
using KPComponents.KPSession;
using KPCore.KPSecurity;
using KPEntity.ORM;
using KPEnumerator.KPEntity;
using KPEnumerator.KPSecurity;
using NHibernate.Criterion;
using System;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace KPComponents
{
    ///
    /// <para>Authors: Juliano Tiago Rinaldi and
    /// Tiago Antonio Jacobi</para>
    ///
    [ToolboxData(@"<{0}:KPMenuControl runat=server ></{0}:KPMenuControl>")]
    public class KPMenuControl : WebControl
    {
        public string Title { get; set; }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (Page != null)
                EnsureChildControls();
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            #region MenuControl
            HtmlGenericControl menuControl = new HtmlGenericControl("div");
            menuControl.Attributes.Add("class", "Menu");

            KPSecuritySession session = (KPSecuritySession)KPSessionHelper.GetSession(KPSessionKeyEnum.SESSION_LOGIN);
            if (session == null)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
                return;
            }

            FrwUser loggedUser = FrwUser.FindOne(Expression.Eq("UserLogin", session.Login));

            // Add Main Menu Bar
            menuControl.Controls.Add(this.MainMenuBar(loggedUser));

            // Add user Action Bar
            menuControl.Controls.Add(this.UserActionBar(session));

            // Add
            //menuControl.Controls.Add(menuForm);

            #endregion MenuControl
            this.Controls.Add(menuControl);

            #region Script code
            // TODO: WindowFinderInput Foi comentado

            /*
            string userCrypt = KPCryptography.EncryptStringAES(session.Login);
            string wcfAjaxJason = System.Web.VirtualPathUtility.ToAbsolute("~/WCF/WCFAjaxJson.svc/GetWindowFinder");
            string scriptWindowFinder = @"
                    $(function () {
                            $(""#WindowFinderInput"").keypress(function (e) {
                                if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                                    var params = new Object();
                                    params.windowID = $(""#WindowFinderInput"").val();
                                    params.user = '" + userCrypt + @"';

                                    $.ajax({
                                            url: '" + wcfAjaxJason + @"',
                                            data: JSON.stringify(params),
                                            dataType: 'json',
                                            type: 'POST',
                                            contentType: 'application/json; charset=utf-8'
                                        })
                                        .done(function (data) {
                                            if (!isEmptyOrNull(data.d)) {
                                                eval(data.d);
                                            }
                                            $(""#WindowFinderInput"").val('');
                                        })
                                        .fail(function (jqXHR, textStatus, error) {
                                            alert(error);
                                        });
                                    return false;
                                }
                                return true;
                            });
                        });";

            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "WindowFinderScript", scriptWindowFinder, true);
            */

            #endregion Script code
        }

        public HtmlGenericControl MainMenuBar(FrwUser loggedUser)
        {
            HtmlGenericControl mainMenuBar = new HtmlGenericControl("ul");
            mainMenuBar.Attributes.Add("class", "MainMenuBar");

            #region UL MainMenuBar

            ICriterion query = Expression.And(Expression.Eq("IsVisible", StateVisibleEnum.Yes), Expression.IsNull("objIdParent"));
            FrwMenu[] frwMenuRootList = FrwMenu.FindAll(Order.Asc("Sequence"), query);

            #region Menu Item

            HtmlGenericControl menuItemRoot = this.CreateMenuItem(Title);
            HtmlGenericControl menuItemsBox = this.CreateMenuItemItems(frwMenuRootList);

            #endregion Menu Item
            mainMenuBar.Controls.Add(menuItemRoot);

            #region Menu Item WindowFinder

            // TODO: WindowFinderInput foi comentado.
            // HtmlGenericControl menuItemWindowFinder = this.CreateMenuItemWindowFinder();

            #endregion Menu Item WindowFinder
            // mainMenuBar.Controls.Add(menuItemWindowFinder);

            #region Items Sub Menus
            foreach (FrwMenu item in frwMenuRootList)
            {
                HtmlGenericControl subMenu = this.CreateMenuItemItemSubMenu(item);

                if (subMenu != null)
                {
                    menuItemsBox.Controls.Add(this.CreateMenuItemItem(item));
                    mainMenuBar.Controls.Add(subMenu);
                }
            }

            menuItemRoot.Controls.Add(menuItemsBox);
            #endregion Items Sub Menus

            #endregion UL MainMenuBar

            return mainMenuBar;
        }

        ///
        /// This method creates the user action bar
        ///
        /// <param name="userSecSess"></param>
        /// <returns></returns>
        private HtmlGenericControl UserActionBar(KPSecuritySession userSecSess)
        {
            FrwUser loggedUser = FrwUser.FindOne(Expression.Eq("UserLogin", userSecSess.Login));

            //StringBuilder sbMenu = new StringBuilder();
            HtmlGenericControl menuUserAction = new HtmlGenericControl("div");
            menuUserAction.Attributes.Add("class", "MenuUserAction");

            #region DIV MenuUserAction

            #region DIV User Info
            HtmlGenericControl userInfo = new HtmlGenericControl("div");
            userInfo.Attributes.Add("class", "UserInfo");

            HtmlGenericControl userName = new HtmlGenericControl("span");
            userName.Attributes.Add("class", "UserName");
            userName.Attributes.Add("title", "Nome do Usuário");
            userName.InnerText = loggedUser.UserFullName;

            userInfo.Controls.Add(userName);
            #endregion DIV User Info
            menuUserAction.Controls.Add(userInfo);

            #region DIV Company
            FrwUserCompany[] listUserCompany = FrwUserCompany.FindAllByProperty("objIdUser", loggedUser);

            DropDownList userCompanyControl = new DropDownList() { AutoPostBack = true };
            userCompanyControl.SelectedIndexChanged += new EventHandler(userCompanyControl_SelectedIndexChanged);
            userCompanyControl.Attributes.Add("class", "UserCompany");
            userCompanyControl.Attributes.Add("title", "Trocar Empresa");

            foreach (FrwUserCompany userCompany in listUserCompany)
            {
                ListItem item = new ListItem();
                item.Value = userCompany.objIdCompany.IdCompany.ToString();
                item.Text = userCompany.objIdCompany.CompanyFantasyName;

                if (userSecSess.FrwCompany == userCompany.objIdCompany.IdCompany)
                {
                    item.Selected = true;
                }

                userCompanyControl.Items.Add(item);
            }

            #endregion DIV Company

            //HtmlForm companyForm = new HtmlForm();
            //companyForm.Controls.Add(userCompanyControl);
            menuUserAction.Controls.Add(userCompanyControl);

            #region Actions

            //HtmlGenericControl btSettings = new HtmlGenericControl("button");
            //btSettings.Attributes.Add("class", "Action Settings");

            HtmlGenericControl btLogout = new HtmlGenericControl("button");
            btLogout.Attributes.Add("class", "Action Logout");
            btLogout.Attributes.Add("title", "Sair do Sistema");
            btLogout.Attributes.Add("onclick", "window.location.replace('Logout.aspx'); return false;");

            #endregion Actions
            // menuUserAction.Controls.Add(btSettings);
            menuUserAction.Controls.Add(btLogout);

            #endregion DIV MenuUserAction

            return menuUserAction;
        }

        private void userCompanyControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            KPSecuritySession userSecSess = (KPSecuritySession)KPSessionHelper.GetSession(KPSessionKeyEnum.SESSION_LOGIN);
            int companyID = userSecSess.FrwCompany;
            userSecSess.FrwCompany = Convert.ToInt32(((DropDownList)sender).SelectedValue);
            LogHelper.Log(String.Format("Usuário [{0}] trocou de empresa de ID [{1}] para ID [{2}]", userSecSess.Login, companyID, userSecSess.FrwCompany));
            KPSessionHelper.SetSession(KPSessionKeyEnum.SESSION_LOGIN, userSecSess);

            //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "RefrechAll", "parent.__doPostBack('','');", true);

        }

        ///
        /// This method creates a new Menu Item
        ///
        /// <param name="menuItemTitle"></param>
        /// <returns></returns>
        private HtmlGenericControl CreateMenuItem(string menuItemTitle)
        {
            HtmlGenericControl menuItem = new HtmlGenericControl("li");
            menuItem.Attributes.Add("class", "MenuItem");

            HtmlGenericControl menuTitle = new HtmlGenericControl("a");
            menuTitle.Attributes.Add("class", "MenuItemTitle");
            menuTitle.InnerText = (String.IsNullOrEmpty(menuItemTitle) ? "" : menuItemTitle);
            //sbMenu.Append(@"");
            //

            HtmlGenericControl menuTitleImg = new HtmlGenericControl("img");
            menuTitleImg.Attributes.Add("class", "MenuTitleImage");
            menuTitleImg.Attributes.Add("src", "/Assets/Imgs/Themes/Default/menu_icon.png");

            menuTitle.Controls.Add(menuTitleImg);

            menuItem.Controls.Add(menuTitle);

            return menuItem;
        }

        ///
        /// Create the items to the menu Item
        ///
        /// <param name="frwMenuItemList"></param>
        /// <returns>An HtmlGenericControl with items to be add to MenuItem</returns>
        private HtmlGenericControl CreateMenuItemItems(FrwMenu[] frwMenuItemList)
        {
            HtmlGenericControl menuItem = new HtmlGenericControl("ul");
            menuItem.Attributes.Add("class", "DropdownMenu DropdownMenuHidden");
            /*
            foreach (FrwMenu item in frwMenuItemList)
            {
                HtmlGenericControl idMenuItem = new HtmlGenericControl("li");
                idMenuItem.Attributes.Add("data-submenu-id", ("MenuItem" + item.IdMenu));

                HtmlGenericControl idMenuTitle = new HtmlGenericControl("a");
                idMenuTitle.InnerText = item.WindowTitleMenu;

                idMenuItem.Controls.Add(idMenuTitle);

                menuItem.Controls.Add(idMenuItem);
            }
            */
            return menuItem;
        }

        private HtmlGenericControl CreateMenuItemItem(FrwMenu item)
        {
            HtmlGenericControl idMenuItem = new HtmlGenericControl("li");
            idMenuItem.Attributes.Add("data-submenu-id", ("MenuItem" + item.IdMenu));

            HtmlGenericControl idMenuTitle = new HtmlGenericControl("a");
            idMenuTitle.InnerText = item.WindowTitleMenu;

            idMenuItem.Controls.Add(idMenuTitle);

            return idMenuItem;
        }

        ///
        /// This method creates the MenuItem related to FindWindows in the system.
        ///
        /// <returns></returns>
        private HtmlGenericControl CreateMenuItemWindowFinder()
        {
            HtmlGenericControl menuItemWindowFinder = new HtmlGenericControl("li");
            menuItemWindowFinder.Attributes.Add("class", "MenuItem");

            HtmlForm menuForm = new HtmlForm();
            menuForm.Attributes.Add("id", "WindowFinderForm");

            HtmlGenericControl menuInput = new HtmlGenericControl("input");
            menuInput.Attributes.Add("id", "WindowFinderInput");
            menuInput.Attributes.Add("class", "WindowFinder");

            menuForm.Controls.Add(menuInput);

            menuItemWindowFinder.Controls.Add(menuInput);

            return menuItemWindowFinder;
        }

        private HtmlGenericControl CreateMenuItemItemSubMenu(FrwMenu subMenuItem)
        {
            bool hasChildren = false;

            KPSecuritySession securitySession = KPFormsAuthentication.SecuritySession;
            string strOnClickMenu = @"addNewTab('KPTabControl', '{0}', '{1}');";

            HtmlGenericControl subMenuItemControl = new HtmlGenericControl("div");
            subMenuItemControl.Attributes.Add("id", ("MenuItem" + subMenuItem.IdMenu));
            subMenuItemControl.Attributes.Add("class", "PopOverMenu");

            #region Title

            HtmlGenericControl subMenuItemTitle = new HtmlGenericControl("h3");
            subMenuItemTitle.Attributes.Add("class", "PopOverMenuTitle");
            subMenuItemTitle.InnerText = subMenuItem.WindowTitleMenu;

            #endregion
            subMenuItemControl.Controls.Add(subMenuItemTitle);

            HtmlGenericControl menuContent = new HtmlGenericControl("div");
            menuContent.Attributes.Add("class", "PopOverMenuContent");

            #region Menu Content Items

            HtmlGenericControl menuContentItems = new HtmlGenericControl("ul");
            menuContentItems.Attributes.Add("class", "PopOverMenuContentItems");

            PagePermission securityPage = null;
            bool itemNivel2Create = false;
            bool isOnlyMenuItem = false;
            FrwMenu parentNivel1Order = FrwMenu.TryFind(subMenuItem.IdMenu);
            FrwMenu[] frwMenuNivel1List = FrwMenu.FindAll(Order.Asc("Sequence"), Expression.And(Expression.Eq("IsVisible", StateVisibleEnum.Yes), Expression.Eq("objIdParent", parentNivel1Order)));
            foreach (FrwMenu itemNivel1 in frwMenuNivel1List)
            {

                isOnlyMenuItem = itemNivel1.objIdWindow.WindowEnum.Equals("_UNKNOW_");
                securityPage = securitySession.GetPagePermission(itemNivel1.objIdWindow.IdWindow);
                if (isOnlyMenuItem || (securityPage != null && securityPage.ExistPage && securityPage.IsPreview))
                {
                    HtmlGenericControl subMenuItemLi = this.CreateItemLinkToOpeMenu(strOnClickMenu, itemNivel1);

                    FrwMenu parentNivel2Order = FrwMenu.TryFind(itemNivel1.IdMenu);
                    FrwMenu[] frwMenuNivel2List = FrwMenu.FindAll(Order.Asc("Sequence"), Expression.And(Expression.Eq("IsVisible", StateVisibleEnum.Yes), Expression.Eq("objIdParent", parentNivel2Order)));
                    if (frwMenuNivel2List.Count() > 0)
                    {
                        HtmlGenericControl subSubMenuItem = new HtmlGenericControl("ul");
                        subSubMenuItem.Attributes.Add("class", "SubSubMenuItem");

                        itemNivel2Create = false;
                        foreach (FrwMenu itemNivel2 in frwMenuNivel2List)
                        {
                            if (itemNivel2 != null && itemNivel2.objIdWindow != null)
                            {
                                securityPage = securitySession.GetPagePermission(itemNivel2.objIdWindow.IdWindow);
                                if (securityPage != null && securityPage.ExistPage && securityPage.IsPreview)
                                {
                                    itemNivel2Create = true;
                                    HtmlGenericControl subSubMenuItemLi = this.CreateItemLinkToOpeMenu(strOnClickMenu, itemNivel2);
                                    subSubMenuItem.Controls.Add(subSubMenuItemLi);
                                }
                            }
                        }

                        if (itemNivel2Create || !isOnlyMenuItem)
                        {
                            hasChildren = true;
                            subMenuItemLi.Controls.Add(subSubMenuItem);
                        }
                    }

                    menuContentItems.Controls.Add(subMenuItemLi);
                }
            }

            #endregion Menu Content Items
            menuContent.Controls.Add(menuContentItems);

            #region Menu content image

            HtmlGenericControl menuContentImage = new HtmlGenericControl("img");
            menuContentImage.Attributes.Add("alt", subMenuItem.WindowTitleMenu);
            menuContentImage.Attributes.Add("src", subMenuItem.ImageUrl);

            #endregion Menu content image
            menuContent.Controls.Add(menuContentImage);

            subMenuItemControl.Controls.Add(menuContent);

            if (!hasChildren)
            {
                subMenuItemControl = null;
            }

            return subMenuItemControl;
        }

        private HtmlGenericControl CreateItemLinkToOpeMenu(string strOnClickMenu, FrwMenu item)
        {

            string onClickAction = "";
            if (!String.IsNullOrEmpty(item.objIdWindow.WindowPath) && !item.objIdWindow.WindowPath.Equals("#"))
            {
                onClickAction = String.Format(strOnClickMenu, item.objIdWindow.WindowTitle, item.objIdWindow.WindowPath);
            }

            HtmlGenericControl subMenuItemLi = new HtmlGenericControl("li");

            HtmlGenericControl subMenuItemLink = new HtmlGenericControl("a");
            subMenuItemLink.InnerText = item.WindowTitleMenu;
            if (!String.IsNullOrEmpty(onClickAction))
            {
                subMenuItemLink.Attributes.Add("onclick", onClickAction);
            }

            subMenuItemLi.Controls.Add(subMenuItemLink);

            return subMenuItemLi;
        }

    }
}


text:
#ifndef IO_UTIL_H
#define IO_UTIL_H

#include "avro.h"
#include "postgres.h"

#define check(err, call) { err = call; if (err) return err; }

/* Function that writes something using the Avro writer that is passed to it. Must return 0
 * on success, ENOSPC if the buffer was too small (the operation will be retried), and any
 * other value to indicate any other error (the operation will not be retried). */
typedef int (*try_writing_cb)(avro_writer_t, void *);

int try_writing(bytea **output, try_writing_cb cb, void *context);
int write_schema_json(avro_writer_t writer, void *context);
int write_avro_binary(avro_writer_t writer, void *context);

#endif /* IO_UTIL_H */

redpajama_set_name: RedPajamaGithub


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

namespace EpForceDirectedGraph.cs
{
    public class Triple<T,U,V>
    {
        public Triple()
        {
        }

        public Triple(T iFirst, U iSecond,V iThird)
        {
            this.first = iFirst;
            this.second = iSecond;
            this.third = iThird;
        }

        public T first { get; set; }
        public U second { get; set; }
        public V third { get; set; }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 80: 129 (1941)

#### Original name
Mollisiaster serratus Kirschst.

### Remarks
null


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.banda.network.domain.NetworkFunction" table="NET_FUNCTION" schema="public">

        <id name="id" type="long">
        	<column name="id" />
        	<generator class="edu.banda.coel.server.common.ConfigurableAssignedGenerator">
      			<param name="delegate">sequence</param>
      			<param name="sequence">NET_FUNCTION_ID_SEQ</param>
   			</generator>
        </id>

        <version name="version" type="java.lang.Long">
            <column name="ol_version" not-null="true" />
        </version>

        <property name="name" type="string">
            <column name="name" length="50" not-null="true" />
        </property>

        <property name="timeCreated" type="timestamp">
            <column name="time_created" not-null="true" />
        </property>

        <many-to-one name="createdBy" class="com.banda.core.domain.um.User" lazy="proxy" fetch="select">
            <column name="created_by"/>
        </many-to-one>

        <property name="index" type="java.lang.Integer">
            <column name="index_" />
        </property>

        <many-to-one name="function" class="com.banda.function.domain.AbstractFunction" fetch="join" cascade="all">
            <column name="function_id" not-null="true" />
        </many-to-one>

	    <property name="statesWeightsIntegratorType">
    		<column name="states_weights_integrator_type"/>
        	<type name="org.hibernate.type.EnumType">
        		<param name="type">5</param>
    	        <param name="enumClass">com.banda.network.domain.StatesWeightsIntegratorType</param>
	        </type>
       	</property>

	    <property name="multiComponentUpdaterType">
    		<column name="multi_component_updater_type" not-null="true" />
        	<type name="org.hibernate.type.EnumType">
        		<param name="type">5</param>
    	        <param name="enumClass">com.banda.core.domain.MultiStateUpdateType</param>
	        </type>
       	</property>

        <many-to-one name="parentFunction" class="com.banda.network.domain.NetworkFunction" fetch="select">
        	<column name="parent_id"/>
    	</many-to-one>

        <bag name="layerFunctions" lazy="false" inverse="true" fetch="join" cascade="all-delete-orphan" order-by="index_">
            <key column="parent_id" not-null="true" />
            <one-to-many class="com.banda.network.domain.NetworkFunction" />
        </bag>

    </class>
</hibernate-mapping>


text:
		<form class="form-inline" role="form">

					 Monto
					<input type="text" class="form-control input-sm" placeholder="Monto gastado">

					Tipo Moneda
					<select class="form-control input-sm">
					  <option>Seleccione una opción</option>
					  <option>MXP</option>
					  <option>USD</option>
					</select>

					Concepto
					<select class="form-control input-sm">
					  <option>Seleccione una opción</option>
					  <option>Alimento</option>
					  <option>Transporte</option>
					  <option>Hospedaje</option>
					</select>

					Comprobante
					<select class="form-control input-sm">
					  <option>Seleccione una opción</option>
					  <option>Si</option>
					  <option>No</option>
					</select>

					Elige un archivo
					<input type="file" id="exampleInputFile">

					Justificación
					<select class="form-control input-sm">
					  <option>Seleccione una opción</option>
					  <option>1</option>
					  <option>2</option>
					</select>

					Agregar
					<button class='btn btn-info' data-toggle="tooltip" data-placement="right" title="Agregar más gastos" ></button>

Gastos

							#
							Monto
							Moneda
							Concepto
							Èxiste comprobante
							Justificación

					<button class='btn btn-primary' >Guardar</button>

		</form>


text:
/**
 * beaker
 * - the very root of everything, the starting point of everything
 * - setup routing
 * - only the most fundamental configs go here.
 */
(function() {
  'use strict';

  window.beaker = {
    toBeAddedToOutputDisplayFactory: {},
    bkoDirective: function(type, impl) {
      if (window.beaker.outputDisplayFactory) {
        window.beaker.outputDisplayFactory.add(type, impl);
      } else {
        this.toBeAddedToOutputDisplayFactory[type] = impl;
      }
    },
    toBeAddedToOutputDisplayService: {},
    bkoFactory: function(name, impl) {
      if (window.beaker.outputDisplayService) {
        window.beaker.outputDisplayService.addService(name, impl);
      } else {
        this.toBeAddedToOutputDisplayService[name] = impl;
      }
    },
    toBeAddedToOutputDisplayType: {},
    registerOutputDisplay: function(type, displays) {
      if (window.beaker.outputDisplayFactory) {
        window.beaker.outputDisplayFactory.addOutputDisplayType(type, displays);
      } else {
        this.toBeAddedToOutputDisplayType[type] = displays;
      }
    },
    postHelperHooks: []
  };

  var initPlugins = function() {
    var deferred = Q.defer();
    var plugins;
    // duplicated in commonUtils.js
    function loadJS(url, success, failure) {
      var e = document.createElement('script');
      e.type = "text/javascript";
      var millis = new Date().getTime();
      e.src = url + "?_=" + millis;
      if (success) {
        e.onload = success;
      }
      if (failure) {
        e.onerror = failure;
      }
      document.head.appendChild(e);
    };
    function loadList(urls, success, failure) {
      if (urls.length == 0) {
        if (success)
          return success();
        return;
      }
      var url = urls.shift();
      loadJS(url, function() {
        loadList(urls, success, failure);
      }, failure);
    }

    $.get('../beaker/rest/util/getInitPlugins')
        .done(function(list) {
          loadList(list, function() {
            deferred.resolve();
          }, function() {
            console.log("error loading init plugins");
          });
        });
    return deferred.promise;
  };

  var initOutputDisplay = function()
  {
    var deferred = Q.defer();

    ZeroClipboard.config( { swfPath: "app/images/ZeroClipboard.swf", hoverClass: 'dropdown-submenu-flash' } );

    function loadJS(url, success, failure) {
      var e = document.createElement('script');
      e.type = "text/javascript";
      e.src = url;
      if (success) {
        e.onload = success;
      }
      if (failure) {
        e.onerror = failure;
      }
      document.head.appendChild(e);
    };
    function loadList(urls, success, failure) {
      if (urls.length == 0) {
        if (success)
          return success();
        return;
      }
      var url = urls.shift();
      loadJS(url, function() {
        loadList(urls, success, failure);
      }, failure);
    }

    if (window.bkInit && window.bkInit.getOutputDisplayCssList) {
      for ( var i = 0; i < window.bkInit.getOutputDisplayCssList.length; i++) {
        var url = window.bkInit.getOutputDisplayCssList[i];
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = url;
        document.head.appendChild(link);
      }
    }
    if (window.bkInit && window.bkInit.getOutputDisplayJsList) {
      loadList(window.bkInit.getOutputDisplayJsList, function() {
        deferred.resolve();
      }, function() {
        console.log("error loading output displays");
      });
    } else
      deferred.resolve();
    return deferred.promise;
  }

  var setupBeakerConfigAndRun = function() {

    var beaker = angular.module('beaker', [
      'ngRoute',
      'ngStorage',
      'bk.core',
      'bk.evaluatePluginManager',
      'bk.controlPanel',
      'bk.mainApp',
      'bk.helper',
      'bk.utils',
      'bk.publication',
      'bk.electron'
    ]);

    // setup routing. the template is going to replace ng-view
    beaker.config(function($routeProvider) {
      var sessionRouteResolve = {};
      var generateId = function() {
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        return _(_.range(6)).map(function() {
          return possible.charAt(Math.floor(Math.random() * possible.length));
        }).join('');
      };
      var makeNewProvider = function(result) {
        return function() {
          var newSessionId = generateId();
          sessionRouteResolve.isNewSession = function () {
            return result;
          };
          return '/session/' + newSessionId;
        };
      };
      $routeProvider
          .when('/session/new', {
            redirectTo: makeNewProvider("new")
          })
          .when('/session/empty', {
            redirectTo: makeNewProvider("empty")
          })
          .when('/session/import', {
            redirectTo: function() {
              sessionRouteResolve.isImport = function() {
                return true;
              };
              return '/session/' + generateId();
            }
          })
          .when('/session/:sessionId', {
            template: JST["template/mainapp/app"](),
            controller: 'notebookRouter',
            resolve: sessionRouteResolve
          })
          .when('/open', {
            redirectTo: function(routeParams, path, search) {
              var newSessionId = generateId();
              sessionRouteResolve.isOpen = function() {
                return true;
              };
              sessionRouteResolve.target = function() {
                return search;
              };
              return '/session/' + newSessionId;
            }
          })
          .when('/control', {
            template: JST["template/dashboard/app"]()
          }).otherwise({
            redirectTo: "/control"
          });
    });

    beaker.config(function(bkRecentMenuProvider) {
      var recentMenuServer = {
        addItem: function(doc, callback) {
          if (!doc) {
            return;
          }

          var req = $.ajax({
            type: "POST",
            datatype: "json",
            url: "../beaker/rest/recent-menu/addItem",
            data: {item: doc}
          });
          req.done(callback);
          req.fail(function(jqXHR, textStatus) {
            console.error("Request failed: " + textStatus);
          });
        },
        getItems: function(callback) {
          var req = $.ajax({
            type: "GET",
            datatype: "json",
            url: "../beaker/rest/recent-menu/getItems",
            data: {}
          });
          req.done(callback);
          req.fail(function(jqXHR, textStatus) {
            console.error("Request failed: " + textStatus);
          });
        },
        clear: function(callback) {
          var req = $.ajax({
            type: "POST",
            datatype: "json",
            url: "../beaker/rest/recent-menu/clear",
            data: {}
          });
          req.done(callback);
          req.fail(function(jqXHR, textStatus) {
            console.error("Request failed: " + textStatus);
          });
        }
      };
      bkRecentMenuProvider.configServer(recentMenuServer);
    });

    beaker.config(function(bkShareProvider) {
      if (window.bkInit && window.bkInit.shareService) {
        bkShareProvider.config(window.bkInit.shareService);
      }
    });

    beaker.config(function(bkTrackProvider) {
      if (window.bkInit && window.bkInit.trackingService) {
        bkTrackProvider.config(window.bkInit.trackingService);
      }
    });

    beaker.run(function($rootScope, $location, $route, $document, bkUtils, bkCoreManager, bkHelper, bkElectron) {
      var user;
      var lastAction = new Date();
      var beakerRootOp = {
        gotoControlPanel: function() {
          var ret = $location.path("/control").search({});
          if (bkUtils.isElectron) {
            $rootScope.$apply();
          }
          return ret;
        },
        openNotebook: function(notebookUri, uriType, readOnly, format) {
          if (!notebookUri) {
            return;
          }
          var routeParams = {
            uri: notebookUri
          };
          if (uriType) {
            routeParams.type = uriType;
          }
          if (readOnly) {
            routeParams.readOnly = true;
          }
          if (format) {
            routeParams.format = format;
          }
          var ret = $location.path('/open').search(routeParams);
          if (bkUtils.isElectron) {
            $rootScope.$apply();
          }
          return ret;
        },
        newSession: function(empty) {
          var name = "/session/new";
          if (empty) {
            name = "/session/empty";
          }
          if (bkUtils.isElectron){
            bkHelper.openWindow(name, 'notebook');
            return;
          }
          if ($location.$$path === name) {
            return $route.reload();
          } else {
            return $location.path(name).search({});
          }
        },
        openSession: function(sessionId) {
          if (bkUtils.isElectron) {
            bkElectron.IPC.send('session-focused', sessionId);
          } else {
            return $location.path("session/" + sessionId).search({});
          }
        }
      };
      bkUtils.initializeCometd(document.baseURI+'cometd/');
      bkCoreManager.init(beakerRootOp);
      Q.delay(1000).then(function() {
        $.get("../beaker/rest/util/whoami", {}, function(data) {
          user = data;
          bkUtils.log("start", {user: data});
        }, "json");
      });
      var noteAction = function() {
        lastAction = new Date();
      };
      window.addEventListener('click', noteAction, false);
      window.addEventListener('keypress', noteAction, false);
      window.setInterval(function() {
        var now = new Date();
        if ((now - lastAction) < 60 * 1000) {
          bkUtils.log("tick", {user: user});
        }
      }, 60 * 1000);
      $document.bind('keydown', function(e) {
        if (e.which === 27) {
          $('.dropdown.open .dropdown-toggle').dropdown('toggle');
        }
      });
      bkCoreManager.addImportInput();
      $document.bind('drop dragover', function (e) {
        e.preventDefault();
      });
      var counter = 0;
      $document.bind('dragenter', function (e) {
        counter++;
        $('body').addClass('dragover');
      });
      $document.bind('dragleave', function (e) {
        counter--;
        if (counter === 0) {
          $('body').removeClass('dragover');
        }
      });
      $document.bind('drop', function() {
        $('body').removeClass('dragover');
      });
      window.bkHelper = bkHelper;
      for (var i in window.beaker.postHelperHooks) {
        window.beaker.postHelperHooks[i]();
      }
    });

    beaker.run(function(bkEvaluatePluginManager) {
      // for known plugins, so we can refer to the plugin with either its name or URL
      var defaultEvaluatorUrlMap = {
        "Html": { url: "./plugin/evaluator/html.js",             bgColor: "#E3502B", fgColor: "#FFFFFF", borderColor: "",        shortName: "Ht" },
        "Latex": { url: "./plugin/evaluator/latex.js",           bgColor: "#FFFFFF", fgColor: "#030303", borderColor: "#3D4444", shortName: "La" },
        "JavaScript": { url: "./plugin/evaluator/javaScript.js", bgColor: "#EFDB52", fgColor: "#4A4A4A", borderColor: "",        shortName: "Js" }
      };

      _.chain(defaultEvaluatorUrlMap).each(function(value, key) {
        bkEvaluatePluginManager.addNameToUrlEntry(key, value);
      });

      if (window.bkInit && window.bkInit.getEvaluatorUrlMap) {
        var evaluatorsUrlMap = window.bkInit.getEvaluatorUrlMap();
        _.chain(evaluatorsUrlMap).keys().each(function(key) {
          var value = evaluatorsUrlMap[key];
          bkEvaluatePluginManager.addNameToUrlEntry(key, value);
        });
      }
    });

    beaker.run(function(bkUtils, $rootScope) {
      bkUtils.getVersionInfo().then(function(versionInfo) {
        window.beaker.version = versionInfo.version;
        window.beaker.buildTime = versionInfo.buildTime;
        $rootScope.getVersion = function() {
          return window.beaker.version;
        };
        $rootScope.getBuildTime = function() {
          return window.beaker.buildTime;
        };
      });
    });
  };
  var bootstrapBkApp = function() {
    // make sure requirejs reports error
    requirejs.config({
      enforceDefine: true
    });

    angular.element(document).ready(function() {
      angular.bootstrap(document, ["beaker"]);
    });
  };
  Q.fcall(initPlugins).then(initOutputDisplay)
      .then(setupBeakerConfigAndRun)
      .then(bootstrapBkApp)
      .catch(function (err) {
        console.log(err);
      });
})();


text:
package org.wildfly.security.mechanism._private;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.util.function.Function;
import java.util.function.Supplier;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.wildfly.common.Assert;
import org.wildfly.security.auth.callback.CredentialCallback;
import org.wildfly.security.credential.PasswordCredential;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.mechanism.AuthenticationMechanismException;
import org.wildfly.security.password.Password;
import org.wildfly.security.password.PasswordFactory;
import org.wildfly.security.password.TwoWayPassword;
import org.wildfly.security.password.interfaces.ClearPassword;
import org.wildfly.security.password.spec.ClearPasswordSpec;
import org.wildfly.security.password.spec.EncryptablePasswordSpec;

/**
 * Utils to be used by authentication mechanism (SASL or HTTP) implementations.
 *
 * @author David M. Lloyd
 */
public final class MechanismUtil {
    private MechanismUtil() {}

    /**
     * Get a password from a client or server callback, falling back to clear password if needed.  Note that the
     * parameters, while optional, may be required on the client side of some mechanisms in order to ensure that the
     * encoded password is compatible with the server challenge.
     *
     * @param userName the user name to report for error reporting purposes (must not be {@code null})
     * @param callbackHandler the callback handler (must not be {@code null})
     * @param passwordType the password class (must not be {@code null})
     * @param passwordAlgorithm the password algorithm name (must not be {@code null})
     * @param matchParameters the optional parameters to match (may be {@code null})
     * @param generateParameters the optional default parameters to use if the password must be generated (may be {@code null})
     * @param providers the security providers to use with the {@link PasswordFactory}
     * @param <S> the password type
     * @param log mechanism specific logger
     * @return the password
     */
    public static <S extends Password> S getPasswordCredential(String userName, CallbackHandler callbackHandler, Class<S> passwordType, String passwordAlgorithm, AlgorithmParameterSpec matchParameters, AlgorithmParameterSpec generateParameters, Supplier<Provider[]> providers, ElytronMessages log) throws AuthenticationMechanismException {
        Assert.checkNotNullParam("userName", userName);
        Assert.checkNotNullParam("callbackHandler", callbackHandler);
        Assert.checkNotNullParam("passwordType", passwordType);
        Assert.checkNotNullParam("passwordAlgorithm", passwordAlgorithm);
        Assert.checkNotNullParam("providers", providers);
        try {
            final PasswordFactory passwordFactory = PasswordFactory.getInstance(passwordAlgorithm, providers);

            CredentialCallback credentialCallback = new CredentialCallback(PasswordCredential.class, passwordAlgorithm, matchParameters);

            try {
                MechanismUtil.handleCallbacks(log, callbackHandler, credentialCallback);
                S password = credentialCallback.applyToCredential(PasswordCredential.class, c -> c.getPassword(passwordType));
                if (password != null) {
                    // update parameters to match requirement, if necessary
                    return matchParameters != null ? passwordType.cast(passwordFactory.transform(password, matchParameters)) : password;
                }
                // fall out
            } catch (UnsupportedCallbackException e) {
                if (e.getCallback() != credentialCallback) {
                    throw log.mechCallbackHandlerFailedForUnknownReason(e);
                }
                // fall out
            } catch (InvalidAlgorithmParameterException | ClassCastException e) {
                // fall out
            }

            credentialCallback = new CredentialCallback(PasswordCredential.class, ClearPassword.ALGORITHM_CLEAR);

            try {
                MechanismUtil.handleCallbacks(log, callbackHandler, credentialCallback);
                final TwoWayPassword twoWayPassword = credentialCallback.applyToCredential(PasswordCredential.class, c -> c.getPassword(TwoWayPassword.class));
                if (twoWayPassword != null) {
                    final PasswordFactory clearFactory = PasswordFactory.getInstance(twoWayPassword.getAlgorithm(), providers);
                    final ClearPasswordSpec spec = clearFactory.getKeySpec(clearFactory.translate(twoWayPassword), ClearPasswordSpec.class);
                    if (matchParameters != null) {
                        return passwordType.cast(passwordFactory.generatePassword(new EncryptablePasswordSpec(spec.getEncodedPassword(), generateParameters)));
                    } else {
                        return passwordType.cast(passwordFactory.generatePassword(spec));
                    }
                }
            } catch (UnsupportedCallbackException e) {
                if (e.getCallback() != credentialCallback) {
                    throw log.mechCallbackHandlerFailedForUnknownReason(e);
                }
                // fall out
            }

            final PasswordCallback passwordCallback = new PasswordCallback("User password", false);

            try {
                MechanismUtil.handleCallbacks(log, callbackHandler, passwordCallback);
                final char[] password = passwordCallback.getPassword();
                if (password != null) {
                    if (matchParameters != null) {
                        return passwordType.cast(passwordFactory.generatePassword(new EncryptablePasswordSpec(password, generateParameters)));
                    } else {
                        return passwordType.cast(passwordFactory.generatePassword(new ClearPasswordSpec(password)));
                    }
                }
            } catch (UnsupportedCallbackException e) {
                if (e.getCallback() != passwordCallback) {
                    throw log.mechCallbackHandlerFailedForUnknownReason(e);
                }
                // fall out
            }
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) {
            throw log.mechCallbackHandlerDoesNotSupportCredentialAcquisition(e);
        }

        throw log.mechUnableToRetrievePassword(userName);
    }

    /**
     * A varargs wrapper method for callback handler invocation.
     *
     * @param log the logger for error purposes
     * @param callbackHandler the callback handler
     * @param callbacks the callbacks
     * @throws AuthenticationMechanismException if the callback handler fails for some reason
     * @throws UnsupportedCallbackException if the callback handler throws this exception
     */
    public static void handleCallbacks(ElytronMessages log, CallbackHandler callbackHandler, Callback... callbacks) throws AuthenticationMechanismException, UnsupportedCallbackException {
        try {
            callbackHandler.handle(callbacks);
        } catch (AuthenticationMechanismException | UnsupportedCallbackException e) {
            throw e;
        } catch (Throwable e) {
            throw log.mechCallbackHandlerFailedForUnknownReason(e);
        }
    }

    /**
     * Get or compute the value for the given key in HttpScope, storing the computed value (if one is generated).
     * The function must not generate a {@code null} value or an unspecified exception will result.
     *
     * @param scope the HTTP scope to store computed value (must not be {@code null})
     * @param key the key to retrieve (must not be {@code null})
     * @param mappingFunction the function to apply to acquire the value (must not be {@code null})
     * @return the stored or new value (not {@code null})
     */
    public static <R> R computeIfAbsent(HttpScope scope, String key, Function<String, R> mappingFunction) {
        Assert.checkNotNullParam("scope", scope);
        Assert.checkNotNullParam("key", key);
        Assert.checkNotNullParam("mappingFunction", mappingFunction);
        synchronized (scope) {
            if (! scope.exists()) {
                scope.create();
            }
            final R existing = (R) scope.getAttachment(key);
            if (existing == null) {
                R newValue = mappingFunction.apply(key);
                Assert.assertNotNull(newValue);
                scope.setAttachment(key, newValue);
                return newValue;
            } else {
                return existing;
            }
        }
    }
}


text:
import { GridColumn } from './gridColumn';
export class GridConfig {

  private _columns: Array<GridColumn>;

  constructor() {
    this._columns = [];
  }

  public addColumn(column: GridColumn) {
    this._columns.push(column);
  }

  public getColumns(): Array<GridColumn> {
    return this._columns;
  }
}


text:
from __future__ import print_function

import tensorflow as tf
import numpy as np

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data

#  Fully connected layer
def fc_layer(z, n_neurons, activ_function, reg_function):
    n_inputs = int(z.get_shape()[1])
    stddev = 1 / np.sqrt(n_inputs)
    w_shape = (n_inputs,n_neurons)
    w_init = tf.truncated_normal(w_shape, stddev=stddev)
    w = tf.Variable(w_init, name="weights")

    b_init = tf.zeros([n_neurons])
    b = tf.Variable(b_init, name='biases')

    a = tf.matmul(z, w) + b

    reg_loss = 0
    if reg_function is not None:
        reg_loss = reg_function(w)

    return activ_function(a), reg_loss

#  Reset del grafo
tf.reset_default_graph()

# Lectura del dataset
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)

# Parameters
learning_rate = 0.001
training_epochs = 300
batch_size = 100
display_step = 1

# Network Parameters

hidden_list = [256, 256, n_classes]
activ_functions = [tf.nn.relu]*(len(hidden_list)-1) + [tf.identity]
regularizers = [None]*len(hidden_list)
#regularizers = [tf.nn.l2_loss]*len(hidden_list)
dropouts = [0.5,0.5] + [None]
beta = 0

# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])

reg_cost = 0
reg_loss = 0

nb_hidden = len(hidden_list)
z = x
for layer in range(nb_hidden):
    z, reg_loss = fc_layer(z,hidden_list[layer],activ_functions[layer],regularizers[layer])
    reg_cost += reg_loss
    if dropouts[layer] is not None:
        z = tf.nn.dropout(z, dropouts[layer])

out = tf.nn.softmax_cross_entropy_with_logits(logits=z,labels=y)
cost = tf.reduce_mean(out + beta*reg_cost)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost))
    print("Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(z, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wangzhe.ui;

import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import org.apache.log4j.Logger;

/**
 *
 * @author ocq
 */
public class Util {

    private static Logger log = Logger.getLogger(Util.class.getName());

    public static Parent getParent(String fxmlUrl) {
        Parent parent = null;
        try {
            parent = FXMLLoader.load(Util.class.getResource(fxmlUrl));
        } catch (IOException ex) {
            log.error(ex);
        }
        return parent;
    }
}


text:
namespace EntertainmentSystem.Web.Areas.Media.Controllers
{
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using Common.Constants;
    using Infrastructure.Mapping;
    using Services.Contracts.Media.Fetchers;
    using ViewModels;
    using ViewModels.Contracts;
    using Web.Controllers;

    [Authorize]
    public abstract class MediaController : BaseController
    {
        protected IMediaPageViewModel<T> GetMediaFilesPage<T>(
            IBaseMediaFetcherService service,
            int page,
            string search,
            string collectionName,
            string categoryName)
            where T : MediaBaseViewModel
        {
            var files = service.GetAll(search, collectionName, categoryName);

            int pagesToSkip = (page - 1) * GlobalConstants.MediaFilesPerPage;

            int totalpages = (int)Math.Ceiling(files.Count() / (decimal)GlobalConstants.MediaFilesPerPage);

            var filesPage = files
                .Skip(pagesToSkip)
                .Take(GlobalConstants.MediaFilesPerPage)
                .To<T>()
                .ToList();

            var newViewModel = new MediaPageViewModel<T>
            {
                MediaFiles = filesPage,
                CurrentPage = page,
                TotalPages = totalpages,
                Search = search,
                FilterByCollection = collectionName,
                FilterByCategory = categoryName
            };

            return newViewModel;
        }
    }
}


text:
set -e

# TODO: keep files in a temp directory

# Make a graph
vg construct -r test/x.fa > x-flat.vg
vg index -x x-flat.xg -g x-flat.gcsa -k 16 x-flat.vg

# Make a file of characteristic indel sequences, with no SNPs
true > indel_seqs.txt
for SEQ_NUM in {1..10}; do
    # Create a seeded sequence
    SEQ=$(vg sim -n 1 -l 100 -x x-flat.xg -e 0.00 -i 0 -f -s "${SEQ_NUM}")
    if [ "${SEQ_NUM}" -lt 5 ]; then
        # Cut out the middle to make it a deletion
        echo "${SEQ:0:30}${SEQ:70:30}" >> indel_seqs.txt
    else
        # Insert something to make it an insertion
        INSERT_SEQ=$(vg sim -n 1 -l 50 -x x-flat.xg -e 0.00 -i 0 -f -s "${SEQ_NUM}00")
        echo "${SEQ:0:50}${INSERT_SEQ}${SEQ:50:50}" >> indel_seqs.txt
    fi
done

# Map them, making sure to stamp down the ends hard
vg map -x x-flat.xg -g x-flat.gcsa --reads indel_seqs.txt --full-l-bonus 100 -t 1 > svs.gam

# Make a new reference graph
vg mod -i svs.gam x-flat.vg | vg mod --unchop - > reference.vg
vg index -x reference.xg -g reference.gcsa -k 16 reference.vg

# Find its ends
LEFT_ID=$(vg find -x reference.xg -p x:1 | vg view -j - 2>/dev/null | jq '.node[].id')
RIGHT_ID=$(vg find -x reference.xg -p x:1000 | vg view -j - 2>/dev/null | jq '.node[].id')

vg view -dp reference.vg | dot -Tsvg -o test.svg

# Simulate a haplotype pair that touches both end nodes
vg sim -n 1000 -l 1000 -x reference.xg -s 100 -e 0 -i 0 -J | grep "node_id.: ${LEFT_ID}}" | grep "node_id.: ${RIGHT_ID}}" | head -n2 | vg view -JGa - > haplotype.gam

# Plot it (we have some nice overlaps and nesting)
vg view -dp reference.vg -A haplotype.gam | dot -Tsvg -o test.svg

# Decide what variants it has, duplicating it out to ensure calls
cat haplotype.gam haplotype.gam haplotype.gam haplotype.gam haplotype.gam | vg pileup reference.vg - > haplotype.vgpu

# And make it a graph
vg view -aj haplotype.gam | jq -r '">" + .name, .sequence' > haplotype.fa
vg construct -r haplotype.fa > haplotype.vg
vg index -x haplotype.xg haplotype.vg

for READ_LENGTH in 50 40 30 20 10; do
    # Go down in read length until there's a difference

    # Simulate some sample reads from it
    # 100 * 60 / 1000 = 6x coverage ish
    # 1000 * 60 / 1000 = 60x coverage ish
    DESIRED_COVERAGE=60
    REF_LENGTH=1000

    READ_COUNT=$(($DESIRED_COVERAGE * $REF_LENGTH / $READ_LENGTH))
    echo "Making ${READ_COUNT} reads..."
    vg sim -n ${READ_COUNT} -l ${READ_LENGTH} -x haplotype.xg -e 0.00 -i 0.00 -s 9999 > reads.txt

    # Map them
    vg map -x reference.xg -g reference.gcsa --reads reads.txt > reads.gam
    vg pileup reference.vg reads.gam > reads.vgpu

    #vg view -d reference.vg -A reads.gam | dot -Tsvg -o test.svg

    vg call reference.vg haplotype.vgpu | grep -v "0/0" | grep -v "#" | sort -n -k2 | cut -f1,2,10 | cut -f1 -d':' | sed s_1/0_0/1_g > truth.tsv
    vg call reference.vg reads.vgpu | grep -v "0/0" | grep -v "#" | sort -n -k2 | cut -f1,2,10 | cut -f1 -d':' | sed s_1/0_0/1_g > calls.tsv

    echo "Differences at read length ${READ_LENGTH}:"
    # Get diff for calls based off truth.
    # Diff returns 1 if there's a difference.
    diff calls.tsv truth.tsv
done


text:
{% extends 'layout.html' %}

{% block body %}

Articles

        {% for article in articles %}

            {% if request.cookies.get('language') == 'en' %}

{{ article.title }}

            {% else %}

{{ article.title_uk }}

            {% endif %}
        {% endfor %}

{% endblock %}


text:
// $Date: 2013-11-28 03:36:46 +0400 (Чт., 28 нояб. 2013) $
// $Revision: 844 $

#ifndef __signature_parser_h__
#define __signature_parser_h__

#include <stdint.h>

class ParserState
{
public:
  enum parts
  {
      pInitial
    , pSignature
    , pTemplateName
    , pTemplateValue
    , pTemplates
  };

  parts part;
  ParserState();

  static const char *parse(ParserState &, const char *&);
};

#endif //__signature_parser_h__


text:
using System;

namespace SharpVk.Interop.NVidia
{
    /// <summary>
    ///
    /// </summary>
    public unsafe delegate SharpVk.Result VkDeviceCreateRayTracingPipelinesDelegate(SharpVk.Interop.Device device, SharpVk.Interop.PipelineCache pipelineCache, uint createInfoCount, SharpVk.Interop.NVidia.RayTracingPipelineCreateInfo* createInfos, SharpVk.Interop.AllocationCallbacks* allocator, SharpVk.Interop.Pipeline* pipelines);
}


text:
#region

using System;
using System.Linq;
using System.Web.Mvc;
using MvcPaging;
using SocialNetwork.Core.Models;
using SocialNetwork.Web.Mappers;
using SocialNetwork.Web.ViewModels;

#endregion

namespace SocialNetwork.Web.Areas.admin.Controllers
{
    public class UsersController : BaseController
    {
        /// <summary>
        /// Главная страница с отображением списка пользователей
        /// </summary>
        /// <param name="page">Номер страницы</param>
        /// <param name="act">Категория пользователей (все, активные, заблокированные)</param>
        public ActionResult Index(int? page, string act = "")
        {
            var currentPageIndex = page.HasValue ? page.Value - 1 : 0;

            var mapper = DependencyResolver.Current.GetService<IMapper>();
            var users = UserRepository.GetAll();

            switch (act)
            {
                case "blocked":
                    users = users.Where(item => item.IsBlocked);
                    break;
                case "active":
                    users = users.Where(item => !item.IsBlocked);
                    break;
            }

            var usersViewModels = users.Select(
                item => (UserViewModel) mapper.Map(item, typeof (User), typeof (UserViewModel)))
                .ToPagedList(currentPageIndex, DefaultPageSize);

            ViewBag.CountAllUsers = UserRepository.GetAll().Count();
            ViewBag.CountActiveUsers = UserRepository.GetAll().Count(item=>!item.IsBlocked);
            ViewBag.CountBlockedUsers = UserRepository.GetAll().Count(item => item.IsBlocked);

            return View(usersViewModels);
        }

        /// <summary>
        /// Заблокировать/разблокировать пользователя
        /// </summary>
        /// <param name="id">ID пользователя</param>
        public ActionResult Block(int? id)
        {
            if (id != null && CurrentUser.Id != id) UserRepository.Block((int) id);
            if (Request.UrlReferrer != null) return Redirect(Request.UrlReferrer.PathAndQuery);
            return RedirectToAction("Index", "Users");
        }

        /// <summary>
        /// Удалить пользователя
        /// </summary>
        /// <param name="id">ID пользователя</param>
        public ActionResult Delete(int? id)
        {
            if (id != null && CurrentUser.Id != id) UserRepository.Delete((int)id);
            if (Request.UrlReferrer != null) return Redirect(Request.UrlReferrer.PathAndQuery);
            return RedirectToAction("Index", "Users");
        }
    }
}


text:
package com.googlecode.bpmn_simulator.test.visualisation;

import static org.junit.Assert.*;

import java.awt.Component;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Arrays;

import javax.imageio.ImageIO;

public final class Assert {

	private static final int[] EQUAL_PIXEL = { 0 };
	private static final int[] UNEQUAL_PIXEL = { 1 };

	private Assert() {
	}

	private static BufferedImage loadImage(final File file) {
		final BufferedImage image;
		try {
			image = ImageIO.read(file);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		if (image == null) {
			throw new RuntimeException("no applicable ImageReader registered");
		}
		return image;
	}

	private static void storeImage(final File file, final RenderedImage image) {
		try {
			ImageIO.write(image, "png", file);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	private static BufferedImage createImage(final int type, final Component component) {
		final BufferedImage image = new BufferedImage(component.getWidth(), component.getHeight(), type);
		component.printAll(image.getGraphics());
		return image;
	}

	private static void compareRaster(final Raster expected, final Raster actual) {
		final int width = expected.getWidth();
		final int height = expected.getHeight();
		assertEquals("different width", width, actual.getWidth());
		assertEquals("different height", height, actual.getHeight());
		final int[] expectedPixel = new int[expected.getNumDataElements()];
		final int[] actualPixel = new int[actual.getNumDataElements()];
		final BufferedImage diffImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
		final WritableRaster diffRaster = diffImage.getRaster();
		int diffCount = 0;
		for (int y = 0; y < height; ++y) {
			for (int x = 0; x < width; ++x) {
				if (!Arrays.equals(expected.getPixel(x, y, expectedPixel),
						expected.getPixel(x, y, actualPixel))) {
					diffRaster.setPixel(x, y, EQUAL_PIXEL);
				} else {
					diffRaster.setPixel(x, y, UNEQUAL_PIXEL);
				}
			}
		}
		storeImage(new File("diff.png"), diffImage);
		if (diffCount > 0) {
			final int sumCount = width * height;
			fail(MessageFormat.format("{0} from {1} pixels differ ({2,percent})", diffCount, sumCount, (100. / sumCount) * diffCount));
		}
	}

	private static void compareImages(final RenderedImage expected, final RenderedImage actual) {
		compareRaster(expected.getData(), actual.getData());
	}

	public static void assertEqualImages(final File expected, final Component actual) {
		final BufferedImage expectedImage = loadImage(expected);
		final BufferedImage actualImage = createImage(expectedImage.getType(), actual);
		compareImages(expectedImage, actualImage);
	}

}


text:
inline auto & DataForChunk(const cChunk & a_Chunk)
{
	return *static_cast<cIncrementalRedstoneSimulatorChunkData *>(a_Chunk.GetRedstoneSimulatorData());
}

template <typename... ArrayTypes>
inline void UpdateAdjustedRelative(const cChunk & From, const cChunk & To, const Vector3i Position, const Vector3i Offset)
{
	DataForChunk(To).WakeUp(cIncrementalRedstoneSimulatorChunkData::RebaseRelativePosition(From, To, Position + Offset));

	for (const auto & LinkedOffset : cSimulator::GetLinkedOffsets(Offset))
	{
		DataForChunk(To).WakeUp(cIncrementalRedstoneSimulatorChunkData::RebaseRelativePosition(From, To, Position + LinkedOffset));
	}
}

template <typename ArrayType>
inline void UpdateAdjustedRelatives(const cChunk & From, const cChunk & To, const Vector3i Position, const ArrayType & Relative)
{
	for (const auto & Offset : Relative)
	{
		UpdateAdjustedRelative(From, To, Position, Offset);
	}
}

template <typename ArrayType>
inline void InvokeForAdjustedRelatives(ForEachSourceCallback & Callback, const Vector3i Position, const ArrayType & Relative)
{
	for (const auto & Offset : Relative)
	{
		Callback(Position + Offset);
	}
}

inline constexpr Vector3i OffsetYP{ 0, 1, 0 };

inline constexpr Vector3i OffsetYM{ 0, -1, 0 };

inline constexpr std::array<Vector3i, 6> RelativeAdjacents
{
	{
		{ 1, 0, 0 },
		{ -1, 0, 0 },
		{ 0, 1, 0 },
		{ 0, -1, 0 },
		{ 0, 0, 1 },
		{ 0, 0, -1 },
	}
};

inline constexpr std::array<Vector3i, 4> RelativeLaterals
{
	{
		{ 1, 0, 0 },
		{ -1, 0, 0 },
		{ 0, 0, 1 },
		{ 0, 0, -1 },
	}
};


text:
title:  "NY FOTOTRA IAINGAN'NY TENY"
date:   01/05/2022
---

### Saintsaino

Ivereno ny andalan-teny nosoratanao ary diniho izany,

Farito ireo teny, na andian-teny, na fehézanteny, na hevitra miverimberina. Asio tsipika eny ambanin'ireo teny na fehezanteny manan-danja na manana heviny manokana ho anao.

Mamplasa →→ hampifandraisana ireo teny na fehezanteny mifandraika amin'ny teny na fehezanteny hafa.

`Inona ny fomba fijery manokana asongadin'ny naoty noraisinao ankapobeny?`

Ianaro tsianjery ny andininy tianao indrindra ao amin'ny Jak. 3:1-12. Soraty imbetsaka izany mba hahamora ny fitadidianao azy.

`Oviana ny fotoana farany nilazanao tamim-pahitsiana izay tao am-ponao?`

`Oviana ny fotoana nitenenan'ny olona iray zavatra manan-danja tokoa ho anao?`

Mariky ny fahamatorana kristianina izay mihamitombo ny toetra tsy tafintohina amin'ny teny (Jak. 3:2). Porofon'ny fanoloran-tena lalin'ny olona iray ho amin'ny fanovana ataon'i Kristy izany. Asehon'ny tenin'ny olona izany satria "amin'ny haben'ny ao am-pony no itenenan'ny vavany"- Lio. 6:45. Nambaran'i Jesôsy ihany koa fa izay mivoaka ny vava no maloto satria "izay mivoaka avy amin'ny vava (...) dia avy amin'ny fo-Mat. 15:18.

Na dia kely aza ny lela dia misy fiantraikany lehibe ny asany. Mety hampiorina sy hampahery ny olona ny teny feno halemem-panahy, izay raisiny toy ny loharano mamelombelona sy toho-tantely ho an'ny fanahy (Ohab. 16:24; 18:4). Mifanohitra amin'izany, mety hahatezitra na koa hiteraka ratram po lalina ao amin'ny olona iray ny teny tsy araka ny tokony ho izy, indrindra rehefa atao anatin'ny firehetan'ny fahatezerana (Ohab. 12:18; 15:18).

Mahaliana fa ny sasany tamin'ireo fananarana mafy indrindra nataon'i Jesôsy tamin'ireo mpianany dia vokatry ny teny nambaran'izy ireo. Rehefa niezaka nandresy lahatra an'i Jesôsy tsy hankeny amin'ny hazo fijaliana i Petera dia nahazo valinteny tahaka izao: "Mankanesa ato ivohoko, ry Satana; fahatafintohinana amiko hianao, satria tsy misaina izay an'Andriamanitra hianao, fa izay an'ny olona." - Mat. 16:23. Hitan'i Jesôsy mazava ny fototry ny olana: tsy nisaina na koa nametraka ho lohalaharana izay laharaham-pahamehana i Petera ka nahatonga azy hanao izany teny izany.

Taloha kelin'izany, rehefa tsy nanaiky handray an'i Jesôsy ireo mponina tao amin'ny tanàna iray an'ny Samaritana dia nanoso-kevitra ny hampidinana afo avy any an-danitra handevona azy ireo i Jakoba sy i Jaona. Niteny mafy azy ireo i Jesôsy ka nanao hoe: "Tsy fantatrareo ny toetry ny fanahy izay anareo" - Lio. 9:55. Hita taratra teo amin'ny tenin'izy ireo indray ny olana: fanahy ratsy no nandrisika azy.

Tsy misy paikady atoron'i Jakoba mba hialana amin'izany olana izany. Indrisy fa fehin-kevitra izao aza no ataony: "fa tsy misy olona mahafolaka ny lela" - Jak. 3:8. Tsy hain'ny olombelona, tahaka ny tsy hahaizany manova ny fony, ny hanova ny teny nataony. Andriamanitra irery no afaka manao fanovana ambonin'ny herin'olombelona tahaka izany.

` `


text:
import os
import sys
import time
import string

import gtk
import wnck
from PIL import Image
from pykeyboard import PyKeyboard

from cookbot.colorops import rgb_to_hsv, rgb_delta, delta_hist, delta_chi_square
from cookbot.ocr import OCR

if sys.platform.startswith('linux'):
    import ctypes

ROSTER_OUTLINES = [(248, 72 + i*60, 249, 72 + i*60 + 56) for i in xrange(8)]

ROSTER_LABELS = [(70, 77 + i*60, 207, 77 + i*60 + 46) for i in xrange(8)]

RECIPE_TITLE = (276, 560, 880, 604)

RECIPE_TEXT = (276, 604, 1027, 670)

TICKET_NO = (912, 576, 1009, 599)

CANARY_PX = (66, 679)

ROSTER = [(24, 90),
          (24, 164),
          (24, 216),
          (24, 285),
          (24, 324),
          (24, 398),
          (24, 461),
          (24, 516),
          ]

def _getcolors(im, color):
    n = im.size[0] * im.size[1]
    return {k:v for (v, k) in im.getcolors(n)}.get(color, 0)

def yellow(im):
    return _getcolors(im, (255, 242, 0))

class BaseWindow(object):
    def __init__(self, db, **opts):
        self.db = db
        self._opts = opts

        self._window = None
        self._img = None

        self._title = None
        self._text = None
        self._ticket_no = None
        self._orders = None

        self.k = PyKeyboard()
        self.ocr = OCR(db, **opts)

    def get_window(self):
        raise NotImplementedError

    def focus(self):
        raise NotImplementedError

    def grab(self, *args):
        raise NotImplementedError

    def capture(self, bbox=None):
        x, y, w, h = self.get_coords()

        img = self.grab(x, y, w, h)

        if bbox:
            img = img.crop(bbox)

        return img

    def __getattr__(self, attr):
        if attr.startswith('_'):
            raise AttributeError(attr)

        # maybe this is too much magic?
        value = getattr(self, '_' + attr)

        if value is None:
            value = getattr(self, 'get_' + attr)()
            setattr(self, '_' + attr, value)

        return value

    def refresh(self, img=None):
        t = time.time()

        self._img = img or self.capture()

        self._title = None
        self._text = None
        self._orders = None
        self._ticket_no = None
        self._active = None

    def get_title(self):
        # returns the recipe title
        return self.ocr(self._img.crop(RECIPE_TITLE), mode='line',
                        whitelist=string.letters + './()"-&')

    def get_text(self):
        # returns the recipe text
        return self.ocr(self._img.crop(RECIPE_TEXT), mode='text',
                        whitelist=string.letters + string.digits + ',./!?()')

    def get_ticket_no(self):
        # returns the number of the ticket, or None
        try:
            return int(self.ocr(self._img.crop(TICKET_NO), mode='word',
                                whitelist=string.digits,
                                contrast=True))
        except ValueError:
            return None

    def get_orders(self):
        # returns the complete status for each slot
        n = range(1, 9)
        roster = self.get_roster()
        outlines, x_factor = self.get_outlines(roster)

        return zip(n, roster, outlines, x_factor)

    def get_outlines(self, roster=None):
        # returns the actual state for each slot, and how far they
        # receded to the left
        if roster is None:
            roster = [True] * 8

        outlines = []
        x_factor = []

        for i, v in enumerate(roster):
            if not v:
                outlines.append(None)
                x_factor.append(None)
                continue

            bbox = ROSTER_OUTLINES[i]
            x1, y1, x2, y2 = bbox

            out = _identify_outline(self._img.crop(bbox))

            if out is not None:
                outlines.append(out)
                x_factor.append(x2)
                continue

            while x1 > 60:
                x1 -= 1
                x2 -= 1

                out = _identify_outline(self._img.crop((x1, y1, x2, y2)))

                if out is not None:
                    outlines.append(out)
                    x_factor.append(x2)
                    break

            else:
                outlines.append(None)
                x_factor.append(None)

        assert len(outlines) == 8
        assert len(x_factor) == 8

        return outlines, x_factor

    def get_roster(self):
        # returns the state for each slot, if highlighted or not
        roster = [rgb_delta(self._img.getpixel(b), (255, 255, 255)) < 1 for b in ROSTER]
        assert len(roster) == 8
        return roster

    @property
    def canary(self):
        # this is a 'canary' pixel that should be immutable during normal
        # gameplay. This is used to avoid doing something wrong during
        # the screen flashes, like Rush Hour.
        return self._img.getpixel(CANARY_PX)

    def at_kitchen(self):
        # true if at the kitchen preparation screen
        return self._img.getpixel((840, 164)) == (37, 44, 139)

    def at_grill(self):
        # true if at the grill/boiler screen
        p = self._img.getpixel((394, 283))
        return p in {(134, 134, 132), (106, 106, 104), (95, 94, 100), (85, 83, 89)}

    def key(self, k, d=0.1):
        self.k.press_key(k)
        time.sleep(self._opts['key_delay'])
        self.k.release_key(k)
        time.sleep(self._opts['key_delay'])

    def escape(self):
        # used to pause the game on bot errors
        self.key(self.k.escape_key)

    def change_recipe(self):
        # for testing recipes. Change to the next recipe.
        self.key(self.k.control_key)
        time.sleep(self._opts['loop_delay'])

    def order_ok(self):
        # for testing recipes. Check if the order was successul.
        SMILEY_BBOX = (61, 72, 221, 128)
        return max([yellow(self.capture(SMILEY_BBOX)) for x in xrange(20)]) > 800

    def save_label(self, n):
        bbox = ROSTER_LABELS[n-1]

        im = self._img.crop(bbox)

        im.save('img_%s_%s.bmp' % (int(time.time()), n))

    def id_label(self, n):
        bbox = ROSTER_LABELS[n-1]

        hb = self._img.crop(bbox).histogram()

        final = min([(name, delta_chi_square(ha, hb)) for (name, ha) in self._refs.iteritems()], key=lambda x: x[1])

        if final[1] < 1000:
            return final[0]

        return None

def _identify_outline(im):
    t = im.size[0] * im.size[1]

    colors = im.getcolors(t)

    n, c = max(colors, key=lambda x: x[0])

    f = n/float(t)

    if f < 0.8:
        return None

    if rgb_delta(c, (0, 0, 0)) < 1:
        return 'new'

    if rgb_delta(c, (79, 79, 79)) < 1:
        return 'active'

    if rgb_delta(c, (114, 114, 114)) < 1:
        return 'cooking'

    if rgb_delta(c, (190, 0, 0)) < 1:
        return 'burning'

    if rgb_delta(c, (255, 255, 64)) < 1:
        return 'ready'

    if rgb_delta(c, (106, 255, 255)) < 1:
        return 'waiting'

    h, s, v = rgb_to_hsv(*c)

    if h == 0.5 and s == 0 and v > 100:
        return 'waiting'

    if h == 1/6.0 and s == 0 and v > 100:
        return 'ready'

    #raise RuntimeError("Cannot identify outline")

class GTKWindow(BaseWindow):

    _libpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_grabber.so')
    _grabber = ctypes.CDLL(_libpath)

    def grab(self, x, y, w, h):
        size = w * h
        objlength = size * 3

        self._grabber.get_screen.argtypes = []
        result = (ctypes.c_ubyte*objlength)()

        self._grabber.get_screen(x, y, w, h, result)
        return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)

    def focus(self):
        self.window.activate(int(time.time()))

    def get_window(self):
        screen = wnck.screen_get_default()

        # flush gtk events
        while gtk.events_pending():
            gtk.main_iteration()

        # find the game window
        for window in screen.get_windows():
            if window.get_name() == 'CookServeDelicious':
                return window

        raise RuntimeError("Can't find game window")

    def get_coords(self):
        x, y, w, h = self.window.get_geometry()

        # remove the title bar
        h -= 28
        y += 28

        return x, y, w, h

if sys.platform.startswith('linux'):
    GameWindow = GTKWindow

else:
    raise NotImplementedError("Platform not supported: %s" % sys.platform)

if __name__ == '__main__':
    win = GameWindow()

    while 1:
        win.refresh()
        win.get_outlines()


text:
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;

namespace Plainion.Windows.Controls.Text.AutoCorrection
{
    /// <summary>
    /// Converts URLs into clickable hyperlinks
    /// </summary>
    /// <remarks>
    /// Initial verison inspired by:
    /// http://blogs.msdn.com/b/prajakta/archive/2006/10/17/autp-detecting-hyperlinks-in-richtextbox-part-i.aspx
    /// http://blogs.msdn.com/b/prajakta/archive/2006/11/28/auto-detecting-hyperlinks-in-richtextbox-part-ii.aspx
    /// </remarks>
    public class ClickableHyperlink : IAutoCorrection
    {
        public AutoCorrectionResult TryApply(AutoCorrectionInput input)
        {
            bool success = false;

            foreach (var wordRange in input.Context.GetWords())
            {
                string wordText = wordRange.TextOnly();
                var url = TryCreateUrl(wordText);
                if (url != null && !IsInHyperlinkScope(wordRange.Start) && !IsInHyperlinkScope(wordRange.End))
                {
                    var hyperlink = new Hyperlink(wordRange.Start, wordRange.End);
                    hyperlink.NavigateUri = url;
                    WeakEventManager<Hyperlink, RequestNavigateEventArgs>.AddHandler(hyperlink, "RequestNavigate", OnHyperlinkRequestNavigate);

                    success = true;
                }
            }

            return new AutoCorrectionResult(success);
        }

        private static bool IsInHyperlinkScope(TextPointer position)
        {
            return GetHyperlinkAncestor(position) != null;
        }

        private static Hyperlink GetHyperlinkAncestor(TextPointer position)
        {
            var parent = position.Parent as Inline;
            while (parent != null && !(parent is Hyperlink))
            {
                parent = parent.Parent as Inline;
            }

            return parent as Hyperlink;
        }

        private static void OnHyperlinkRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.AbsoluteUri);
            e.Handled = true;
        }

        private static Uri TryCreateUrl(string wordText)
        {
            try
            {
                if (wordText.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
                    wordText.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ||
                    wordText.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
                {
                    return new Uri(wordText);
                }

                if (wordText.StartsWith("www.", StringComparison.OrdinalIgnoreCase))
                {
                    return new Uri("http://" + wordText);
                }

                return null;
            }
            catch
            {
                return null;
            }
        }

        public AutoCorrectionResult TryUndo(TextPointer start)
        {
            var hyperlink = start.Parent as Hyperlink;
            if (hyperlink == null)
            {
                var para = start.Parent as Paragraph;
                if (para != null)
                {
                    hyperlink = para.Inlines.OfType<Hyperlink>().SingleOrDefault();
                }

                if (hyperlink == null)
                {
                    return new AutoCorrectionResult(false);
                }
            }

            // Deleting the hyperlink is done using logic below.

            // 1. Copy its children Inline to a temporary array.
            var hyperlinkChildren = hyperlink.Inlines;
            var inlines = new Inline[hyperlinkChildren.Count];
            hyperlinkChildren.CopyTo(inlines, 0);

            // 2. Remove each child from parent hyperlink element and insert it after the hyperlink.
            for (int i = inlines.Length - 1; i >= 0; i--)
            {
                hyperlinkChildren.Remove(inlines[i]);
                hyperlink.SiblingInlines.InsertAfter(hyperlink, inlines[i]);
            }

            // 3. Apply hyperlink's local formatting properties to inlines (which are now outside hyperlink scope).
            var localProperties = hyperlink.GetLocalValueEnumerator();
            var inlineRange = new TextRange(inlines[0].ContentStart, inlines[inlines.Length - 1].ContentEnd);

            while (localProperties.MoveNext())
            {
                var property = localProperties.Current;
                var dp = property.Property;
                object value = property.Value;

                if (!dp.ReadOnly &&
                    dp != Inline.TextDecorationsProperty && // Ignore hyperlink defaults.
                    dp != TextElement.ForegroundProperty &&
                    dp != BaseUriHelper.BaseUriProperty &&
                    !IsHyperlinkProperty(dp))
                {
                    inlineRange.ApplyPropertyValue(dp, value);
                }
            }

            // 4. Delete the (empty) hyperlink element.
            hyperlink.SiblingInlines.Remove(hyperlink);

            return new AutoCorrectionResult(true);
        }

        private static bool IsHyperlinkProperty(DependencyProperty dp)
        {
            return dp == Hyperlink.CommandProperty ||
                dp == Hyperlink.CommandParameterProperty ||
                dp == Hyperlink.CommandTargetProperty ||
                dp == Hyperlink.NavigateUriProperty ||
                dp == Hyperlink.TargetNameProperty;
        }
    }
}


text:
package org.javalite.async;

import com.google.inject.Inject;
import org.javalite.async.services.GreetingService;

/**
 * @author Igor Polevoy on 4/5/15.
 */
public class HelloInjectedCommand extends Command {

    @Inject
    private GreetingService greetingService;

    public static String result;

    private String message;

    public HelloInjectedCommand(String message) {
        this.message = message;
    }

    public HelloInjectedCommand() {} // have to have a default constructor

    @Override
    public String toString() {
        return message;
    }

    @Override
    public void execute() {
        result = message + greetingService.getGreeting();
    }
}


text:
<?php

namespace Test\Integration\Version3x2;

include_once(__DIR__. '/../Version3x0/PubSubCommandsTest.php');

class PubSubCommandsTest extends \Test\Integration\Version3x0\PubSubCommandsTest {

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/dialogflow/v2beta1/context.proto

package com.google.cloud.dialogflow.v2beta1;

public interface ListContextsRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.dialogflow.v2beta1.ListContextsRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. The session to list all contexts from.
   * Format: `projects/<Project ID>/agent/sessions/<Session ID>` or
   * `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
   * ID>/sessions/<Session ID>`. If `Environment ID` is not specified, we assume
   * default 'draft' environment. If `User ID` is not specified, we assume
   * default '-' user.
   *

   *
   * string parent = 1;
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. The session to list all contexts from.
   * Format: `projects/<Project ID>/agent/sessions/<Session ID>` or
   * `projects/<Project ID>/agent/environments/<Environment ID>/users/<User
   * ID>/sessions/<Session ID>`. If `Environment ID` is not specified, we assume
   * default 'draft' environment. If `User ID` is not specified, we assume
   * default '-' user.
   *

   *
   * string parent = 1;
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Optional. The maximum number of items to return in a single page. By
   * default 100 and at most 1000.
   *

   *
   * int32 page_size = 2;
   */
  int getPageSize();

  /**
   *
   *
   *

   * Optional. The next_page_token value returned from a previous list request.
   *

   *
   * string page_token = 3;
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * Optional. The next_page_token value returned from a previous list request.
   *

   *
   * string page_token = 3;
   */
  com.google.protobuf.ByteString getPageTokenBytes();
}


text:
USE [estatio_dev]
/**
* Stored procedure creates column with default and removes default constraint
**/
CREATE PROCEDURE addColumn
(
    @table VARCHAR(255),
    @column VARCHAR(255),
    @type VARCHAR(255),
    @default VARCHAR(255)
)
AS
BEGIN
    IF NOT EXISTS(SELECT * FROM sys.columns
            WHERE [name] = @column AND [object_id] = OBJECT_ID(QUOTENAME(@table)))
    BEGIN
        DECLARE @addColumnCmd NVARCHAR(1000)
        SET @addColumnCmd = 'ALTER TABLE ['+ QUOTENAME(@table) + '] ADD ['+ QUOTENAME(@column) + '] ' + @type + ' NOT NULL DEFAULT ''' + @default + ''''
        EXEC sp_executesql @addColumnCmd

        DECLARE @dropDefaultCmd NVARCHAR(1000)
        SELECT
            @dropDefaultCmd = 'ALTER TABLE [' + @table + '] DROP CONSTRAINT ' + d.name
        FROM
            sys.tables t
            JOIN sys.default_constraints d ON d.parent_object_id = t.object_id
            JOIN sys.columns c ON c.object_id = t.object_id AND c.column_id = d.parent_column_id
        WHERE
            t.name = @table AND c.name = @column
        EXEC sp_executesql @dropDefaultCmd
    END
END
GO

/**
* Moves database to a different schema and renames it
**/
CREATE PROCEDURE moveRenameDb
(
	@FromSchema VARCHAR(255),
    @FromDb VARCHAR(255),
    @ToSchema VARCHAR(255),
    @ToDb VARCHAR(255)
)
AS
BEGIN
	DECLARE @NewName VARCHAR(255) = @ToSchema+'.'+@FromDb
	IF NOT EXISTS (
		SELECT  schema_name
		FROM    information_schema.schemata
		WHERE   schema_name = @ToSchema )
		BEGIN
			EXEC('CREATE SCHEMA '+@ToSchema)
		END
	EXEC('ALTER SCHEMA '+@ToSchema +' TRANSFER '+@FromSchema+'.'+@FromDb)
	EXEC sp_rename @NewName, @ToDb;
END
GO

/**
* Upgrade Application Tenancy
**/

ALTER TABLE [dbo].[IsisSecurityApplicationTenancy] DROP CONSTRAINT [IsisSecurityApplicationTenancy_PK]
ALTER TABLE [dbo].[IsisSecurityApplicationTenancy] ALTER COLUMN [path] VARCHAR(255) NOT NULL
ALTER TABLE [dbo].[IsisSecurityApplicationTenancy] ADD  CONSTRAINT [IsisSecurityApplicationTenancy_PK] PRIMARY KEY CLUSTERED
(
	[path] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 12) ON [PRIMARY]
GO
ALTER TABLE IsisSecurityApplicationTenancy ALTER COLUMN parentPath VARCHAR(255)
GO
ALTER TABLE IsisSecurityApplicationUser ALTER COLUMN tenancyId VARCHAR(255)
GO
EXEC sp_rename 'IsisSecurityApplicationUser.tenancyId', 'atPath', 'COLUMN';
GO

EXEC dbo.addColumn 'Brand', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Index', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Link', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Tax', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Charge', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Organisation', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Person', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Property', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'BankMandate', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Lease', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Invoice', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'LeaseItem', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'LeaseAssignment', 'atPath', 'VARCHAR(255)', '/ITA'
EXEC dbo.addColumn 'Tag', 'atPath', 'VARCHAR(255)', '/ITA'
GO

UPDATE lea SET atPath = '/ITA/' + LEFT(agr.reference,3)
    FROM Lease lea
    INNER JOIN Agreement agr ON lea.id = agr.id
GO

/**
* Move databases to new schemas
*/
EXEC dbo.moveRenameDb 'dbo','IsisAuditEntry','isisaudit','AuditEntry'
EXEC dbo.moveRenameDb 'dbo','IsisCommand','isiscommand', 'Command'
EXEC dbo.moveRenameDb 'dbo','IsisPublishedEvent', 'isispublishing', 'PublishedEvent'
EXEC dbo.moveRenameDb 'dbo','IsisSecurityApplicationPermission','isissecurity','ApplicationPermission'
EXEC dbo.moveRenameDb 'dbo','IsisSecurityApplicationRole','isissecurity','ApplicationRole'
EXEC dbo.moveRenameDb 'dbo','IsisSecurityApplicationTenancy','isissecurity','ApplicationTenancy'
EXEC dbo.moveRenameDb 'dbo','IsisSecurityApplicationUser','isissecurity','ApplicationUser'
EXEC dbo.moveRenameDb 'dbo','IsisSecurityApplicationUserRoles','isissecurity','ApplicationUserRoles'
EXEC dbo.moveRenameDb 'dbo','IsisUserSetting', 'isissettings','UserSetting'

/**
* Change from DATETIME2 TO DATE
**/
ALTER TABLE dbo.Agreement ALTER COLUMN endDate DATE
ALTER TABLE dbo.Agreement ALTER COLUMN startDate DATE
ALTER TABLE dbo.AgreementRole ALTER COLUMN endDate DATE
ALTER TABLE dbo.AgreementRole ALTER COLUMN startDate DATE
ALTER TABLE dbo.AgreementRoleCommunicationChannel ALTER COLUMN endDate DATE
ALTER TABLE dbo.AgreementRoleCommunicationChannel ALTER COLUMN startDate DATE
ALTER TABLE dbo.BreakOption ALTER COLUMN breakDate DATE NOT NULL
ALTER TABLE dbo.BreakOption ALTER COLUMN exerciseDate DATE NOT NULL
ALTER TABLE dbo.BreakOption ALTER COLUMN reminderDate DATE
ALTER TABLE dbo.Event ALTER COLUMN date DATE NOT NULL
ALTER TABLE dbo.FinancialAccountTransaction ALTER COLUMN transactionDate DATE NOT NULL
ALTER TABLE dbo.FixedAssetRegistration ALTER COLUMN startDate DATE
ALTER TABLE dbo.FixedAssetRegistration ALTER COLUMN endDate DATE
ALTER TABLE dbo.FixedAssetRole ALTER COLUMN endDate DATE
ALTER TABLE dbo.FixedAssetRole ALTER COLUMN startDate DATE
ALTER TABLE dbo.Guarantee ALTER COLUMN terminationDate DATE
ALTER TABLE dbo.IndexBase ALTER COLUMN startDate DATE NOT NULL
ALTER TABLE dbo.IndexValue ALTER COLUMN startDate DATE NOT NULL
ALTER TABLE dbo.Invoice ALTER COLUMN dueDate DATE NOT NULL
ALTER TABLE dbo.Invoice ALTER COLUMN invoiceDate DATE
ALTER TABLE dbo.InvoiceItem ALTER COLUMN dueDate DATE NOT NULL
ALTER TABLE dbo.InvoiceItem ALTER COLUMN effectiveEndDate DATE
ALTER TABLE dbo.InvoiceItem ALTER COLUMN effectiveStartDate DATE
ALTER TABLE dbo.InvoiceItem ALTER COLUMN endDate DATE
ALTER TABLE dbo.InvoiceItem ALTER COLUMN startDate DATE
ALTER TABLE dbo.Lease ALTER COLUMN tenancyEndDate DATE
ALTER TABLE dbo.Lease ALTER COLUMN tenancyStartDate DATE
ALTER TABLE dbo.LeaseAssignment ALTER COLUMN assignmentDate DATE NOT NULL
ALTER TABLE dbo.LeaseItem ALTER COLUMN endDate DATE
ALTER TABLE dbo.LeaseItem ALTER COLUMN epochDate DATE
ALTER TABLE dbo.LeaseItem ALTER COLUMN nextDueDate DATE
ALTER TABLE dbo.LeaseItem ALTER COLUMN startDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN endDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN startDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN paymentDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN registrationDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN baseIndexStartDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN effectiveDate DATE
ALTER TABLE dbo.LeaseTerm ALTER COLUMN nextIndexStartDate DATE
ALTER TABLE dbo.Occupancy ALTER COLUMN endDate DATE
ALTER TABLE dbo.Occupancy ALTER COLUMN startDate DATE
ALTER TABLE dbo.PartyRegistration ALTER COLUMN endDate DATE
ALTER TABLE dbo.PartyRegistration ALTER COLUMN startDate DATE
ALTER TABLE dbo.PartyRelationship ALTER COLUMN endDate DATE
ALTER TABLE dbo.PartyRelationship ALTER COLUMN startDate DATE
ALTER TABLE dbo.PaymentTerm ALTER COLUMN dueDate DATE NOT NULL
ALTER TABLE dbo.Property ALTER COLUMN acquireDate DATE
ALTER TABLE dbo.Property ALTER COLUMN disposalDate DATE
ALTER TABLE dbo.Property ALTER COLUMN openingDate DATE
ALTER TABLE dbo.TaxRate ALTER COLUMN endDate DATE
ALTER TABLE dbo.TaxRate ALTER COLUMN startDate DATE
ALTER TABLE dbo.Unit ALTER COLUMN endDate DATE
ALTER TABLE dbo.Unit ALTER COLUMN startDate DATE

/**
* Clean up unused tables
**/
DROP TABLE [dbo].[UserSetting]
GO
DROP TABLE [dbo].[Tag]
GO
DROP TABLE [dbo].[IsisSettingApplicationSetting]
GO
DROP TABLE [dbo].[PaymentTerm]
GO

/**
* Fix columns that have changed in the dom but were never upgraded
 */
ALTER TABLE LandRegister ALTER COLUMN rendita DECIMAL(19,2)
GO
ALTER TABLE FinancialAccountTransaction ALTER COLUMN financialAccountId BIGINT NOT NULL
GO
ALTER TABLE LeaseTerm DROP COLUMN taxable
GO

/**
* Drop all procedures
**/
DROP PROCEDURE dbo.addColumn
GO
DROP PROCEDURE dbo.moveRenameDb
GO


text:
"""
Simple demo of using Pandas to visualize time series data
"""

import pymysql
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#edit for your specific ODM database
conn = pymysql.connect(host='localhost', port=3306, user='root', \
        passwd='', db='LBRODM_small')
cursor = conn.cursor()

#hard coded to plot water temperature observations at SiteID = 2
sql_statement = "SELECT LocalDateTime, DataValue FROM DataValues \
        WHERE SiteID = 2 AND VariableID = 36 ORDER BY LocalDateTime"
cursor.execute(sql_statement)
rows =  cursor.fetchall()

localDateTimes, dataValues = zip(*rows)

ts = pd.Series(dataValues, index=localDateTimes)

fig, axes = plt.subplots(nrows=2, ncols=2)

#time series plot
ts.plot(ax=axes[0,0])
axes[0,0].set_title('Temperature at SiteID=2')

#weekly stats plot
ts.resample('W', how=['mean', np.min, np.max]).plot(ax=axes[0,1])
axes[0,1].set_title('Weekly Resample')

#montly stats plot
ts.resample('M', how=['mean', np.min, np.max]).plot(ax=axes[1,0])
axes[1,0].set_title('Monthly Resample')

#montly boxplot
df = pd.DataFrame(ts, columns=['tmp'])
df['mon'] = df.index.month
df.boxplot(column = 'tmp', by='mon', ax=axes[1,1])
axes[1,1].set_title('Monthly Boxplot')
fig = axes[1][1].get_figure()
fig.suptitle('')

plt.tight_layout()
plt.savefig('Class14_InClassDemoPandas.png')
plt.show()


text:
#include "worker.h"
#include "tools.h"

Worker::Worker()
{
    status = "Idle";
}

void Worker::setStatusString(const QString &string)
{
    status = string;
    emit statusStringChanged(status);
}

QString Worker::statusString() const
{
    return status;
}


text:
package ch.usi.dag.disl.exclusion;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import ch.usi.dag.disl.cbloader.ManifestHelper;
import ch.usi.dag.disl.cbloader.ManifestHelper.ManifestInfo;
import ch.usi.dag.disl.exception.ExclusionPrepareException;
import ch.usi.dag.disl.exception.ManifestInfoException;
import ch.usi.dag.disl.exception.ScopeParserException;
import ch.usi.dag.disl.scope.Scope;
import ch.usi.dag.disl.scope.ScopeImpl;
import ch.usi.dag.disl.util.Constants;

public abstract class ExclusionSet {

	private static final String PROP_EXCLIST = "disl.exclusionList";
	private static final String excListPath =
			System.getProperty(PROP_EXCLIST, null);

	private static final String JAR_PATH_BEGIN = "/";
	private static final String JAR_PATH_END = "!";

	private static final char JAR_ENTRY_DELIM = '/';
	private static final char CLASS_DELIM = '.';
	private static final String ALL_METHODS = ".*";

	public static Set<Scope> prepare() throws ScopeParserException,
			ManifestInfoException, ExclusionPrepareException {

		Set<Scope> exclSet = defaultExcludes();
		exclSet.addAll(instrumentationJar());
		exclSet.addAll(readExlusionList());

		return exclSet;
	}

	private static Set<Scope> defaultExcludes() throws ScopeParserException {

		// if appended to the package name (for scoping purposes),
		// excludes all methods in all classes in the package and sub-packages
		final String EXCLUDE_CLASSES = ".*.*";

		Set<Scope> exclSet = new HashSet<Scope>();

		// DiSL agent classes
		exclSet.add(new ScopeImpl(
				"ch.usi.dag.dislagent" + EXCLUDE_CLASSES));

		// dynamic bypass classes
		exclSet.add(new ScopeImpl(
				"ch.usi.dag.disl.dynamicbypass" + EXCLUDE_CLASSES));

		// DiSLRE classes
		exclSet.add(new ScopeImpl(
				"ch.usi.dag.dislre" + EXCLUDE_CLASSES));

		// java instrument classes could cause troubles if instrumented
		exclSet.add(new ScopeImpl(
				"sun.instrument" + EXCLUDE_CLASSES));

		// finalize method in java.lang.Object can cause problems
		exclSet.add(new ScopeImpl("java.lang.Object.finalize"));

		return exclSet;
	}

	private static Set<Scope> instrumentationJar()
			throws ManifestInfoException, ExclusionPrepareException,
			ScopeParserException {

		try {

			// add classes from instrumentation jar

			Set<Scope> exclSet = new HashSet<Scope>();

			// get DiSL manifest info
			ManifestInfo mi = ManifestHelper.getDiSLManifestInfo();

			// no manifest found
			if(mi == null) {
				return exclSet;
			}

			// get URL of the instrumentation jar manifest
			URL manifestURL =
					ManifestHelper.getDiSLManifestInfo().getResource();

			// manifest path contains "file:" + jar name + "!" + manifest path
			String manifestPath = manifestURL.getPath();

			// extract jar path
			int jarPathBegin = manifestPath.indexOf(JAR_PATH_BEGIN);
			int jarPathEnd = manifestPath.indexOf(JAR_PATH_END);
			String jarPath = manifestPath.substring(jarPathBegin, jarPathEnd);

			// open jar...
			JarFile jarFile = new JarFile(jarPath);

			// ... and iterate over items
			Enumeration<JarEntry> entries = jarFile.entries();
			while (entries.hasMoreElements()) {

				JarEntry entry = entries.nextElement();

				// get entry name
				String entryName = entry.getName();

				// add all classes to the exclusion list
				if (entryName.endsWith(Constants.CLASS_EXT)) {

					String className =
							entryName.replace(JAR_ENTRY_DELIM, CLASS_DELIM);

					// remove class ext
					int classNameEnd =
							className.lastIndexOf(Constants.CLASS_EXT);
					className = className.substring(0, classNameEnd);

					// add exclusion for all methods
					String classExcl = className + ALL_METHODS;

					exclSet.add(new ScopeImpl(classExcl));
				}
			}

			jarFile.close();

			return exclSet;

		} catch(IOException e) {
			throw new ExclusionPrepareException(e);
		}
	}

	private static Set<Scope> readExlusionList()
			throws ExclusionPrepareException, ScopeParserException {

		final String COMMENT_START = "#";

		try {

			Set<Scope> exclSet = new HashSet<Scope>();

			// if exclusion list path exits
			if(excListPath != null) {

				// read exclusion list line by line
				Scanner scanner = new Scanner(new FileInputStream(excListPath));
				while (scanner.hasNextLine()) {

					String line = scanner.nextLine();

					if(! line.startsWith(COMMENT_START)) {
						exclSet.add(new ScopeImpl(line));
					}
				}

				scanner.close();
			}

			return exclSet;

		} catch(FileNotFoundException e) {
			throw new ExclusionPrepareException(e);
		}
	}
}


text:
/* Write a program that enters from the console a positive integer n and prints all the numbers from 1 to N inclusive, on a single line, separated by a whitespace. */

using System;

class NumbersFromOneToN
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());

        for (int i = 1; i <= n; i++)
        {
            Console.Write("{0} ", i);
        }

        Console.WriteLine();
    }
}


text:
package cern.enice.jira.amh.logback;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cern.enice.jira.amh.api.LogProvider;

public class LogbackLogProvider implements LogProvider {

	private Logger logger = LoggerFactory.getLogger(getClass().getName());
	private ObjectMapper objectMapper = new ObjectMapper();

	public void start() {
		log(LogProvider.INFO, "Logback Log Provider service is started.");
	}

	public void stop() {
		log(LogProvider.INFO, "Logback Log Provider service is stopped.");
	}

	@Override
	public void log(int level, String message) {
		log(level, message, null, null);
	}

	@Override
	public void log(int level, String message, Throwable exception) {
		log(level, message, null, exception);
	}

	@Override
	public void log(int level, String message, Object object) {
		log(level, message, object, null);
	}

	@Override
	public void log(int level, String message, Object object, Throwable exception) {
		if (level == LogProvider.ERROR) {
			logger.error(message, exception);
		} else if (level == LogProvider.WARNING) {
			logger.warn(message, exception);
		} else if (level == LogProvider.INFO) {
			logger.info(message, exception);
		} else if (level == LogProvider.DEBUG) {
			logger.debug(message, exception);
		}
		logObjectAsString(level, object);
	}

	private void logObjectAsString(int level, Object object) {
		if (object == null) return;
		try {
			String objectAsString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
			if (objectAsString == null) return;
			switch (level) {
				case ERROR: logger.error(objectAsString); break;
				case WARNING: logger.warn(objectAsString); break;
				case INFO: logger.info(objectAsString); break;
				case DEBUG: logger.debug(objectAsString); break;
			}
		} catch (Exception e) {
			logger.debug("Failed to convert object to string.", e);
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hugo
 * Date: 17-09-08
 * Time: 21:57
 */

namespace Korri\ComposerVersion;

class GitException extends \Exception
{

}