text:
django-admin-easy
=================

Collection of admin fields, decorators and mixin to help to create computed or custom fields more friendly and easy way

.. image:: https://img.shields.io/badge/django-1.8%201.9%201.10%201.11%202.0%202.1%202.2%203.0%203.1%203.2-brightgreen.svg
  :target: http://pypi.python.org/pypi/django-admin-easy

.. image:: https://img.shields.io/pypi/v/django-admin-easy.svg?style=flat
  :target: http://pypi.python.org/pypi/django-admin-easy

.. image:: https://img.shields.io/pypi/pyversions/django-admin-easy.svg?maxAge=2592000
  :target: http://pypi.python.org/pypi/django-admin-easy

.. image:: https://img.shields.io/pypi/format/django-admin-easy.svg?maxAge=2592000
  :target: http://pypi.python.org/pypi/django-admin-easy

.. image:: https://img.shields.io/pypi/status/django-admin-easy.svg?maxAge=2592000
  :target: http://pypi.python.org/pypi/django-admin-easy

.. image:: https://img.shields.io/travis/ebertti/django-admin-easy/master.svg?maxAge=2592000
  :target: https://travis-ci.org/ebertti/django-admin-easy

.. image:: https://img.shields.io/requires/github/ebertti/django-admin-easy.svg?maxAge=2592000
  :target: https://requires.io/github/ebertti/django-admin-easy/requirements/

.. image:: https://img.shields.io/coveralls/ebertti/django-admin-easy/master.svg?maxAge=2592000
  :target: https://coveralls.io/r/ebertti/django-admin-easy?branch=master

Installation
------------

1. Requirements: **Django > 1.8** and **Python > 3.5**

2. ``pip install django-admin-easy==0.6.1``

* For **Django < 1.8** or **Python 2.x**

  ``pip install django-admin-easy==0.4.1``

How it Works
------------

When you want to display a field on Django Admin, and this field doesn't exist in your Model
or you need to compute some information, like a Image or Link, you will need to create a method on your ModelAdminClass like this:

.. code-block:: python

    from django.contrib import admin

    class YourAdmin(admin.ModelAdmin):
        fields = ('sum_method', 'some_img', 'is_true')

        def sum_method(self, obj):
            sum_result = obj.field1 + obj.field2 + obj.field3
            return '%s' % sum_result
        sum_method.short_description = 'Sum'
        sum_method.admin_order_field = 'field1'
        sum_method.allow_tags = True

        def some_img(self, obj):
            return '' % obj.image
        some_img.short_description = 'image'
        some_img.admin_order_field = 'id'
        some_img.allow_tags = True

        def is_true(self, obj):
            return obj.value > 0
        is_true.short_description = 'Positive'
        is_true.admin_order_field = 'value'
        is_true.boolean = True

It takes too much lines! =D

With **django-admin-easy** you can easily create this field with less lines:

.. code-block:: python

    from django.contrib import admin
    import easy

    class YourAdmin(admin.ModelAdmin):
        fields = ('sum_method', 'some_img', 'is_true')

        sum_method = easy.SimpleAdminField(lambda obj: '%s' % (obj.field1 + obj.field2 + obj.field3), 'Sum', 'field1', True)
        some_img = easy.ImageAdminField('image', 'id')
        is_true = easy.BooleanAdminField('Positive', 'value')

If you still prefer using a custom method, you can use our decorators, like this:

.. code-block:: python

    from django.contrib import admin
    import easy

    class YourAdmin(admin.ModelAdmin):
        fields = ('sum_method', 'some_img', 'is_true')

        @easy.smart(short_description='Sum', admin_order_field='field1', allow_tags=True )
        def sum_method(self, obj):
            sum_result = obj.field1 + obj.field2 + obj.field3
            return '%s' % sum_result

        @easy.short(desc='image', order='id', tags=True)
        def some_img(self, obj):
            return '' % obj.image

        @easy.short(desc='Positive', order='value', bool=True)
        def is_true(self, obj):
            return obj.value > 0

Another Decorators
------------------

In all of this extra decorators, you can use `short` or `smart` arguments to complement field information.

* **Allow HTML tags**

.. code-block:: python

    @easy.with_tags()
    def some_field_with_html(self, obj):
        return '{}'.format(obj.value)
    # output some as: mark_safe("something")

if value is `5`, will display:

**5** and not `<b>5</b>` on admin page.

* **Cached field**

If you, for some reason, need to cache a custom field on admin

.. code-block:: python

    @easy.cache(10)# in secondd, default is 60
    def some_field_with_html(self, obj):
        return obj.related.some_hard_word()

If you change something on your model, or some related object, you can clean this cache using this easy way:

.. code-block:: python

    import easy
    # wherever you want
    easy.cache_clear(my_model_instance)

    # or
    class MyModel(models.Model):
        # ... fields

        def save(*args, **kwargs):
            easy.cache_clear(self)
            super(MyModel, self).save(*args, **kwargs)

* **Django template filter**

Can be used with all template filters on your project.

.. code-block:: python

    # builtin template filter like {{ value|title }}
    @easy.filter('title')
    def some_field_with_html(self, obj):
        return 'ezequiel bertti'
    # output: "Ezequiel Bertti"

    # like {% load i10n %} and {{ value|localize }}
    @easy.filter('localize', 'l10n')
    def some_field_with_html(self, obj):
        return 10000
    # output: "10.000"

    # like {{ value|date:'y-m-d' }}
    @easy.filter('date', 'default', 'y-m-d')
    def some_field_with_html(self, obj):
        return datetime(2016, 06, 28)
    # output: "16-06-28"

* **Django utils functions**

Tested with:

.. code-block:: python

    @easy.utils('html.escape')
    @easy.utils('html.conditional_escape')
    @easy.utils('html.strip_tags')
    @easy.utils('safestring.mark_safe')
    @easy.utils('safestring.mark_for_escaping')
    @easy.utils('text.slugify')
    @easy.utils('translation.gettext')
    @easy.utils('translation.ugettext')
    @easy.utils('translation.gettext_lazy')
    @easy.utils('translation.ugettext_lazy')
    @easy.utils('translation.gettext_noop')
    @easy.utils('translation.ugettext_noop')
    def your_method(self, obj):
        return obj.value

More Examples
-------------

.. code-block:: python

    from django.contrib import admin
    import easy

    class YourAdmin(admin.ModelAdmin):
        list_fields = ('id', 'custom1', 'custom2', 'custom3' ... 'customN')

        actions = ('simples_action',)

        @easy.action('My Little Simple Magic Action')
        def simple_action(self, request, queryset):
            return queryset.update(magic=True)

        # actoin only for user that has change permission on this model
        @easy.action('Another Simple Magic Action', 'change')
        def simple_action(self, request, queryset):
            return queryset.update(magic=True)

        # render a value of field, method, property or your model or related model
        simple1 = easy.SimpleAdminField('model_field')
        simple2 = easy.SimpleAdminField('method_of_model')
        simple3 = easy.SimpleAdminField('related.attribute_or_method')
        simple4 = easy.SimpleAdminField('related_set.count', 'count')
        simple5 = easy.SimpleAdminField(lambda x: x.method(), 'show', 'order_by')

        # render boolean fields
        bool1 = easy.BooleanAdminField(lambda x: x.value > 10, 'high')

        # render with string format fields
        format1 = easy.FormatAdminField('{o.model_field} - {o.date_field:Y%-%m}', 'column name')

        # render foreignkey with link to change_form in admin
        fk1 = easy.ForeignKeyAdminField('related')

        # render foreignkey with link to change_form in admin and related_id content as text
        fk2 = easy.ForeignKeyAdminField('related', 'related_id')

        # render foreignkey_id, like raw_id_fields, with link to change_form in admin and related_id content as text
        # without extra queries or select_related to prevent extra n-1 queries
        raw1 = easy.RawIdAdminField('related')

        # render template
        template1 = easy.TemplateAdminField('test.html', 'shorty description', 'order_field')

        # render to change_list of another model with a filter on query
        link1 = easy.LinkChangeListAdminField('app_label', 'model_name', 'attribute_to_text',
                                              {'field_name':'dynamic_value_model'})

        link2 = easy.LinkChangeListAdminField('app_label', 'model_name', 'attribute_to_text',
                                              {'field_name':'dynamic_value_model'},
                                              {'another_field': 'static_value'})

        # display image of some model
        image1 = easy.ImageAdminField('image', {'image_attrs':'attr_value'})

        # use django template filter on a field
        filter1 = easy.FilterAdminField('model_field', 'upper')
        filter2 = easy.FilterAdminField('date_field', 'date', 'django', 'y-m-d')
        filter3 = easy.FilterAdminField('float_field', 'localize', 'l18n')

        @easy.smart(short_description='Field Description 12', admin_order_field='model_field')
        def custom12(self, obj):
            return obj.something_cool()

        @easy.short(desc='Field Description 1', order='model_field', tags=True)
        def decorator1(self, obj):
            return '' + obj.model_field + ''

        @easy.short(desc='Field Description 2', order='model_field', bool=True)
        def decorator2(self, obj):
            return obj.model_field > 10

If you want to use on admin form to show some information,
don't forget to add your custom field on ``readonly_fields`` attribute of your admin class

.. code-block:: python

    from django.contrib import admin
    import easy

    class YourAdmin(admin.ModelAdmin):
        fields = ('custom1', 'custom2', 'custom3' ... 'customN')
        readonly_fields = ('custom1', 'custom2', 'custom3' ... 'customN')

        custom1 = easy.ForeignKeyAdminField('related')
        # ...

Another way to use is directly on ``list_fields`` declaration:

.. code-block:: python

    from django.contrib import admin
    import easy

    class YourAdmin(admin.ModelAdmin):
        list_fields = (
            easy.TemplateAdminField('test.html', 'shorty description', 'order_field'),
            easy.ImageAdminField('image', {'image_attrs':'attr_value'}),
            # ...
        )

        # ...

Mixin
-----

To help you to create a custom view on django admin, we create the MixinEasyViews for your Admin Classes

.. code-block:: python

    from django.contrib import admin
    import easy

    class MyModelAdmin(easy.MixinEasyViews, admin.ModelAdmin):
        # ...

        def easy_view_jump(self, request, pk=None):
            # do something here
            return HttpResponse('something')

To call this view, you can use this reverse:

.. code-block:: python

    from django.core.urlresolvers import reverse

    # to do something with one object of a model
    reverse('admin:myapp_mymodel_easy', args=(obj.pk, 'jump'))

    # or to do something with a model
    reverse('admin:myapp_mymodel_easy', args=('jump',))

Or one HTML template

.. code-block:: html

    #
    {% url 'admin:myapp_mymodel_easy' obj.pk 'jump' %}

    #
    {% url 'admin:myapp_mymodel_easy' 'jump' %}

Utilities
---------

* Response for admin actions

  Return for the change list and show some message for the user keeping or not the filters.

.. code-block:: python

    from django.contrib import admin
    from django.contrib import messages
    import easy

    class YourAdmin(admin.ModelAdmin):
        # ...
        actions = ('simples_action',)

        def simples_action(self, request, queryset):

            success = queryset.do_something()
            if success:
                return easy.action_response(request, 'Some success message for user', keep_querystring=False)
            else:
                return easy.action_response(request, 'Some error for user', messages.ERROR)

            # or just redirect to changelist with filters
            return easy.action_response()

So easy, no?

Screenshot
----------

Using example of poll of django tutorial

.. image:: https://raw.githubusercontent.com/ebertti/django-admin-easy/master/screenshot/more.png

.. image:: https://raw.githubusercontent.com/ebertti/django-admin-easy/master/screenshot/related.png

Please help us
--------------
This project is still under development. Feedback and suggestions are very welcome and I encourage you to use the `Issues list <http://github.com/ebertti/django-admin-easy/issues>`_ on Github to provide that feedback.

.. image:: https://img.shields.io/github/issues/ebertti/django-admin-easy.svg
   :target: https://github.com/ebertti/django-admin-easy/issues

.. image:: https://img.shields.io/waffle/label/ebertti/django-admin-easy/in%20progress.svg?maxAge=2592000
   :target: https://waffle.io/ebertti/django-admin-easy

.. image:: https://img.shields.io/github/forks/ebertti/django-admin-easy.svg
   :target: https://github.com/ebertti/django-admin-easy/network

.. image:: https://img.shields.io/github/stars/ebertti/django-admin-easy.svg
   :target: https://github.com/ebertti/django-admin-easy/stargazers

Authors
-------
The django-admin-easy was originally created by Ezequiel Bertti `@ebertti <https://github.com/ebertti>`_ October 2014.

Changelog
---------
* 0.6.1

   * Add Support do Django 3.2 and Python 3.9

* 0.6

   * Add RawIdAdminField

* 0.5.1

   * Add permission on action decorator

* 0.4.1

  * Django 2.0

* 0.4

  * Django 1.11
  * Create module utils with action_response

* 0.3.2

  * Add params_static to LinkChangeListAdminField

* 0.3.1

  * Add FormatAdminField

* 0.3

  * Add import from `__future__` on all files
  * Django 1.10
  * More decorators
  * More admin fields

* 0.2.2

  * Add MixinEasyViews

* 0.2.1

  * Fix for Django 1.7 from `@kevgathuku <https://github.com/kevgathuku>`_


text:
var Router = Ember.Router.extend({
  location: ENV.locationType
});

Router.map(function() {
  this.resource('about');
  this.resource('posts', function() {
    this.resource('post', { path: ':post_id' });
  });
});

export default Router;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="x-ua-compatible" content="ie=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" />
		<link rel="stylesheet" href="build/conversational-form-docs.min.css">

			<menu id="small-screen-menu">

Conversational Form examples

						<input type="checkbox" onclick="window.conversationalFormExamples.toggleConversation(event)">

					<svg viewBox="0 0 29 14" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
						<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-linecap="square">
							<g transform="translate(-325.000000, -87.000000)" stroke="#FFFFFF" stroke-width="2">
								<g transform="translate(325.000000, 87.000000)">
									<path d="M27.4802431,7 L1.23827993,7"></path>
									<path d="M27.4802431,1 L1.23827993,1"></path>
									<path d="M27.4802431,13 L1.23827993,13"></path>
								</g>
							</g>
						</g>
					</svg>

			</menu>

					<input type="checkbox" onclick="window.conversationalFormExamples.toggleConversation(event)">

					<svg viewBox="0 0 22 22" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
						<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" stroke-linecap="square">
							<g transform="translate(-328.000000, -83.000000)" stroke="#FFFFFF" stroke-width="2">
								<g id="close" transform="translate(329.000000, 84.000000)">
									<path d="M19.6371966,19.2779351 L1.08132646,0.722064927"></path>
									<path d="M19.4923318,0.722064927 L0.936461672,19.2779351"></path>
								</g>
							</g>
						</g>
					</svg>

						Add a welcome message

						And style it like a champ

					<form id="form" cf-form>

							<input cf-questions="Hi friend, this is a welcome message example, let's begin?" cf-label="Yes, let's begin!" type="radio" value="0">
							Newsletter

						<input type="text" cf-questions="..." />
					</form>


text:
import { TaskInstance } from './-private/task-instance';
import { deprecatePrivateModule } from './-private/utils';
deprecatePrivateModule('ember-concurrency/-task-instance');
export default TaskInstance;


text:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

	<!-- /properties/applicationContext.xml The main Spring configuration file.
		This file should not be modified but by the developers. This file is referenced
		by /webapp/WEB-INF/web.xml. -->

	<bean id="app_context" class="org.esupportail.commons.context.ApplicationContextHolder" />

	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:/properties/defaults.properties</value>
			</list>
		</property>
	</bean>

</beans>


text:
package o;

import android.graphics.Bitmap;

public class AuX$ˊ extends AuX.Aux
{
  Bitmap ˊ;
  Bitmap ˋ;
  boolean ˎ;
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     o.AuX.Àä
 * JD-Core Version:    0.6.2
 */


text:
import React from 'react';
import AMUIReact from 'amazeui-react';

import Lib from '../Lib'

var VideoList = React.createClass({
  render: function () {
    var list = this.props.list;
    var insetList = [];
    for (var i = 0; i < list.length; i++) {
      insetList.push({
        title: list[i].title,
        link: '#/play/' + list[i].aid,
        desc: list[i].description,
        img: list[i].pic
      });
    }
    var data = {
      header: {
        title: '视频'
      },
      main: insetList
    };
    return <AMUIReact.ListNews data={data} thumbPosition='left' key='list'/>;
  }
});

var UpUserList = React.createClass({
  render: function () {
    var list = this.props.list;
    var insetList = [];
    for (var i = 0; i < list.length; i++) {
      insetList.push({
        title: list[i].uname,
        link: '#',
        desc: list[i].usign,
        img: list[i].upic
      });
    }
    var data = {
      header: {
        title: '用户'
      },
      main: insetList
    };
    return <AMUIReact.ListNews data={data} thumbPosition='left' key='list'/>;
  }
});

var BangumiList = React.createClass({
  render: function () {
    var list = this.props.list;
    var insetList = [];
    for (var i = 0; i < list.length; i++) {
      insetList.push({
        title: list[i].title,
        link: '#/sp/' + list[i].spid,
        desc: list[i].evaluate,
        img: list[i].cover
      });
    }
    var data = {
      header: {
        title: '新番'
      },
      main: insetList
    };
    return <AMUIReact.ListNews data={data} thumbPosition='left' key='list'/>;
  }
});

var SPList = React.createClass({
  render: function () {
    var list = this.props.list;
    var insetList = [];
    for (var i = 0; i < list.length; i++) {
      insetList.push({
        title: list[i].title,
        link: '#/sp/' + list[i].spid,
        desc: list[i].description,
        img: list[i].pic
      });
    }
    var data = {
      header: {
        title: '专题'
      },
      main: insetList
    };
    return <AMUIReact.ListNews data={data} thumbPosition='left' key='list'/>;
  }
});

//总容器
var ContentList = React.createClass({
  render: function () {
    var type = this.props.type;
    if (this.props.data[type].length > 0) {
      var allData = this.props.data;
      var rendList = [];
      switch (type) {
        case 'video':
          rendList.push(<VideoList key="videoList" list={ allData.video }/>);
          break;
        case 'upuser':
          rendList.push(<UpUserList key="upList" list={ allData.upuser }/>);
          break;
        case 'bangumi':
          rendList.push(<BangumiList key="bangumiList" list={ allData.bangumi }/>);
          break;
        case 'special':
          rendList.push(<SPList key="spList" list={ allData.special }/>);
          break;
      }
      if (this.props.allPage[type] > this.props.page) {
        rendList.push(<Lib.LoadingButton block clickHandler={this.props.handler} loadingText='正在加载...' key='load-btn'>加载更多</Lib.LoadingButton>)
      }
      return
{rendList}
;
    }
    return <Lib.NoMoreWidght />;
  }
});

var selectData = [
  {link: 'video', title: '视频'},
  {link: 'bangumi', title: '新番'},
  {link: 'special', title: '专题'},
  {link: 'upuser', title: 'up主'}];

var SearchContent = React.createClass({
  getSearch: function (content, page, order) {
    $.ajax({
      method: 'post',
      url: Lib.BaseUrl + '/search',
      data: {content: content, count: 15, page: page, order: order},
      context: this,
      success: function (data) {
        var allData = this.state.data;
        //页码为1重置
        if (page == 1) {
          allData = {video: [], bangumi: [], special: [], upuser: []};
        }
        for (var dataType in allData) {
          allData[dataType] = allData[dataType].concat(data.result[dataType]);
        }
        var allPage = {
          video: data.page_info.video.pages,
          bangumi: data.page_info.bangumi.pages,
          special: data.page_info.special.pages,
          upuser: data.page_info.upuser.pages
        };
        this.setState({
          content: content,
          data: allData,
          loading: false,
          page: page,
          allPage: allPage,
          error: false,
          isLoad: true
        });
      },
      error: function () {
        this.setState({error: true});
      }
    });
  },
  getInitialState: function () {
    return {
      content: null,
      error: false,
      loading: false,
      order: 'hot',
      //默认分类
      type: 'video',
      page: 1,
      //总共页数
      allPage: {video: 1, bangumi: 1, special: 1, upuser: 1},
      //各分类分页数据
      data: {video: [], bangumi: [], special: [], upuser: []},
      //是否首次访问
      isLoad: false
    };
  },
  handleSubmit: function (e) {
    e.preventDefault();
    var value = document.getElementById('search_content').value;
    this.getSearch(value, 1, this.state.order);
    this.setState({loading: true});
  },
  //切换分类
  handleTypeClick: function (nav, index, e) {
    if (nav) {
      e.preventDefault();
      if (this.state.type != nav.link) {
        this.setState({type: nav.link});
      }
    }
  },
  pageAdd: function () {
    this.getSearch(this.state.content, this.state.page + 1, this.state.order);
  },
  render: function () {
    var btnSearch = <AMUIReact.Button type='submit'><AMUIReact.Icon icon="search"/></AMUIReact.Button>;
    return

      <AMUIReact.Grid>
        <AMUIReact.Col md={8} mdOffset={2}>
          <AMUIReact.Form onSubmit={this.handleSubmit} id="search-form">
            <AMUIReact.Input placeholder="要搜索的内容" id='search_content' btnAfter={btnSearch}/></AMUIReact.Form>
        </AMUIReact.Col>
      </AMUIReact.Grid>
      <AMUIReact.Grid>
        <AMUIReact.Col md={8} mdOffset={2}>
          {(this.state.error ? (<Lib.ErrorWidght />) : (this.state.loading ? <Lib.LoadingWidght /> :
            (this.state.isLoad) ?
<AMUIReact.Menu cols={4} data={selectData} onSelect={this.handleTypeClick}/>
              <ContentList handler={ this.pageAdd } allPage={ this.state.allPage} data={ this.state.data }
                           type={ this.state.type } page={ this.state.page }/>
 :

))}
        </AMUIReact.Col>
      </AMUIReact.Grid>

;
  }
});

export default React.createClass({
  render: function () {
    return

      <SearchContent />

;
  }
});


text:
package hudson.plugins.scm.koji;

import hudson.Extension;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.plugins.scm.koji.model.BuildProvider;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import org.fakekoji.xmlrpc.server.JavaServerConstants;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;

import javax.annotation.Nonnull;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.net.URL;

public class KojiBuildProvider implements Describable<KojiBuildProvider>, Serializable {

    private final BuildProvider buildProvider;

    @DataBoundConstructor
    public KojiBuildProvider(String topUrl, String downloadUrl) {
        buildProvider = new BuildProvider(replaceXPort(topUrl), replaceDPORT(downloadUrl));
    }

    @SuppressWarnings("unchecked")
    @Override
    public Descriptor<KojiBuildProvider> getDescriptor() {
        return Jenkins.getActiveInstance().getDescriptorOrDie(getClass());
    }

    public BuildProvider getBuildProvider() {
        return buildProvider;
    }

    public String getTopUrl() {
        return buildProvider.getTopUrl();
    }

    public String getDownloadUrl() {
        return buildProvider.getDownloadUrl();
    }

    private static String replaceDPORT(String url) {
        return url.replace(
                ":" + JavaServerConstants.dPortAxiom,
                ":" + JavaServerConstants.DFAULT_DWNLD_PORT
        );
    }

    private static String replaceXPort(String url) {
        return url.replace(
                ":" + JavaServerConstants.xPortAxiom,
                ":" + JavaServerConstants.DFAULT_RP2C_PORT
        );
    }

    @Extension
    public static final class KojiBuildProviderDescriptor extends Descriptor<KojiBuildProvider> {

        private static final String SUPPORTED_PROTOCOL = "HTTP";
        private static final String URL_INVALID = "The URL is invalid";
        private static final String PROTOCOL_NOT_SUPPORTED = "Only " + SUPPORTED_PROTOCOL + " protocol is supported";

        @Nonnull
        @Override
        public String getDisplayName() {
            return "Koji build provider";
        }

        FormValidation doCheckTopUrl(@QueryParameter String value) {
            try {
                new URL(replaceXPort(value));
            } catch (MalformedURLException e) {
                return FormValidation.error(URL_INVALID);
            }
            return FormValidation.ok();
        }

        FormValidation doCheckDownloadUrl(@QueryParameter String value) {
            try {
                final URL url = new URL(replaceDPORT(value));
                if (!url.getProtocol().equals(SUPPORTED_PROTOCOL.toLowerCase())) {
                    return FormValidation.error(PROTOCOL_NOT_SUPPORTED);
                }
            } catch (MalformedURLException e) {
                return FormValidation.error(URL_INVALID);
            }
            return FormValidation.ok();
        }
    }
}


text:
import React from 'react';
import {
  Button,
  Flex,
  Link,
  Divider,
} from '@chakra-ui/react';

import { useExtraLinks } from 'src/api';

interface Props {
  dagId: string;
  taskId: string;
  executionDate: string;
  extraLinks: string[];
}

const ExtraLinks = ({
  dagId,
  taskId,
  executionDate,
  extraLinks = [],
}: Props) => {
  const { data: links = [] } = useExtraLinks({
    dagId, taskId, executionDate, extraLinks,
  });

  if (!links.length) return null;
  const isExternal = (url: string | null) => url && /^(?:[a-z]+:)?\/\//.test(url);

  return (
    <>
      <Divider my={2} />
      <Flex flexWrap="wrap">
        {links.map(({ name, url }) => (
          <Button
            key={name}
            as={Link}
            colorScheme="blue"
            href={url}
            isDisabled={!url}
            target={isExternal(url) ? '_blank' : undefined}
          >
            {name}
          </Button>
        ))}
      </Flex>
    </>
  );
};

export default ExtraLinks;


text:
#include "qunicodetables_p.h"
#include "qlibrary.h"
#include "qtextcodec.h"

#include "qharfbuzz_p.h"

QT_USE_NAMESPACE

extern "C" {

HB_GraphemeClass HB_GetGraphemeClass(HB_UChar32 ch)
{
    const QUnicodeTables::Properties *prop = QUnicodeTables::properties(ch);
    return (HB_GraphemeClass) prop->graphemeBreak;
}

HB_WordClass HB_GetWordClass(HB_UChar32 ch)
{
    const QUnicodeTables::Properties *prop = QUnicodeTables::properties(ch);
    return (HB_WordClass) prop->wordBreak;
}

HB_SentenceClass HB_GetSentenceClass(HB_UChar32 ch)
{
    const QUnicodeTables::Properties *prop = QUnicodeTables::properties(ch);
    return (HB_SentenceClass) prop->sentenceBreak;
}

HB_LineBreakClass HB_GetLineBreakClass(HB_UChar32 ch)
{
    return (HB_LineBreakClass)QUnicodeTables::lineBreakClass(ch);
}

void HB_GetGraphemeAndLineBreakClass(HB_UChar32 ch, HB_GraphemeClass *grapheme, HB_LineBreakClass *lineBreak)
{
    const QUnicodeTables::Properties *prop = QUnicodeTables::properties(ch);
    *grapheme = (HB_GraphemeClass) prop->graphemeBreak;
    *lineBreak = (HB_LineBreakClass) prop->line_break_class;
}

void HB_GetUnicodeCharProperties(HB_UChar32 ch, HB_CharCategory *category, int *combiningClass)
{
    const QUnicodeTables::Properties *prop = QUnicodeTables::properties(ch);
    *category = (HB_CharCategory)prop->category;
    *combiningClass = prop->combiningClass;
}

HB_CharCategory HB_GetUnicodeCharCategory(HB_UChar32 ch)
{
    return (HB_CharCategory)QChar::category(ch);
}

int HB_GetUnicodeCharCombiningClass(HB_UChar32 ch)
{
    return QChar::combiningClass(ch);
}

HB_UChar16 HB_GetMirroredChar(HB_UChar16 ch)
{
    return QChar::mirroredChar(ch);
}

void *HB_Library_Resolve(const char *library, int version, const char *symbol)
{
#ifdef QT_NO_LIBRARY
    return 0;
#else
    return QLibrary::resolve(QLatin1String(library), version, symbol);
#endif
}

} // extern "C"

QT_BEGIN_NAMESPACE

HB_Bool qShapeItem(HB_ShaperItem *item)
{
    return HB_ShapeItem(item);
}

HB_Face qHBNewFace(void *font, HB_GetFontTableFunc tableFunc)
{
    return HB_NewFace(font, tableFunc);
}

void qHBFreeFace(HB_Face face)
{
    HB_FreeFace(face);
}

void qGetCharAttributes(const HB_UChar16 *string, hb_uint32 stringLength,
                        const HB_ScriptItem *items, hb_uint32 numItems,
                        HB_CharAttributes *attributes)
{
    HB_GetCharAttributes(string, stringLength, items, numItems, attributes);
}

QT_END_NAMESPACE


text:
package com.asakusafw.compiler.flow;

import com.asakusafw.compiler.flow.example.MockHogeExporterDescription;
import com.asakusafw.compiler.flow.example.MockHogeImporterDescription;
import com.asakusafw.compiler.operator.model.MockHoge;
import com.asakusafw.vocabulary.flow.Export;
import com.asakusafw.vocabulary.flow.FlowDescription;
import com.asakusafw.vocabulary.flow.Import;
import com.asakusafw.vocabulary.flow.In;
import com.asakusafw.vocabulary.flow.JobFlow;
import com.asakusafw.vocabulary.flow.Out;

/**
 * A jobflow class which is not declared as public.
 */
@JobFlow(name = "testing")
class NotPublicJobFlow extends FlowDescription {

    private final In<MockHoge> in;

    private final Out<MockHoge> out;

    /**
     * Creates a new instance.
     * @param in input
     * @param out output
     */
    public NotPublicJobFlow(
            @Import(name = "hoge", description = MockHogeImporterDescription.class)
            In<MockHoge> in,
            @Export(name = "hoge", description = MockHogeExporterDescription.class)
            Out<MockHoge> out) {
        this.in = in;
        this.out = out;
    }

    @Override
    protected void describe() {
        out.add(in);
    }
}


text:
#pragma once

#include <functional>

#include "envoy/common/time.h"
#include "envoy/config/typed_config.h"
#include "envoy/ssl/context.h"
#include "envoy/ssl/context_config.h"
#include "envoy/ssl/private_key/private_key.h"
#include "envoy/stats/scope.h"

namespace Envoy {
namespace Ssl {

/**
 * Manages all of the SSL contexts in the process
 */
class ContextManager {
public:
  virtual ~ContextManager() = default;

  /**
   * Builds a ClientContext from a ClientContextConfig.
   */
  virtual ClientContextSharedPtr createSslClientContext(Stats::Scope& scope,
                                                        const ClientContextConfig& config) PURE;

  /**
   * Builds a ServerContext from a ServerContextConfig.
   */
  virtual ServerContextSharedPtr
  createSslServerContext(Stats::Scope& scope, const ServerContextConfig& config,
                         const std::vector<std::string>& server_names) PURE;

  /**
   * @return the number of days until the next certificate being managed will expire.
   */
  virtual size_t daysUntilFirstCertExpires() const PURE;

  /**
   * Iterate through all currently allocated contexts.
   */
  virtual void iterateContexts(std::function<void(const Context&)> callback) PURE;

  /**
   * Access the private key operations manager, which is part of SSL
   * context manager.
   */
  virtual PrivateKeyMethodManager& privateKeyMethodManager() PURE;

  /**
   * @return the number of seconds until the next OCSP response being managed will
   * expire, or `absl::nullopt` if no OCSP responses exist.
   */
  virtual absl::optional<uint64_t> secondsUntilFirstOcspResponseExpires() const PURE;
};

using ContextManagerPtr = std::unique_ptr<ContextManager>;

class ContextManagerFactory : public Config::UntypedFactory {
public:
  ~ContextManagerFactory() override = default;
  virtual ContextManagerPtr createContextManager(TimeSource& time_source) PURE;

  // There could be only one factory thus the name is static.
  std::string name() const override { return "ssl_context_manager"; }
  std::string category() const override { return "envoy.ssl_context_manager"; }
};

} // namespace Ssl
} // namespace Envoy


text:
TabActivity
======================

Library allowing to use Activity with TabLayout (support:design) and nested Fragments with tab's own stack.
For the fragments it is possible to handle their lifecycle like usual fragment.

Brief
----------

Use this library If your goal is to implement tabs navigation (iOS style),
when each tab has its own collection of Fragments with its own back stack.
Some time ago there was quite effective class [TabActivity](http://developer.android.com/reference/android/app/TabActivity.html),
but now it is deprecated.

How to use
----------

Main Tab activity should extend BaseTabActivity with several abstract methods.

If you want to add new "level" in current tab - use Fragment extended BaseTabFragment.

If you have fragments inside BaseTabFragment (like ViewPager) you should extend BaseTabChildFragment in conjunction with getChildFragmentManager

All fragments added to FragmentManager using _#add_ method (not _#replace_). It means that fragment's lifecycle methods won't be called in the way you expected in this Tab model.
E.g. When new fragment added in tab the previous one won't receive any event like onPause or onStop.
Because of that fact there are special methods that will be called in the "right" way.

```java

    public void onTabStarted()
    public void onTabResumed()
    public void onTabPaused()
    public void onTabStopped()

```

Taking example above when new fragment is added on top of the tab's stack
methods _#onTabStarted()_ _#onTabResumed()_ will be called on new Fragment and _#onTabPaused()_ _#onTabStopped()_ on previous top Fragment.
Therefore it is the best place to put logic for saving / restoring content of fragments (in order to increase performance of the app)
similar as you do it in usual Fragment's lifecycle methods.

For better experience you should add android:launchMode="singleTask" to your Main Tab Activity,
in order to correctly handling deep linking and better user experience.

How it works
-----------------------

The benefit of library that it allows restoring and handling each fragments' stack using FragmentManager (it doesn't store Fragments' instances anywhere).

TabFragmentManager is the entry point for handling back stack, saving / restoring tabs, managing lifecycle of fragments.

Sample
------

Contains main parts of the library. It is quite understandable and can be used as manual for library.

Notes
-----

Developer is responsible for correct usage of memory and user experience (start, resume / pause, stop worker threads, services, tasks, free up memory, etc.)

In generally you used _onStart_, _onResume_,... methods and now you should use _onTabStarted_, _onTabResumed_,... instead.

LICENSE
-------

The Apache Software License, Version 2.0

http://www.apache.org/licenses/


text:
using namespace gpos;

//---------------------------------------------------------------------------
//	@function:
//		CMessageTest::EresUnittest
//
//	@doc:
//		Function for raising assert exceptions; again, encapsulated in a function
//		to facilitate debugging
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMessageTest::EresUnittest()
{
	CUnittest rgut[] =
		{
		GPOS_UNITTEST_FUNC(CMessageTest::EresUnittest_BasicWrapper),
		};

	return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut));
}

//---------------------------------------------------------------------------
//	@function:
//		CMessageTest::EresUnittest_BasicWrapper
//
//	@doc:
//		Wrapper around basic test to provide va_list arguments
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMessageTest::EresUnittest_BasicWrapper()
{
	// create memory pool of 128KB
	CAutoMemoryPool amp;
	CMemoryPool *mp = amp.Pmp();

	return EresUnittest_Basic(mp,
				// parameters to Assert message
				__FILE__, __LINE__, GPOS_WSZ_LIT("!true"));
}

//---------------------------------------------------------------------------
//	@function:
//		CMessageTest::EresUnittest_Basic
//
//	@doc:
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMessageTest::EresUnittest_Basic
	(
	const void *pv,
	...
	)
{
	const ULONG size = 2048;

	CMemoryPool *mp = (CMemoryPool*)pv;

	// take pre-defined assertion exc message
	CMessage *pmsg = CMessage::GetMessage(CException::ExmiAssert);

	GPOS_ASSERT(GPOS_MATCH_EX(pmsg->m_exception,
							  CException::ExmaSystem,
							  CException::ExmiAssert));

	// target buffer for format test
	WCHAR *wsz = GPOS_NEW_ARRAY(mp, WCHAR, size);
	CWStringStatic wss(wsz, size);

	VA_LIST vl;
	VA_START(vl, pv);

	// manufacture an OOM message (no additional parameters)
	pmsg->Format(&wss, vl);

	VA_END(vl);

	GPOS_TRACE(wsz);

	GPOS_DELETE_ARRAY(wsz);

	return GPOS_OK;
}

// EOF


text:
package gcm

import (
	"bytes"
	"reflect"
	"runtime"
	"time"
)

var managed map[string]*goroutine

// package initializer.
func init() {
	managed = make(map[string]*goroutine, maxCapacity)
	go statusMonitor()
}

// goroutine status monitor.
func statusMonitor() {
	for {
		for _, v := range managed {
			if len(v.contexts) == 0 {
				v.status = Stopped
			}
		}
		<-time.After(time.Second * 3)
	}
}

// Register
//
//   [args]
//     gofunc : function object, that is run as goroutine.
//
//   [returns]
//     string : unique name of 'gofunc' in the gcm package.
//              you can use this name for 'gofunc' argument for other functions.
//              e.g. UnRegister, Start, ChangeMultiplicity, Stop, GetStatus, GetMultiplicity.
//     error  : if gofunc already registered, return ErrFuncExists
func Register(gofunc interface{}) (string, error) {
	name := getUniqueName(gofunc)
	_, exists := managed[name]
	if exists {
		return name, ErrFuncExists
	}
	managed[name] = &goroutine{
		reflect.ValueOf(gofunc),
		nil,
		0,
		make([]interface{}, maxMultiplicity),
		Stopped}
	return name, nil
}

// UnRegister
//
//   [args]
//     gofunc : function object or function name, that was returned by Register function.
//
//   [returns]
//     error  : if gofunc is not Register, return ErrFuncNotExists
func UnRegister(gofunc interface{}) error {
	name := getUniqueName(gofunc)
	_, exists := managed[name]
	if !exists {
		return ErrFuncNotExists
	}
	delete(managed, name)
	return nil
}

//
func Start(gofunc interface{}, m int, args ...interface{}) error {
	return nil
}

//
func ChangeMultiplicity(gofunc interface{}, m int) error {
	return nil
}

//
func Stop(gofunc interface{}, async bool) error {
	return nil
}

func GetStatus(gofunc interface{}) (Status, error) {
	return Stopped, nil
}

func GetMultiplicity(gofunc interface{}) (int, error) {
	return 0, nil
}

// get unique name of function.
// function name format = <package_name>.<function_name>:'<function_type_name>'
func getUniqueName(gofunc interface{}) string {
	switch gofunc.(type) {
	case string:
		return gofunc.(string)
	default:
		v := reflect.ValueOf(gofunc)
		buf := &bytes.Buffer{}
		buf.WriteString(runtime.FuncForPC(v.Pointer()).Name())
		buf.WriteString(":'")
		buf.WriteString(v.Type().Name())
		buf.WriteString("'")
		return buf.String()
	}
}

type goroutine struct {
	gofunc       reflect.Value
	args         []interface{}
	multiplicity int
	contexts     []interface{}
	status       Status
}

func (g *goroutine) start() error {
	switch g.status {
	case Running:
		return nil
	case Stopping:
		return nil // TODO new error
	}
	for i := 0; i < g.multiplicity; i++ {
		// TODO impl context
		ctx := struct{}{}
		go g.gofunc.Call(getValues(ctx, g.args...))
		g.contexts[i] = ctx
	}
	g.status = Running
	return nil
}

func (g *goroutine) changeMultiplicity(m int) error {
	cur := g.multiplicity
	if m > cur {
		// increase goroutine
		for i := cur; i < m; i++ {
			// TODO impl context
			ctx := struct{}{}
			go g.gofunc.Call(getValues(ctx, g.args...))
			g.contexts[i] = ctx
		}
	} else if m < cur {
		// decrease goroutine
		for i := m; i < cur; i++ {
			ctx := g.contexts[i]
			if ctx != nil {
				// TODO call ctx.Cancel(cancelCallbackFunc)
				// func() {
				// 	   g.contexts[i] = nil
				// }()
			}
		}
	}
	g.multiplicity = m
	return nil
}

func (g *goroutine) stop(async bool) error {
	switch g.status {
	case Stopping:
		return nil
	case Stopped:
		return nil
	}
	for i := 0; i < maxMultiplicity; i++ {
		ctx := g.contexts[i]
		if ctx != nil {
			// TODO call ctx.Cancel(cancelCallbackFunc)
			// func() {
			// 	   g.contexts[i] = nil
			// }()
		}
	}
	g.status = Stopping
	return nil
}

func getValues(ctx interface{}, args ...interface{}) []reflect.Value {
	values := make([]reflect.Value, len(args)+1)
	values[0] = reflect.ValueOf(ctx)
	for i := 1; i < len(values); i++ {
		values[i] = reflect.ValueOf(args[i-1])
	}
	return values
}

// EOF


text:
// =========================================================================== //
//                                                                             //
// Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty,                    //
//   Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed,   //
//   Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger,        //
//   Laurie Hendren, Clark Verbrugge and McGill University.                    //
//                                                                             //
//   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 natlab;

import java.util.List;

import com.google.common.base.Joiner;

/**
 * Describes the position and nature of a problem encountered while compiling
 * source. This can include matlab to natlab translation problems, parsing
 * problems, and general compilation problems
 */

public class CompilationProblem {
  private final boolean located;
  private final int line;
  private final int col;
  private final String msg;

  public CompilationProblem(int line, int col, String msg) {
    this.line = line;
    this.col = col;
    this.msg = msg;
    this.located = true;
  }

  public CompilationProblem(String msg) {
    this.line = -1;
    this.col = -1;
    this.msg = msg;
    this.located = false;
  }

  public CompilationProblem(String format, Object... args) {
    this(String.format(format, args));
  }

  public boolean hasLocation() {
    return located;
  }

  public int getLine() {
    return line;
  }

  public int getColumn() {
    return col;
  }

  public String getMessage() {
    return msg;
  }

  public String toString() {
    if (located) {
      return String.format("[%d, %d] %s", line, col, msg);
    }
    return msg;
  }

  public static String toStringAll(List<CompilationProblem> errors) {
    return Joiner.on('\n').join(errors);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Web.WebPages.OAuth;
using PaymillWrapper.Models;

namespace PaymillWrapper
{
    public static class AuthConfig
    {
        public static void RegisterAuth()
        {
            // Para permitir que los usuarios de este sitio inicien sesión con sus cuentas de otros sitios como, por ejemplo, Microsoft, Facebook y Twitter,
            // es necesario actualizar este sitio. Para obtener más información, visite http://go.microsoft.com/fwlink/?LinkID=252166

            //OAuthWebSecurity.RegisterMicrosoftClient(
            //    clientId: "",
            //    clientSecret: "");

            //OAuthWebSecurity.RegisterTwitterClient(
            //    consumerKey: "",
            //    consumerSecret: "");

            //OAuthWebSecurity.RegisterFacebookClient(
            //    appId: "",
            //    appSecret: "");

            //OAuthWebSecurity.RegisterGoogleClient();
        }
    }
}


text:
from __future__ import absolute_import, division, print_function

import unittest

import numpy as np
import datashape
import blaze
from blaze.datadescriptor import dd_as_py
from blaze.tests.common import MayBeUriTest
from blaze import append

from blaze.py2help import skip

class TestEphemeral(unittest.TestCase):
    def test_create_scalar(self):
        a = blaze.array(True)
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('bool'))
        self.assertEqual(bool(a), True)
        a = blaze.array(-123456)
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('int32'))
        self.assertEqual(int(a), -123456)
        a = blaze.array(-1.25e-10)
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('float64'))
        self.assertEqual(float(a), -1.25e-10)
        a = blaze.array(-1.25e-10+2.5j)
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('complex[float64]'))
        self.assertEqual(complex(a), -1.25e-10+2.5j)

    def test_create_from_numpy(self):
        a = blaze.array(np.arange(3))
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [0, 1, 2])

    def test_create(self):
        # A default array (backed by NumPy)
        a = blaze.array([1,2,3])
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [1, 2, 3])

    def test_create_append(self):
        # A default array (backed by NumPy, append not supported yet)
        a = blaze.array([])
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertRaises(ValueError, append, a, [1,2,3])
        # XXX The tests below still do not work
        # self.assertEqual(a[0], 1)
        # self.assertEqual(a[1], 2)
        # self.assertEqual(a[2], 3)

    def test_create_compress(self):
        # A compressed array (backed by BLZ)
        a = blaze.array(np.arange(1,4), caps={'compress': True})
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [1, 2, 3])
        # XXX The tests below still do not work
        # self.assertEqual(a[0], 1)
        # self.assertEqual(a[1], 2)
        # self.assertEqual(a[2], 3)

    def test_create_iter(self):
        # A simple 1D array
        a = blaze.array(i for i in range(10))
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('10, int32'))
        self.assertEqual(dd_as_py(a._data), list(range(10)))
        # A nested iter
        a = blaze.array((i for i in range(x)) for x in range(5))
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('5, var, int32'))
        self.assertEqual(dd_as_py(a._data),
                         [[i for i in range(x)] for x in range(5)])
        # A list of iter
        a = blaze.array([range(3), (1.5*x for x in range(4)), iter([-1, 1])])
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(a.dshape, datashape.dshape('3, var, float64'))
        self.assertEqual(dd_as_py(a._data),
                         [list(range(3)),
                          [1.5*x for x in range(4)],
                          [-1, 1]])

    def test_create_compress_iter(self):
        # A compressed array (backed by BLZ)
        a = blaze.array((i for i in range(10)), caps={'compress': True})
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), list(range(10)))

    def test_create_zeros(self):
        # A default array
        a = blaze.zeros('10, int64')
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [0]*10)

    def test_create_compress_zeros(self):
        # A compressed array (backed by BLZ)
        a = blaze.zeros('10, int64', caps={'compress': True})
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [0]*10)

    def test_create_ones(self):
        # A default array
        a = blaze.ones('10, int64')
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [1]*10)

    def test_create_compress_ones(self):
        # A compressed array (backed by BLZ)
        a = blaze.ones('10, int64', caps={'compress': True})
        self.assertTrue(isinstance(a, blaze.Array))
        self.assertEqual(dd_as_py(a._data), [1]*10)

    def test_create_record(self):
        # A simple record array
        a = blaze.array([(10, 3.5), (15, 2.25)],
                        dshape="var, {val: int32; flt: float32}")
        self.assertEqual(dd_as_py(a._data), [{'val': 10, 'flt': 3.5},
                        {'val': 15, 'flt': 2.25}])
        # Test field access via attributes
        aval = a.val
        self.assertEqual(dd_as_py(aval._data), [10, 15])
        aflt = a.flt
        self.assertEqual(dd_as_py(aflt._data), [3.5, 2.25])

class TestPersistent(MayBeUriTest, unittest.TestCase):

    uri = True

    def test_create(self):
        persist = blaze.Storage(self.rooturi, format="blz")
        a = blaze.array([], 'float64', storage=persist)
        self.assertTrue(isinstance(a, blaze.Array))
        print("->", a.dshape.shape)
        self.assertTrue(a.dshape.shape == (0,))
        self.assertEqual(dd_as_py(a._data), [])

    def test_append(self):
        persist = blaze.Storage(self.rooturi, format="blz")
        a = blaze.zeros('0, float64', storage=persist)
        self.assertTrue(isinstance(a, blaze.Array))
        append(a,list(range(10)))
        self.assertEqual(dd_as_py(a._data), list(range(10)))

    # Using a 1-dim as the internal dimension
    def test_append2(self):
        persist = blaze.Storage(self.rooturi, format="blz")
        a = blaze.empty('0, 2, float64', storage=persist)
        self.assertTrue(isinstance(a, blaze.Array))
        lvals = [[i,i*2] for i in range(10)]
        append(a,lvals)
        self.assertEqual(dd_as_py(a._data), lvals)

    def test_open(self):
        persist = blaze.Storage(self.rooturi, format="blz")
        a = blaze.ones('0, float64', storage=persist)
        append(a,range(10))
        # Re-open the dataset in URI
        a2 = blaze.open(persist)
        self.assertTrue(isinstance(a2, blaze.Array))
        self.assertEqual(dd_as_py(a2._data), list(range(10)))

if __name__ == '__main__':
    unittest.main(verbosity=2)


text:
class Article
  include Mongoid::Document
  field :name
  field :content
  field :published_on, :type => Date
  validates_presence_of :name
  embeds_many :comments
  referenced_in :author
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Inclusion (xmlserializer4j 1.0 API)</title>
<meta name="date" content="2016-05-29">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

org.xmlserializer4j.annotation

Enum Inclusion

java.lang.Object

java.lang.Enum<Inclusion>

org.xmlserializer4j.annotation.Inclusion

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<Inclusion>

public enum Inclusion
extends java.lang.Enum<Inclusion>

Enumeration for inclusion of Java fields in XML for use with the XMLInclude annotation.

Enum Constant Summary

Enum Constants

Enum Constant and Description

ALWAYS

Always include this field/type even if null.

NEVER

Never include this field/type.

NON_NULL

Only include this field/type when not null.

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static Inclusion
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static Inclusion[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

ALWAYS

public static final Inclusion ALWAYS

Always include this field/type even if null.

NON_NULL

public static final Inclusion NON_NULL

Only include this field/type when not null.

NEVER

public static final Inclusion NEVER

Never include this field/type.

Method Detail

values

public static Inclusion[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (Inclusion c : Inclusion.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static Inclusion valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/allpass_wechat_sel" />
    <item android:drawable="@drawable/allpass_wechat" />

</selector>


text:
#include "BoxTest.h"

#include "shapes/Box.h"
#include "items/Text.h"

namespace Visualization {

ITEM_COMMON_DEFINITIONS(BoxTest, "item")

BoxTest::BoxTest(Item* parent, int sub) :
Super(parent), items(this)
{
	setFlag(QGraphicsItem::ItemIsMovable);
//	style.setMargins(4);
//	style.setSpaceBetweenElements(3);
//	style.setAlignment(SequentialLayoutStyle::Alignment::Center);
//	style.setDirection(SequentialLayoutStyle::LeftToRight);
//
//	boxStyle.setCorner(BoxStyle::RoundCorner, 10);
//	boxStyle.setOutline(QPen(QBrush(QColor(0x00, 0x00, 0xFF)), 1));
//	boxStyle.setShadow(QBrush(QColor(0xFF, 0xAA, 0xAA)), 2, 1, false);
//	setShapeStyle(&boxStyle);

	for (int i = 0; i < sub; ++i)
		items.append(new BoxTest(&items, sub - 1 - i));

	if (sub == 0)
	{
		items.append(new Text(&items, "Test"));
	}
}

void BoxTest::determineChildren()
{
}

void BoxTest::updateGeometry(int, int)
{
	getShape()->setInnerSize(items.widthInParent(), items.heightInParent());
	items.setPos(getShape()->contentLeft(), getShape()->contentTop());
}

}


text:
package DP_Disambiguation_FeatureBuilding;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import DP_Disambiguation_DumpHandler.DBpediaType;
import DP_Disambiguation_DumpHandler.Dictionary;
import DP_Disambiguation_DumpHandler.ID;
import DP_Disambiguation_DumpHandler.Printer;
import DP_Disambiguation_DumpHandler.Tuple;

public class DBPediaFetcher {

	public DBPediaFetcher(HashMap<String, DBpediaType> dBpediaTypes) {
		super();
		DBpediaTypes = dBpediaTypes;
	}

	private HashMap <String,DBpediaType> DBpediaTypes;

	public void updateEntities (Dictionary anchorLinks,String DBPediaDumpPath) throws IOException
		{
			BufferedReader br = new BufferedReader(new FileReader(DBPediaDumpPath));
			String currentLine = null;
			DBpediaType dBpediaTypeObject = null;

			HashMap <String, ID> IDs = anchorLinks.getIDs();

			Printer.print("Updateing DBpedia Types", "");

			while ((currentLine = br.readLine()) != null)
			{
				Tuple <String,String > tuple = fetchData (currentLine);
				String wikiID = tuple.getFirst();
				String fetchedType = tuple.getSecond();
				ID wikiEntity = null;

				if ((wikiEntity = IDs.get(wikiID)) != null)
				{
						//Printer.print("Updateing entity " + wikiID, "adding DBpedia type" + fetchedType);

					 	if (DBpediaTypes.containsKey(fetchedType))
				    	  dBpediaTypeObject = DBpediaTypes.get(fetchedType);
					 	else
					 	{
				    	  dBpediaTypeObject = new DBpediaType(fetchedType);
					 	  DBpediaTypes.put(fetchedType, dBpediaTypeObject);
					 	}

						if (!wikiEntity.getDBpediaTypes().contains(dBpediaTypeObject))
						{
							wikiEntity.addDBpediaType(dBpediaTypeObject);
						}

				}

			}
		}

	private Tuple<String , String> fetchData (String currentLine)
	{
		// Create a Pattern object
		  String  entityID = null;
		  String  dBpediaType = null;
		  int patternFound = 0;
		  String pattern = "([^\\/ #]+)>";
	      Pattern r = Pattern.compile(pattern);

	      // Now create matcher object.
	      Matcher m = r.matcher(currentLine);

	      while (m.find( )) {

	    	  patternFound++;

	    	  if (patternFound == 1)
	    	  {
		    	 entityID = m.group(1);

		    	 if (entityID.startsWith(" "))
		    		 entityID = entityID.substring(1);
		    	 entityID = entityID.replace(' ', '_');
		    	 entityID = entityID.toLowerCase();
	    	  }

	    	  if (patternFound == 3)
	    	  {
		    	 dBpediaType =  m.group(1);
		    	 if (dBpediaType.startsWith(" "))
		    		 dBpediaType = entityID.substring(1);
		    	 dBpediaType = dBpediaType.replace(' ', '_');
		    	 dBpediaType = dBpediaType.replace(':', '_');
		    	 dBpediaType = dBpediaType.toLowerCase();
	    	  }
	      }

		return new Tuple <String,String> (entityID,dBpediaType);
	}
}


text:
/*!
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 */

/**
 * AngularJS service that handles the popover query parameter for Piwik's angular code.
 *
 * If the popover parameter's first part is the name of an existing AngularJS directive,
 * a dialog is created using ngDialog with the contents being an element with that directive.
 * The other parts of the parameter are treated as attributes for the element, eg,
 * `"mydirective:myparam=val:myotherparam=val2"`.
 *
 * It should not be necessary to use this service directly, instead the piwik-dialogtoggler
 * directive should be used.
 *
 * TODO: popover as a query parameter refers less to dialogs and more to any popup window
 *       (ie, not necessarily modal). should replace it w/ 'dialog' or maybe 'modal'.
 */
angular.module('piwikApp').factory('piwikDialogtogglerUrllistener', function ($rootScope, $location, $injector, $rootElement, ngDialog) {
    var service = {},
        dialogQueryParamName = 'popover';

    function getHtmlFromDialogQueryParam(paramValue) {
        var info = paramValue.split(':'),
            directiveName = info.shift(),
            dialogContent = '';

        dialogContent += '<div ' + directiveName;
        angular.forEach(info, function (argumentAssignment) {
            var pair = argumentAssignment.split('='),
                key = pair[0],
                value = pair[1];
            dialogContent += ' ' + key + '="' + decodeURIComponent(value) + '"';
        });
        dialogContent += '/>';

        return dialogContent;
    }

    function directiveExists(directiveAttributeString) {
        // NOTE: directiveNormalize is not exposed by angularjs and the devs don't seem to want to expose it:
        //       https://github.com/angular/angular.js/issues/7955
        //       so logic is duplicated here.
        var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i,
            directiveName = angular.element.camelCase(directiveAttributeString.replace(PREFIX_REGEXP, ''));

        return $injector.has(directiveName + 'Directive');
    }

    service.checkUrlForDialog = function () {
        var dialogParamValue = $location.search()[dialogQueryParamName];
        if (dialogParamValue && directiveExists(dialogParamValue)) {
            var dialog = ngDialog.open({
                template: getHtmlFromDialogQueryParam(dialogParamValue),
                plain: true,
                className: ''
            });

            dialog.closePromise.then(function () {
                $location.search(dialogQueryParamName, null);
            });
        }
    };

    service.propagatePersistedDialog = function (directive, attributes) {
        var paramValue = directive;
        angular.forEach(attributes, function (value, name) {
            paramValue += ':' + name + '=' + encodeURIComponent(value);
        });

        $location.search(dialogQueryParamName, paramValue);
    };

    $rootScope.$on('$locationChangeSuccess', function () {
        service.checkUrlForDialog();
    });

    return service;
});


text:
@import "../colors.css";

.container {
  width: 55px;
  height: 55px;
  background-color: var(--color-background);
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: none;
  position: relative;
  overflow: hidden;
}

.container:first-child {
  margin-top: 10px;
}

.container:hover {
  background-color: var(--color-primary);
}

.active {
  composes: container;
  background-color: var(--color-primary);
}

.tooltip {
  & > div > :first-child {
    border-right-color: var(--color-primary);
  }
  & > div > :nth-child(2) {
    background-color: var(--color-primary);
    min-height: inherit;
  }
}


text:
[![Build Status](https://travis-ci.org/jiangyu7408/sharding-preemption.svg?style=flat-square)](https://travis-ci.org/jiangyu7408/sharding-preemption)
[![GitHub license](https://img.shields.io/github/license/mashape/apistatus.svg?style=flat-square)](https://github.com/jiangyu7408/sharding-preemption)
[![Packagist Version](https://img.shields.io/packagist/v/jiangyu/sharding-preemption.svg?style=flat-square)](https://packagist.org/packages/jiangyu/sharding-preemption)
[![Total Downloads](https://img.shields.io/packagist/dt/jiangyu/sharding-preemption.svg?style=flat-square)](https://packagist.org/packages/jiangyu/sharding-preemption)
[![Code Climate](https://codeclimate.com/repos/566514d8c92a3c3880000919/badges/dd9269505f16881f8df0/gpa.svg?style=flat-square)](https://codeclimate.com/repos/566514d8c92a3c3880000919/feed)
[![Test Coverage](https://codeclimate.com/repos/566514d8c92a3c3880000919/badges/dd9269505f16881f8df0/coverage.svg)](https://codeclimate.com/repos/566514d8c92a3c3880000919/coverage)

# ShardingPreemption
A micro shard preemption framework.

Suppose you have 100 shards, and you have 10 workers to handle all these shards, so each of the workers can handle 10 shards, and each shard can only be handled by 1 worker.

By splitting all 100 shards to 10 slices, and fire 10 workers at the same time, each worker try to occupy a slice, they can take over all those shards finally.

If workers are not working on 1 machine, then some DLM(Distributed Lock Manager)solutions can be imported to reach that goal.

```
$options = getopt('', ['worker:']);

$workerCount = isset($options['worker']) ? (int) $options['worker'] : 2;

$allShardSetting = [
    'db1' => [
        'host' => '127.0.0.1',
        'port' => '3306',
        'username' => 'hello',
        'password' => 'world',
        'database' => 'db1',
    ],
    'db2' => [
        'host' => '127.0.0.1',
        'port' => '3307',
        'username' => 'hello',
        'password' => 'world',
        'database' => 'db2',
    ],
    'db3' => [
        'host' => '127.0.0.1',
        'port' => '3308',
        'username' => 'hello',
        'password' => 'world',
        'database' => 'db3',
    ],
];

$skeleton = new PollMySQLOnSingleMachine($allShardSetting, function (ResourceCollection $slice) {
    $sliceHash = $slice->getHashValue();
    $pid = posix_getpid();
    dump($pid.' acquired ownership on slice['.$sliceHash.'] =>');
    dump($slice->getDigestion());

    dump($pid.' working');
    sleep(5);

    dump($pid.' job done, quit');
});

$skeleton->setWorkerCount($workerCount);
$skeleton->poll();

```


text:
package ucar.nc2.dt.point;

import ucar.nc2.dt.*;
import ucar.nc2.units.DateUnit;
import ucar.nc2.units.SimpleUnit;
import ucar.nc2.units.DateFormatter;
import ucar.nc2.Variable;
import ucar.nc2.constants.FeatureType;
import ucar.nc2.dataset.NetcdfDataset;
import ucar.nc2.util.CancelTask;
import ucar.ma2.StructureData;
import ucar.ma2.DataType;
import java.util.List;
import java.util.Date;
import java.io.IOException;
import java.text.ParseException;

/**
 * Superclass for implementations of PointObsDataset.
 *
 *
 * @deprecated use ucar.nc2.ft.point
 * @author caron
 */

public abstract class PointObsDatasetImpl extends TypedDatasetImpl implements PointObsDataset {

  /**
   * Get conversion factor for this unit into meters.
   *
   * @param unitsString unit you want to convert
   * @return conversion factor : value in meters = factor * (value in units)
   * @throws Exception if not valid unit, or not convertible to meters
   */
  protected static double getMetersConversionFactor(String unitsString) throws Exception {
    SimpleUnit unit = SimpleUnit.factoryWithExceptions(unitsString);
    return unit.convertTo(1.0, SimpleUnit.meterUnit);
  }

  protected DateUnit timeUnit;

  public PointObsDatasetImpl() {
    super();
  }

  public PointObsDatasetImpl(String title, String description, String location) {
    super(title, description, location);
  }

  public PointObsDatasetImpl(NetcdfDataset ncfile) {
    super(ncfile);
  }

  protected abstract void setTimeUnits(); // reminder for subclasses to set this

  /////////////////////////////////

  public String getDetailInfo() {
    StringBuffer sbuff = new StringBuffer();
    sbuff.append("PointObsDataset\n");
    sbuff.append("  adapter   = ").append(getClass().getName()).append("\n");
    sbuff.append("  timeUnit  = ").append(getTimeUnits()).append("\n");
    sbuff.append("  dataClass = ").append(getDataClass()).append("\n");
    sbuff.append("  dataCount = ").append(getDataCount()).append("\n");
    sbuff.append(super.getDetailInfo());

    return sbuff.toString();
  }

  public FeatureType getScientificDataType() {
    return FeatureType.POINT;
  }

  public Class getDataClass() {
    return PointObsDatatype.class;
  }

  public DateUnit getTimeUnits() {
    return timeUnit;
  }

  public List getData() throws IOException {
    return getData((CancelTask) null);
  }

  public List getData(ucar.unidata.geoloc.LatLonRect boundingBox) throws IOException {
    return getData(boundingBox, null);
  }

  public List getData(ucar.unidata.geoloc.LatLonRect boundingBox, Date start, Date end) throws IOException {
    return getData(boundingBox, start, end, null);
  }

  protected DateFormatter formatter;

  protected double getTime(Variable timeVar, StructureData sdata) throws ParseException {
    if (timeVar == null)
      return 0.0;

    if ((timeVar.getDataType() == DataType.CHAR) || (timeVar.getDataType() == DataType.STRING)) {
      String time = sdata.getScalarString(timeVar.getShortName());
      if (null == formatter)
        formatter = new DateFormatter();
      Date date = formatter.getISODate(time);
      return date.getTime() / 1000.0;
    } else {
      return sdata.convertScalarFloat(timeVar.getShortName());
    }
  }

}


text:
package com.github.dm.jrt.stream;

import com.github.dm.jrt.core.JRoutineCore;
import com.github.dm.jrt.core.channel.Channel;
import com.github.dm.jrt.core.channel.ChannelConsumer;
import com.github.dm.jrt.core.common.RoutineException;
import com.github.dm.jrt.core.config.ChannelConfiguration;
import com.github.dm.jrt.core.util.ConstantConditions;
import com.github.dm.jrt.function.Function;

import org.jetbrains.annotations.NotNull;

/**
 * Mapping binding function.
 * <p>
 * Created by davide-maestroni on 09/11/2016.
 *
 * @param <IN>  the input data type.
 * @param <OUT> the output data type.
 */
class BindMappingFunction<IN, OUT> implements Function<Channel<?, IN>, Channel<?, OUT>> {

  private final ChannelConfiguration mConfiguration;

  private final Function<? super IN, ? extends OUT> mMappingFunction;

  /**
   * Constructor.
   *
   * @param configuration   the channel configuration.
   * @param mappingFunction the mapping function.
   */
  BindMappingFunction(@NotNull final ChannelConfiguration configuration,
      @NotNull final Function<? super IN, ? extends OUT> mappingFunction) {
    mConfiguration = ConstantConditions.notNull("channel configuration", configuration);
    mMappingFunction = ConstantConditions.notNull("function instance", mappingFunction);
  }

  public Channel<?, OUT> apply(final Channel<?, IN> channel) {
    final Channel<OUT, OUT> outputChannel = JRoutineCore.io().apply(mConfiguration).buildChannel();
    channel.bind(new MappingFunctionConsumer<IN, OUT>(mMappingFunction, outputChannel));
    return outputChannel;
  }

  /**
   * Channel consumer implementation.
   *
   * @param <IN>  the input data type.
   * @param <OUT> the output data type.
   */
  private static class MappingFunctionConsumer<IN, OUT> implements ChannelConsumer<IN> {

    private final Function<? super IN, ? extends OUT> mMappingFunction;

    private final Channel<OUT, ?> mOutputChannel;

    /**
     * Constructor.
     *
     * @param mappingFunction the mapping function.
     * @param outputChannel   the output channel.
     */
    private MappingFunctionConsumer(
        @NotNull final Function<? super IN, ? extends OUT> mappingFunction,
        @NotNull final Channel<OUT, ?> outputChannel) {
      mMappingFunction = mappingFunction;
      mOutputChannel = outputChannel;
    }

    public void onComplete() {
      mOutputChannel.close();
    }

    public void onError(@NotNull final RoutineException error) {
      mOutputChannel.abort(error);
    }

    public void onOutput(final IN output) throws Exception {
      mOutputChannel.pass(mMappingFunction.apply(output));
    }
  }
}


text:
/*
 * File:   interrupt_handler.h
 * Author: Igor
 *
 * Created on March 28, 2015, 11:36 AM
 */

#ifndef INTERRUPT_HANDLER_H
#define	INTERRUPT_HANDLER_H
bool PrepSend;
volatile unsigned int LEDtime = 0, talkTime = 0;
void __attribute__((interrupt, no_auto_psv)) _T2Interrupt(void);
void __attribute__((interrupt, no_auto_psv)) _T1Interrupt(void);
#endif	/* INTERRUPT_HANDLER_H */


text:
var imagemin = require('imagemin');
var imageminWebp = require('imagemin-webp');
var loaderUtils = require('loader-utils');

module.exports = function (content) {
  this.cacheable && this.cacheable();

  var query = loaderUtils.getOptions(this) || {};
  var configKey = query.config || 'webpLoader';
  var options = this.options && this.options[configKey] || {};
  var config = Object.assign({}, options, query);

  var callback = this.async();

  if (this.debug === true && config.bypassOnDebug === true) {
    return callback(null, content);
  } else {
    imagemin
      .buffer(content,{
        plugins: [imageminWebp(config)]
      })
      .then(function(data){
        callback(null, data);
      })
      .catch(function(err){
        callback(err);
      });
  }
};

module.exports.raw = true;


text:
<?php

namespace Data\Model;

use Zend\Form\Annotation;

/**
 * @Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
 * @Annotation\Name("delivery-method")
 */
class DeliveryMethod
{
    /**
     * @Annotation\Type("Zend\Form\Element\Hidden")
     * @Annotation\Attributes({"type":"integer"})
     */
    public $id;

    /**
     * @Annotation\Type("Zend\Form\Element\Text")
     * @Annotation\Required({"required":"true" })
     * @Annotation\Filter({"name":"StripTags"})
     * @Annotation\Validator({"name":"StringLength", "options":{"min":"1"}})
     * @Annotation\Options({"label":"Название: "})
     * @Annotation\Attributes({"class":"form-control","placeholder":"Название"})
     * @Annotation\Filter({"name":"StringTrim"})
     */
    public $name;

    /**
     * @Annotation\Type("Zend\Form\Element\Submit")
     * @Annotation\Attributes({"value":"Submit"})
     * @Annotation\Attributes({"class":"btn btn-success"})
     */
    public $submit;
}


text:
#ifndef __LINUX_CACHE_H
#define __LINUX_CACHE_H
#include <linux/kernel.h>
#include <asm/cache.h>
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#ifndef L1_CACHE_ALIGN
#define L1_CACHE_ALIGN(x) ALIGN(x, L1_CACHE_BYTES)
#endif
#ifndef SMP_CACHE_BYTES
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define SMP_CACHE_BYTES L1_CACHE_BYTES
#endif
#ifndef __read_mostly
#define __read_mostly
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#endif
#ifndef ____cacheline_aligned
#define ____cacheline_aligned __attribute__((__aligned__(SMP_CACHE_BYTES)))
#endif
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#ifndef ____cacheline_aligned_in_smp
#define ____cacheline_aligned_in_smp
#endif
#ifndef __cacheline_aligned
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define __cacheline_aligned   __attribute__((__aligned__(SMP_CACHE_BYTES),   __section__(".data.cacheline_aligned")))
#endif
#ifndef __cacheline_aligned_in_smp
#define __cacheline_aligned_in_smp
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#endif
#ifndef INTERNODE_CACHE_SHIFT
#define INTERNODE_CACHE_SHIFT L1_CACHE_SHIFT
#endif
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#ifndef ____cacheline_internodealigned_in_smp
#define ____cacheline_internodealigned_in_smp
#endif
#endif
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */


text:
using System;

namespace ApiScanner.Entities.Models
{
    public class ApiLocationModel
    {
        /// <summary>
        /// Id of api.
        /// </summary>
        public Guid ApiId { get; set; }

        /// <summary>
        /// Id of location.
        /// </summary>
        public Guid LocationId { get; set; }

        /// <summary>
        /// Api.
        /// </summary>
        public ApiModel Api { get; set; }

        /// <summary>
        /// Location.
        /// </summary>
        public LocationModel Location { get; set; }
    }
}


text:
package com.sogrey.frame.views.PhotoExpolor.utils;

import java.io.Closeable;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore.Images.ImageColumns;

/**
 * Various I/O utilities
 *
 * @author alessandro
 *
 */
public class IOUtils {

	/**
	 * Close a {@link Closeable} stream without throwing any exception
	 *
	 * @param c
	 */
	public static void closeSilently( final Closeable c ) {
		if ( c == null ) return;
		try {
			c.close();
		} catch ( final Throwable t ) {}
	}

	public static void closeSilently( final ParcelFileDescriptor c ) {
		if ( c == null ) return;
		try {
			c.close();
		} catch ( final Throwable t ) {}
	}

	public static void closeSilently( Cursor cursor ) {
		if ( cursor == null ) return;
		try {
			if ( cursor != null ) cursor.close();
		} catch ( Throwable t ) {}
	}

	/**
	 * Try to return the absolute file path from the given Uri
	 *
	 * @param context
	 * @param uri
	 * @return the file path or null
	 */
	public static String getRealFilePath( final Context context, final Uri uri ) {

		if ( null == uri ) return null;

		final String scheme = uri.getScheme();
		String data = null;

		if ( scheme == null )
			data = uri.getPath();
		else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
			data = uri.getPath();
		} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
			Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
			if ( null != cursor ) {
				if ( cursor.moveToFirst() ) {
					int index = cursor.getColumnIndex( ImageColumns.DATA );
					if ( index > -1 ) {
						data = cursor.getString( index );
					}
				}
				cursor.close();
			}
		}
		return data;
	}
}


text:
<?php

require_once("../../../config.php");

_load_language_file("/website_code/php/management/user_details_management.inc");

require("../user_library.php");

if(is_user_admin()){

    $database_id = database_connect("templates list connected","template list failed");

    $query="update {$xerte_toolkits_site->database_table_prefix}logindetails set firstname=?, surname=?, username=?, email=? WHERE login_id = ?";
    $params = array($_POST['firstname'], $_POST['surname'], $_POST['username'], $_POST['user_id'], $_POST['email']);

    $res =db_query($query, $params);
    if($res) {
        echo USERS_UPDATE_SUCCESS;
    }else{
        echo USERS_UPDATE_FAIL;
    }
}


text:
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).

```ts

import { _AbstractConstructor } from '@angular/material/core';
import { AbstractControl } from '@angular/forms';
import { AfterContentInit } from '@angular/core';
import { AfterViewInit } from '@angular/core';
import { AnimationEvent as AnimationEvent_2 } from '@angular/animations';
import { AnimationTriggerMetadata } from '@angular/animations';
import { CanColor } from '@angular/material/core';
import { CdkStep } from '@angular/cdk/stepper';
import { CdkStepLabel } from '@angular/cdk/stepper';
import { CdkStepper } from '@angular/cdk/stepper';
import { CdkStepperNext } from '@angular/cdk/stepper';
import { CdkStepperPrevious } from '@angular/cdk/stepper';
import { ChangeDetectorRef } from '@angular/core';
import { _Constructor } from '@angular/material/core';
import { Directionality } from '@angular/cdk/bidi';
import { ElementRef } from '@angular/core';
import { ErrorStateMatcher } from '@angular/material/core';
import { EventEmitter } from '@angular/core';
import { FocusMonitor } from '@angular/cdk/a11y';
import { FocusOrigin } from '@angular/cdk/a11y';
import { FormGroupDirective } from '@angular/forms';
import * as i0 from '@angular/core';
import * as i10 from '@angular/cdk/stepper';
import * as i11 from '@angular/material/icon';
import * as i7 from '@angular/material/core';
import * as i8 from '@angular/common';
import * as i9 from '@angular/cdk/portal';
import { NgForm } from '@angular/forms';
import { OnDestroy } from '@angular/core';
import { Optional } from '@angular/core';
import { QueryList } from '@angular/core';
import { StepperOptions } from '@angular/cdk/stepper';
import { StepperOrientation } from '@angular/cdk/stepper';
import { StepState } from '@angular/cdk/stepper';
import { Subject } from 'rxjs';
import { TemplatePortal } from '@angular/cdk/portal';
import { TemplateRef } from '@angular/core';
import { ThemePalette } from '@angular/material/core';
import { ViewContainerRef } from '@angular/core';

// @public
export const MAT_STEPPER_INTL_PROVIDER: {
    provide: typeof MatStepperIntl;
    deps: Optional[][];
    useFactory: typeof MAT_STEPPER_INTL_PROVIDER_FACTORY;
};

// @public
export function MAT_STEPPER_INTL_PROVIDER_FACTORY(parentIntl: MatStepperIntl): MatStepperIntl;

// @public (undocumented)
export class MatStep extends CdkStep implements ErrorStateMatcher, AfterContentInit, OnDestroy {
    constructor(stepper: MatStepper, _errorStateMatcher: ErrorStateMatcher, _viewContainerRef: ViewContainerRef, stepperOptions?: StepperOptions);
    color: ThemePalette;
    isErrorState(control: AbstractControl | null, form: FormGroupDirective | NgForm | null): boolean;
    _lazyContent: MatStepContent;
    // (undocumented)
    ngAfterContentInit(): void;
    // (undocumented)
    ngOnDestroy(): void;
    _portal: TemplatePortal;
    stepLabel: MatStepLabel;
    // (undocumented)
    static ɵcmp: i0.ɵɵComponentDeclaration<MatStep, "mat-step", ["matStep"], { "color": "color"; }, {}, ["stepLabel", "_lazyContent"], ["*"], false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStep, [null, { skipSelf: true; }, null, { optional: true; }]>;
}

// @public
export class MatStepContent {
    constructor(_template: TemplateRef<any>);
    // (undocumented)
    _template: TemplateRef<any>;
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<MatStepContent, "ng-template[matStepContent]", never, {}, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepContent, never>;
}

// @public (undocumented)
export class MatStepHeader extends _MatStepHeaderBase implements AfterViewInit, OnDestroy, CanColor {
    constructor(_intl: MatStepperIntl, _focusMonitor: FocusMonitor, _elementRef: ElementRef<HTMLElement>, changeDetectorRef: ChangeDetectorRef);
    active: boolean;
    disableRipple: boolean;
    errorMessage: string;
    focus(origin?: FocusOrigin, options?: FocusOptions): void;
    // (undocumented)
    _getDefaultTextForState(state: StepState): string;
    _getHostElement(): HTMLElement;
    _getIconContext(): MatStepperIconContext;
    iconOverrides: {
        [key: string]: TemplateRef<MatStepperIconContext>;
    };
    index: number;
    // (undocumented)
    _intl: MatStepperIntl;
    label: MatStepLabel | string;
    // (undocumented)
    ngAfterViewInit(): void;
    // (undocumented)
    ngOnDestroy(): void;
    optional: boolean;
    selected: boolean;
    state: StepState;
    _stringLabel(): string | null;
    _templateLabel(): MatStepLabel | null;
    // (undocumented)
    static ɵcmp: i0.ɵɵComponentDeclaration<MatStepHeader, "mat-step-header", never, { "color": "color"; "state": "state"; "label": "label"; "errorMessage": "errorMessage"; "iconOverrides": "iconOverrides"; "index": "index"; "selected": "selected"; "active": "active"; "optional": "optional"; "disableRipple": "disableRipple"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepHeader, never>;
}

// @public (undocumented)
export class MatStepLabel extends CdkStepLabel {
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<MatStepLabel, "[matStepLabel]", never, {}, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepLabel, never>;
}

// @public (undocumented)
export class MatStepper extends CdkStepper implements AfterContentInit {
    constructor(dir: Directionality, changeDetectorRef: ChangeDetectorRef, elementRef: ElementRef<HTMLElement>);
    readonly animationDone: EventEmitter<void>;
    readonly _animationDone: Subject<AnimationEvent_2>;
    get animationDuration(): string;
    set animationDuration(value: string);
    color: ThemePalette;
    disableRipple: boolean;
    // (undocumented)
    _getAnimationDuration(): string;
    headerPosition: 'top' | 'bottom';
    _iconOverrides: Record<string, TemplateRef<MatStepperIconContext>>;
    _icons: QueryList<MatStepperIcon>;
    labelPosition: 'bottom' | 'end';
    // (undocumented)
    ngAfterContentInit(): void;
    _stepHeader: QueryList<MatStepHeader>;
    // (undocumented)
    _stepIsNavigable(index: number, step: MatStep): boolean;
    readonly steps: QueryList<MatStep>;
    _steps: QueryList<MatStep>;
    // (undocumented)
    static ɵcmp: i0.ɵɵComponentDeclaration<MatStepper, "mat-stepper, mat-vertical-stepper, mat-horizontal-stepper, [matStepper]", ["matStepper", "matVerticalStepper", "matHorizontalStepper"], { "selectedIndex": "selectedIndex"; "disableRipple": "disableRipple"; "color": "color"; "labelPosition": "labelPosition"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; }, { "animationDone": "animationDone"; }, ["_steps", "_icons"], never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepper, [{ optional: true; }, null, null]>;
}

// @public
export const matStepperAnimations: {
    readonly horizontalStepTransition: AnimationTriggerMetadata;
    readonly verticalStepTransition: AnimationTriggerMetadata;
};

// @public
export class MatStepperIcon {
    constructor(templateRef: TemplateRef<MatStepperIconContext>);
    name: StepState;
    // (undocumented)
    templateRef: TemplateRef<MatStepperIconContext>;
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<MatStepperIcon, "ng-template[matStepperIcon]", never, { "name": "matStepperIcon"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepperIcon, never>;
}

// @public
export interface MatStepperIconContext {
    active: boolean;
    index: number;
    optional: boolean;
}

// @public
export class MatStepperIntl {
    readonly changes: Subject<void>;
    completedLabel: string;
    editableLabel: string;
    optionalLabel: string;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepperIntl, never>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<MatStepperIntl>;
}

// @public (undocumented)
export class MatStepperModule {
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepperModule, never>;
    // (undocumented)
    static ɵinj: i0.ɵɵInjectorDeclaration<MatStepperModule>;
    // (undocumented)
    static ɵmod: i0.ɵɵNgModuleDeclaration<MatStepperModule, [typeof i1.MatStep, typeof i2.MatStepLabel, typeof i1.MatStepper, typeof i3.MatStepperNext, typeof i3.MatStepperPrevious, typeof i4.MatStepHeader, typeof i5.MatStepperIcon, typeof i6.MatStepContent], [typeof i7.MatCommonModule, typeof i8.CommonModule, typeof i9.PortalModule, typeof i10.CdkStepperModule, typeof i11.MatIconModule, typeof i7.MatRippleModule], [typeof i7.MatCommonModule, typeof i1.MatStep, typeof i2.MatStepLabel, typeof i1.MatStepper, typeof i3.MatStepperNext, typeof i3.MatStepperPrevious, typeof i4.MatStepHeader, typeof i5.MatStepperIcon, typeof i6.MatStepContent]>;
}

// @public
export class MatStepperNext extends CdkStepperNext {
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<MatStepperNext, "button[matStepperNext]", never, { "type": "type"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepperNext, never>;
}

// @public
export class MatStepperPrevious extends CdkStepperPrevious {
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<MatStepperPrevious, "button[matStepperPrevious]", never, { "type": "type"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<MatStepperPrevious, never>;
}

export { StepperOrientation }

export { StepState }

// (No @packageDocumentation comment for this package)

```


text:
'''
Copyleft Jan 03, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego,  Email: airanmehr@gmail.com
'''
# from __future__ import print_function
import numpy as np;

np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;

pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import os;

home = os.path.expanduser('~') + '/'
import Utils.Util as utl

def loadstudy():
    geneid2symbol = {}
    din_xlsx = os.path.join(utl.home, "nbt.3102-S4_GeneIDs.xlsx")
    # Read data
    if os.path.isfile(din_xlsx):
        import xlrd
        book = xlrd.open_workbook(din_xlsx)
        pg = book.sheet_by_index(0)
        for r in range(pg.nrows):
            symbol, geneid, pval = [pg.cell_value(r, c) for c in range(pg.ncols)]
            if geneid:
                geneid2symbol[int(geneid)] = symbol
    return geneid2symbol.keys()


text:
import uno

# a UNO struct later needed to create a document
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
from com.sun.star.awt import Size

from com.sun.star.lang import XMain

def insertTextIntoCell( table, cellName, text, color ):
    tableText = table.getCellByName( cellName )
    cursor = tableText.createTextCursor()
    cursor.setPropertyValue( "CharColor", color )
    tableText.setString( text )

def createTable():
    """creates a new writer document and inserts a table with some data (also known as the SWriter sample)"""
    ctx = uno.getComponentContext()
    smgr = ctx.ServiceManager
    desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

    # open a writer document
    doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )

    text = doc.Text
    cursor = text.createTextCursor()
    text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
    text.insertString( cursor, "Now we are in the second line\n" , 0 )

    # create a text table
    table = doc.createInstance( "com.sun.star.text.TextTable" )

    # with 4 rows and 4 columns
    table.initialize( 4,4)

    text.insertTextContent( cursor, table, 0 )
    rows = table.Rows

    table.setPropertyValue( "BackTransparent", uno.Bool(0) )
    table.setPropertyValue( "BackColor", 13421823 )
    row = rows.getByIndex(0)
    row.setPropertyValue( "BackTransparent", uno.Bool(0) )
    row.setPropertyValue( "BackColor", 6710932 )

    textColor = 16777215

    insertTextIntoCell( table, "A1", "FirstColumn", textColor )
    insertTextIntoCell( table, "B1", "SecondColumn", textColor )
    insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
    insertTextIntoCell( table, "D1", "SUM", textColor )

    values = ( (22.5,21.5,121.5),
              (5615.3,615.3,-615.3),
              (-2315.7,315.7,415.7) )
    table.getCellByName("A2").setValue(22.5)
    table.getCellByName("B2").setValue(5615.3)
    table.getCellByName("C2").setValue(-2315.7)
    table.getCellByName("D2").setFormula("sum <A2:C2>")

    table.getCellByName("A3").setValue(21.5)
    table.getCellByName("B3").setValue(615.3)
    table.getCellByName("C3").setValue(-315.7)
    table.getCellByName("D3").setFormula("sum <A3:C3>")

    table.getCellByName("A4").setValue(121.5)
    table.getCellByName("B4").setValue(-615.3)
    table.getCellByName("C4").setValue(415.7)
    table.getCellByName("D4").setFormula("sum <A4:C4>")

    cursor.setPropertyValue( "CharColor", 255 )
    cursor.setPropertyValue( "CharShadowed", uno.Bool(1) )

    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
    text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 )
    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )

    textFrame = doc.createInstance( "com.sun.star.text.TextFrame" )
    textFrame.setSize( Size(15000,400))
    textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER )

    text.insertTextContent( cursor, textFrame, 0 )

    textInTextFrame = textFrame.getText()
    cursorInTextFrame = textInTextFrame.createTextCursor()
    textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 )
    textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0)
    text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )

    cursor.setPropertyValue( "CharColor", 65536 )
    cursor.setPropertyValue( "CharShadowed", uno.Bool(0) )

    text.insertString( cursor, " That's all for now !!" , 0 )

g_exportedScripts = createTable,


text:
#include <stdio.h>

#include "generic_code.h"
#include "entdec.h"
#include "logging.h"
#include "odintrin.h"
#include "pvq_code.h"

/** Encodes a random variable using a "generic" model, assuming that the distribution is
 * one-sided (zero and up), has a single mode, and decays exponentially passed the mode
 *
 * @param [in,out] dec   range decoder
 * @param [in,out] model generic probability model
 * @param [in,out] ExQ16 expectation of x (adapted)
 * @param [in]     integration integration period of ExQ16 (leaky average over 1<<integration samples)
 *
 * @retval decoded variable x
 */
int generic_decode(od_ec_dec *dec, GenericEncoder *model, int *ExQ16, int integration)
{
  int lgQ1;
  int shift;
  int id;
  ogg_uint16_t *cdf;
  int xs;
  int lsb=0;
  int x;

  lgQ1=logEx(*ExQ16);

  /* If expectation is too large, shift x to ensure that
     all we have past xs=15 is the exponentially decaying tail
     of the distribution */
  shift=OD_MAXI(0,(lgQ1-5)>>1);

  /* Choose the cdf to use: we have two per "octave" of ExQ16 */
  id=OD_MINI(GENERIC_TABLES-1,lgQ1);
  cdf=model->cdf[id];

  xs=od_ec_decode_cdf(dec,cdf,16);

  if(xs==15){
    int E;
    unsigned decay;
    /* Estimate decay based on the assumption that the distribution is close to Laplacian for large values.
       We should probably have an adaptive estimate instead. */
    E = ((*ExQ16>>8)+(1<<shift>>1))>>shift;
    decay = OD_MAXI(2,OD_MINI(254,256*E/(E+256)));

    xs+=laplace_decode_special(dec,decay,-1);
  }

  if(shift!=0){
    int special;
    /* Because of the rounding, there's only half the number of possibilities for xs=0 */
    special=(xs==0);
    if (shift-special>0)
      lsb=od_ec_dec_bits(dec,shift-special);
    lsb-=!special<<(shift-1);
  }
  x = (xs<<shift)+lsb;

  generic_model_update(model,ExQ16,x,xs,id,integration);

  OD_LOG((OD_LOG_ENTROPY_CODER, OD_LOG_DEBUG,
          "dec: %d %d %d %d %d %x", *ExQ16, x, shift, id, xs, dec->rng));
  return x;
}


text:
<?php

namespace AG\ShortenerBundle\Controller;

use Doctrine\ORM\EntityManager;
use Knp\Component\Pager\Paginator;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class AdminController extends Controller
{
    /**
     * @var Request
     */
    private $request;

    /**
     * @var EntityManager
     */
    private $em;

    /**
     * @var Paginator
     */
    private $paginator;

    /**
     * @return array
     * @Template
     */
    public function indexAction()
    {
        $linkList = $this->em->getRepository('AGShortenerBundle:Link')->findAllAdminQuery();

        return array(
            'linkList' => $this->paginator->paginate(
                $linkList,
                $this->request->query->getInt('page', 1),
                20
            )
        );
    }
}


text:
package io.javalin.examples;

import io.javalin.Javalin;
import static io.javalin.apibuilder.ApiBuilder.get;
import static io.javalin.apibuilder.ApiBuilder.patch;
import static io.javalin.apibuilder.ApiBuilder.post;

public class HelloWorldCors {

    public static void main(String[] args) {

        Javalin corsApp = Javalin.create(config -> {
            config.enableCorsForOrigin("http://localhost:7001/", "http://localhost:7002");
        }).start(7070);

        corsApp.routes(() -> {
            get(ctx -> ctx.json("Hello Get"));
            post(ctx -> ctx.json("Hello Post"));
            patch(ctx -> ctx.json("Hello Patch"));
        });

        Javalin.create().start(7001).get("/", ctx -> ctx.html("Try some CORS"));
        Javalin.create().start(7002).get("/", ctx -> ctx.html("Try some CORS"));
        Javalin.create().start(7003).get("/", ctx -> ctx.html("No CORS here"));

    }

}


text:
using System;
using System.IO;
using Xunit;

namespace Tests.System.IO
{
    [PlatformSpecific(TestPlatforms.AnyUnix)]
    public class PathInternalTests_Unix
    {
        [Theory,
           InlineData(@"", @""),
           InlineData(null, null),
           InlineData(@"/", @"/"),
           InlineData(@"//", @"/"),
           InlineData(@"///", @"/"),
           InlineData(@"\", @"\"),
           InlineData(@"\\", @"\\"),
           InlineData(@"\\\", @"\\\"),
           InlineData(@"\/", @"\/"),
           InlineData(@"\/\", @"\/\"),

           InlineData(@"a/a", @"a/a"),
           InlineData(@"a//a", @"a/a"),
           InlineData(@"a\\a", @"a\\a"),
           InlineData(@"/a", @"/a"),
           InlineData(@"//a", @"/a"),
           InlineData(@"\\a", @"\\a"),
           InlineData(@"a/", @"a/"),
           InlineData(@"a//", @"a/"),
           InlineData(@"a\\", @"a\\"),
           ]
        [PlatformSpecific(TestPlatforms.AnyUnix)]
        public void NormalizeDirectorySeparatorTests(string path, string expected)
        {
            string result = PathInternal.NormalizeDirectorySeparators(path);
            Assert.Equal(expected, result);
            if (string.Equals(path, expected, StringComparison.Ordinal))
                Assert.Same(path, result);
        }
    }
}