text:
package org.ice4j.socket;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * Represents a <tt>DatagramSocket</tt> which allows filtering
 * <tt>DatagramPacket</tt>s it reads from the network using
 * <tt>DatagramPacketFilter</tt>s so that the <tt>DatagramPacket</tt>s do not
 * get received through it but through associated
 * <tt>MultiplexedDatagramSocket</tt>s.
 *
 * @author Lyubomir Marinov
 */
public class MultiplexingDatagramSocket
    extends SafeCloseDatagramSocket
{
    /**
     * The {@code MultiplexingXXXSocketSupport} which implements functionality
     * common to TCP and UDP sockets in order to facilitate implementers such as
     * this instance.
     */
    private final MultiplexingXXXSocketSupport<MultiplexedDatagramSocket>
        multiplexingXXXSocketSupport
            = new MultiplexingXXXSocketSupport<MultiplexedDatagramSocket>()
            {
                /**
                 * {@inheritDoc}
                 */
                @Override
                protected MultiplexedDatagramSocket createSocket(
                        DatagramPacketFilter filter)
                    throws SocketException
                {
                    return
                        new MultiplexedDatagramSocket(
                                MultiplexingDatagramSocket.this,
                                filter);
                }

                /**
                 * {@inheritDoc}
                 */
                @Override
                protected void doReceive(DatagramPacket p)
                    throws IOException
                {
                    multiplexingXXXSocketSupportDoReceive(p);
                }

                /**
                 * {@inheritDoc}
                 */
                @Override
                protected void doSetReceiveBufferSize(int receiveBufferSize)
                    throws SocketException
                {
                    multiplexingXXXSocketSupportDoSetReceiveBufferSize(
                            receiveBufferSize);
                }

                /**
                 * {@inheritDoc}
                 */
                @Override
                protected List<DatagramPacket> getReceived()
                {
                    return received;
                }

                /**
                 * {@inheritDoc}
                 */
                @Override
                protected List<DatagramPacket> getReceived(
                        MultiplexedDatagramSocket socket)
                {
                    return socket.received;
                }
            };

    /**
     * The list of <tt>DatagramPacket</tt>s to be received through this
     * <tt>DatagramSocket</tt> i.e. not accepted by the list of
     * {@link MultiplexedDatagramSocket} of this instance at the time of the
     * reading from the network.
     */
    private final List<DatagramPacket> received
        = new SocketReceiveBuffer()
        {
            private static final long serialVersionUID
                = 3125772367019091216L;

            @Override
            public int getReceiveBufferSize()
                throws SocketException
            {
                return MultiplexingDatagramSocket.this.getReceiveBufferSize();
            }
        };

    /**
     * Buffer variable for storing the SO_TIMEOUT value set by the
     * last <tt>setSoTimeout()</tt> call. Although not strictly needed,
     * getting the locally stored value as opposed to retrieving it
     * from a parent <tt>getSoTimeout()</tt> call seems to
     * significantly improve efficiency, at least on some platforms.
     */
    private int soTimeout = 0;

    /**
     * Whether this socket should be kept open even when all of its
     * {@link MultiplexedDatagramSocket} are closed (if the value is
     * {@code true}), or it should be closed when the last of its
     * {@link MultiplexedDatagramSocket} is closed (if the value is
     * {@code false}).
     */
    private final boolean persistent;

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering and binds it to any available
     * port on the local host machine. The socket will be bound to the wildcard
     * address, an IP address chosen by the kernel.
     *
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket()
     */
    public MultiplexingDatagramSocket()
        throws SocketException
    {
        this(false);
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering and binds it to any available
     * port on the local host machine. The socket will be bound to the wildcard
     * address, an IP address chosen by the kernel.
     *
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @param persistent whether this socket should be kept open after all of
     * its {@link MultiplexedDatagramSocket}s are closed.
     * @see DatagramSocket#DatagramSocket()
     */
    public MultiplexingDatagramSocket(boolean persistent)
        throws SocketException
    {
        this.persistent = persistent;
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering on a specific
     * <tt>DatagramSocket</tt>.
     *
     * @param delegate the <tt>DatagramSocket</tt> on which
     * <tt>DatagramPacket</tt> filtering is to be enabled by the new instance
     * @throws SocketException if anything goes wrong while initializing the new
     * instance
     */
    public MultiplexingDatagramSocket(DatagramSocket delegate)
        throws SocketException
    {
        this(delegate, false);
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering on a specific
     * <tt>DatagramSocket</tt>.
     *
     * @param delegate the <tt>DatagramSocket</tt> on which
     * <tt>DatagramPacket</tt> filtering is to be enabled by the new instance
     * @param persistent whether this socket should be kept open after all of
     * its {@link MultiplexedDatagramSocket}s are closed.
     * @throws SocketException if anything goes wrong while initializing the new
     * instance
     */
    public MultiplexingDatagramSocket(
            DatagramSocket delegate,
            boolean persistent)
        throws SocketException
    {
        super(delegate);

        this.persistent = persistent;
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering and binds it to the specified
     * port on the local host machine. The socket will be bound to the wildcard
     * address, an IP address chosen by the kernel.
     *
     * @param port the port to bind the new socket to
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(int)
     */
    public MultiplexingDatagramSocket(int port)
        throws SocketException
    {
        this(port, false);
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering and binds it to the specified
     * port on the local host machine. The socket will be bound to the wildcard
     * address, an IP address chosen by the kernel.
     *
     * @param port the port to bind the new socket to
     * @param persistent whether this socket should be kept open after all of
     * its {@link MultiplexedDatagramSocket}s are closed.
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(int)
     */
    public MultiplexingDatagramSocket(int port, boolean persistent)
        throws SocketException
    {
        super(port);

        this.persistent = persistent;
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering, bound to the specified local
     * address. The local port must be between 0 and 65535 inclusive. If the IP
     * address is 0.0.0.0, the socket will be bound to the wildcard address, an
     * IP address chosen by the kernel.
     *
     * @param port the local port to bind the new socket to
     * @param laddr the local address to bind the new socket to
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(int, InetAddress)
     */
    public MultiplexingDatagramSocket(int port, InetAddress laddr)
        throws SocketException
    {
        this(port, laddr, false);
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering, bound to the specified local
     * address. The local port must be between 0 and 65535 inclusive. If the IP
     * address is 0.0.0.0, the socket will be bound to the wildcard address, an
     * IP address chosen by the kernel.
     *
     * @param port the local port to bind the new socket to
     * @param laddr the local address to bind the new socket to
     * @param persistent whether this socket should be kept open after all of
     * its {@link MultiplexedDatagramSocket}s are closed.
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(int, InetAddress)
     */
    public MultiplexingDatagramSocket(
            int port,
            InetAddress laddr,
            boolean persistent)
        throws SocketException
    {
        super(port, laddr);

        this.persistent = persistent;
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering, bound to the specified local
     * socket address.
     *

     * If the specified local socket address is <tt>null</tt>, creates an
     * unbound socket.
     *

     *
     * @param bindaddr local socket address to bind, or <tt>null</tt> for an
     * unbound socket
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(SocketAddress)
     */
    public MultiplexingDatagramSocket(SocketAddress bindaddr)
        throws SocketException
    {
        this(bindaddr, false);
    }

    /**
     * Initializes a new <tt>MultiplexingDatagramSocket</tt> instance which is
     * to enable <tt>DatagramPacket</tt> filtering, bound to the specified local
     * socket address.
     *

     * If the specified local socket address is <tt>null</tt>, creates an
     * unbound socket.
     *

     *
     * @param bindaddr local socket address to bind, or <tt>null</tt> for an
     * unbound socket
     * @param persistent whether this socket should be kept open after all of
     * its {@link MultiplexedDatagramSocket}s are closed.
     * @throws SocketException if the socket could not be opened, or the socket
     * could not bind to the specified local port
     * @see DatagramSocket#DatagramSocket(SocketAddress)
     */
    public MultiplexingDatagramSocket(
                SocketAddress bindaddr,
                boolean persistent)
        throws SocketException
    {
        super(bindaddr);

        this.persistent = persistent;
    }

    /**
     * Closes a specific <tt>MultiplexedDatagramSocket</tt> which filters
     * <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt>.
     *
     * @param multiplexed the <tt>MultiplexedDatagramSocket</tt> to close
     */
    void close(MultiplexedDatagramSocket multiplexed)
    {
        if (!multiplexingXXXSocketSupport.close(multiplexed)
            && !persistent)
        {
            close();
        }
    }

    /**
     * Gets a <tt>MultiplexedDatagramSocket</tt> which filters
     * <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using a
     * specific <tt>DatagramPacketFilter</tt>. If such a
     * <tt>MultiplexedDatagramSocket</tt> does not exist in this instance, it is
     * created.
     *
     * @param filter the <tt>DatagramPacketFilter</tt> to get a
     * <tt>MultiplexedDatagramSocket</tt> for
     * @return a <tt>MultiplexedDatagramSocket</tt> which filters
     * <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using the
     * specified <tt>filter</tt>
     * @throws SocketException if creating the
     * <tt>MultiplexedDatagramSocket</tt> for the specified <tt>filter</tt>
     * fails
     */
    public MultiplexedDatagramSocket getSocket(DatagramPacketFilter filter)
        throws SocketException
    {
        return getSocket(filter, /* create */ true);
    }

    /**
     * Gets a <tt>MultiplexedDatagramSocket</tt> which filters
     * <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using a
     * specific <tt>DatagramPacketFilter</tt>. If <tt>create</tt> is true and
     * such a <tt>MultiplexedDatagramSocket</tt> does not exist in this
     * instance, it is created.
     *
     * @param filter the <tt>DatagramPacketFilter</tt> to get a
     * <tt>MultiplexedDatagramSocket</tt> for
     * @param create whether or not to create a
     * <tt>MultiplexedDatagramSocket</tt> if this instance does not already have
     * a socket for the given <tt>filter</tt>.
     * @return a <tt>MultiplexedDatagramSocket</tt> which filters
     * <tt>DatagramPacket</tt>s away from this <tt>DatagramSocket</tt> using the
     * specified <tt>filter</tt>
     * @throws SocketException if creating the
     * <tt>MultiplexedDatagramSocket</tt> for the specified <tt>filter</tt>
     * fails.
     */
    public MultiplexedDatagramSocket getSocket(
            DatagramPacketFilter filter,
            boolean create)
        throws SocketException
    {
        return multiplexingXXXSocketSupport.getSocket(filter, create);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int getSoTimeout()
    {
        return soTimeout;
    }

    /**
     * Implements {@link MultiplexingXXXSocketSupport#doReceive(DatagramPacket)}
     * on behalf of {@link #multiplexingXXXSocketSupport}. Receives a
     * {@code DatagramPacket} from this socket.
     *
     * @param p the {@code DatagramPacket} into which to place the incoming data
     * @throws IOException if an I/O error occurs
     */
    private void multiplexingXXXSocketSupportDoReceive(DatagramPacket p)
        throws IOException
    {
        super.receive(p);
    }

    /**
     * Implements
     * {@link MultiplexingXXXSocketSupport#doSetReceiveBufferSize(int)} on
     * behalf of {@link #multiplexingXXXSocketSupport}. Sets the
     * {@code SO_RCVBUF} option to the specified value for this
     * {@code DatagramSocket}. The {@code SO_RCVBUF} option is used by the
     * network implementation as a hint to size the underlying network I/O
     * buffers. The {@code SO_RCVBUF} setting may also be used by the network
     * implementation to determine the maximum size of the packet that can be
     * received on this socket.
     *
     * @param receiveBufferSize the size to which to set the receive buffer size
     * @throws SocketException if there is an error in the underlying protocol,
     * such as a UDP error
     */
    private void multiplexingXXXSocketSupportDoSetReceiveBufferSize(
            int receiveBufferSize)
        throws SocketException
    {
        super.setReceiveBufferSize(receiveBufferSize);
    }

    /**
     * Receives a datagram packet from this socket. The <tt>DatagramPacket</tt>s
     * returned by this method do not match any of the
     * <tt>DatagramPacketFilter</tt>s of the <tt>MultiplexedDatagramSocket</tt>s
     * associated with this instance at the time of their receipt. When this
     * method returns, the <tt>DatagramPacket</tt>'s buffer is filled with the
     * data received. The datagram packet also contains the sender's IP address,
     * and the port number on the sender's machine.
     *

     * This method blocks until a datagram is received. The <tt>length</tt>
     * field of the datagram packet object contains the length of the received
     * message. If the message is longer than the packet's length, the message
     * is truncated.
     *

     *
     * @param p the <tt>DatagramPacket</tt> into which to place the incoming
     * data
     * @throws IOException if an I/O error occurs
     * @throws SocketTimeoutException if <tt>setSoTimeout(int)</tt> was
     * previously called and the timeout has expired
     * @see DatagramSocket#receive(DatagramPacket)
     */
    @Override
    public void receive(DatagramPacket p)
        throws IOException
    {
        multiplexingXXXSocketSupport.receive(received, p, soTimeout);
    }

    /**
     * Receives a <tt>DatagramPacket</tt> from this <tt>DatagramSocket</tt> upon
     * request from a specific <tt>MultiplexedDatagramSocket</tt>.
     *
     * @param multiplexed the <tt>MultiplexedDatagramSocket</tt> which requests
     * the receipt of a <tt>DatagramPacket</tt> from the network
     * @param p the <tt>DatagramPacket</tt> to receive the data from the network
     * @throws IOException if an I/O error occurs
     * @throws SocketTimeoutException if <tt>setSoTimeout(int)</tt> was
     * previously called on <tt>multiplexed</tt> and the timeout has expired
     */
    void receive(MultiplexedDatagramSocket multiplexed, DatagramPacket p)
        throws IOException
    {
        multiplexingXXXSocketSupport.receive(
                multiplexed.received,
                p,
                multiplexed.getSoTimeout());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setReceiveBufferSize(int receiveBufferSize)
        throws SocketException
    {
        multiplexingXXXSocketSupport.setReceiveBufferSize(receiveBufferSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setSoTimeout(int timeout)
        throws SocketException
    {
        super.setSoTimeout(timeout);

        soTimeout = timeout;
    }
}


text:
namespace {

void AddHitTestRegion(FuzzedDataProvider* fuzz,
                      std::vector<viz::AggregatedHitTestRegion>* regions,
                      std::vector<viz::FrameSinkId>* frame_sink_ids,
                      const uint32_t depth = 0) {
  constexpr uint32_t kMaxDepthAllowed = 25;
  if (fuzz->remaining_bytes() < sizeof(viz::AggregatedHitTestRegion))
    return;
  viz::FrameSinkId frame_sink_id(fuzz->ConsumeIntegralInRange<uint32_t>(
                                     1, std::numeric_limits<uint32_t>::max()),
                                 fuzz->ConsumeIntegralInRange<uint32_t>(
                                     1, std::numeric_limits<uint32_t>::max()));
  uint32_t flags = fuzz->ConsumeIntegral<uint32_t>();
  // The reasons' value is kNotAsyncHitTest if the flag's value is kHitTestAsk.
  uint32_t reasons = (flags & viz::HitTestRegionFlags::kHitTestAsk)
                         ? fuzz->ConsumeIntegralInRange<uint32_t>(
                               1, std::numeric_limits<uint32_t>::max())
                         : viz::AsyncHitTestReasons::kNotAsyncHitTest;
  gfx::Rect rect(
      fuzz->ConsumeIntegralInRange<int>(std::numeric_limits<int>::min() + 1,
                                        std::numeric_limits<int>::max()),
      fuzz->ConsumeIntegralInRange<int>(std::numeric_limits<int>::min() + 1,
                                        std::numeric_limits<int>::max()),
      fuzz->ConsumeIntegral<int>(), fuzz->ConsumeIntegral<int>());
  int32_t child_count =
      depth < kMaxDepthAllowed ? fuzz->ConsumeIntegralInRange(0, 10) : 0;
  gfx::Transform transform;
  if (fuzz->ConsumeBool() && fuzz->remaining_bytes() >= sizeof(transform)) {
    std::vector<uint8_t> matrix_bytes =
        fuzz->ConsumeBytes<uint8_t>(sizeof(gfx::Transform));
    memcpy(&transform, matrix_bytes.data(), matrix_bytes.size());
  }
  regions->emplace_back(frame_sink_id, flags, rect, transform, child_count,
                        reasons);
  // Always add the first frame sink id, because the root needs to be in the
  // list of FrameSinkId.
  if (regions->size() == 1 || fuzz->ConsumeBool())
    frame_sink_ids->push_back(frame_sink_id);
  while (child_count-- > 0)
    AddHitTestRegion(fuzz, regions, frame_sink_ids, depth + 1);
}

class Environment {
 public:
  Environment() { base::CommandLine::Init(0, nullptr); }
};

}  // namespace

extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t num_bytes) {
  // Initialize the environment only once.
  static Environment environment;

  // If there isn't enough memory to have a single AggregatedHitTestRegion, then
  // skip.
  if (num_bytes < sizeof(viz::AggregatedHitTestRegion))
    return 0;

  // Create the list of AggregatedHitTestRegion objects.
  std::vector<viz::AggregatedHitTestRegion> regions;
  std::vector<viz::FrameSinkId> frame_sink_ids;
  FuzzedDataProvider fuzz(data, num_bytes);
  AddHitTestRegion(&fuzz, &regions, &frame_sink_ids);

  // Create the HitTestQuery and send hit-test data.
  viz::HitTestQuery query;
  query.OnAggregatedHitTestRegionListUpdated(regions);

  for (float x = 0; x < 1000.; x += 10) {
    for (float y = 0; y < 1000.; y += 10) {
      gfx::PointF location(x, y);
      query.FindTargetForLocation(viz::EventSource::MOUSE, location);
      query.TransformLocationForTarget(frame_sink_ids, location, &location);
    }
  }

  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
id: 205
title: 'Review: Trik Internetan Ngebut dengan Tri Tanpa Kuota'
date: 2011-10-11T20:27:00+00:00
author: Ihsan Ariswanto
layout: post
guid: /uncategorized/review-trik-internetan-ngebut-dengan-tri-tanpa-kuota/
permalink: /informasi/tips-dan-trik/review-trik-internetan-ngebut-dengan-tri-tanpa-kuota/
blogger_blog:
  - ihsanariswanto.blogspot.com
blogger_author:
  - ihsan
blogger_permalink:
  - /2011/10/review-trik-internetan-ngebut-dengan.html
blogger_internal:
  - /feeds/811343025317713881/posts/default/1001466738522419403
categories:
  - Tips dan Trik
tags:
  - Komputer
---

  Beberapa minggu yang lalu, saya mendapat bocoran trik internetan cepat dengan kartu 3 (Tri). Saya sendiri sudah mencobanya, dan ternyata memang berhasil. Memang tidak gratis, tapi cukup dengan bermodal kartu Tri yang harga tiga ribuan (atau kurang), saya bisa internetan ngebut dan unlimited sampai tiga hari. Dengan trik ini, kita tidak dibatasi oleh kuota.

    Pada awal memakai trik itu, saya mendapat kecepatan download sampai 25KB/s. Maklum, karena hanya mendapat sinyal edge. Sementara teman yang lain, ada yang bisa sampai 100KB/s bahkan lebih karena mendapat sinyal 3G.

    Akhir-akhir ini, entah kenapa, trik tersebut sudah tidak jalan semulus dulu lagi. Memang, saya masih bisa internetan tanpa batas sampai 3 hari, hanya dengan kartu yang Rp 2500. Tapi kecepatan yang saya dapat cuma mentok di 5KB/s alias 40kbps.

    Hmmm… sepertinya memang perlu mencari trik lain nih… Oya, kalau pembaca ingin tau triknya, bisa kasih emailnya di kolom komentar. Sebab saya gak bisa menyebrkan di tempat umum seperti ini, karena pasti triknya cepet mati.


text:
package SistemaBibliotecaApp;

//import java.sql.Connection;
//import java.sql.SQLException;
import java.util.Scanner;

import DAO.ConexaoMySQL;
import VIEW.SistemaBibliotecaMenu;

public class SistemaBibliotecaApp {

	private static Scanner ler;

	public static void main(String[] args) throws Exception {

		int opcao = 0;

		do{
			System.out.println("Escolha uma opção:");
			System.out.println("1 - LOGIN");
			System.out.println("0 - SAIR");

			ler = new Scanner(System.in);
			opcao = ler.nextInt();

			switch(opcao){
			    case 1:
			    	//Login();

			    	int opcao2 = -1;
			       // UsuarioVO usuarioVO = null;
			        SistemaBibliotecaAppLogin login= null;

			        while (opcao2 != 0) {

			            switch (opcao2){
			                case -1:
			                    login = (login == null) ? new SistemaBibliotecaAppLogin() : login;

			                    //usuarioVO = login.EfetuarLogin();
			                    if(login.EfetuarLogin()){
			                    	System.out.println("Login efetuado!");

			                    	SistemaBibliotecaMenu menuBiblioteca = new SistemaBibliotecaMenu();
			                        menuBiblioteca.exibeMenu();

			                    }else{
			                    	System.out.println("Erro no login!");
			                    }

			                    opcao2=0;
			                    break;
			            }
			        }

			    	break;
			    case 0:
			    	break;
			    default:
			    	System.out.println("Opção inválida!");
			    		break;

			}

	        ConexaoMySQL.fecharConexao();
		}while(opcao!=0);

		System.out.println("*****PROGRAMA ENCERRADO******");
	}

}


text:
"""
Defines the classes :class:`Choice` and :class:`ChoiceList`.  See
:doc:`/dev/choicelists`.
"""

from future.utils import with_metaclass
from past.builtins import cmp

import warnings

from django.utils.translation import gettext_lazy as _
from django.utils.functional import lazy
from django.utils.deconstruct import deconstructible
from django.db import models
from django.conf import settings
from django.db.models import NOT_PROVIDED
from django.db.migrations.serializer import BaseSerializer
from django.db.migrations.writer import MigrationWriter

from lino.utils import is_string
from lino.core import actions
from lino.core import actors
from lino.core import tables
from lino.core import fields
from .exceptions import UnresolvedChoice
from .signals import receiver, pre_analyze

STRICT = True
VALUE_FIELD = models.CharField(_("value"), max_length=20)
VALUE_FIELD.attname = 'value'

@deconstructible
class Choice(fields.TableRow):
    """A constant value whose unicode representation depends on the
    current language at runtime.  Every item of a :class:`ChoiceList`
    must be an instance of :class:`Choice` or a subclass thereof.

    .. attribute:: choicelist

        The choice list that owns this choice.

    .. attribute:: value

        (a string) The value to use e.g. when this choice is being stored in a
        database.

    .. attribute:: text

        A translatable string containing the text to show to the user.

    .. attribute:: names

        A list of names to be used as attribute name on the choicelist for referring
        to this choice from application code.

        If this is `None` or not specified, the choice is a nameless
        choice, which is a full-fledged choice object but is not
        accessible as a class attribute on its choicelist.

    .. attribute:: button_text

        The text to appear on buttons representing this state.

    """
    choicelist = None
    remark = None
    pk = None
    value = None
    text = None
    names = ''
    button_text = None

    def __init__(self, value=None, text=None, names=None, **kwargs):
        """Create a new :class:`Choice` instance.

        Parameters: see :attr:`value`, :attr:`text` and :attr:`name`.
        Any keyword arguments will become attributes on the instance.

        This is also being called from :meth:`Choicelist.add_item`.

        If `names` is given, it should be either an iterable of strings or a
        string of space-separated names.  Each name will be installed as an
        attribute of the choicelist that contains this choice and must be a
        valid Python identifier.  Lino will refuse to add duplicate names.

        """
        if value is not None:
            if not isinstance(value, str):
                raise Exception("value must be a string")
            self.value = self.pk = value
        if names is None:
            names = self.names
        if isinstance(names, str):
            names = tuple(names.split())
        self.names = names

        # if name is not None:
        #     if self.name is None:
        #         self.name = value
        # else:
        #     self.name = name
        if text is None:
            if self.text is None:
                # self.text = self.__class__.__name__
                self.text = self.value
        else:
            # assert_pure(text)
            self.text = text
        for k, v in kwargs.items():
            setattr(self, k, v)

    @property
    def name(self):
       if len(self.names) == 0:
           return None
       # elif len(self.names) == 1:
       else:
           return self.names[0]
       # raise Exception("{} has multiple names".format(self))
       # return ' '.join(self.names[0])

    # def deconstruct(self):
    #     return ('str', self.value, {})
    #     # path = self.choicelist.__module__ + "." + self.choicelist.__name__
    #     # args = (self.value, self.text, self.name)
    #     # kwargs = {}
    #     # return (path, args, kwargs)
    #     # return ('lino.api.rt.resolve', (str(self.choicelist), self.value), {})

    def update(self, **kwargs):
        for k, v in kwargs.items():
            if not hasattr(self, k):
                raise Exception("%s has no attribute `%s`" % (self, k))
            setattr(self, k, v)

    def attach(i, cls):
        i.choicelist = cls
        if i.value is None:
            i.pk = i.value = str(len(cls.choices)+1)
        elif len(i.value) > cls.max_length:
            if len(cls._fields) > 0:
                raise Exception(
                    "%s cannot add value %r because fields exist "
                    "and max_length is %d."
                    % (cls, i.value, cls.max_length) + """\
When fields have been created, we cannot simply change their max_length because
Django creates copies of them when inheriting models.
""")
            cls.max_length = len(i.value)
            #~ for fld in cls._fields:
                #~ fld.set_max_length(cls.max_length)

        dt = cls.display_text(i)
        cls.choices.append((i, dt))
        # cls.preferred_width = max(cls.preferred_width, len(unicode(dt)))
        cls.items_dict[i.value] = i
        #~ cls.items_dict[i] = i

    def remove(self):
        """Remove this choice from its list.

        Usage example see
        """
        self.choicelist.remove_item(self)

    def __len__(self):
        # if self.value is None:
        #     return 1
        return len(self.value)

    def __cmp__(self, other):
        if other.__class__ is self.__class__:
            return cmp(self.value, other.value)
        return cmp(self.value, other)

    def __eq__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__eq__(other)
        if other.__class__ is self.__class__:
            return (self.value == other.value)
        return self.value == other

    def __ne__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__neq__(other)
        if other.__class__ is self.__class__:
            return (self.value != other.value)
        return (self.value != other)

    def __lt__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__lt__(other)
        if other.__class__ is self.__class__:
            return (self.value < other.value)
        return (self.value < other)

    def __le__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__le__(other)
        if other.__class__ is self.__class__:
            return (self.value <= other.value)
        return (self.value <= other)

    def __gt__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__gt__(other)
        if other.__class__ is self.__class__:
            return (self.value > other.value)
        return (self.value > other)

    def __ge__(self, other):
        # if self.value is None:
        #     return super(Choice, self).__ge__(other)
        if other.__class__ is self.__class__:
            return (self.value >= other.value)
        return (self.value >= other)

    __hash__ = object.__hash__
    #~ 20120620: removed to see where it was used
    #~ def __getattr__(self,name):
        #~ return curry(getattr(self.choicelist, name),self)

    def __repr__(self):
        # when there several names, we use the first one
        if len(self.names) > 0:
            return "<%s.%s:%s>" % (
                self.choicelist, self.names[0], self.value)
        else:
            return "<%s:%s>" % (self.choicelist, self.value)

    # def __str__(self):
    #     if self.name:
    #         return str(self.name)
    #     return str(self.text)

    def __str__(self):
        # return force_str(self.text, errors="replace")
        # return self.text
        if self.choicelist.show_values:
            return "{0} ({1})".format(self.value, self.text)
        return str(self.text)

    @classmethod
    def get_chooser_for_field(cls, fieldname):
        return None

    def get_typed_instance(self, model):
        """
        Used when implementing :ref:`polymorphism`.
        """
        return self

    def obj2href(self, ar):
        # needed by `detail_pointer`
        return str(self)

class UnresolvedValue(Choice):
    def __init__(self, choicelist, value):
        self.choicelist = choicelist
        self.value = value
        self.text = "Unresolved value %r for %s" % (
            value, choicelist.__name__)
        self.names = {}

class ChoiceListMeta(actors.ActorMetaClass):

    def __new__(meta, classname, bases, classDict):
        #~ if not classDict.has_key('app_label'):
            #~ classDict['app_label'] = cls.__module__.split('.')[-2]
        """
        UserGroups manually sets `max_length` because the
        default list has only one group with value "system",
        but applications may want to add longer group names
        """
        if 'label' in classDict:
            raise Exception("label replaced by verbose_name_plural")
        classDict.setdefault('max_length', 10)
        cls = actors.ActorMetaClass.__new__(meta, classname, bases, classDict)

        cls.items_dict = {}
        cls.clear()
        cls._fields = []
        # cls._lazy_items = []
        return cls

#~ choicelist_column_fields = dict()
#~ choicelist_column_fields['value'] = fields.VirtualField(models.CharField())
#~ choicelist_column_fields['text'] = fields.VirtualField(models.CharField())
#~ choicelist_column_fields['name'] = fields.VirtualField(models.CharField())

class CallableChoice(object):
    def __repr__(self):
        return "{}.as_callable('{}')".format(repr(self.ChoiceList), self.name)
    # def __eq__(self, other):
    #     return self.ChoiceList == other.ChoiceList and self.name == other.name
    def __init__(self, ChoiceList, name):
        self.ChoiceList = ChoiceList
        self.name = name
    def __call__(self, *args, **kwargs):
        return self.ChoiceList.get_by_name(self.name)
        # return self.callfn(*args, **kwargs)

class ChoiceList(with_metaclass(ChoiceListMeta, tables.AbstractTable)):

    """
    User-defined choice lists must inherit from this base class.

    .. attribute:: max_length

        The default `max_length` for fields using this choicelist.

    """
    abstract = True
    workflow_actions = []

    item_class = Choice
    """
    The class of items of this list.
    """

    auto_fit_column_widths = True

    default_value = None
    """A string with the name of a choice to be used as default value for
    fields using this list.

    Note that this specifies the *default* default value for *all*
    :class:`ChoiceListField <lino.core.choicelists.ChoiceListField>`
    of this choicelist, including parameter fields.

    You can remove that "default default value" for all tables by
    specifying `default=''`. There are two places where you can
    specify this: (a) on the parameter field itself (which then
    applies to all subtables) or (b) just on one table. For example
    (excerpt from :mod:`lino_avanti.lib.avanti`)::

        from lino_xl.lib.clients.choicelists import ClientStates
        ClientStates.default_value = 'coached'

        parameters = ObservedDateRange(
            ...
            client_state=ClientStates.field(blank=True, default=''))

    Note that the default values of parameter fields of a table which
    is used as the *models default table* will apply for the choices
    of pointers to that model. Concrete use case is the choicelist of
    `cal.Guest.partner` in :ref:`avanti` which should show only
    coached clients.  So instead of above code we actually now do::

        class MyClients(My, Clients):
            @classmethod
            def param_defaults(self, ar, **kw):
                kw = super(MyClients, self).param_defaults(ar, **kw)
                kw.update(client_state='')
                return kw

    The disadvantage
    is that when somebody *does not* want your default value, then
    they must explicitly specify `default=''` when defining a field on
    your choicelist.

    """

    preferred_foreignkey_width = 20
    """
    Default preferred with for ChoiceList fields to this list.
    """

    stored_name = None
    """Every subclass of ChoiceList will be automatically registered.
    Define this if your class's name clashes with the name of an
    existing ChoiceList.

    """

    verbose_name = None
    verbose_name_plural = None

    show_values = False
    """Set this to `True` if the user interface should include the `value`
    attribute of each choice.

    """

    preferred_width = None
    """Preferred width (in characters) used by
    :class:`fields<lino.core.fields.ChoiceListField>` that refer to
    this list.

    If this is `None`, then Lino calculates the value at startup,
    taking the length of the longest choice text.  The hard-coded
    absolute minimum in that case is 4.  Note that it calculates the
    value using the :attr:`default site language
    <lino.site.Site.languages>` and thus might guess wrong if the user
    language is not the default site language.

    Note that by this we mean the width of the bare text field,
    excluding any UI-specific control like the trigger button of a
    combobox.  That's why e.g. :mod:`lino.modlib.extjs.ext_elems` adds
    another value for the trigger button.

    """

    pk = True  # added 20150218.

    removed_names = frozenset()

    @classmethod
    def get_default_action(cls):
        return actions.ShowTable()

    hidden_columns = frozenset(['workflow_buttons'])

    column_names = 'value name text *'

    button_text = models.CharField(_("Button text"), blank=True)

    old2new = {}
    """
    A dict which maps old values to their new values.

    This dict is consulted when an unknown value is read from database
    (e.g. during a migration).  If if contains a replacement for the
    old value, Lino will return the choice with the new value.
    """

    @classmethod
    def get_column_names(self, ar):
        return self.column_names

    @classmethod
    def get_data_elem(self, name):
        de = super(ChoiceList, self).get_data_elem(name)
        if de:
            return de
        return getattr(self, name, None)
        #~ return _choicelist_column_fields.get(name)

    @fields.virtualfield(VALUE_FIELD)
    def value(cls, choice, ar):
        return choice.value

    @fields.virtualfield(models.CharField(_("text"), max_length=50))
    def text(cls, choice, ar):
        return choice.text

    @fields.virtualfield(models.CharField(_("name"), max_length=20))
    def name(cls, choice, ar):
        return ' '.join(choice.names)

    @fields.displayfield(_("Remark"))
    def remark(cls, choice, ar):
        return choice.remark

    @fields.displayfield(_("Type"))
    def type(cls, choice, ar):
        return choice.__class__.__name__

    # @fields.displayfield(_("Description"))
    # def description(cls, choice, ar):
    #     return choice.help_text

    @classmethod
    def get_data_rows(self, ar=None):
        """

        """
        # return sorted(self.items())
        return self.get_list_items()

    @classmethod
    def get_actor_label(self):
        """
        Compute the label of this actor.
        Called only if `label` is not set, and only once during site startup.
        """
        return self._label or self.verbose_name_plural or self.__name__

    @classmethod
    def clear(cls):
        """Clear the list, i.e. remove all items.

        This is used when you want to restart from scratch for building a
        choicelist.

        """
        # remove previously defined named choices from class dict:
        for ci in cls.items_dict.values():
            for name in ci.names:
                delattr(cls, name)
                # if cls.__name__ == "UserTypes":
                #     print("20200504 clear {} {} {}".format(cls, ci.name, ci))
        cls.removed_names = frozenset()
        cls.items_dict = {}
        cls.choices = []  # remove blank_item from choices
        cls.workflow_actions = []

    @classmethod
    def remove_item(cls, i):
        """Remove the specified item from this list. Called by
        :meth:`Choice.remove`.
        """
        del cls.items_dict[i.value]
        for name in i.names:
            cls.removed_names.add(name)
            # print(20161215, cls.removed_names)
            delattr(cls, name)
        for n, el in enumerate(cls.choices):
            if el[0] == i:
                del cls.choices[n]
        for n, a in enumerate(cls.workflow_actions):
            if a.target_state == i:
                del cls.workflow_actions[n]

    # @classmethod  # was not used
    # def setup_field(cls, fld):
    #     pass

    @classmethod
    def sort(cls):
        """
        Sort the items by their value.

        Used for example by :mod:`lino_xl.lib.orders` where we add a journal
        group to :class:`lino_xl.lib.ledger.JournalGroups` and want it to come
        before the other groups.

        """
        cls.choices.sort(key=lambda x: x[0].value)

    @classmethod
    def field(cls, *args, **kw):
        """
        Create and return a database field that points to one value of this
        choicelist.

        The returned field is an instance of :class:`ChoiceListField`.
        Returns a `DummyField` if the plugin which defines this
        choicelist is not installed.
        """
        if settings.SITE.is_installed(cls.app_label):
            fld = ChoiceListField(cls, *args, **kw)
            # cls.setup_field(fld)
            cls._fields.append(fld)
            return fld
        return fields.DummyField()

    @classmethod
    def multifield(cls, *args, **kw):
        """
        Not yet implemented.
        Create a database field (a :class:`ChoiceListField`)
        that holds a set of multiple values of this choicelist.
        """
        fld = MultiChoiceListField(cls, *args, **kw)
        cls._fields.append(fld)
        return fld

    @classmethod
    def add_item_lazy(cls, *args, **kwargs):
        """Run :meth:`add_item` with these arguments when all plugins have
        been loaded.

        This is used e.g. when declaring :mod:`lino_xl.lib.ledger.VoucherTypes`
        : a voucher type is defined using its ByJournal table, but the model of
        that table is not necessarily resolvable at that moment.

        """
        @receiver(pre_analyze, weak=False)
        def func(sender, **ignored):
            cls.add_item(*args, **kwargs)
            # logger.info("20190506 added item %s to %s %s %s", i, cls, args, kwargs)

        # cls._lazy_items.append(func)
        # we must store the func somewhere because receiver only connects it to
        # the signal, which is a weak reference.

    @classmethod
    def add_item(cls, *args, **kwargs):
        """Instantiates a new choice and adds it to this list. Signature is
        that of the :meth:`Choice.__init__` method (which might have
        been overridden if you defined a customized
        :attr:`item_class`.

        """
        return cls.add_item_instance(cls.item_class(*args, **kwargs))

    @classmethod
    def class_init(cls):
        super(ChoiceList, cls).class_init()
        if cls.abstract:
            return
        if cls.preferred_width is None:
            pw = 4
            for i in cls.get_list_items():
                dt = cls.display_text(i)
                pw = max(pw, len(dt))
            cls.preferred_width = pw
            # print("20200122b setting preferred_width for {} to {}".format(cls, cls.preferred_width))

    @classmethod
    def add_item_instance(cls, i):
        #~ if cls is ChoiceList:
            #~ raise Exception("Cannot define items on the base class")
        is_duplicate = False
        if i.value is not None and i.value in cls.items_dict:
            raise Exception("Duplicate value %r in %s." % (i.value, cls))
            warnings.warn("Duplicate value %r in %s." % (i.value, cls))
            is_duplicate = True
        for name in i.names:
            if not is_duplicate:
                if name in cls.__dict__:
                    raise Exception(
                        "An attribute named %r is already defined in %s" % (
                            name, cls.__name__))
            # if cls.__name__ == "UserTypes":
            #     print("20200504 add {} {} {}".format(cls, i.name, i))
            setattr(cls, name, i)
            #~ i.name = name
        i.attach(cls)
        return i

    @classmethod
    def get_pk_field(self):
        """See :meth:`lino.core.actors.Actor.get_pk_field`.
        """
        return VALUE_FIELD

    @classmethod
    def get_row_by_pk(cls, ar, pk):
        return cls.get_by_value(pk)

    @classmethod
    def to_python(cls, value):
        # if isinstance(value, Choice):
        #     return value
        if not value:
            return None
        nv = cls.old2new.get(value)
        if nv is not None:
            value = nv
        v = cls.items_dict.get(value) or cls.get_by_name(value, None)
        if v is not None:
            return v
        if settings.SITE.strict_choicelist_values:
            raise UnresolvedChoice(
                "Unresolved value %r (%s) for %s (set "
                "Site.strict_choicelist_values to False "
                "to ignore this)" % (
                    value, value.__class__, cls))
        return UnresolvedValue(cls, value)

    @classmethod
    def get_choices(cls):
        return cls.choices

    #~ @classmethod
    #~ def get_choices(cls):
        #~ """
        #~ We must make it dynamic since e.g. UserTypes can change after
        #~ the fields have been created.

        #~ https://docs.djangoproject.com/en/3.1/ref/models/fields/
        #~ note that choices can be any iterable object -- not necessarily
        #~ a list or tuple. This lets you construct choices dynamically.
        #~ But if you find yourself hacking choices to be dynamic, you're
        #~ probably better off using a proper database table with a
        #~ ForeignKey. choices is meant for static data that doesn't
        #~ change much, if ever.
        #~ """
        #~ for c in cls.choices:
            #~ yield c

    @classmethod
    def display_text(cls, bc):
        """Return the text to be used for representing the given choice
        instance `bc` to the user.

        Override this to customize the display text of choices.
        :class:`lino.modlib.users.UserGroups` and
        :class:`lino.modlib.cv.models.CefLevel` used to do this before
        we had the :attr:`ChoiceList.show_values` option.

        This must be lazyly translatable because the result are also
        used to build the `choices` attribute of ChoiceListFields on
        this choicelist.

        Note that Django's `lazy` function has a list of
        "resultclasses" which are used "so that the automatic forcing
        of the lazy evaluation code is triggered".

        """
        if cls.show_values:
            # if unicodeerror:
            # assert_pure(str(bc))
            # str(bc)

            def fn(bc):
                # return "%s (%s)" % (bc.value, str(bc))
                return "{0} ({1})".format(bc.value, bc)
            return lazy(fn, str, str)(bc)
        return lazy(str, str, str)(bc)

    @classmethod
    def get_by_name(self, name, *args):
        """
        Supports the case that `name` is `None` (returns `None` then).
        """
        if name:
            return getattr(self, name, *args)
        else:
            return None

    @classmethod
    def get_by_value(cls, value, *args):
        """
        Return the item (a :class:`Choice` instance) corresponding to the
        specified `value`.
        """
        if not isinstance(value, str):
            raise Exception("%r is not a string" % value)
        #~ print "get_text_for_value"
        #~ return self.items_dict.get(value, None)
        #~ return self.items_dict.get(value)
        return cls.items_dict.get(value, *args)

    @classmethod
    def as_callable(self, name):
        """
        Use this when you want to specify some named default choice of this
        list as a default value *without* removing the possibility to
        clear and re-populate the list after the field definition.

        Usage example::

            foo_state = MyStates.as_callable('foo')

        This is used internally when you specify a string as default value of a
        choicelist field.

        """
        return CallableChoice(self, name)

    @classmethod
    def get_default_value(self):
        """Return the *default* default value for fields using this
        choicelist.

        """
        return self.get_by_name(self.default_value)

    #~ @classmethod
    #~ def items(self):
        #~ return [choice[0] for choice in self.choices]

    @classmethod
    def find(cls, **fkw):
        """Find and return the choice that satisfies the given search
        criteria.  Return `None` if no choice is found or if more than
        one choice is found.

        """
        lst = cls.filter(**fkw)
        if len(lst) == 1:
            return lst[0]
        return None

    @classmethod
    def filter(self, **fkw):
        def f(item):
            for k, v in list(fkw.items()):
                if getattr(item, k) != v:
                    return False
            return True
        return [choice[0] for choice in self.choices if f(choice[0])]

    # @classmethod
    # def filter_choice(self, **fkw):
    #     """
    #     Apply the fkw filter and return the list of filtered choices.
    #     :param fkw:
    #     :return:
    #     """
    #     def f(item):
    #         for k, v in list(fkw.items()):
    #             if getattr(item, k) != v:
    #                 return False
    #         return True
    #
    #     return [choice for choice in self.choices if f(choice[0])]

    @classmethod
    def get_list_items(self):
        return [choice[0] for choice in self.choices]
    objects = get_list_items  # deprecated alias for backwards compat
    items = get_list_items   # deprecated alias for backwards compat

    @classmethod
    def get_text_for_value(self, value):
        """
        Return the text corresponding to the specified value.
        """
        bc = self.get_by_value(value)
        if bc is None:
            return _("%(value)r (invalid choice for %(list)s)") % dict(
                list=self.__name__, value=value)
        return self.display_text(bc)

class ChoiceListField(models.CharField):

    """A field that stores a value to be selected from a
    :class:`ChoiceList`.

    ChoiceListField cannot be nullable since they are implemented as
    CharFields.  Therefore when filtering on empty values in a
    database query you cannot use ``__isnull``.  The following query
    won't work as expected::

      for u in users.User.objects.filter(user_type__isnull=False):

    You must either check for an empty string::

      for u in users.User.objects.exclude(user_type='')

    or use the ``__gte`` operator::

      for u in users.User.objects.filter(user_type__gte=dd.UserLevels.guest):

    """

    empty_strings_allowed = False

    def __init__(self, choicelist=None, verbose_name=None,
                 force_selection=True, default=None, **kw):
        if verbose_name is None:
            verbose_name = choicelist.verbose_name
        self.choicelist = choicelist
        self.force_selection = force_selection
        if default is not None:
            if is_string(default):
                default = choicelist.as_callable(default)
            kw.update(default=default)
        defaults = dict(
            max_length=choicelist.max_length)
        # if choicelist.default_value:
        #     defaults.update(
        #         default=choicelist.as_callable(choicelist.default_value))
        if choicelist.default_value:
            defaults.update(default=choicelist.get_default_value)
        # if not 'help_text' in kw:
        #     # inherited docstrings won't be helpful here.
        #     doc = choicelist.__dict__['__doc__']
        #     if doc:
        #         kw['help_text'] = choicelist.__doc__.split('\n\n')[0]
        defaults.update(kw)
        models.CharField.__init__(self, verbose_name, **defaults)

    # def contribute_to_class(self, cls, name):
    #     super(ChoiceListField, self).contribute_to_class(cls, name)
    #     # add workflow actions to the model so that we can access them
    #     # as InstanceActions
    #     logger.info("20150122 %s %s", cls, name)
    #     for a in self.choicelist.workflow_actions:
    #         logger.info("20150122 %s %s", a.action_name, a)
    #         setattr(cls, a.action_name, a)

    def deconstruct(self):
        """
        Needed for Django 1.7+, see
        https://docs.djangoproject.com/en/3.1/howto/custom-model-fields/#custom-field-deconstruct-method
        """

        name, path, args, kwargs = super(ChoiceListField, self).deconstruct()
        # args = [self.choicelist]

        kwargs['choicelist'] = self.choicelist
        # kwargs.pop('default', None)
        # TODO: above line is cheating in order to get makemigrations
        # to pass. we remove the `default` attribute because it is not
        # serializable. This means that our migrations are probably
        # invalid and not usable.

        return name, path, args, kwargs

    def get_internal_type(self):
        return "CharField"

    #~ def set_max_length(self,ml):
        #~ self.max_length = ml

    def from_db_value(self, value, expression, connection, context=None):
        if value is None:
            return None
        return self.choicelist.to_python(value)

    def to_python(self, value):
        """See Django's docs about `to_python()
        <https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.Field.to_python>`__.

        """
        #~ if self.attname == 'query_register':
            #~ print '20120527 to_python', repr(value), '\n'
        if isinstance(value, Choice):
            return value
        return self.choicelist.to_python(value)

    def _get_choices(self):
        """HACK: Django by default stores a copy of our list when the
        `choices` of a field are evaluated for the first time. We
        don't want that because ChoiceLists may change afterwards.

        """
        return self.choicelist.choices

    def _set_choices(self, value):
        # if value != []:
        #     logger.warning("Ignoring set choices {0}".format(value))
        return

    choices = property(_get_choices, _set_choices)

    def get_prep_value(self, value):
        """
        Excerpt from `Django docs
        <https://docs.djangoproject.com/en/3.0/howto/custom-model-fields/#converting-python-objects-to-query-values>`__:
        "If you override `to_python()
        <https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.Field.to_python>`__
        you also have to override `get_prep_value()
        <https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.Field.get_prep_value>`__
        to convert Python objects back to query values."
        """
        #~ if self.attname == 'query_register':
            #~ print '20120527 get_prep_value()', repr(value)
        #~ return value.value
        # Hamza, why did you add the following 2 lines?
        # if isinstance(value,unicode):
        #     return str(value)
        if value:
            if callable(value):  # Django 1.9
                value = value()
            value = self.to_python(value)  # see Luc's blog 20160204
            return value.value
        return ''
        #~ return None

    def value_to_string(self, obj):
        value = self.value_from_object(obj)
        #~ if self.attname == 'query_register':
            #~ print '20120527 value_to_string', repr(value)
        return self.get_prep_value(value)
        #~ return self.get_db_prep_value(value,connection)

    #~ def save_form_data(self, instance, data):
        #~ setattr(instance, self.name, data)

    def get_text_for_value(self, value):
        return self.choicelist.get_text_for_value(value.value)

class MultiChoiceListField(ChoiceListField):
    """
    A field whose value is a `list` of `Choice` instances.
    Stored in the database as a CharField using a delimiter character.
    """
    delimiter_char = ','
    max_values = 1

    def __init__(self, choicelist, verbose_name=None, max_values=10, **kw):
        if verbose_name is None:
            verbose_name = choicelist.verbose_name_plural
        self.max_values = max_values
        defaults = dict(
            max_length=(choicelist.max_length + 1) * max_values
        )
        defaults.update(kw)
        ChoiceListField.__init__(self, verbose_name, **defaults)

    #~ def set_max_length(self,ml):
        #~ self.max_length = (ml+1) * self.max_values

    def from_db_value(self, value, expression, connection, context=None):
        return [self.choicelist.to_python(v) for v in value.split(self.delimiter_char)]

    def to_python(self, value):
        if value is None:
            return []
        if isinstance(value, list):
            return value
        value = [self.choicelist.to_python(v)
                 for v in value.split(self.delimiter_char)]
        return value

    def get_prep_value(self, value):
        """
        This must convert the given Python value (always a list)
        into the value to be stored to database.
        """
        return self.delimiter_char.join([bc.value for bc in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_prep_value(value)

    def get_text_for_value(self, value):
        return ', '.join([
            self.choicelist.get_text_for_value(bc.value) for bc in value])

# from lino.core.choicelists import Choice, ChoiceList, CallableChoice

class ChoiceSerializer(BaseSerializer):
    def serialize(self):
        return ("rt.models.{}.{}.get_by_value('{}')".format(
            self.value.choicelist.app_label, self.value.choicelist.__name__,
                self.value.value),
            {'from lino.api.shell import rt'})

MigrationWriter.register_serializer(Choice, ChoiceSerializer)

class ChoiceListSerializer(BaseSerializer):
    def serialize(self):
        return ("rt.models.{}.{}".format(
            self.value.choicelist.app_label, self.value.choicelist.__name__),
            {'from lino.api.shell import rt'})
MigrationWriter.register_serializer(ChoiceList, ChoiceListSerializer)

class CallableChoiceSerializer(BaseSerializer):
    def serialize(self):
        choice = self.value()
        return ("rt.models.{}.{}.as_callable('{}')".format(
            choice.choicelist.app_label, choice.choicelist.__name__, choice.name),
            {'from lino.api.shell import rt'})

MigrationWriter.register_serializer(CallableChoice, CallableChoiceSerializer)


text:
package com.net2plan.examples.ocnbook.offline;

import cern.colt.matrix.tdouble.DoubleMatrix1D;
import com.net2plan.interfaces.networkDesign.IAlgorithm;
import com.net2plan.interfaces.networkDesign.Link;
import com.net2plan.interfaces.networkDesign.Net2PlanException;
import com.net2plan.interfaces.networkDesign.NetPlan;
import com.net2plan.libraries.IPUtils;
import com.net2plan.utils.Constants.RoutingType;
import com.net2plan.utils.InputParameter;
import com.net2plan.utils.Pair;
import com.net2plan.utils.TimeTrace;
import com.net2plan.utils.Triple;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Searches for the OSPF link weights that minimize a measure of congestion, using a simulated annealing (SAN) heuristic
 *
 * The time evolution of different metrics can be stored in output files, for later processing.
 * As an example, see the {@code fig_sec12_4_ospfWeightSAN.m} MATLAB file used for generating the graph/s of the case study in the
 * book using this algorithm.
 * @net2plan.description
 * @net2plan.keywords IP/OSPF, Flow assignment (FA), Simulated annealing (SAN)
 * @net2plan.ocnbooksections Section 12.4
 * @net2plan.inputParameters
 * @author Pablo Pavon-Marino
 */
public class Offline_fa_ospfWeightOptimization_SAN implements IAlgorithm
{
	private int numIterOuterLoop;

	private TimeTrace stat_objFunction;
	private TimeTrace stat_bestObjFunction;
	private TimeTrace stat_temperature;
	private OSPFHeuristicUtils ospfEngine;

	private InputParameter san_initializationType = new InputParameter ("san_initializationType", "#select# random" , "The type of initialization of the OSPF link weights");
	private InputParameter san_worseCaseObjFunctionWorsening = new InputParameter ("san_worseCaseObjFunctionWorsening", (double) 0.25 , "Objective function worsening in a transition considered as worse case for initial temperature computation" , 0 , false , Double.MAX_VALUE , true);
	private InputParameter san_geometricTemperatureReductionFactor = new InputParameter ("san_geometricTemperatureReductionFactor", (double) 0.8 , "Geometric decrease factor of the temperature" , 0 , true , 1 , true);
	private InputParameter san_freezingProbabilityThreshold = new InputParameter ("san_freezingProbabilityThreshold", (double) 0.01 , "If the fraction of iterations with a jump, in the inner loop, is below this, the system is reheated (temperature to the initial value). If not, decreased geometrically" , 0 , true , 1 , true);
	private InputParameter san_initialAcceptanceProbability = new InputParameter ("san_initialAcceptanceProbability", (double) 0.5 , "Acceptance probability of the worst case transition: to compute the initial temperature" , 0 , false , Double.MAX_VALUE , true);
	private InputParameter san_maxNumIterationsInnerLoop = new InputParameter ("san_maxNumIterationsInnerLoop", (int) 1000 , "Number of iterations of the inner loop (all with the same temperature)" , 1 , Integer.MAX_VALUE);
	private InputParameter san_maxNumIterationsOuterLoop = new InputParameter ("san_maxNumIterationsOuterLoop", (int) 50 , "Number of iterations of the outer loop" , 1 , Integer.MAX_VALUE);
	private InputParameter san_differenceInWeightToBeNeighbors = new InputParameter ("san_differenceInWeightToBeNeighbors", (int) 1 , "Two solutions where all the links have the same weight, but one link where the weight differs in the quantity given by this parameter, are considered neighbors");
	private InputParameter ospf_maxLinkWeight = new InputParameter ("ospf_maxLinkWeight", (int) 16 , "OSPF link weights are constrained to be integers between 1 and this parameter" , 1 , Integer.MAX_VALUE);
	private InputParameter ospf_weightOfMaxUtilizationInObjectiveFunction = new InputParameter ("ospf_weightOfMaxUtilizationInObjectiveFunction", (double) 0.9 , "Objective function is this factor multiplied by maximum link utilization, plus 1 minus this factor by average link utilization" , 0 , true , 1 , true);
	private InputParameter algorithm_randomSeed = new InputParameter ("algorithm_randomSeed", (long) 1 , "Seed of the random number generator");
	private InputParameter algorithm_outputFileNameRoot = new InputParameter ("algorithm_outputFileNameRoot", "ospfWeghtOptimization_san" , "Root of the file name to be used in the output files. If blank, no output");
	private InputParameter algorithm_maxExecutionTimeInSeconds = new InputParameter ("algorithm_maxExecutionTimeInSeconds", (double) 60 , "Algorithm maximum running time in seconds" , 0 , false , Double.MAX_VALUE , true);

	@Override
	public String executeAlgorithm(NetPlan netPlan, Map<String, String> algorithmParameters, Map<String, String> net2planParameters)
	{
		/* Initialize all InputParameter objects defined in this object (this uses Java reflection) */
		InputParameter.initializeAllInputParameterFieldsOfObject(this, algorithmParameters);

		/* Basic checks */
		final int N = netPlan.getNumberOfNodes();
		final int E = netPlan.getNumberOfLinks ();
		if (N == 0) throw new Net2PlanException("The input design must have nodes");
		netPlan.removeAllUnicastRoutingInformation();
		netPlan.setRoutingTypeAllDemands (RoutingType.HOP_BY_HOP_ROUTING);

		final long algorithmInitialtime = System.nanoTime();
		final long algorithmEndtime = algorithmInitialtime + (long) (algorithm_maxExecutionTimeInSeconds.getDouble() * 1E9);

		/* Compute initial solution */
		Random rng = new Random (algorithm_randomSeed.getLong ());
		this.ospfEngine = new OSPFHeuristicUtils(netPlan, ospf_maxLinkWeight.getInt (), ospf_weightOfMaxUtilizationInObjectiveFunction.getDouble (), rng);
		this.stat_bestObjFunction = new TimeTrace ();
		this.stat_objFunction = new TimeTrace ();
		this.stat_temperature = new TimeTrace ();
		this.numIterOuterLoop = 0;

		Pair<DoubleMatrix1D,Double> p = ospfEngine.getInitialSolution (san_initializationType.getString ());
		DoubleMatrix1D currentSol = p.getFirst();
		double currentObjFunction = p.getSecond();

		/* Compute the initial and end temperatures, and the geometric temperature reduction factor */
		final double initialTemperature = -san_worseCaseObjFunctionWorsening.getDouble () / Math.log(san_initialAcceptanceProbability.getDouble ());

		//System.out.println("initialTemperature: " + initialTemperature + ", geometricReductionFactor: " + san_geometricTemperatureReductionFactor.getDouble ());

		double currentTemperature = initialTemperature;
		DoubleMatrix1D bestSol = currentSol.copy ();
		double bestObjFunction = currentObjFunction;

		stat_objFunction.add(0.0 , currentObjFunction);
		stat_bestObjFunction.add(0.0 , bestObjFunction);
		stat_temperature.add(0.0 , currentTemperature);
		while ((System.nanoTime() < algorithmEndtime) && (numIterOuterLoop < san_maxNumIterationsOuterLoop.getInt ()))
		{
			numIterOuterLoop ++;
			int numFrozenJumps = 0;
			for (int innerIt = 0 ; innerIt < san_maxNumIterationsInnerLoop.getInt () ; innerIt ++)
			{
				final Link neighborDifferentLink = netPlan.getLink (rng.nextInt(E));
				final double oldWeight = currentSol.get(neighborDifferentLink.getIndex ());
				double newWeight = 1;
				do
				{ newWeight = oldWeight + rng.nextInt(2*san_differenceInWeightToBeNeighbors.getInt ()+1) - san_differenceInWeightToBeNeighbors.getInt (); }
				while ((oldWeight == newWeight) || (newWeight < 1) || (newWeight > ospf_maxLinkWeight.getInt ()));

				currentSol.set(neighborDifferentLink.getIndex (), newWeight);
				final double neighborObjFunction = ospfEngine.computeObjectiveFunction(currentSol).getFirst();

				if ((neighborObjFunction < currentObjFunction) || (rng.nextDouble() < Math.exp(-(neighborObjFunction - currentObjFunction)/currentTemperature)))
				{
					/* If this jump does not change objFunction, consider it a frozen one */
					if (currentObjFunction == neighborObjFunction) numFrozenJumps ++;
					/* jump to the neighbor solution */
					currentObjFunction = neighborObjFunction;
					if (neighborObjFunction < bestObjFunction) { bestObjFunction = neighborObjFunction; bestSol = currentSol.copy (); /* System.out.println("Improving solution (temp: " + currentTemperature + ", objFunction: "+  bestObjFunction); */ }
				}
				else
				{
					currentSol.set(neighborDifferentLink.getIndex (), oldWeight);
					numFrozenJumps ++;
				}
				final double currentTimeInSecs = (System.nanoTime() - algorithmInitialtime) * 1e-9;
				stat_objFunction.add(currentTimeInSecs , currentObjFunction);
				stat_bestObjFunction.add(currentTimeInSecs , bestObjFunction);
				stat_temperature.add(currentTimeInSecs , currentTemperature);
			}
			if (((double) numFrozenJumps)/san_maxNumIterationsInnerLoop.getInt () > 1-san_freezingProbabilityThreshold.getDouble ())
				{ currentTemperature = initialTemperature; /* System.out.println("Reheat the system."); */ } // reheat the system
			else
				{ currentTemperature *= san_geometricTemperatureReductionFactor.getDouble(); /* System.out.println("Decrease temperature."); */ } // decrease temperature
		}

		IPUtils.setECMPForwardingRulesFromLinkWeights(netPlan, bestSol);
		for (Link e : netPlan.getLinks()) IPUtils.setLinkWeight(e, bestSol.get(e.getIndex()));

		stat_bestObjFunction.printToFile(new File (algorithm_outputFileNameRoot.getString () + "_bestObjFunc.txt"));
		stat_objFunction.printToFile(new File (algorithm_outputFileNameRoot.getString () + "_objFunc.txt"));
		stat_temperature.printToFile(new File (algorithm_outputFileNameRoot.getString () + "_temp.txt"));
		System.out.println("Ok! ObjFunction: " + bestObjFunction );
		return "Ok! ObjFunction: " + bestObjFunction;
	}

	@Override
	public String getDescription()
	{
		return "Given a set of nodes, links and offered traffic, this algorithm assumes that the nodes are IP routers running the OSPF protocol (applying ECMP rules) for routing it. The algorithm searches for the set of link weights that optimize the routing. In particular, the target is minimizing a congestion metric computed as a function of both the worst-case link utilization and the average link utilization. The algorithm is based on applying a simulated annealign (SAN) heuristic approach.";
	}

	@Override
	public List<Triple<String, String, String>> getParameters()
	{
		/* Returns the parameter information for all the InputParameter objects defined in this object (uses Java reflection) */
		return InputParameter.getInformationAllInputParameterFieldsOfObject(this);
	}

}


text:
obj-y     = fork.o exec_domain.o panic.o \
	    cpu.o exit.o itimer.o time.o softirq.o resource.o \
	    sysctl.o sysctl_binary.o capability.o ptrace.o timer.o user.o \
	    signal.o sys.o kmod.o workqueue.o pid.o task_work.o \
	    extable.o params.o posix-timers.o \
	    kthread.o sys_ni.o posix-cpu-timers.o \
	    hrtimer.o nsproxy.o \
	    notifier.o ksysfs.o cred.o reboot.o \
	    async.o range.o groups.o smpboot.o find_roots.o

ifdef CONFIG_FUNCTION_TRACER
# Do not trace debug files and internal ftrace files
CFLAGS_REMOVE_cgroup-debug.o = -pg
CFLAGS_REMOVE_irq_work.o = -pg
endif

obj-y += sched/
obj-y += locking/
obj-y += power/
obj-y += printk/
obj-y += cpu/
obj-y += irq/
obj-y += rcu/

obj-$(CONFIG_CHECKPOINT_RESTORE) += kcmp.o
obj-$(CONFIG_FREEZER) += freezer.o
obj-$(CONFIG_PROFILING) += profile.o
obj-$(CONFIG_STACKTRACE) += stacktrace.o
obj-y += time/
obj-$(CONFIG_FUTEX) += futex.o
ifeq ($(CONFIG_COMPAT),y)
obj-$(CONFIG_FUTEX) += futex_compat.o
endif
obj-$(CONFIG_GENERIC_ISA_DMA) += dma.o
obj-$(CONFIG_SMP) += smp.o
ifneq ($(CONFIG_SMP),y)
obj-y += up.o
endif
obj-$(CONFIG_UID16) += uid16.o
obj-$(CONFIG_SYSTEM_TRUSTED_KEYRING) += system_keyring.o system_certificates.o
obj-$(CONFIG_MODULES) += module.o
obj-$(CONFIG_MODULE_SIG) += module_signing.o
obj-$(CONFIG_KALLSYMS) += kallsyms.o
obj-$(CONFIG_BSD_PROCESS_ACCT) += acct.o
obj-$(CONFIG_KEXEC) += kexec.o
obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o
obj-$(CONFIG_COMPAT) += compat.o
obj-$(CONFIG_CGROUPS) += cgroup.o
obj-$(CONFIG_CGROUP_FREEZER) += cgroup_freezer.o
obj-$(CONFIG_CPUSETS) += cpuset.o
obj-$(CONFIG_UTS_NS) += utsname.o
obj-$(CONFIG_USER_NS) += user_namespace.o
obj-$(CONFIG_PID_NS) += pid_namespace.o
obj-$(CONFIG_IKCONFIG) += configs.o
obj-$(CONFIG_RESOURCE_COUNTERS) += res_counter.o
obj-$(CONFIG_SMP) += stop_machine.o
obj-$(CONFIG_KPROBES_SANITY_TEST) += test_kprobes.o
obj-$(CONFIG_AUDIT) += audit.o auditfilter.o
obj-$(CONFIG_AUDITSYSCALL) += auditsc.o
obj-$(CONFIG_AUDIT_WATCH) += audit_watch.o
obj-$(CONFIG_AUDIT_TREE) += audit_tree.o
obj-$(CONFIG_GCOV_KERNEL) += gcov/
obj-$(CONFIG_KPROBES) += kprobes.o
obj-$(CONFIG_KGDB) += debug/
obj-$(CONFIG_DETECT_HUNG_TASK) += hung_task.o
obj-$(CONFIG_LOCKUP_DETECTOR) += watchdog.o
obj-$(CONFIG_SECCOMP) += seccomp.o
obj-$(CONFIG_RELAY) += relay.o
obj-$(CONFIG_SYSCTL) += utsname_sysctl.o
obj-$(CONFIG_TASK_DELAY_ACCT) += delayacct.o
obj-$(CONFIG_TASKSTATS) += taskstats.o tsacct.o
obj-$(CONFIG_TRACEPOINTS) += tracepoint.o
obj-$(CONFIG_LATENCYTOP) += latencytop.o
obj-$(CONFIG_BINFMT_ELF) += elfcore.o
obj-$(CONFIG_COMPAT_BINFMT_ELF) += elfcore.o
obj-$(CONFIG_BINFMT_ELF_FDPIC) += elfcore.o
obj-$(CONFIG_FUNCTION_TRACER) += trace/
obj-$(CONFIG_TRACING) += trace/
obj-$(CONFIG_TRACE_CLOCK) += trace/
obj-$(CONFIG_RING_BUFFER) += trace/
obj-$(CONFIG_TRACEPOINTS) += trace/
obj-$(CONFIG_IRQ_WORK) += irq_work.o
obj-$(CONFIG_CPU_PM) += cpu_pm.o

obj-$(CONFIG_PERF_EVENTS) += events/

obj-$(CONFIG_USER_RETURN_NOTIFIER) += user-return-notifier.o
obj-$(CONFIG_PADATA) += padata.o
obj-$(CONFIG_CRASH_DUMP) += crash_dump.o
obj-$(CONFIG_JUMP_LABEL) += jump_label.o
obj-$(CONFIG_CONTEXT_TRACKING) += context_tracking.o

$(obj)/configs.o: $(obj)/config_data.h

# config_data.h contains the same information as ikconfig.h but gzipped.
# Info from config_data can be extracted from /proc/config*
targets += config_data.gz
$(obj)/config_data.gz: $(KCONFIG_CONFIG) FORCE
	$(call if_changed,gzip)

      filechk_ikconfiggz = (echo "static const char kernel_config_data[] __used = MAGIC_START"; cat $< | scripts/bin2c; echo "MAGIC_END;")
targets += config_data.h
$(obj)/config_data.h: $(obj)/config_data.gz FORCE
	$(call filechk,ikconfiggz)

$(obj)/time.o: $(obj)/timeconst.h

quiet_cmd_hzfile = HZFILE  $@
      cmd_hzfile = echo "hz=$(CONFIG_HZ)" > $@

targets += hz.bc
$(obj)/hz.bc: $(objtree)/include/config/hz.h FORCE
	$(call if_changed,hzfile)

quiet_cmd_bc  = BC      $@
      cmd_bc  = bc -q $(filter-out FORCE,$^) > $@

targets += timeconst.h
$(obj)/timeconst.h: $(obj)/hz.bc $(src)/timeconst.bc FORCE
	$(call if_changed,bc)

###############################################################################
#
# Roll all the X.509 certificates that we can find together and pull them into
# the kernel so that they get loaded into the system trusted keyring during
# boot.
#
# We look in the source root and the build root for all files whose name ends
# in ".x509".  Unfortunately, this will generate duplicate filenames, so we
# have make canonicalise the pathnames and then sort them to discard the
# duplicates.
#
###############################################################################
ifeq ($(CONFIG_SYSTEM_TRUSTED_KEYRING),y)
X509_CERTIFICATES-y := $(wildcard *.x509) $(wildcard $(srctree)/*.x509)
X509_CERTIFICATES-$(CONFIG_MODULE_SIG) += $(objtree)/signing_key.x509
X509_CERTIFICATES-raw := $(sort $(foreach CERT,$(X509_CERTIFICATES-y), \
				$(or $(realpath $(CERT)),$(CERT))))
X509_CERTIFICATES := $(subst $(realpath $(objtree))/,,$(X509_CERTIFICATES-raw))

ifeq ($(X509_CERTIFICATES),)
$(warning *** No X.509 certificates found ***)
endif

ifneq ($(wildcard $(obj)/.x509.list),)
ifneq ($(shell cat $(obj)/.x509.list),$(X509_CERTIFICATES))
$(info X.509 certificate list changed)
$(shell rm $(obj)/.x509.list)
endif
endif

kernel/system_certificates.o: $(obj)/x509_certificate_list

quiet_cmd_x509certs  = CERTS   $@
      cmd_x509certs  = cat $(X509_CERTIFICATES) /dev/null >$@ $(foreach X509,$(X509_CERTIFICATES),; echo "  - Including cert $(X509)")

targets += $(obj)/x509_certificate_list
$(obj)/x509_certificate_list: $(X509_CERTIFICATES) $(obj)/.x509.list
	$(call if_changed,x509certs)

targets += $(obj)/.x509.list
$(obj)/.x509.list:
	@echo $(X509_CERTIFICATES) >$@
endif

clean-files := x509_certificate_list .x509.list

ifeq ($(CONFIG_MODULE_SIG),y)
###############################################################################
#
# If module signing is requested, say by allyesconfig, but a key has not been
# supplied, then one will need to be generated to make sure the build does not
# fail and that the kernel may be used afterwards.
#
###############################################################################
ifndef CONFIG_MODULE_SIG_HASH
$(error Could not determine digest type to use from kernel config)
endif

signing_key.priv signing_key.x509: x509.genkey
	@echo "###"
	@echo "### Now generating an X.509 key pair to be used for signing modules."
	@echo "###"
	@echo "### If this takes a long time, you might wish to run rngd in the"
	@echo "### background to keep the supply of entropy topped up.  It"
	@echo "### needs to be run as root, and uses a hardware random"
	@echo "### number generator if one is available."
	@echo "###"
	openssl req -new -nodes -utf8 -$(CONFIG_MODULE_SIG_HASH) -days 36500 \
		-batch -x509 -config x509.genkey \
		-outform DER -out signing_key.x509 \
		-keyout signing_key.priv 2>&1
	@echo "###"
	@echo "### Key pair generated."
	@echo "###"

x509.genkey:
	@echo Generating X.509 key generation config
	@echo  >x509.genkey "[ req ]"
	@echo >>x509.genkey "default_bits = 4096"
	@echo >>x509.genkey "distinguished_name = req_distinguished_name"
	@echo >>x509.genkey "prompt = no"
	@echo >>x509.genkey "string_mask = utf8only"
	@echo >>x509.genkey "x509_extensions = myexts"
	@echo >>x509.genkey
	@echo >>x509.genkey "[ req_distinguished_name ]"
	@echo >>x509.genkey "O = Magrathea"
	@echo >>x509.genkey "CN = Glacier signing key"
	@echo >>x509.genkey "emailAddress = slartibartfast@magrathea.h2g2"
	@echo >>x509.genkey
	@echo >>x509.genkey "[ myexts ]"
	@echo >>x509.genkey "basicConstraints=critical,CA:FALSE"
	@echo >>x509.genkey "keyUsage=digitalSignature"
	@echo >>x509.genkey "subjectKeyIdentifier=hash"
	@echo >>x509.genkey "authorityKeyIdentifier=keyid"
endif


text:
from __future__ import print_function

import argparse
import multiprocessing
import os
import shutil
import subprocess
import sys
import settings

def default_toolchain():
    # We don't have default toolchain on Windows and os.uname() isn't supported.
    if sys.platform == 'win32':
        return None

    (sysname, _, _, _, machine) = os.uname()
    toolchain = os.path.join(settings.PROJECT_DIR,
                             'cmake',
                             'toolchain_%s_%s.cmake' % (sysname.lower(), machine.lower()))
    return toolchain if os.path.isfile(toolchain) else None

def get_arguments():
    devhelp_preparser = argparse.ArgumentParser(add_help=False)
    devhelp_preparser.add_argument('--devhelp', action='store_true', default=False,
                                   help='show help with all options '
                                        '(including those, which are useful for developers only)')

    devhelp_arguments, args = devhelp_preparser.parse_known_args()
    if devhelp_arguments.devhelp:
        args.append('--devhelp')

    def devhelp(helpstring):
        return helpstring if devhelp_arguments.devhelp else argparse.SUPPRESS

    parser = argparse.ArgumentParser(parents=[devhelp_preparser], epilog="""
        This tool is a thin wrapper around cmake and make to help build the
        project easily. All the real build logic is in the CMakeLists.txt files.
        For most of the options, the defaults are also defined there.
        """)

    buildgrp = parser.add_argument_group('general build options')
    buildgrp.add_argument('--builddir', metavar='DIR', default=os.path.join(settings.PROJECT_DIR, 'build'),
                          help='specify build directory (default: %(default)s)')
    buildgrp.add_argument('--clean', action='store_true', default=False,
                          help='clean build')
    buildgrp.add_argument('--cmake-param', metavar='OPT', action='append', default=[],
                          help='add custom argument to CMake')
    buildgrp.add_argument('--compile-flag', metavar='OPT', action='append', default=[],
                          help='add custom compile flag')
    buildgrp.add_argument('--build-type', metavar='TYPE', default='MinSizeRel',
                          help='set build type (default: %(default)s)')
    buildgrp.add_argument('--debug', dest='build_type', action='store_const', const='Debug', default=argparse.SUPPRESS,
                          help='debug build (alias for --build-type %(const)s)')
    buildgrp.add_argument('--install', metavar='DIR', nargs='?', default=None, const=False,
                          help='install after build (default: don\'t install; '
                               'default directory if install: OS-specific)')
    buildgrp.add_argument('-j', '--jobs', metavar='N', type=int, default=multiprocessing.cpu_count() + 1,
                          help='number of parallel build jobs (default: %(default)s)')
    buildgrp.add_argument('--link-lib', metavar='OPT', action='append', default=[],
                          help='add custom library to be linked')
    buildgrp.add_argument('--linker-flag', metavar='OPT', action='append', default=[],
                          help='add custom linker flag')
    buildgrp.add_argument('--amalgam', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                          help='enable amalgamated build (%(choices)s)')
    buildgrp.add_argument('--lto', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                          help='enable link-time optimizations (%(choices)s)')
    buildgrp.add_argument('--shared-libs', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                          help='enable building of shared libraries (%(choices)s)')
    buildgrp.add_argument('--strip', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                          help='strip release binaries (%(choices)s)')
    buildgrp.add_argument('--toolchain', metavar='FILE', default=default_toolchain(),
                          help='specify toolchain file (default: %(default)s)')
    buildgrp.add_argument('-v', '--verbose', action='store_const', const='ON',
                          help='increase verbosity')

    compgrp = parser.add_argument_group('optional components')
    compgrp.add_argument('--doctests', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('build doctests (%(choices)s)'))
    compgrp.add_argument('--jerry-cmdline', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='build jerry command line tool (%(choices)s)')
    compgrp.add_argument('--jerry-cmdline-snapshot', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='build snapshot command line tool (%(choices)s)')
    compgrp.add_argument('--jerry-cmdline-test', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('build test version of the jerry command line tool (%(choices)s)'))
    compgrp.add_argument('--libfuzzer', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('build jerry with libfuzzer support (%(choices)s)'))
    compgrp.add_argument('--jerry-ext', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='build jerry-ext (%(choices)s)')
    compgrp.add_argument('--jerry-math', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='build and use jerry-math (%(choices)s)')
    compgrp.add_argument('--jerry-port-default', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='build default jerry port implementation (%(choices)s)')
    compgrp.add_argument('--unittests', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('build unittests (%(choices)s)'))

    coregrp = parser.add_argument_group('jerry-core options')
    coregrp.add_argument('--cpointer-32bit', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable 32 bit compressed pointers (%(choices)s)')
    coregrp.add_argument('--error-messages', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable error messages (%(choices)s)')
    coregrp.add_argument('--external-context', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable external context (%(choices)s)')
    coregrp.add_argument('--jerry-debugger', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable the jerry debugger (%(choices)s)')
    coregrp.add_argument('--js-parser', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable js-parser (%(choices)s)')
    coregrp.add_argument('--function-to-string', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable function toString (%(choices)s)')
    coregrp.add_argument('--line-info', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='provide line info (%(choices)s)')
    coregrp.add_argument('--logging', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable logging (%(choices)s)')
    coregrp.add_argument('--mem-heap', metavar='SIZE', type=int,
                         help='size of memory heap (in kilobytes)')
    coregrp.add_argument('--gc-limit', metavar='SIZE', type=int,
                         help='memory usage limit to trigger garbage collection (in bytes)')
    coregrp.add_argument('--stack-limit', metavar='SIZE', type=int,
                         help='maximum stack usage (in kilobytes)')
    coregrp.add_argument('--gc-mark-limit', metavar='SIZE', type=int,
                         help='maximum depth of recursion during GC mark phase')
    coregrp.add_argument('--mem-stats', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable memory statistics (%(choices)s)'))
    coregrp.add_argument('--mem-stress-test', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable mem-stress test (%(choices)s)'))
    coregrp.add_argument('--profile', metavar='FILE',
                         help='specify profile file')
    coregrp.add_argument('--promise-callback', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable promise callback (%(choices)s)')
    coregrp.add_argument('--regexp-strict-mode', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable regexp strict mode (%(choices)s)'))
    coregrp.add_argument('--show-opcodes', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable parser byte-code dumps (%(choices)s)'))
    coregrp.add_argument('--show-regexp-opcodes', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable regexp byte-code dumps (%(choices)s)'))
    coregrp.add_argument('--snapshot-exec', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable executing snapshot files (%(choices)s)')
    coregrp.add_argument('--snapshot-save', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable saving snapshot files (%(choices)s)')
    coregrp.add_argument('--system-allocator', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable system allocator (%(choices)s)')
    coregrp.add_argument('--valgrind', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable Valgrind support (%(choices)s)'))
    coregrp.add_argument('--vm-exec-stop', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable VM execution stop callback (%(choices)s)')
    coregrp.add_argument('--vm-throw', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help='enable VM throw callback (%(choices)s)')

    maingrp = parser.add_argument_group('jerry-main options')
    maingrp.add_argument('--link-map', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable the generation of link map for jerry command line tool (%(choices)s)'))
    maingrp.add_argument('--compile-commands', metavar='X', choices=['ON', 'OFF'], type=str.upper,
                         help=devhelp('enable the generation of compile_commands.json (%(choices)s)'))

    arguments = parser.parse_args(args)
    if arguments.devhelp:
        parser.print_help()
        sys.exit(0)

    return arguments

def generate_build_options(arguments):
    build_options = []

    def build_options_append(cmakeopt, cliarg):
        if cliarg:
            build_options.append('-D%s=%s' % (cmakeopt, cliarg))

    # general build options
    build_options_append('CMAKE_BUILD_TYPE', arguments.build_type)
    build_options_append('EXTERNAL_COMPILE_FLAGS', ' '.join(arguments.compile_flag))
    build_options_append('EXTERNAL_LINK_LIBS', ' '.join(arguments.link_lib))
    build_options_append('EXTERNAL_LINKER_FLAGS', ' '.join(arguments.linker_flag))
    build_options_append('ENABLE_AMALGAM', arguments.amalgam)
    build_options_append('ENABLE_LTO', arguments.lto)
    build_options_append('BUILD_SHARED_LIBS', arguments.shared_libs)
    build_options_append('ENABLE_STRIP', arguments.strip)
    build_options_append('CMAKE_TOOLCHAIN_FILE', arguments.toolchain)
    build_options_append('CMAKE_VERBOSE_MAKEFILE', arguments.verbose)

    # optional components
    build_options_append('DOCTESTS', arguments.doctests)
    build_options_append('JERRY_CMDLINE', arguments.jerry_cmdline)
    build_options_append('JERRY_CMDLINE_SNAPSHOT', arguments.jerry_cmdline_snapshot)
    build_options_append('JERRY_CMDLINE_TEST', arguments.jerry_cmdline_test)
    build_options_append('JERRY_LIBFUZZER', arguments.libfuzzer)
    build_options_append('JERRY_EXT', arguments.jerry_ext)
    build_options_append('JERRY_MATH', arguments.jerry_math)
    build_options_append('JERRY_PORT_DEFAULT', arguments.jerry_port_default)
    build_options_append('UNITTESTS', arguments.unittests)

    # jerry-core options
    build_options_append('JERRY_CPOINTER_32_BIT', arguments.cpointer_32bit)
    build_options_append('JERRY_ERROR_MESSAGES', arguments.error_messages)
    build_options_append('JERRY_EXTERNAL_CONTEXT', arguments.external_context)
    build_options_append('JERRY_DEBUGGER', arguments.jerry_debugger)
    build_options_append('JERRY_PARSER', arguments.js_parser)
    build_options_append('JERRY_FUNCTION_TO_STRING', arguments.function_to_string)
    build_options_append('JERRY_LINE_INFO', arguments.line_info)
    build_options_append('JERRY_LOGGING', arguments.logging)
    build_options_append('JERRY_GLOBAL_HEAP_SIZE', arguments.mem_heap)
    build_options_append('JERRY_GC_LIMIT', arguments.gc_limit)
    build_options_append('JERRY_STACK_LIMIT', arguments.stack_limit)
    build_options_append('JERRY_MEM_STATS', arguments.mem_stats)
    build_options_append('JERRY_MEM_GC_BEFORE_EACH_ALLOC', arguments.mem_stress_test)
    build_options_append('JERRY_PROFILE', arguments.profile)
    build_options_append('JERRY_PROMISE_CALLBACK', arguments.promise_callback)
    build_options_append('JERRY_REGEXP_STRICT_MODE', arguments.regexp_strict_mode)
    build_options_append('JERRY_PARSER_DUMP_BYTE_CODE', arguments.show_opcodes)
    build_options_append('JERRY_REGEXP_DUMP_BYTE_CODE', arguments.show_regexp_opcodes)
    build_options_append('JERRY_SNAPSHOT_EXEC', arguments.snapshot_exec)
    build_options_append('JERRY_SNAPSHOT_SAVE', arguments.snapshot_save)
    build_options_append('JERRY_SYSTEM_ALLOCATOR', arguments.system_allocator)
    build_options_append('JERRY_VALGRIND', arguments.valgrind)
    build_options_append('JERRY_VM_EXEC_STOP', arguments.vm_exec_stop)
    build_options_append('JERRY_VM_THROW', arguments.vm_throw)

    if arguments.gc_mark_limit is not None:
        build_options.append('-D%s=%s' % ('JERRY_GC_MARK_LIMIT', arguments.gc_mark_limit))

    # jerry-main options
    build_options_append('ENABLE_LINK_MAP', arguments.link_map)
    build_options_append('ENABLE_COMPILE_COMMANDS', arguments.compile_commands)

    # general build options (final step)
    if arguments.cmake_param:
        build_options.extend(arguments.cmake_param)

    return build_options

def configure_output_dir(arguments):
    if not os.path.isabs(arguments.builddir):
        arguments.builddir = os.path.join(settings.PROJECT_DIR, arguments.builddir)

    if arguments.clean and os.path.exists(arguments.builddir):
        shutil.rmtree(arguments.builddir)

    if not os.path.exists(arguments.builddir):
        os.makedirs(arguments.builddir)

def configure_jerry(arguments):
    configure_output_dir(arguments)

    build_options = generate_build_options(arguments)

    cmake_cmd = ['cmake', '-B' + arguments.builddir, '-H' + settings.PROJECT_DIR]

    if arguments.install:
        cmake_cmd.append('-DCMAKE_INSTALL_PREFIX=%s' % arguments.install)

    cmake_cmd.extend(build_options)

    return subprocess.call(cmake_cmd)

def make_jerry(arguments):
    make_cmd = ['cmake', '--build', arguments.builddir, '--config', arguments.build_type]
    env = dict(os.environ)
    env['CMAKE_BUILD_PARALLEL_LEVEL'] = str(arguments.jobs)
    env['MAKEFLAGS'] = '-j%d' % (arguments.jobs) # Workaround for CMake < 3.12
    proc = subprocess.Popen(make_cmd, env=env)
    proc.wait()

    return proc.returncode

def install_jerry(arguments):
    install_target = 'INSTALL' if os.path.exists(os.path.join(arguments.builddir, 'Jerry.sln')) else 'install'
    make_cmd = ['cmake', '--build', arguments.builddir, '--config', arguments.build_type, '--target', install_target]
    return subprocess.call(make_cmd)

def print_result(ret):
    print('=' * 30)
    if ret:
        print('Build failed with exit code: %s' % (ret))
    else:
        print('Build succeeded!')
    print('=' * 30)

def main():
    arguments = get_arguments()

    ret = configure_jerry(arguments)

    if not ret:
        ret = make_jerry(arguments)

    if not ret and arguments.install is not None:
        ret = install_jerry(arguments)

    print_result(ret)
    sys.exit(ret)

if __name__ == "__main__":
    main()


text:
var Client = require('../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getBillingInfo: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/orders/{orderId}/billinginfo?draft={draft}&responseFields={responseFields}'
	}),
	setBillingInfo: Client.method({
		method: constants.verbs.PUT,
		url: '{+tenantPod}api/commerce/orders/{orderId}/billinginfo?updatemode={updateMode}&version={version}&responseFields={responseFields}'
	})
});


text:
/* global XMLHttpRequest */
import { context } from './context'

var NONE = {}
/**
 * This module contains some functions to fetch and decode audio files.
 *
 * @module load
 */

/**
 * Load a remote audio file and return a promise.
 * @param {String} url
 * @param {Object} options - (Optional) may include:
 *
 * - context: the audio context
 *
 * @return {Promise<AudioBuffer>} a promise that resolves to an AudioBuffer
 * @example
 * load('sound.mp3').then(function (buffer) {
 *   sample(buffer, true).start()
 * }
 */
export function load (url, opts) {
  opts = opts || NONE
  return fetch(url, 'arraybuffer').then(decodeAudio(context(opts.context)))
}

/**
 * Fetch an url and return a promise
 * @param {String} url - the url
 * @param {String} type - can be 'text' or 'arraybuffer'
 * @return {Promise} a promise to the result
 */
export function fetch (url, type) {
  type = type === 'arraybuffer' ? type : 'text'
  return new Promise(function (resolve, reject) {
    var xhr = new XMLHttpRequest()

    xhr.open('GET', url, true)
    xhr.responseType = type

    xhr.onload = function () {
      if (xhr.response) {
        resolve(xhr.response)
      }
    }
    xhr.onerror = reject

    xhr.send()
  })
}

/**
 * Decode an array buffer into an AudioBuffer.
 * @param {AudioContext} context - (Optional) the context to be used (can be null to use
 * synth-kit's default audio context)
 * @param {Array} array - (Optional) the array to be decoded. If not given,
 * it returns a function that decodes the buffer so it can be chained with
 * fetch function (see example)
 * @return {Promise<AudioBuffer>} a promise that resolves to an audio buffer
 * @example
 * fecth('sound.mp3').then(decodeAudio())
 */
export function decodeAudio (ac, arrayBuffer) {
  if (arguments.length === 1) return function (array) { return decodeAudio(ac, array) }
  return new Promise(function (resolve, reject) {
    ac.decodeAudioData(arrayBuffer, resolve, reject)
  })
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Ens\JobeetBundle\Tests\Utils;

use Ens\JobeetBundle\Utils\Jobeet;

class JobeetTest extends \PHPUnit_Framework_TestCase {

    static public function slugify($text) {

        // replace non letter or digits by -
        $text = preg_replace('#[^\\pL\d]+#u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        if (function_exists('iconv')) {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        }

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('#[^-\w]+#', '', $text);

        if (empty($test)) {
            return 'n-a';
        }

        return $test;
    }

    public function testSlugify() {
        $this->assertEquals('sensio', Jobeet::slugify('Sensio'));
        $this->assertEquals('sensio-labs', Jobeet::slugify('sensio labs'));
        $this->assertEquals('sensio-labs', Jobeet::slugify('sensio labs'));
        $this->assertEquals('paris-france', Jobeet::slugify('paris,france'));
        $this->assertEquals('sensio', Jobeet::slugify(' sensio'));
        $this->assertEquals('sensio', Jobeet::slugify('sensio '));
        $this->assertEquals('n-a', Jobeet::slugify(' - '));
        if (function_exists('iconv')) {
            $this->assertEquals('developpeur-web', Jobeet::slugify('Développeur Web'));
        }
    }

}


text:
require 'ruby-debug'
require File.dirname(__FILE__) << "/lib/has_own_logger.rb"
class ActiveRecord::Base
  include ClassLogger
end