text:
Function Get-ADSIDomainMode
{
<#
.SYNOPSIS
	Function to retrieve Domain mode

.DESCRIPTION
	Function to retrieve Domain mode

.PARAMETER Credential
	Specifies alternative credential

.PARAMETER DomainName
	Specifies the Domain Name where the function should look

.EXAMPLE
	Get-ADSIDomainMode

.EXAMPLE
	Get-ADSIDomainMode -Credential (Get-Credential)

.EXAMPLE
	Get-ADSIDomainMode -DomainName "FXTEST.local"

.NOTES
	Francois-Xavier Cat
	lazywinadmin.com
	@lazywinadm
	github.com/lazywinadmin/ADSIPS
#>
	[cmdletbinding()]
	PARAM (
		[Alias("RunAs")]
		[System.Management.Automation.PSCredential]
		[System.Management.Automation.Credential()]
		$Credential = [System.Management.Automation.PSCredential]::Empty,

		$DomainName = [System.DirectoryServices.ActiveDirectory.Domain]::Getcurrentdomain()
	)
	PROCESS
	{
		TRY
		{
			IF ($PSBoundParameters['Credential'] -or $PSBoundParameters['DomainName'])
			{
				Write-Verbose '[PROCESS] Credential or DomainName specified'
				$Splatting = @{ }
				IF ($PSBoundParameters['Credential']) { $Splatting.Credential = $Credential }
				IF ($PSBoundParameters['DomainName']) { $Splatting.DomainName = $DomainName }

				(Get-ADSIDomain @splatting).DomainMode

			}
			ELSE
			{
				(Get-ADSIDomain).DomainMode
			}

		}
		CATCH
		{
			Write-Warning -Message '[PROCESS] Something wrong happened!'
			Write-Warning -Message $error[0].Exception.Message
		}
	}
}


text:
Quran Tafseer REST APIs and Quran Text

## Idea

The idea is to create one REST API for all Quran Tafseer/Interpretation for developers.
The idea came to me when I tried to search for REST API for Quran Tafseer/Interpretation I couldn't find one,
and each Quran application web/mobile has its own Quran Tafseer/Interpretation, so I thought it's a good idea
to create one.

## How to contribute and help the project

1. [Report Bugs](https://github.com/EmadMokhtar/tafseer_api/issues/new)
    * If you found a bug please report, it'll help the project to grow and improve.
1. [Suggest Ideas](https://github.com/EmadMokhtar/tafseer_api/issues/new)
    * If you have an innovative idea you feel it'll be awesome to add to the API, please share.
1. Use the API
    * Yes using the API will help the project, this is the reason I built this API 😉.
1. Spread the word
    * Share the API with your friends and community.
1. Write a wrapper or client for the API.
    * Please find the client list below.
1. [Donate](https://www.paypal.me/emadhabib/1)
    * You can help me in growing the project with any amount.
1. Check [translation help](https://github.com/EmadMokhtar/tafseer_api/labels/translation%20help) label, and help in documentation translation.
1. Check [help wanted](https://github.com/EmadMokhtar/tafseer_api/labels/help%20wanted) label, and help in developing the API.

## Development Stack

1. [Python](https://www.python.org/)
1. [Django](https://www.djangoproject.com/)
1. [Django REST Framework](http://www.django-rest-framework.org/)

## How to run locally

* Create a virtualenv
    `mkvirtualenv tafsser_api`
* Install dependencies
    `pip install -r requirements/requirements_dev.txt`
* Create .env file and add project settings

|   Setting    |    Example     |
| ------------- |:-------------:|
|   DEBUG    |    DEBUG=True     |
|   SECRET_KEY    |    SECRET_KEY=VeryVerySecret     |
|   DATABASE_URL    |    DATABASE_URL=sqlite:///db.sqlite3     |

* Run model migrations
    `python manage.py migrate`
* Run development server
    `python manage.py runserver`

## Clients

* [CSharp client](https://github.com/xh0/QuranTafseerCSharpClient) created by [Bassam Abd Elhamid](https://github.com/xh0)
* [Python client pytafseer](https://pypi.org/project/pytafseer/) created by [Emad Mokhtar Elsayed Habib](https://github.com/emadmokhtar)

## Quran Tafseer/Interpretation Sources

|   Tafseer    |   Soruce      | Language |
| ------------- |:-------------:|---------|
|التفسير الميسر| [Tanzil.net](http://tanzil.net/trans/) | العربية |
|تفسير الجلالي| [Tanzil.net](http://tanzil.net/trans/)     | العربية
|تفسير السعدي| [Ayat](http://quran.ksu.edu.sa)| العربية
|تفسير ابن كثير| [Ayat](http://quran.ksu.edu.sa)| العربية
|تفسير الوسيط لطنطاوي| [Ayat](http://quran.ksu.edu.sa)| العربية
|تفسير البغوي| [Ayat](http://quran.ksu.edu.sa)| العربية
|تفسير القرطبي| [Ayat](http://quran.ksu.edu.sa)| العربية
|تفسير الطبري| [Ayat](http://quran.ksu.edu.sa)|  العربية
Arberry | [Tanzil.net](http://tanzil.net/trans/) | English |
Yusuf Ali | [Tanzil.net](http://tanzil.net/trans/) |English |
Keyzer | [Tanzil.net](http://tanzil.net/trans/) | Dutch |
Leemhuis | [Tanzil.net](http://tanzil.net/trans/) | Dutch |
Siregar | [Tanzil.net](http://tanzil.net/trans/) | Dutch |

redpajama_set_name: RedPajamaGithub


text:
YUI( { filter: 'debug' } ).use( 'bewype-layout-designer', function ( Y ) {

    var _hidden         = Y.one( 'input#content_id'),
        _fileStaticPath = Y.one( 'input#file_static_path').get( 'value' ),
        _uploadUrl      = Y.one( 'input#upload_url').get( 'value' ),
        CONTENT_NODE = Y.one( '#' + _hidden.get( 'value' ) );

    /**
     *
     */
    function attachNewsLetter () {

        // pug it
        CONTENT_NODE.plug( Y.Bewype.LayoutDesigner, {
            fileStaticPath  : _fileStaticPath,
            uploadUrl       : _uploadUrl,
            panelPosition   : 'right',
            panelOffsetY    : 40,
            panelOffsetX    : 40,
            pickerColorSize : 90
        } );
    }

    /**
     *
     */
    function onPreview ( e ) {

        // unplug before cloning;
        CONTENT_NODE.unplug( Y.Bewype.LayoutDesigner );

        // get clone for preview
        var _clone      = CONTENT_NODE.cloneNode( true ),
            _window     = null;

        // open window with content ...
        _window= window.open( '', 'previewWindow',
            'location=0, status=0, scrollbars=1, width=720, height=420' );
        // ..
        _window.document.write( '<center>' + _clone.get( 'innerHTML' ) + '</center>' );
        // re-attach
        attachNewsLetter( CONTENT_NODE );
    }

    /**
     *
     */
    function onSubmit( node ) {

        var _name       = node.get( 'name' ),
            _newsletter = Y.one( '#id_content' ),
            _textArea   = Y.Node.create( '<textarea id="id_content" name="content" />');

        // ..
        if ( [ '_addanother', '_continue', '_save' ].indexOf( _name ) != -1 && _newsletter ) {
            // unplug before cloning;
            _newsletter.unplug( Y.Bewype.LayoutDesigner );
            // .. restore texte area
            _textArea.set( 'value', _newsletter.get( 'innerHTML' ) );
            // ..
            _newsletter.replace( _textArea );
            // hide textarea
            _textArea.setStyle( 'display', 'none' );
        }
    }

    /**
     *
     */
    function initLayoutDesignerEvents( submitRow ) {

        submitRow.all( 'input' ).each( function( v, k ) {

            var _target     = v,
                _type       = v.get( 'type' ),
                _name       = v.get( 'name' );

            // check is a submmit button
            if( _type === 'submit' ) {
                // .. add cb
                _target.after( 'click', function( e ) {
                    onSubmit( _target, _name );
                } );
            }
        } );
    }

    /**
     *
     */
    function initLayoutDesigner ( e ) {

        // get node
        attachNewsLetter();

        // .. add cb
        Y.one('#designer_preview').on( 'click', onPreview );

    }

    var _submitRow = Y.one( 'div.submit-row' );

    if ( _submitRow ) {
        Y.after("domready", initLayoutDesigner );
        Y.after("domready", Y.bind( initLayoutDesignerEvents, this, _submitRow ) );
    }
} );


text:
Implementing
============
Users can opt-in to enhanced security by enabling two-factor authentication.
There is currently no enforcement of a policy, it is entirely optional.
However, you could override this behaviour to enforce a custom policy.

Limiting access to certain views
--------------------------------
For increased security views can be limited to two-factor-enabled users. This
allows you to secure certain parts of the website. Doing so requires a
decorator, class mixin or a custom inspection of a user's session.

Decorator
~~~~~~~~~
You can use django-otp's built-in :meth:`~django_otp.decorators.otp_required`
decorator to limit access to two-factor-enabled users::

    from django_otp.decorators import otp_required

    @otp_required
    def my_view(request):
        pass

Mixin
~~~~~
The mixin :class:`~two_factor.views.mixins.OTPRequiredMixin` can be used to
limit access to class-based views (CBVs)::

    class ExampleSecretView(OTPRequiredMixin, TemplateView):
        template_name = 'secret.html'

Custom
~~~~~~
The method ``is_verified()`` is added through django-otp's
:class:`~django_otp.middleware.OTPMiddleware` which can be used to check if the
user was logged in using two-factor authentication::

    def my_view(request):
        if request.user.is_verified():
            # user logged in using two-factor
            pass
        else:
            # user not logged in using two-factor
            pass

Enforcing two-factor
--------------------
Forcing users to enable two-factor authentication is not implemented. However,
you could create your own custom policy.

Admin Site
----------
By default the admin login is patched to use the login views provided by this
application. Patching the admin is required as users would otherwise be able
to circumvent OTP verification. See also :data:`~two_factor.TWO_FACTOR_PATCH_ADMIN`.
Be aware that certain packages include their custom login views, for example
`django.contrib.admindocs`. When using said packages, OTP verification
can be circumvented. Thus however the normal admin login view is patched,
OTP might not always be enforced on the admin views. See the next paragraph
on how to do this.

.. _Hooking AdminSite instances into your URLconf:
   https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf

In order to only allow verified users (enforce OTP) to access the admin pages,
you have to use a custom admin site. You can either use
:class:`~two_factor.admin.AdminSiteOTPRequired` or
:class:`~two_factor.admin.AdminSiteOTPRequiredMixin`. See also the Django
documentation on `Hooking AdminSite instances into your URLconf`_.

Signals
-------
When a user was successfully verified using a OTP, the signal
:data:`~two_factor.signals.user_verified` is sent. The signal includes the
user, the device used and the request itself. You can use this signal for
example to warn a user when one of his backup tokens was used::

    from django.contrib.sites.models import get_current_site
    from django.dispatch import receiver
    from two_factor.signals import user_verified

    @receiver(user_verified)
    def test_receiver(request, user, device, **kwargs):
        current_site = get_current_site(request)
        if device.name == 'backup':
            message = 'Hi %(username)s,\n\n'\
                      'You\'ve verified yourself using a backup device '\
                      'on %(site_name)s. If this wasn\'t you, your '\
                      'account might have been compromised. You need to '\
                      'change your password at once, check your backup '\
                      'phone numbers and generate new backup tokens.'\
                      % {'username': user.get_username(),
                         'site_name': current_site.name}
            user.email_user(subject='Backup token used', message=message)


text:
cd /home/lichess4545/web/staging.lichess4545.com/
export PYTHONPATH=/home/lichess4545/web/staging.lichess4545.com/
/home/lichess4545/web/staging.lichess4545.com/env/bin/gunicorn --error-logfile /home/lichess4545/log/staging.heltour/gunicorn-error.log -t 300 -w 4 -b 127.0.0.1:8680  heltour.staging_wsgi:application


text:
[![Build Status](https://travis-ci.org/ruivieira/crystal-gsl.svg?branch=master)](https://travis-ci.org/ruivieira/crystal-gsl.svg?branch=master)

GNU Scientific Library (GSL) binding for Crystal

## Installation

Add this to your application's `shard.yml`:

```yaml
dependencies:
  gsl:
    github: ruivieira/crystal-gsl
```
## System dependencies

### Ubuntu < 16.04

* libgsl0-dev
* gsl-bin

### Ubuntu >= 16.04

* libgsl-dev
* gsl-bin

### Fedora

* gsl
* gsl-devel

## Usage

```crystal
require "gsl"
```

### Documentation

Full documentation can be found at [here](https://ruivieira.github.io/crystal-gsl/).

### Examples

Examples can be found [here](https://ruivieira.github.io/projects/crystal-gsl/).

*Warning*:

- Not fully test
- Pre-release (API will break)
- Not fit for production

## Contributing

1. Fork it ( https://github.com/ruivieira/crystal-gsl/fork )
2. Create your feature branch (git checkout -b my-new-feature)
3. Commit your changes (git commit -am 'Add some feature')
4. Push to the branch (git push origin my-new-feature)
5. Create a new Pull Request

### Developing Depencies

* Ruby & rake
* [crystal-icr](https://github.com/greyblake/crystal-icr) , > 0.2.10 // Install manually not by shard install

## Contributors

- [ruivieira](https://github.com/ruivieira) Rui Vieira - creator, maintainer
- [dylandy](https://github.com/dylandy) Dylandy Chang - developer, maintainer


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package me.jayfella.pluginwizard;

import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.project.ProjectManager;
import org.netbeans.api.templates.TemplateRegistration;
import org.netbeans.spi.project.ui.support.ProjectChooser;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;

@TemplateRegistration(folder = "Project/JME3", displayName = "#PluginWizard_displayName", description = "PluginWizardDescription.html", iconBase = "me/jayfella/pluginwizard/jmonkeyplugin.png")
@Messages("PluginWizard_displayName=JME Plugin")
public class PluginWizardWizardIterator implements WizardDescriptor./*Progress*/InstantiatingIterator
{
    private int index;
    private WizardDescriptor.Panel[] panels;
    private WizardDescriptor wiz;

    private WizardUtils wizardUtils = new WizardUtils();

    public PluginWizardWizardIterator()
    {
    }

    public static PluginWizardWizardIterator createIterator()
    {
        return new PluginWizardWizardIterator();
    }

    private WizardDescriptor.Panel[] createPanels()
    {
        return new WizardDescriptor.Panel[]
        {
            new PluginWizardWizardPanel(),
        };
    }

    private String[] createSteps()
    {
        return new String[]
        {
            NbBundle.getMessage(PluginWizardWizardIterator.class, "LBL_CreateProjectStep")
        };
    }

    private void unzipFile(String zipFile, FileObject dirFo) throws IOException
    {
        ZipInputStream str = new ZipInputStream(getClass().getClassLoader().getResourceAsStream(zipFile));
        ZipEntry entry;

        try
        {
            while ((entry = str.getNextEntry()) != null)
            {
                if (entry.isDirectory())
                {
                    FileUtil.createFolder(dirFo, entry.getName());
                }
                else
                {
                    FileObject fo = FileUtil.createData(dirFo, entry.getName());
                    writeFile(str, fo);
                 }
            }
        }
        finally
        {
            str.close();
        }
    }

    private void createModule(FileObject suiteDirFo, FileObject moduleDirFo) throws IOException
    {
        unzipFile("me/jayfella/pluginwizard/ModuleTemplate.zip", moduleDirFo);

        File moduleDir = FileUtil.toFile(moduleDirFo);
        File suiteDir = FileUtil.toFile(suiteDirFo);

        // create the base package in the module.
        String basePackage = wiz.getProperty("pluginBasePackage").toString().replace(".", "" + File.separatorChar);
        File basePackageDir = new File(moduleDir.getAbsolutePath() + File.separatorChar + "src" + File.separatorChar + basePackage);
        basePackageDir.mkdirs();

        String pluginName = (String)wiz.getProperty("pluginName");

        // create a Bundle.properties file in the base package.
        File bundlePropertiesFile = new File(basePackageDir.getAbsolutePath() + File.separatorChar + "Bundle.properties");
        bundlePropertiesFile.createNewFile();
        wizardUtils.createBundlePropertiesFile(FileUtil.toFileObject(bundlePropertiesFile), pluginName);

        // create a manifest.mf file
        File manifestFile = new File(suiteDir.getAbsolutePath() + File.separatorChar + pluginName + File.separatorChar + "manifest.mf");
        manifestFile.createNewFile();
        wizardUtils.createModuleManifestFile(manifestFile, wiz.getProperty("pluginBasePackage").toString());

        // modify the project.xml file to reflect the new base package
        File projectXmlFile = new File(moduleDir.getAbsolutePath() + File.separatorChar + "nbproject/project.xml");
        wizardUtils.setModuleBasePackageInProjectXmlFile(FileUtil.toFileObject(projectXmlFile), wiz.getProperty("pluginBasePackage").toString());

        // give them a copy of the jme license to use, and modify project.properties to point to it.
        wizardUtils.copyJmeLicenseToModule(basePackageDir);
        wizardUtils.setLicenseInProjectProperties(moduleDir.getAbsolutePath() + File.separatorChar + "nbproject/project.properties",  basePackage + File.separatorChar + "jme-license.txt");

        String wrappedJarLocation = wiz.getProperty("wrappedJar").toString();
        if (!wrappedJarLocation.isEmpty())
        {
            // copy the jar to the appropriate folder
            File wrappedJar = new File(wrappedJarLocation);
            File wrappedJarDestinationDir = new File(moduleDir.getAbsolutePath() + File.separatorChar + "release" + File.separatorChar + "modules" + File.separatorChar + "ext");
            Path wrappedJarDestination = Paths.get(wrappedJarDestinationDir.getAbsolutePath() + File.separatorChar + wrappedJar.getName());

            wrappedJarDestinationDir.mkdirs();
            Files.copy(wrappedJar.toPath(), wrappedJarDestination);

            // modify the project.xml file to reflect the new wrapped jar.
            wizardUtils.addWrappedJarToModuleProjectXmlFile(FileUtil.toFileObject(projectXmlFile), wrappedJar.getName());
        }
    }

    @Override
    public Set<FileObject> instantiate() throws IOException
    {
        String pluginName = (String)wiz.getProperty("pluginName");

        File suiteDir = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
        File moduleDir = new File(suiteDir.getAbsolutePath() + File.separatorChar + pluginName);

        // check if module suite exists.
        if (!suiteDir.exists())
        {
            suiteDir.mkdirs();
            unzipFile("me/jayfella/pluginwizard/ModuleSuiteTemplate.zip", FileUtil.toFileObject(suiteDir));
        }

        moduleDir.mkdirs();

        // create the new module.
        createModule(FileUtil.toFileObject(suiteDir), FileUtil.toFileObject(moduleDir));

        // inform the module suite of the new module.
        String suiteProjectPropertiesFile = new StringBuilder()
                .append(suiteDir.getAbsolutePath())
                .append(File.separatorChar)
                .append("nbproject")
                .append(File.separatorChar)
                .append("project.properties")
                .toString();

        wizardUtils.addModuleToSuiteProperties(suiteProjectPropertiesFile, wiz.getProperty("pluginBasePackage").toString(), pluginName);

        // finally, open the project.
        Set<FileObject> resultSet = new LinkedHashSet<FileObject>();

        // Always open top dir as a project:
        FileObject suiteFileObject = FileUtil.toFileObject(suiteDir);
        resultSet.add(suiteFileObject);

        // Look for nested projects to open as well:
        Enumeration<? extends FileObject> e = suiteFileObject.getFolders(true);
        while (e.hasMoreElements())
        {
            FileObject subfolder = e.nextElement();
            if (ProjectManager.getDefault().isProject(subfolder))
            {
                resultSet.add(subfolder);
            }
        }

        File parent = suiteDir.getParentFile();
        if (parent != null && parent.exists())
        {
            ProjectChooser.setProjectsFolder(parent);
        }

        return resultSet;
    }

    @Override
    public void initialize(WizardDescriptor wiz)
    {
        this.wiz = wiz;
        index = 0;
        panels = createPanels();

        String[] steps = createSteps();

        for (int i = 0; i < panels.length; i++)
        {
            Component c = panels[i].getComponent();

            if (steps[i] == null)
            {
                steps[i] = c.getName();
            }

            if (c instanceof JComponent)
            {
                JComponent jc = (JComponent) c;

                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, new Integer(i));
                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
            }
        }
    }

    @Override
    public void uninitialize(WizardDescriptor wiz)
    {
        this.wiz.putProperty("projdir", null);
        this.wiz.putProperty("name", null);
        this.wiz.putProperty("pluginBasePackage", null);
        this.wiz.putProperty("wrappedJar", null);

        this.wiz = null;
        panels = null;
    }

    @Override
    public String name()
    {
        return MessageFormat.format("{0} of {1}", new Object[] { new Integer(index + 1), new Integer(panels.length) });
    }

    @Override
    public boolean hasNext()
    {
        return index < panels.length - 1;
    }

    @Override
    public boolean hasPrevious()
    {
        return index > 0;
    }

    @Override
    public void nextPanel()
    {
        if (!hasNext())
            throw new NoSuchElementException();

        index++;
    }

    @Override
    public void previousPanel()
    {
        if (!hasPrevious())
            throw new NoSuchElementException();

        index--;
    }

    @Override
    public WizardDescriptor.Panel current()
    {
        return panels[index];
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    @Override public final void addChangeListener(ChangeListener l) { }
    @Override public final void removeChangeListener(ChangeListener l) { }

    private void writeFile(ZipInputStream str, FileObject fo) throws IOException
    {
        OutputStream out = fo.getOutputStream();

        try
        {
            FileUtil.copy(str, out);
        }
        finally
        {
            out.close();
        }
    }

}


text:
/*=========================================================================================
  File Name: app-menu.js
  Description: Menu navigation, custom scrollbar, hover scroll bar, multilevel menu
  initialization and manipulations
  ----------------------------------------------------------------------------------------
  Item Name: Robust - Responsive Admin Theme
  Version: 1.2
  Author: GeeksLabs
  Author URL: http://www.themeforest.net/user/geekslabs
==========================================================================================*/
(function(window, document, $) {
  'use strict';

  $.app = $.app || {};

  var $body       = $('body');
  var $window     = $( window );
  var menuWrapper_el = $('div[data-menu="menu-wrapper"]').html();
  var menuWrapperClasses = $('div[data-menu="menu-wrapper"]').attr('class');

  // Main menu
  $.app.menu = {
    expanded: null,
    collapsed: null,
    hidden : null,
    container: null,
    horizontalMenu: false,

    manualScroller: {
      obj: null,

      init: function() {
        var scroll_theme = ($('.main-menu').hasClass('menu-dark')) ? 'light' : 'dark';
        this.obj = $(".main-menu-content").perfectScrollbar({
          suppressScrollX: true,
          theme: scroll_theme
        });
      },

      update: function() {
        if (this.obj) {
          // Scroll to currently active menu on page load if data-scroll-to-active is true
          if($('.main-menu').data('scroll-to-active') === true){
              var position;
              if( $(".main-menu-content").find('li.active').parents('li').length > 0 ){
                position = $(".main-menu-content").find('li.active').parents('li').last().position();
              }
              else{
                position = $(".main-menu-content").find('li.active').position();
              }
              setTimeout(function(){
                // $.app.menu.container.scrollTop(position.top);
                $.app.menu.container.stop().animate({scrollTop:position.top}, 300);
                $('.main-menu').data('scroll-to-active', 'false');
              },300);
          }
          $(".main-menu-content").perfectScrollbar('update');
        }
      },

      enable: function() {
        this.init();
      },

      disable: function() {
        if (this.obj) {
          $('.main-menu-content').perfectScrollbar('destroy');
        }
      },

      updateHeight: function(){
        if( ($body.data('menu') == 'vertical-menu' || $body.data('menu') == 'vertical-overlay-menu' ) && $('.main-menu').hasClass('menu-fixed')){
          $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height() - $('.main-menu-header').outerHeight() - $('.main-menu-footer').outerHeight() );
          this.update();
        }
      }
    },

    mMenu: {
      obj: null,

      init: function(){
        $(".main-menu").mmenu({
          slidingSubmenus: true,
          offCanvas: false,
          counters    : false,
          navbar      : {
            title     : ''
          },
          navbars     : [
            {
              position  : 'top',
              content   : ['searchfield']
            }
          ],
          searchfield   : {
            resultsPanel  : true
          },
          setSelected   : {
            parent      : true
          }
        },
          {
            // configuration
            classNames: {
                divider: "navigation-header",
                selected: "active"
            },
            searchfield   : {
              clear : true
            }
          }
        );

        $('a.mm-next').addClass('mm-fullsubopen');

        // Assign menu to API variable
        this.obj = $(".main-menu").data( "mmenu" );
      },

      enable: function(){
        this.init();
      },
      disable: function(){
      }
    },

    init: function() {
      if($('.main-menu-content').length > 0){
        this.container = $('.main-menu-content');

        var menuObj = this;

        this.change();
      }
      else{
        // For 1 column layout menu won't be initialized so initiate drill down for mega menu

        // Drill down menu
        // ------------------------------
        this.drillDownMenu();
      }
    },

    drillDownMenu: function(screenSize){
      if($('.drilldown-menu').length){
        if(screenSize == 'sm' || screenSize == 'xs'){
          if($('#navbar-mobile').attr('aria-expanded') == 'true'){

            $('.drilldown-menu').slidingMenu({
              backLabel:true
            });
          }
        }
        else{
          $('.drilldown-menu').slidingMenu({
            backLabel:true
          });
        }
      }
    },

    change: function() {
      var currentBreakpoint = Unison.fetch.now(); // Current Breakpoint

      this.reset();

      var menuType = $body.data('menu');

      if (currentBreakpoint) {
        switch (currentBreakpoint.name) {
          case 'xl':
          case 'lg':
            if(menuType === 'vertical-overlay-menu'){
              this.hide();
            }
            else if(menuType === 'vertical-compact-menu'){
              this.open();
            }
            else{
              this.expand();
            }
            break;
          case 'md':
            if(menuType === 'vertical-overlay-menu' || menuType === 'vertical-mmenu'){
              this.hide();
            }
            else if(menuType === 'vertical-compact-menu'){
              this.open();
            }
            else{
              this.collapse();
            }
            break;
          case 'sm':
            this.hide();
            break;
          case 'xs':
            this.hide();
            break;
        }
      }

      // On the small and extra small screen make them overlay menu
      if(menuType === 'vertical-menu' || menuType === 'vertical-compact-menu' || menuType === 'vertical-content-menu'){
        this.toOverlayMenu(currentBreakpoint.name);
      }

      if($body.is('.horizontal-layout') && !$body.hasClass('.horizontal-menu-demo')){
        this.changeMenu(currentBreakpoint.name);

        $('.menu-toggle').removeClass('is-active');
      }

      // Initialize drill down menu for vertical layouts, for horizontal layouts drilldown menu is intitialized in changemenu function
      if(menuType != 'horizontal-menu' && menuType != 'horizontal-top-icon-menu'){
        // Drill down menu
        // ------------------------------
        this.drillDownMenu(currentBreakpoint.name);
      }

      // Dropdown submenu on large screen on hover For Large screen only
      // ---------------------------------------------------------------
      if(currentBreakpoint.name == 'xl'){
        $('body[data-open="hover"] .dropdown').on('mouseenter', function(){
          if (!($(this).hasClass('open'))) {
            $(this).addClass('open');
          }else{
            $(this).removeClass('open');
          }
        }).on('mouseleave', function(event){
          $(this).removeClass('open');
        });

        $('body[data-open="hover"] .dropdown a').on('click', function(e){
          if(menuType == 'horizontal-menu' || menuType == 'horizontal-top-icon-menu'){
            var $this = $(this);
            if($this.hasClass('dropdown-toggle')){
              return false;
            }
          }
        });
      }

      // Added data attribute brand-center for navbar-brand-center
      // TODO:AJ: Shift this feature in JADE.
      if($('.header-navbar').hasClass('navbar-brand-center')){
        $('.header-navbar').attr('data-nav','brand-center');
      }
      if(currentBreakpoint.name == 'sm' || currentBreakpoint.name == 'xs'){
        $('.header-navbar[data-nav=brand-center]').removeClass('navbar-brand-center');
      }else{
        $('.header-navbar[data-nav=brand-center]').addClass('navbar-brand-center');
      }

      // Dropdown submenu on small screen on click
      // --------------------------------------------------
      $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
        if($(this).siblings('ul.dropdown-menu').length > 0){
          event.preventDefault();
        }
        event.stopPropagation();
        $(this).parent().siblings().removeClass('open');
        $(this).parent().toggleClass('open');
      });

      // Horizontal Fixed Nav Sticky hight issue on small screens
      if(menuType == 'horizontal-menu' || menuType == 'horizontal-top-icon-menu'){
        if(currentBreakpoint.name == 'sm' || currentBreakpoint.name == 'xs'){
          if($(".menu-fixed").length){
            $(".menu-fixed").unstick();
          }
        }
        else{
          if($(".navbar-fixed").length){
            $(".navbar-fixed").sticky();
          }
        }
      }

      /********************************************
      *             Searchable Menu               *
      ********************************************/

      function searchMenu(list) {

        var input = $(".menu-search");
        $(input)
          .change( function () {
            var filter = $(this).val();
            if(filter) {
              // Hide Main Navigation Headers
              $('.navigation-header').hide();
              // this finds all links in a list that contain the input,
              // and hide the ones not containing the input while showing the ones that do
              $(list).find("li a:not(:Contains(" + filter + "))").hide().parent().hide();
              // $(list).find("li a:Contains(" + filter + ")").show().parents('li').show().addClass('open').closest('li').children('a').show();
              var searchFilter = $(list).find("li a:Contains(" + filter + ")");
              if( searchFilter.parent().hasClass('has-sub') ){
                searchFilter.show()
                .parents('li').show()
                .addClass('open')
                .closest('li')
                .children('a').show()
                .children('li').show();

                // searchFilter.parents('li').find('li').show().children('a').show();
                if(searchFilter.siblings('ul').length > 0){
                  searchFilter.siblings('ul').children('li').show().children('a').show();
                }

              }
              else{
                searchFilter.show().parents('li').show().addClass('open').closest('li').children('a').show();
              }
            } else {
              // return to default
              $('.navigation-header').show();
              $(list).find("li a").show().parent().show().removeClass('open');
            }
            $.app.menu.manualScroller.update();
            return false;
          })
        .keyup( function () {
            // fire the above change event after every letter
            $(this).change();
        });
      }

      if(menuType === 'vertical-menu' || menuType === 'vertical-overlay-menu' || menuType === 'vertical-content-menu'){
        // custom css expression for a case-insensitive contains()
        jQuery.expr[':'].Contains = function(a,i,m){
            return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
        };

        searchMenu($("#main-menu-navigation"));
      }
    },

    changeLogo: function(menuType){
      var logo = $('.brand-logo');
      if(menuType == 'expand'){
        logo.attr('src',logo.data('expand'));
      }
      else{
        logo.attr('src',logo.data('collapse'));
      }
    },

    transit: function(callback1, callback2) {
      var menuObj = this;
      $body.addClass('changing-menu');

      callback1.call(menuObj);

      if($body.hasClass('vertical-layout')){
        if($body.hasClass('menu-open') || $body.hasClass('menu-expanded')){
          $('.menu-toggle').addClass('is-active');

          // Show menu header search when menu is normally visible
          if( $body.data('menu') === 'vertical-menu' || $body.data('menu') === 'vertical-content-menu'){
            if($('.main-menu-header')){
              $('.main-menu-header').show();
            }
          }
        }
        else{
          $('.menu-toggle').removeClass('is-active');

          // Hide menu header search when only menu icons are visible
          if( $body.data('menu') === 'vertical-menu' || $body.data('menu') === 'vertical-content-menu'){
            if($('.main-menu-header')){
              $('.main-menu-header').hide();
            }
          }
        }
      }

      setTimeout(function() {
        callback2.call(menuObj);
        $body.removeClass('changing-menu');

        menuObj.update();
      }, 500);
    },

    open: function() {
      if($body.is('.vertical-mmenu')){
        this.mMenu.enable();
      }
      this.transit(function() {
        $body.removeClass('menu-hide menu-collapsed').addClass('menu-open');
        this.hidden = false;
        this.expanded = true;
      }, function() {
        if(!$('.main-menu').hasClass('menu-native-scroll') && !$body.is('.vertical-mmenu') && $('.main-menu').hasClass('menu-fixed') ){
          this.manualScroller.enable();
          $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height() - $('.main-menu-header').outerHeight() - $('.main-menu-footer').outerHeight() );
          // this.manualScroller.update();
        }
      });
    },

    hide: function() {
      if($body.is('.vertical-mmenu')){
        this.mMenu.disable();
      }

      this.transit(function() {
        $body.removeClass('menu-open menu-expanded').addClass('menu-hide');
        this.hidden = true;
        this.expanded = false;
      }, function() {
        if(!$('.main-menu').hasClass('menu-native-scroll') && !$body.is('.vertical-mmenu') && $('.main-menu').hasClass('menu-fixed')){
          this.manualScroller.enable();
        }
      });
    },

    expand: function() {
      if (this.expanded === false) {
        if( $body.data('menu') == 'vertical-menu'){
          this.changeLogo('expand');
        }
        this.transit(function() {
          $body.removeClass('menu-collapsed').addClass('menu-expanded');
          this.collapsed = false;
          this.expanded = true;

        }, function() {

          if($body.is('.vertical-mmenu')){
            this.mMenu.enable();
          }
          else if( ($('.main-menu').hasClass('menu-native-scroll') || $body.data('menu') == 'vertical-mmenu' || $body.data('menu') == 'horizontal-menu' || $body.data('menu') == 'horizontal-top-icon-menu' )){
            this.manualScroller.disable();
          }
          else{
            if($('.main-menu').hasClass('menu-fixed'))
              this.manualScroller.enable();
          }

          if( $body.data('menu') == 'vertical-menu' && $('.main-menu').hasClass('menu-fixed')){
            $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height() - $('.main-menu-header').outerHeight() - $('.main-menu-footer').outerHeight() );
            // this.manualScroller.update();
          }

        });
      }
    },

    collapse: function() {
      if (this.collapsed === false) {
        if( ($body.data('menu') == 'vertical-menu' ) ){
          this.changeLogo('collapse');
        }
        this.transit(function() {
          $body.removeClass('menu-expanded').addClass('menu-collapsed');
          this.collapsed = true;
          this.expanded  = false;

        }, function() {

          if($body.data('menu') == 'vertical-content-menu'){
            this.manualScroller.disable();
          }

          if( ($body.data('menu') == 'horizontal-menu' || $body.data('menu') == 'horizontal-top-icon-menu') &&  $body.hasClass('vertical-overlay-menu')){
            if($('.main-menu').hasClass('menu-fixed'))
              this.manualScroller.enable();
          }
          if( $body.data('menu') == 'vertical-menu' && $('.main-menu').hasClass('menu-fixed') ){
            $('.main-menu-content').css('height', $(window).height() - $('.header-navbar').height());
            // this.manualScroller.update();
          }
        });
      }
    },

    toOverlayMenu: function(screen){
      var menu = $body.data('menu');
      if(screen == 'sm' || screen == 'xs'){
        if($body.hasClass(menu)){
          $body.removeClass(menu).addClass('vertical-overlay-menu');
        }
        if(menu == 'vertical-content-menu'){
          $('.main-menu').addClass('menu-fixed');
        }
      }
      else{
        if($body.hasClass('vertical-overlay-menu')){
          $body.removeClass('vertical-overlay-menu').addClass(menu);
        }
        if(menu == 'vertical-content-menu'){
          $('.main-menu').removeClass('menu-fixed');
        }
      }
    },

    changeMenu: function(screen){
      // Replace menu html
      $('div[data-menu="menu-wrapper"]').html('');
      $('div[data-menu="menu-wrapper"]').html(menuWrapper_el);

      var menuWrapper    = $('div[data-menu="menu-wrapper"]'),
      menuContainer      = $('div[data-menu="menu-container"]'),
      menuNavigation     = $('ul[data-menu="menu-navigation"]'),
      megaMenu           = $('li[data-menu="megamenu"]'),
      megaMenuCol        = $('li[data-mega-col]'),
      dropdownMenu       = $('li[data-menu="dropdown"]'),
      dropdownSubMenu    = $('li[data-menu="dropdown-submenu"]');

      if(screen == 'sm' || screen == 'xs'){

        // Change body classes
        $body.removeClass($body.data('menu')).addClass('vertical-layout vertical-overlay-menu fixed-navbar');

        // Add navbar-fix-top class on small screens
        $('nav.header-navbar').addClass('navbar-fixed-top');

        // Change menu wrapper, menu container, menu navigation classes
        menuWrapper.removeClass().addClass('main-menu menu-light menu-fixed menu-shadow');
        // menuContainer.removeClass().addClass('main-menu-content');
        menuNavigation.removeClass().addClass('navigation navigation-main');

        // If Mega Menu
        megaMenu.removeClass('dropdown mega-dropdown').addClass('has-sub');
        megaMenu.children('ul').removeClass();
        megaMenuCol.each(function(index, el) {

          // Remove drilldown-menu and menu list
          var megaMenuSub = $(el).find('.mega-menu-sub');
          megaMenuSub.find('li').has('ul').addClass('has-sub');

          // if mega menu title is given, remove title and make it list item with mega menu title's text
          var first_child = $(el).children().first(),
          first_child_text = '';

          if( first_child.is('h6') ){
            first_child_text = first_child.html();
            first_child.remove();
            $(el).prepend(''+first_child_text+'').addClass('has-sub mega-menu-title');
          }
        });
        megaMenu.find('a').removeClass('dropdown-toggle');
        megaMenu.find('a').removeClass('dropdown-item');

        // If Dropdown Menu
        dropdownMenu.removeClass('dropdown').addClass('has-sub');
        dropdownMenu.find('a').removeClass('dropdown-toggle nav-link');
        dropdownMenu.children('ul').find('a').removeClass('dropdown-item');
        dropdownMenu.find('ul').removeClass('dropdown-menu');
        dropdownSubMenu.removeClass().addClass('has-sub');

        $.app.nav.init();

        // Dropdown submenu on small screen on click
        // --------------------------------------------------
        $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
          event.preventDefault();
          event.stopPropagation();
          $(this).parent().siblings().removeClass('open');
          $(this).parent().toggleClass('open');
        });
      }
      else{
        // Change body classes
        $body.removeClass('vertical-layout vertical-overlay-menu fixed-navbar').addClass($body.data('menu'));

        // Remove navbar-fix-top class on large screens
        $('nav.header-navbar').removeClass('navbar-fixed-top');

        // Change menu wrapper, menu container, menu navigation classes
        menuWrapper.removeClass().addClass(menuWrapperClasses);

        // Intitialize drill down menu for horizontal layouts
        // --------------------------------------------------
        this.drillDownMenu(screen);

        $('a.dropdown-item.nav-has-children').on('click',function(){
          event.preventDefault();
          event.stopPropagation();
        });
        $('a.dropdown-item.nav-has-parent').on('click',function(){
          event.preventDefault();
          event.stopPropagation();
        });
      }
    },

    toggle: function() {
      var currentBreakpoint = Unison.fetch.now(); // Current Breakpoint
      var collapsed = this.collapsed;
      var expanded = this.expanded;
      var hidden = this.hidden;
      var menu = $body.data('menu');

      switch (currentBreakpoint.name) {
        case 'xl':
        case 'lg':
        case 'md':
          if(expanded === true){
            if(menu == 'vertical-compact-menu' || menu == 'vertical-mmenu' || menu == 'vertical-overlay-menu'){
              this.hide();
            }
            else{
              this.collapse();
            }
          }
          else{
            if(menu == 'vertical-compact-menu' || menu == 'vertical-mmenu' || menu == 'vertical-overlay-menu'){
              this.open();
            }
            else{
              this.expand();
            }
          }
          break;
        case 'sm':
          if (hidden === true) {
            this.open();
          } else {
            this.hide();
          }
          break;
        case 'xs':
          if (hidden === true) {
            this.open();
          } else {
            this.hide();
          }
          break;
      }

      // Re-init sliding menu to update width
      this.drillDownMenu(currentBreakpoint.name);
    },

    update: function() {
      this.manualScroller.update();
    },

    reset: function() {
      this.expanded  = false;
      this.collapsed = false;
      this.hidden    = false;
      $body.removeClass('menu-hide menu-open menu-collapsed menu-expanded');
    },
  };

  // Navigation Menu
  $.app.nav = {
    container: $('.navigation-main'),
    initialized : false,
    navItem: $('.navigation-main').find('li').not('.navigation-category'),

    config: {
      speed: 300,
    },

    init: function(config) {
      this.initialized = true; // Set to true when initialized
      $.extend(this.config, config);

      if(!$body.is('.vertical-mmenu')){
        this.bind_events();
      }
    },

    bind_events: function() {
      var menuObj = this;

      $('.navigation-main').on('mouseenter.app.menu', 'li', function() {
        var $this = $(this);
        $('.hover', '.navigation-main').removeClass('hover');
        if( $body.hasClass('menu-collapsed') || ($body.data('menu') == 'vertical-compact-menu' && !$body.hasClass('vertical-overlay-menu')) ){
          $('.main-menu-content').children('span.menu-title').remove();
          $('.main-menu-content').children('a.menu-title').remove();
          $('.main-menu-content').children('ul.menu-content').remove();

          // Title
          var menuTitle = $this.find('span.menu-title').clone(),
          tempTitle,
          tempLink;
          if(!$this.hasClass('has-sub') ){
            tempTitle = $this.find('span.menu-title').text();
            tempLink = $this.children('a').attr('href');
            if(tempTitle !== ''){
              menuTitle = $("");
              menuTitle.attr("href", tempLink);
              menuTitle.attr("title", tempTitle);
              menuTitle.text(tempTitle);
              menuTitle.addClass("menu-title");
            }
          }
          // menu_header_height = ($('.main-menu-header').length) ? $('.main-menu-header').height() : 0,
          // fromTop = menu_header_height + $this.position().top + parseInt($this.css( "border-top" ),10);
          var fromTop;
          if($this.css( "border-top" )){
            fromTop = $this.position().top + parseInt($this.css( "border-top" ), 10);
          }
          else{
            fromTop = $this.position().top;
          }
          if($body.data('menu') !== 'vertical-compact-menu'){
            menuTitle.appendTo('.main-menu-content').css({
              position:'fixed',
              top : fromTop,
            });
          }

          // Content
          if($this.hasClass('has-sub') && $this.hasClass('nav-item')) {
            var menuContent = $this.children('ul:first');
            menuObj.adjustSubmenu($this);
          }
        }
        $this.addClass('hover');
      }).on('mouseleave.app.menu', 'li', function() {
        // $(this).removeClass('hover');
      }).on('active.app.menu', 'li', function(e) {
        $(this).addClass('active');
        e.stopPropagation();
      }).on('deactive.app.menu', 'li.active', function(e) {
        $(this).removeClass('active');
        e.stopPropagation();
      }).on('open.app.menu', 'li', function(e) {

        var $listItem = $(this);
        $listItem.addClass('open');

        menuObj.expand($listItem);

        // If menu collapsible then do not take any action
        if ($('.main-menu').hasClass('menu-collapsible')) {
          return false;
        }
        // If menu accordion then close all except clicked once
        else{
          $listItem.siblings('.open').find('li.open').trigger('close.app.menu');
          $listItem.siblings('.open').trigger('close.app.menu');
        }

        e.stopPropagation();
      }).on('close.app.menu', 'li.open', function(e) {
        var $listItem = $(this);

        $listItem.removeClass('open');
        menuObj.collapse($listItem);

        e.stopPropagation();
      }).on('click.app.menu', 'li', function(e) {
        var $listItem = $(this);
        if($listItem.is('.disabled')){
          e.preventDefault();
        }
        else{
          if( $body.hasClass('menu-collapsed') || ($body.data('menu') == 'vertical-compact-menu' && $listItem.is('.has-sub') && !$body.hasClass('vertical-overlay-menu')) ){
            e.preventDefault();
          }
          else{
            if ($listItem.has('ul')) {
              if ($listItem.is('.open')) {
                $listItem.trigger('close.app.menu');
              } else {
                $listItem.trigger('open.app.menu');
              }
            } else {
              if (!$listItem.is('.active')) {
                $listItem.siblings('.active').trigger('deactive.app.menu');
                $listItem.trigger('active.app.menu');
              }
            }
          }
        }

        e.stopPropagation();
      });

      $('.main-menu-content').on('mouseleave', function(){
        if( $body.hasClass('menu-collapsed') || $body.data('menu') == 'vertical-compact-menu' ){
          $('.main-menu-content').children('span.menu-title').remove();
          $('.main-menu-content').children('a.menu-title').remove();
          $('.main-menu-content').children('ul.menu-content').remove();
        }
        $('.hover', '.navigation-main').removeClass('hover');
      });

      // If list item has sub menu items then prevent redirection.
      $('.navigation-main li.has-sub > a').on('click',function(e){
        e.preventDefault();
      });

      $('ul.menu-content').on('click', 'li', function(e) {
        var $listItem = $(this);
        if($listItem.is('.disabled')){
          e.preventDefault();
        }
        else{
          if ($listItem.has('ul')) {
            if ($listItem.is('.open')) {
              $listItem.removeClass('open');
              menuObj.collapse($listItem);
            } else {
              $listItem.addClass('open');

              menuObj.expand($listItem);

              // If menu collapsible then do not take any action
              if ($('.main-menu').hasClass('menu-collapsible')) {
                return false;
              }
              // If menu accordion then close all except clicked once
              else{
                $listItem.siblings('.open').find('li.open').trigger('close.app.menu');
                $listItem.siblings('.open').trigger('close.app.menu');
              }

              e.stopPropagation();
            }
          } else {
            if (!$listItem.is('.active')) {
              $listItem.siblings('.active').trigger('deactive.app.menu');
              $listItem.trigger('active.app.menu');
            }
          }
        }

        e.stopPropagation();
      });
    },

    /**
     * Ensure an admin submenu is within the visual viewport.
     * @param {jQuery} $menuItem The parent menu item containing the submenu.
     */
    adjustSubmenu: function ( $menuItem ) {
      var menuHeaderHeight, menutop, topPos, winHeight,
      bottomOffset, subMenuHeight, popOutMenuHeight, borderWidth, scroll_theme,
      $submenu = $menuItem.children('ul:first'),
      ul = $submenu.clone(true);

      menuHeaderHeight = $('.main-menu-header').height();
      menutop          = $menuItem.position().top;
      winHeight        = $window.height() - $('.header-navbar').height();
      borderWidth      = 0;
      subMenuHeight    = $submenu.height();

      if(parseInt($menuItem.css( "border-top" ),10) > 0){
        borderWidth = parseInt($menuItem.css( "border-top" ),10);
      }

      popOutMenuHeight = winHeight - menutop - $menuItem.height() - 30;
      scroll_theme     = ($('.main-menu').hasClass('menu-dark')) ? 'light' : 'dark';

      if($body.data('menu') === 'vertical-compact-menu'){
        topPos = menutop + borderWidth;
        popOutMenuHeight = winHeight - menutop - 30;
      }
      else if($body.data('menu') === 'vertical-content-menu'){
        topPos = menutop + $menuItem.height() + borderWidth;
        popOutMenuHeight = winHeight - $('.content-header').height() -$menuItem.height() - menutop - 60;
      }
      else{
        topPos = menutop + $menuItem.height() + borderWidth;
      }

      if($body.data('menu') == 'vertical-content-menu'){
        ul.addClass('menu-popout').appendTo('.main-menu-content').css({
          'top' : topPos,
          'position' : 'fixed',
        });
      }
      else{
        ul.addClass('menu-popout').appendTo('.main-menu-content').css({
          'top' : topPos,
          'position' : 'fixed',
          'max-height': popOutMenuHeight,
        });

        $('.main-menu-content > ul.menu-content').perfectScrollbar({
          theme:scroll_theme,
        });
      }
    },

    collapse: function($listItem, callback) {
      var $subList = $listItem.children('ul');

      $subList.show().slideUp($.app.nav.config.speed, function() {
        $(this).css('display', '');

        $(this).find('> li').removeClass('is-shown');

        if (callback) {
          callback();
        }

        $.app.nav.container.trigger('collapsed.app.menu');
      });
    },

    expand: function($listItem, callback) {
      var $subList  = $listItem.children('ul');
      var $children = $subList.children('li').addClass('is-hidden');

      $subList.hide().slideDown($.app.nav.config.speed, function() {
        $(this).css('display', '');

        if (callback) {
          callback();
        }

        $.app.nav.container.trigger('expanded.app.menu');
      });

      setTimeout(function() {
        $children.addClass('is-shown');
        $children.removeClass('is-hidden');
      }, 0);
    },

    refresh: function() {
      $.app.nav.container.find('.open').removeClass('open');
    },
  };

})(window, document, jQuery);


text:
using UnityEngine;
using System.Collections;

public class LadderZone : MonoBehaviour
{
	private PlayerController thePlayer;

	// Use this for initialization
	void Start ()
	{
		this.thePlayer = FindObjectOfType<PlayerController> ();
	}

	void OnTriggerEnter2D (Collider2D other)
	{
		if (other.name == "Player") {
			this.thePlayer.onLadder = true;
		}
	}

	void OnTriggerExit2D (Collider2D other)
	{
		if (other.name == "Player") {
			this.thePlayer.onLadder = false;
		}
	}
}


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

namespace TchApp.HttpSimulator
{
    internal partial class Frame
    {
        private static readonly Type IHttpRequestFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature);
        private static readonly Type IHttpResponseFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature);
        private static readonly Type IHttpRequestIdentifierFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature);
        private static readonly Type IServiceProvidersFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature);
        private static readonly Type IHttpRequestLifetimeFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature);
        private static readonly Type IHttpConnectionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature);
        private static readonly Type IHttpAuthenticationFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature);
        private static readonly Type IQueryFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature);
        private static readonly Type IFormFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature);
        private static readonly Type IHttpUpgradeFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature);
        private static readonly Type IResponseCookiesFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature);
        private static readonly Type IItemsFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature);
        private static readonly Type ITlsConnectionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature);
        private static readonly Type IHttpWebSocketFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature);
        private static readonly Type ISessionFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature);
        private static readonly Type IHttpSendFileFeatureType = typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature);

        private object _currentIHttpRequestFeature;
        private object _currentIHttpResponseFeature;
        private object _currentIHttpRequestIdentifierFeature;
        private object _currentIServiceProvidersFeature;
        private object _currentIHttpRequestLifetimeFeature;
        private object _currentIHttpConnectionFeature;
        private object _currentIHttpAuthenticationFeature;
        private object _currentIQueryFeature;
        private object _currentIFormFeature;
        private object _currentIHttpUpgradeFeature;
        private object _currentIResponseCookiesFeature;
        private object _currentIItemsFeature;
        private object _currentITlsConnectionFeature;
        private object _currentIHttpWebSocketFeature;
        private object _currentISessionFeature;
        private object _currentIHttpSendFileFeature;

        private void FastReset()
        {
            _currentIHttpRequestFeature = this;
            _currentIHttpResponseFeature = this;
            _currentIHttpUpgradeFeature = this;
            _currentIHttpRequestLifetimeFeature = this;
            _currentIHttpConnectionFeature = this;

            _currentIHttpRequestIdentifierFeature = null;
            _currentIServiceProvidersFeature = null;
            _currentIHttpAuthenticationFeature = null;
            _currentIQueryFeature = null;
            _currentIFormFeature = null;
            _currentIResponseCookiesFeature = null;
            _currentIItemsFeature = null;
            _currentITlsConnectionFeature = null;
            _currentIHttpWebSocketFeature = null;
            _currentISessionFeature = null;
            _currentIHttpSendFileFeature = null;
        }

        private object FastFeatureGet(Type key)
        {
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature))
            {
                return _currentIHttpRequestFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature))
            {
                return _currentIHttpResponseFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature))
            {
                return _currentIHttpRequestIdentifierFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature))
            {
                return _currentIServiceProvidersFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature))
            {
                return _currentIHttpRequestLifetimeFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature))
            {
                return _currentIHttpConnectionFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature))
            {
                return _currentIHttpAuthenticationFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature))
            {
                return _currentIQueryFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature))
            {
                return _currentIFormFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature))
            {
                return _currentIHttpUpgradeFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature))
            {
                return _currentIResponseCookiesFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature))
            {
                return _currentIItemsFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature))
            {
                return _currentITlsConnectionFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature))
            {
                return _currentIHttpWebSocketFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature))
            {
                return _currentISessionFeature;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature))
            {
                return _currentIHttpSendFileFeature;
            }
            return ExtraFeatureGet(key);
        }

        private void FastFeatureSet(Type key, object feature)
        {
            _featureRevision++;

            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature))
            {
                _currentIHttpRequestFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature))
            {
                _currentIHttpResponseFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature))
            {
                _currentIHttpRequestIdentifierFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature))
            {
                _currentIServiceProvidersFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature))
            {
                _currentIHttpRequestLifetimeFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature))
            {
                _currentIHttpConnectionFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature))
            {
                _currentIHttpAuthenticationFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IQueryFeature))
            {
                _currentIQueryFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IFormFeature))
            {
                _currentIFormFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature))
            {
                _currentIHttpUpgradeFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature))
            {
                _currentIResponseCookiesFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IItemsFeature))
            {
                _currentIItemsFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature))
            {
                _currentITlsConnectionFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature))
            {
                _currentIHttpWebSocketFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.ISessionFeature))
            {
                _currentISessionFeature = feature;
                return;
            }
            if (key == typeof(global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature))
            {
                _currentIHttpSendFileFeature = feature;
                return;
            };
            ExtraFeatureSet(key, feature);
        }

        private IEnumerable<KeyValuePair<Type, object>> FastEnumerable()
        {
            if (_currentIHttpRequestFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpRequestFeatureType, _currentIHttpRequestFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestFeature);
            }
            if (_currentIHttpResponseFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpResponseFeatureType, _currentIHttpResponseFeature as global::Microsoft.AspNetCore.Http.Features.IHttpResponseFeature);
            }
            if (_currentIHttpRequestIdentifierFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpRequestIdentifierFeatureType, _currentIHttpRequestIdentifierFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestIdentifierFeature);
            }
            if (_currentIServiceProvidersFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IServiceProvidersFeatureType, _currentIServiceProvidersFeature as global::Microsoft.AspNetCore.Http.Features.IServiceProvidersFeature);
            }
            if (_currentIHttpRequestLifetimeFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpRequestLifetimeFeatureType, _currentIHttpRequestLifetimeFeature as global::Microsoft.AspNetCore.Http.Features.IHttpRequestLifetimeFeature);
            }
            if (_currentIHttpConnectionFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpConnectionFeatureType, _currentIHttpConnectionFeature as global::Microsoft.AspNetCore.Http.Features.IHttpConnectionFeature);
            }
            if (_currentIHttpAuthenticationFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpAuthenticationFeatureType, _currentIHttpAuthenticationFeature as global::Microsoft.AspNetCore.Http.Features.Authentication.IHttpAuthenticationFeature);
            }
            if (_currentIQueryFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IQueryFeatureType, _currentIQueryFeature as global::Microsoft.AspNetCore.Http.Features.IQueryFeature);
            }
            if (_currentIFormFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IFormFeatureType, _currentIFormFeature as global::Microsoft.AspNetCore.Http.Features.IFormFeature);
            }
            if (_currentIHttpUpgradeFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpUpgradeFeatureType, _currentIHttpUpgradeFeature as global::Microsoft.AspNetCore.Http.Features.IHttpUpgradeFeature);
            }
            if (_currentIResponseCookiesFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IResponseCookiesFeatureType, _currentIResponseCookiesFeature as global::Microsoft.AspNetCore.Http.Features.IResponseCookiesFeature);
            }
            if (_currentIItemsFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IItemsFeatureType, _currentIItemsFeature as global::Microsoft.AspNetCore.Http.Features.IItemsFeature);
            }
            if (_currentITlsConnectionFeature != null)
            {
                yield return new KeyValuePair<Type, object>(ITlsConnectionFeatureType, _currentITlsConnectionFeature as global::Microsoft.AspNetCore.Http.Features.ITlsConnectionFeature);
            }
            if (_currentIHttpWebSocketFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpWebSocketFeatureType, _currentIHttpWebSocketFeature as global::Microsoft.AspNetCore.Http.Features.IHttpWebSocketFeature);
            }
            if (_currentISessionFeature != null)
            {
                yield return new KeyValuePair<Type, object>(ISessionFeatureType, _currentISessionFeature as global::Microsoft.AspNetCore.Http.Features.ISessionFeature);
            }
            if (_currentIHttpSendFileFeature != null)
            {
                yield return new KeyValuePair<Type, object>(IHttpSendFileFeatureType, _currentIHttpSendFileFeature as global::Microsoft.AspNetCore.Http.Features.IHttpSendFileFeature);
            }

            if (MaybeExtra != null)
            {
                foreach(var item in MaybeExtra)
                {
                    yield return item;
                }
            }
        }
    }
}


text:
require "omniauth-facebook"
fb_id           = Rails.env.production? ? "#{@settings[:facebook_id_production]}" : "#{@settings[:facebook_id_development]}"
fb_secret       = Rails.env.production? ? "#{@settings[:facebook_secret_production]}" : "#{@settings[:facebook_secret_development]}"
config.omniauth :facebook, fb_id, fb_secret


text:
/* Remove extraneous whitespace in panes of vertical tabs. */

#google-tag-settings-form div.vertical-tabs .vertical-tabs-panes fieldset.vertical-tabs-pane {
  padding-top: 0;
}

#google-tag-settings-form div.vertical-tabs .fieldset-wrapper {
  margin-top: 0;
}


text:
namespace Microsoft.Azure.Management.Network.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// Application gateway backendhealth pool.
    /// </summary>
    public partial class ApplicationGatewayBackendHealthPool
    {
        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayBackendHealthPool class.
        /// </summary>
        public ApplicationGatewayBackendHealthPool() { }

        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayBackendHealthPool class.
        /// </summary>
        public ApplicationGatewayBackendHealthPool(ApplicationGatewayBackendAddressPool backendAddressPool = default(ApplicationGatewayBackendAddressPool), IList<ApplicationGatewayBackendHealthHttpSettings> backendHttpSettingsCollection = default(IList<ApplicationGatewayBackendHealthHttpSettings>))
        {
            BackendAddressPool = backendAddressPool;
            BackendHttpSettingsCollection = backendHttpSettingsCollection;
        }

        /// <summary>
        /// Reference of application gateway backend address pool resource.
        /// </summary>
        [JsonProperty(PropertyName = "backendAddressPool")]
        public ApplicationGatewayBackendAddressPool BackendAddressPool { get; set; }

        /// <summary>
        /// List of application gateway backendhealth http settings.
        /// </summary>
        [JsonProperty(PropertyName = "backendHttpSettingsCollection")]
        public IList<ApplicationGatewayBackendHealthHttpSettings> BackendHttpSettingsCollection { get; set; }

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>Stockton, Unified! - School Directory</title>
    <link rel="shortcut icon" href="icon/icon.png" type="image/x-icon" />
    <link rel="apple-touch-icon" href="icon/icon.png">
    <link rel="apple-touch-icon-precomposed" href="icon/icon.png">

    <link href="css/stylesheets/framework7.min.css" media="screen, projection" rel="stylesheet" type="text/css" />

    <link rel="stylesheet" href="font-awesome-4.3.0/css/font-awesome.min.css">
    <link href="css/stylesheets/template.css" media="screen, projection" rel="stylesheet" type="text/css" />
    <link href="css/stylesheets/responsive.css" media="screen, projection" rel="stylesheet" type="text/css" />

								<select name="school-selected" id="school-selected" onchange="getSchool()">
								</select>

School


text:
package net.tinyos.plot;

import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.util.*;

public class PlotApplet extends JApplet {
	private plotpanel plot;

	public PlotApplet() {
	}

	private Color toColor (String s) {
		StringTokenizer st = new StringTokenizer(s);
		Color c = new Color (Integer.parseInt(st.nextToken()),
			Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		return c;
	}

	public void init() {
		plot = new plotpanel();
		getContentPane().add(plot);
		String bg = null;
		String antialiasing = getParameter ("antialiasing");
		String minX=getParameter ("minX"),
		       maxX=getParameter ("maxX"),
		       minY=getParameter ("minY"),
		       maxY=getParameter ("maxY");
		if (minX != null)
			plot.setMinX (Double.parseDouble(minX));
		if (minY != null)
			plot.setMinY (Double.parseDouble(minY));
		if (maxX != null)
			plot.setMaxX (Double.parseDouble(maxX));
		if (maxY != null)
			plot.setMaxY (Double.parseDouble(maxY));

		if (antialiasing != null && antialiasing.equals("true"))
			plot.setAntiAliasing (true);

		if ((bg = getParameter ("background")) != null) {
			Color c = toColor (bg);
			plot.setBackground(c);
		}
		for (int i = 1; ; i++) {
			String function = getParameter ("function"+i);
			if (function == null) {
				break;
			}
			String description = getParameter ("description"+i);
			String color = getParameter ("color"+i);
			plot.addFunction (new ParsedFunction(function), toColor(color), description);
		}
		//add (plot);
	}
}


text:
layout: post
author: Adrian
title: Adrian's Turtle Exercise
---

The
first time I drew the rainbow, it took up about 80 lines, so I used a function and for loop to condense the code. I also
set the turtle to go at "ludicrous" speed which is a predefined constant in the turtle library. I spent a long time trying
to figure out the geometry involved, and used a lot of guess and check.

![Turtle image](https://f.cloud.github.com/assets/6354212/1945696/8a7bdb70-7fd5-11e3-8487-5a24965210ed.png)

```
import turtle

wn = turtle.Screen()

# set the window background color
wn.bgcolor("skyblue")

kevin = turtle.Turtle()
kevin.shape("turtle")
kevin.speed('ludicrous')

def drawRainbow(kevin, radius, width):
    kevin.penup()
    colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet", "skyblue"]
    kevin.right(-90)

    for i in range(len(colors)):
        kevin.color(colors[i])
        pos_1 = radius - (i/7) * width
        # 7 is the length of the list of colors - 1
        kevin.goto(pos_1, -50)
        kevin.pendown()
        kevin.begin_fill()
        kevin.circle(pos_1, 180)
        kevin.end_fill()
        kevin.penup()
        kevin.right(180)

drawRainbow(kevin, 200, 150)
kevin.goto(0, -50)

wn.exitonclick()
```


text:
package com.eagle.programmar.IBMASM.Directives;

import com.eagle.programmar.IBMASM.Terminals.IBMASM_Keyword;
import com.eagle.tokens.TokenSequence;

public class IBMASM_CSECT_Directive extends TokenSequence
{
	public IBMASM_Keyword CSECT = new IBMASM_Keyword("CSECT");
}


text:
package com.untamedears.JukeAlert.listener;

import static com.untamedears.JukeAlert.util.Utility.isOnSnitch;

import java.util.Set;
import java.util.UUID;

import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;

import com.untamedears.ItemExchange.events.IETransactionEvent;
import com.untamedears.JukeAlert.JukeAlert;
import com.untamedears.JukeAlert.manager.SnitchManager;
import com.untamedears.JukeAlert.model.Snitch;

public class ItemExchangeListener implements Listener{

	private final JukeAlert plugin = JukeAlert.getInstance();
	SnitchManager snitchManager = plugin.getSnitchManager();

	@EventHandler(priority = EventPriority.HIGHEST)
	public void exchangeEvent(IETransactionEvent event){
		Player player = event.getPlayer();
		Location location = event.getExchangeLocation();
		World world = location.getWorld();
		UUID accountId = player.getUniqueId();
		Set<Snitch> snitches = snitchManager.findSnitches(world, location);
		for (Snitch snitch : snitches) {
            if (!isOnSnitch(snitch, accountId)) {
                snitch.imposeSnitchTax();
                if (snitch.shouldLog()) {
                	plugin.getJaLogger().logSnitchExchangeEvent(snitch, player, location);
                }
            }
        }
	}
}


text:
#ifndef MISCDELEGATE_H
#define MISCDELEGATE_H

#include <QItemDelegate>

// TODO: inherit from QStyleItemDelegate when available in 4.4

class MiscDelegate : public QItemDelegate
{
    Q_OBJECT
public:
    MiscDelegate(QObject *parent = 0);
    ~MiscDelegate();

    // create editor widget
    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                          const QModelIndex &index) const;
    // set the contents of the editor
    void setEditorData(QWidget *editor, const QModelIndex &index) const;
    // set the contents of the model
    void setModelData(QWidget *editor, QAbstractItemModel *model,
                      const QModelIndex &index) const;
    // manage the editor's geometry
    void updateEditorGeometry(QWidget *editor,
                              const QStyleOptionViewItem &option,
                              const QModelIndex &index) const;
};

#endif // MISCDELEGATE_H


text:
This text describes deployments for [orchestrator on raft](raft.md).

This complements general [deployment](deployment.md) documentation.

### Backend DB

You may choose between using `MySQL` and `SQLite`. See [backend configuration](configuration-backend.md).

- For MySQL:
  - The backend servers will be standalone. No replication setup. Each `orchestrator` node will interact with its own dedicated backend server.
  - You _must_ have a `1:1` mapping `orchestrator:MySQL`.
  - Suggestion: run `orchestrator` and its dedicated MySQL server on same box.
  - Make sure to `GRANT` privileges for the `orchestrator` user on each backend node.

- For `SQLite`:
  - `SQLite` is bundled with `orchestrator`.
  - Make sure the `SQLite3DataFile` is writable by the `orchestrator` user.

### High availability

`orchestrator` high availability is gained by using `raft`. You do not need to take care of backend DB high availability.

### What to deploy: service

- Deploy the `orchestrator` service onto service boxes.
  As suggested, you may want to put `orchestrator` service and `MySQL` service on same box. If using `SQLite` there's nothing else to do.

- Consider adding a proxy on top of the service boxes; the proxy would redirect all traffic to the leader node. There is one and only one leader node, and the status check endpoint is `/api/leader-check`.
  - Clients may only interact with healthy raft nodes.
    - Simplest is to just interact with the leader. Setting up a proxy is one way to ensure that. See [proxy: leader section](raft.md#proxy-leader).
    -  Otherwise all healthy raft nodes will reverse proxy your requests to the leader. See [proxy: healthy raft nodes section](raft.md#proxy-healthy-raft-nodes).
- Nothing should directly interact with a backend DB. Only the leader is capable of coordinating changes to the data with the other `raft` nodes.

- `orchestrator` nodes communicate between themselves on `DefaultRaftPort`. This port should be open to all `orchestrator` nodes, and no one else needs to have access to this port.

### What to deploy: client

To interact with orchestrator from shell/automation/scripts, you may choose to:

- Directly interact with the HTTP API
  - You may only interact with the _leader_. A good way to achieve this is using a proxy.
- Use the [orchestrator-client](orchestrator-client.md) script.
  - Deploy `orchestrator-client` on any box from which you wish to interact with `orchestrator`.
  - Create and edit `/etc/profile.d/orchestrator-client.sh` on those boxes to read:
    ```
    ORCHESTRATOR_API="http://your.orchestrator.service.proxy:80/api"
    ```
    or
    ```
    ORCHESTRATOR_API="http://your.orchestrator.service.host1:3000/api http://your.orchestrator.service.host2:3000/api http://your.orchestrator.service.host3:3000/api"
    ```
    In the latter case you will provide the list of all `orchestrator` nodes, and the `orchestrator-client` script will automatically figure out which is the leader. With this setup your automation will not need a proxy (though you may still wish to use a proxy for web interface users).

    Make sure to chef/puppet/whatever the `ORCHESTRATOR_API` value such that it adapts to changes in your environment.

- The `orchestrator` command line client will refuse to run given a raft setup, since it interacts directly with the underlying database and doesn't participate in the raft consensus, and thus cannot ensure all raft members will get visibility into it changes.
  - Fortunately `orchestrator-client` provides an almost identical interface as the command line client.
  - You may force the command line client to run via `--ignore-raft-setup`. This is a "I know what I'm doing" risk you take. If you do choose to use it, then it makes more sense to connect to the leader's backend DB.

### Orchestrator service

As noted, a single `orchestrator` node will assume leadership. Only the leader will:

- Run recoveries

However all nodes will:

- Discover (probe) your MySQL topologies
- Run failure detection
- Register their own health check

Non-leader nodes must _NOT_:

- Run arbitrary commands (e.g. `relocate`, `begin-downtime`)
- Run recoveries per human request.
- Serve client HTTP requests (but some endpoints, such as load-balancer and health checks, are valid).

### A visual example

![orchestrator deployment, raft](images/orchestrator-deployment-raft.png)

In the above there are three `orchestrator` nodes in a `raft` cluster, each using its own dedicated database (either `MySQL` or `SQLite`).

`orchestrator` nodes communicate with each other.

Only one `orchestrator` node is the leader.

All `orchestrator` nodes probe the entire `MySQL` fleet. Each `MySQL` server is probed by each of the `raft` members.

### orchestrator/raft operational scenarios

##### A node crashes:

Start the node, start the `MySQL` service if applicable, start the `orchestrator` service. The `orchestrator` service should join the `raft` group, get a recent snapshot, catch up with `raft` replication log and continue as normal.

##### A new node is provisioned / a node is re-provisioned

Such that the backend database is completely empty/missing.

- If `SQLite`, nothing to be done. The node will just join the `raft` group, get a snapshot from one of the active nodes, catch up with `raft` log and run as normal.
- If `MySQL`, the same will be attempted. However, the `MySQL` server will have to [have the privileges](configuration-backend.md#mysql-backend-db-setup) for `orchestrator` to operate. So if this is a brand new server, those privileges are likely to not be there.
  As example, our `puppet` setup periodically ensures privileges are set on our MySQL servers. Thus, when a new server is provisioned, next `puppet` run lays the privileges for `orchestrator`. `puppet` also ensures the `orchestrator` service is running, and so, pending some time, `orchestrator` can automatically join the group.

##### Cloning is valid

If you choose to, you may also provision new boxes by cloning your existing backend databases using your favorite backup/restore  or dump/load method.

This is **perfectly valid** though **not required**.

- If `MySQL`, run backup/restore, either logical or physical.
- If `SQLite`, run `.dump` + restore, see [10. Converting An Entire Database To An ASCII Text File](https://sqlite.org/cli.html).

- Start the `orchestrator` service. It should catch up with `raft` replication log and join the `raft` cluster.

##### Replacing a node

Assuming `RaftNodes: ["node1", "node2", "node3"]`, and you wish to replace `node3` with `nodeX`.

- You may take down `node3`, and the `raft` cluster will continue to work as long as `node1` and `node2` are good.
- Create `nodeX` box. Generate backend db data (see above).
- On `node1`, `node2` and `nodeX` reconfigure `RaftNodes: ["node1", "node2", "nodeX"]`.
- Start `orchestrator` on `nodeX`. It will be refused and will not join the cluster because `node1` and `node2` are not yet aware of the change.
- Restart `orchestrator` on `node1`.
- Restart `orchestrator` on `node2`.
  - All three nodes should form a happy cluster at this time.


text:
using System.Collections.Generic;

namespace Tup.Cobar4Net.Parser.Ast.Expression.Primary.Function.Encryption
{
    /// <author>
    ///     QIU Shuo
    /// </author>
    public class DesEncrypt : FunctionExpression
    {
        public DesEncrypt(IList<IExpression> arguments)
            : base("DES_ENCRYPT", arguments)
        {
        }

        public override FunctionExpression ConstructFunction(IList<IExpression> arguments)
        {
            return new DesEncrypt(arguments);
        }
    }
}


text:
package Command::TOPIC;
@ISA = qw(Command);

use warnings;
use strict;
use Method::Signatures;

use Numeric qw(
    ERR_NOTREGISTERED
    ERR_NEEDMOREPARAMS
    ERR_NOSUCHCHANNEL
    ERR_NOTONCHANNEL
    ERR_CHANOPRIVSNEEDED
    RPL_NOTOPIC
    RPL_TOPIC
);

our (%channel, %topic);
Class::self->readable_variables qw(target);

method parse($arguments) {
    local ($1, $2);
    my ($channel, $topic);

    ($channel, $topic) = $arguments =~ /^(\S+)\s*(.*)$/;

    $channel{id $self} = $channel;
    if ($topic) {
        $topic{id $self} = $self->stripc($topic);
    } else {
        $topic{id $self} = undef;
    }
}

method run {
    my ($server)   = $self->server;
    my ($origin)   = $self->origin;
    my ($channame) = $channel{id $self};
    my ($topic)    = $topic{id $self};
    my ($channel, $message);

    unless ($origin->is_registered) {
        $origin->numeric(ERR_NOTREGISTERED);
        return;
    }

    unless ($channame) {
        $origin->numeric(ERR_NEEDMOREPARAMS, 'TOPIC');
        return;
    }

    unless ($channel = $server->find_channel($channame)) {
        $origin->numeric(ERR_NOSUCHCHANNEL, $channame);
        return;
    }

    unless (defined($topic)) {
        if ($channel->topic) {
            $origin->numeric(RPL_NOTOPIC, $channel->name);
        } else {
            $origin->numeric(RPL_TOPIC, $channel->name, $channel->topic);
        }
        return;
    }

    unless ($origin->is_on($channel) or $origin->is_supervisor) {
        $origin->numeric(ERR_NOTONCHANNEL, $channame);
        return;
    }

    unless ($origin->is_op($channel) or $origin->is_supervisor) {
        $origin->numeric(ERR_NOTONCHANNEL, $channel);
        return;
    }

    $message = "TOPIC @{[$channel->name]} :$topic";
    $channel->set_topic($topic);
    $channel->broadcast($origin->prefix($message));
}

1;


text:
from oslo_log import log as logging

from senlin.common import context
from senlin.common import exception
from senlin.common import wsgi
from senlin.db import api as db_api
from senlin.drivers import base as driver_base

LOG = logging.getLogger(__name__)

class TrustMiddleware(wsgi.Middleware):
    '''Extract trust info from request.

    The extracted information is filled into the request context.
    Senlin engine will use this information for access control.
    '''
    def _get_trust(self, ctx):
        '''List trusts with current user as the trustor.'''

        # DB table is used as a cache for the trusts.
        cred_exists = False
        res = db_api.cred_get(ctx, ctx.user, ctx.project)
        if res is not None:
            try:
                trust_id = res.cred['openstack']['trust']
                return trust_id
            except KeyError:
                # Garbage in the store, ignore it
                cred_exists = True
                pass

        params = {
            'auth_url': ctx.auth_url,
            'token': ctx.auth_token,
            'project_id': ctx.project,
            'user_id': ctx.user,
        }
        kc = driver_base.SenlinDriver().identity(params)
        service_cred = context.get_service_context()
        admin_id = kc.get_user_id(**service_cred)
        try:
            trust = kc.trust_get_by_trustor(ctx.user, admin_id, ctx.project)
        except exception.InternalError as ex:
            if ex.code == 400:
                trust = None
            else:
                raise ex
        if not trust:
            # Create a trust if no existing one found
            trust = kc.trust_create(ctx.user, admin_id, ctx.project, ctx.roles)

        # update cache
        if cred_exists:
            db_api.cred_update(ctx.user, ctx.project,
                               {'cred': {'openstack': {'trust': trust.id}}})
        else:
            values = {
                'user': ctx.user,
                'project': ctx.project,
                'cred': {'openstack': {'trust': trust.id}}
            }
            db_api.cred_create(ctx, values)

        return trust.id

    def process_request(self, req):
        trust_id = self._get_trust(req.context)
        req.context.trusts = trust_id


text:
<?php

namespace osCommerce\OM\Core\Site\Website\Application\Account\Action\Partner\Extend;

use osCommerce\OM\Core\ApplicationAbstract;

class Payment
{
    public static function execute(ApplicationAbstract $application)
    {
    }
}


text:
package ufo.hackerrank.job.numbrs.budget_shopping;

public class Solution {

    	static int budgetShopping(int n, int[] bundleQuantities, int[] bundleCosts) {

    		if (    n <= 0
    				|| bundleCosts == null || bundleQuantities == null
    				|| bundleCosts.length == 0 || bundleQuantities.length == 0
    				|| bundleCosts.length != bundleQuantities.length
    				) {
	        	return 0;
	        }

	        final int[] max = {0};

	        calculateRecursive(n, bundleCosts, bundleQuantities, max, 0, 0);

	        return max[0];
	    }

    	static void calculateRecursive(int n, int[] cost, int[] quantity, int[] max, int position, int count) {
	        if (n == 0 || position == cost.length) {
                if (count>max[0]) {
                    max[0] = count;
                }
	            return;
	        }
	        for (int i = 0; i <= n/cost[position]; i++) {
	            calculateRecursive(n - i * cost[position], cost, quantity, max, position + 1, count + i * quantity[position]);
	        }
	    }

}


text:
declare namespace Express {
    export interface Request {
        requester: Requester
    }
}

declare namespace SocketIO {
    export interface Socket {
        requester: Requester
    }
}


text:
import mock
import six

from oslo_db import exception as db_exc

from neutron.tests import base

from networking_cisco import backwards_compatibility as bc
from networking_cisco.backwards_compatibility import l3_exceptions as l3
from networking_cisco.plugins.cisco.l3.rpc import l3_router_cfg_agent_rpc_cb

# NOTE(bobmel): The scheduling functions called by some of the callback
# functions are tested in test_l3_routertype_aware_schedulers.py and in
# test_l3_router_appliance_plugin.py (specifically the class
# L3CfgAgentRouterApplianceTestCase).
class TestCfgAgentL3RouterCallbacks(base.BaseTestCase):

    def setUp(self):
        self.l3_plugin = mock.MagicMock()
        self.cb = l3_router_cfg_agent_rpc_cb.L3RouterCfgRpcCallback(
            self.l3_plugin)
        self.contextMock = mock.MagicMock()
        super(TestCfgAgentL3RouterCallbacks, self).setUp()

    def test_cfg_sync_routers_retries_on_db_errors(self):
        router_ids = ['some_router_id_1', 'some_router_id_2']
        routers = [{'id': router_ids[0]}, {'id': router_ids[1]}]
        host = 'some_host'
        hosting_device_ids = [host]
        self.l3_plugin.list_active_sync_routers_on_hosting_devices = (
            mock.MagicMock(side_effect=[db_exc.DBDeadlock, db_exc.DBDeadlock,
                                        routers]))
        result = self.cb.cfg_sync_routers(self.contextMock, host,
                                          router_ids, hosting_device_ids)
        calls = [mock.call(mock.ANY, host, router_ids, hosting_device_ids)
                 for call in [1, 2, 3]]
        (self.l3_plugin.list_active_sync_routers_on_hosting_devices
         .assert_has_calls(calls))
        self.assertEqual(
            3,
            self.l3_plugin.list_active_sync_routers_on_hosting_devices.
            call_count)
        self.assertEqual(routers, result)

    def test_cfg_sync_routers_missing_scheduling_fcn(self):
        self.l3_plugin.list_active_sync_routers_on_hosting_devices = (
            mock.MagicMock(side_effect=AttributeError))
        result = self.cb.cfg_sync_routers(self.contextMock, 'some_host')
        self.assertEqual([], result)

    def test_cfg_sync_all_hosted_routers_retries_on_db_errors(self):
        routers = [{'id': 'some_router_id_1'}, {'id': 'some_router_id_2'}]
        self.l3_plugin.list_all_routers_on_hosting_devices = mock.MagicMock(
            side_effect=[db_exc.DBDeadlock, db_exc.DBDeadlock, routers])
        result = self.cb.cfg_sync_all_hosted_routers(self.contextMock,
                                                     'some_host')
        self.assertEqual(
            3, self.l3_plugin.list_all_routers_on_hosting_devices.call_count)
        self.assertEqual(routers, result)

    def test_cfg_sync_all_hosted_routers_missing_scheduling_fcn(self):
        self.l3_plugin.list_all_routers_on_hosting_devices = mock.MagicMock(
            side_effect=AttributeError)
        result = self.cb.cfg_sync_all_hosted_routers(self.contextMock,
                                                     'some_host')
        self.assertEqual([], result)

    def test_update_floatingip_statuses_cfg_retries_on_db_errors(self):
        fip_statuses = {'fip_id_1': 'ACTIVE'}
        self.l3_plugin.update_floatingip_status = mock.MagicMock(
            side_effect=[db_exc.DBDeadlock, None])
        self.cb.update_floatingip_statuses_cfg(
            self.contextMock, 'some_router_id', fip_statuses)
        calls = [mock.call(self.contextMock, fip_id, status)
                 for fip_id, status in six.iteritems(fip_statuses)]
        self.l3_plugin.update_floatingip_status.assert_has_calls(calls)
        self.assertEqual(2, self.l3_plugin.update_floatingip_status.call_count)

    def test_update_floatingip_statuses_cfg_ignores_missing_fip(self):
        bad_fip_id = 'id_non_existent_fip'
        fip_statuses = {bad_fip_id: 'ACTIVE'}
        self.l3_plugin.update_floatingip_status = mock.MagicMock(
            side_effect=[l3.FloatingIPNotFound(floatingip_id=bad_fip_id)])
        self.l3_plugin.get_floatingips = mock.MagicMock(return_value=[])
        with mock.patch('networking_cisco.plugins.cisco.l3.rpc'
                        '.l3_router_cfg_agent_rpc_cb.LOG.debug') as log_mock:
            self.cb.update_floatingip_statuses_cfg(
                self.contextMock, 'some_router_id', fip_statuses)
        calls = [mock.call("Floating IP: %s no longer present.", bad_fip_id)]
        log_mock.assert_has_calls(calls, any_order=True)
        self.assertEqual(1, self.l3_plugin.update_floatingip_status.call_count)

    def test_update_floatingip_statuses_cfg_sets_status_down_if_no_router(
            self):
        fip_id = 'fip_id_1'
        status = 'ACTIVE'
        fip_statuses = {fip_id: status}
        self.l3_plugin.update_floatingip_status = mock.MagicMock()
        self.l3_plugin.get_floatingips = mock.MagicMock(return_value=[{
            'id': fip_id, 'router_id': None}])
        self.cb.update_floatingip_statuses_cfg(
            self.contextMock, 'some_router_id', fip_statuses)
        calls = [mock.call(self.contextMock, fip_id, status),
                 mock.call(self.contextMock, fip_id,
                           bc.constants.FLOATINGIP_STATUS_DOWN)]
        self.l3_plugin.update_floatingip_status.assert_has_calls(calls)
        self.assertEqual(2, self.l3_plugin.update_floatingip_status.call_count)

    def test_update_port_statuses_cfg_retries_on_db_errors(self):
        port_ids = ['some_port_id_1', 'some_port_id_2']
        status = 'ACTIVE'
        self.l3_plugin.update_router_port_statuses = mock.MagicMock(
            side_effect=[db_exc.DBDeadlock, db_exc.DBDeadlock, port_ids])
        self.cb.update_port_statuses_cfg(self.contextMock, port_ids, status)
        calls = [mock.call(self.contextMock, port_ids, status)
                 for call in [1, 2, 3]]
        self.assertEqual(3,
                         self.l3_plugin.update_router_port_statuses.call_count)
        self.l3_plugin.update_router_port_statuses.assert_has_calls(calls)


text:
@charset "UTF-8";
.computer.only, .mobile.only, .tablet.only {
  display: none; }

@media only screen and (min-width: 992px) {
  .computer.only {
    display: inline-block; } }

@media only screen and (min-width: 768px) and (max-width: 992px) {
  .tablet.only {
    display: inline-block; } }

@media only screen and (max-width: 768px) {
  .mobile.only {
    display: inline-block; } }

@media only screen and (min-width: 992px) {
  td.computer.only, th.computer.only {
    display: table-cell; } }

@media only screen and (min-width: 768px) and (max-width: 992px) {
  td.tablet.only, th.tablet.only {
    display: table-cell; } }

@media only screen and (max-width: 768px) {
  td.mobile.only, th.mobile.only {
    display: table-cell; } }

.panel-body.edit {
  padding: 0px; }
  .panel-body.edit textarea {
    border: 0px;
    resize: none; }

.margin-bottom {
  margin-bottom: 15px; }

.footer {
  height: 40px;
  margin-top: -40px; }

body {
  height: 100%; }

.body {
  min-height: 100%;
  margin-bottom: -40px;
  padding-bottom: 40px;
  font-family: Helvetica, Arial, "LiHei Pro", "微軟正黑體", "新細明體", sans-serif; }

/*# sourceMappingURL=core.css.map */