text:
"""
Views for managing instances.
"""
from collections import OrderedDict
import logging

from django.conf import settings
from django import http
from django import shortcuts
from django.urls import reverse
from django.urls import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views import generic

from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon import tables
from horizon import tabs
from horizon.utils import memoized
from horizon import workflows

from openstack_dashboard import api
from openstack_dashboard.utils import filters

from openstack_dashboard.dashboards.project.instances \
    import console as project_console
from openstack_dashboard.dashboards.project.instances \
    import forms as project_forms
from openstack_dashboard.dashboards.project.instances \
    import tables as project_tables
from openstack_dashboard.dashboards.project.instances \
    import tabs as project_tabs
from openstack_dashboard.dashboards.project.instances \
    import workflows as project_workflows
from openstack_dashboard.dashboards.project.networks.ports \
    import views as port_views
from openstack_dashboard.utils import futurist_utils
from openstack_dashboard.views import get_url_with_pagination

LOG = logging.getLogger(__name__)

class IndexView(tables.DataTableView):
    table_class = project_tables.InstancesTable
    page_title = _("Instances")

    def has_more_data(self, table):
        return self._more

    def _get_flavors(self):
        # Gather our flavors to correlate our instances to them
        try:
            flavors = api.nova.flavor_list(self.request)
            return dict([(str(flavor.id), flavor) for flavor in flavors])
        except Exception:
            exceptions.handle(self.request, ignore=True)
            return {}

    def _get_images(self):
        # Gather our images to correlate our instances to them
        try:
            # TODO(gabriel): Handle pagination.
            images = api.glance.image_list_detailed(self.request)[0]
            return dict([(str(image.id), image) for image in images])
        except Exception:
            exceptions.handle(self.request, ignore=True)
            return {}

    def _get_instances(self, search_opts):
        try:
            instances, self._more = api.nova.server_list(
                self.request,
                search_opts=search_opts)
        except Exception:
            self._more = False
            instances = []
            exceptions.handle(self.request,
                              _('Unable to retrieve instances.'))

        # In case of exception when calling nova.server_list
        # don't call api.network
        if not instances:
            return []

        # TODO(future): Explore more efficient logic to sync IP address
        # and drop the setting OPENSTACK_INSTANCE_RETRIEVE_IP_ADDRESSES.
        # The situation servers_update_addresses() is needed is only
        # when IP address of a server is updated via neutron API and
        # nova network info cache is not synced. Precisely there is no
        # need to check IP addresses of all servers. It is sufficient to
        # fetch IP address information for servers recently updated.
        if not getattr(settings,
                       'OPENSTACK_INSTANCE_RETRIEVE_IP_ADDRESSES', True):
            return instances
        try:
            api.network.servers_update_addresses(self.request, instances)
        except Exception:
            exceptions.handle(
                self.request,
                message=_('Unable to retrieve IP addresses from Neutron.'),
                ignore=True)

        return instances

    def get_data(self):
        marker = self.request.GET.get(
            project_tables.InstancesTable._meta.pagination_param, None)
        search_opts = self.get_filters({'marker': marker, 'paginate': True})

        image_dict, flavor_dict = futurist_utils.call_functions_parallel(
            self._get_images, self._get_flavors)

        non_api_filter_info = (
            ('image_name', 'image', image_dict.values()),
            ('flavor_name', 'flavor', flavor_dict.values()),
        )
        if not process_non_api_filters(search_opts, non_api_filter_info):
            self._more = False
            return []

        instances = self._get_instances(search_opts)

        # Loop through instances to get flavor info.
        for instance in instances:
            if hasattr(instance, 'image'):
                # Instance from image returns dict
                if isinstance(instance.image, dict):
                    image_id = instance.image.get('id')
                    if image_id in image_dict:
                        instance.image = image_dict[image_id]
                    # In case image not found in image_dict, set name to empty
                    # to avoid fallback API call to Glance in api/nova.py
                    # until the call is deprecated in api itself
                    else:
                        instance.image['name'] = _("-")

            flavor_id = instance.flavor["id"]
            if flavor_id in flavor_dict:
                instance.full_flavor = flavor_dict[flavor_id]
            else:
                # If the flavor_id is not in flavor_dict,
                # put info in the log file.
                LOG.info('Unable to retrieve flavor "%s" for instance "%s".',
                         flavor_id, instance.id)

        return instances

def process_non_api_filters(search_opts, non_api_filter_info):
    """Process filters by non-API fields

    There are cases where it is useful to provide a filter field
    which does not exist in a resource in a backend service.
    For example, nova server list provides 'image' field with image ID
    but 'image name' is more useful for GUI users.
    This function replaces fake fields into corresponding real fields.

    The format of non_api_filter_info is a tuple/list of
    (fake_field, real_field, resources).

    This returns True if further lookup is required.
    It returns False if there are no matching resources,
    for example, if no corresponding real field exists.
    """
    for fake_field, real_field, resources in non_api_filter_info:
        if not _swap_filter(resources, search_opts, fake_field, real_field):
            return False
    return True

def _swap_filter(resources, search_opts, fake_field, real_field):
    if fake_field not in search_opts:
        return True
    filter_string = search_opts[fake_field]
    matched = [resource for resource in resources
               if resource.name.lower() == filter_string.lower()]
    if not matched:
        return False
    search_opts[real_field] = matched[0].id
    del search_opts[fake_field]
    return True

class LaunchInstanceView(workflows.WorkflowView):
    workflow_class = project_workflows.LaunchInstance

    def get_initial(self):
        initial = super(LaunchInstanceView, self).get_initial()
        initial['project_id'] = self.request.user.tenant_id
        initial['user_id'] = self.request.user.id
        defaults = getattr(settings, 'LAUNCH_INSTANCE_DEFAULTS', {})
        initial['config_drive'] = defaults.get('config_drive', False)
        return initial

def console(request, instance_id):
    data = _('Unable to get log for instance "%s".') % instance_id
    tail = request.GET.get('length')
    if tail and not tail.isdigit():
        msg = _('Log length must be a nonnegative integer.')
        messages.warning(request, msg)
    else:
        try:
            data = api.nova.server_console_output(request,
                                                  instance_id,
                                                  tail_length=tail)
        except Exception:
            exceptions.handle(request, ignore=True)
    return http.HttpResponse(data.encode('utf-8'), content_type='text/plain')

def auto_console(request, instance_id):
    console_type = getattr(settings, 'CONSOLE_TYPE', 'AUTO')
    try:
        instance = api.nova.server_get(request, instance_id)
        console_url = project_console.get_console(request, console_type,
                                                  instance)[1]
        return shortcuts.redirect(console_url)
    except Exception:
        redirect = reverse("horizon:project:instances:index")
        msg = _('Unable to get console for instance "%s".') % instance_id
        exceptions.handle(request, msg, redirect=redirect)

def vnc(request, instance_id):
    try:
        instance = api.nova.server_get(request, instance_id)
        console_url = project_console.get_console(request, 'VNC', instance)[1]
        return shortcuts.redirect(console_url)
    except Exception:
        redirect = reverse("horizon:project:instances:index")
        msg = _('Unable to get VNC console for instance "%s".') % instance_id
        exceptions.handle(request, msg, redirect=redirect)

def mks(request, instance_id):
    try:
        instance = api.nova.server_get(request, instance_id)
        console_url = project_console.get_console(request, 'MKS', instance)[1]
        return shortcuts.redirect(console_url)
    except Exception:
        redirect = reverse("horizon:project:instances:index")
        msg = _('Unable to get MKS console for instance "%s".') % instance_id
        exceptions.handle(request, msg, redirect=redirect)

def spice(request, instance_id):
    try:
        instance = api.nova.server_get(request, instance_id)
        console_url = project_console.get_console(request, 'SPICE',
                                                  instance)[1]
        return shortcuts.redirect(console_url)
    except Exception:
        redirect = reverse("horizon:project:instances:index")
        msg = _('Unable to get SPICE console for instance "%s".') % instance_id
        exceptions.handle(request, msg, redirect=redirect)

def rdp(request, instance_id):
    try:
        instance = api.nova.server_get(request, instance_id)
        console_url = project_console.get_console(request, 'RDP', instance)[1]
        return shortcuts.redirect(console_url)
    except Exception:
        redirect = reverse("horizon:project:instances:index")
        msg = _('Unable to get RDP console for instance "%s".') % instance_id
        exceptions.handle(request, msg, redirect=redirect)

class SerialConsoleView(generic.TemplateView):
    template_name = 'serial_console.html'

    def get_context_data(self, **kwargs):
        context = super(SerialConsoleView, self).get_context_data(**kwargs)
        instance = None
        try:
            instance = api.nova.server_get(self.request,
                                           self.kwargs['instance_id'])
        except Exception:
            context["error_message"] = _(
                "Cannot find instance %s.") % self.kwargs['instance_id']
            # name is unknown, so leave it blank for the window title
            # in full-screen mode, so only the instance id is shown.
            context['page_title'] = self.kwargs['instance_id']
            return context
        context['page_title'] = "%s (%s)" % (instance.name, instance.id)
        try:
            console_url = project_console.get_console(self.request,
                                                      "SERIAL", instance)[1]
            context["console_url"] = console_url
            context["protocols"] = "['binary', 'base64']"
        except exceptions.NotAvailable:
            context["error_message"] = _(
                "Cannot get console for instance %s.") % self.kwargs[
                'instance_id']
        return context

class UpdateView(workflows.WorkflowView):
    workflow_class = project_workflows.UpdateInstance
    success_url = reverse_lazy("horizon:project:instances:index")

    def get_context_data(self, **kwargs):
        context = super(UpdateView, self).get_context_data(**kwargs)
        context["instance_id"] = self.kwargs['instance_id']
        return context

    @memoized.memoized_method
    def get_object(self, *args, **kwargs):
        instance_id = self.kwargs['instance_id']
        try:
            return api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse("horizon:project:instances:index")
            msg = _('Unable to retrieve instance details.')
            exceptions.handle(self.request, msg, redirect=redirect)

    def get_initial(self):
        initial = super(UpdateView, self).get_initial()
        instance = self.get_object()
        initial.update({'instance_id': self.kwargs['instance_id'],
                        'name': getattr(instance, 'name', ''),
                        'description': getattr(instance, 'description', ''),
                        'target_tenant_id': self.request.user.tenant_id})
        return initial

class RebuildView(forms.ModalFormView):
    form_class = project_forms.RebuildInstanceForm
    template_name = 'project/instances/rebuild.html'
    success_url = reverse_lazy('horizon:project:instances:index')
    page_title = _("Rebuild Instance")
    submit_label = page_title

    def get_context_data(self, **kwargs):
        context = super(RebuildView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        context['can_set_server_password'] = api.nova.can_set_server_password()
        return context

    @memoized.memoized_method
    def get_object(self, *args, **kwargs):
        instance_id = self.kwargs['instance_id']
        try:
            return api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse("horizon:project:instances:index")
            msg = _('Unable to retrieve instance details.')
            exceptions.handle(self.request, msg, redirect=redirect)

    def get_initial(self):
        instance = self.get_object()
        initial = {'instance_id': self.kwargs['instance_id'],
                   'description': getattr(instance, 'description', '')}
        return initial

class DecryptPasswordView(forms.ModalFormView):
    form_class = project_forms.DecryptPasswordInstanceForm
    template_name = 'project/instances/decryptpassword.html'
    success_url = reverse_lazy('horizon:project:instances:index')
    page_title = _("Retrieve Instance Password")

    def get_context_data(self, **kwargs):
        context = super(DecryptPasswordView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        context['keypair_name'] = self.kwargs['keypair_name']
        return context

    def get_initial(self):
        return {'instance_id': self.kwargs['instance_id'],
                'keypair_name': self.kwargs['keypair_name']}

class DisassociateView(forms.ModalFormView):
    form_class = project_forms.Disassociate
    template_name = 'project/instances/disassociate.html'
    success_url = reverse_lazy('horizon:project:instances:index')
    page_title = _("Disassociate floating IP")
    submit_label = _("Disassocaite")

    def get_context_data(self, **kwargs):
        context = super(DisassociateView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        return context

    def get_initial(self):
        return {'instance_id': self.kwargs['instance_id']}

class DetailView(tabs.TabView):
    tab_group_class = project_tabs.InstanceDetailTabs
    template_name = 'horizon/common/_detail.html'
    redirect_url = 'horizon:project:instances:index'
    page_title = "{{ instance.name|default:instance.id }}"
    image_url = 'horizon:project:images:images:detail'
    volume_url = 'horizon:project:volumes:detail'

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        instance = self.get_data()
        if instance.image:
            instance.image_url = reverse(self.image_url,
                                         args=[instance.image['id']])
        instance.volume_url = self.volume_url
        context["instance"] = instance
        context["url"] = get_url_with_pagination(
            self.request,
            project_tables.InstancesTable._meta.pagination_param,
            project_tables.InstancesTable._meta.prev_pagination_param,
            self.redirect_url)

        context["actions"] = self._get_actions(instance)
        return context

    def _get_actions(self, instance):
        table = project_tables.InstancesTable(self.request)
        return table.render_row_actions(instance)

    def _get_volumes(self, instance):
        instance_id = instance.id
        try:
            instance.volumes = api.nova.instance_volumes_list(self.request,
                                                              instance_id)
            # Sort by device name
            instance.volumes.sort(key=lambda vol: vol.device)
        except Exception:
            msg = _('Unable to retrieve volume list for instance '
                    '"%(name)s" (%(id)s).') % {'name': instance.name,
                                               'id': instance_id}
            exceptions.handle(self.request, msg, ignore=True)

    def _get_flavor(self, instance):
        instance_id = instance.id
        try:
            instance.full_flavor = api.nova.flavor_get(
                self.request, instance.flavor["id"])
        except Exception:
            msg = _('Unable to retrieve flavor information for instance '
                    '"%(name)s" (%(id)s).') % {'name': instance.name,
                                               'id': instance_id}
            exceptions.handle(self.request, msg, ignore=True)

    def _get_security_groups(self, instance):
        instance_id = instance.id
        try:
            instance.security_groups = api.neutron.server_security_groups(
                self.request, instance_id)
        except Exception:
            msg = _('Unable to retrieve security groups for instance '
                    '"%(name)s" (%(id)s).') % {'name': instance.name,
                                               'id': instance_id}
            exceptions.handle(self.request, msg, ignore=True)

    def _update_addresses(self, instance):
        instance_id = instance.id
        try:
            api.network.servers_update_addresses(self.request, [instance])
        except Exception:
            msg = _('Unable to retrieve IP addresses from Neutron for '
                    'instance "%(name)s" (%(id)s).') \
                % {'name': instance.name, 'id': instance_id}
            exceptions.handle(self.request, msg, ignore=True)

    @memoized.memoized_method
    def get_data(self):
        instance_id = self.kwargs['instance_id']

        try:
            instance = api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse(self.redirect_url)
            exceptions.handle(self.request,
                              _('Unable to retrieve details for '
                                'instance "%s".') % instance_id,
                              redirect=redirect)
            # Not all exception types handled above will result in a redirect.
            # Need to raise here just in case.
            raise exceptions.Http302(redirect)

        choices = project_tables.STATUS_DISPLAY_CHOICES
        instance.status_label = (
            filters.get_display_label(choices, instance.status))

        futurist_utils.call_functions_parallel(
            (self._get_volumes, [instance]),
            (self._get_flavor, [instance]),
            (self._get_security_groups, [instance]),
            (self._update_addresses, [instance]),
        )

        return instance

    def get_tabs(self, request, *args, **kwargs):
        instance = self.get_data()
        return self.tab_group_class(request, instance=instance, **kwargs)

class ResizeView(workflows.WorkflowView):
    workflow_class = project_workflows.ResizeInstance
    success_url = reverse_lazy("horizon:project:instances:index")

    def get_context_data(self, **kwargs):
        context = super(ResizeView, self).get_context_data(**kwargs)
        context["instance_id"] = self.kwargs['instance_id']
        return context

    @memoized.memoized_method
    def get_object(self, *args, **kwargs):
        instance_id = self.kwargs['instance_id']
        try:
            instance = api.nova.server_get(self.request, instance_id)
        except Exception:
            redirect = reverse("horizon:project:instances:index")
            msg = _('Unable to retrieve instance details.')
            exceptions.handle(self.request, msg, redirect=redirect)
        flavor_id = instance.flavor['id']
        flavors = self.get_flavors()
        if flavor_id in flavors:
            instance.flavor_name = flavors[flavor_id].name
        else:
            try:
                flavor = api.nova.flavor_get(self.request, flavor_id)
                instance.flavor_name = flavor.name
            except Exception:
                msg = _('Unable to retrieve flavor information for instance '
                        '"%s".') % instance_id
                exceptions.handle(self.request, msg, ignore=True)
                instance.flavor_name = _("Not available")
        return instance

    @memoized.memoized_method
    def get_flavors(self, *args, **kwargs):
        try:
            flavors = api.nova.flavor_list(self.request)
            return OrderedDict((str(flavor.id), flavor) for flavor in flavors)
        except Exception:
            redirect = reverse("horizon:project:instances:index")
            exceptions.handle(self.request,
                              _('Unable to retrieve flavors.'),
                              redirect=redirect)

    def get_initial(self):
        initial = super(ResizeView, self).get_initial()
        _object = self.get_object()
        if _object:
            initial.update(
                {'instance_id': self.kwargs['instance_id'],
                 'name': getattr(_object, 'name', None),
                 'old_flavor_id': _object.flavor['id'],
                 'old_flavor_name': getattr(_object, 'flavor_name', ''),
                 'flavors': self.get_flavors()})
        return initial

class AttachInterfaceView(forms.ModalFormView):
    form_class = project_forms.AttachInterface
    template_name = 'project/instances/attach_interface.html'
    page_title = _("Attach Interface")
    form_id = "attach_interface_form"
    submit_label = _("Attach Interface")
    success_url = reverse_lazy('horizon:project:instances:index')

    def get_context_data(self, **kwargs):
        context = super(AttachInterfaceView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        return context

    def get_initial(self):
        args = {'instance_id': self.kwargs['instance_id']}
        submit_url = "horizon:project:instances:attach_interface"
        self.submit_url = reverse(submit_url, kwargs=args)
        return args

class AttachVolumeView(forms.ModalFormView):
    form_class = project_forms.AttachVolume
    template_name = 'project/instances/attach_volume.html'
    page_title = _("Attach Volume")
    modal_id = "attach_volume_modal"
    submit_label = _("Attach Volume")
    success_url = reverse_lazy('horizon:project:instances:index')

    def get_initial(self):
        args = {'instance_id': self.kwargs['instance_id']}
        submit_url = "horizon:project:instances:attach_volume"
        self.submit_url = reverse(submit_url, kwargs=args)
        try:
            volume_list = api.cinder.volume_list(self.request)
        except Exception:
            volume_list = []
            exceptions.handle(self.request,
                              _("Unable to retrieve volume information."))
        return {"instance_id": self.kwargs["instance_id"],
                "volume_list": volume_list}

    def get_context_data(self, **kwargs):
        context = super(AttachVolumeView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        return context

class DetachVolumeView(forms.ModalFormView):
    form_class = project_forms.DetachVolume
    template_name = 'project/instances/detach_volume.html'
    page_title = _("Detach Volume")
    modal_id = "detach_volume_modal"
    submit_label = _("Detach Volume")
    success_url = reverse_lazy('horizon:project:instances:index')

    def get_initial(self):
        args = {'instance_id': self.kwargs['instance_id']}
        submit_url = "horizon:project:instances:detach_volume"
        self.submit_url = reverse(submit_url, kwargs=args)
        return {"instance_id": self.kwargs["instance_id"]}

    def get_context_data(self, **kwargs):
        context = super(DetachVolumeView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        return context

class DetachInterfaceView(forms.ModalFormView):
    form_class = project_forms.DetachInterface
    template_name = 'project/instances/detach_interface.html'
    page_title = _("Detach Interface")
    form_id = "detach_interface_form"
    submit_label = _("Detach Interface")
    success_url = reverse_lazy('horizon:project:instances:index')

    def get_context_data(self, **kwargs):
        context = super(DetachInterfaceView, self).get_context_data(**kwargs)
        context['instance_id'] = self.kwargs['instance_id']
        return context

    def get_initial(self):
        args = {"instance_id": self.kwargs["instance_id"]}
        submit_url = "horizon:project:instances:detach_interface"
        self.submit_url = reverse(submit_url, kwargs=args)
        return args

class UpdatePortView(port_views.UpdateView):
    workflow_class = project_workflows.UpdatePort
    failure_url = 'horizon:project:instances:detail'

    @memoized.memoized_method
    def _get_object(self, *args, **kwargs):
        port_id = self.kwargs['port_id']
        try:
            return api.neutron.port_get(self.request, port_id)
        except Exception:
            redirect = reverse(self.failure_url,
                               args=(self.kwargs['instance_id'],))
            msg = _('Unable to retrieve port details')
            exceptions.handle(self.request, msg, redirect=redirect)

    def get_initial(self):
        initial = super(UpdatePortView, self).get_initial()
        initial['instance_id'] = self.kwargs['instance_id']
        return initial

class RescueView(forms.ModalFormView):
    form_class = project_forms.RescueInstanceForm
    template_name = 'project/instances/rescue.html'
    submit_label = _("Confirm")
    submit_url = "horizon:project:instances:rescue"
    success_url = reverse_lazy('horizon:project:instances:index')
    page_title = _("Rescue Instance")

    def get_context_data(self, **kwargs):
        context = super(RescueView, self).get_context_data(**kwargs)
        context["instance_id"] = self.kwargs['instance_id']
        args = (self.kwargs['instance_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        return context

    def get_initial(self):
        return {'instance_id': self.kwargs["instance_id"]}


text:
require_relative "feature_helper"

describe "visit all route with get request", type: :feature do
  it "visits homepage" do
    visit "/"
    expect(page).to have_content "My Todolist"
  end

  it "visits create new page" do
    visit "/lists/new"
    expect(page).to have_content "New Todo"
  end

  it "visits a certain todo list" do
    visit "/"
    click_on "Create a new Todolist"
    fill_in "title", with: "Test Todo"
    fill_in "body", with: "Test Todo Body"
    click_on "Create"
    click_on "Test Todo"
    expect(page).to have_content "Back"
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.CognitiveServices.Vision.Face.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Coordinates within an image
    /// </summary>
    public partial class Position
    {
        /// <summary>
        /// Initializes a new instance of the Position class.
        /// </summary>
        public Position()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the Position class.
        /// </summary>
        /// <param name="x">The horizontal component, in pixels.</param>
        /// <param name="y">The vertical component, in pixels.</param>
        public Position(double x, double y)
        {
            X = x;
            Y = y;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the horizontal component, in pixels.
        /// </summary>
        [JsonProperty(PropertyName = "x")]
        public double X { get; set; }

        /// <summary>
        /// Gets or sets the vertical component, in pixels.
        /// </summary>
        [JsonProperty(PropertyName = "y")]
        public double Y { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            //Nothing to validate
        }
    }
}


text:
package org.nschmidt.ldparteditor.dialog.startup;

import static org.nschmidt.ldparteditor.helper.WidgetUtility.widgetUtil;

import java.io.File;
import java.text.Collator;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.nschmidt.ldparteditor.resource.ResourceManager;
import org.nschmidt.ldparteditor.widget.NButton;

/**
 * This first dialog - shown on startup - asks for mandatory information about
 * the user.
 * <p>
 * Note: This class should not be instantiated, it defines the gui layout and no
 * business logic.
 */
class StartupDesign extends Dialog {

    private static final String BROWSE = "Browse..."; //$NON-NLS-1$

    // Use final only for subclass/listener references!
    final Button[] btnOkPtr = new Button[1];
    final Combo[] cmbLocalePtr = new Combo[1];
    final Text[] txtLdrawPathPtr = new Text[1];
    final Text[] txtUnofficialPathPtr = new Text[1];
    final Text[] txtLdrawUserNamePtr = new Text[1];
    final Text[] txtRealNamePtr = new Text[1];
    final Text[] txtPartAuthoringPathPtr = new Text[1];
    final Combo[] cmbLicensePtr = new Combo[1];
    final Label[] lblCurrentActionPtr = new Label[1];
    final Label[] lblFormStatusIconPtr = new Label[1];
    final Label[] lblFormStatusPtr = new Label[1];
    final NButton[] btnBrowseLdrawPathPtr = new NButton[1];
    final NButton[] btnBrowseUnofficialPathPtr = new NButton[1];
    final NButton[] btnBrowseAuthoringPathPtr = new NButton[1];

    final Map<String, Locale> localeMap = new HashMap<>();

    StartupDesign(Shell parentShell) {
        super(parentShell);
    }

    /**
     * Create contents of the dialog.
     *
     * @param parent
     */
    @Override
    protected Control createDialogArea(Composite parent) {
        Composite cmpContainer = (Composite) super.createDialogArea(parent);
        GridLayout gridLayout = (GridLayout) cmpContainer.getLayout();
        gridLayout.verticalSpacing = 10;
        gridLayout.horizontalSpacing = 10;

        Label lblWelcome = new Label(cmpContainer, SWT.NONE);
        lblWelcome.setText("Welcome to LD Part Editor!"); //$NON-NLS-1$ NO_I18N!!

        Label lblSeparator = new Label(cmpContainer, SWT.SEPARATOR | SWT.HORIZONTAL);
        lblSeparator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

        Label lblFirstPrompt = new Label(cmpContainer, SWT.NONE);
        lblFirstPrompt.setText("Please answer the following questions on the first start of this program:"); //$NON-NLS-1$ NO_I18N!!

        Label lblLocale = new Label(cmpContainer, SWT.NONE);
        lblLocale.setText("Choose your locale:"); //$NON-NLS-1$ NO_I18N!!

        Combo cmbLocale = new Combo(cmpContainer, SWT.READ_ONLY);
        this.cmbLocalePtr[0] = cmbLocale;

        String[] locales = new String[DateFormat.getAvailableLocales().length];
        Locale[] locs = DateFormat.getAvailableLocales();
        Arrays.sort(locs, (o1, o2) ->
            Collator.getInstance(Locale.ENGLISH).compare(o1.getDisplayName(Locale.ENGLISH), o2.getDisplayName(Locale.ENGLISH))
        );
        localeMap.clear();
        int englishIndex = 0;
        for (int i = 0; i < locales.length; i++) {
            locales[i] = locs[i].getDisplayName();
            localeMap.put(locales[i], locs[i]);
            if (locs[i].equals(Locale.US)) {
                englishIndex = i;
            }
        }

        cmbLocale.setItems(locales);
        cmbLocale.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        cmbLocale.select(englishIndex);

        Label lblLdrawFolderQuestion = new Label(cmpContainer, SWT.NONE);
        lblLdrawFolderQuestion.setText("Where is your LDraw™ folder located?"); //$NON-NLS-1$ NO_I18N!!

        Composite cmpPathChooser1 = new Composite(cmpContainer, SWT.NONE);
        cmpPathChooser1.setLayout(new RowLayout(SWT.HORIZONTAL));

        Text txtLdrawPath = new Text(cmpPathChooser1, SWT.BORDER);
        this.txtLdrawPathPtr[0] = txtLdrawPath;
        txtLdrawPath.setEditable(false);
        txtLdrawPath.setLayoutData(new RowData(294, SWT.DEFAULT));

        String ldrawDir = System.getenv("LDRAWDIR"); //$NON-NLS-1$
        if (ldrawDir != null) {
            txtLdrawPath.setText(ldrawDir);
        }

        NButton btnBrowseLdrawPath = new NButton(cmpPathChooser1, SWT.NONE);
        this.btnBrowseLdrawPathPtr[0] = btnBrowseLdrawPath;
        btnBrowseLdrawPath.setText(BROWSE);

        Label lblLdrawUserQuestion = new Label(cmpContainer, SWT.NONE);
        lblLdrawUserQuestion.setText("What is your LDraw™ user name?"); //$NON-NLS-1$ NO_I18N!!

        Text txtLdrawUserName = new Text(cmpContainer, SWT.BORDER);
        this.txtLdrawUserNamePtr[0] = txtLdrawUserName;
        txtLdrawUserName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

        Label lblRealNameQuestion = new Label(cmpContainer, SWT.NONE);
        lblRealNameQuestion.setText("What is your real name?"); //$NON-NLS-1$ NO_I18N!!

        Text txtRealName = new Text(cmpContainer, SWT.BORDER);
        this.txtRealNamePtr[0] = txtRealName;
        txtRealName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));

        Label lblLicenseQuestion = new Label(cmpContainer, SWT.NONE);
        lblLicenseQuestion.setText("Under which license do you want to publish your work?"); //$NON-NLS-1$ NO_I18N!!

        Combo cmbLicense = new Combo(cmpContainer, SWT.NONE);
        this.cmbLicensePtr[0] = cmbLicense;
        widgetUtil(cmbLicense).setItems("0 !LICENSE Licensed under CC BY 4.0 : see CAreadme.txt", "0 !LICENSE Licensed under CC BY 2.0 and CC BY 4.0 : see CAreadme.txt", "0 !LICENSE Redistributable under CCAL version 2.0 : see CAreadme.txt", "0 !LICENSE Not redistributable : see NonCAreadme.txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        cmbLicense.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        cmbLicense.setText("0 !LICENSE Licensed under CC BY 4.0 : see CAreadme.txt"); //$NON-NLS-1$
        cmbLicense.select(0);

        Label lblAuthoringFolderQuestion = new Label(cmpContainer, SWT.NONE);
        lblAuthoringFolderQuestion.setText("Define the Part Authoring Folder Path:"); //$NON-NLS-1$ NO_I18N!!

        Composite cmpPathChooser2 = new Composite(cmpContainer, SWT.NONE);
        cmpPathChooser2.setLayout(new RowLayout(SWT.HORIZONTAL));

        Text txtPartAuthoringPath = new Text(cmpPathChooser2, SWT.BORDER);
        this.txtPartAuthoringPathPtr[0] = txtPartAuthoringPath;
        txtPartAuthoringPath.setEditable(false);
        txtPartAuthoringPath.setLayoutData(new RowData(294, SWT.DEFAULT));

        NButton btnBrowseAuthoringPath = new NButton(cmpPathChooser2, SWT.NONE);
        this.btnBrowseAuthoringPathPtr[0] = btnBrowseAuthoringPath;
        btnBrowseAuthoringPath.setText(BROWSE);

        Label lblUnofficialPathQuestion = new Label(cmpContainer, SWT.NONE);
        lblUnofficialPathQuestion.setText("Define the Folder Path for Unofficial Parts:"); //$NON-NLS-1$ NO_I18N!!

        Composite cmpPathChooser3 = new Composite(cmpContainer, SWT.NONE);
        cmpPathChooser3.setLayout(new RowLayout(SWT.HORIZONTAL));

        Text txtUnofficialPath = new Text(cmpPathChooser3, SWT.BORDER);
        this.txtUnofficialPathPtr[0] = txtUnofficialPath;
        txtUnofficialPath.setEditable(false);
        txtUnofficialPath.setLayoutData(new RowData(294, SWT.DEFAULT));

        if (ldrawDir != null) {
            txtUnofficialPath.setText(ldrawDir + File.separator + "Unofficial"); //$NON-NLS-1$
        }

        NButton btnBrowseUnofficialPath = new NButton(cmpPathChooser3, SWT.NONE);
        this.btnBrowseUnofficialPathPtr[0] = btnBrowseUnofficialPath;
        btnBrowseUnofficialPath.setText(BROWSE);

        Composite cmpFormStatus = new Composite(cmpContainer, SWT.NONE);
        cmpFormStatus.setLayout(new RowLayout(SWT.HORIZONTAL));

        Label lblFormStatusIcon = new Label(cmpFormStatus, SWT.NONE);
        this.lblFormStatusIconPtr[0] = lblFormStatusIcon;
        lblFormStatusIcon.setImage(ResourceManager.getImage("icon16_info.png", 16)); //$NON-NLS-1$

        Label lblFormStatus = new Label(cmpFormStatus, SWT.NONE);
        this.lblFormStatusPtr[0] = lblFormStatus;
        lblFormStatus.setText("Please complete the form."); //$NON-NLS-1$ NO_I18N!!

        Label lblCurrentAction = new Label(cmpContainer, SWT.NONE);
        this.lblCurrentActionPtr[0] = lblCurrentAction;

        return cmpContainer;
    }

    /**
     * Create contents of the button bar.
     *
     * @param parent
     */
    @Override
    protected void createButtonsForButtonBar(Composite parent) {
        btnOkPtr[0] = createButton(parent, IDialogConstants.OK_ID, "OK", true); //$NON-NLS-1$ NO_I18N!!
        createButton(parent, IDialogConstants.CANCEL_ID, "Cancel", false); //$NON-NLS-1$ NO_I18N!!
    }
}


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

import com.facebook.presto.operator.LookupSourceFactory;
import com.facebook.presto.operator.LookupSourceProvider;
import com.facebook.presto.operator.OuterPositionIterator;
import com.facebook.presto.operator.PagesIndex;
import com.facebook.presto.operator.StaticLookupSourceProvider;
import com.facebook.presto.operator.TaskContext;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.planner.Symbol;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.units.DataSize;

import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Supplier;

import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.Futures.transform;
import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static java.util.Objects.requireNonNull;

public class IndexLookupSourceFactory
        implements LookupSourceFactory
{
    private final List<Type> outputTypes;
    private final Map<Symbol, Integer> layout;
    private final Supplier<IndexLoader> indexLoaderSupplier;
    private TaskContext taskContext;
    private final SettableFuture<?> whenTaskContextSet = SettableFuture.create();

    public IndexLookupSourceFactory(
            Set<Integer> lookupSourceInputChannels,
            List<Integer> keyOutputChannels,
            OptionalInt keyOutputHashChannel,
            List<Type> outputTypes,
            Map<Symbol, Integer> layout,
            IndexBuildDriverFactoryProvider indexBuildDriverFactoryProvider,
            DataSize maxIndexMemorySize,
            IndexJoinLookupStats stats,
            boolean shareIndexLoading,
            PagesIndex.Factory pagesIndexFactory,
            JoinCompiler joinCompiler)
    {
        this.outputTypes = ImmutableList.copyOf(requireNonNull(outputTypes, "outputTypes is null"));
        this.layout = ImmutableMap.copyOf(requireNonNull(layout, "layout is null"));

        if (shareIndexLoading) {
            IndexLoader shared = new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler);
            this.indexLoaderSupplier = () -> shared;
        }
        else {
            this.indexLoaderSupplier = () -> new IndexLoader(lookupSourceInputChannels, keyOutputChannels, keyOutputHashChannel, outputTypes, indexBuildDriverFactoryProvider, 10_000, maxIndexMemorySize, stats, pagesIndexFactory, joinCompiler);
        }
    }

    @Override
    public List<Type> getTypes()
    {
        return outputTypes;
    }

    @Override
    public List<Type> getOutputTypes()
    {
        return outputTypes;
    }

    @Override
    public Map<Symbol, Integer> getLayout()
    {
        return layout;
    }

    @Override
    public void setTaskContext(TaskContext taskContext)
    {
        this.taskContext = taskContext;
        whenTaskContextSet.set(null);
    }

    @Override
    public ListenableFuture<LookupSourceProvider> createLookupSourceProvider()
    {
        checkState(taskContext != null, "taskContext not set");

        IndexLoader indexLoader = indexLoaderSupplier.get();
        indexLoader.setContext(taskContext);
        return Futures.immediateFuture(new StaticLookupSourceProvider(new IndexLookupSource(indexLoader)));
    }

    @Override
    public ListenableFuture<?> whenBuildFinishes()
    {
        return Futures.transformAsync(
                whenTaskContextSet,
                ignored -> transform(
                        this.createLookupSourceProvider(),
                        lookupSourceProvider -> {
                            // Close the lookupSourceProvider we just created.
                            // The only reason we created it is to wait until lookup source is ready.
                            lookupSourceProvider.close();
                            return null;
                        },
                        directExecutor()),
                directExecutor());
    }

    @Override
    public int partitions()
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public OuterPositionIterator getOuterPositionIterator()
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public void destroy()
    {
        // nothing to do
    }
}


text:
SET FOREIGN_KEY_CHECKS=0;
-- --------------------------------------------------------

INSERT INTO `@prefix@api_tab_menu` (`Description`, `Description_courte`, `id_categorie`, `Lien`) VALUES ('manage-accounts.title', 'manage-accounts.title', '3', 'manage-accounts');

UPDATE `@prefix@api_tab_menu_rangs_droit` a
  INNER JOIN `@prefix@api_tab_menu` b
    ON b.`Lien` = 'manage-accounts'
  INNER JOIN `@prefix@api_tab_rangs` c
    ON c.`id` = a.`id_rang`
       AND c.`indice` in (1,10,20,30)
SET `id_menu` = concat(`id_menu`,b.`id`,';');

ALTER TABLE `@prefix@tab_accounts` ADD `userId` INT(11) NOT NULL ;
ALTER TABLE `@prefix@tab_accounts` ADD INDEX(`userId`);
ALTER TABLE `@prefix@tab_accounts` ADD CONSTRAINT `fk_accounts_usersId` FOREIGN KEY (`userId`) REFERENCES `@prefix@api_tab_utilisateurs`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE `@prefix@tab_accounts_items` ADD `userId` INT(11) NOT NULL ;
ALTER TABLE `@prefix@tab_accounts_items` ADD INDEX(`userId`);
ALTER TABLE `@prefix@tab_accounts_items` ADD CONSTRAINT `fk_accounts_items_usersId` FOREIGN KEY (`userId`) REFERENCES `@prefix@api_tab_utilisateurs`(`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;

ALTER TABLE `@prefix@tab_accounts` ADD UNIQUE(`code`);

-- --------------------------------------------------------
SET FOREIGN_KEY_CHECKS=1;


text:
package org.apache.tomcat.test.watchdog;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;

/**
 * Represents a collection of Cookie instances.
 *

 * Fires events when the cookies have been changed internally. Deals
 * with management of cookies in terms of saving and loading them,
 * and disabling them.
 *
 * @author	Ramesh.Mandava
 */
public class CookieController {

//    private VetoableChangeSupport vceListeners;

    private static Hashtable cookieJar = new Hashtable();

    /* public no arg constructor for bean */
    public CookieController() {
    }

/////////////////////////////////////////////////////////////
 /**
     * Records any cookies which have been sent as part of an HTTP response.
     * The connection parameter must be already have been opened, so that
     * the response headers are available.  It's ok to pass a non-HTTP
     * URL connection, or one which does not have any set-cookie headers.
     */
    public void recordAnyCookies(Vector rcvVectorOfCookies , URL url ) {

	if ((rcvVectorOfCookies == null) || ( rcvVectorOfCookies.size()== 0) ) {
	    // no headers here
	    return;
	}
	try {
	/*
        Properties properties = new Properties();
	FileInputStream fin = new FileInputStream("ServerAutoRun.properties");
	properties.load(fin);

	String cookiepolicy = properties.getProperty("cookie.acceptpolicy");
	if (cookiepolicy == null || cookiepolicy.equals("none")) {
	    return;
	}
	*/

	for (int hi = 0; hi<rcvVectorOfCookies.size(); hi++) {

		String cookieValue = (String)rcvVectorOfCookies.elementAt(hi) ;
		recordCookie(url, cookieValue); // What to do here
	    }

	}
	catch( Exception e )
	{
		System.out.println("exception : " + e );
	}
    }

    /**
     * Create a cookie from the cookie, and use the HttpURLConnection to
     * fill in unspecified values in the cookie with defaults.
     */
    public void recordCookie(URL url,
				     String cookieValue) {
	HttpCookie cookie = new HttpCookie(url, cookieValue);

	// First, check to make sure the cookie's domain matches the
	// server's, and has the required number of '.'s
	String twodot[]=
	    {"com", "edu", "net", "org", "gov", "mil", "int"};
	String domain = cookie.getDomain();
	if( domain == null )
	    return;
	int index = domain.indexOf(':');
	if (index != -1) {
	    int portCookie;
	    try {
		portCookie = (Integer.valueOf(domain.substring(index+1,domain.length()))).intValue();
	    } catch (Exception e) {
		return;
	    }
	    portCookie = ( portCookie == -1 ) ? 80 : portCookie;
	    domain=domain.substring(0,index);
	}
	domain.toLowerCase();

	String host = url.getHost();
	host.toLowerCase();

	boolean domainOK = host.equals(domain);
	if( !domainOK && host.endsWith( domain ) ) {
	    int dotsNeeded = 2;
	    for( int i = 0; i < twodot.length; i++ ) {
		if( domain.endsWith( twodot[i] ) ) {
		    dotsNeeded = 1;
		}
	    }

	    int lastChar = domain.length();
	    for( ; lastChar > 0 && dotsNeeded > 0; dotsNeeded-- ) {
		lastChar = domain.lastIndexOf( '.', lastChar-1 );
	    }

	    if( lastChar > 0 )
		domainOK = true;
	}

	if( domainOK ) {
	    recordCookie(cookie);

	}
    }

    /**
     * Record the cookie in the in-memory container of cookies.  If there
     * is already a cookie which is in the exact same domain with the
     * exact same
     */
    public void recordCookie(HttpCookie cookie) {
	if (!checkIfCookieOK(cookie)) {
	    return;
	}
	synchronized (cookieJar) {

	    String domain = cookie.getDomain().toLowerCase();

	    Vector cookieList = (Vector)cookieJar.get(domain);
	    if (cookieList == null) {
		cookieList = new Vector();
	    }

	    addOrReplaceCookie(cookieList, cookie);
	    cookieJar.put(domain, cookieList);

	}

    }

    public boolean checkIfCookieOK(HttpCookie cookie) {
	return true;
    }

    /**
     * Scans the vector of cookies looking for an exact match with the
     * given cookie.  Replaces it if there is one, otherwise adds
     * one at the end.  The vector is presumed to have cookies which all
     * have the same domain, so the domain of the cookie is not checked.
     *

     *

     * If this is called, it is assumed that the cookie jar is exclusively
     * held by the current thread.
     *
     */
    private void addOrReplaceCookie(Vector cookies,
				       HttpCookie cookie) {
	int numCookies = cookies.size();

	String path = cookie.getPath();
	String name = cookie.getName();
	HttpCookie replaced = null;
	int replacedIndex = -1;

	for (int i = 0; i < numCookies; i++) {
	    HttpCookie existingCookie = (HttpCookie)cookies.elementAt(i);

	    String existingPath = existingCookie.getPath();
	    if (path.equals(existingPath)) {
		String existingName = existingCookie.getName();
		if (name.equals(existingName)) {
		    // need to replace this one!
		    replaced = existingCookie;
		    replacedIndex = i;
		    break;
		}
	    }
	}

	// Do the replace - if cookie has already expired, remove
	// the replaced cookie.
	if (replaced != null) {
	    if (cookie.isSaveableInMemory()) {
		cookies.setElementAt(cookie, replacedIndex);
		//System.out.println("REPLACED existing cookie with " + cookie);
	    } else {
		cookies.removeElementAt(replacedIndex);
		//System.out.println("Removed cookie b/c or expr " + cookie);
	    }

	} else { // only save the cookie in memory if it is non persistent
          	 // or not expired.
	    if (cookie.isSaveableInMemory()) {
		cookies.addElement(cookie);
		//System.out.println("RECORDED new cookie " + cookie);
	    }

	}

    }

    public String applyRelevantCookies(URL url ) {

       try {
		/*
		Properties properties = new Properties();
		FileInputStream fin = new FileInputStream("ServerAutoRun.properties");
		properties.load(fin);
		// check current accept policy instead enableCookies
		String cookiepolicy = properties.getProperty("cookie.acceptpolicy");
		if (cookiepolicy == null || cookiepolicy.equals("none")) {
		    return null;
		}

		*/

		return applyCookiesForHost(url);

	}
	catch ( Exception e )
	{
		System.out.println("Exception : " +e );
		return null;
	}

    }

   /**
     * Host may be a FQDN, or a partial domain name starting with a dot.
     * Adds any cookies which match the host and path to the
     * cookie set on the URL connection.
     */
    private String applyCookiesForHost(URL url ){
	String cookieString = null;
	Vector cookieVector = getAllRelevantCookies(url);

	if (cookieVector != null) {

	    for (Enumeration e = cookieVector.elements(); e.hasMoreElements();) {
		HttpCookie cookie = (HttpCookie)e.nextElement();
		if( cookieString == null ) {
		    cookieString = cookie.getNameValue();
		} else {
		    cookieString = cookieString + "; " + cookie.getNameValue();
		}
	    }

	 /*

	    if( cookieString != null ) {
		httpConn.setRequestProperty("Cookie", cookieString);

//		System.out.println("Returned cookie string: " + cookieString + " for HOST = " + host);
	     }

	  */

	}
//		System.out.println("Returned cookie string: " + cookieString + " for HOST = " + host);
	return cookieString;

    }

    private Vector getAllRelevantCookies(URL url) {
	String host = url.getHost();
	Vector cookieVector = getSubsetRelevantCookies(host, url);

	Vector tempVector;
	int index;

	while ((index = host.indexOf('.', 1)) >= 0) {
	    // trim off everything up to, and including the dot.
	    host = host.substring(index+1);

            // add onto cookieVector
	    tempVector = getSubsetRelevantCookies(host,url);
	    if (tempVector != null ) {
		for (Enumeration e = tempVector.elements(); e.hasMoreElements(); ) {
		    if (cookieVector == null) {
			cookieVector = new Vector(2);
		    }

		    cookieVector.addElement(e.nextElement());

		}
	    }
	}
	return cookieVector;
    }

    private Vector getSubsetRelevantCookies(String host, URL url) {

	Vector cookieList = (Vector)cookieJar.get(host);

//	System.out.println("getRelevantCookies() .. for host, url " + host +", "+url);
	Vector cookiePortList = (Vector)cookieJar.get(host+":"+((url.getPort() == -1) ? 80 : url.getPort()));
	if (cookiePortList != null) {
	    if (cookieList == null) {
		cookieList = new Vector(10);
	    }
	    Enumeration cookies = cookiePortList.elements();
	    while (cookies.hasMoreElements()) {
		cookieList.addElement(cookies.nextElement());
	    }
	}

	if (cookieList == null) {
	    return null;
	}

	String path = url.getFile();
//	System.out.println("        path is " + path + "; protocol = " + url.getProtocol());

	int queryInd = path.indexOf('?');
	if (queryInd > 0) {
	    // strip off the part following the ?
	    path = path.substring(0, queryInd);
	}

	Enumeration cookies = cookieList.elements();
	Vector cookiesToSend = new Vector(10);

	while (cookies.hasMoreElements()) {
	    HttpCookie cookie = (HttpCookie)cookies.nextElement();

	    String cookiePath = cookie.getPath();

	    if (path.startsWith(cookiePath)) {
		// larrylf: Actually, my documentation (from Netscape)
		// says that /foo should
		// match /foobar and /foo/bar.  Yuck!!!

		if (!cookie.hasExpired()) {
		    cookiesToSend.addElement(cookie);
		}

/*
   We're keeping this piece of commented out code around just in
   case we decide to put it back.  the spec does specify the above,
   but it is so disgusting!

		int cookiePathLen = cookiePath.length();

		// verify that /foo does not match /foobar by mistake
		if ((path.length() == cookiePathLen)
		    || (path.length() > cookiePathLen &&
			path.charAt(cookiePathLen) == '/')) {

		    // We have a matching cookie!

		    if (!cookie.hasExpired()) {
			cookiesToSend.addElement(cookie);
		    }
		}
*/
	    }
	}

	// Now, sort the cookies in most to least specific order
	// Yes, its the deaded bubblesort!! Wah Ha-ha-ha-ha....
	// (it should be a small vector, so perf is not an issue...)
	if( cookiesToSend.size() > 1 ) {
	    for( int i = 0; i < cookiesToSend.size()-1; i++ ) {
		HttpCookie headC = (HttpCookie)cookiesToSend.elementAt(i);
		String head = headC.getPath();
		// This little excercise is a cheap way to get
		// '/foo' to read more specfic then '/'
		if( !head.endsWith("/") ) {
		    head = head + "/";
		}
		for( int j = i+1; j < cookiesToSend.size(); j++ ) {
		    HttpCookie scanC = (HttpCookie)cookiesToSend.elementAt(j);
		    String scan = scanC.getPath();
		    if( !scan.endsWith("/") ) {
			scan = scan + "/";
		    }

		    int headCount = 0;
		    int index = -1;
		    while( (index=head.indexOf('/', index+1)) != -1 ) {
			headCount++;
		    }
		    index = -1;

		    int scanCount = 0;
		    while( (index=scan.indexOf('/', index+1)) != -1 ) {
			scanCount++;
		    }

		    if( scanCount > headCount ) {
			cookiesToSend.setElementAt(headC, j);
			cookiesToSend.setElementAt(scanC, i);
			headC = scanC;
			head = scan;
		    }
		}
	    }
	}

    return cookiesToSend;

    }

    /*
     * Writes cookies out to PrintWriter if they are persistent
     * (i.e. have a expr date)
     * and haven't expired. Will remove cookies that have expired as well
     */
    private void saveCookiesToStream(PrintWriter pw) {

	Enumeration cookieLists = cookieJar.elements();

	while (cookieLists.hasMoreElements()) {
	    Vector cookieList = (Vector)cookieLists.nextElement();

	    Enumeration cookies = cookieList.elements();

	    while (cookies.hasMoreElements()) {
		HttpCookie cookie = (HttpCookie)cookies.nextElement();

		if (cookie.getExpirationDate() != null) {
		    if (cookie.isSaveable()) {
			pw.println(cookie);
		    } else { // the cookie must have expired,
			//remove from Vector cookieList
			cookieList.removeElement(cookie);
		    }

		}
	    }
	}
        // Must print something to the printwriter in the case that
	// the cookieJar has been cleared - otherwise the old cookie
	// file will continue to exist.
	pw.print("");
    }
/////////////////////////////////////////////////////////////
    /* adds cookieList to the existing cookie jar*/
    public void addToCookieJar(HttpCookie[] cookieList) {

	if (cookieList != null) {
	    for (int i = 0; i < cookieList.length; i++) {

		recordCookie(cookieList[i]);
	    }
	}

    }

    /*adds one cookie to the Cookie Jar */
    public void addToCookieJar(String cookieString, URL docURL) {
	recordCookie(new HttpCookie(docURL, cookieString));
    }

    /* loads the cookies from the given filename */
    public void loadCookieJarFromFile(String cookieFileName) {
	try {
	    FileReader fr = new FileReader(cookieFileName);

	    BufferedReader in = new BufferedReader(fr);

	    try {
		String cookieString;
		while ((cookieString = in.readLine()) != null) {
		    HttpCookie cookie = new HttpCookie(cookieString);
		    // Record the cookie, without notification.  We don't
		    // do a notification for cookies that are read at
		    // program start-up.
		    recordCookie(cookie);
		}
	    } finally {
		in.close();
	    }

	} catch (IOException e) {
	    // do nothing; it's not an error not to have persistent cookies
	}

    }

    /* saves the cookies to the given file specified by fname */
    public void saveCookieJarToFile(String cookieFileName) {
	try {
	    FileWriter fw = new FileWriter(cookieFileName);
	    PrintWriter pw = new PrintWriter(fw, false);

	    try {
		saveCookiesToStream(pw);
	    } finally {
		pw.close();
	    }

	} catch (IOException e) {
	    // REMIND: I18N
	    System.err.println("Saving cookies failed " + e.getMessage());
	}
    }

    /**
     * Return an array with all of the cookies represented by this
     * jar.  This is useful when the bean is shutting down, and the client
     * wants to make the cookie jar persist.
     */
    public HttpCookie[] getAllCookies() {

	Vector result = new Vector();
	Hashtable jar;
	jar = (Hashtable) cookieJar.clone();

	synchronized (jar) {

	    for (Enumeration e = jar.elements(); e.hasMoreElements() ;) {
		Vector v = (Vector) e.nextElement();
		for (int i = 0; i < v.size(); i++) {
		    HttpCookie hc = (HttpCookie) v.elementAt(i);
		    result.addElement(hc);

		}

	    }
	}

	HttpCookie[] resultA = new HttpCookie[result.size()];
	for (int i = 0; i < result.size(); i++) {
	    resultA[i] = (HttpCookie) result.elementAt(i);
	}
	return resultA;
    }

    /* Gets all cookies that applies for the URL */
    public HttpCookie[] getCookiesForURL(URL url) {

	Vector cookieVector = getAllRelevantCookies(url);

	if (cookieVector == null) {
	    return null;
	}

	int i = 0;
	HttpCookie[] cookieArr = new HttpCookie[cookieVector.size()];

	for (Enumeration e = cookieVector.elements(); e.hasMoreElements(); ) {

	    cookieArr[i++] = (HttpCookie)e.nextElement();
//	    System.out.println("cookieArr["+(i-1)+"] = " +cookieArr[i-1].toString());
	}

	return cookieArr;
    }

    /* this will set the property of enableCookies to isDisabled */
    public void setCookieDisable(boolean isDisabled) {

	// Pending visit back this again
	try {
	Properties properties = new Properties();
	properties.load(new FileInputStream("ServerAutoRun.properties") );

	properties.put("enableCookies", isDisabled ? "false" : "true");
	properties.store(new FileOutputStream("ServerAutoRun.properties"),"comments");
	}
	catch ( Exception e )
	{
		System.out.println("Exception : " + e );
	}
    }

    public void discardAllCookies() {
	cookieJar.clear();

    }

    /*
     * purges any expired cookies in the Cookie hashtable.
     */
    public void purgeExpiredCookies() {
	Enumeration cookieLists = cookieJar.elements();

	while (cookieLists.hasMoreElements()) {
	    Vector cookieList = (Vector)cookieLists.nextElement();

	    Enumeration cookies = cookieList.elements();

	    while (cookies.hasMoreElements()) {
		HttpCookie cookie = (HttpCookie)cookies.nextElement();

		if (cookie.hasExpired()) {
		    cookieList.removeElement(cookie);
		}
	    }
	}

    }

}


text:
<?php

namespace app\modules\penatausahaan\controllers;

use Yii;
use app\models\TaMutasiKas;
use app\modules\penatausahaan\models\TaMutasiKasSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MutasikasController implements the CRUD actions for TaMutasiKas model.
 */
class MutasikasController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all TaMutasiKas models.
     * @return mixed
     */
    public function actionIndex()
    {
        IF($this->cekakses() !== true){
            Yii::$app->getSession()->setFlash('warning',  'Anda tidak memiliki hak akses');
            return $this->redirect(Yii::$app->request->referrer);
        }
        IF(Yii::$app->session->get('tahun'))
        {
            $Tahun = Yii::$app->session->get('tahun');
        }ELSE{
            $Tahun = DATE('Y');
        }
        $searchModel = new TaMutasiKasSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['tahun' => $Tahun, 'sekolah_id' => Yii::$app->user->identity->sekolah_id]);
        $dataProvider->query->orderBy('tgl_bukti, no_bukti DESC');

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'Tahun' => $Tahun,
        ]);
    }

    /**
     * Displays a single TaMutasiKas model.
     * @param string $tahun
     * @param string $no_bukti
     * @return mixed
     */
    public function actionView($tahun, $no_bukti)
    {
        IF($this->cekakses() !== true){
            Yii::$app->getSession()->setFlash('warning',  'Anda tidak memiliki hak akses');
            return $this->redirect(Yii::$app->request->referrer);
        }
        IF(Yii::$app->session->get('tahun'))
        {
            $Tahun = Yii::$app->session->get('tahun');
        }ELSE{
            $Tahun = DATE('Y');
        }
        return $this->renderAjax('view', [
            'model' => $this->findModel($tahun, $no_bukti),
        ]);
    }

    /**
     * Creates a new TaMutasiKas model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        IF($this->cekakses() !== true){
            Yii::$app->getSession()->setFlash('warning',  'Anda tidak memiliki hak akses');
            return $this->redirect(Yii::$app->request->referrer);
        }
        IF(Yii::$app->session->get('tahun'))
        {
            $Tahun = Yii::$app->session->get('tahun');
        }ELSE{
            $Tahun = DATE('Y');
        }

        $model = new TaMutasiKas();
        $model->tahun = $Tahun;
        $model->sekolah_id = Yii::$app->user->identity->sekolah_id;
        $model->user_id = Yii::$app->user->identity->id;

        if ($model->load(Yii::$app->request->post())) {
            $model->nilai = str_replace(',', '.', $model->nilai);
            IF($model->save()){
                echo 1;
            }ELSE{
                echo 0;
            }
        } else {
            return $this->renderAjax('_form', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing TaMutasiKas model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $tahun
     * @param string $no_bukti
     * @return mixed
     */
    public function actionUpdate($tahun, $no_bukti)
    {
        IF($this->cekakses() !== true){
            Yii::$app->getSession()->setFlash('warning',  'Anda tidak memiliki hak akses');
            return $this->redirect(Yii::$app->request->referrer);
        }
        IF(Yii::$app->session->get('tahun'))
        {
            $Tahun = Yii::$app->session->get('tahun');
        }ELSE{
            $Tahun = DATE('Y');
        }

        $model = $this->findModel($tahun, $no_bukti);

        if ($model->load(Yii::$app->request->post())) {
            $model->nilai = str_replace(',', '.', $model->nilai);
            IF($model->save()){
                echo 1;
            }ELSE{
                echo 0;
            }
        } else {
            return $this->renderAjax('_form', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing TaMutasiKas model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $tahun
     * @param string $no_bukti
     * @return mixed
     */
    public function actionDelete($tahun, $no_bukti)
    {
        IF($this->cekakses() !== true){
            Yii::$app->getSession()->setFlash('warning',  'Anda tidak memiliki hak akses');
            return $this->redirect(Yii::$app->request->referrer);
        }
        IF(Yii::$app->session->get('tahun'))
        {
            $Tahun = Yii::$app->session->get('tahun');
        }ELSE{
            $Tahun = DATE('Y');
        }

        $this->findModel($tahun, $no_bukti)->delete();

        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * Finds the TaMutasiKas model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $tahun
     * @param string $no_bukti
     * @return TaMutasiKas the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($tahun, $no_bukti)
    {
        if (($model = TaMutasiKas::findOne(['tahun' => $tahun, 'no_bukti' => $no_bukti])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    protected function cekakses(){

        IF(Yii::$app->user->identity){
            $akses = \app\models\RefUserMenu::find()->where(['kd_user' => Yii::$app->user->identity->kd_user, 'menu' => 508])->one();
            IF($akses){
                return true;
            }else{
                return false;
            }
        }ELSE{
            return false;
        }
    }

}


text:
<?php

namespace Symfony\Component\DependencyInjection\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;

class AliasTest extends TestCase
{
    public function testConstructor()
    {
        $alias = new Alias('foo');

        $this->assertEquals('foo', (string) $alias);
        $this->assertFalse($alias->isPublic());
    }

    public function testCanConstructANonPublicAlias()
    {
        $alias = new Alias('foo', false);

        $this->assertEquals('foo', (string) $alias);
        $this->assertFalse($alias->isPublic());
    }

    public function testCanConstructAPrivateAlias()
    {
        $alias = new Alias('foo', false, false);

        $this->assertEquals('foo', (string) $alias);
        $this->assertFalse($alias->isPublic());
        $this->assertTrue($alias->isPrivate());
    }

    public function testCanSetPublic()
    {
        $alias = new Alias('foo', false);
        $alias->setPublic(true);

        $this->assertTrue($alias->isPublic());
    }

    public function testCanDeprecateAnAlias()
    {
        $alias = new Alias('foo', false);
        $alias->setDeprecated('vendor/package', '1.1', 'The %alias_id% service is deprecated.');

        $this->assertTrue($alias->isDeprecated());
    }

    public function testReturnsCorrectDeprecation()
    {
        $alias = new Alias('foo', false);
        $alias->setDeprecated('vendor/package', '1.1', 'The "%alias_id%" is deprecated.');

        $deprecation = $alias->getDeprecation('foo');
        $this->assertEquals('The "foo" is deprecated.', $deprecation['message']);
        $this->assertEquals('vendor/package', $deprecation['package']);
        $this->assertEquals('1.1', $deprecation['version']);
    }

    /**
     * @dataProvider invalidDeprecationMessageProvider
     */
    public function testCannotDeprecateWithAnInvalidTemplate($message)
    {
        $this->expectException(InvalidArgumentException::class);
        $def = new Alias('foo');
        $def->setDeprecated('package', '1.1', $message);
    }

    public function invalidDeprecationMessageProvider()
    {
        return [
            "With \rs" => ["invalid \r message %alias_id%"],
            "With \ns" => ["invalid \n message %alias_id%"],
            'With */s' => ['invalid */ message %alias_id%'],
            'message not containing required %alias_id% variable' => ['this is deprecated'],
            'template not containing required %alias_id% variable' => [true],
        ];
    }
}


text:
.class public abstract Lcom/google/common/collect/Sets$SetView;
.super Ljava/util/AbstractSet;
.source "Sets.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/common/collect/Sets;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "SetView"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<E:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/util/AbstractSet",
        "<TE;>;"
    }
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 537
    .local p0, "this":Lcom/google/common/collect/Sets$SetView;, "Lcom/google/common/collect/Sets$SetView<TE;>;"
    invoke-direct {p0}, Ljava/util/AbstractSet;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/google/common/collect/Sets$1;)V
    .locals 0
    .param p1, "x0"    # Lcom/google/common/collect/Sets$1;

    .prologue
    .line 536
    .local p0, "this":Lcom/google/common/collect/Sets$SetView;, "Lcom/google/common/collect/Sets$SetView<TE;>;"
    invoke-direct {p0}, Lcom/google/common/collect/Sets$SetView;-><init>()V

    return-void
.end method

# virtual methods
.method public copyInto(Ljava/util/Set;)Ljava/util/Set;
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<S::",
            "Ljava/util/Set",
            "<TE;>;>(TS;)TS;"
        }
    .end annotation

    .prologue
    .line 562
    .local p0, "this":Lcom/google/common/collect/Sets$SetView;, "Lcom/google/common/collect/Sets$SetView<TE;>;"
    .local p1, "set":Ljava/util/Set;, "TS;"
    invoke-interface {p1, p0}, Ljava/util/Set;->addAll(Ljava/util/Collection;)Z

    .line 563
    return-object p1
.end method

.method public immutableCopy()Lcom/google/common/collect/ImmutableSet;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Lcom/google/common/collect/ImmutableSet",
            "<TE;>;"
        }
    .end annotation

    .prologue
    .line 549
    .local p0, "this":Lcom/google/common/collect/Sets$SetView;, "Lcom/google/common/collect/Sets$SetView<TE;>;"
    invoke-static {p0}, Lcom/google/common/collect/ImmutableSet;->copyOf(Ljava/util/Collection;)Lcom/google/common/collect/ImmutableSet;

    move-result-object v0

    return-object v0
.end method


text:
2cl
==

contact list converter


text:
#include <folly/executors/Codel.h>
#include <folly/portability/GTest.h>
#include <chrono>
#include <thread>

using std::chrono::milliseconds;
using std::this_thread::sleep_for;

TEST(CodelTest, Basic) {
  folly::Codel c;
  std::this_thread::sleep_for(milliseconds(110));
  // This interval is overloaded
  EXPECT_FALSE(c.overloaded(milliseconds(100)));
  std::this_thread::sleep_for(milliseconds(90));
  // At least two requests must happen in an interval before they will fail
  EXPECT_FALSE(c.overloaded(milliseconds(50)));
  EXPECT_TRUE(c.overloaded(milliseconds(50)));
  std::this_thread::sleep_for(milliseconds(110));
  // Previous interval is overloaded, but 2ms isn't enough to fail
  EXPECT_FALSE(c.overloaded(milliseconds(2)));
  std::this_thread::sleep_for(milliseconds(90));
  // 20 ms > target interval * 2
  EXPECT_TRUE(c.overloaded(milliseconds(20)));
}

TEST(CodelTest, highLoad) {
  folly::Codel c;
  c.overloaded(milliseconds(40));
  EXPECT_EQ(100, c.getLoad());
}

TEST(CodelTest, mediumLoad) {
  folly::Codel c;
  c.overloaded(milliseconds(20));
  sleep_for(milliseconds(90));
  // this is overloaded but this request shouldn't drop because it's not >
  // slough timeout
  EXPECT_FALSE(c.overloaded(milliseconds(8)));
  EXPECT_GT(100, c.getLoad());
}

TEST(CodelTest, reducingLoad) {
  folly::Codel c;
  c.overloaded(milliseconds(20));
  sleep_for(milliseconds(90));
  EXPECT_FALSE(c.overloaded(milliseconds(4)));
}

TEST(CodelTest, oneRequestNoDrop) {
  folly::Codel c;
  EXPECT_FALSE(c.overloaded(milliseconds(20)));
}

TEST(CodelTest, getLoadSanity) {
  folly::Codel c;
  // should be 100% but leave a litte wiggle room.
  c.overloaded(milliseconds(10));
  EXPECT_LT(99, c.getLoad());
  EXPECT_GT(101, c.getLoad());

  // should be 70% but leave a litte wiggle room.
  c.overloaded(milliseconds(7));
  EXPECT_LT(60, c.getLoad());
  EXPECT_GT(80, c.getLoad());

  // should be 20% but leave a litte wiggle room.
  c.overloaded(milliseconds(2));
  EXPECT_LT(10, c.getLoad());
  EXPECT_GT(30, c.getLoad());

  // this test demonstrates how silly getLoad() is, but silly isn't
  // necessarily useless
}


text:
  # create variable for total
  # iterate through each number in array
    # add number to total
  # return total

# 1. total initial solution
def total(numbers)
  total = 0
  numbers.each do |num|
    total += num
  end

  return total
end

# 3. total refactored solution
def total(numbers)
  numbers.reduce(:+)
end

# 4. sentence_maker pseudocode
# make sure all pseudocode is commented out!
# Input: array of strings
# Output: returns a sentence of all strings combined. Starts with a capital letter and ends with a period.
# Steps to solve the problem.

# initialize method
  # output variable equal to empty string
  # iterate through strings array
    # if first item, capitalize it
    # otherwise, add it to string
  # return output with period at the end

# 5. sentence_maker initial solution
def sentence_maker(strings)
  return strings.join(' ').capitalize + '.'
end

# 6. sentence_maker refactored solution


text:
/* @LICENSE(MUSLC_MIT) */

#include <unistd.h>
#include "internal/syscall.h"
#include "libc.h"

ssize_t sendfile(int out_fd, int in_fd, off_t *ofs, size_t count)
{
	return syscall(SYS_sendfile, out_fd, in_fd, ofs, count);
}

LFS64(sendfile);


text:
<?php op_include_form('deleteConfirmForm', $form, array(
  'button' => __('Delete'),
  'title' => __('Do you really delete this topic?'),
  'url' => url_for('@communityTopic_delete?id='.$communityTopic->getId())
)) ?>


text:
package de.envisia.postgresql.encoders

import java.nio.ByteOrder
import java.nio.charset.Charset

import akka.stream.scaladsl.{ Flow, Source }
import akka.util.ByteString
import de.envisia.akka.utils.ByteStringUtils
import de.envisia.postgresql.message.frontend.StartupMessage

class StartupMessageEncoder(charset: Charset) {

  // To build a correct message we need to use BIG_ENDIAN
  implicit val order = ByteOrder.BIG_ENDIAN

  def encode(startup: StartupMessage): ByteString = {
    val builder = ByteString.newBuilder
    builder.putShort(3)
    builder.putShort(0)

    startup.parameters.foreach {
      case (key, msg) =>
        msg match {
          case value: String =>
            ByteStringUtils.putCString(builder, key, charset)
            ByteStringUtils.putCString(builder, value, charset)
          case Some(value) =>
            ByteStringUtils.putCString(builder, key, charset)
            ByteStringUtils.putCString(builder, value.toString, charset)
          case _ =>
        }
    }

    builder.putByte(0)
    ByteStringUtils.resultWithLength(builder)
  }

}


text:
package network

type Forwardingsession struct {
	Acl6name         string `json:"acl6name,omitempty"`
	Aclname          string `json:"aclname,omitempty"`
	Connfailover     string `json:"connfailover,omitempty"`
	Name             string `json:"name,omitempty"`
	Netmask          string `json:"netmask,omitempty"`
	Network          string `json:"network,omitempty"`
	Processlocal     string `json:"processlocal,omitempty"`
	Sourceroutecache string `json:"sourceroutecache,omitempty"`
	Td               int    `json:"td,omitempty"`
}


text:
from .aws import Action as BaseAction
from .aws import BaseARN

service_name = "Amazon GameSparks"
prefix = "gamesparks"

class Action(BaseAction):
    def __init__(self, action: str = None) -> None:
        super().__init__(prefix, action)

class ARN(BaseARN):
    def __init__(self, resource: str = "", region: str = "", account: str = "") -> None:
        super().__init__(
            service=prefix, resource=resource, region=region, account=account
        )

CreateGame = Action("CreateGame")
CreateSnapshot = Action("CreateSnapshot")
CreateStage = Action("CreateStage")
DeleteGame = Action("DeleteGame")
DeleteStage = Action("DeleteStage")
DisconnectPlayer = Action("DisconnectPlayer")
ExportSnapshot = Action("ExportSnapshot")
GetExtension = Action("GetExtension")
GetExtensionVersion = Action("GetExtensionVersion")
GetGame = Action("GetGame")
GetGameConfiguration = Action("GetGameConfiguration")
GetGeneratedCodeJob = Action("GetGeneratedCodeJob")
GetPlayerConnectionStatus = Action("GetPlayerConnectionStatus")
GetSnapshot = Action("GetSnapshot")
GetStage = Action("GetStage")
GetStageDeployment = Action("GetStageDeployment")
ImportGameConfiguration = Action("ImportGameConfiguration")
InvokeBackend = Action("InvokeBackend")
ListExtensionVersions = Action("ListExtensionVersions")
ListExtensions = Action("ListExtensions")
ListGames = Action("ListGames")
ListGeneratedCodeJobs = Action("ListGeneratedCodeJobs")
ListSnapshots = Action("ListSnapshots")
ListStageDeployments = Action("ListStageDeployments")
ListStages = Action("ListStages")
ListTagsForResource = Action("ListTagsForResource")
StartGeneratedCodeJob = Action("StartGeneratedCodeJob")
StartStageDeployment = Action("StartStageDeployment")
TagResource = Action("TagResource")
UntagResource = Action("UntagResource")
UpdateGame = Action("UpdateGame")
UpdateGameConfiguration = Action("UpdateGameConfiguration")
UpdateSnapshot = Action("UpdateSnapshot")
UpdateStage = Action("UpdateStage")


text:
package org.apache.asterix.dataflow.data.common;

import org.apache.asterix.common.functions.FunctionSignature;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.functions.ExternalFunctionInfo;
import org.apache.asterix.om.typecomputer.base.IResultTypeComputer;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.IAType;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IAlgebricksConstantValue;
import org.apache.hyracks.algebricks.core.algebra.expressions.IExpressionTypeComputer;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;

public class ExpressionTypeComputer implements IExpressionTypeComputer {

    public static final ExpressionTypeComputer INSTANCE = new ExpressionTypeComputer();

    private ExpressionTypeComputer() {
    }

    @Override
    public Object getType(ILogicalExpression expr, IMetadataProvider<?, ?> metadataProvider,
            IVariableTypeEnvironment env) throws AlgebricksException {
        switch (expr.getExpressionTag()) {
            case CONSTANT:
                return getTypeForConstant((ConstantExpression) expr, env);
            case FUNCTION_CALL:
                return getTypeForFunction((AbstractFunctionCallExpression) expr, env, metadataProvider);
            case VARIABLE:
                try {
                    return env.getVarType(((VariableReferenceExpression) expr).getVariableReference());
                } catch (Exception e) {
                    throw new AlgebricksException("Could not resolve type for " + expr.toString() + ","
                            + "please check whether the used variable has been defined!", e);
                }
            default:
                throw new IllegalStateException();
        }
    }

    private IAType getTypeForFunction(AbstractFunctionCallExpression expr, IVariableTypeEnvironment env,
            IMetadataProvider<?, ?> mp) throws AlgebricksException {
        FunctionIdentifier fi = expr.getFunctionIdentifier();
        // Note: built-in functions + udfs
        IResultTypeComputer rtc;
        FunctionSignature signature = new FunctionSignature(fi);
        if (BuiltinFunctions.isBuiltinCompilerFunction(signature, true)) {
            rtc = BuiltinFunctions.getResultTypeComputer(fi);
        } else {
            rtc = ((ExternalFunctionInfo) expr.getFunctionInfo()).getResultTypeComputer();
        }
        if (rtc == null) {
            throw new AlgebricksException("Type computer missing for " + fi);
        }
        return rtc.computeType(expr, env, mp);
    }

    private IAType getTypeForConstant(ConstantExpression expr, IVariableTypeEnvironment env) {
        IAlgebricksConstantValue acv = expr.getValue();
        if (acv.isFalse() || acv.isTrue()) {
            return BuiltinType.ABOOLEAN;
        } else if (acv.isMissing()) {
            return BuiltinType.AMISSING;
        } else if (acv.isNull()) {
            return BuiltinType.ANULL;
        } else {
            AsterixConstantValue value = (AsterixConstantValue) acv;
            return value.getObject().getType();
        }
    }

}


text:
CREATE TABLE `tb_bxtlrumrtn` (
  `col_uttbttlgkx` smallint(181) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `tb_irclltefag` (
  `col_iabzixqyhm` tinyblob,
  `col_otoxjlwatj` date DEFAULT '2019-07-04',
  UNIQUE KEY `col_otoxjlwatj` (`col_otoxjlwatj`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
package com.zacharyarden.viceboard.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import io.realm.RealmObject;

public class Video extends RealmObject implements Parcelable {

    @SerializedName("duration")
    @Expose
    private String duration;
    @SerializedName("video_duration")
    @Expose
    private String videoDuration;
    @SerializedName("ooyalaId")
    @Expose
    private String ooyalaId;
    @SerializedName("thrid_party_video_id")
    @Expose
    private String thridPartyVideoId;
    @SerializedName("video_type")
    @Expose
    private String videoType;

    /**
     *
     * @return
     * The duration
     */
    public String getDuration() {
        return duration;
    }

    /**
     *
     * @param duration
     * The duration
     */
    public void setDuration(String duration) {
        this.duration = duration;
    }

    /**
     *
     * @return
     * The videoDuration
     */
    public String getVideoDuration() {
        return videoDuration;
    }

    /**
     *
     * @param videoDuration
     * The video_duration
     */
    public void setVideoDuration(String videoDuration) {
        this.videoDuration = videoDuration;
    }

    /**
     *
     * @return
     * The ooyalaId
     */
    public String getOoyalaId() {
        return ooyalaId;
    }

    /**
     *
     * @param ooyalaId
     * The ooyalaId
     */
    public void setOoyalaId(String ooyalaId) {
        this.ooyalaId = ooyalaId;
    }

    /**
     *
     * @return
     * The thridPartyVideoId
     */
    public String getThridPartyVideoId() {
        return thridPartyVideoId;
    }

    /**
     *
     * @param thridPartyVideoId
     * The thrid_party_video_id
     */
    public void setThridPartyVideoId(String thridPartyVideoId) {
        this.thridPartyVideoId = thridPartyVideoId;
    }

    /**
     *
     * @return
     * The videoType
     */
    public String getVideoType() {
        return videoType;
    }

    /**
     *
     * @param videoType
     * The video_type
     */
    public void setVideoType(String videoType) {
        this.videoType = videoType;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.duration);
        dest.writeString(this.videoDuration);
        dest.writeString(this.ooyalaId);
        dest.writeString(this.thridPartyVideoId);
        dest.writeString(this.videoType);
    }

    public Video() {
    }

    protected Video(Parcel in) {
        this.duration = in.readString();
        this.videoDuration = in.readString();
        this.ooyalaId = in.readString();
        this.thridPartyVideoId = in.readString();
        this.videoType = in.readString();
    }

    public static final Parcelable.Creator<Video> CREATOR = new Parcelable.Creator<Video>() {
        @Override
        public Video createFromParcel(Parcel source) {
            return new Video(source);
        }

        @Override
        public Video[] newArray(int size) {
            return new Video[size];
        }
    };
}