text:
package com.github.manasg.logging;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;

public class RemoteAppender extends AppenderSkeleton {
    protected String destination = "localhost:2464";
    protected String environment = "unknown_env";
    protected String hostname = "";

    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    private String getDestinationURL() {
        StringBuffer sb = new StringBuffer();
        sb.append("http://").append(this.destination).append("/api/log");
        return sb.toString();
    }

    public String getEnvironment() {
        return environment;
    }

    public void setEnvironment(String environment) {
        this.environment = environment;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    public RemoteAppender() {
        // default
        this.setThreshold(Level.WARN);

        // try to get the IP/hostname
        try {
            this.hostname = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            this.hostname = "unknown";
        }

    }

    @Override
    public void close() {
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    @Override
    protected void append(LoggingEvent arg0) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(getDestinationURL());

        try {
            String payload = AmonPayload.AmonPayloadJson(arg0,getEnvironment(),hostname);
            httpPost.setEntity(new StringEntity(payload));
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse response2 = httpclient.execute(httpPost);

            //System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);

        } catch (Exception e) {

        } finally {
            httpPost.releaseConnection();
        }
    }

}


text:
"""This file contains functions and variables used for time manipulations.

This file should contain common methods that can be used in Plaso to convert
timestamps in various formats into the standard micro seconds precision integer
Epoch UTC time that is used internally to store timestamps in Plaso.

The file can also contain common functions to change the default timestamp into
a more human readable one.
"""

import calendar
import datetime
import dateutil.parser
import logging
import time
import pytz

MONTH_DICT = {
    'jan': 1,
    'feb': 2,
    'mar': 3,
    'apr': 4,
    'may': 5,
    'jun': 6,
    'jul': 7,
    'aug': 8,
    'sep': 9,
    'oct': 10,
    'nov': 11,
    'dec': 12}

class Timestamp(object):
  """Class for converting timestamps to plaso timestamps.

    The Plaso timestamp is a 64-bit signed timestamp value containing:
    micro seconds since 1970-01-01 00:00:00.

    The timestamp is not necessarily in UTC.
  """
  # The minimum timestamp in seconds
  TIMESTAMP_MIN_SECONDS = -(((1 << 63L) - 1) / 1000000)

  # The maximum timestamp in seconds
  TIMESTAMP_MAX_SECONDS = ((1 << 63L) - 1) / 1000000

  # The minimum timestamp in micro seconds
  TIMESTAMP_MIN_MICRO_SECONDS = -((1 << 63L) - 1)

  # The maximum timestamp in micro seconds
  TIMESTAMP_MAX_MICRO_SECONDS = (1 << 63L) - 1

  # The days per month of a non leap year
  DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

  # The number of seconds in a day
  SECONDS_PER_DAY = 24 * 60 * 60

  # The number of micro seconds per second
  MICRO_SECONDS_PER_SECOND = 1000000

  # The multiplication factor to change milli seconds to micro seconds.
  MILLI_SECONDS_TO_MICRO_SECONDS = 1000

  # The difference between Jan 1, 1980 and Jan 1, 1970 in seconds.
  FAT_DATE_TO_POSIX_BASE = 315532800

  # The difference between Jan 1, 1601 and Jan 1, 1970 in micro seconds
  WEBKIT_TIME_TO_POSIX_BASE = 11644473600L * 1000000

  # The difference between Jan 1, 1601 and Jan 1, 1970 in 100th of nano seconds.
  FILETIME_TO_POSIX_BASE = 11644473600L * 10000000

  # The number of seconds between January 1, 1904 and Jan 1, 1970.
  # Value confirmed with sleuthkit:
  #  http://svn.sleuthkit.org/repos/sleuthkit/trunk/tsk3/fs/tsk_hfs.h
  # and linux source file linux/include/linux/hfsplus_fs.h
  HFSTIME_TO_POSIX_BASE = 2082844800

  # The number of seconds between January 1, 1970 and January 1, 2001.
  # As specified in:
  # https://developer.apple.com/library/ios/documentation/
  #       cocoa/Conceptual/DatesAndTimes/Articles/dtDates.html
  COCOA_TIME_TO_POSIX_BASE = 978307200

  # The difference between POSIX (Jan 1, 1970) and DELPHI (Dec 30, 1899).
  # http://docwiki.embarcadero.com/Libraries/XE3/en/System.TDateTime
  DELPHI_TIME_TO_POSIX_BASE = 25569

  @classmethod
  def CopyToDatetime(cls, timestamp, timezone):
    """Copies the timestamp to a datetime object.

    Args:
      timestamp: An integer containing the timestamp.
      timezone: The timezone (pytz.timezone) object.

    Returns:
      A datetime object.
    """
    datetime_object = datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.utc)
    try:
      datetime_object += datetime.timedelta(microseconds=timestamp)
      return datetime_object.astimezone(timezone)
    except OverflowError as exception:
      logging.error(
          u'Unable to copy {0:d} to a datetime object with error: {1:s}'.format(
              timestamp, exception))

    return datetime_object

  @classmethod
  def CopyToIsoFormat(cls, timestamp, timezone=pytz.utc):
    """Copies the timestamp to an ISO 8601 formatted string.

    Args:
      timestamp: An integer containing the timestamp.
      timezone: Optional timezone (instance of pytz.timezone).
                The default is UTC.

    Returns:
      A string containing an ISO 8601 formatted date and time.
    """
    datetime_object = cls.CopyToDatetime(timestamp, timezone)
    return datetime_object.isoformat()

  @classmethod
  def CopyToPosix(cls, timestamp):
    """Converts microsecond timestamps to POSIX timestamps.

    Args:
      timestamp: An integer containing the microsecond timestamp.

    Returns:
      An integer value containing the timestamp.
    """
    return timestamp // cls.MICRO_SECONDS_PER_SECOND

  @classmethod
  def DaysInMonth(cls, month, year):
    """Determines the days in a month for a specific year.

    Args:
      month: The month where 0 represents January.
      year: The year as in 1970.

    Returns:
      An integer containing the number of days in the month.

    Raises:
      ValueError: if the month value is invalid.
    """
    if month not in range(0, 12):
      raise ValueError(u'Invalid month value')

    days_per_month = cls.DAYS_PER_MONTH[month]

    if month == 1 and cls.IsLeapYear(year):
      days_per_month += 1

    return days_per_month

  @classmethod
  def DaysInYear(cls, year):
    """Determines the days in a year.

    Args:
      year: The year as in 1970.

    Returns:
      An integer containing the number of days in the year.
    """
    days_in_year = 365
    if cls.IsLeapYear(year):
      return days_in_year + 1
    return days_in_year

  @classmethod
  def DayOfYear(cls, day, month, year):
    """Determines the day of the year for a specific day of a month in a year.

    Args:
      day: The day of the month where 0 represents the first day.
      month: The month where 0 represents January.
      year: The year as in 1970.

    Returns:
      An integer containing the day of year.
    """
    day_of_year = day

    for past_month in range(0, month):
      day_of_year += cls.DaysInMonth(past_month, year)

    return day_of_year

  @classmethod
  def FromCocoaTime(cls, cocoa_time):
    """Converts a Cocoa time to a timestamp.

    In Cocoa, time and date values are stored in a unsigned 32-bit integer
    containing the number of seconds since January 1, 2001 at 00:00:00
    (midnight) UTC (GMT).

    Args:
      cocoa_time: The timestamp in Cocoa format.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    return cls.FromPosixTime(cocoa_time + cls.COCOA_TIME_TO_POSIX_BASE)

  @classmethod
  def FromDelphiTime(cls, delphi_time):
    """Converts a Delphi time to a timestamp.

    In Delphi, time and date values (TDateTime)
    are stored in a unsigned little endian 64-bit
    floating point containing the number of seconds
    since December 30, 1899 at 00:00:00 (midnight) Local Timezone.
    TDateTime does not have any time zone information.

    Args:
      delphi_time: The timestamp in Delphi format.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    posix_time = (delphi_time - cls.DELPHI_TIME_TO_POSIX_BASE) * 86400.0
    if (posix_time < cls.TIMESTAMP_MIN_SECONDS or
        posix_time > cls.TIMESTAMP_MAX_SECONDS):
      return 0

    return cls.FromPosixTime(int(posix_time))

  @classmethod
  def FromFatDateTime(cls, fat_date_time):
    """Converts a FAT date and time into a timestamp.

    FAT date time is mainly used in DOS/Windows file formats and FAT.

    The FAT date and time is a 32-bit value containing two 16-bit values:
      * The date (lower 16-bit).
        * bits 0 - 4:  day of month, where 1 represents the first day
        * bits 5 - 8:  month of year, where 1 represent January
        * bits 9 - 15: year since 1980
      * The time of day (upper 16-bit).
        * bits 0 - 4: seconds (in 2 second intervals)
        * bits 5 - 10: minutes
        * bits 11 - 15: hours

    Args:
      fat_date_time: The 32-bit FAT date time.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    number_of_seconds = cls.FAT_DATE_TO_POSIX_BASE

    day_of_month = (fat_date_time & 0x1f) - 1
    month = ((fat_date_time >> 5) & 0x0f) - 1
    year = (fat_date_time >> 9) & 0x7f

    if day_of_month < 0 or day_of_month > 30 or month < 0 or month > 11:
      return 0

    number_of_days = cls.DayOfYear(day_of_month, month, 1980 + year)
    for past_year in range(0, year):
      number_of_days += cls.DaysInYear(past_year)

    fat_date_time >>= 16

    seconds = (fat_date_time & 0x1f) * 2
    minutes = (fat_date_time >> 5) & 0x3f
    hours = (fat_date_time >> 11) & 0x1f

    if hours > 23 or minutes > 59 or seconds > 59:
      return 0

    number_of_seconds += (((hours * 60) + minutes) * 60) + seconds

    number_of_seconds += number_of_days * cls.SECONDS_PER_DAY

    return number_of_seconds * cls.MICRO_SECONDS_PER_SECOND

  @classmethod
  def FromFiletime(cls, filetime):
    """Converts a FILETIME into a timestamp.

    FILETIME is mainly used in Windows file formats and NTFS.

    The FILETIME is a 64-bit value containing:
      100th nano seconds since 1601-01-01 00:00:00

    Technically FILETIME consists of 2 x 32-bit parts and is presumed
    to be unsigned.

    Args:
      filetime: The 64-bit FILETIME timestamp.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    # TODO: Add a handling for if the timestamp equals to zero.
    if filetime < 0:
      return 0
    timestamp = (filetime - cls.FILETIME_TO_POSIX_BASE) / 10

    if timestamp > cls.TIMESTAMP_MAX_MICRO_SECONDS:
      return 0
    return timestamp

  @classmethod
  def FromHfsTime(cls, hfs_time, timezone=pytz.utc, is_dst=False):
    """Converts a HFS time to a timestamp.

    HFS time is the same as HFS+ time, except stored in the local
    timezone of the user.

    Args:
      hfs_time: Timestamp in the hfs format (32 bit unsigned int).
      timezone: The timezone object of the system's local time.
      is_dst: A boolean to indicate the timestamp is corrected for daylight
              savings time (DST) only used for the DST transition period.
              The default is false.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    timestamp_local = cls.FromHfsPlusTime(hfs_time)
    return cls.LocaltimeToUTC(timestamp_local, timezone, is_dst)

  @classmethod
  def FromHfsPlusTime(cls, hfs_time):
    """Converts a HFS+ time to a timestamp.

    In HFS+ date and time values are stored in an unsigned 32-bit integer
    containing the number of seconds since January 1, 1904 at 00:00:00
    (midnight) UTC (GMT).

    Args:
      hfs_time: The timestamp in HFS+ format.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    return cls.FromPosixTime(hfs_time - cls.HFSTIME_TO_POSIX_BASE)

  @classmethod
  def FromJavaTime(cls, java_time):
    """Converts a Java time to a timestamp.

    Jave time is the number of milliseconds since
    January 1, 1970, 00:00:00 UTC.

    URL: http://docs.oracle.com/javase/7/docs/api/
         java/sql/Timestamp.html#getTime%28%29

    Args:
      java_time: The Java Timestamp.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    return java_time * cls.MILLI_SECONDS_TO_MICRO_SECONDS

  @classmethod
  def FromPosixTime(cls, posix_time):
    """Converts a POSIX timestamp into a timestamp.

    The POSIX time is a signed 32-bit or 64-bit value containing:
      seconds since 1970-01-01 00:00:00

    Args:
      posix_time: The POSIX timestamp.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    if (posix_time < cls.TIMESTAMP_MIN_SECONDS or
        posix_time > cls.TIMESTAMP_MAX_SECONDS):
      return 0
    return int(posix_time) * cls.MICRO_SECONDS_PER_SECOND

  @classmethod
  def FromPosixTimeWithMicrosecond(cls, posix_time, microsecond):
    """Converts a POSIX timestamp with microsecond into a timestamp.

    The POSIX time is a signed 32-bit or 64-bit value containing:
      seconds since 1970-01-01 00:00:00

    Args:
      posix_time: The POSIX timestamp.
      microsecond: The microseconds to add to the timestamp.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    timestamp = cls.FromPosixTime(posix_time)
    if not timestamp:
      return 0
    return timestamp + microsecond

  @classmethod
  def FromPythonDatetime(cls, datetime_object):
    """Converts a Python datetime object into a timestamp."""
    if not isinstance(datetime_object, datetime.datetime):
      return 0

    posix_epoch = int(calendar.timegm(datetime_object.utctimetuple()))
    epoch = cls.FromPosixTime(posix_epoch)
    return epoch + datetime_object.microsecond

  @classmethod
  def FromTimeParts(
      cls, year, month, day, hour, minutes, seconds, microseconds=0,
      timezone=pytz.utc):
    """Converts a list of time entries to a timestamp.

    Args:
      year: An integer representing the year.
      month: An integer between 1 and 12.
      day: An integer representing the number of day in the month.
      hour: An integer representing the hour, 0 <= hour < 24.
      minutes: An integer, 0 <= minute < 60.
      seconds: An integer, 0 <= second < 60.
      microseconds: Optional number of microseconds ranging from:
                    0 <= microsecond < 1000000. The default is 0.
      timezone: Optional timezone (instance of pytz.timezone).
                The default is UTC.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    try:
      date = datetime.datetime(
          year, month, day, hour, minutes, seconds, microseconds)
    except ValueError as exception:
      logging.warning((
          u'Unable to create timestamp from {0:04d}-{1:02d}-{2:02d} '
          u'{3:02d}:{4:02d}:{5:02d}.{6:06d} with error: {7:s}').format(
              year, month, day, hour, minutes, seconds, microseconds,
              exception))
      return 0

    if type(timezone) is str:
      timezone = pytz.timezone(timezone)

    date_use = timezone.localize(date)
    epoch = int(calendar.timegm(date_use.utctimetuple()))

    return cls.FromPosixTime(epoch) + microseconds

  @classmethod
  def FromTimeString(
      cls, time_string, timezone=pytz.utc, dayfirst=False,
      gmt_as_timezone=True):
    """Converts a string containing a date and time value into a timestamp.

    Args:
      time_string: String that contains a date and time value.
      timezone: Optional timezone object (instance of pytz.timezone) that
                the data and time value in the string represents. This value
                is used when the timezone cannot be determined from the string.
      dayfirst: An optional boolean argument. If set to true then the
                parser will change the precedence in which it parses timestamps
                from MM-DD-YYYY to DD-MM-YYYY (and YYYY-MM-DD will be
                YYYY-DD-MM, etc).
      gmt_as_timezone: Sometimes the dateutil parser will interpret GMT and UTC
                       the same way, that is not make a distinction. By default
                       this is set to true, that is GMT can be intepreted
                       differently than UTC. If that is not the expected result
                       this attribute can be set to false.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    datetime_object = StringToDatetime(
        time_string, timezone=timezone, dayfirst=dayfirst,
        gmt_as_timezone=gmt_as_timezone)
    return cls.FromPythonDatetime(datetime_object)

  @classmethod
  def FromWebKitTime(cls, webkit_time):
    """Converts a WebKit time into a timestamp.

    The WebKit time is a 64-bit value containing:
      micro seconds since 1601-01-01 00:00:00

    Args:
      webkit_time: The 64-bit WebKit time timestamp.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    if webkit_time < (cls.TIMESTAMP_MIN_MICRO_SECONDS +
                      cls.WEBKIT_TIME_TO_POSIX_BASE):
      return 0
    return webkit_time - cls.WEBKIT_TIME_TO_POSIX_BASE

  @classmethod
  def GetNow(cls):
    """Retrieves the current time (now) as a timestamp in UTC."""
    time_elements = time.gmtime()
    return calendar.timegm(time_elements) * 1000000

  @classmethod
  def IsLeapYear(cls, year):
    """Determines if a year is a leap year.

       A leap year is dividable by 4 and not by 100 or by 400
       without a remainder.

    Args:
      year: The year as in 1970.

    Returns:
      A boolean value indicating the year is a leap year.
    """
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

  @classmethod
  def LocaltimeToUTC(cls, timestamp, timezone, is_dst=False):
    """Converts the timestamp in localtime of the timezone to UTC.

    Args:
      timestamp: An integer containing the timestamp.
      timezone: The timezone (pytz.timezone) object.
      is_dst: A boolean to indicate the timestamp is corrected for daylight
              savings time (DST) only used for the DST transition period.
              The default is false.

    Returns:
      An integer containing the timestamp or 0 on error.
    """
    if timezone and timezone != pytz.utc:
      datetime_object = (
          datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=None) +
          datetime.timedelta(microseconds=timestamp))

      # Check if timezone is UTC since utcoffset() does not support is_dst
      # for UTC and will raise.
      datetime_delta = timezone.utcoffset(datetime_object, is_dst=is_dst)
      seconds_delta = int(datetime_delta.total_seconds())
      timestamp -= seconds_delta * cls.MICRO_SECONDS_PER_SECOND

    return timestamp

  @classmethod
  def RoundToSeconds(cls, timestamp):
    """Takes a timestamp value and rounds it to a second precision."""
    leftovers = timestamp % cls.MICRO_SECONDS_PER_SECOND
    scrubbed = timestamp - leftovers
    rounded = round(float(leftovers) / cls.MICRO_SECONDS_PER_SECOND)

    return int(scrubbed + rounded * cls.MICRO_SECONDS_PER_SECOND)

def StringToDatetime(
    time_string, timezone=pytz.utc, dayfirst=False, gmt_as_timezone=True):
  """Converts a string representation of a timestamp into a datetime object.

  Args:
    time_string: String that contains a date and time value.
    timezone: Optional timezone object (instance of pytz.timezone) that
               the data and time value in the string represents. This value
               is used when the timezone cannot be determined from the string.
    dayfirst: An optional boolean argument. If set to true then the
              parser will change the precedence in which it parses timestamps
              from MM-DD-YYYY to DD-MM-YYYY (and YYYY-MM-DD will be YYYY-DD-MM,
              etc).
    gmt_as_timezone: Sometimes the dateutil parser will interpret GMT and UTC
                     the same way, that is not make a distinction. By default
                     this is set to true, that is GMT can be intepreted
                     differently than UTC. If that is not the expected result
                     this attribute can be set to false.

  Returns:
    A datetime object.
  """
  if not gmt_as_timezone and time_string.endswith(' GMT'):
    time_string = u'{0:s}UTC'.format(time_string[:-3])

  try:
    datetime_object = dateutil.parser.parse(time_string, dayfirst=dayfirst)

  except (TypeError, ValueError) as exception:
    logging.error(
        u'Unable to copy {0:s} to a datetime object with error: {1:s}'.format(
            time_string, exception))
    return datetime.datetime(1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.utc)

  if datetime_object.tzinfo:
    return datetime_object.astimezone(pytz.utc)

  return timezone.localize(datetime_object)

def GetCurrentYear():
  """Determines the current year."""
  datetime_object = datetime.datetime.now()
  return datetime_object.year

redpajama_set_name: RedPajamaGithub


text:
"""Affinity Propagation clustering algorithm."""

# Author: Alexandre Gramfort alexandre.gramfort@inria.fr
#        Gael Varoquaux gael.varoquaux@normalesup.org

# License: BSD 3 clause

import numpy as np
import warnings

from ..exceptions import ConvergenceWarning
from ..base import BaseEstimator, ClusterMixin
from ..utils import as_float_array, check_random_state
from ..utils.deprecation import deprecated
from ..utils.validation import check_is_fitted, _deprecate_positional_args
from ..metrics import euclidean_distances
from ..metrics import pairwise_distances_argmin
from .._config import config_context

def _equal_similarities_and_preferences(S, preference):
    def all_equal_preferences():
        return np.all(preference == preference.flat[0])

    def all_equal_similarities():
        # Create mask to ignore diagonal of S
        mask = np.ones(S.shape, dtype=bool)
        np.fill_diagonal(mask, 0)

        return np.all(S[mask].flat == S[mask].flat[0])

    return all_equal_preferences() and all_equal_similarities()

@_deprecate_positional_args
def affinity_propagation(S, *, preference=None, convergence_iter=15,
                         max_iter=200, damping=0.5, copy=True, verbose=False,
                         return_n_iter=False, random_state='warn'):
    """Perform Affinity Propagation Clustering of data.

    Read more in the :ref:`User Guide <affinity_propagation>`.

    Parameters
    ----------

    S : array-like of shape (n_samples, n_samples)
        Matrix of similarities between points.

    preference : array-like of shape (n_samples,) or float, default=None
        Preferences for each point - points with larger values of
        preferences are more likely to be chosen as exemplars. The number of
        exemplars, i.e. of clusters, is influenced by the input preferences
        value. If the preferences are not passed as arguments, they will be
        set to the median of the input similarities (resulting in a moderate
        number of clusters). For a smaller amount of clusters, this can be set
        to the minimum value of the similarities.

    convergence_iter : int, default=15
        Number of iterations with no change in the number
        of estimated clusters that stops the convergence.

    max_iter : int, default=200
        Maximum number of iterations

    damping : float, default=0.5
        Damping factor between 0.5 and 1.

    copy : bool, default=True
        If copy is False, the affinity matrix is modified inplace by the
        algorithm, for memory efficiency.

    verbose : bool, default=False
        The verbosity level.

    return_n_iter : bool, default=False
        Whether or not to return the number of iterations.

    random_state : int, RandomState instance or None, default=0
        Pseudo-random number generator to control the starting state.
        Use an int for reproducible results across function calls.
        See the :term:`Glossary <random_state>`.

        .. versionadded:: 0.23
            this parameter was previously hardcoded as 0.

    Returns
    -------

    cluster_centers_indices : ndarray of shape (n_clusters,)
        Index of clusters centers.

    labels : ndarray of shape (n_samples,)
        Cluster labels for each point.

    n_iter : int
        Number of iterations run. Returned only if `return_n_iter` is
        set to True.

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_affinity_propagation.py
    <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`.

    When the algorithm does not converge, it returns an empty array as
    ``cluster_center_indices`` and ``-1`` as label for each training sample.

    When all training samples have equal similarities and equal preferences,
    the assignment of cluster centers and labels depends on the preference.
    If the preference is smaller than the similarities, a single cluster center
    and label ``0`` for every sample will be returned. Otherwise, every
    training sample becomes its own cluster center and is assigned a unique
    label.

    References
    ----------
    Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
    Between Data Points", Science Feb. 2007
    """
    S = as_float_array(S, copy=copy)
    n_samples = S.shape[0]

    if S.shape[0] != S.shape[1]:
        raise ValueError("S must be a square array (shape=%s)" % repr(S.shape))

    if preference is None:
        preference = np.median(S)
    if damping < 0.5 or damping >= 1:
        raise ValueError('damping must be >= 0.5 and < 1')

    preference = np.array(preference)

    if (n_samples == 1 or
            _equal_similarities_and_preferences(S, preference)):
        # It makes no sense to run the algorithm in this case, so return 1 or
        # n_samples clusters, depending on preferences
        warnings.warn("All samples have mutually equal similarities. "
                      "Returning arbitrary cluster center(s).")
        if preference.flat[0] >= S.flat[n_samples - 1]:
            return ((np.arange(n_samples), np.arange(n_samples), 0)
                    if return_n_iter
                    else (np.arange(n_samples), np.arange(n_samples)))
        else:
            return ((np.array([0]), np.array([0] * n_samples), 0)
                    if return_n_iter
                    else (np.array([0]), np.array([0] * n_samples)))

    if random_state == 'warn':
        warnings.warn(
            "'random_state' has been introduced in 0.23. It will be set to "
            "None starting from 1.0 (renaming of 0.25) which means that "
            "results will differ at every function call. Set 'random_state' "
            "to None to silence this warning, or to 0 to keep the behavior of "
            "versions <0.23.",
            FutureWarning
        )
        random_state = 0
    random_state = check_random_state(random_state)

    # Place preference on the diagonal of S
    S.flat[::(n_samples + 1)] = preference

    A = np.zeros((n_samples, n_samples))
    R = np.zeros((n_samples, n_samples))  # Initialize messages
    # Intermediate results
    tmp = np.zeros((n_samples, n_samples))

    # Remove degeneracies
    S += ((np.finfo(S.dtype).eps * S + np.finfo(S.dtype).tiny * 100) *
          random_state.randn(n_samples, n_samples))

    # Execute parallel affinity propagation updates
    e = np.zeros((n_samples, convergence_iter))

    ind = np.arange(n_samples)

    for it in range(max_iter):
        # tmp = A + S; compute responsibilities
        np.add(A, S, tmp)
        I = np.argmax(tmp, axis=1)
        Y = tmp[ind, I]  # np.max(A + S, axis=1)
        tmp[ind, I] = -np.inf
        Y2 = np.max(tmp, axis=1)

        # tmp = Rnew
        np.subtract(S, Y[:, None], tmp)
        tmp[ind, I] = S[ind, I] - Y2

        # Damping
        tmp *= 1 - damping
        R *= damping
        R += tmp

        # tmp = Rp; compute availabilities
        np.maximum(R, 0, tmp)
        tmp.flat[::n_samples + 1] = R.flat[::n_samples + 1]

        # tmp = -Anew
        tmp -= np.sum(tmp, axis=0)
        dA = np.diag(tmp).copy()
        tmp.clip(0, np.inf, tmp)
        tmp.flat[::n_samples + 1] = dA

        # Damping
        tmp *= 1 - damping
        A *= damping
        A -= tmp

        # Check for convergence
        E = (np.diag(A) + np.diag(R)) > 0
        e[:, it % convergence_iter] = E
        K = np.sum(E, axis=0)

        if it >= convergence_iter:
            se = np.sum(e, axis=1)
            unconverged = (np.sum((se == convergence_iter) + (se == 0))
                           != n_samples)
            if (not unconverged and (K > 0)) or (it == max_iter):
                never_converged = False
                if verbose:
                    print("Converged after %d iterations." % it)
                break
    else:
        never_converged = True
        if verbose:
            print("Did not converge")

    I = np.flatnonzero(E)
    K = I.size  # Identify exemplars

    if K > 0 and not never_converged:
        c = np.argmax(S[:, I], axis=1)
        c[I] = np.arange(K)  # Identify clusters
        # Refine the final set of exemplars and clusters and return results
        for k in range(K):
            ii = np.where(c == k)[0]
            j = np.argmax(np.sum(S[ii[:, np.newaxis], ii], axis=0))
            I[k] = ii[j]

        c = np.argmax(S[:, I], axis=1)
        c[I] = np.arange(K)
        labels = I[c]
        # Reduce labels to a sorted, gapless, list
        cluster_centers_indices = np.unique(labels)
        labels = np.searchsorted(cluster_centers_indices, labels)
    else:
        warnings.warn("Affinity propagation did not converge, this model "
                      "will not have any cluster centers.", ConvergenceWarning)
        labels = np.array([-1] * n_samples)
        cluster_centers_indices = []

    if return_n_iter:
        return cluster_centers_indices, labels, it + 1
    else:
        return cluster_centers_indices, labels

###############################################################################

class AffinityPropagation(ClusterMixin, BaseEstimator):
    """Perform Affinity Propagation Clustering of data.

    Read more in the :ref:`User Guide <affinity_propagation>`.

    Parameters
    ----------
    damping : float, default=0.5
        Damping factor (between 0.5 and 1) is the extent to
        which the current value is maintained relative to
        incoming values (weighted 1 - damping). This in order
        to avoid numerical oscillations when updating these
        values (messages).

    max_iter : int, default=200
        Maximum number of iterations.

    convergence_iter : int, default=15
        Number of iterations with no change in the number
        of estimated clusters that stops the convergence.

    copy : bool, default=True
        Make a copy of input data.

    preference : array-like of shape (n_samples,) or float, default=None
        Preferences for each point - points with larger values of
        preferences are more likely to be chosen as exemplars. The number
        of exemplars, ie of clusters, is influenced by the input
        preferences value. If the preferences are not passed as arguments,
        they will be set to the median of the input similarities.

    affinity : {'euclidean', 'precomputed'}, default='euclidean'
        Which affinity to use. At the moment 'precomputed' and
        ``euclidean`` are supported. 'euclidean' uses the
        negative squared euclidean distance between points.

    verbose : bool, default=False
        Whether to be verbose.

    random_state : int, RandomState instance or None, default=0
        Pseudo-random number generator to control the starting state.
        Use an int for reproducible results across function calls.
        See the :term:`Glossary <random_state>`.

        .. versionadded:: 0.23
            this parameter was previously hardcoded as 0.

    Attributes
    ----------
    cluster_centers_indices_ : ndarray of shape (n_clusters,)
        Indices of cluster centers.

    cluster_centers_ : ndarray of shape (n_clusters, n_features)
        Cluster centers (if affinity != ``precomputed``).

    labels_ : ndarray of shape (n_samples,)
        Labels of each point.

    affinity_matrix_ : ndarray of shape (n_samples, n_samples)
        Stores the affinity matrix used in ``fit``.

    n_iter_ : int
        Number of iterations taken to converge.

    Notes
    -----
    For an example, see :ref:`examples/cluster/plot_affinity_propagation.py
    <sphx_glr_auto_examples_cluster_plot_affinity_propagation.py>`.

    The algorithmic complexity of affinity propagation is quadratic
    in the number of points.

    When ``fit`` does not converge, ``cluster_centers_`` becomes an empty
    array and all training samples will be labelled as ``-1``. In addition,
    ``predict`` will then label every sample as ``-1``.

    When all training samples have equal similarities and equal preferences,
    the assignment of cluster centers and labels depends on the preference.
    If the preference is smaller than the similarities, ``fit`` will result in
    a single cluster center and label ``0`` for every sample. Otherwise, every
    training sample becomes its own cluster center and is assigned a unique
    label.

    References
    ----------

    Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages
    Between Data Points", Science Feb. 2007

    Examples
    --------
    >>> from sklearn.cluster import AffinityPropagation
    >>> import numpy as np
    >>> X = np.array([[1, 2], [1, 4], [1, 0],
    ...               [4, 2], [4, 4], [4, 0]])
    >>> clustering = AffinityPropagation(random_state=5).fit(X)
    >>> clustering
    AffinityPropagation(random_state=5)
    >>> clustering.labels_
    array([0, 0, 0, 1, 1, 1])
    >>> clustering.predict([[0, 0], [4, 4]])
    array([0, 1])
    >>> clustering.cluster_centers_
    array([[1, 2],
           [4, 2]])
    """
    @_deprecate_positional_args
    def __init__(self, *, damping=.5, max_iter=200, convergence_iter=15,
                 copy=True, preference=None, affinity='euclidean',
                 verbose=False, random_state='warn'):

        self.damping = damping
        self.max_iter = max_iter
        self.convergence_iter = convergence_iter
        self.copy = copy
        self.verbose = verbose
        self.preference = preference
        self.affinity = affinity
        self.random_state = random_state

    # TODO: Remove in 1.1
    # mypy error: Decorated property not supported
    @deprecated("Attribute _pairwise was deprecated in "  # type: ignore
                "version 0.24 and will be removed in 1.1 (renaming of 0.26).")
    @property
    def _pairwise(self):
        return self.affinity == "precomputed"

    def _more_tags(self):
        return {'pairwise': self.affinity == 'precomputed'}

    def fit(self, X, y=None):
        """Fit the clustering from features, or affinity matrix.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
                array-like of shape (n_samples, n_samples)
            Training instances to cluster, or similarities / affinities between
            instances if ``affinity='precomputed'``. If a sparse feature matrix
            is provided, it will be converted into a sparse ``csr_matrix``.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        self

        """
        if self.affinity == "precomputed":
            accept_sparse = False
        else:
            accept_sparse = 'csr'
        X = self._validate_data(X, accept_sparse=accept_sparse)
        if self.affinity == "precomputed":
            self.affinity_matrix_ = X
        elif self.affinity == "euclidean":
            self.affinity_matrix_ = -euclidean_distances(X, squared=True)
        else:
            raise ValueError("Affinity must be 'precomputed' or "
                             "'euclidean'. Got %s instead"
                             % str(self.affinity))

        self.cluster_centers_indices_, self.labels_, self.n_iter_ = \
            affinity_propagation(
                self.affinity_matrix_, preference=self.preference,
                max_iter=self.max_iter,
                convergence_iter=self.convergence_iter, damping=self.damping,
                copy=self.copy, verbose=self.verbose, return_n_iter=True,
                random_state=self.random_state)

        if self.affinity != "precomputed":
            self.cluster_centers_ = X[self.cluster_centers_indices_].copy()

        return self

    def predict(self, X):
        """Predict the closest cluster each sample in X belongs to.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features)
            New data to predict. If a sparse matrix is provided, it will be
            converted into a sparse ``csr_matrix``.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Cluster labels.
        """
        check_is_fitted(self)
        X = self._validate_data(X, reset=False)
        if not hasattr(self, "cluster_centers_"):
            raise ValueError("Predict method is not supported when "
                             "affinity='precomputed'.")

        if self.cluster_centers_.shape[0] > 0:
            with config_context(assume_finite=True):
                return pairwise_distances_argmin(X, self.cluster_centers_)
        else:
            warnings.warn("This model does not have any cluster centers "
                          "because affinity propagation did not converge. "
                          "Labeling every sample as '-1'.", ConvergenceWarning)
            return np.array([-1] * X.shape[0])

    def fit_predict(self, X, y=None):
        """Fit the clustering from features or affinity matrix, and return
        cluster labels.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
                array-like of shape (n_samples, n_samples)
            Training instances to cluster, or similarities / affinities between
            instances if ``affinity='precomputed'``. If a sparse feature matrix
            is provided, it will be converted into a sparse ``csr_matrix``.

        y : Ignored
            Not used, present here for API consistency by convention.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            Cluster labels.
        """
        return super().fit_predict(X, y)


text:
import * as React from 'react';
import { ConferenceStream, ChromeExtension, DownloadUtil } from 'react-conf-webrtc';

interface IMediaStreamControlProps {
    audioEnabled: boolean;
    videoEnabled: boolean;
    recording: boolean;
    toggleAudioEnabled: (stream?: ConferenceStream) => void;
    toggleVideoEnabled: (stream?: ConferenceStream) => void;
    toggleScreenShare?: () => void;
    toggleRecording?: () => void;
}

export class MediaStreamControl extends React.Component<IMediaStreamControlProps, {}> {

    constructor() {
        super()
        this.onToggleAudioEnabled = this.onToggleAudioEnabled.bind(this);
        this.onToggleVideoEnabled = this.onToggleVideoEnabled.bind(this);
        this.onToggleScreenShare = this.onToggleScreenShare.bind(this);
        this.onToggleRecording = this.onToggleRecording.bind(this);
    }

    private onToggleAudioEnabled() {
        this.props.toggleAudioEnabled();
    }

    private onToggleVideoEnabled() {
        this.props.toggleVideoEnabled();
    }

    private onToggleScreenShare() {
        ChromeExtension.Instance.isExtensionAvailable()
            .then(available => {
                if (available) {
                    if (this.props.toggleScreenShare) {
                        this.props.toggleScreenShare();
                    }
                }
                else {
                    DownloadUtil.download('https://github.com/teamious/react-conf-webrtc/raw/master/docs/ext/teamious.screen.chrome.crx');
                }
            })
    }

    private onToggleRecording() {
        if (this.props.toggleRecording) {
            this.props.toggleRecording();
        }
    }

    render() {
        const muteText = this.props.audioEnabled ? 'Mute Audio' : 'Unmute Audio';
        const disableText = this.props.videoEnabled ? 'Disable Video' : 'Enable Video';
        const shareText = 'Share Screen';
        const recodingText = !this.props.recording ? 'Record' : 'Stop recordig';
        return (
            <div className='rcw-stream-controls'>
                <button className='rcw-stream-control-mute' onClick={this.onToggleAudioEnabled}>{muteText}</button>

                <button className='rcw-stream-control-disable' onClick={this.onToggleVideoEnabled}>{disableText}</button>

                {
                    this.props.toggleScreenShare && ChromeExtension.Instance.isChrome() &&
                    <button className='rcw-stream-control-share' onClick={this.onToggleScreenShare}>{shareText}</button>
                }
                {
                    this.props.toggleRecording &&
                    <button className='rcw-stream-control-recoding' onClick={this.onToggleRecording}>{recodingText}</button>
                }
            </div>
        )
    }
}


text:
<?php
$_SERVER['SCRIPT_FILENAME'] = FRONTEND_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = FRONTEND_ENTRY_URL;

/**
 * Application configuration for frontend functional tests
 */
return yii\helpers\ArrayHelper::merge(
    require(YII_APP_BASE_PATH . '/common/config/main.php'),
    require(YII_APP_BASE_PATH . '/common/config/main-local.php'),
    require(YII_APP_BASE_PATH . '/frontend/config/main.php'),
    require(YII_APP_BASE_PATH . '/frontend/config/main-local.php'),
    require(__DIR__ . '/../config.php'),
    require(__DIR__ . '/../config-local.php'),
    require(__DIR__ . '/../functional.php'),
    require(__DIR__ . '/config.php'),
    [
    ]
);


text:
@interface LLBootstrap : NSObject

@end


text:
[![Build Status](https://travis-ci.org/webrtc/adapter.svg)](https://travis-ci.org/webrtc/adapter)

# WebRTC adapter #
[adapter.js] is a shim to insulate apps from spec changes and prefix differences. In fact, the standards and protocols used for WebRTC implementations are highly stable, and there are only a few prefixed names. For full interop information, see [webrtc.org/web-apis/interop](http://www.webrtc.org/web-apis/interop).

## Install ##

#### Bower
```bash
bower install webrtc-adapter#gh-pages
```

One caveat is that the version is gh-pages hence you will get the latest adapter.js unless you manually specify a version. See Usage instructions for more details.

#### NPM
```bash
npm install webrtc-adapter
```

## Usage ##
##### NPM
Copy to desired location in your src tree or use a minify/vulcanize tool (node_modules is usually not published with the code).
See [webrtc/samples repo](https://github.com/webrtc/samples/blob/master/package.json) as an example on how you can do this.

#### Prebuilt releases
##### Web
In the [gh-pages branch](https://github.com/webrtc/adapter/tree/gh-pages) prebuilt ready to use files can be downloaded/linked directly.
Latest version can be found at http://webrtc.github.io/adapter/adapter-latest.js.
Specific versions can be found at http://webrtc.github.io/adapter/adapter-N.N.N.js, e.g. http://webrtc.github.io/adapter/adapter-1.0.2.js.

##### Bower
You will find `adapter.js` in `bower_components/webrtc-adapter/`.

Due to using the `gh-pages` branch as a version, you cannot use the bower package version for making sure you are using the correct version, rather you have to statically link the `adapter-version` file yourself, e.g. if you want version 1.0.5 you have to use the following file: `bower_components/webrtc-adapter/adapter-1.0.5.js`.

##### NPM
In node_modules/webrtc-adapter/out/ folder you will find 4 files:
* `adapter.js` - includes all the shims and is visible in the browser under the global `adapter` object (window.adapter).
* `adapter_no_edge.js` - same as above but does not include the Microsoft Edge (ORTC) shim.
* `adapter_no_edge_no_global.js` - same as above but is not exposed/visible in the browser (you cannot call/interact with the shims in the browser).
* `adapter_no_global.js` - same as `adapter.js` but is not exposed/visible in the browser (you cannot call/interact with the shims in the browser).

Include the file that suits your need in your project.

## Development ##
Detailed information on developing in the [webrtc](https://github.com/webrtc) github repo can be found in the [WebRTC GitHub repo developer's guide](https://docs.google.com/document/d/1tn1t6LW2ffzGuYTK3366w1fhTkkzsSvHsBnOHoDfRzY/edit?pli=1#heading=h.e3366rrgmkdk).

Head over to [test/README.md](https://github.com/webrtc/samples/blob/gh-pages/test/README.md) and get started developing.


text:
package main.habitivity.controllers;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import main.habitivity.habits.Habit;
import main.habitivity.interactions.HabitInteractionsFactory;
import main.habitivity.users.User;
import main.habitivity.users.UserContainer;

/**
 * Controls grabbing users from the server
 */
public class AllUsersController {

    public AllUsersController() {
    }

    /**
     * Gets a list of users that the currently logged in user is following
     *
     * @return - a list of users that the user is currently following
     */
    public ArrayList<String> getUsersFollowers() {
        return UserContainer.getInstance().getUser().getFollowers();
    }

    /**
     * Gets a list of users that the currently logged in user is following
     *
     * @return - a list of users that the user is currently following
     */
    public ArrayList<User> getUsersFollowing() {
        User currentLoggedInUser = UserContainer.getInstance().getUser();
        ArrayList<User> userFollowing = new ArrayList<User>();

        for (User following : currentLoggedInUser.getFollowing()) {
            userFollowing.add(following);
        }
        return userFollowing;
    }

    /**
     * Gets all the users in the server
     *
     * @return - a list of all the users in the server
     */
    public static ArrayList<User> getAllUsers() {
        ArrayList<User> allUsers = new ArrayList<>();

        ElasticsearchController.GetAllUserTask getAllUsers
                = new ElasticsearchController.GetAllUserTask();

        getAllUsers.execute();

        try {
            allUsers = getAllUsers.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        UserContainer.getInstance().setAllUsers(allUsers);
        return allUsers;
    }
}


text:
<?php

namespace Acme\Domain\Entity;

use Acme\Domain\Entity\EntityInterface;
use Acme\Domain\Entity\EntityTrait;

use Acme\Domain\Value\DateTime;
use Acme\Domain\Value\Byte;

/**
 * 画像
 *
 * @author k.holy74@gmail.com
 */
class Image implements EntityInterface, \ArrayAccess, \IteratorAggregate
{

	use EntityTrait;

	/**
	 * @var int
	 */
	private $id;

	/**
	 * @var string
	 */
	private $fileName;

	/**
	 * @var Acme\Domain\Value\Byte
	 */
	private $fileSize;

	/**
	 * @var string
	 */
	private $encodedData;

	/**
	 * @var string
	 */
	private $mimeType;

	/**
	 * @var int
	 */
	private $width;

	/**
	 * @var int
	 */
	private $height;

	/**
	 * @var Acme\Domain\Value\DateTime
	 */
	private $createdAt;

	/**
	 * @var int バイト表記の小数点以下桁数
	 */
	private $byteScale;

	/**
	 * @var array of string バイト表記単位の配列
	 */
	private $byteUnits;

	/**
	 * __construct()
	 *
	 * @param array プロパティの配列
	 */
	public function __construct(array $properties = [])
	{

		if (!isset($properties['byteScale'])) {
			$properties['byteScale'] = 1;
		}

		if (!isset($properties['byteUnits'])) {
			$properties['byteUnits'] = ['B','KB','MB','GB','TB','PB','EB','ZB','YB'];
		}

		$this->initialize($properties);
	}

	/**
	 * 登録日時をセットします。
	 *
	 * @param Acme\Domain\Value\DateTime
	 */
	private function setCreatedAt(DateTime $createdAt)
	{
		$this->createdAt = $createdAt;
	}

	/**
	 * ファイルサイズをセットします。
	 *
	 * @param Acme\Domain\Value\DateTime
	 */
	private function setFileSize(Byte $fileSize)
	{
		$this->fileSize = $fileSize;
	}

	/**
	 * エンコードされたデータを Data URI 形式で返します。
	 *
	 * @return string Data URI
	 */
	public function getDataUri()
	{
		return (isset($this->mimeType) && isset($this->encodedData))
			? sprintf('data:%s;base64,%s', $this->mimeType, $this->encodedData)
			: null;
	}

}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(ServerV2.Startup))]
namespace ServerV2
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}


text:
package org.test.input.stream;

import org.test.input.LineStreamer;
import org.test.input.pojo.Line;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public class ReadableLinesStreamer implements LineStreamer {
    private final Readable readable;

    public ReadableLinesStreamer(Readable readable) {
        this.readable = readable;
    }

    public ReadableLinesStreamer(File file) throws FileNotFoundException {
        this(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
    }

    @Override
    public Stream<Line> stream(boolean parallel) {
        return StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(
                        new LinesIterator(readable), 0), parallel);
    }

    @Override
    public void close() throws IOException {
        if (readable instanceof Closeable) {
            ((Closeable)readable).close();
        }
    }
}


text:
<?php
    include('lib/password.php');
	session_start();
?>

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>CRG Login</title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="css/style.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">
    <link href="../build/css/custom.min.css" rel="stylesheet">

            <form action="" method="POST">

                <input type="text" class="form-control" placeholder="Official Email Address" required="" name="username" />

                <input type="password" class="form-control" placeholder="Password" required="" name="password"/>

				<input type="submit" name="login" value="submit" class="btn btn-default btn-lg submit"/>

<?php

	include "db/config.php";
	// for user login
	if (isset($_POST['login'])) {

		$username = $_POST['username'];
		$_SESSION['username']=$username; // create session

		$password = $_POST['password'];

		//$query = "select * from cr_login where username='$username' AND password='$password'";
                $query = "select password from users where username='$username' and type='admin' ";

		$result = mysqli_query($connection, $query);

        if (mysqli_num_rows($result) != 1){
            // invalid login information

			 echo "
 Wrong Email Id or Password!
";
			   echo "";
            //show the loginform again.
        } else {
            $hash_cost = 10;

            $user = mysqli_fetch_row($result);

            if(password_verify('c8d4e8763d'.$password, $user[0])){
                echo "
 Login Success
";
                echo "";
            }else{
                echo "
 Invalid Password
";
                echo "";
            }
        }
	}

?>


text:
module CricketHelper
end


text:
<?php

namespace Admin\Validator;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;

class Fotos {

    protected $inputFilter;

    public function getInputFilter() {

        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $inputFactory = new InputFactory();

            $inputFilter->add($inputFactory->createInput(
                            array(
                                'name' => 'id',
                                'required' => false,
                                'filters' => array(
                                    array('name' => 'Int'),
                                ),
                            )
                    )
            );

            $inputFilter->add(
                    $inputFactory->createInput(array(
                        'name' => 'imagem',
                        'required' => true,
                        'validators' => array(
                            array(
                                'name' => 'Zend\Validator\File\UploadFile',
                                'options' => array(
                                    'messages' => array(
                                        'fileUploadFileErrorNoFile' => 'Arquivo não foi carregado',
                                    )
                                )
                            ),
                            array(
                                'name' => 'Zend\Validator\File\Extension',
                                'options' => array(
                                    'extension' => 'png,jpg',
                                    'messages' => array(
                                        'fileExtensionNotFound' => 'Extensão de arquivo não encontrada',
                                        'fileExtensionFalse' => 'Extensão não permitida'
                                    ),
                                ),
                            ),
                        ),
                        'filters' => array(
                            array(
                                'name' => 'Zend\Filter\File\RenameUpload',
                                'options' => array(
                                    'target' => 'public/uploads/galeria',
                                    'randomize' => true,
                                    'use_upload_extension' => true,
                                    'use_upload_name' => true
                                )
                            )
                        )
                    ))
            );

            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }

}


text:
#include "config.h"

#ifndef SFDREADERLISTENER_SLUMPADETECKEN_H
#define SFDREADERLISTENER_SLUMPADETECKEN_H

class SFDBufReaderListener {
public:

   /**
    *   Called when a buffer is read. Ownership is passed on
    *   to the listener.
    *   @param buf Read buffer or NULL if failure.
    */
   virtual void bufferRead( BitBuffer* buf ) = 0;

};

#endif


text:
from __future__ import absolute_import, print_function, division
import os
import unittest
import sys

from numpy.testing.nosetester import NoseTester

# This class contains code adapted from NumPy,
# numpy/testing/nosetester.py,
# Copyright (c) 2005-2011, NumPy Developers
class TheanoNoseTester(NoseTester):
    """
    Nose test runner.

    This class enables running nose tests from inside Theano,
    by calling theano.test().
    This version is more adapted to what we want than Numpy's one.
    """

    def _test_argv(self, verbose, extra_argv):
        """
        Generate argv for nosetest command

        :type verbose: int
        :param verbose: Verbosity value for test outputs, in the range 1-10.
                        Default is 1.

        :type extra_argv: list
        :param extra_argv: List with any extra arguments to pass to nosetests.
        """
        # self.package_path = os.path.abspath(self.package_path)
        argv = [__file__, self.package_path]
        argv += ['--verbosity', str(verbose)]
        if extra_argv:
            argv += extra_argv
        return argv

    def _show_system_info(self):
        import theano
        print("Theano version %s" % theano.__version__)
        theano_dir = os.path.dirname(theano.__file__)
        print("theano is installed in %s" % theano_dir)

        super(TheanoNoseTester, self)._show_system_info()

    def prepare_test_args(self, verbose=1, extra_argv=None, coverage=False,
                          capture=True, knownfailure=True):
        """
        Prepare arguments for the `test` method.

        Takes the same arguments as `test`.
        """
        import nose.plugins.builtin
        # compile argv
        argv = self._test_argv(verbose, extra_argv)

        # numpy way of doing coverage
        if coverage:
            argv += ['--cover-package=%s' % self.package_name,
                     '--with-coverage', '--cover-tests',
                     '--cover-inclusive', '--cover-erase']

        # Capture output only if needed
        if not capture:
            argv += ['-s']

        # construct list of plugins
        plugins = []
        if knownfailure:
            from numpy.testing.noseclasses import KnownFailure
            plugins.append(KnownFailure())
        plugins += [p() for p in nose.plugins.builtin.plugins]

        return argv, plugins

    def test(self, verbose=1, extra_argv=None, coverage=False, capture=True,
             knownfailure=True):
        """
        Run tests for module using nose.

        :type verbose: int
        :param verbose: Verbosity value for test outputs, in the range 1-10.
                        Default is 1.

        :type extra_argv: list
        :param extra_argv: List with any extra arguments to pass to nosetests.

        :type coverage: bool
        :param coverage: If True, report coverage of Theano
                         code. Default is False.

        :type capture: bool
        :param capture: If True, capture the standard output of the tests, like
                        nosetests does in command-line. The output of failing
                        tests will be displayed at the end. Default is True.

        :type knownfailure: bool
        :param knownfailure: If True, tests raising KnownFailureTest will
                not be considered Errors nor Failure, but reported as
                "known failures" and treated quite like skipped tests.
                Default is True.

        :returns: Returns the result of running the tests as a
                  ``nose.result.TextTestResult`` object.
        """
        from nose.config import Config
        from nose.plugins.manager import PluginManager
        from numpy.testing.noseclasses import NumpyTestProgram
        # Many Theano tests suppose device=cpu, so we need to raise an
        # error if device==gpu.
        if not os.path.exists('theano/__init__.py'):
            try:
                from theano import config
                if config.device != "cpu":
                    raise ValueError("Theano tests must be run with device=cpu."
                                     " This will also run GPU tests when possible.\n"
                                     " If you want GPU-related tests to run on a"
                                     " specific GPU device, and not the default one,"
                                     " you should use the init_gpu_device theano flag.")
            except ImportError:
                pass

        # cap verbosity at 3 because nose becomes *very* verbose beyond that
        verbose = min(verbose, 3)
        self._show_system_info()

        cwd = os.getcwd()
        if self.package_path in os.listdir(cwd):
            # The tests give weird errors if the package to test is
            # in current directory.
            raise RuntimeError((
                "This function does not run correctly when, at the time "
                "theano was imported, the working directory was theano's "
                "parent directory. You should exit your Python prompt, change "
                "directory, then launch Python again, import theano, then "
                "launch theano.test()."))

        argv, plugins = self.prepare_test_args(verbose, extra_argv, coverage,
                                               capture, knownfailure)

        # The "plugins" keyword of NumpyTestProgram gets ignored if config is
        # specified. Moreover, using "addplugins" instead can lead to strange
        # errors. So, we specify the plugins in the Config as well.
        cfg = Config(includeExe=True, plugins=PluginManager(plugins=plugins))
        t = NumpyTestProgram(argv=argv, exit=False, config=cfg)
        return t.result

def main(modulename):
    if 0:
        unittest.main()
    elif len(sys.argv) == 2 and sys.argv[1] == "--debug":
        module = __import__(modulename)
        tests = unittest.TestLoader().loadTestsFromModule(module)
        tests.debug()
    elif len(sys.argv) == 1:
        module = __import__(modulename)
        tests = unittest.TestLoader().loadTestsFromModule(module)
        unittest.TextTestRunner(verbosity=2).run(tests)
    else:
        print("options: [--debug]")


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using csharp_extensions.Implementations.IEnumerableExtensions;

namespace csharp_extensions.Extensions
{
    public static class IEnumerableExtensions
    {

        // Why isn't this available by default?
        public static T FirstOrDefault<T>(
            this IEnumerable<T> list,
            Func<T, bool> func,
            T defaultValue)
        {
            return Methods.FirstOrDefault(list, func, defaultValue);
        }

        /// <summary>
        /// http://rosettacode.org/wiki/Flatten_a_list#C.23
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IEnumerable<T> Flatten<T>(this IEnumerable<T> list)
        {
            return Methods.Flatten(list);
        }

        public static List<T> AddRange<T>(this List<T> list, List<object> otherList)
        {
            return Methods.AddRange<T>(list, otherList);
        }

        public static IEnumerable<T> Subset<T>(this IEnumerable<T> array, int beginIndex, int endIndex)
        {
            return array.Skip(beginIndex).Take(endIndex);
        }

        public static string Join(this IEnumerable<string> array, string seperator)
        {
            return string.Join(seperator, array);
        }

        /// <summary>
        /// int[] left = { 1, 2, 3, 4, 5 };
        /// string[] right = { "abc", "def", "ghi", "jkl", "mno" };
        /// // using KeyValuePair<> approach
        /// foreach (var item in left.Zip(right))
        /// {
        ///     Console.WriteLine("{0}/{1}", item.Key, item.Value);
        /// }
        ///
        /// // using projection approach
        /// foreach (string item in left.Zip(right,
        ///     (x,y) => string.Format("{0}/{1}", x, y)))
        /// {
        ///     Console.WriteLine(item);
        /// }
        /// </summary>
        /// <typeparam name="TLeft"></typeparam>
        /// <typeparam name="TRight"></typeparam>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        // http://stackoverflow.com/a/242420/356849
        // returns each pais as a KeyValuePair<,>
        public static IEnumerable<KeyValuePair<TLeft, TRight>> Zip<TLeft, TRight>(
            this IEnumerable<TLeft> left,
            IEnumerable<TRight> right)
        {
            return Methods.Zip(left, right);
        }
    }
}


text:
/**
 * Created by eirikskogland on 28.09.15.
 */
angular.module('ExamApp').factory('SchoolSubCategory', ['$http', function($http) {

    var allCats = [];
    $http.get('assets/json/school_sub_categories.json').then(function(response) {
        allCats = response.data;
    });

    return {
        // returns all the sub categories
        all: function() {
            return $http.get('assets/json/school_sub_categories.json');

        },
        get: function(id){
            for(var i = 0; i < allCats.length; i++) {
                console.log("SubCat.id: "+ allCats[i].id);
                if(allCats[i].id == id){
                    console.log("Sub categories found for id:" + JSON.stringify(allCats[i]));

                    return allCats[i];
                }
            }
            return null;
        }

    }

}]);


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class EditarGeometria_EditarLinha
    Inherits System.Windows.Forms.Form

    'Descartar substituições de formulário para limpar a lista de componentes.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Exigido pelo Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'OBSERVAÇÃO: o procedimento a seguir é exigido pelo Windows Form Designer
    'Pode ser modificado usando o Windows Form Designer.
    'Não o modifique usando o editor de códigos.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.bCancelar = New MeshExplorer.Controls.DarkButton()
        Me.bAceitar = New MeshExplorer.Controls.DarkButton()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.tLinha = New System.Windows.Forms.TextBox()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.L_Ponto2 = New System.Windows.Forms.ComboBox()
        Me.L_Ponto1 = New System.Windows.Forms.ComboBox()
        Me.SuspendLayout()
        '
        'bCancelar
        '
        Me.bCancelar.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.bCancelar.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.bCancelar.Location = New System.Drawing.Point(19, 73)
        Me.bCancelar.Name = "bCancelar"
        Me.bCancelar.Size = New System.Drawing.Size(108, 25)
        Me.bCancelar.TabIndex = 41
        Me.bCancelar.Text = "Cancelar"
        Me.bCancelar.UseVisualStyleBackColor = True
        '
        'bAceitar
        '
        Me.bAceitar.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.bAceitar.Location = New System.Drawing.Point(143, 73)
        Me.bAceitar.Name = "bAceitar"
        Me.bAceitar.Size = New System.Drawing.Size(232, 25)
        Me.bAceitar.TabIndex = 40
        Me.bAceitar.Text = "Aceitar"
        Me.bAceitar.UseVisualStyleBackColor = True
        '
        'Label2
        '
        Me.Label2.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label2.Location = New System.Drawing.Point(264, 15)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(88, 17)
        Me.Label2.TabIndex = 38
        Me.Label2.Text = "Ponto 2:"
        '
        'Label1
        '
        Me.Label1.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label1.Location = New System.Drawing.Point(140, 15)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(88, 17)
        Me.Label1.TabIndex = 36
        Me.Label1.Text = "Ponto 1:"
        '
        'tLinha
        '
        Me.tLinha.Enabled = False
        Me.tLinha.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.tLinha.Location = New System.Drawing.Point(19, 35)
        Me.tLinha.Name = "tLinha"
        Me.tLinha.Size = New System.Drawing.Size(108, 23)
        Me.tLinha.TabIndex = 35
        Me.tLinha.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
        '
        'Label3
        '
        Me.Label3.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label3.ForeColor = System.Drawing.Color.WhiteSmoke
        Me.Label3.Location = New System.Drawing.Point(16, 15)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(122, 17)
        Me.Label3.TabIndex = 34
        Me.Label3.Text = "Linha Selecionada:"
        '
        'L_Ponto2
        '
        Me.L_Ponto2.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest
        Me.L_Ponto2.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems
        Me.L_Ponto2.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.L_Ponto2.FormattingEnabled = True
        Me.L_Ponto2.Location = New System.Drawing.Point(267, 35)
        Me.L_Ponto2.Name = "L_Ponto2"
        Me.L_Ponto2.Size = New System.Drawing.Size(108, 23)
        Me.L_Ponto2.TabIndex = 43
        '
        'L_Ponto1
        '
        Me.L_Ponto1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest
        Me.L_Ponto1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems
        Me.L_Ponto1.Font = New System.Drawing.Font("Segoe UI", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.L_Ponto1.FormattingEnabled = True
        Me.L_Ponto1.Location = New System.Drawing.Point(143, 35)
        Me.L_Ponto1.Name = "L_Ponto1"
        Me.L_Ponto1.Size = New System.Drawing.Size(108, 23)
        Me.L_Ponto1.TabIndex = 42
        '
        'EditarGeometria_EditarLinha
        '
        Me.AcceptButton = Me.bAceitar
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.FromArgb(CType(CType(76, Byte), Integer), CType(CType(76, Byte), Integer), CType(CType(76, Byte), Integer))
        Me.CancelButton = Me.bCancelar
        Me.ClientSize = New System.Drawing.Size(391, 113)
        Me.Controls.Add(Me.L_Ponto2)
        Me.Controls.Add(Me.L_Ponto1)
        Me.Controls.Add(Me.bCancelar)
        Me.Controls.Add(Me.bAceitar)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.tLinha)
        Me.Controls.Add(Me.Label3)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "EditarGeometria_EditarLinha"
        Me.ShowInTaskbar = False
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
        Me.Text = "Editar Linha"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub

    Private WithEvents bCancelar As MeshExplorer.Controls.DarkButton
    Private WithEvents bAceitar As MeshExplorer.Controls.DarkButton
    Friend WithEvents Label2 As Label
    Friend WithEvents Label1 As Label
    Friend WithEvents tLinha As TextBox
    Friend WithEvents Label3 As Label
    Friend WithEvents L_Ponto2 As ComboBox
    Friend WithEvents L_Ponto1 As ComboBox
End Class


text:
import { Component, ElementRef, OnInit, NgZone, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MapsAPILoader } from '@agm/core';
import { MdDialog, MdDialogRef } from '@angular/material';
import { NgModule } from '@angular/core';
import { ToasterService } from 'angular2-toaster';
import { TranslateService } from 'ng2-translate';
import { ActivatedRoute, Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

import { AchievementService } from '../shared/achievement.service';
import { Achievement } from '../shared/achievement.model';
import { Medium } from '../../media/shared/medium.model';
import { RouteFinishedAchievement } from '../shared/route-finished-achievement.model';
import { ExhibitsVisitedAchievement } from '../shared/exhibits-visited-achievement.model';
import { RouteService } from '../../routes/shared/routes.service';
import { ExhibitService } from '../../exhibits/shared/exhibit.service';
import { Exhibit } from '../../exhibits/shared/exhibit.model';
import { Route } from '../../routes/shared/route.model';
import { ConfirmDeleteDialogComponent } from '../../shared/confirm-delete-dialog/confirm-delete-dialog.component';
import { User } from '../../../users/user.model';
import { UserService } from '../../../users/user.service';

@Component({
    moduleId: module.id,
    selector: 'view-achievement',
    templateUrl: 'view-achievement.component.html',
    styleUrls: ['view-achievement.component.css']
})

export class ViewAchievementComponent implements OnInit {

    achievement: any;
    id: number;
    previewURL: SafeUrl;
    achievements: Achievement[];

    canDelete = true;
    canEdit = true;

    private deleteDialogRef: MdDialogRef<ConfirmDeleteDialogComponent>;

    exhibitsVisitedAchievement = ExhibitsVisitedAchievement.emptyExhibitsVisitedAchievement();
    routeFinishedAchievement = RouteFinishedAchievement.emptyRouteFinishedAchievement();

    constructor(private routeService: RouteService,
        private router: Router,
        private toasterService: ToasterService,
        private route: ActivatedRoute,
        private achievementService: AchievementService,
        private dialog: MdDialog,
        private translateService: TranslateService,
        private exhibitService: ExhibitService,
        private spinnerService: NgxSpinnerService,
        private userService: UserService,
        private sanitizer: DomSanitizer,
    ) { }

    ngOnInit() {
        this.getId();
    }

    private getId() {
        this.route.params
            .subscribe(params => {
                this.id = +params['id'];
                this.getAchievement();
            });
    }

    private getAchievement() {
        this.achievementService
            .getAchievement(this.id)
            .then((achievement: Achievement) => {
                this.spinnerService.hide();
                this.achievement = achievement;
                this.getCurrentUser();
                this.getRoute();
                this.getImage(this.id);
            })
            .catch((error: any) => {
                this.toasterService.pop('error', this.translate('Error fetching achievement'), error);
                this.spinnerService.hide();
            });
    }

    // implimented this method so that student can only edit or delete his exhibit only.

    getCurrentUser() {
        this.userService.getCurrent()
            .then(
                (response) => {
                    let currentUserId = response.id;
                    for (let role of response.roles) {
                        if (role === 'Student') {
                            if (currentUserId !== this.achievement.userId) {
                                this.canDelete = false;
                                this.canEdit = false;
                            } else {
                                this.canDelete = true;
                                this.canEdit = true;
                            }
                        }
                    }

                }
            );
    }

    getRoute() {
        this.routeService.getRoute(this.achievement.routeId)
            .then(
                response => {
                    this.achievement.routeTitle = response.title;
                }
            )
            .catch(
                (error: any) => {
                    console.error(error);
                }
            );
    }

    private getImage(id: number) {
        this.achievementService.getImage(id, true)
            .then(
                response => {
                    let base64Data: string;
                    let reader = new FileReader();
                    reader.readAsDataURL(response);
                    reader.onloadend = () => {
                        base64Data = reader.result;
                        this.previewURL = this.sanitizer.bypassSecurityTrustUrl(base64Data);
                    };
                }
            ).catch(
                (error: any) => {
                    this.toasterService.pop('error', this.translate('Error fetching achievement'), error);
                }
            );
    }

    deleteAchievement(achievement: Achievement) {
        let context = this;
        this.deleteDialogRef = this.dialog.open(ConfirmDeleteDialogComponent, {
            data: {
                title: this.translateService.instant('Delete achievement'),
                message: this.translateService.instant('Confirm delete achievement', { title: achievement.title }),
            }
        });
        this.deleteDialogRef.afterClosed().subscribe(
            (confirmed: boolean) => {
                if (confirmed) {
                    this.achievementService.deleteAchievement(achievement.id)
                        .then(
                            () => {
                                // tslint:disable-next-line:max-line-length
                                this.toasterService.pop('success', 'Success', achievement.title + ' - ' + this.translate('Achievement deleted'));
                                this.router.navigate(['../../'], { relativeTo: this.route });
                            }

                        ).catch(
                            error => this.toasterService.pop('error', this.translate('Error while saving'), error)
                        );
                }
            }
        );
    }

    private translate(data: string): string {
        let translatedResponse: string;
        this.translateService.get(data).subscribe(
            (value: string) => {
                translatedResponse = value;
            }
        );
        return translatedResponse;
    }
}


text:
var assert = require('assert');

var _require = require('path'),
    join = _require.join;

var exists = require('../../src/exists');
var context = require('../context/WroteContext');

var equal = assert.equal;

var eraseTestSuite = {
    context,
    'should return false for a file'(_ref) {
        return new Promise(function ($return, $error) {
            var tempFile, res;
            tempFile = _ref.tempFile;
            return Promise.resolve(exists(tempFile)).then(function ($await_2) {
                try {
                    res = $await_2;
                    assert(!res);
                    return $return();
                } catch ($boundEx) {
                    return $error($boundEx);
                }
            }.bind(this), $error);
        }.bind(this));
    },
    'should return true for a file'(_ref2) {
        return new Promise(function ($return, $error) {
            var tempFile, createTempFileWithData, res;
            tempFile = _ref2.tempFile, createTempFileWithData = _ref2.createTempFileWithData;
            return Promise.resolve(createTempFileWithData()).then(function ($await_3) {
                try {
                    return Promise.resolve(exists(tempFile)).then(function ($await_4) {
                        try {
                            res = $await_4;
                            assert(res);
                            return $return();
                        } catch ($boundEx) {
                            return $error($boundEx);
                        }
                    }.bind(this), $error);
                } catch ($boundEx) {
                    return $error($boundEx);
                }
            }.bind(this), $error);
        }.bind(this));
    },
    'should return true for a directory'(_ref3) {
        return new Promise(function ($return, $error) {
            var FIXTURES_TEST_DIR, res;
            FIXTURES_TEST_DIR = _ref3.FIXTURES_TEST_DIR;
            return Promise.resolve(exists(FIXTURES_TEST_DIR)).then(function ($await_5) {
                try {
                    res = $await_5;
                    assert(res);
                    return $return();
                } catch ($boundEx) {
                    return $error($boundEx);
                }
            }.bind(this), $error);
        }.bind(this));
    },
    'should throw a permission denied error'(_ref4) {
        return new Promise(function ($return, $error) {
            var makeNoExecutableDirectory, temp, test, code;
            makeNoExecutableDirectory = _ref4.makeNoExecutableDirectory;
            return Promise.resolve(makeNoExecutableDirectory()).then(function ($await_6) {
                try {
                    temp = $await_6;
                    test = join(temp, 'test/wrote.data');
                    var $Try_1_Post = function () {
                        try {
                            return $return();
                        } catch ($boundEx) {
                            return $error($boundEx);
                        }
                    }.bind(this);var $Try_1_Catch = function (_ref5) {
                        try {
                            code = _ref5.code;

                            equal(code, 'EACCES');
                            return $Try_1_Post();
                        } catch ($boundEx) {
                            return $error($boundEx);
                        }
                    }.bind(this);try {
                        return Promise.resolve(exists(test)).then(function ($await_7) {
                            try {
                                throw new Error('should have thrown');
                            } catch ($boundEx) {
                                return $Try_1_Catch($boundEx);
                            }
                        }.bind(this), $Try_1_Catch);
                    } catch (_ref5) {
                        $Try_1_Catch(_ref5)
                    }
                } catch ($boundEx) {
                    return $error($boundEx);
                }
            }.bind(this), $error);
        }.bind(this));
    }
};

module.exports = eraseTestSuite;


text:
#include <ql/cashflows/cashflows.hpp>
#include <qle/pricingengines/depositengine.hpp>

namespace QuantExt {

DepositEngine::DepositEngine(const Handle<YieldTermStructure>& discountCurve,
                             boost::optional<bool> includeSettlementDateFlows, Date settlementDate, Date npvDate)
    : discountCurve_(discountCurve), includeSettlementDateFlows_(includeSettlementDateFlows),
      settlementDate_(settlementDate), npvDate_(npvDate) {
    registerWith(discountCurve_);
}

void DepositEngine::calculate() const {
    QL_REQUIRE(!discountCurve_.empty(), "discounting term structure handle is empty");

    results_.value = 0.0;
    results_.errorEstimate = Null<Real>();

    Date refDate = discountCurve_->referenceDate();

    Date settlementDate = settlementDate_;
    if (settlementDate_ == Date()) {
        settlementDate = refDate;
    } else {
        QL_REQUIRE(settlementDate >= refDate, "settlement date (" << settlementDate << ") before "
                                                                                "discount curve reference date ("
                                                                  << refDate << ")");
    }

    Date valuationDate = npvDate_;
    if (npvDate_ == Date()) {
        valuationDate = refDate;
    } else {
        QL_REQUIRE(npvDate_ >= refDate, "npv date (" << npvDate_ << ") before "
                                                                    "discount curve reference date (" << refDate
                                                     << ")");
    }

    bool includeRefDateFlows =
        includeSettlementDateFlows_ ? *includeSettlementDateFlows_ : Settings::instance().includeReferenceDateEvents();

    results_.value =
        CashFlows::npv(arguments_.leg, **discountCurve_, includeRefDateFlows, settlementDate, valuationDate);

    results_.fairRate = arguments_.index->clone(discountCurve_)->fixing(refDate);

} // calculate
} // namespace QuantExt


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S11.2.2_A4_T2;
* @section: 11.2.2;
* @assertion: If NewExpression or MemberExpression does not implement internal [[Construct]] method, throw TypeError;
* @description: Checking Number object case;
*/

//CHECK#1
try {
  new new Number(1);
  $ERROR('#1: new new Number(1) throw TypeError');
}
catch (e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#1: new new Number(1) throw TypeError');
  }
}

//CHECK#2
try {
  var x = new Number(1);
  new x;
  $ERROR('#2: var x = new Number(1); new x throw TypeError');
}
catch (e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#2: var x = new Number(1); new x throw TypeError');
  }
}

//CHECK#3
try {
  var x = new Number(1);
  new x();
  $ERROR('#3: var x = new Number(1); new x() throw TypeError');
}
catch (e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#3: var x = new Number(1); new x() throw TypeError');
  }
}


text:
<?php

class PersistentTest extends RememberTestCase
{
    public function testPersistentCaching()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $cached = Group::find(static::ID);

        $this->assertEquals($group, $cached);
    }

    public function testPersistentCachingPopsCorrectlyWhenUpdating()
    {
        Group::create(['id' => static::ID, 'name' => 'Test Group']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));

        static::$sql = true;

        $group->update(['name' => 'Test Group Two']);

        $group = Group::find(static::ID);

        static::$sql = false;

        $this->assertEquals($group, Group::find(static::ID));
    }

    public function testPersistentCachingWhenDeleting()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->delete();

        $cached = Group::find(static::ID);

        $this->assertNull($cached);
    }

    /**
     * @expectedException SqlIssuedException
     */
    public function testSqlIssuedAfterDeletion()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->delete();

        static::$sql = false;

        Group::find(static::ID);
    }

    /**
     * @expectedException SqlIssuedException
     */
    public function testSqlIssuedAfterUpdating()
    {
        Group::create(['id' => static::ID, 'name' => 'Delete Test']);

        $group = Group::find(static::ID);

        $group->update(['name' => 'foobar']);

        static::$sql = false;

        Group::find(static::ID);
    }
}


text:
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace LexModelsV2
{
namespace Model
{

  /**
   *
Defines an ASCII text message to send to the user.

See Also:

   * AWS
   * API Reference

   */
  class AWS_LEXMODELSV2_API PlainTextMessage
  {
  public:
    PlainTextMessage();
    PlainTextMessage(Aws::Utils::Json::JsonView jsonValue);
    PlainTextMessage& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The message to send to the user.

     */
    inline const Aws::String& GetValue() const{ return m_value; }

    /**
     *
The message to send to the user.

     */
    inline bool ValueHasBeenSet() const { return m_valueHasBeenSet; }

    /**
     *
The message to send to the user.

     */
    inline void SetValue(const Aws::String& value) { m_valueHasBeenSet = true; m_value = value; }

    /**
     *
The message to send to the user.

     */
    inline void SetValue(Aws::String&& value) { m_valueHasBeenSet = true; m_value = std::move(value); }

    /**
     *
The message to send to the user.

     */
    inline void SetValue(const char* value) { m_valueHasBeenSet = true; m_value.assign(value); }

    /**
     *
The message to send to the user.

     */
    inline PlainTextMessage& WithValue(const Aws::String& value) { SetValue(value); return *this;}

    /**
     *
The message to send to the user.

     */
    inline PlainTextMessage& WithValue(Aws::String&& value) { SetValue(std::move(value)); return *this;}

    /**
     *
The message to send to the user.

     */
    inline PlainTextMessage& WithValue(const char* value) { SetValue(value); return *this;}

  private:

    Aws::String m_value;
    bool m_valueHasBeenSet;
  };

} // namespace Model
} // namespace LexModelsV2
} // namespace Aws


text:
package org.itsnat.droid.impl.xmlinflater.drawable.classtree;

import org.itsnat.droid.impl.dom.drawable.DOMElemDrawable;
import org.itsnat.droid.impl.xmlinflated.drawable.ElementDrawableChild;
import org.itsnat.droid.impl.xmlinflated.drawable.ElementDrawableChildBase;
import org.itsnat.droid.impl.xmlinflated.drawable.GradientDrawableChildPadding;
import org.itsnat.droid.impl.xmlinflater.drawable.AttrDrawableContext;
import org.itsnat.droid.impl.xmlinflater.drawable.ClassDescDrawableMgr;
import org.itsnat.droid.impl.xmlinflater.shared.attr.AttrDescReflecMethodDimensionIntFloor;

/**
 * Created by jmarranz on 10/11/14.
 */
public class ClassDescGradientDrawableChildPadding extends ClassDescElementDrawableChildNormal<GradientDrawableChildPadding>
{
    public ClassDescGradientDrawableChildPadding(ClassDescDrawableMgr classMgr)
    {
        super(classMgr,"shape:padding",null);
    }

    @Override
    public Class<GradientDrawableChildPadding> getDrawableOrElementDrawableClass()
    {
        return GradientDrawableChildPadding.class;
    }

    @Override
    public ElementDrawableChild createElementDrawableChild(DOMElemDrawable domElement, DOMElemDrawable domElementParent, ElementDrawableChildBase parentChildDrawable, AttrDrawableContext attrCtx)
    {
        return new GradientDrawableChildPadding(parentChildDrawable);
    }

    @SuppressWarnings("unchecked")
    protected void init()
    {
        super.init();

        addAttrDescAN(new AttrDescReflecMethodDimensionIntFloor(this, "left", 0f));
        addAttrDescAN(new AttrDescReflecMethodDimensionIntFloor(this, "top", 0f));
        addAttrDescAN(new AttrDescReflecMethodDimensionIntFloor(this, "right", 0f));
        addAttrDescAN(new AttrDescReflecMethodDimensionIntFloor(this, "bottom", 0f));
    }

}