text:
.. _installation:

============
Installation
============

.. note::
  These installation notes are mainly for the provided PEPI implementations, running on the specified :ref:`hardware`. Configurations outside this scope may require different setup steps, but will generally have similar steps.

.. _Prerequisites:

Prerequisites
=============

Python
------
The included client and servers target Python 2.7/3.6 or newer. Other versions may work, but are untested. You can check this in your terminal:

.. code-block:: shell-session

  $ python --version
  Python 2.7.13
  $ python --version
  Python 3.6.1

If you have an old version, or you get errors about Python not being recognised, you should follow the `Python Install Guide`_.

.. _Python Install Guide: https://wiki.python.org/moin/BeginnersGuide/Download

Raspberry Pi
------------
The provided :py:class:`~raspi_server.raspi_server.RaspPiCameraServer` implementation should run on any Raspberry Pi, but has only been tested on a RPi 3. The OS distro that you use shouldn't matter, but we suggest `Raspbian`_ (or Raspbian Lite for maximum performance). You'll need a microSD card - 8GB is perfect.

Unless you plan on plugging a keyboard, mouse and monitor into your Pis, you'll probably be using SSH to control them. It is important to note that, by default, SSH comes **disabled** unless you configure the flash SD card before boot. If you plan on SSH and you're running the Pi's over Wi-fi, you'll need to add your Wi-Fi details to the SD card before boot too.

Enabling SSH
~~~~~~~~~~~~
#. Download the `Raspbian`_ image you wish to use.
#. Flash the Raspbian image to your SD card. You can use a number of tools for this, we recommend `Etcher <https://etcher.io/>`_.
#. After flashing the SD card, eject it then reinsert it. You should see it mounted in your file explorer, usually called ``BOOT``.
#. Open the SD card in your file explorer.
#. Create a new file in the root of the SD card called exactly ``ssh``, **without any file extension** to enable SSH by default on this SD card.

.. _Raspbian: https://www.raspberrypi.org/downloads/raspbian/

Configuring Wi-Fi
~~~~~~~~~~~~~~~~~
#. Open your file exporer to the root of your flashed SD card.
#. Create a new file called ``wpa_supplicant.conf``, containing the following details.  Replace SSID and PASSWORD with your intended wireless network's details (keep the quotes).

   .. code-block:: text

     network={
      ssid="SSID"
      psk="PASSWORD"
     }

#. Save the file back to the SD card and eject the card.

Camera Module
-------------
The provided :py:class:`~raspi_server.raspi_server.RaspPiCameraServer` can use any ``Camera`` implementation, but is intended for use with a Raspberry Pi Camera Module. This module needs proper configuration and installation to work.

PiCamera has provided a great `quickstart guide`_ on this process. However, if you are using SSH (ie. a terminal) to connect to your Raspberry Pi, you cannot complete the last steps in that guide as it requires a GUI.

To enable the camera through the terminal:

.. code-block:: console

  $ sudo raspi-config
  5 Interfacing Options   Configure connections to peripherals
  P1 Camera       Enable/Disable connection to the Raspberry Pi Camera
  Would you like the camera interface to be enabled? <Yes>
  The camera interface is enabled. <OK>
  <Finish>

You'll need to reboot after enabling the camera.

.. _quickstart guide: https://picamera.readthedocs.io/en/release-1.13/quickstart.html

.. _SSH Keys:

SSH Keys
--------
You may wish to look into using SSH keys. This removes the need to type in a password when logging into the Pi over SSH -- something that gets very annoying when you're wrangling dozens of them.

If you use SSH keys alongside the Raspberry Pi server implementation, you can place a copy of your private key in your cloned Git repo under ``/raspi_server/keys``. This will allow you to use the provided utility scripts to push out new versions to all servers at once, which is super useful for development work.

While we recommend using a new SSH key-pair for PEPI with the name given below, it's not mandatory but you will need modify the utility scripts.

You can generate a new SSH key from most Unix terminals with:

.. code-block:: console

   $ ssh-keygen -t rsa -C "PEPI SSH Key"

You'll be asked to save the SSH key - save it somewhere easy like your home folder under the name pepi_rsa: ``~/pepi_rsa``.

Now the problem is getting the SSH private key onto your Pi's. The easiest way is to use SSH itself (with a password this time):

.. code-block:: console

   $ cat ~/pepi_rsa.pub | ssh pi@<IP-ADDRESS> 'cat >> .ssh/authorized_keys'

You should now be able to SSH into the Pi without a password (you may be prompted about an unknown host, this is expected for the first usage):

.. code-block:: console

   $ ssh -i /path/to/your/pepi_rsa pi@<IP-ADDRESS>

Client Installation
===================
#. Clone the Git repo to get the latest version of the PEPI client:

   .. code-block:: console

      $ cd ~
      $ git clone https://github.com/curtiswest/pepi.git
      $ cd pepi
      $ ls
      LICENSE      README.rst   client       pepi.thrift   raspi_server server       test         unittest.cfg

#. Install the client's Python dependencies:

   .. code-block:: console

      $ python --version
      Python 2.7.13 (or Python 3.6.1)
      $ cd client/
      $ sudo pip install -r requirements.txt

#. Make the client executable:

   .. code-block:: console

      $ chmod +x run.py

#. Run the client using either of the commands below:

   .. code-block:: console

      $ python run.py
      INFO:werkzeug: * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
      $ ./run.py
      INFO:werkzeug: * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

#. Open your internet browser to `<http://0.0.0.0:5000/>`_ and you should see the PEPI user interface. See :ref:`Using PEPI <using-pepi>` to learn more about this interface.

Raspberry Pi Server Installation
================================

.. note::
  Make sure you've followed the relevant steps in the `Prerequisites`_ section above before proceeding.

Setting up your first Pi is the slowest. After one is set up, you can simply :ref:`duplicate that SD card <flash cards>`.

Downloading & Installing
------------------------

Firstly, we need to obtain the software:

#. SSH into your pi, e.g. ``ssh pi@<IP-ADDRESS>`` or if using `SSH Keys`_ (recommended), ``ssh -i /path/to/pepi_rsa pi@<IP-ADDRESS>``
#. Clone the latest version of the software from Git

   .. code-block:: console

      $ cd ~
      $ git clone https://github.com/curtiswest/pepi.git
      $ cd pepi
      $ ls
      LICENSE      README.rst   client       pepi.thrift   raspi_server server       test         unittest.cfg

Alternatively, if your Pi does not have internet access, you could download a `.zip of the repo` and use a flash drive to transfer it to the Pi.

.. _.zip of the repo: https://github.com/curtiswest/pepi/archive/master.zip

#. Place a copy of your SSH key in the ``raspi_server/keys`` folder if you want to use the utility scripts:

   .. code-block:: console

      $ cp /path/to/your/pepi_rsa raspi_server/keys

#. Install the server's requirements.

   .. code-block:: console

      $ python --version
      Python 2.7.13 (or Python 3.6.1)
      $ cd raspi_server/
      $ sudo pip install -r requirements.txt

#. Test that the server can launch:

   .. code-block:: console

      $ python server.py
      INFO:root:Starting RaspPiImagingServer

#. If you see the above, then the server is working fine. Stop the server with ``CTRL + C``.
#. Now, we need to setup launching the software on boot. A script is included, ``raspi_server/start_on_boot.sh``, that handles everything needed to launch the server (from the correct directory context etc). You can add this to the Pi's boot sequence by executing the following:

   .. code-block:: console

      $ cd ..
      $ pwd
      /home/pi/pepi
      $ sudo sed -i -e '$i \bash /home/pi/pepi/raspi_server/start_on_boot.sh &\n' /etc/rc.local

#. Reboot your Pi with:

   .. code-block:: console

      $ sudo shutdown -r now

#. The server should have started running automatically on boot. You can check this by looking for the ``run.py`` process:

   .. code-block:: console

      $ ssh -i /path/to/pepi_rsa pi@<IP-ADDRESS>
      $ ps aux | grep run.py
      root       740  1.5  2.5 120552 22388 ?        Sl   20:58   0:02 python run.py

#. If everything works, congratulations! If not, try walking through these steps and double-checking the commands were entered correctly. Perhaps try checking that your script was added to the boot script correctly (sometimes you may need special permissions to edit the /etc/rc.local file) with:

   .. code-block:: console

      $ cat /etc/rc.local | tail -5
      fi

      bash /home/pi/pepi/raspi_server/start_on_boot.sh &

      exit 0

.. _flash cards:

Duplicating SD cards
--------------------

.. warning::
  You will be reading and writing from raw disk partitions. **You could erase your computer** if you execute the commands below with the wrong parameters. Double-check your commands before executing.

.. note::
  It is untested whether these image files are compatible across the different Raspberry Pi Models. That is to say, it is unclear whether a Raspberry Pi 3 image can be cloned onto an SD card intended for a Raspberry Pi Zero. If you try this, please update this documentation with the results and create a `pull request`_.

.. _pull request: https://github.com/curtiswest/pepi/compare

Once you've verified that the card works exactly how you want, you can make an image of the SD card that will allow you to duplicate it onto other SD cards.

#. Insert the card into your card reader.
#. Find where the card is mounted by running ``diskutil list``. Look for the device that matches your SD card, generally by the size of the disk is easiest. Here, a 8GB SD card is inserted and appears under ``/dev/disk2/``.

   .. code-block:: console

      $ diskutil list
      /dev/disk0 (internal, physical):
         #:                       TYPE NAME                    SIZE       IDENTIFIER
         0:      GUID_partition_scheme                        *121.3 GB   disk0
         2:          Apple_CoreStorage Macintosh HD            120.5 GB   disk0s2
      /dev/disk2 (internal, physical):
         #:                       TYPE NAME                    SIZE       IDENTIFIER
         0:     FDisk_partition_scheme                        *7.9 GB     disk2
         1:             Windows_FAT_32 boot                    43.7 MB    disk2s1
         2:                      Linux                         7.9 GB     disk2s2

#. Remember the ``/dev/diskx/`` (where x = your disk's number, which above would be ``/dev/disk2/``) location where you SD card is mounted.
#. Run the following command to unmount any mounted SD card partitions:

   .. code-block:: console

      $ df -H
      Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
      /dev/disk1     112Gi   69Gi   42Gi    62% 1354336 4293612943    0%   /
      /dev/disk2s1    41Mi   21Mi   20Mi    51%       0          0  100%   /Volumes/boot
      $
      $ sudo umount /dev/diskx*
      $ df -H
      Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
      /dev/disk1     112Gi   69Gi   42Gi    62% 1354336 4293612943    0%   /

#. Now, we can image the SD card with the ``dd`` command:

   .. code-block:: console

      $ dd if=/dev/diskx/ of=~/rpi.img bs=4M
      $ ls -la ~/ | grep rpi.img
      -rw-r--r--   1 root        staff  7948206080 20 Aug 23:23 rpi.img
      $ sudo sync

   The ``rpi.img`` file contains a complete copy of the SD card. It is possible to shrink the image to copy it quicker using a `GParted`_ live boot disk, but you'll need to expand it again once copied across. If you have lots of cards to duplicate, you could look into building a `Open Source Image Duplicator`_ to allow you to duplicate several at a time.

.. _GParted: https://gparted.org/
.. _Open Source Image Duplicator: https://github.com/rockandscissor/osid/

#. Eject that SD card, and insert the new SD card you want to setup.
#. Locate where that disk is located (usually, it's the same--but not always!), in this case ``/dev/disk2/``:

   .. code-block:: console

      $ diskutil list
      /dev/disk0 (internal, physical):
         #:                       TYPE NAME                    SIZE       IDENTIFIER
         0:      GUID_partition_scheme                        *121.3 GB   disk0
         2:          Apple_CoreStorage Macintosh HD            120.5 GB   disk0s2
      /dev/disk2 (internal, physical):
         #:                       TYPE NAME                    SIZE       IDENTIFIER
         0:             Windows_FAT_32                        *7.9 GB     disk2

#. Unmount the new SD card, if it has any mounted partitions:

   .. code-block:: console

      $ sudo umount /dev/diskx*

#. Now we can copy the image back onto the SD card by simply reversing the ``dd`` command (notice the ``if`` and ``of`` arguments are now reversed):

   .. code-block:: console

      $ dd if=~/rpi.img of=/dev/diskx/ bs=4M
      $ sudo sync

#. Eject the SD card, and repeat the above 3 steps for as many cards as you need. You should be able to put these cards directly into new Raspberry Pi's and have them work just as the first did.


text:
"""Test module for the @-decorator syntax, which is version-specific"""

from cherrypy import expose, tools
from cherrypy._cpcompat import ntob

class ExposeExamples(object):

    @expose
    def no_call(self):
        return "Mr E. R. Bradshaw"

    @expose()
    def call_empty(self):
        return "Mrs. B.J. Smegma"

    @expose("call_alias")
    def nesbitt(self):
        return "Mr Nesbitt"

    @expose(["alias1", "alias2"])
    def andrews(self):
        return "Mr Ken Andrews"

    @expose(alias="alias3")
    def watson(self):
        return "Mr. and Mrs. Watson"

class ToolExamples(object):

    @expose
    @tools.response_headers(headers=[('Content-Type', 'application/data')])
    def blah(self):
        yield ntob("blah")
    # This is here to demonstrate that _cp_config = {...} overwrites
    # the _cp_config attribute added by the Tool decorator. You have
    # to write _cp_config[k] = v or _cp_config.update(...) instead.
    blah._cp_config['response.stream'] = True

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace App\Bundle\BackOfficeBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use App\Bundle\BackOfficeBundle\Entity\Demande;
use App\Bundle\BackOfficeBundle\Entity\Reclamation;

class NotificationController extends Controller
{

    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $demandes = $em->getRepository('AppBackOfficeBundle:Demande')->findBy(array('status'=>'0','notified'=>'0'));
        $reclamations = $em->getRepository('AppBackOfficeBundle:Reclamation')->findBy(array('status'=>'0','notified'=>'0'));

        return $this->render('AppBackOfficeBundle:Notification:notification.html.twig', array(
            'demandes' => $demandes,'reclamations' => $reclamations,
        ));
    }

    public function vuAction($id)
    {
    	$em = $this->getDoctrine()->getManager();

        $demande = $em->getRepository('AppBackOfficeBundle:Demande')->find($id);
        $demande->setNotified(1);
        $em->persist($demande);
		$em->flush();
		return $this->redirect($this->generateUrl('notification-admin'));

    }
    public function vureclamationAction($id)
    {
    	$em = $this->getDoctrine()->getManager();

        $reclamation = $em->getRepository('AppBackOfficeBundle:Reclamation')->find($id);
        $reclamation->setNotified(1);
        $reclamation->setConsultedAt(new \DateTime());
        $em->persist($reclamation);
		$em->flush();
		return $this->redirect($this->generateUrl('notification-admin'));

    }

      public function barrenotificationAction()
    {
        //if($this->get('security.context')->isGranted('ROLE_SUPER_USER'))
        $em = $this->getDoctrine()->getManager();
        $demandes = $em->getRepository('AppBackOfficeBundle:Demande')->findBy(array('status' => '0', 'notified' => '0'));
        $reclamations = $em->getRepository('AppBackOfficeBundle:Reclamation')->findBy(array('status' => '0', 'notified' => '0'));
        $array_demandes=array();
        $array_demandes["id"]=array(); $array_demandes["nom"]=array(); $array_demandes["prenom"]=array();$array_demandes["type"]=array();$array_demandes["createdAt"]=array();
        $array_reclamations=array();
        $array_reclamations["id"]=array(); $array_reclamations["nom"]=array(); $array_reclamations["prenom"]=array();$array_reclamations["type"]=array();$array_reclamations["createdAt"]=array();

        for($i=0 ; $i<count($demandes); $i++)
            {
            array_push($array_demandes["id"], $demandes[$i]->getId());
            array_push($array_demandes["type"], $demandes[$i]->getTypeDemande()->getLibelle());
            array_push($array_demandes["nom"], $demandes[$i]->getEtudiant()->getNom());
            array_push($array_demandes["prenom"], $demandes[$i]->getEtudiant()->getPrenom());
            array_push($array_demandes["createdAt"], $demandes[$i]->getCreatedAt()->format('d-m-Y H:i'));

          }
        for($i=0 ; $i<count($reclamations); $i++)
            {
            array_push($array_reclamations["id"], $reclamations[$i]->getId());
            array_push($array_reclamations["type"], $reclamations[$i]->getTypeReclamation()->getLibelle());
            array_push($array_reclamations["nom"], $reclamations[$i]->getEtudiant()->getNom());
            array_push($array_reclamations["prenom"], $reclamations[$i]->getEtudiant()->getPrenom());
            array_push($array_reclamations["createdAt"], $reclamations[$i]->getCreatedAt()->format('d-m-Y H:i'));

          }

        $json = json_encode(array(
            'demandes' => $array_demandes,
            'reclamations' => $array_reclamations
        ));

        $response = new Response();
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent($json);
        return $response;

}
public function todemandeAction($id){
        $em = $this->getDoctrine()->getManager();

        $demande = $em->getRepository('AppBackOfficeBundle:Demande')->find($id);
        $demande->setNotified(1);
        $em->persist($demande);
        $em->flush();

        $route = 'traiterdemande';
        if($demande->getTypeDemande()->getCode() == 'CM')
            $route = 'traiterdemandechangement';
        if($demande->getTypeDemande()->getCode() == 'ER')
            $route = 'traiterelementrefaire';
         if($demande->getTypeDemande()->getCode() == '5M')
            $route = 'traitermodulelibre';

        return $this->redirect($this->generateUrl($route,array('id' =>  trim($id) )));
    }

    public function toreclamationAction($id){

        $em = $this->getDoctrine()->getManager();

        $reclamation = $em->getRepository('AppBackOfficeBundle:Reclamation')->find($id);
        $reclamation->setNotified(1);
        $em->persist($reclamation);
        $em->flush();

       return $this->redirect($this->generateUrl('repondreReclamation',array('id' => trim($id))));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.EncapsulateField;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.EncapsulateField
{
    public class EncapsulateFieldTests : AbstractCSharpCodeActionTest
    {
        protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
            => new EncapsulateFieldRefactoringProvider();

        private static readonly Dictionary<OptionKey, object> AllOptionsOff =
            new Dictionary<OptionKey, object>
            {
                { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.FalseWithNoneEnforcement },
                { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CodeStyleOptions.FalseWithNoneEnforcement },
            };

        internal Task TestAllOptionsOffAsync(
            string initialMarkup, string expectedMarkup,
            ParseOptions parseOptions = null,
            CompilationOptions compilationOptions = null,
            int index = 0, bool compareTokens = true,
            IDictionary<OptionKey, object> options = null,
            bool withScriptOption = false)
        {
            options = options ?? new Dictionary<OptionKey, object>();
            foreach (var kvp in AllOptionsOff)
            {
                options.Add(kvp);
            }

            return TestAsync(initialMarkup, expectedMarkup,
                parseOptions, compilationOptions, index, compareTokens, options,
                withScriptOption: withScriptOption);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PrivateFieldToPropertyIgnoringReferences()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = bar;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 1);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PrivateFieldToPropertyUpdatingReferences()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = Bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task TestCodeStyle1()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = Bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            await TestAsync(text, expected,
                options: OptionsSet(
                    Tuple.Create((IOption)CSharpCodeStyleOptions.PreferExpressionBodiedProperties, true, NotificationOption.None),
                    Tuple.Create((IOption)CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, false, NotificationOption.None)));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task TestCodeStyle2()
        {
            var text = @"
class foo
{
    private int b[|a|]r;

    void baz()
    {
        var q = Bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get => bar;

        set => bar = value;
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            await TestAsync(text, expected,
                options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CodeStyleOptions.TrueWithNoneEnforcement));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PublicFieldIntoPublicPropertyIgnoringReferences()
        {
            var text = @"
class foo
{
    public int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = bar;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 1);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PublicFieldIntoPublicPropertyUpdatingReferences()
        {
            var text = @"
class foo
{
    public int b[|a|]r;

    void baz()
    {
        var q = bar;
    }
}
";

            var expected = @"
class foo
{
    private int bar;

    public int Bar
    {
        get
        {
            return bar;
        }

        set
        {
            bar = value;
        }
    }

    void baz()
    {
        var q = Bar;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task StaticPreserved()
        {
            var text = @"class Program
{
    static int [|foo|];
}";

            var expected = @"class Program
{
    static int foo;

    public static int Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task UniqueNameGenerated()
        {
            var text = @"
class Program
{
    [|int foo|];
    string Foo;
}";

            var expected = @"
class Program
{
    int foo;
    string Foo;

    public int Foo1
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task GenericField()
        {
            var text = @"
class C<T>
{
    private [|T foo|];
}";

            var expected = @"
class C<T>
{
    private T foo;

    public T Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task NewFieldNameIsUnique()
        {
            var text = @"
class foo
{
    public [|int X|];
    private string x;
}";

            var expected = @"
class foo
{
    private int x1;
    private string x;

    public int X
    {
        get
        {
            return x1;
        }

        set
        {
            x1 = value;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task RespectReadonly()
        {
            var text = @"
class foo
{
    private readonly [|int x|];
}";

            var expected = @"
class foo
{
    private readonly int x;

    public int X
    {
        get
        {
            return x;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PreserveNewAndConsiderBaseMemberNames()
        {
            var text = @"
class c
{
    protected int foo;

    protected int Foo { get; set; }
}

class d : c
{
    protected new int [|foo|];
}";

            var expected = @"
class c
{
    protected int foo;

    protected int Foo { get; set; }
}

class d : c
{
    private new int foo;

    protected int Foo1
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task EncapsulateMultiplePrivateFields()
        {
            var text = @"
class foo
{
    private int [|x, y|];

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    private int x, y;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    public int Y
    {
        get
        {
            return y;
        }

        set
        {
            y = value;
        }
    }

    void bar()
    {
        X = 1;
        Y = 2;
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task EncapsulateMultiplePrivateFields2()
        {
            var text = @"
class foo
{
    [|private int x;
    private int y|];

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    private int x;
    private int y;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    public int Y
    {
        get
        {
            return y;
        }

        set
        {
            y = value;
        }
    }

    void bar()
    {
        X = 1;
        Y = 2;
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task EncapsulateSinglePublicFieldInMultipleVariableDeclarationAndUpdateReferences()
        {
            var text = @"
class foo
{
    public int [|x|], y;

    void bar()
    {
        x = 1;
        y = 2;
    }
}";

            var expected = @"
class foo
{
    public int y;
    private int x;

    public int X
    {
        get
        {
            return x;
        }

        set
        {
            x = value;
        }
    }

    void bar()
    {
        X = 1;
        y = 2;
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694057")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task ConstFieldNoGetter()
        {
            var text = @"
class Program
{
    private const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    public static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694276")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task EncapsulateFieldNamedValue()
        {
            var text = @"
class Program
{
    private const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    public static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(694276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/694276")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PublicFieldNamed__()
        {
            var text = @"
class Program
{
    public int [|__|];
}
";

            var expected = @"
class Program
{
    private int __1;

    public int __
    {
        get
        {
            return __1;
        }

        set
        {
            __1 = value;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(695046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/695046")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AvailableNotJustOnVariableName()
        {
            var text = @"
class Program
{
    pri[||]vate int x;
}
";

            await TestActionCountAsync(text, 2);
        }

        [WorkItem(705898, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/705898")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task CopyFieldAccessibility()
        {
            var text = @"
class Program
{
    protected const int [|bar|] = 3;
}
";

            var expected = @"
class Program
{
    private const int bar = 3;

    protected static int Bar
    {
        get
        {
            return bar;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task UpdateReferencesCrossProject()
        {
            var text = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
public class C
{
    public int [|foo|];
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
        <ProjectReference>Assembly1</ProjectReference>
        <Document>
public class D
{
    void bar()
    {
        var c = new C;
        c.foo = 3;
    }
}
        </Document>
    </Project>
</Workspace>";

            var expected = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
public class C
{
    private int foo;

    public int Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}
        </Document>
    </Project>
    <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
        <ProjectReference>Assembly1</ProjectReference>
        <Document>
public class D
{
    void bar()
    {
        var c = new C;
        c.Foo = 3;
    }
}
        </Document>
    </Project>
</Workspace>";
            await TestAllOptionsOffAsync(text, expected, new CodeAnalysis.CSharp.CSharpParseOptions(), TestOptions.ReleaseExe, compareTokens: false);
        }

        [WorkItem(713269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713269")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task PreserveUnsafe()
        {
            var text = @"
class C
{
    unsafe int* [|foo|];
}
";

            var expected = @"
class C
{
    unsafe int* foo;

    public unsafe int* Foo
    {
        get
        {
            return foo;
        }

        set
        {
            foo = value;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713240")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task ConsiderReturnTypeAccessibility()
        {
            var text = @"
public class Program
{
    private State [|state|];
}

internal enum State
{
    WA
}
";

            var expected = @"
public class Program
{
    private State state;

    internal State State
    {
        get
        {
            return state;
        }

        set
        {
            state = value;
        }
    }
}

internal enum State
{
    WA
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713191")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task DoNotReferToReadOnlyPropertyInConstructor()
        {
            var text = @"
class Program
{
    public readonly int [|Field|];

    public Program(int f)
    {
        this.Field = f;
    }
}";

            var expected = @"
class Program
{
    private readonly int field;

    public Program(int f)
    {
        this.field = f;
    }

    public int Field
    {
        get
        {
            return field;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(713191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713191")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task DoNotReferToStaticReadOnlyPropertyInConstructor()
        {
            var text = @"
class Program
{
    public static readonly int [|Field|];

    static Program()
    {
        Field = 3;
    }
}";

            var expected = @"
class Program
{
    private static readonly int field;

    static Program()
    {
        field = 3;
    }

    public static int Field
    {
        get
        {
            return field;
        }
    }
}";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 0);
        }

        [WorkItem(765959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/765959")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task GenerateInTheCorrectPart()
        {
            var text = @"
partial class Program {}

partial class Program {
   private int [|x|];
}
";
            var expected = @"
partial class Program {}

partial class Program {
    private int x;

    public int X
    {
        get
        {
            return x;
        }
        set
        {
            x = value;
        }
    }
}
";
            await TestAllOptionsOffAsync(text, expected);
        }

        [WorkItem(829178, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829178")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task ErrorTolerance()
        {
            var text = @"class Program
{
    a b c [|b|]
}";

            using (var workspace = await CreateWorkspaceFromFileAsync(text, null, null))
            {
                var result = await GetCodeRefactoringAsync(workspace);
                Assert.NotNull(result);
            }
        }

        [WorkItem(834072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834072")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task DuplicateFieldErrorTolerance()
        {
            var text = @"
class Program
{
    public const string [|s|] = ""S"";
    public const string s = ""S"";
    }
";

            using (var workspace = await CreateWorkspaceFromFileAsync(text, null, null))
            {
                var result = await GetCodeRefactoringAsync(workspace);
                Assert.NotNull(result);
            }
        }

        [WorkItem(862517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/862517")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task Trivia()
        {
            var text = @"
namespace ConsoleApplication1
{
    class Program
    {
        // Some random comment
        public int myI[||]nt;
    }
}
";

            var expected = @"
namespace ConsoleApplication1
{
    class Program
    {
        // Some random comment
        private int myInt;

        public int MyInt
        {
            get
            {
                return myInt;
            }

            set
            {
                myInt = value;
            }
        }
    }
}";

            await TestAllOptionsOffAsync(text, expected);
        }

        [WorkItem(1096007, "https://github.com/dotnet/roslyn/issues/282")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task DoNotEncapsulateOutsideTypeDeclaration()
        {
            await TestMissingAsync(
@"var [|x|] = 1;");

            await TestMissingAsync(
@"namespace N
{
    var [|x|] = 1;
}");

            await TestMissingAsync(
@"enum E
{
    [|x|] = 1;
}");
        }

        [WorkItem(5524, "https://github.com/dotnet/roslyn/issues/5524")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AlwaysUseEnglishUSCultureWhenFixingVariableNames_TurkishDottedI()
        {
            using (new CultureContext("tr-TR"))
            {
                await TestAllOptionsOffAsync(
@"class C
{
    int [|iyi|];
}",
@"class C
{
    int iyi;

    public int Iyi
    {
        get
        {
            return iyi;
        }

        set
        {
            iyi = value;
        }
    }
}");
            }
        }

        [WorkItem(5524, "https://github.com/dotnet/roslyn/issues/5524")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AlwaysUseEnglishUSCultureWhenFixingVariableNames_TurkishUndottedI()
        {
            using (new CultureContext("tr-TR"))
            {
                await TestAllOptionsOffAsync(
@"class C
{
    int [|ırak|];
}",
@"class C
{
    int ırak;

    public int Irak
    {
        get
        {
            return ırak;
        }

        set
        {
            ırak = value;
        }
    }
}");
            }
        }

        [WorkItem(5524, "https://github.com/dotnet/roslyn/issues/5524")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AlwaysUseEnglishUSCultureWhenFixingVariableNames_Arabic()
        {
            using (new CultureContext("ar-EG"))
            {
                await TestAllOptionsOffAsync(
@"class C
{
    int [|بيت|];
}",
@"class C
{
    int بيت;

    public int بيت1
    {
        get
        {
            return بيت;
        }

        set
        {
            بيت = value;
        }
    }
}");
            }
        }

        [WorkItem(5524, "https://github.com/dotnet/roslyn/issues/5524")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AlwaysUseEnglishUSCultureWhenFixingVariableNames_Spanish()
        {
            using (new CultureContext("es-ES"))
            {
                await TestAllOptionsOffAsync(
@"class C
{
    int [|árbol|];
}",
@"class C
{
    int árbol;

    public int Árbol
    {
        get
        {
            return árbol;
        }

        set
        {
            árbol = value;
        }
    }
}");
            }
        }

        [WorkItem(5524, "https://github.com/dotnet/roslyn/issues/5524")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task AlwaysUseEnglishUSCultureWhenFixingVariableNames_Greek()
        {
            using (new CultureContext("el-GR"))
            {
                await TestAllOptionsOffAsync(
@"class C
{
    int [|σκύλος|];
}",
@"class C
{
    int σκύλος;

    public int Σκύλος
    {
        get
        {
            return σκύλος;
        }

        set
        {
            σκύλος = value;
        }
    }
}");
            }
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task TestEncapsulateEscapedIdentifier()
        {
            await TestAllOptionsOffAsync(@"
class C
{
    int [|@class|];
}
", @"
class C
{
    int @class;

    public int Class
    {
        get
        {
            return @class;
        }

        set
        {
            @class = value;
        }
    }
}
", compareTokens: false);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task TestEncapsulateEscapedIdentifierAndQualifiedAccess()
        {
            await TestAllOptionsOffAsync(@"
class C
{
    int [|@class|];
}
", @"
class C
{
    int @class;

    public int Class
    {
        get
        {
            return this.@class;
        }

        set
        {
            this.@class = value;
        }
    }
}
", compareTokens: false, options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error));
        }

        [WorkItem(7090, "https://github.com/dotnet/roslyn/issues/7090")]
        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField)]
        public async Task ApplyCurrentThisPrefixStyle()
        {
            await TestAllOptionsOffAsync(
@"class C
{
    int [|i|];
}",
@"class C
{
    int i;

    public int I
    {
        get
        {
            return this.i;
        }

        set
        {
            this.i = value;
        }
    }
}", options: Option(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Error));
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
        public async Task TestTuple()
        {
            var text = @"
class C
{
    private (int, string) b[|o|]b;

    void M()
    {
        var q = bob;
    }
}
";

            var expected = @"
class C
{
    private (int, string) bob;

    public (int, string) Bob
    {
        get
        {
            return bob;
        }

        set
        {
            bob = value;
        }
    }

    void M()
    {
        var q = bob;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 1, parseOptions: TestOptions.Regular, withScriptOption: true);
        }

        [Fact, Trait(Traits.Feature, Traits.Features.EncapsulateField), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
        public async Task TupleWithNames()
        {
            var text = @"
class C
{
    private (int a, string b) b[|o|]b;

    void M()
    {
        var q = bob.b;
    }
}
";

            var expected = @"
class C
{
    private (int a, string b) bob;

    public (int a, string b) Bob
    {
        get
        {
            return bob;
        }

        set
        {
            bob = value;
        }
    }

    void M()
    {
        var q = bob.b;
    }
}
";
            await TestAllOptionsOffAsync(text, expected, compareTokens: false, index: 1, parseOptions: TestOptions.Regular, withScriptOption: true);
        }
    }
}


text:
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>D&D die roller</title>
  <!-- <link rel="stylesheet" href="css/theme.css"/> -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <!-- <link href="css/bootstrap-theme.min.css" rel="stylesheet"> -->
    <link rel="stylesheet" href="css/app.css"/>
</head>
<body>
  <div ng-view></div>

  <script src="lib/jquery-1.10.2.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="lib/calculator.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>
</body>
</html>


text:
Initial Orbit Determination (IOD) module
========================================

.. graphviz::

   digraph {
      "poliastro.core.iod" -> "vallado", "izzo";
   }

\
\
The :py:mod:`poliastro.core.iod` deals with the problem of determining an orbit
being given two position vectors along it and the that the body takes to travel from
one to another.

This problem is known as Lambert's problem and many algorithms have developed to solved since
the main difficult of it is focused on numerical methods. This module contains two different
functions that enable to solve the Lambert problem.

.. automodule:: poliastro.core.iod
   :members:


text:
package cn.fiona.pet.config;

import cn.fiona.pet.security.credentials.RetryLimitHashedCredentialsMatcher;
import cn.fiona.pet.security.listener.ExpirationSessionListener;
import cn.fiona.pet.security.realm.SmartRealm;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;

import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 *
 */
//@Configuration
public class ShiroConfiguration {

    @Bean(name = "cacheManager")
    public EhCacheManager cacheManager() {
        EhCacheManager cacheManager = new EhCacheManager();
        cacheManager.setCacheManagerConfigFile("classpath:META-INF/spring/ehcache.xml");
        return cacheManager;
    }

    @Bean(name = "credentialsMatcher")
    public RetryLimitHashedCredentialsMatcher credentialsMatcher(EhCacheManager ehCacheManager) {
        RetryLimitHashedCredentialsMatcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher(ehCacheManager);
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(2);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    @Bean(name = "smartRealm")
    public SmartRealm smartRealm(RetryLimitHashedCredentialsMatcher credentialsMatcher) {
        SmartRealm smartRealm = new SmartRealm();
        smartRealm.setCredentialsMatcher(credentialsMatcher);
        smartRealm.setCachingEnabled(true);
        smartRealm.setAuthenticationCachingEnabled(true);
        smartRealm.setAuthenticationCacheName("authenticationCache");
        smartRealm.setAuthorizationCachingEnabled(true);
        smartRealm.setAuthorizationCacheName("authorizationCache");
        return smartRealm;
    }

    @Bean(name = "sessionIdCookie")
    public SimpleCookie sessionIdCookie() {
        SimpleCookie simpleCookie = new SimpleCookie("sid");
        simpleCookie.setHttpOnly(true);
        simpleCookie.setMaxAge(-1);
        return simpleCookie;
    }

    @Bean(name = "sessionIdGenerator")
    public JavaUuidSessionIdGenerator sessionIdGenerator() {
        return new JavaUuidSessionIdGenerator();
    }

    @Bean(name = "sessionValidationScheduler")
    public QuartzSessionValidationScheduler sessionValidationScheduler(DefaultSessionManager sessionManager) {
        QuartzSessionValidationScheduler quartzSessionValidationScheduler = new QuartzSessionValidationScheduler();
        quartzSessionValidationScheduler.setSessionValidationInterval(1800000);
        quartzSessionValidationScheduler.setSessionManager(sessionManager);
        return quartzSessionValidationScheduler;
    }

    @Bean(name = "sessionDAO")
    public EnterpriseCacheSessionDAO sessionDAO(JavaUuidSessionIdGenerator sessionIdGenerator) {
        EnterpriseCacheSessionDAO sessionDAO = new EnterpriseCacheSessionDAO();
        sessionDAO.setActiveSessionsCacheName("shiro-activeSessionCache");
        sessionDAO.setSessionIdGenerator(sessionIdGenerator);
        return sessionDAO;
    }

    @Bean(name = "expirationSessionListener")
    public ExpirationSessionListener expirationSessionListener() {
        return new ExpirationSessionListener();
    }

    @Bean(name = "sessionManager")
    public DefaultWebSessionManager sessionManager(SessionDAO sessionDAO, ExpirationSessionListener expirationSessionListener, SimpleCookie sessionIdCookie) {
        DefaultWebSessionManager defaultSessionManager = new DefaultWebSessionManager();
        defaultSessionManager.setGlobalSessionTimeout(1800000);
        defaultSessionManager.setDeleteInvalidSessions(true);
        defaultSessionManager.setSessionValidationSchedulerEnabled(true);
//        defaultSessionManager.setSessionValidationScheduler(sessionValidationScheduler);
        defaultSessionManager.setSessionDAO(sessionDAO);
        defaultSessionManager.setSessionListeners(ImmutableList.of(expirationSessionListener));
        defaultSessionManager.setSessionIdCookie(sessionIdCookie);
        return defaultSessionManager;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(DefaultSessionManager sessionManager, EhCacheManager cacheManager, SmartRealm smartRealm) {
        DefaultWebSecurityManager defaultSecurityManager = new DefaultWebSecurityManager();
        defaultSecurityManager.setSessionManager(sessionManager);
        defaultSecurityManager.setCacheManager(cacheManager);
        defaultSecurityManager.setRealm(smartRealm);
        return defaultSecurityManager;
    }

    @Bean(name = "methodInvokingFactoryBean")
    public MethodInvokingFactoryBean methodInvokingFactoryBean(DefaultSecurityManager securityManager) {
        MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
        methodInvokingFactoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
        methodInvokingFactoryBean.setArguments(new Object[]{securityManager});
        return methodInvokingFactoryBean;
    }

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("index.html");
        shiroFilterFactoryBean.setSuccessUrl("index.html");
        Map<String, String> filterChainDefinitionMap = Maps.newHashMap();
        filterChainDefinitionMap.put("/**", "user");
        filterChainDefinitionMap.put("/api/accounts/**", "anon");
        filterChainDefinitionMap.put("/index.html", "anon");
        filterChainDefinitionMap.put("/doc/**", "anon");
        filterChainDefinitionMap.put("/api/doc/**", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}


text:
package org.kie.services.remote.ws.deployment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;
import javax.jws.WebService;

import org.jbpm.services.api.RuntimeDataService;
import org.kie.internal.query.QueryContext;
import org.kie.remote.services.rest.DeployResourceBase;
import org.kie.remote.services.rest.ResourceBase;
import org.kie.remote.services.ws.common.ExceptionType;
import org.kie.remote.services.ws.common.WebServiceFaultInfo;
import org.kie.remote.services.ws.deployment.generated.DeploymentIdRequest;
import org.kie.remote.services.ws.deployment.generated.DeploymentInfoResponse;
import org.kie.remote.services.ws.deployment.generated.DeploymentWebService;
import org.kie.remote.services.ws.deployment.generated.DeploymentWebServiceException;
import org.kie.remote.services.ws.deployment.generated.ProcessIdsResponse;
import org.kie.services.client.serialization.jaxb.impl.deploy.JaxbDeploymentJobResult;
import org.kie.services.client.serialization.jaxb.impl.deploy.JaxbDeploymentUnit;
import org.kie.services.client.serialization.jaxb.impl.deploy.JaxbDeploymentUnitList;
import org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessDefinition;
import org.kie.services.client.serialization.jaxb.impl.process.JaxbProcessDefinitionList;
import org.kie.services.remote.ws.PaginationUtil;
import org.kie.services.shared.ServicesVersion;

// TODO: validation of input
// TODO: catchinge and translating exceptions

@WebService(
        serviceName = "DeploymentService",
        portName = "DeploymentServicePort",
        name = "DeploymentService",
        endpointInterface = "org.kie.remote.services.ws.deployment.generated.DeploymentWebService",
        targetNamespace = DeploymentWebServiceImpl.NAMESPACE)
public class DeploymentWebServiceImpl extends ResourceBase implements DeploymentWebService {

    final static String NAMESPACE = "http://services.remote.kie.org/" + ServicesVersion.VERSION + "/command";

    @Inject
    private DeployResourceBase deployBase;

    @Inject
    private RuntimeDataService runtimeDataService;

    @Override
    public DeploymentInfoResponse manage( DeploymentIdRequest request ) throws DeploymentWebServiceException {
        String strategy = request.getStrategy() == null ? null : request.getStrategy().toString();
        String mergeMode = request.getMergeMode() == null ? null : request.getMergeMode().toString();

        JaxbDeploymentJobResult jobResult= null;
        JaxbDeploymentUnit jaxbDepUnit;
        switch( request.getOperation() ) {
        case DEPLOY:
            jobResult = deployBase.submitDeployJob(request.getDeploymentId(), strategy, mergeMode, request.getDescriptor());
            jaxbDepUnit = jobResult.getDeploymentUnit();
            break;
        case UNDEPLOY:
            jobResult = deployBase.submitUndeployJob(request.getDeploymentId());
            jaxbDepUnit = jobResult.getDeploymentUnit();
            break;
        case GET_INFO:
            jaxbDepUnit = deployBase.determineStatus(request.getDeploymentId(), true);
            break;
        default:
            WebServiceFaultInfo faultInfo = new WebServiceFaultInfo();
            // TODO: faultInfo.setCorrelationId(?)
            faultInfo.setType(ExceptionType.VALIDATION);
            throw new DeploymentWebServiceException("Unknown operation type: " + request.getOperation(), faultInfo);
        }

        // TODO: check job result
        if( jobResult != null ) {

        }

        DeploymentInfoResponse response = new DeploymentInfoResponse();
        response.setOperationRequested(request.getOperation());
        response.setDeploymentUnit(jaxbDepUnit);
        return response;
    }

    @Override
    public ProcessIdsResponse getProcessDefinitionIds( DeploymentIdRequest request ) throws DeploymentWebServiceException {
        int [] pageInfo = PaginationUtil.getPageInfo(request.getPageNumber(), request.getPageSize());
        String deploymentId = request.getDeploymentId();

        List<String> processIdList = null;
        try {
            processIdList = new ArrayList<String>(runtimeDataService.getProcessIds(deploymentId, new QueryContext(pageInfo[0], pageInfo[1])));
            Collections.sort(processIdList);
        } catch( Exception e) {
            // possibly because the deployment is being modified and not fully un/deployed.. (un/deploy*ing*)
            logger.debug( "Unable to retrieve process ids for deployment '{}': {}", deploymentId, e.getMessage(), e);
        }

        ProcessIdsResponse response = new ProcessIdsResponse();
        response.setDeploymentId(deploymentId);
        if( processIdList != null ) {
            response.getProcessId().addAll(processIdList);
        }
        return response;
    }

    @Override
    public JaxbProcessDefinitionList getProcessDefinitionInfo( DeploymentIdRequest request ) throws DeploymentWebServiceException {
        List<JaxbProcessDefinition> jaxbProcDefList = new ArrayList<JaxbProcessDefinition>();
        int [] pageInfo = PaginationUtil.getPageInfo(request.getPageNumber(), request.getPageSize());

        // retrieve info
        deployBase.fillProcessDefinitionList( request.getDeploymentId(), pageInfo, getMaxNumResultsNeeded(pageInfo), jaxbProcDefList);

        // pagination
        JaxbProcessDefinitionList resultList = paginateAndCreateResult(pageInfo, jaxbProcDefList, new JaxbProcessDefinitionList());
        return resultList;
    }

    @Override
    public JaxbDeploymentUnitList getDeploymentInfo( DeploymentIdRequest request ) throws DeploymentWebServiceException {
        int [] pageInfo = PaginationUtil.getPageInfo(request.getPageNumber(), request.getPageSize());
        int maxNumResults = getMaxNumResultsNeeded(pageInfo);
        JaxbDeploymentUnitList jaxbDepUnitList = deployBase.getDeploymentList(pageInfo, maxNumResults);
        return jaxbDepUnitList;
    }

}


text:
package com.gmail.mararok.OceanDepth.Enviroment;

import java.util.Arrays;
import java.util.Random;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator;

/**
 *
 */
public class OceanDepthGenerator extends ChunkGenerator {
	private int PartsAmount;
	private int WaterPartsAmount;
	private byte[][] OceanChunk;

	private void generateOceanChunk(World oceanWorld) {
		byte[] waterPart = new byte[4096];
		Arrays.fill(waterPart, (byte)Material.STATIONARY_WATER.getId());
		PartsAmount = oceanWorld.getMaxHeight() / 16;
		OceanChunk = new byte[PartsAmount][];
		WaterPartsAmount = PartsAmount - 3;
		for (int partIndex = 0; partIndex < WaterPartsAmount;++partIndex) {
			OceanChunk[partIndex] = new byte[4096];
			System.arraycopy(waterPart,0,OceanChunk[partIndex],0,4096);
		}

		int x,z;
		int bedrockID = (byte)Material.BEDROCK.getId();
		int blockY = (0 & 0xF) << 8;
		for(x = 0; x < 16; x++) {
			for(z = 0; z < 16; z++) {
				OceanChunk[0][blockY | (z << 4) | x] = (byte) bedrockID;
			}
		}
	}

	@Override
	public Location getFixedSpawnLocation(World world, Random random) {
		return new Location(world,0,40,0);
	}
	@Override
	public byte[][] generateBlockSections(World world, Random random, int x,
			int z, BiomeGrid biomes) {
		setBiomes(biomes);
		if (OceanChunk == null) {
			generateOceanChunk(world);
		}

		byte[][] result = new byte[PartsAmount][];
		for (int partIndex = 0; partIndex < WaterPartsAmount;++partIndex) {
			result[partIndex] = new byte[4096];
			System.arraycopy(OceanChunk[partIndex],0,result[partIndex],0,4096);
		}
		return result;

	}

	void setBlock(byte[][] result, int x, int y, int z, byte blockID) {
		int shiftedY = y >> 4;
	    if (result[shiftedY] == null) {
	        result[shiftedY] = new byte[4096];
	    }
	    result[shiftedY][((y & 0xF) << 8) | (z << 4) | x] = blockID;
	}

	private void setBiomes(BiomeGrid biomes) {
		int x,z;
		for (x = 0; x < 15;++x) {
			for (z = 0; z < 15; ++z) {
				biomes.setBiome(x,z,Biome.OCEAN);
			}
		}
	}

}


text:
title: "65daysofstatic - Escape Velocity"
release_year: 2016
track_name: "Escape Velocity"
artist: "65daysofstatic"
album: "No Man's Sky: Music for an Infinite Universe"
youtube_embed_id: BcNJq2KSjGg
---


text:
ReadStats::ReadStats(unsigned readLength)
{
    seqan::resize(scoreCount, readLength);
    seqan::resize(nucCount,readLength);

        for(unsigned i = 0; i < length(scoreCount); ++i){
            seqan::resize(scoreCount[i], 255, 0); // 2nd dim is ascii chars for scores
            seqan::resize(nucCount[i], seqan::ValueSize<seqan::Dna5>::VALUE, 0);     // 2nd dim is elems of Dna5
        }

  //      std::cout << "Init readStats with readLength " << readLength << std::endl;
};

void ReadStats::collectReadStats(seqan::CharString const & id, seqan::Dna5String const & seq, seqan::CharString const  & qual)
{
    SEQAN_ASSERT_EQ(length(seq), length(qual));
    readLenCount[length(seq)]++;
    for(unsigned pos = 0; pos < length(seq); ++pos){
        ++scoreCount[pos][qual[pos]];
        ++nucCount[pos][seqan::ordValue(seq[pos])];
      //  std::cout << "In pos ["<< pos << "] " <<  seq[pos] << ":" << qual[pos] << std::endl;
    }
};

void ReadStats::toString(){
        std::cout << "== Read Stats == " << std::endl;
        for(unsigned i = 0; i < length(scoreCount); ++i)
            std::cout << scoreCount[i] << std::endl;
};

void ReadStats::collectQuantiles(seqan::String<unsigned> & cum_intervals, seqan::String<char> & quantiles, unsigned points)
{
    seqan::resize(quantiles, points);
    //we assume the sum of all counts is the last elem in cum_intervals

    unsigned total_sum = cum_intervals[length(cum_intervals)-1];

    std::cout << "Working with total sum: " << total_sum << std::endl;
};


text:
Cloudify REST Client
====================

[![Circle CI](https://circleci.com/gh/cloudify-cosmo/cloudify-rest-client/tree/master.svg?style=shield)](https://circleci.com/gh/cloudify-cosmo/cloudify-rest-client/tree/master)
[![PyPI](http://img.shields.io/pypi/dm/cloudify-rest-client.svg)](http://img.shields.io/pypi/dm/cloudify-rest-client.svg)
[![PypI](http://img.shields.io/pypi/v/cloudify-rest-client.svg)](http://img.shields.io/pypi/v/cloudify-rest-client.svg)

Client for interacting with Cloudify manager REST API.

See [http://cloudify-rest-client.readthedocs.org/en/latest/](http://cloudify-rest-client.readthedocs.org/en/latest/)


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Create Search tabs — Google Earth Enterprise 5.3.9 documentation</title>
    <link rel="stylesheet" href="../../static/bizstyle.css" type="text/css" />
    <link rel="stylesheet" href="../../static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />
    <link rel="next" title="Add custom search services" href="addCustomSearchServices.html" />
    <link rel="prev" title="Search your POI vector data or map layer data" href="searchPOIVectorMapLayerData.html" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.9 documentation »

GEE Server administration »

Previous topic

Search your POI vector data or map layer data

Next topic

Add custom search services

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Create Search tabs¶

You can create search tabs in GEE to add search services that let
you query GEE Server using Google Earth Enterprise Client (EC) or
a Google Map (http://maps.google.com/).

Search tabs allow Google Earth EC or Google Maps users to:

Replace the standard search tabs in Google Earth EC.

Search 2D or 3D databases created with Google Earth Enterprise
Fusion.

Access other databases not related to Google Earth Enterprise
Fusion (such as geocoders, Google Search Appliance, and so on).

Access external search servers (such as a real estate search).

For example, if you have a database of property locations that
contains specific information that your users need, you can create
a search tab called Property Search and configure it to search
for locations in your property database, even if that database is
stored on another server.

You can also create search tabs with multiple fields. For
example, you might create a Driving Directions search tab with
From and To labels in the Create Search Definition dialog. You
populate the URL field with the custom service that returns the
actual directions.

The Search tabs page of Google Earth Enterprise Server allows
you to pre-configure the search tabs to be used for any Fusion
database. You define all of the search tabs using the
Search tabs page, and then you select one or more search tabs
for a specific database when you publish it using the Databases
page. See Publish databases and portables for details.

Define a new search tab

To define a new search tab:

In the GEE Server Admin console,
click Search tabs.

Click Create new. The Create Search Definition dialog appears.

Enter a unique Name for your search tab.

Enter a Label that will display as the name of the search tab in the client.

Provide a URL.

If you want to reference a Google Earth Enterprise Server plug-in for the
search tab, enter the name of the plug-in. The following plug-ins are available:

POISearch

/gesearch/FederatedSearch

/gesearch/CoordinateSearch

/gesearch/PlacesSearch

/gesearch/ExampleSearch

Optionally provide additional query parameters.
The syntax is key1=value1&key2;=value2. For example,
flyToFirstElement=true&displayKeys;=location flies to
the first element of your search results and displays the
Location key in the results. Google Earth EC must be able to
understand and respond to these key/value pairs, so you must
be very familiar with your search application to use this
field.

Warning

Any web service, servlet, or web application
you configure the search tabs to query must return valid KML
to Google Earth EC. For Google Maps, it must return valid
JavaScript in the specified structure.

Optionally provide additional config parameters.
Specify the following field parameters:

Label: Label of the search box.

Suggestion: Suggestion to the user of what to search for.

Key: The parameter name that the value in the text
box will be assigned when the search is submitted.

Optionally click add field to add another set of search
field parameters.

Click Save.

The search tab is ready for you to add to your database. See
Publish databases and portables for details.

Customize search tab style in Google Earth EC

You may want to customize the appearance of the search tabs
as they display in Google Earth EC. You can edit
/opt/google/gehttpd/htdocs/earth/supplemental_ui.html to
change the style and various elements for the search form
that appears. The changes you make are then included in the
database at the time you publish.

To customize the style and elements of a search tab:

Make a backup copy of
/opt/google/gehttpd/htdocs/earth/supplemental_ui.html
and open your renamed file for edit.

In the HTML code, update the style and display elements
to customize your search form.

Save the HTML file with the name you want to use for your
search tabs, e.g.,
/opt/google/gehttpd/htdocs/earth/search_supplemental_ui_MySearchTab.html.

Publish your database with the selected search tab(s).

View your database in Google Earth EC.

Search tabs now appear with the style and element
settings that you customized.

Navigation

          index

          next |

          previous |

Google Earth Enterprise 5.3.9 documentation »

GEE Server administration »

        © Copyright 2021, Open GEE Contributors.
      Created using Sphinx 1.7.5.


text:
<?php

namespace PushEDX\Chat;

use Carbon\Carbon;
use Flarum\User\User;
use Flarum\Database\AbstractModel;

/**
 * @property int        $id
 *
 * @property string     $message
 *
 * @property int        $actorId
 * @property User       $actor
 *
 * @property Carbon     $created_at
 */
class Message extends AbstractModel
{
    protected $table = 'pushedx_messages';

    /**
     * Create a new message.
     *
     * @param string $message
     * @param int $actorId
     * @param Carbon $created_at
     */
    public static function build($message, $actorId, $created_at)
    {
        $msg = new static;

        $msg->message = $message;
        $msg->actorId = $actorId;
        $msg->created_at = $created_at;

        return $msg;
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function actor()
    {
        return $this->belongsTo(User::class, 'actorId');
    }
}


text:
import unittest

from django.template import TemplateSyntaxError
from django.test import TestCase as DjangoTestCase

from django_comments_xtd.templatetags.comments_xtd import render_markup_comment, formatter

@unittest.skipIf(not formatter, "This test case needs django-markup, docutils and markdown installed to be run")
class RenderMarkupValueFilterTestCase(DjangoTestCase):

    def test_render_markup_comment_in_markdown(self):
        comment = r'''#!markdown
An [example](http://url.com/ "Title")'''
        result = render_markup_comment(comment)
        self.assertEqual(result,
                         '
An example
')

    def test_render_markup_comment_in_restructuredtext(self):
        comment = r'''#!restructuredtext
A fibonacci generator in Python, taken from `LiteratePrograms <http://en.literateprograms.org/Fibonacci_numbers_%28Python%29>`_::

    def fib():
        a, b = 0, 1
        while 1:
            yield a
            a, b = b, a + b'''
        result = render_markup_comment(comment)
        self.assertEqual(result,
                         r'''
A fibonacci generator in Python, taken from LiteratePrograms:

def fib():
    a, b = 0, 1
    while 1:
        yield a
        a, b = b, a + b

''')

@unittest.skipIf(formatter, "This test case needs django-markup or docutils or markdown not installed to be run")
class MarkupNotAvailableTestCase(DjangoTestCase):

    def test_render_markup_comment(self):
        comment = r'''#!markdown
An [example](http://url.com/ "Title")'''
        render_markup_comment, comment
        self.assertRaises(TemplateSyntaxError, render_markup_comment, comment)


text:
/**
 * User: Alexander Slesarenko
 * Date: 12/15/13
 */
package scalan.meta

import java.io.File
import com.typesafe.scalalogging.slf4j.LazyLogging
import scalan.util.FileUtil
import ScalanAst._

class EntityManagement(val config: CodegenConfig) extends ScalanParsersEx with LazyLogging {

  case class EntityManager(name: String, file: File, entityDef: SEntityModuleDef, config: CodegenConfig)

  protected val entities = config.entityFiles.flatMap { f =>
    val file = FileUtil.file(config.srcPath, f)
    try {
      val d = parseEntityModule(file)
      Some(new EntityManager(d.name, file, d, config))
    } catch {
      case e: Exception =>
        logger.error(s"Failed to parse file at $file (relative to ${FileUtil.currentWorkingDir})", e)
        None
    }
  }

  def getCodegen: MetaCodegen = ScalanCodegen

  def createFileGenerator(codegen: MetaCodegen, module: SEntityModuleDef, config: CodegenConfig) =
    new EntityFileGenerator(codegen, module, config)

  def generateAll() = {
    entities.foreach { man =>
      println(s"  generating ${man.file}")
      val g = createFileGenerator(getCodegen, man.entityDef, man.config)
      val implCode = g.getImplFile
      saveEntity(man.file, implCode)
    }
  }

  def saveEntity(file: File, implCode: String) = {
    val fileName = file.getName.split('.')(0)
    val folder = file.getParentFile
    val implFile = FileUtil.file(folder, "impl", s"${fileName}Impl.scala")

    implFile.mkdirs()

    FileUtil.write(implFile, implCode)
  }

}


text:
import datetime
import uuid
import importlib

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.renderers import JSON
from pyramid.security import NO_PERMISSION_REQUIRED

from channelstream import patched_json as json
from channelstream.wsgi_views.wsgi_security import APIFactory

def datetime_adapter(obj, request):
    return obj.isoformat()

def uuid_adapter(obj, request):
    return str(obj)

def make_app(server_config):
    config = Configurator(
        settings=server_config, root_factory=APIFactory, default_permission="access"
    )
    config.include("pyramid_jinja2")
    module_, class_ = server_config["signature_checker"].rsplit(".", maxsplit=1)
    signature_checker_cls = getattr(importlib.import_module(module_), class_)
    config.registry.signature_checker = signature_checker_cls(server_config["secret"])
    authn_policy = AuthTktAuthenticationPolicy(
        server_config["cookie_secret"], max_age=2592000
    )
    authz_policy = ACLAuthorizationPolicy()

    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    json_renderer = JSON(serializer=json.dumps, indent=4)
    json_renderer.add_adapter(datetime.datetime, datetime_adapter)
    json_renderer.add_adapter(uuid.UUID, uuid_adapter)
    config.add_renderer("json", json_renderer)

    config.add_subscriber(
        "channelstream.subscribers.handle_new_request", "pyramid.events.NewRequest"
    )
    config.add_request_method("channelstream.utils.handle_cors", "handle_cors")
    config.include("channelstream.wsgi_views")
    config.scan("channelstream.wsgi_views.server")
    config.scan("channelstream.wsgi_views.error_handlers")
    config.scan("channelstream.events")

    config.include("pyramid_apispec.views")
    config.pyramid_apispec_add_explorer(
        spec_route_name="openapi_spec",
        script_generator="channelstream.utils:swagger_ui_script_template",
        permission="admin",
        route_args={
            "factory": "channelstream.wsgi_views.wsgi_security:AdminAuthFactory"
        },
    )
    app = config.make_wsgi_app()
    return app


text:
package privatelink

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CreateVpcEndpoint invokes the privatelink.CreateVpcEndpoint API synchronously
func (client *Client) CreateVpcEndpoint(request *CreateVpcEndpointRequest) (response *CreateVpcEndpointResponse, err error) {
	response = CreateCreateVpcEndpointResponse()
	err = client.DoAction(request, response)
	return
}

// CreateVpcEndpointWithChan invokes the privatelink.CreateVpcEndpoint API asynchronously
func (client *Client) CreateVpcEndpointWithChan(request *CreateVpcEndpointRequest) (<-chan *CreateVpcEndpointResponse, <-chan error) {
	responseChan := make(chan *CreateVpcEndpointResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CreateVpcEndpoint(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CreateVpcEndpointWithCallback invokes the privatelink.CreateVpcEndpoint API asynchronously
func (client *Client) CreateVpcEndpointWithCallback(request *CreateVpcEndpointRequest, callback func(response *CreateVpcEndpointResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CreateVpcEndpointResponse
		var err error
		defer close(result)
		response, err = client.CreateVpcEndpoint(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CreateVpcEndpointRequest is the request struct for api CreateVpcEndpoint
type CreateVpcEndpointRequest struct {
	*requests.RpcRequest
	ClientToken               string                   `position:"Query" name:"ClientToken"`
	SecurityGroupId           *[]string                `position:"Query" name:"SecurityGroupId"  type:"Repeated"`
	EndpointType              string                   `position:"Query" name:"EndpointType"`
	Zone                      *[]CreateVpcEndpointZone `position:"Query" name:"Zone"  type:"Repeated"`
	ServiceName               string                   `position:"Query" name:"ServiceName"`
	DryRun                    requests.Boolean         `position:"Query" name:"DryRun"`
	EndpointDescription       string                   `position:"Query" name:"EndpointDescription"`
	ZonePrivateIpAddressCount requests.Integer         `position:"Query" name:"ZonePrivateIpAddressCount"`
	ProtectedEnabled          requests.Boolean         `position:"Query" name:"ProtectedEnabled"`
	EndpointName              string                   `position:"Query" name:"EndpointName"`
	VpcId                     string                   `position:"Query" name:"VpcId"`
	ServiceId                 string                   `position:"Query" name:"ServiceId"`
}

// CreateVpcEndpointZone is a repeated param struct in CreateVpcEndpointRequest
type CreateVpcEndpointZone struct {
	VSwitchId string `name:"VSwitchId"`
	ZoneId    string `name:"ZoneId"`
	Ip        string `name:"ip"`
}

// CreateVpcEndpointResponse is the response struct for api CreateVpcEndpoint
type CreateVpcEndpointResponse struct {
	*responses.BaseResponse
	EndpointDomain         string `json:"EndpointDomain" xml:"EndpointDomain"`
	RequestId              string `json:"RequestId" xml:"RequestId"`
	CreateTime             string `json:"CreateTime" xml:"CreateTime"`
	EndpointBusinessStatus string `json:"EndpointBusinessStatus" xml:"EndpointBusinessStatus"`
	EndpointDescription    string `json:"EndpointDescription" xml:"EndpointDescription"`
	ServiceId              string `json:"ServiceId" xml:"ServiceId"`
	EndpointStatus         string `json:"EndpointStatus" xml:"EndpointStatus"`
	VpcId                  string `json:"VpcId" xml:"VpcId"`
	EndpointName           string `json:"EndpointName" xml:"EndpointName"`
	ServiceName            string `json:"ServiceName" xml:"ServiceName"`
	Bandwidth              int64  `json:"Bandwidth" xml:"Bandwidth"`
	EndpointId             string `json:"EndpointId" xml:"EndpointId"`
	ConnectionStatus       string `json:"ConnectionStatus" xml:"ConnectionStatus"`
}

// CreateCreateVpcEndpointRequest creates a request to invoke CreateVpcEndpoint API
func CreateCreateVpcEndpointRequest() (request *CreateVpcEndpointRequest) {
	request = &CreateVpcEndpointRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Privatelink", "2020-04-15", "CreateVpcEndpoint", "privatelink", "openAPI")
	request.Method = requests.POST
	return
}

// CreateCreateVpcEndpointResponse creates a response to parse from CreateVpcEndpoint response
func CreateCreateVpcEndpointResponse() (response *CreateVpcEndpointResponse) {
	response = &CreateVpcEndpointResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}