text:
require 'uri'

module Idobata::Hook
  class Docbase < Base
    module Helper
      def link_to_post(post_title, post_url)
        capture_haml do
          haml_tag :a, post_title, href: post_url
        end
      end

      def link_to_user(team_domain, user_id, user_name)
        url = "https://#{team_domain}.docbase.io/users/#{user_id}"
        capture_haml do
          haml_tag :a, user_name, href: url
        end
      end

      def link_to_joined_team_or_group(name, message)
        url = URI::RFC2396_Parser.new.extract(message).first

        capture_haml do
          haml_tag :a, name, href: url
        end
      end

      def md(source)
        HTML::Pipeline::MarkdownFilter.new(source, gfm: true).call.to_s.html_safe
      end
    end
  end
end


text:
package com.swfarm.biz.chain.web;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.swfarm.biz.chain.dto.SearchSkuDevKpiSheetsCriteria;
import com.swfarm.biz.chain.srv.KpiReportService;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.oa.srv.UserService;
import com.swfarm.pub.utils.SpringUtils;

public class GenerateSkuDevKpiSheetsController extends AbstractController {

	private KpiReportService kpiReportService;

	public void setKpiReportService(KpiReportService kpiReportService) {
		this.kpiReportService = kpiReportService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		SearchSkuDevKpiSheetsCriteria criteria = (SearchSkuDevKpiSheetsCriteria) req
				.getAttribute("criteria");
		if (criteria != null) {
			if (StringUtils.isNotEmpty(criteria.getProductManagerNo())) {
				this.kpiReportService.generateSkuDevKpiSheet(
						criteria.getProductManagerNo(),
						criteria.getSkuStartDate(), criteria.getSkuEndDate(),
						criteria.getSaleStartDate(), criteria.getSaleEndDate());
			} else {
				List productManagers = this.getProductManagers();
				if (CollectionUtils.isNotEmpty(productManagers)) {
					for (Iterator iter = productManagers.iterator(); iter
							.hasNext();) {
						User productManager = (User) iter.next();
						criteria.setProductManagerNo(productManager
								.getUsername());
						this.kpiReportService.generateSkuDevKpiSheet(
								criteria.getProductManagerNo(),
								criteria.getSkuStartDate(),
								criteria.getSkuEndDate(),
								criteria.getSaleStartDate(),
								criteria.getSaleEndDate());
					}
				}
			}
		}
		return new ModelAndView("redirect:/chain/search_skudevkpisheets.shtml");
	}

	public List getProductManagers() {
		UserService userService = (UserService) SpringUtils
				.getBean("userService");
		List productManagers = userService.findUsersByRole("产品经理");
		return productManagers;
	}

}

redpajama_set_name: RedPajamaGithub


text:
(function() {
  var Score,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  module.exports = Score = (function(_super) {
    __extends(Score, _super);

    function Score() {
      return Score.__super__.constructor.apply(this, arguments);
    }

    Score.test = function() {
      return this;
    };

    return Score;

  })(require("lodash"));

}).call(this);


text:
module TokyoMetro::Modules::ToFactory::Api::Generate::Group
end


text:
Enforce that all elements that require alternative text have meaningful information to relay back to the end user. This is a critical component of accessibility for screenreader users in order for them to understand the content's purpose on the page. By default, this rule checks for alternative text on the following elements: `<img>`, `<area>`, `<input type="image">`, and `<object>`.

#### Resources
  1. [aXe object-alt](https://dequeuniversity.com/rules/axe/2.1/object-alt)
  2. [aXe image-alt](https://dequeuniversity.com/rules/axe/2.1/image-alt)
  3. [aXe input-image-alt](https://dequeuniversity.com/rules/axe/2.1/input-image-alt)
  4. [aXe area-alt](https://dequeuniversity.com/rules/axe/2.1/area-alt)

## How to resolve
### `<img>`
An `<img>` must have the `alt` prop set with meaningful text or as an empty string to indicate that it is an image for decoration.

For images that are being used as icons for a button or control, the `alt` prop should be set to an empty string (`alt=""`).

```js
<button>
  <img src="icon.png" alt="" />
  Save
</button>
```
The content of an `alt` attribute is used to calculate the accessible label of an element, whereas the text content is used to produce a label for the element. For this reason, adding a label to an icon can produce a confusing or duplicated label on a control that already has appropriate text content.

### `<object>`
Add alternative text to all embedded `<object>` elements using either inner text, setting the `title` prop, or using the `aria-label` or `aria-labelledby` props.

### `<input type="image">`
All `<input type="image">` elements must have a non-empty `alt` prop set with a meaningful description of the image or have the `aria-label` or `aria-labelledby` props set.

### `<area>`
All clickable `<area>` elements within an image map have an `alt`, `aria-label` or `aria-labelledby` prop that describes the purpose of the link.

## Rule details

This rule takes one optional object argument of type object:

```json
{
    "rules": {
        "jsx-a11y/img-has-alt": [ 2, {
            "elements": [ "img", "object", "area", "input[type=\"image\"]" ],
            "img": ["Image"],
            "object": ["Object"],
            "area": ["Area"],
            "input[type=\"image\"]": ["InputImage"]
          }],
    }
}
```

The `elements` option is a whitelist for DOM elements to check for alternative text. If an element is removed from the default set of elements (noted above), any custom components for that component will also be ignored. In order to indicate any custom wrapper components that should be checked, you can map the DOM element to an array of JSX custom components. This is a good use case when you have a wrapper component that simply renders an `img` element, for instance (like in React):

```jsx
// Image.js
const Image = props => {
  const {
    alt,
    ...otherProps
  } = props;

  return (
    <img alt={alt} {...otherProps} />
  );
}

...

// Header.js (for example)
...
return (
  <header>
    <Image alt="Logo" src="logo.jpg" />
  </header>
);
```

Note that passing props as spread attribute without explicitly the necessary accessibility props defined will cause this rule to fail. Explicitly pass down the set of props needed for rule to pass. Use `Image` component above as a reference for destructuring and applying the prop. **It is a good thing to explicitly pass props that you expect to be passed for self-documentation.** For example:

#### Bad
```jsx
function Foo(props) {
  return <img {...props} />
}
```

#### Good
```jsx
function Foo({ alt, ...props}) {
    return <img alt={alt} {...props} />
}

// OR

function Foo(props) {
    const {
        alt,
        ...otherProps
    } = props;

   return <img alt={alt} {...otherProps} />
}
```

### Succeed
```jsx
<img src="foo" alt="Foo eating a sandwich." />
<img src="foo" alt={"Foo eating a sandwich."} />
<img src="foo" alt={altText} />
<img src="foo" alt={`${person} smiling`} />
<img src="foo" alt="" />

<object aria-label="foo" />
<object aria-labelledby="id1" />
<object>Meaningful description</object>
<object title="An object" />

<area aria-label="foo" />
<area aria-labelledby="id1" />
<area alt="This is descriptive!" />

<input type="image" alt="This is descriptive!" />
<input type="image" aria-label="foo" />
<input type="image" aria-labelledby="id1" />

```

### Fail
```jsx
<img src="foo" />
<img {...props} />
<img {...props} alt /> // Has no value
<img {...props} alt={undefined} /> // Has no value
<img {...props} alt={`${undefined}`} /> // Has no value
<img src="foo" role="presentation" /> // Avoid ARIA if it can be achieved without
<img src="foo" role="none" /> // Avoid ARIA if it can be achieved without

<object {...props} />

<area {...props} />

<input type="image" {...props} />
```


text:
Script | Description
------------ | -------------
[ocp36-sat6.py](ocp36-sat6.py) | Dynamically import docker images to local satellite via registry.access.redhat.com
[project_export.sh](project_export.sh) | Export project content to json files
[project_import.sh](project_import.sh) | Import exported project content in json files to OCP objects
[backup_master_node.sh](backup_master_node.sh) | Create backup of important files on master or nodes hosts (root access required)


text:
package space.samatov.mmatoday.Fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

import samatov.space.mmatoday.R;
import space.samatov.mmatoday.model.Article;

public class ArticleDetailsFragment  extends Fragment{

    public static final String FRAGMENT_KEY="article_details_fragment";
    public static final String ARGS_KEY="article_details";
    private Article mArticle;
    private ImageView mImageView;
    private TextView mAuthorTextView;
    private TextView mTittleTextView;
    private TextView mContentTextView;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view=inflater.inflate(R.layout.fragment_article_details,container,false);
        Bundle args=getArguments();
        ArrayList<Article> argument=args.getParcelableArrayList(ARGS_KEY);
        mArticle=argument.get(0);
        mImageView= (ImageView) view.findViewById(R.id.articleImageView);
        mAuthorTextView= (TextView) view.findViewById(R.id.articleAuthorTextView);
        mTittleTextView= (TextView) view.findViewById(R.id.articleTittleTextView);
        mContentTextView= (TextView) view.findViewById(R.id.articleContentTextView);
        Glide.with(getActivity()).load(mArticle.getmImageUrl()).into(mImageView);
        mTittleTextView.setText(mArticle.getmHeadline());
        mAuthorTextView.setText("by "+ mArticle.getmAuthor());
        for (String paragraph:mArticle.getContent()){
            mContentTextView.append(paragraph);
            mContentTextView.append("\n\n");
        }

        return view;
    }
}


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">
    <meta name="description" content="This is Delhi University Community Radio Official website.">
    <meta name="author" content="Vineet">

    <title>Delhi University Community Radio</title>

    <link rel="stylesheet" href="../css/bootstrap.min.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="../css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="../css/creative.css" type="text/css">

Faq's

What is Delhi University Community Radio(DUCR)?

Delhi University Community Radio (DUCR) is a community radio station broadcasting on 90.4MHz.

Where DUCR is located?

DUCR is located inside University Stadium, G.C. Narang Road, North Campus, Delhi-110007, University Of Delhi.

What is the range of DUCR?

The range of DUCR is 10-12 km radius.

What type of programs are broadcast from DUCR?

Programs beneficial for Delhi University Community as well as people living nearby.

How DUCR is managed?

DUCR is managed by students.

Who can participate in DUCR programs?

Any student of DU can participate in 011-27662336 DUCR programs.

Who should be contacted?

Consultant DUCR on email: ducr90.4@gmail.com


text:
package net.bigpoint.assessment.gasstation.exceptions;

/**
 * This exception is thrown whenever gas could not be bought because not enough was available
 *
 */
public class NotEnoughGasException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = -4577139900795204370L;

}


text:
module SlackGamebot
  module Commands
    class Rank < SlackRubyBot::Commands::Base
      def self.call(client, data, match)
        arguments = match['expression'].split.reject(&:blank?) if match.names.include?('expression')
        users = arguments || []
        if arguments && arguments.any?
          users = User.find_many_by_slack_mention!(users)
        else
          users << ::User.find_create_or_update_by_slack_id!(client, data.user)
        end
        message = User.rank_section(users).map do |user|
          user.rank ? "#{user.rank}. #{user}" : "#{user.user_name}: not ranked"
        end.join("\n")
        send_message client, data.channel, message
      end
    end
  end
end


text:
Google Visualization PHP
========================

[![Build Status](https://travis-ci.org/vube/google-visualization-php.png?branch=master)](https://travis-ci.org/vube/google-visualization-php)
[![Coverage Status](https://coveralls.io/repos/vube/google-visualization-php/badge.png?branch=master)](https://coveralls.io/r/vube/google-visualization-php?branch=master)
[![Latest Stable Version](https://poser.pugx.org/vube/google-visualization-php/v/stable.png)](https://packagist.org/packages/vube/google-visualization-php)
[![Dependency Status](https://www.versioneye.com/user/projects/526595aa632bac5e560019b6/badge.png)](https://www.versioneye.com/user/projects/526595aa632bac5e560019b6)

Google Visualization DataSource implemented in PHP

This PHP library allows you to implement Google Visualization DataSource queries in PHP.

Features
--------

- Use PHP endpoints in Apache or Nginx as a DataSource for Google Charts
- Limited query language support
    - select columns
    - pivot

Limitations
-----------

- The full query language is not yet supported.

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

Load google-visualization-php into your project by adding the following lines to your `composer.json`

``` json
{
    "require": {
        "vube/google-visualization-php": ">=0.2"
    }
}
```

Dependencies
------------

- PHP 5.3.2+
- Composer

References
----------

* Based very closely on [google-visualization-java](https://code.google.com/p/google-visualization-java/source/browse/trunk/src/main/java/com/google/visualization/datasource/) with some modifications to make it work in PHP 5.3.2+


text:
package flex.messaging;

import flex.messaging.config.ConfigMap;

/**
 * Components created in the Flex configuration environment can implement
 * the FlexConfigurable interface to get access to the configuration
 * properties like a regular component in the system.
 */
public interface FlexConfigurable
{
    /**
     * Initializes the component with configuration information.
     *
     * @param id The id of the component.
     * @param configMap The properties for configuring component.
     */
    void initialize(String id, ConfigMap configMap);
}


text:
"""
Defines views.
"""
# pylint: disable=no-name-in-module,import-error
import calendar
import locale
import logging
import operator
import time
from collections import defaultdict, OrderedDict

from flask import abort, redirect
from flask.ext.mako import exceptions, render_template
from lxml import etree

from presence_analyzer.main import app
from presence_analyzer.utils import (
    get_data,
    group_by_weekday,
    jsonify,
    mean,
    seconds_since_midnight,
    get_mean_start_end,
    variation_for_day_start_end,
    standard_deviation_from_data,
)

log = logging.getLogger(__name__)  # pylint: disable=invalid-name

@app.route('/')
def mainpage():
    """
    Redirects to front page.
    """
    return redirect('/presence_weekday')

@app.route('/api/v1/users', methods=['GET'])
@jsonify
def users_view_v1():
    """
    Users listing for dropdown.
    """
    data = get_data()
    return [
        {'user_id': i, 'name': 'User {0}'.format(str(i))}
        for i in data.keys()
    ]

@app.route('/api/v2/users', methods=['GET'])
@jsonify
def users_view_v2():
    """
    Users listing for dropdown.
    """
    # pylint: disable=no-member
    with open(app.config['USERS_XML_FILE'], 'r') as usersxmlfile:
        tree = etree.parse(usersxmlfile)
    url_base = "{}://{}".format(
        tree.find('server').findtext('protocol'),
        tree.find('server').findtext('host'),
    )
    data = [
        {
            'user_id': elem.get('id'),
            'name': elem.findtext('name'),
            'avatar': '{}{}'.format(url_base, elem.findtext('avatar')),
        }
        for elem in tree.findall('./users/user')
    ]
    locale.setlocale(locale.LC_COLLATE, "")
    data.sort(key=operator.itemgetter('name'), cmp=locale.strcoll)
    return data

@app.route('/api/v1/mean_time_weekday/<int:user_id>', methods=['GET'])
@jsonify
def mean_time_weekday_view(user_id):
    """
    Returns mean presence time of given user grouped by weekday.
    """
    data = get_data()
    if user_id not in data:
        log.debug('User %s not found!', user_id)
        return 'NO_USER_DATA'

    weekdays = group_by_weekday(data[user_id])
    result = [
        (calendar.day_abbr[weekday], mean(intervals))
        for weekday, intervals in enumerate(weekdays)
    ]

    return result

@app.route('/api/v1/presence_weekday/<int:user_id>', methods=['GET'])
@jsonify
def presence_weekday_view(user_id):
    """
    Returns total presence time of given user grouped by weekday.
    """
    data = get_data()
    if user_id not in data:
        log.debug('User %s not found!', user_id)
        return 'NO_USER_DATA'

    weekdays = group_by_weekday(data[user_id])
    result = [
        (calendar.day_abbr[weekday], sum(intervals))
        for weekday, intervals in enumerate(weekdays)
    ]

    result.insert(0, ('Weekday', 'Presence (s)'))
    return result

@app.route('/api/v1/standard_deviation/<int:user_id>', methods=['GET'])
@jsonify
def standard_deviation(user_id):
    """
    Returns standard deviation of user start and end work time
    of each working day.

    It creates structure like this:
    day_start_end is structure like so:
        {
            0: {    # 0 mean monday and so on
                    variation_of_starting_work_time: [
                        [
                            starting_floor_hour,
                            starting_floor_minutes,
                            starting_floor_seconds
                        ],
                        [
                            starting_top_hour,
                            starting_top_minutes,
                            starting_top_seconds,
                        ],
                    ],
                    variation_of_ending_work_time: [
                        [
                            ending_floor_hour,
                            ending_floor_minutes,
                            ending_floor_seconds
                        ],
                        [
                            ending_top_hour,
                            ending_top_minutes,
                            ending_top_seconds,
                        ],
                    ],
                ],
            },
        }
    """
    data = get_data()
    if user_id not in data:
        log.debug('User %s not found!', user_id)
        return 'NO_USER_DATA'

    day_start_end = {}
    for day_idx in range(7):
        day_start_end[day_idx] = defaultdict(lambda: 0)

    weekdays = get_mean_start_end(data[user_id])

    day_start_end = variation_for_day_start_end(
        day_start_end,
        data[user_id],
        weekdays,
    )

    day_start_end = standard_deviation_from_data(day_start_end, weekdays)

    return day_start_end

@app.route('/api/v1/presence_start_end/<int:user_id>', methods=['GET'])
@jsonify
def presence_start_end(user_id):
    """
    Returns total presence time of given user grouped by weekday.
    """
    data = get_data()
    if user_id not in data:
        log.debug('User %s not found!', user_id)
        return 'NO_USER_DATA'

    weekdays = {x: {'start': [], 'end': []} for x in range(7)}

    for day in data[user_id].keys():
        weekdays[day.weekday()]['start'].append(
            seconds_since_midnight(data[user_id][day]['start'])
        )
        weekdays[day.weekday()]['end'].append(
            seconds_since_midnight(data[user_id][day]['end'])
        )
    for day_idx in weekdays.keys():
        start_time_tuple = time.gmtime(mean(weekdays[day_idx]['start']))
        end_time_tuple = time.gmtime(mean(weekdays[day_idx]['end']))
        weekdays[day_idx]['start'] = [
            start_time_tuple.tm_hour,
            start_time_tuple.tm_min,
            start_time_tuple.tm_sec,
        ]

        weekdays[day_idx]['end'] = [
            end_time_tuple.tm_hour,
            end_time_tuple.tm_min,
            end_time_tuple.tm_sec,
        ]

    return weekdays

@app.route('/<template>')
def render_html(template):
    """
    Returns rendered html files.
    """
    urls = OrderedDict([
        ('presence_weekday', 'Presence weekday'),
        ('mean_time_weekday', 'Mean time weekday'),
        ('presence_start_end', 'Presence start end'),
        ('standard_deviation', 'Standard deviation'),
    ])
    try:
        return render_template(template + '.html', urls=urls)
    except (exceptions.TopLevelLookupException, exceptions.SyntaxException):
        abort(404)


text:
package ru.job4j.comparator;

import java.util.Comparator;

/**
 * Class to List of String with comparator.
 * @author Tolstonogov Alexey
 * @version 1.0
 * @since 1.0
 */
public class ListCompare implements Comparator<String> {
    /**
     * Comparator of String values.
     * @param left First string.
     * @param right Second string.
     * @return >0 if first string greater than second;
     *         <0 if first string less than second;
     *         0 if first string is equal to second.
     */
    @Override
    public int compare(String left, String right) {
        int result = 0;
        int size = Math.min(left.length(), right.length());
        for (int index = 0; index < size && result == 0; index++) {
            result = Integer.compare(left.charAt(index), right.charAt(index));
        }
        if (result == 0) {
            result = left.length() - right.length();
        }
        return result;
    }
}


text:
package com.thebuzzmedia.common.util;

/**
 * @author Riyad Kalla (software@thebuzzmedia.com)
 * @since 1.0
 */
public class NumberUtils {
	/**
	 * Used to parse a byte numeric value (-128 to 127) from a
	 * byte[] starting at the given index and using the given
	 * number of bytes. Parsing values from {@link Byte#MIN_VALUE} to
	 * {@link Byte#MAX_VALUE} are supported.
	 *

	 * Because this method cannot return an primitive value representing a
	 * failed parse attempt (e.g. -1) it will throw an exception if any of the
	 * input values are invalid or if a value cannot be parsed from the given
	 * array cleanly (i.e. non-ASCII bytes representing chars '0' through '9'
	 * (starting char '-' is allowed for negatives) are encountered).
	 *

	 * Care should be taken to either protect against bad values before hand or
	 * handle the exceptions by the caller.
	 *

	 * The implementation of this method is highly efficient, using no
	 * object-creation during parsing and only allocating a few primitives for
	 * state-tracking.
	 *
	 * @param data
	 *            The array to parse the number from.
	 * @param index
	 *            The index into the array where parsing will begin from.
	 * @param length
	 *            The number of bytes to parse to construct the final value.
	 *
	 * @return a byte numeric value as parsed from the given array.
	 *
	 * @throws IllegalArgumentException
	 *             if data is null or empty, if
	 *             length <= 0, if index is < 0
	 *             or if index + length is >
	 *             data.length.
	 * @throws NumberFormatException
	 *             if an non-numeric char with an ASCII code < 48 (0) or >
	 *             57 (9) is encountered (first char of '-' (for a negative) is
	 *             fine) also if the size of the value being parsed overflows
	 *             beyond the limits of {@link Byte#MAX_VALUE} or
	 *             {@link Byte#MIN_VALUE}.
	 */
	public static byte parseByte(byte[] data, int index, int length)
			throws IllegalArgumentException, NumberFormatException {
		return (byte) parseLong(data, index, length, Byte.MIN_VALUE,
				Byte.MAX_VALUE);
	}

	/**
	 * Used to parse a short value from a byte[]
	 * starting at the given index and using the given number of bytes. Parsing
	 * values from {@link Short#MIN_VALUE} to {@link Short#MAX_VALUE} are
	 * supported.
	 *

	 * Because this method cannot return an primitive value representing a
	 * failed parse attempt (e.g. -1) it will throw an exception if any of the
	 * input values are invalid or if a value cannot be parsed from the given
	 * array cleanly (i.e. non-ASCII bytes representing chars '0' through '9'
	 * (starting char '-' is allowed for negatives) are encountered).
	 *

	 * Care should be taken to either protect against bad values before hand or
	 * handle the exceptions by the caller.
	 *

	 * The implementation of this method is highly efficient, using no
	 * object-creation during parsing and only allocating a few primitives for
	 * state-tracking.
	 *
	 * @param data
	 *            The array to parse the number from.
	 * @param index
	 *            The index into the array where parsing will begin from.
	 * @param length
	 *            The number of bytes to parse to construct the final value.
	 *
	 * @return a short value as parsed from the given array.
	 *
	 * @throws IllegalArgumentException
	 *             if data is null or empty, if
	 *             length <= 0, if index is < 0
	 *             or if index + length is >
	 *             data.length.
	 * @throws NumberFormatException
	 *             if an non-numeric char with an ASCII code < 48 (0) or >
	 *             57 (9) is encountered (first char of '-' (for a negative) is
	 *             fine) also if the size of the value being parsed overflows
	 *             beyond the limits of {@link Short#MAX_VALUE} or
	 *             {@link Short#MIN_VALUE}.
	 */
	public static short parseShort(byte[] data, int index, int length)
			throws IllegalArgumentException, NumberFormatException {
		return (short) parseLong(data, index, length, Short.MIN_VALUE,
				Short.MAX_VALUE);
	}

	/**
	 * Used to parse an integer from a byte[] starting
	 * at the given index and using the given number of bytes. Parsing values
	 * from {@link Integer#MIN_VALUE} to {@link Integer#MAX_VALUE} are
	 * supported.
	 *

	 * Because this method cannot return an primitive value representing a
	 * failed parse attempt (e.g. -1) it will throw an exception if any of the
	 * input values are invalid or if a value cannot be parsed from the given
	 * array cleanly (i.e. non-ASCII bytes representing chars '0' through '9'
	 * (starting char '-' is allowed for negatives) are encountered).
	 *

	 * Care should be taken to either protect against bad values before hand or
	 * handle the exceptions by the caller.
	 *

	 * The implementation of this method is highly efficient, using no
	 * object-creation during parsing and only allocating a few primitives for
	 * state-tracking.
	 *
	 * @param data
	 *            The array to parse the number from.
	 * @param index
	 *            The index into the array where parsing will begin from.
	 * @param length
	 *            The number of bytes to parse to construct the final value.
	 *
	 * @return an integer value as parsed from the given array.
	 *
	 * @throws IllegalArgumentException
	 *             if data is null or empty, if
	 *             length <= 0, if index is < 0
	 *             or if index + length is >
	 *             data.length.
	 * @throws NumberFormatException
	 *             if an non-numeric char with an ASCII code < 48 (0) or >
	 *             57 (9) is encountered (first char of '-' (for a negative) is
	 *             fine) also if the size of the value being parsed overflows
	 *             beyond the limits of {@link Integer#MAX_VALUE} or
	 *             {@link Integer#MIN_VALUE}.
	 */
	public static int parseInt(byte[] data, int index, int length)
			throws IllegalArgumentException, NumberFormatException {
		return (int) parseLong(data, index, length, Integer.MIN_VALUE,
				Integer.MAX_VALUE);
	}

	/**
	 * Used to parse a long from a byte[] starting at
	 * the given index and using the given number of bytes. Parsing values from
	 * {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported.
	 *

	 * Because this method cannot return an primitive value representing a
	 * failed parse attempt (e.g. -1) it will throw an exception if any of the
	 * input values are invalid or if a value cannot be parsed from the given
	 * array cleanly (i.e. non-ASCII bytes representing chars '0' through '9'
	 * (starting char '-' is allowed for negatives) are encountered).
	 *

	 * Care should be taken to either protect against bad values before hand or
	 * handle the exceptions by the caller.
	 *

	 * The implementation of this method is highly efficient, using no
	 * object-creation during parsing and only allocating a few primitives for
	 * state-tracking.
	 *
	 * @param data
	 *            The array to parse the number from.
	 * @param index
	 *            The index into the array where parsing will begin from.
	 * @param length
	 *            The number of bytes to parse to construct the final value.
	 *
	 * @return a long value as parsed from the given array.
	 *
	 * @throws IllegalArgumentException
	 *             if data is null or empty, if
	 *             length <= 0, if index is < 0
	 *             or if index + length is >
	 *             data.length.
	 * @throws NumberFormatException
	 *             if an non-numeric char with an ASCII code < 48 (0) or >
	 *             57 (9) is encountered (first char of '-' (for a negative) is
	 *             fine) also if the size of the value being parsed overflows
	 *             beyond the limits of {@link Long#MAX_VALUE} or
	 *             {@link Long#MIN_VALUE}.
	 */
	public static long parseLong(byte[] data, int index, int length)
			throws IllegalArgumentException, NumberFormatException {
		return parseLong(data, index, length, Long.MIN_VALUE, Long.MAX_VALUE);
	}

	protected static long parseLong(byte[] data, int index, int length,
			long minValue, long maxValue) throws IllegalArgumentException,
			NumberFormatException {
		if (data == null || data.length == 0)
			throw new IllegalArgumentException("data cannot be null or empty");
		if (index < 0 || length <= 0 || (index + length > data.length))
			throw new IllegalArgumentException("index [" + index
					+ "] must be >= 0 and length [" + length
					+ "] must be > 0 and (index + length) [" + (index + length)
					+ "] must be <= data.length [" + data.length + "]");

		long result = 0;

		// Check the first byte to see if this is a negative number: '-' is 45
		boolean neg = (data[index] == 45 ? true : false);

		/*
		 * Begin iterating on the bytes, parsing the number. If we are dealing
		 * with a negative number, start on the index + 1 element because the
		 * element at index is '-'.
		 */
		for (int i = (neg ? 1 : 0); i < length; i++) {
			/*
			 * Get the byte representing the digit. Convert it quickly to an int
			 * by subtracting the ASCII value of '0' from it (48); yielding its
			 * true int value: 0 through 9
			 */
			long digit = (data[index + i] - 48);

			/*
			 * If the digit parsed is less than 0 or greater than 9, then it
			 * wasn't an ASCII character byte representing a number and we have
			 * to throw an exception notifying the caller that this run of bytes
			 * does not represent a number.
			 */
			if (digit < 0 || digit > 9)
				throw new NumberFormatException(
						"A non-numeric value (ASCII code " + (digit + 48)
								+ ") was encountered at index " + (index + i)
								+ " while trying to parse an integer from '"
								+ new String(data, index, length) + "'.");

			/*
			 * Adjust the value of the parsed number by magnitudes of 10 to
			 * ensure its value is adjusted for the right place it was in (e.g.
			 * one's place, ten's place, hundred's, etc.)
			 */
			for (int j = i, end = length - 1; j < end; j++)
				digit *= 10;

			/*
			 * Add the parsed value to the running total. We store all values
			 * during calculation as negatives because the MIN_VALUE bound of
			 * all primitive types holds 1 more value than the positive bounds
			 * (e.g. -128 to 127 for byte).
			 *
			 * We just flip the negative when we return the value if necessary.
			 *
			 * TIP from: http://nadeausoftware.com/node/97
			 */
			result -= digit;

			/*
			 * Now we check to make sure the value hasn't overflowed the lower
			 * bounds of the primitive type we were parsing for.
			 *
			 * Since we only parse negative values (and flip the negative as a
			 * last step if necessary) we can check against our minValue for any
			 * primitive type smaller than a long, and for a long, check if the
			 * type has flipped to a positive value to indicate an overflow.
			 */
			if (result < minValue || result > 0)
				throw new NumberFormatException(
						"Value has overflowed. The number represented in the given array from index "
								+ index
								+ " to "
								+ (index + length)
								+ " exclusive ("
								+ new String(data, index, length)
								+ ") is larger than the limits of the target primitive type with value bounds of "
								+ minValue + " to " + maxValue + ".");
		}

		// Flip the sign if it was positive or leave it negative.
		return (neg ? result : -result);
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class events extends CI_Controller {

   public function __construct()
   {
      parent::__construct();
      $this->load->model('events_model');
   }

   public function index()
   {
      $this->load->view('templates/header');
      $this->load->view('events');
      $this->load->view('templates/footer');
   }

	public function events()
	{
      $events = $this->events_model->get_events();

      if(!empty($this->events_model->error))
      {
         //show_error($this->events_model->error, 500);
         header('HTTP/1.1 Internal Server Error', true, 500);
         echo $this->events_model->error;
         return;
      }

      if(empty($events)) $events = array();

      echo json_encode($events);
	}

   public function loadStands()
   {
      //sleep(1);
      $hall_id = $this->input->get('hall_id');
      $event_id = $this->input->get('event_id');

      if( empty($hall_id) || empty($event_id) )
      {
         header('HTTP/1.1 400 Bad Request',true,400);
         echo 'Required Filed missing! hall_id or event_id';
         return false;
      }

      $stands = $this->events_model->loadStands($hall_id,$event_id);

      if(!empty($this->events_model->error))
      {
         header('HTTP/1.1 Internal Server Error', true, 500);
         echo $this->events_model->error;
         return;
      }

      if(empty($stands)) $stands = array();

      //----------- load docs of subscriber companies only
      $companies = array();

      foreach($stands as $stand)
      {
         if( !empty($stand['company_id']) )
            $companies[] = $stand['company_id'];
      }

      if( !empty($companies) )
      {
         $companies = array_unique($companies);

         $files = $this->events_model->loadFiles($companies);

         if(!empty($this->events_model->error))
         {
            header('HTTP/1.1 Internal Server Error', true, 500);
            echo $this->events_model->error;
            return;
         }
      }

      if(empty($files)) $files = array();

      //var_dump($stands, $files);

      $response = array();
      $response['stands'] = (!empty($stands)) ? $stands : array();
      $response['files'] = (!empty($files)) ? $files : array();

      echo json_encode($response);
   }

   public function download()
   {
      $company_id = $this->input->get('company_id');
      $file_name = $this->input->get('file_name');

      if( empty($company_id) || empty($file_name) )
      {
         header('HTTP/1.1 400 Bad Request',true,400);
         echo 'Required Filed missing! company_id or file_name';
         return false;
      }

      $this->load->helper('download');

      $path = "./assets/uploads/companies/company" . $company_id . "/docs/" . $file_name;

      $data = file_get_contents($path);

      //var_dump($data);

      force_download($file_name, $data);
   }

   public function saveReservation()
   {
      //var_dump($_REQUEST,$_FILES);
      //$this->events_model->do_upload();
      //return;

      $msg = array();

      //----------------- validation

      $data = array();
      $modl = $this->input->post('model');

      if(!empty($modl))
      {
         $data = @json_decode($modl,true);
      }

      $errors = '';
      $required = array(
         'company_name',
         'email',
         'phone',
         'admin_email',
         'event_id',
         'date_from',
         'date_to',
         'stand_id',
      );

      foreach($required as $req)
      {
         if( empty($data[$req]) )
         {
            $errors .= $req . ', ';
         }
      }

      if(empty($_FILES['logo']))$errors.='logo, ';

      $errors = rtrim($errors, ', ');

      if( !empty($errors) )
      {
         header('HTTP/1.1 400 Bad Request',true,400);
         echo 'Required Filed(s) missing! '.$errors;
         return false;
      }

      //------- save company if its not already there in db

      $fields = array(
         'company_id' => (int)$data['company_id'],
         'company_name'=> $data['company_name'],
         'email'=> $data['email'],
         'phone'=> $data['phone'],
         'admin_email'=> $data['admin_email']
      );

      $company_id = $this->events_model->saveCompany($fields);

      if(!$company_id)
      {
         header('HTTP/1.1 Internal server error',true,500);
         echo $this->events_model->error;
         echo ' Details: '.$this->events_model->error_developer;
         return false;
      }

      $msg[] = 'Company Saved Successfully! with id:' . $company_id;

      //------- save reservation

      $data['company_id'] = $company_id;

      $reservation_id = $this->events_model->saveReservation($data);

      if(!$reservation_id)
      {
         header('HTTP/1.1 Internal server error',true,500);
         echo $this->events_model->error;
         echo ' Details: '.$this->events_model->error_developer;
         return false;
      }

      $msg[] = 'Stand reserved successfully! with reservation id:'.$reservation_id;

      //------------------- save logo

      $uploaded = $this->events_model->uploadLogo($company_id);
      //var_dump($uploaded);

      if(!empty($uploaded))
      {
         $fields = array(
            'company_id' => (int)$data['company_id'],
            'logo'=> $uploaded
         );
         $company_updated = $this->events_model->saveCompany($fields);

         /*if(!$company_id)
         {
            header('HTTP/1.1 Internal server error',true,500);
            echo $this->events_model->error;
            echo ' Details: '.$this->events_model->error_developer;
            return false;
         }*/
      }

      //------------------ upload docs (if any)

      $files_errors = array();

      if(!empty($_FILES) && count($_FILES)>1)
      {
         $uploaded_files=array();
         foreach($_FILES as $k=>$v)
         {
            if($k=='logo')continue;
            $uploaded = $this->events_model->uploadDocs($company_id,$k);
            if(!empty($uploaded))
            {
               $uploaded_files[] = $uploaded;
            }
            else
            {
               $files_errors[] = $this->events_model->error;
            }
         }

         //----------- save uploaded files in db
         if(!empty($uploaded_files))
         {
            $saved = $this->events_model->saveDocs($company_id,$uploaded_files);
         }
      }

      echo json_encode(array(
         'company_id' => $company_id,
         'reservation_id' => $reservation_id,
         'files_error' => $files_errors
      ));

   }

   public function register_visit()
   {

      //----------------- validation

      $errors = '';
      $required = array(
         'email',
         'pass',
         'stand_id',
         'event_id',
      );

      foreach($required as $req)
      {
         $v = $this->input->get_post($req);
         if( empty($v) )
         {
            $errors .= $req . ', ';
         }
      }

      $errors = rtrim($errors, ', ');

      if( !empty($errors) )
      {
         header('HTTP/1.1 400 Bad Request',true,400);
         echo 'Required Filed(s) missing! '.$errors;
         return false;
      }

      //------------------------------------------

      $email = $this->input->get_post('email');
      $password = $this->input->get_post('pass');
      $event_id = $this->input->get_post('event_id');
      $stand_id = $this->input->get_post('stand_id');

      $registered = $this->events_model->registerUserVisit($email,$password,$event_id,$stand_id);

      if(empty($registered))
      {
         header('HTTP/1.1 500 Internal sever error',true,400);
         echo $this->events_model->error;
         return false;
      }

      echo 'User visit count registered successfully!';

   }

   /*
    * load all event which is going to end today
    * & send email to company admin
    * i.e.
    * receive a report about the users who visited their stand on the event after it is over.
    * */
   public function sendEventReport()
   {
      $result = $this->events_model->loadEventReport();

      if(!empty($this->events_model->error))
      {
         header('HTTP/1.1 500 Internal sever error',true,400);
         echo $this->events_model->error;
         return false;
      }

      if(empty($result))
      {
         echo 'Nothing to report';
         return false;
      }

      //----------------------

      $this->load->library('email');

      foreach($result as $event)
      {
         $to = $event[0]['admin_email'];
         $mail_subject = "Event reoprt";

         $mail = "
         Hi there,
         Event : ".$event[0]['event_name']."

         From : ".$event[0]['date_from']."

         To : ".$event[0]['date_to']."

         Address : ".$event[0]['address']."

         User Details:

         ";

         foreach($event as $user)
         {
            $mail .= "user:".$user['user_name'];
            $mail .= " visit date:".$user['visit_datetime'];
            $mail .= "
";
         }

         $mail .= "Thanks";

         $this->email->from('info@exposition.com', 'Exposition');
         //$this->email->to($to);
         $this->email->to('mmamjb1@gmail.com');
         $this->email->subject($mail_subject);
         $this->email->message($mail);
         $this->email->send();

         var_dump($mail);
      }

   }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Borrera erinacea Ach.

### Remarks
null


text:
package com.koushikdutta.ion;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.Service;
import android.content.Context;
import android.os.Build;
import android.widget.ImageView;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by koush on 4/15/14.
 */
public abstract class ContextReference<T> extends WeakReference<T> implements IonContext{
    public ContextReference(T context) {
        super(context);
    }

    abstract static class NormalContextReference<T extends Context> extends ContextReference<T> {
        NormalContextReference(T context) {
            super(context);
        }

        static String isAlive(Context context) {
            if (context instanceof Service)
                return ServiceContextReference.isAlive((Service) context);
            if (context instanceof Activity)
                return ActivityContextReference.isAlive((Activity) context);
            return null;
        }

        @Override
        public Context getContext() {
            return get();
        }
    }

    public static class ServiceContextReference extends com.koushikdutta.ion.ContextReference.NormalContextReference<Service> {
        public ServiceContextReference(Service service) {
            super(service);
        }

        static String isAlive(Service candidate) {
            if (candidate == null)
                return "Service reference null";
            ActivityManager manager = (ActivityManager)candidate.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = manager.getRunningServices(Integer.MAX_VALUE);
            if (services == null)
                return "Could not retrieve services from service manager";
            for (ActivityManager.RunningServiceInfo service: services) {
                if (candidate.getClass().getName().equals(service.service.getClassName())) {
                    return null;
                }
            }
            return "Service stopped";
        }

        @Override
        public String isAlive() {
            return isAlive(get());
        }
    }

    public static class ActivityContextReference extends com.koushikdutta.ion.ContextReference.NormalContextReference<Activity> {
        public ActivityContextReference(Activity activity) {
            super(activity);
        }

        static String isAlive(Activity a) {
            if (a == null)
                return "Activity reference null";
            if (a.isFinishing())
                return "Activity finished";
            return null;
        }

        @Override
        public String isAlive() {
            return isAlive(get());
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public static class FragmentContextReference extends ContextReference<Fragment> {
        public FragmentContextReference(Fragment fragment) {
            super(fragment);
        }

        @Override
        public Context getContext() {
            Fragment fragment = get();
            if (fragment == null)
                return null;
            return fragment.getActivity();
        }

        @Override
        public String isAlive() {
            Fragment fragment = get();
            if (fragment == null)
                return "Fragment reference null";
            String ret = ActivityContextReference.isAlive(fragment.getActivity());
            if (ret != null)
                return ret;
            if (fragment.isDetached())
                return "Fragment detached";
            return null;
        }
    }

    public static class SupportFragmentContextReference extends ContextReference<android.support.v4.app.Fragment> {
        public SupportFragmentContextReference(android.support.v4.app.Fragment fragment) {
            super(fragment);
        }

        @Override
        public Context getContext() {
            android.support.v4.app.Fragment fragment = get();
            if (fragment == null)
                return null;
            return fragment.getActivity();
        }

        @Override
        public String isAlive() {
            android.support.v4.app.Fragment fragment = get();
            if (fragment == null)
                return "Fragment reference null";
            String ret = ActivityContextReference.isAlive(fragment.getActivity());
            if (ret != null)
                return ret;
            if (fragment.isDetached())
                return "Fragment detached";
            return null;
        }
    }

    public static class ImageViewContextReference extends ContextReference<ImageView> {
        public ImageViewContextReference(ImageView imageView) {
            super(imageView);
        }

        @Override
        public String isAlive() {
            ImageView iv = get();
            if (iv == null)
                return "ImageView reference null";
            return NormalContextReference.isAlive(iv.getContext());
        }

        @Override
        public Context getContext() {
            ImageView iv = get();
            if (iv == null)
                return null;
            return iv.getContext();
        }
    }

    public static ContextReference fromContext(Context context) {
        if (context instanceof Service)
            return new com.koushikdutta.ion.ContextReference.ServiceContextReference((Service)context);
        if (context instanceof Activity)
            return new com.koushikdutta.ion.ContextReference.ActivityContextReference((Activity)context);

        return new com.koushikdutta.ion.ContextReference.NormalContextReference<Context>(context) {
            @Override
            public String isAlive() {
                Context context = get();
                if (context == null)
                    return "Context reference null";
                return null;
            }
        };
    }
}


text:
require File.expand_path('../../../spec_helper', __FILE__)

ruby_version_is "1.9" do
  describe "Rational#marshal_dump" do
    ruby_version_is "1.9"..."2.0" do
      it "is a public method" do
        Rational.should have_public_instance_method(:marshal_dump, false)
      end
    end

    ruby_version_is "2.0" do
      it "is a private method" do
        Rational.should have_private_instance_method(:marshal_dump, false)
      end
    end

    it "dumps numerator and denominator" do
      Rational(1, 2).send(:marshal_dump).should == [1, 2]
    end
  end
end


text:
namespace blink {

void FloatClipDisplayItem::replay(GraphicsContext* context)
{
    context->save();
    context->clip(m_clipRect);
}

void FloatClipDisplayItem::appendToWebDisplayItemList(WebDisplayItemList* list) const
{
    list->appendFloatClipItem(m_clipRect);
}

void EndFloatClipDisplayItem::replay(GraphicsContext* context)
{
    context->restore();
}

void EndFloatClipDisplayItem::appendToWebDisplayItemList(WebDisplayItemList* list) const
{
    list->appendEndFloatClipItem();
}

#ifndef NDEBUG
void FloatClipDisplayItem::dumpPropertiesAsDebugString(WTF::StringBuilder& stringBuilder) const
{
    DisplayItem::dumpPropertiesAsDebugString(stringBuilder);
    stringBuilder.append(WTF::String::format(", floatClipRect: [%f,%f,%f,%f]}",
        m_clipRect.x(), m_clipRect.y(), m_clipRect.width(), m_clipRect.height()));
}

#endif

} // namespace blink


text:
/**
 * Constants representing all actions
 */
module.exports = require('keymirror')({
	RECIPE_EVENT_CHANGE: null,
	RECIPE_CREATE: null,
	RECIPE_DELETE: null,
	RECIPE_EDIT: null
});


text:
<?php

declare(strict_types = 1);

namespace Apple\ApnPush\Model;

/**
 * Send this notification to device.
 */
class Notification
{
    /**
     * @var Payload
     */
    private $payload;

    /**
     * @var ApnId
     */
    private $apnId;

    /**
     * @var Priority
     */
    private $priority;

    /**
     * @var Expiration
     */
    private $expiration;

    /**
     * @var CollapseId
     */
    private $collapseId;

    /**
     * @var PushType
     */
    private $pushType;

    /**
     * Constructor.
     *
     * @param Payload         $payload
     * @param ApnId|null      $apnId
     * @param Priority|null   $priority
     * @param Expiration|null $expiration
     * @param CollapseId|null $collapseId
     * @param PushType|null   $pushType
     */
    public function __construct(Payload $payload, ApnId $apnId = null, Priority $priority = null, Expiration $expiration = null, CollapseId $collapseId = null, PushType $pushType = null)
    {
        $this->payload = $payload;
        $this->priority = $priority;
        $this->apnId = $apnId;
        $this->expiration = $expiration;
        $this->collapseId = $collapseId;
        $this->pushType = $pushType;
    }

    /**
     * Create new notification with body only
     *
     * @param string $body
     *
     * @return Notification
     */
    public static function createWithBody(string $body): Notification
    {
        return new self(Payload::createWithBody($body));
    }

    /**
     * Set payload
     *
     * @param Payload $payload
     *
     * @return Notification
     */
    public function withPayload(Payload $payload): Notification
    {
        $cloned = clone $this;

        $cloned->payload = $payload;

        return $cloned;
    }

    /**
     * Get payload
     *
     * @return Payload
     */
    public function getPayload(): Payload
    {
        return $this->payload;
    }

    /**
     * Set apn identifier
     *
     * @param ApnId $apnId
     *
     * @return Notification
     */
    public function withApnId(ApnId $apnId = null): Notification
    {
        $cloned = clone $this;

        $cloned->apnId = $apnId;

        return $cloned;
    }

    /**
     * Get identifier of notification
     *
     * @return ApnId
     */
    public function getApnId(): ?ApnId
    {
        return $this->apnId;
    }

    /**
     * Set priority
     *
     * @param Priority $priority
     *
     * @return Notification
     */
    public function withPriority(Priority $priority = null): Notification
    {
        $cloned = clone $this;

        $cloned->priority = $priority;

        return $cloned;
    }

    /**
     * Get priority
     *
     * @return Priority
     */
    public function getPriority(): ?Priority
    {
        return $this->priority;
    }

    /**
     * Set expiration
     *
     * @param Expiration $expiration
     *
     * @return Notification
     */
    public function withExpiration(Expiration $expiration = null): Notification
    {
        $cloned = clone $this;

        $cloned->expiration = $expiration;

        return $cloned;
    }

    /**
     * Get expiration
     *
     * @return Expiration
     */
    public function getExpiration(): ?Expiration
    {
        return $this->expiration;
    }

    /**
     * Set the collapse identifier
     *
     * @param CollapseId|null $collapseId
     *
     * @return Notification
     */
    public function withCollapseId(CollapseId $collapseId = null): Notification
    {
        $cloned = clone $this;

        $cloned->collapseId = $collapseId;

        return $cloned;
    }

    /**
     * Get the collapse identifier
     *
     * @return CollapseId|null
     */
    public function getCollapseId(): ?CollapseId
    {
        return $this->collapseId;
    }

    /**
     * Set the push type
     *
     * @param PushType|null $pushType
     *
     * @return Notification
     */
    public function withPushType(?PushType $pushType): Notification
    {
        $cloned = clone $this;

        $cloned->pushType = $pushType;

        return $cloned;
    }

    /**
     * Get the push type
     *
     * @return PushType|null
     */
    public function getPushType(): ?PushType
    {
        return $this->pushType;
    }
}


text:
За финален проект трябва да се разработи приложение на Swift за iOS. То може да изпозлва допълнителни сървърни технологии, които могат да компенсират за част от оценката. Всеки един студент записал курса трябва да има пряк принос към финалната версия на проекта под формата на код.

Проекти ще се представят на финална презентация и ще бъдат защитавани в отделна техническа сесия с екипа на курса. На презентацията ще присъстват мениджери от няколко фирми, като целта е студентите да получат обратна връзка за тяхните проекти от хора работещи в ИТ бранша, а не само от екипа.

Студентите трябва да се разпределят в екипи от 3 или 4 човека.
Има няколко теми над които може да се работи. За повече информация виж секцията - [Теми](#Теми).

Възможно е да се предложат и други теми за проекти, които трябва да се синхронизират с екипа преди 17 ноември. На 17 ноември всички нови теми ще бъдат представени и студентите ще трябва да изберат топ 4 от предложениете им. Така ще се сформират екипите.

## Теми

* [Eventy](Eventy.md) - приложение за стриймване на събития
* [Arrows](Arrows.md) - мобилна игра за стреляне със лък
* [TattooAR](TattooAR.md) - приложение за визуализране на татуировки чрез добавена реалност Augmented Reality (AR)
* [Shushu-Mushu](Shushu-Mushu.md) - мобилна чат услуга
* (предложение от Кауфланд)

* [getLocal](getLocal.md) - приложение, което ще помага на хората да намират обекти и услуги

## Въпроси и отговори

1. Може ли да предложа собствен проект?

	Да. Предложението трябва да е одобрено от екипа на курса преди 17 ноември

2. Може ли да участвам сам в отбор?

	Индивидуалните кандидатури ще бъдат разглеждани от екипа и е възможно да не бъдат приети. Трябва да имате много добър аргумент.

3. Може ли да участвам сам по реален порект извън курса ФМИ, в който има и други хора и да го представя като финален проект?

	Да, но трябва да са спазени предните точки (т. 1 и т. 2).

4. Как ще стане оценяването?

	Кодът на проекта трябва да е публикуван в github.com. Всички асети и други ресурси, може да не са част от този проект. Ресурсите трябва да носят и съответните права за дистрибуция. Оценяването ще се формира от презентирането на проекта и техническата сесия.


text:
package com.sequenceiq.cloudbreak.cloud;

import java.util.List;

import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudResource;
import com.sequenceiq.cloudbreak.cloud.model.CloudVmInstanceStatus;

/**
 * This interface includes operations that can be executed on individual instances.
 */
public interface InstanceConnector {

    /**
     * Start instances. You can start instances trough this method. It does not need to wait/block until the VM instances are started, but it can return
     * immediately and the {@link #check(AuthenticatedContext, List)} method is invoked to check regularly whether the VM instances have already been started
     * or not.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param resources            resources managed by Cloudbreak, can be used to figure out which resources are associated with the given VMs
     *                             (e.g. floating IP) and they can be started as well
     * @param vms                  VM instances to be started
     * @return status of instances
     */
    List<CloudVmInstanceStatus> start(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms);

    /**
     * A version of instance start which limits the retries that the operation may normally perform.
     *
     * This falls back to the existing {@link #start(AuthenticatedContext, List, List)} implementation
     * if a specific connector does not implement the API.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param resources            resources managed by Cloudbreak, can be used to figure out which resources are associated with the given VMs
     *                             (e.g. floating IP) and they can be started as well
     * @param vms                  VM instances to be started
     * @param timeboundInMs        A timebound in ms for this call.
     * @return status of instances
     */
    default List<CloudVmInstanceStatus> startWithLimitedRetry(AuthenticatedContext authenticatedContext, List<CloudResource> resources,
            List<CloudInstance> vms, Long timeboundInMs) {
        return start(authenticatedContext, resources, vms);
    }

    /**
     * Stop instances. You can stop instances trough this method. It does not need to wait/block until the VM instances are stopped, but it can return
     * immediately and the {@link #check(AuthenticatedContext, List)} method is invoked to check regularly whether the VM instances have already been stopped
     * or not.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param resources            resources managed by Cloudbreak, can be used to figure out which resources are associated with the given VMs
     *                             (e.g. floating IP) and they can be stopped as well
     * @param vms                  VM instances to be stopped
     * @return status of instances
     */
    List<CloudVmInstanceStatus> stop(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms);

    /**
     * A version of instance stop which limits the retries that operation may normally perform.
     *
     * This falls back to the existing {@link #stop(AuthenticatedContext, List, List)} implementation
     * if a specific connector does not implement the API.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param resources            resources managed by Cloudbreak, can be used to figure out which resources are associated with the given VMs
     *                             (e.g. floating IP) and they can be started as well
     * @param vms                  VM instances to be stopped
     * @param timeboundInMs        A timebound in ms for this call.
     * @return status of instances
     */
    default List<CloudVmInstanceStatus> stopWithLimitedRetry(AuthenticatedContext authenticatedContext, List<CloudResource> resources,
            List<CloudInstance> vms, Long timeboundInMs) {
        return stop(authenticatedContext, resources, vms);
    }

    /**
     * Reboot instances. You can reboot instances through this method. It does not need to wait/block until the VM instances are rebooted, but it can return
     * immediately and the {@link #check(AuthenticatedContext, List)} method is invoked to check regularly whether the VM instances have already been started
     * after a reboot or not.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param instanceIds          a VM instances that need to be rebooted.
     * @return status of instances
     */
    List<CloudVmInstanceStatus> reboot(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> instanceIds);

    /**
     * Invoked to check whether the instances have already reached a StatusGroup.PERMANENT state.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param vms                  the VM instances for which the status needs to be checked
     * @return status of instances
     */
    List<CloudVmInstanceStatus> check(AuthenticatedContext authenticatedContext, List<CloudInstance> vms);

    /**
     * Invoked to check whether the instances have already reached a StatusGroup.PERMANENT state. (Retry logic won't be used in this case)
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param vms                  the VM instances for which the status needs to be checked
     * @return status of instances
     */
    default List<CloudVmInstanceStatus> checkWithoutRetry(AuthenticatedContext authenticatedContext, List<CloudInstance> vms) {
        return check(authenticatedContext, vms);
    }

    /**
     * Gets the Consol output of a particular VM, useful for debugging and also required for setting up a secure connection between Cloudbreak and VM instances
     * since the SSH fingerprint is written into the console output.
     *
     * @param authenticatedContext the authenticated context which holds the client object
     * @param vm                   the VM instance
     * @return the consol output as text
     */
    String getConsoleOutput(AuthenticatedContext authenticatedContext, CloudInstance vm);

}


text:
SET client_encoding TO UTF8;

CREATE TABLE unicode_test (
    testvalue  text NOT NULL
);

CREATE FUNCTION unicode_return() RETURNS text AS $$
  return "\xA0"
$$ LANGUAGE pltcl;

CREATE FUNCTION unicode_trigger() RETURNS trigger AS $$
  set NEW(testvalue) "\xA0"
  return [array get NEW]
$$ LANGUAGE pltcl;

CREATE TRIGGER unicode_test_bi BEFORE INSERT ON unicode_test
  FOR EACH ROW EXECUTE PROCEDURE unicode_trigger();

CREATE FUNCTION unicode_plan1() RETURNS text AS $$
  set plan [ spi_prepare {SELECT $1 AS testvalue} [ list "text" ] ]
  spi_execp $plan [ list "\xA0" ]
  return $testvalue
$$ LANGUAGE pltcl;

SELECT unicode_return();
INSERT INTO unicode_test (testvalue) VALUES ('test');
SELECT * FROM unicode_test;
SELECT unicode_plan1();