text:
from unittest import mock
import uuid

import stevedore

from keystone.api._shared import authentication
from keystone import auth
from keystone.auth.plugins import base
from keystone.auth.plugins import mapped
from keystone import exception
from keystone.tests import unit
from keystone.tests.unit.ksfixtures import auth_plugins

# for testing purposes only
METHOD_NAME = 'simple_challenge_response'
EXPECTED_RESPONSE = uuid.uuid4().hex
DEMO_USER_ID = uuid.uuid4().hex

class SimpleChallengeResponse(base.AuthMethodHandler):
    def authenticate(self, auth_payload):
        response_data = {}
        if 'response' in auth_payload:
            if auth_payload['response'] != EXPECTED_RESPONSE:
                raise exception.Unauthorized('Wrong answer')

            response_data['user_id'] = DEMO_USER_ID
            return base.AuthHandlerResponse(status=True, response_body=None,
                                            response_data=response_data)
        else:
            return base.AuthHandlerResponse(
                status=False,
                response_body={
                    "challenge": "What's the name of your high school?"},
                response_data=None)

class TestAuthPlugin(unit.SQLDriverOverrides, unit.TestCase):

    def test_unsupported_auth_method(self):
        method_name = uuid.uuid4().hex
        auth_data = {'methods': [method_name]}
        auth_data[method_name] = {'test': 'test'}
        auth_data = {'identity': auth_data}
        self.assertRaises(exception.AuthMethodNotSupported,
                          auth.core.AuthInfo.create,
                          auth_data)

    @mock.patch.object(auth.core, '_get_auth_driver_manager')
    def test_addition_auth_steps(self, stevedore_mock):
        simple_challenge_plugin = SimpleChallengeResponse()
        extension = stevedore.extension.Extension(
            name='simple_challenge', entry_point=None, plugin=None,
            obj=simple_challenge_plugin
        )
        test_manager = stevedore.DriverManager.make_test_instance(extension)
        stevedore_mock.return_value = test_manager

        self.useFixture(
            auth_plugins.ConfigAuthPlugins(self.config_fixture,
                                           methods=[METHOD_NAME]))
        self.useFixture(auth_plugins.LoadAuthPlugins(METHOD_NAME))

        auth_data = {'methods': [METHOD_NAME]}
        auth_data[METHOD_NAME] = {
            'test': 'test'}
        auth_data = {'identity': auth_data}
        auth_info = auth.core.AuthInfo.create(auth_data)
        auth_context = auth.core.AuthContext(method_names=[])
        try:
            with self.make_request():
                authentication.authenticate(auth_info, auth_context)
        except exception.AdditionalAuthRequired as e:
            self.assertIn('methods', e.authentication)
            self.assertIn(METHOD_NAME, e.authentication['methods'])
            self.assertIn(METHOD_NAME, e.authentication)
            self.assertIn('challenge', e.authentication[METHOD_NAME])

        # test correct response
        auth_data = {'methods': [METHOD_NAME]}
        auth_data[METHOD_NAME] = {
            'response': EXPECTED_RESPONSE}
        auth_data = {'identity': auth_data}
        auth_info = auth.core.AuthInfo.create(auth_data)
        auth_context = auth.core.AuthContext(method_names=[])
        with self.make_request():
            authentication.authenticate(auth_info, auth_context)
        self.assertEqual(DEMO_USER_ID, auth_context['user_id'])

        # test incorrect response
        auth_data = {'methods': [METHOD_NAME]}
        auth_data[METHOD_NAME] = {
            'response': uuid.uuid4().hex}
        auth_data = {'identity': auth_data}
        auth_info = auth.core.AuthInfo.create(auth_data)
        auth_context = auth.core.AuthContext(method_names=[])
        with self.make_request():
            self.assertRaises(exception.Unauthorized,
                              authentication.authenticate,
                              auth_info,
                              auth_context)

    def test_duplicate_method(self):
        # Having the same method twice doesn't cause load_auth_methods to fail.
        self.useFixture(
            auth_plugins.ConfigAuthPlugins(self.config_fixture,
                                           ['external', 'external']))
        auth.core.load_auth_methods()
        self.assertIn('external', auth.core.AUTH_METHODS)

class TestAuthPluginDynamicOptions(TestAuthPlugin):
    def config_overrides(self):
        super(TestAuthPluginDynamicOptions, self).config_overrides()
        # Clear the override for the [auth] ``methods`` option so it is
        # possible to load the options from the config file.
        self.config_fixture.conf.clear_override('methods', group='auth')

    def config_files(self):
        config_files = super(TestAuthPluginDynamicOptions, self).config_files()
        config_files.append(unit.dirs.tests_conf('test_auth_plugin.conf'))
        return config_files

class TestMapped(unit.TestCase):

    def config_files(self):
        config_files = super(TestMapped, self).config_files()
        config_files.append(unit.dirs.tests_conf('test_auth_plugin.conf'))
        return config_files

    def _test_mapped_invocation_with_method_name(self, method_name):
        with mock.patch.object(auth.plugins.mapped.Mapped,
                               'authenticate',
                               return_value=None) as authenticate:
            auth_data = {
                'identity': {
                    'methods': [method_name],
                    method_name: {'protocol': method_name},
                }
            }
            auth_info = auth.core.AuthInfo.create(auth_data)
            auth_context = auth.core.AuthContext(
                method_names=[],
                user_id=uuid.uuid4().hex)
            with self.make_request():
                authentication.authenticate(auth_info, auth_context)
            # make sure Mapped plugin got invoked with the correct payload
            ((auth_payload,), kwargs) = authenticate.call_args
            self.assertEqual(method_name, auth_payload['protocol'])

    def test_mapped_with_remote_user(self):
        method_name = 'saml2'
        auth_data = {'methods': [method_name]}
        # put the method name in the payload so its easier to correlate
        # method name with payload
        auth_data[method_name] = {'protocol': method_name}
        auth_data = {'identity': auth_data}

        auth_context = auth.core.AuthContext(
            method_names=[],
            user_id=uuid.uuid4().hex)

        self.useFixture(auth_plugins.LoadAuthPlugins(method_name))

        with mock.patch.object(auth.plugins.mapped.Mapped,
                               'authenticate',
                               return_value=None) as authenticate:
            auth_info = auth.core.AuthInfo.create(auth_data)
            with self.make_request(environ={'REMOTE_USER': 'foo@idp.com'}):
                authentication.authenticate(auth_info, auth_context)
            # make sure Mapped plugin got invoked with the correct payload
            ((auth_payload,), kwargs) = authenticate.call_args
            self.assertEqual(method_name, auth_payload['protocol'])

    @mock.patch('keystone.auth.plugins.mapped.PROVIDERS')
    def test_mapped_without_identity_provider_or_protocol(self,
                                                          mock_providers):
        mock_providers.resource_api = mock.Mock()
        mock_providers.federation_api = mock.Mock()
        mock_providers.identity_api = mock.Mock()
        mock_providers.assignment_api = mock.Mock()
        mock_providers.role_api = mock.Mock()

        test_mapped = mapped.Mapped()

        auth_payload = {'identity_provider': 'test_provider'}
        with self.make_request():
            self.assertRaises(
                exception.ValidationError, test_mapped.authenticate,
                auth_payload)

        auth_payload = {'protocol': 'saml2'}
        with self.make_request():
            self.assertRaises(
                exception.ValidationError, test_mapped.authenticate,
                auth_payload)

    def test_supporting_multiple_methods(self):
        method_names = ('saml2', 'openid', 'x509', 'mapped')
        self.useFixture(auth_plugins.LoadAuthPlugins(*method_names))
        for method_name in method_names:
            self._test_mapped_invocation_with_method_name(method_name)


text:
"""
Project:      Voltcraft Data Analyzer
Author:       Valer Bocan, PhD <valer@bocan.ro>
Last updated: June 26th, 2014

Module
description:  The VoltcraftDataFile module processes data files containing history of voltage, current and power factor,
              as generated by the Voltcraft Energy-Logger 4000.

License:      This project is placed in the public domain, hoping that it will be useful to people tinkering with Voltcraft products.

Reference:    Voltcraft File Format: http://www2.produktinfo.conrad.com/datenblaetter/125000-149999/125323-da-01-en-Datenprotokoll_SD_card_file_Formatv1_2.pdf
"""

def DecodeHex(hexinput):
    """
    Converts to hexa each byte in the input tuple, concatenates the result and converts
    the resulting hexadecimal into decimal.
    """
    return int(''.join('{:02x}'.format(x) for x in hexinput), 16)

def DecodeDecimal(hexinput):
    """
    Converts to decimal each byte in the input tuple, concatenates the result and converts
    the resulting string into decimal.
    """
    return int(''.join('{0}'.format(x) for x in hexinput), 10)

redpajama_set_name: RedPajamaGithub


text:
package sage.epg.sd;

import sage.Sage;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Random;

public class SDSageSession extends SDSession
{
  static
  {
    if (Sage.DBG && Sage.getBoolean("debug_sd", false)) enableDebug();
  }

  /**
   * Create a session.
   *

   * The username and password will be saved if they can be used to authenticate successfully.
   * Otherwise, an SDException will be thrown with an appropriate UI message.
   *
   * @param username The username to use for authentication.
   * @param password The password to use for authentication.
   * @throws IOException If there is an I/O related error.
   * @throws SDException If there is a problem authenticating with the Schedules Direct server.
   */
  public SDSageSession(String username, String password) throws IOException, SDException
  {
    super(username, password);
    authenticate();
  }

  @Override
  public InputStreamReader put(URL url, byte[] sendBytes, int off, int len) throws IOException, SDException
  {
    return put(url, sendBytes, off, len, true);
  }

  public InputStreamReader put(URL url, byte[] sendBytes, int off, int len, boolean retry) throws IOException, SDException
  {
    if (SDSession.debugEnabled())
    {
      SDSession.writeDebugLine("PUT " + url.toString() + " (send): " + System.lineSeparator() + new String(sendBytes, off, len));
    }

    // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestMethod("PUT");
    connection.setDoOutput(true);
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
    connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
    // PUT must have a length or we will not get a reply.
    connection.setRequestProperty("Content-Length", Integer.toString(len));
    if (token != null)
      connection.setRequestProperty("token", token);
    try
    {
      // We can timeout just getting the OutputStream.
      OutputStream outStream = connection.getOutputStream();
      outStream.write(sendBytes, off, len);
      outStream.close();

      // Schedules Direct will return an http error 403 if the token has expired. The token can expire
      // because another program is using the same account, so we try once to get the token back.
      if (retry && connection.getResponseCode() == 403)
      {
        token = null;
        authenticate();
        return put(url, sendBytes, off, len, false);
      }

      // We can timeout just getting the InputStream.
      return SDUtils.getStream(connection);
    }
    catch (java.net.SocketTimeoutException e)
    {
      throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
    }
  }

  @Override
  public synchronized InputStreamReader post(URL url, byte sendBytes[], int off, int len) throws IOException, SDException
  {
    return post(url, sendBytes, off, len, true);
  }

  private InputStreamReader post(URL url, byte sendBytes[], int off, int len, boolean retry) throws IOException, SDException
  {
    if (SDSession.debugEnabled())
    {
      SDSession.writeDebugLine("POST " + url.toString() + " (send): " + System.lineSeparator() + new String(sendBytes, off, len));
    }

    // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
    connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
    // POST must have a length or we will not get a reply.
    connection.setRequestProperty("Content-Length", Integer.toString(len));
    if (token != null)
      connection.setRequestProperty("token", token);
    try
    {
      // We can timeout just getting the OutputStream.
      OutputStream outStream = connection.getOutputStream();
      outStream.write(sendBytes, off, len);
      outStream.close();

      // Schedules Direct will return an http error 403 if the token has expired. The token can expire
      // because another program is using the same account, so we try once to get the token back.
      if (retry && connection.getResponseCode() == 403)
      {
        token = null;

        try
        {
          // Wait a random interval between 1 and 30000 milliseconds in case more than one SageTV
          // server is updating at the same time. This should effectively get them out of sync each
          // time they overlap and potentially give the other server a chance to complete it's most
          // recent communication before we get a new token.
          Thread.sleep((new Random()).nextInt(30000) + 1);
        } catch (InterruptedException e) {}

        authenticate();
        return post(url, sendBytes, off, len, false);
      }

      // We can timeout just getting the InputStream.
      return SDUtils.getStream(connection);
    }
    catch (java.net.SocketTimeoutException e)
    {
      throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
    }
  }

  @Override
  public synchronized InputStreamReader get(URL url) throws IOException, SDException
  {
    return get(url, true);
  }

  private InputStreamReader get(URL url, boolean retry) throws IOException, SDException
  {
    if (SDSession.debugEnabled())
    {
      SDSession.writeDebugLine("GET " + url.toString());
    }

    // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
    connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
    if (token != null)
      connection.setRequestProperty("token", token);

    // Schedules Direct will return an http error 403 if the token has expired. The token can expire
    // because another program is using the same account, so we try once to get the token back.
    if (retry && connection.getResponseCode() == 403)
    {
      token = null;

      try
      {
        // Wait a random interval between 1 and 30000 milliseconds in case more than one SageTV
        // server is updating at the same time. This should effectively get them out of sync each
        // time they overlap and potentially give the other server a chance to complete it's most
        // recent communication before we get a new token.
        Thread.sleep((new Random()).nextInt(30000) + 1);
      } catch (InterruptedException e) {}

      authenticate();
      return get(url, false);
    }

    try
    {
      // We can timeout just getting the InputStream.
      return SDUtils.getStream(connection);
    }
    catch (java.net.SocketTimeoutException e)
    {
      throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
    }
  }

  @Override
  public synchronized InputStreamReader delete(URL url) throws IOException, SDException
  {
    return delete(url, true);
  }

  private InputStreamReader delete(URL url, boolean retry) throws IOException, SDException
  {
    if (SDSession.debugEnabled())
    {
      SDSession.writeDebugLine("DELETE " + url.toString());
    }

    // Verified javax.net.ssl.HttpsURLConnection is present in OpenJDK 7+.
    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestMethod("DELETE");
    connection.setConnectTimeout(TIMEOUT);
    connection.setReadTimeout(TIMEOUT);
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Accept-Encoding", "deflate,gzip");
    connection.setRequestProperty("Accept-Charset", "ISO-8859-1");
    if (token != null)
      connection.setRequestProperty("token", token);

    // Schedules Direct will return an http error 403 if the token has expired. The token can expire
    // because another program is using the same account, so we try once to get the token back.
    if (retry && connection.getResponseCode() == 403)
    {
      token = null;
      authenticate();
      return delete(url, false);
    }

    try
    {
      // We can timeout just getting the InputStream.
      return SDUtils.getStream(connection);
    }
    catch (java.net.SocketTimeoutException e)
    {
      throw new SDException(SDErrors.SAGETV_COMMUNICATION_ERROR);
    }
  }
}


text:
layout: base
title:  'Statistics of NUM in UD_Nheengatu-CompLin'
udver: '2'
---

## Treebank Statistics: UD_Nheengatu-CompLin: POS Tags: `NUM`

There are 3 `NUM` lemmas (1%), 3 `NUM` types (0%) and 10 `NUM` tokens (0%).
Out of 15 observed tags, the rank of `NUM` is: 15 in number of lemmas, 15 in number of types and 14 in number of tokens.

The 10 most frequent `NUM` lemmas: musapiri, mukũi, yepé

The 10 most frequent `NUM` types:  musapiri, mukũi, yepé

The 10 most frequent ambiguous lemmas: yepé (<tt>DET</tt> 16, <tt>NUM</tt> 3, <tt>PRON</tt> 3, <tt>PART</tt> 2)

The 10 most frequent ambiguous types:  yepé (<tt>DET</tt> 14, <tt>PRON</tt> 3, <tt>NUM</tt> 2, <tt>PART</tt> 2)

* yepé
  * <tt>DET</tt> 14: Usika yepé mirawasú wírupi , ape ukiri .
  * <tt>PRON</tt> 3: [...] aintá unupá yepé , aintá uyuká yepé , asuí aintá uyapí itá irumu yepé .
  * <tt>NUM</tt> 2: Aité kwá pusanga yaú mairamé uwatari yepé yasí yasupiri rã yané mbira .
  * <tt>PART</tt> 2: Indé rewewé yepé kutara , ma remaã mamentu resika .

## Morphology

The form / lemma ratio of `NUM` is 1.000000 (the average of all parts of speech is 1.226824).

The 1st highest number of forms (1) was observed with the lemma "mukũi": mukũi.

The 2nd highest number of forms (1) was observed with the lemma "musapiri": musapiri.

The 3rd highest number of forms (1) was observed with the lemma "yepé": yepé.

`NUM` occurs with 1 features: <tt>NumType</tt> (10; 100% instances)

`NUM` occurs with 1 feature-value pairs: `NumType=Card`

`NUM` occurs with 1 feature combinations.
The most frequent feature combination is `NumType=Card` (10 tokens).
Examples: musapiri, mukũi, yepé

## Relations

`NUM` nodes are attached to their parents using 2 different relations: <tt>nummod</tt> (7; 70% instances), <tt>nsubj</tt> (3; 30% instances)

Parents of `NUM` nodes belong to 2 different parts of speech: <tt>NOUN</tt> (7; 70% instances), <tt>VERB</tt> (3; 30% instances)

7 (70%) `NUM` nodes are leaves.

2 (20%) `NUM` nodes have one child.

1 (10%) `NUM` nodes have two children.

The highest child degree of a `NUM` node is 2.

Children of `NUM` nodes are attached using 3 different relations: <tt>nmod</tt> (2; 50% instances), <tt>det</tt> (1; 25% instances), <tt>expl</tt> (1; 25% instances)

Children of `NUM` nodes belong to 2 different parts of speech: <tt>PRON</tt> (3; 75% instances), <tt>NOUN</tt> (1; 25% instances)


text:
package org.languagetool.rules.patterns;

import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.RuleMatch;

import java.util.Map;

public class MockFilter extends RuleFilter {

  public MockFilter() {
  }

  @Override
  public RuleMatch acceptRuleMatch(RuleMatch match, Map<String, String> arguments, int patternTokenPos, AnalyzedTokenReadings[] patternTokens) {
    return match;
  }

}


text:
package com.apple.eawt;

/**
 * Common interface for all event listener sub-types.
 * Implementors may implement multiple sub-types, but only need to call {@link Application#addAppEventListener(AppEventListener)} once to receive all notifications.
 *
 * @see AppReOpenedListener
 * @see AppForegroundListener
 * @see AppHiddenListener
 * @see ScreenSleepListener
 * @see SystemSleepListener
 * @see UserSessionListener
 *
 * @since Java for Mac OS X 10.6 Update 3
 * @since Java for Mac OS X 10.5 Update 8
 */
public interface AppEventListener { }


text:
Reading: Chapter 11 of *Head First C*.

1) Read, compile and run `advice_server.c`, which is the example from
page 474 of *Head First C*.

2) In another window, use `telnet` to connect to your server, as on page 475.

3) Read, compile and run `wiki_client.c`, which is based on the
example on page 497.

4) Using `wiki_client.c` as an example, write `advice_client.c`, a
client that connects to `advice_server` and prints a reply.

5) Read, compile and run `ikkp_server.c`, which is based on the
example in on page 483.

6) In another window, use `telnet` to connect to `ikkp_server`, as on page 484.

7) Modify `ikkp_server.c` so it forks a new process for each
connection, as on page 487.

8) See if you can have more than one connection to the server going at
the same time.

9) Check your modified file in to the repo.


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

$lang['imglib_source_image_required']	= 'Ursprungsbild måste anges i inställningarna.';
$lang['imglib_gd_required']		= 'För den här funktionaliteten krävs GD Image Library.';
$lang['imglib_gd_required_for_props']	= 'GD Image Library måste vara installerat på servern för att kunna hämta bildegenskaperna.';
$lang['imglib_unsupported_imagecreate']	= 'Servern stöder inte GD-funktionen som krävs för att behandla bildtypen.';
$lang['imglib_gif_not_supported']	= 'GIF-formatet stöds ofta inte på grund av licenskrav. Använd JPG eller PNG-formatet istället.';
$lang['imglib_jpg_not_supported']	= 'JPG-formatet stöds inte.';
$lang['imglib_png_not_supported']	= 'PNG-formatet stöds inte.';
$lang['imglib_jpg_or_png_required']	= 'Protokollet för skalning av bilder angivet i inställningarna fungerar bara med bildtyperna JPEG och PNG.';
$lang['imglib_copy_error']		= 'Kunde inte byta ut filen. Kontrollera skrivrättigheterna för mappen.';
$lang['imglib_rotate_unsupported']	= 'Servern tycks sakna stöd för att rotera bilder.';
$lang['imglib_libpath_invalid']		= 'Sökvägen till bildmappen är felaktig. Ange rätt sökväg i bildinställningarna.';
$lang['imglib_image_process_failed']	= 'Bildbehandlingen misslyckades. Kontrollera att server stöder valt protokoll och att sökvägen till bildmappen är korrekt.';
$lang['imglib_rotation_angle_required']	= 'En rotationsvinkel måste anges för att rotera bilden.';
$lang['imglib_invalid_path']		= 'Sökvägen till bild-filen är inte korrekt.';
$lang['imglib_copy_failed']		= 'Kunde inte kopiera bilden.';
$lang['imglib_missing_font']		= 'Teckensnitt saknas.';
$lang['imglib_save_failed']		= 'Kunde inte spara bilden. Kontrollera skrivrättigheterna för filen och mappen.';


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta name="generator" content="ApiGen 2.8.0" />

	<title>Class BaseX\Resource\Document | basex-php</title>

	<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />

		Overview

Namespaces

BaseX

Database

Importer

Dav

Iterator

Locks

Error

Iterator

PHPUnit

Query

Resource

Iterator

Session

Silex

Symfony

Security

PHP

Classes

Collection

Document

Raw

Streamable

Tree

Interfaces

CollectionInterface

ResourceInterface

StreamableInterface

	<form id="search">
		<input type="hidden" name="cx" value="" />
		<input type="hidden" name="ie" value="UTF-8" />
		<input type="text" name="q" class="text" />
		<input type="submit" value="Search" />
	</form>

				Overview

				Namespace

Class

				Tree

				Todo

Class Document

BaseX Resource for xml documents.

			BaseX\Resource

			 implements
				BaseX\Resource\ResourceInterface

			BaseX\Resource\Streamable

			 implements
				BaseX\Resource\StreamableInterface

BaseX\Resource\Document

		Namespace: BaseX\Resource

		Package: BaseX

		Located at src/BaseX/Resource/Document.php

Methods summary

			 public

		#
		isRaw( )

			 public
			DOMDocument

		#
		getXML( )

Returns the contents of the document as XML.

Returns the contents of the document as XML.

Returns

					DOMDocument

			 public
			string

		#
		xpath( string <var>$xpath</var> )

Retrieves contents of a document filtered by an XPath expression.

Retrieves contents of a document filtered by an XPath expression.

Parameters

<var>$xpath</var>

string
$xpath An XPath expression to apply to the contents.

Returns

					string
$result

			 public

		#
		getWriteMethod( )

			 public

		#
		getReadMethod( )

			 public

		#
		getContents( )

			 public

		#
		setContents( mixed <var>$data</var> )

Methods inherited from BaseX\Resource\Streamable

			fromSimpleXML(),
			getContentType(),
			getSize(),
			getStream(),
			getUri(),
			refresh(),
			setContentType(),
			setSize()

Methods inherited from BaseX\Resource

			__construct(),
			__toString(),
			copy(),
			delete(),
			exists(),
			getDatabase(),
			getEtag(),
			getModified(),
			getName(),
			getPath(),
			isDeleted(),
			move(),
			parseDate(),
			parseLine(),
			rename(),
			setModified()

Methods inherited from BaseX\Resource\StreamableInterface

			getURI()

Constants inherited from BaseX\Resource

			DATE_FORMAT

Properties inherited from BaseX\Resource\Streamable

			<var>$mime</var>,
			<var>$size</var>

Properties inherited from BaseX\Resource

			<var>$db</var>,
			<var>$deleted</var>,
			<var>$modified</var>,
			<var>$path</var>

		basex-php API documentation generated by ApiGen 2.8.0


text:
require 'ruby-swagger/io/file_system'
require 'ruby-swagger/io/comparable'

module Swagger::IO
  class Definitions

    def self.read_definitions
      definitions = {}

      Swagger::IO::FileSystem.all_files("definitions/**/*.yml").each do |file|
        definitions[File.basename(file, ".yml")] = YAML::load_file(file)
      end

      definitions
    end

    def self.write_definitions(definitions)
      return if definitions.nil?

      #Remove dead definitions
      Swagger::IO::FileSystem.all_files("definitions/**/*.yml").each do |file|
        def_name = File.basename(file, ".yml")

        unless definitions[def_name]
          STDERR.puts "#{def_name} is not present anymore, removing #{file}"
          Swagger::IO::FileSystem.delete_file(file)
        end

      end

      # Write new definitions
      definitions.each do |definition_name, definition|

        # If an old definition exists, we copy over the documentation to the generated definition
        if Swagger::IO::FileSystem.file_exists?("definitions/#{definition_name}.yml")
          old_definition = Swagger::IO::FileSystem.read_file("definitions/#{definition_name}.yml")

          Swagger::IO::Comparable.copy_description_old_definition(definition, old_definition)
        end

        Swagger::IO::FileSystem.write_file(definition.to_yaml, "definitions/#{definition_name}.yml", true)
      end
    end

  end

end


text:
class Object
  def try(*args, &block)
    message, *other_args, options = *args
    if options.is_a?(Hash) && options[:force]
      options.delete(:force)
      other_args.push(options) unless options.empty?
      self && self.public_send(message, *other_args, &block)
    else
      raise NoMethodError, <<-MSG

  Stop! Hold everything!

  I see that you just called "Object#try" on an instance of #{self.class} -
  this probably isn't what you want.

  Please, before you go any further, go read anything by
  Sandi Metz (http://www.sandimetz.com/blog/2014/12/19/suspicions-of-nil), or
  Avdi Grimm (http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/).

  TL;DR - Nil is often a smell that indicates your code could be written differently.
  Inruby, thing.try(:message) is equal to thing && thing.message which is,
  in essence a type check (which you _more than likely_ don't want in your OO code).

  If you would like to continue, change the call to look like this:

  instance.try(<ALL YOUR ARGS>, force: true)
      MSG
    end
  end
end


text:
<!DOCTYPE doctype PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

    <META name="generator" content=
    "HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net">

    <TITLE>Debugger: Stack</TITLE>
    <META http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <LINK rel="stylesheet" type="text/css" href="../../shared/Frontpage.css">

Debugger: Stack

The stack window displays the current trace's execution stack, as unwound and reported by
    the target. Not all debuggers will unwind the stack, in which case, this window displays only
    the innermost frame. When emulation is used to generate the current machine state, only a
    single synthetic frame is shown. Level 0 always refers to the innermost frame, and each
    incremental level refers to the next caller in the chain — most of the time. The current
    frame comprises one element of the tool's current "coordinates." Selecting a frame changes
    those coordinates, potentially causing other windows to display different information. Namely,
    the Registers
    window will show registers for the current frame, assuming they can be retrieved. The Listings
    may also navigate to the current frame's program counter.

Table Columns

The stack table has the following columns:

Level - the level of the frame, counting 0-up starting at the innermost frame.

PC - the address of the instruction to execute next, or upon return of the callee for
      non-0 frames. Different platforms may have different subtleties in how they report PC.
      Double-clicking this field will navigate to the address.

Function - the name of the containing function, if Ghidra has the corresponding module
      image imported and analyzed.

Comment - a user-modifiable comment.


text:
package org.minimalj.example.openapiclient.page;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import org.minimalj.metamodel.model.MjEntity;
import org.minimalj.metamodel.model.MjModel;
import org.minimalj.metamodel.model.MjProperty;
import org.minimalj.model.Model;
import org.minimalj.model.properties.Properties;

public class PropertiesResourceBundle extends ResourceBundle {

	private final Map<String, String> resources = new HashMap<>();

	public PropertiesResourceBundle(Model model) {
		for (Class<?> clazz : model.getEntityClasses()) {
			for (String property : Properties.getProperties(clazz).keySet()) {
				String key = clazz.getSimpleName() + "." + property;
				String name = convert(property);
				resources.put(key, name);
			}
		}
	}

	public PropertiesResourceBundle(MjModel model) {
		for (MjEntity entity : model.entities) {
			for (MjProperty property : entity.properties) {
				String key = entity.getClazz().getSimpleName() + "." + property.name;
				String name = convert(property.name);
				resources.put(key, name);
			}
		}
	}

	private String convert(String key) {
		String result = "";
		for (char c : key.toCharArray()) {
			if (result.length() == 0) {
				result = String.valueOf(Character.toUpperCase(c));
			} else if (Character.isUpperCase(c)) {
				result += " " + c;
			} else {
				result += c;
			}
		}
		result = result.replaceAll(" Of", " of");
		result = result.replaceAll(" From", " from");
		result = result.replaceAll(" To", " to");
		result = result.replaceAll(" Valid", " valid");
		return result;
	}

	@Override
	protected Object handleGetObject(String key) {
		return resources.get(key);
	}

	@Override
	public Enumeration<String> getKeys() {
		List<String> keyList = new ArrayList<>(resources.keySet());
		return new Enumeration<String>() {
			private int i = 0;

			@Override
			public boolean hasMoreElements() {
				return i < keyList.size();
			}

			@Override
			public String nextElement() {
				return keyList.get(i++);
			}
		};
	}

//	@Override
//	public Enumeration<String> getKeys() {
//		return new Enumeration<String>() {
//			@Override
//			public boolean hasMoreElements() {
//				return false;
//			}
//
//			@Override
//			public String nextElement() {
//				return null;
//			}
//		};
//	}
}


text:
{-# LANGUAGE TypeApplications #-}

module Game.Mahjong.Test.HandStat ( tests ) where

import Game.Mahjong.Meld
import Game.Mahjong.Hand
import Game.Mahjong.HandStat
import Game.Mahjong.Static.Examples (allTypesEx1)

import Test.QuickCheck
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck as QC

import Data.Maybe (fromJust)

instance Arbitrary HandStat where
  arbitrary = do
    Positive numOfCoins      <- arbitrary
    Positive numOfBamboos    <- arbitrary
    Positive numOfCharacters <- arbitrary
    Positive numOfWinds      <- arbitrary
    Positive numOfDragons    <- arbitrary
    Positive numOfSimples    <- arbitrary
    Positive numOfTerminals  <- arbitrary
    Positive numOfSequences  <- arbitrary
    Positive numOfTriplets   <- arbitrary
    Positive numOfQuartets   <- arbitrary
    Positive numOfPairs      <- arbitrary
    pure $ HandStat numOfCoins numOfBamboos numOfCharacters
                    numOfWinds numOfDragons
                    numOfSimples numOfTerminals
                    numOfSequences numOfTriplets numOfQuartets numOfPairs

tests :: TestTree
tests = testGroup "Game.Mahjong.HandStat Tests" [
    propertyTests
  , countTests
  ]

-- | Property tests
propertyTests :: TestTree
propertyTests = testGroup "Properties tests" [
    qcPropertyTests
  , qcCountTests
  ]

qcPropertyTests :: TestTree
qcPropertyTests = testGroup "QuickCheck property tests" [
    QC.testProperty "identity on right" $
      \hs -> ((hs :: HandStat) <> mempty)
          == hs
  , QC.testProperty "identity on left" $
      \hs -> (hs :: HandStat)
          == mempty <> hs
  , QC.testProperty "communitivity" $
      \hs1 hs2 -> ((hs1 :: HandStat) <> (hs2 :: HandStat))
                == (hs2 <> hs1)
  , QC.testProperty "associativity" $
      \hs1 hs2 hs3 -> (((hs1 :: HandStat) <> (hs2 :: HandStat)) <> (hs3 :: HandStat))
                   == (hs1 <> (hs2 <> hs3))
  ]

qcCountTests :: TestTree
qcCountTests = testGroup "QuickCheck count tests" [
    QC.testProperty "count numberOfSuits" $
      \hs -> (numOfSuits (hs :: HandStat))
          == (sum $ fmap ($ hs) [numOfCoins, numOfBamboos, numOfCharacters])
  , QC.testProperty "count numberOfHonors" $
      \hs -> (numOfHonors (hs :: HandStat))
          == (sum $ fmap ($ hs) [numOfWinds, numOfDragons])
  , QC.testProperty "count numberOfEdges" $
      \hs -> (numOfEdges (hs :: HandStat))
          == (sum $ fmap ($ hs) [numOfTerminals, numOfWinds, numOfDragons])
  , QC.testProperty "count numberOfMelds" $
      \hs -> (numOfMelds (hs :: HandStat))
          == (sum $ fmap ($ hs) [numOfSequences, numOfTriplets, numOfPairs])
  ]

-- Count tests

countTests :: TestTree
countTests = testGroup "Count tests" [
    testCase "count numOfCoins" $
      numOfCoins stat @?= 1
  , testCase "count numOfBamboos" $
      numOfBamboos stat @?= 1
  , testCase "count numOfCharacters" $
      numOfCharacters stat @?= 1
  , testCase "count numOfWinds" $
      numOfWinds stat @?= 1
  , testCase "count numOfDragons" $
      numOfDragons stat @?= 1
  , testCase "count numOfSimples" $
      numOfSimples stat @?= 2
  , testCase "count numOfTerminals" $
      numOfTerminals stat @?= 1
  , testCase "count numOfSequences" $
      numOfSequences stat @?= 2
  , testCase "count numOfTriplets" $
      numOfTriplets stat @?= 2
  , testCase "count numOfQuartets" $
      numOfQuartets stat @?= 1
  , testCase "count numOfPairs" $
      numOfPairs stat @?= 1
  , testCase "count numOfSuits" $
      numOfSuits stat @?= 3
  , testCase "count numOfHonors" $
      numOfHonors stat @?= 2
  , testCase "count numOfEdges" $
      numOfEdges stat @?= 3
  , testCase "count numOfMelds" $
      numOfMelds stat @?= 5
  ]
  where
    stat = handStat . fromJust $ allTypesEx1


text:
<?php

namespace HVP\CoreModelBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * HolderReference
 */
class HolderReference
{
    /**
     * @var integer
     */
    private $id;

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

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

    /**
     * @var boolean
     */
    private $active;

    /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $Holders;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->Holders = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set ident
     *
     * @param string $ident
     * @return HolderReference
     */
    public function setIdent($ident)
    {
        $this->ident = $ident;

        return $this;
    }

    /**
     * Get ident
     *
     * @return string
     */
    public function getIdent()
    {
        return $this->ident;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return HolderReference
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return HolderReference
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * Add Holders
     *
     * @param \HVP\CoreModelBundle\Entity\Holder $holders
     * @return HolderReference
     */
    public function addHolder(\HVP\CoreModelBundle\Entity\Holder $holders)
    {
        $this->Holders[] = $holders;

        return $this;
    }

    /**
     * Remove Holders
     *
     * @param \HVP\CoreModelBundle\Entity\Holder $holders
     */
    public function removeHolder(\HVP\CoreModelBundle\Entity\Holder $holders)
    {
        $this->Holders->removeElement($holders);
    }

    /**
     * Get Holders
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getHolders()
    {
        return $this->Holders;
    }
    /**
     * @var \HVP\CoreModelBundle\Entity\Holder
     */
    private $Holder;

    /**
     * Set Holder
     *
     * @param \HVP\CoreModelBundle\Entity\Holder $holder
     * @return HolderReference
     */
    public function setHolder(\HVP\CoreModelBundle\Entity\Holder $holder = null)
    {
        $this->Holder = $holder;

        return $this;
    }

    /**
     * Get Holder
     *
     * @return \HVP\CoreModelBundle\Entity\Holder
     */
    public function getHolder()
    {
        return $this->Holder;
    }
}


text:
#import <MapKit/Mapkit.h>

@interface CDebugAnnotation : NSObject<MKAnnotation>

@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, readwrite, copy) NSString *title;

@end


text:
package android.support.v4.view.accessibility;

// Referenced classes of package android.support.v4.view.accessibility:
//            k, e

class f
    implements k
{

    final AccessibilityManagerCompat.AccessibilityStateChangeListenerCompat a;
    final e b;

    f(e e, AccessibilityManagerCompat.AccessibilityStateChangeListenerCompat accessibilitystatechangelistenercompat)
    {
        b = e;
        a = accessibilitystatechangelistenercompat;
        super();
    }

    public void a(boolean flag)
    {
        a.onAccessibilityStateChanged(flag);
    }
}


text:
namespace draco {

using std::unordered_map;

// Shortcut for typed conditionals.
template <bool B, class T, class F>
using conditional_t = typename std::conditional<B, T, F>::type;

Mesh::Mesh() {}

#ifdef DRACO_ATTRIBUTE_DEDUPLICATION_SUPPORTED
void Mesh::ApplyPointIdDeduplication(
    const IndexTypeVector<PointIndex, PointIndex> &id_map,
    const std::vector<PointIndex> &unique_point_ids) {
  PointCloud::ApplyPointIdDeduplication(id_map, unique_point_ids);
  for (FaceIndex f(0); f < num_faces(); ++f) {
    for (int32_t c = 0; c < 3; ++c) {
      faces_[f][c] = id_map[faces_[f][c]];
    }
  }
}
#endif

}  // namespace draco


text:
namespace LinuxPackages.Web.Mvc.Infrastructure.Helpers.Contracts
{
    public interface IUrlIdentifierProvider
    {
        string GenerateIdentifierProviderSalt(int size);

        string EncodeEntityId(int entityId);

        int DecodeEntityId(string urlHash);

        bool IsHashValid(string urlHash);
    }
}


text:
/* This file is part of JnaFileChooser.
 *
 * JnaFileChooser is free software: you can redistribute it and/or modify it
 * under the terms of the new BSD license.
 *
 * JnaFileChooser is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.
 */
package jnafilechooser.api;

import java.awt.Window;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.sun.jna.Platform;

/**
 * JnaFileChooser is a wrapper around the native Windows file chooser
 * and folder browser that falls back to the Swing JFileChooser on platforms
 * other than Windows or if the user chooses a combination of features
 * that are not supported by the native dialogs (for example multiple
 * selection of directories).
 *
 * Example:
 * JnaFileChooser fc = new JnaFileChooser();
 * fc.setFilter("All Files", "*");
 * fc.setFilter("Pictures", "jpg", "jpeg", "gif", "png", "bmp");
 * fc.setMultiSelectionEnabled(true);
 * fc.setMode(JnaFileChooser.Mode.FilesAndDirectories);
 * if (fc.showOpenDialog(parent)) {
 *     Files[] selected = fc.getSelectedFiles();
 *     // do something with selected
 * }
 *
 * @see JFileChooser, WindowsFileChooser, WindowsFileBrowser
 */
public class JnaFileChooser
{
	private static enum Action { Open, Save }

	/**
	 * the availabe selection modes of the dialog
	 */
	public static enum Mode {
		Files(JFileChooser.FILES_ONLY),
		Directories(JFileChooser.DIRECTORIES_ONLY),
		FilesAndDirectories(JFileChooser.FILES_AND_DIRECTORIES);
		private int jFileChooserValue;
		private Mode(int jfcv) {
			this.jFileChooserValue = jfcv;
		}
		public int getJFileChooserValue() {
			return jFileChooserValue;
		}
	}

	protected File[] selectedFiles;
	protected File currentDirectory;
	protected ArrayList<String[]> filters;
	protected boolean multiSelectionEnabled;
	protected Mode mode;

	/**
	 * creates a new file chooser with multiselection disabled and mode set
	 * to allow file selection only.
	 */
	public JnaFileChooser() {
		filters = new ArrayList<String[]>();
		multiSelectionEnabled = false;
		mode = Mode.Files;
		selectedFiles = new File[] { null };
	}

	/**
	 * creates a new file chooser with the specified initial directory
	 *
	 * @param currentDirectory the initial directory
	 */
	public JnaFileChooser(File currentDirectory) {
		this();
		this.currentDirectory = currentDirectory.isDirectory() ?
			currentDirectory : currentDirectory.getParentFile();
	}

	/**
	 * creates a new file chooser with the specified initial directory
	 *
	 * @param currentDirectory the initial directory
	 */
	public JnaFileChooser(String currentDirectoryPath) {
		this(currentDirectoryPath != null ?
			new File(currentDirectoryPath) : null);
	}

	/**
	 * shows a dialog for opening files
	 *
	 * @param parent the parent window
	 *
	 * @return true if the user clicked OK
	 */
	public boolean showOpenDialog(Window parent) {
		return showDialog(parent, Action.Open);
	}

	/**
	 * shows a dialog for saving files
	 *
	 * @param parent the parent window
	 *
	 * @return true if the user clicked OK
	 */
	public boolean showSaveDialog(Window parent) {
		return showDialog(parent, Action.Save);
	}

	private boolean showDialog(Window parent, Action action) {
		// native windows filechooser doesn't support mixed selection mode
		if (Platform.isWindows() && mode != Mode.FilesAndDirectories) {
			// windows filechooser can only multiselect files
			if (multiSelectionEnabled && mode == Mode.Files) {
				// TODO Here we would use the native windows dialog
				// to choose multiple files. However I haven't been able
				// to get it to work properly yet because it requires
				// tricky callback magic and somehow this didn't work for me
				// quite as documented (probably because I messed something up).
				// Because I don't need this feature right now I've put it on
				// hold to get on with stuff.
				// Example code: http://support.microsoft.com/kb/131462/en-us
				// GetOpenFileName: http://msdn.microsoft.com/en-us/library/ms646927.aspx
				// OFNHookProc: http://msdn.microsoft.com/en-us/library/ms646931.aspx
				// CDN_SELCHANGE: http://msdn.microsoft.com/en-us/library/ms646865.aspx
				// SendMessage: http://msdn.microsoft.com/en-us/library/ms644950.aspx
			}
			else if (!multiSelectionEnabled) {
				if (mode == Mode.Files) {
					return showWindowsFileChooser(parent, action);
				}
				else if (mode == Mode.Directories) {
					return showWindowsFolderBrowser(parent);
				}
			}
		}

		// fallback to Swing
		return showSwingFileChooser(parent, action);
	}

	private boolean showSwingFileChooser(Window parent, Action action) {
		final JFileChooser fc = new JFileChooser(currentDirectory);
		fc.setMultiSelectionEnabled(multiSelectionEnabled);
		fc.setFileSelectionMode(mode.getJFileChooserValue());

		// build filters
		if (filters.size() > 0) {
			boolean useAcceptAllFilter = false;
			for (final String[] spec : filters) {
				// the "All Files" filter is handled specially by JFileChooser
				if (spec[1].equals("*")) {
					useAcceptAllFilter = true;
					continue;
				}
				fc.addChoosableFileFilter(new FileNameExtensionFilter(
					spec[0], Arrays.copyOfRange(spec, 1, spec.length)));
			}
			fc.setAcceptAllFileFilterUsed(useAcceptAllFilter);
		}

		int result = -1;
		if (action == Action.Open) {
			result = fc.showOpenDialog(parent);
		}
		else {
			result = fc.showSaveDialog(parent);
		}
		if (result == JFileChooser.APPROVE_OPTION) {
			selectedFiles = multiSelectionEnabled ?
				fc.getSelectedFiles() : new File[] { fc.getSelectedFile() };
			currentDirectory = fc.getCurrentDirectory();
			return true;
		}

		return false;
	}

	private boolean showWindowsFileChooser(Window parent, Action action) {
		final WindowsFileChooser fc = new WindowsFileChooser(currentDirectory);
		fc.setFilters(filters);
		final boolean result = fc.showDialog(parent, action == Action.Open);
		if (result) {
			selectedFiles = new File[] { fc.getSelectedFile() };
			currentDirectory = fc.getCurrentDirectory();
		}
		return result;
	}

	private boolean showWindowsFolderBrowser(Window parent) {
		final WindowsFolderBrowser fb = new WindowsFolderBrowser();
		final File file = fb.showDialog(parent);
		if (file != null) {
			selectedFiles = new File[] { file };
			currentDirectory = file.getParentFile() != null ?
				file.getParentFile() : file;
			return true;
		}

		return false;
	}

	/**
	 * add a filter to the user-selectable list of file filters
	 *
	 * @param filter you must pass at least 2 arguments, the first argument
	 *               is the name of this filter and the remaining arguments
	 *               are the file extensions.
	 *
	 * @throws IllegalArgumentException if less than 2 arguments are passed
	 */
	public void addFilter(String ... values) {
		if (values.length < 2) {
			throw new IllegalArgumentException();
		}
		filters.add(values);
	}

	/**
	 * sets the selection mode
	 *
	 * @param mode the selection mode
	 */
	public void setMode(Mode mode) {
		this.mode = mode;
	}

	public Mode getMode() {
		return mode;
	}

	/**
	 * sets whether to enable multiselection
	 *
	 * @param enabled true to enable multiselection, false to disable it
	 */
	public void setMultiSelectionEnabled(boolean enabled) {
		this.multiSelectionEnabled = enabled;
	}

	public boolean isMultiSelectionEnabled() {
		return multiSelectionEnabled;
	}

	public File[] getSelectedFiles() {
		return selectedFiles;
	}

	public File getSelectedFile() {
		return selectedFiles[0];
	}

	public File getCurrentDirectory() {
		return currentDirectory;
	}
}


text:
package com.google.android.exoplayer2.ext.ima;

import android.content.Context;
import android.net.Uri;
import android.os.SystemClock;
import android.util.Log;
import android.view.ViewGroup;
import com.google.ads.interactivemedia.v3.api.Ad;
import com.google.ads.interactivemedia.v3.api.AdDisplayContainer;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent;
import com.google.ads.interactivemedia.v3.api.AdErrorEvent.AdErrorListener;
import com.google.ads.interactivemedia.v3.api.AdEvent;
import com.google.ads.interactivemedia.v3.api.AdEvent.AdEventListener;
import com.google.ads.interactivemedia.v3.api.AdPodInfo;
import com.google.ads.interactivemedia.v3.api.AdsLoader;
import com.google.ads.interactivemedia.v3.api.AdsLoader.AdsLoadedListener;
import com.google.ads.interactivemedia.v3.api.AdsManager;
import com.google.ads.interactivemedia.v3.api.AdsManagerLoadedEvent;
import com.google.ads.interactivemedia.v3.api.AdsRenderingSettings;
import com.google.ads.interactivemedia.v3.api.AdsRequest;
import com.google.ads.interactivemedia.v3.api.ImaSdkFactory;
import com.google.ads.interactivemedia.v3.api.ImaSdkSettings;
import com.google.ads.interactivemedia.v3.api.player.ContentProgressProvider;
import com.google.ads.interactivemedia.v3.api.player.VideoAdPlayer;
import com.google.ads.interactivemedia.v3.api.player.VideoProgressUpdate;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerLibraryInfo;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.util.Assertions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Loads ads using the IMA SDK. All methods are called on the main thread.
 */
/* package */ final class ImaAdsLoader implements ExoPlayer.EventListener, VideoAdPlayer,
    ContentProgressProvider, AdErrorListener, AdsLoadedListener, AdEventListener {

  private static final boolean DEBUG = false;
  private static final String TAG = "ImaAdsLoader";

  /**
   * Listener for ad loader events. All methods are called on the main thread.
   */
  public interface EventListener {

    /**
     * Called when the timestamps of ad breaks are known.
     *
     * @param adBreakTimesUs The times of ad breaks, in microseconds.
     */
    void onAdBreakTimesUsLoaded(long[] adBreakTimesUs);

    /**
     * Called when the URI for the media of an ad has been loaded.
     *
     * @param adBreakIndex The index of the ad break containing the ad with the media URI.
     * @param adIndexInAdBreak The index of the ad in its ad break.
     * @param uri The URI for the ad's media.
     */
    void onUriLoaded(int adBreakIndex, int adIndexInAdBreak, Uri uri);

    /**
     * Called when the {@link Ad} instance for a specified ad has been loaded.
     *
     * @param adBreakIndex The index of the ad break containing the ad.
     * @param adIndexInAdBreak The index of the ad in its ad break.
     * @param ad The {@link Ad} instance for the ad.
     */
    void onAdLoaded(int adBreakIndex, int adIndexInAdBreak, Ad ad);

    /**
     * Called when the specified ad break has been played to the end.
     *
     * @param adBreakIndex The index of the ad break.
     */
    void onAdBreakPlayedToEnd(int adBreakIndex);

    /**
     * Called when there was an error loading ads.
     *
     * @param error The error.
     */
    void onLoadError(IOException error);

  }

  /**
   * Whether to enable preloading of ads in {@link AdsRenderingSettings}.
   */
  private static final boolean ENABLE_PRELOADING = true;

  private static final String IMA_SDK_SETTINGS_PLAYER_TYPE = "google/exo.ext.ima";
  private static final String IMA_SDK_SETTINGS_PLAYER_VERSION = ExoPlayerLibraryInfo.VERSION;

  /**
   * Threshold before the end of content at which IMA is notified that content is complete if the
   * player buffers, in milliseconds.
   */
  private static final long END_OF_CONTENT_POSITION_THRESHOLD_MS = 5000;

  private final EventListener eventListener;
  private final ExoPlayer player;
  private final Timeline.Period period;
  private final List<VideoAdPlayerCallback> adCallbacks;
  private final AdsLoader adsLoader;

  private AdsManager adsManager;
  private AdTimeline adTimeline;
  private long contentDurationMs;
  private int lastContentPeriodIndex;

  private int playerPeriodIndex;

  private boolean released;

  // Fields tracking IMA's state.

  /**
   * The index of the current ad break that IMA is loading.
   */
  private int adBreakIndex;
  /**
   * The index of the ad within its ad break, in {@link #loadAd(String)}.
   */
  private int adIndexInAdBreak;
  /**
   * The total number of ads in the current ad break, or {@link C#INDEX_UNSET} if unknown.
   */
  private int adCountInAdBreak;

  /**
   * Tracks the period currently being played in IMA's model of playback.
   */
  private int imaPeriodIndex;
  /**
   * Whether the period at {@link #imaPeriodIndex} is an ad.
   */
  private boolean isAdDisplayed;
  /**
   * Whether {@link AdsLoader#contentComplete()} has been called since starting ad playback.
   */
  private boolean sentContentComplete;
  /**
   * If {@link #isAdDisplayed} is set, stores whether IMA has called {@link #playAd()} and not
   * {@link #stopAd()}.
   */
  private boolean playingAd;
  /**
   * If {@link #isAdDisplayed} is set, stores whether IMA has called {@link #pauseAd()} since a
   * preceding call to {@link #playAd()} for the current ad.
   */
  private boolean pausedInAd;
  /**
   * If a content period has finished but IMA has not yet sent an ad event with
   * {@link AdEvent.AdEventType#CONTENT_PAUSE_REQUESTED}, stores the value of
   * {@link SystemClock#elapsedRealtime()} when the content stopped playing. This can be used to
   * determine a fake, increasing content position. {@link C#TIME_UNSET} otherwise.
   */
  private long fakeContentProgressElapsedRealtimeMs;

  /**
   * Creates a new IMA ads loader.
   *
   * @param context The context.
   * @param adTagUri The {@link Uri} of an ad tag compatible with the Android IMA SDK. See
   *     https://developers.google.com/interactive-media-ads/docs/sdks/android/compatibility for
   *     more information.
   * @param adUiViewGroup A {@link ViewGroup} on top of the player that will show any ad UI.
   * @param imaSdkSettings {@link ImaSdkSettings} used to configure the IMA SDK, or {@code null} to
   *     use the default settings. If set, the player type and version fields may be overwritten.
   * @param player The player instance that will play the loaded ad schedule. The player's timeline
   *     must be an {@link AdTimeline} matching the loaded ad schedule.
   * @param eventListener Listener for ad loader events.
   */
  public ImaAdsLoader(Context context, Uri adTagUri, ViewGroup adUiViewGroup,
      ImaSdkSettings imaSdkSettings, ExoPlayer player, EventListener eventListener) {
    this.eventListener = eventListener;
    this.player = player;
    period = new Timeline.Period();
    adCallbacks = new ArrayList<>(1);

    lastContentPeriodIndex = C.INDEX_UNSET;
    adCountInAdBreak = C.INDEX_UNSET;
    fakeContentProgressElapsedRealtimeMs = C.TIME_UNSET;

    player.addListener(this);

    ImaSdkFactory imaSdkFactory = ImaSdkFactory.getInstance();
    AdDisplayContainer adDisplayContainer = imaSdkFactory.createAdDisplayContainer();
    adDisplayContainer.setPlayer(this);
    adDisplayContainer.setAdContainer(adUiViewGroup);

    if (imaSdkSettings == null) {
      imaSdkSettings = imaSdkFactory.createImaSdkSettings();
    }
    imaSdkSettings.setPlayerType(IMA_SDK_SETTINGS_PLAYER_TYPE);
    imaSdkSettings.setPlayerVersion(IMA_SDK_SETTINGS_PLAYER_VERSION);

    AdsRequest request = imaSdkFactory.createAdsRequest();
    request.setAdTagUrl(adTagUri.toString());
    request.setAdDisplayContainer(adDisplayContainer);
    request.setContentProgressProvider(this);

    adsLoader = imaSdkFactory.createAdsLoader(context, imaSdkSettings);
    adsLoader.addAdErrorListener(this);
    adsLoader.addAdsLoadedListener(this);
    adsLoader.requestAds(request);
  }

  /**
   * Releases the loader. Must be called when the instance is no longer needed.
   */
  public void release() {
    if (adsManager != null) {
      adsManager.destroy();
      adsManager = null;
    }
    player.removeListener(this);
    released = true;
  }

  // AdsLoader.AdsLoadedListener implementation.

  @Override
  public void onAdsManagerLoaded(AdsManagerLoadedEvent adsManagerLoadedEvent) {
    adsManager = adsManagerLoadedEvent.getAdsManager();
    adsManager.addAdErrorListener(this);
    adsManager.addAdEventListener(this);
    if (ENABLE_PRELOADING) {
      ImaSdkFactory imaSdkFactory = ImaSdkFactory.getInstance();
      AdsRenderingSettings adsRenderingSettings = imaSdkFactory.createAdsRenderingSettings();
      adsRenderingSettings.setEnablePreloading(true);
      adsManager.init(adsRenderingSettings);
      if (DEBUG) {
        Log.d(TAG, "Initialized with preloading");
      }
    } else {
      adsManager.init();
      if (DEBUG) {
        Log.d(TAG, "Initialized without preloading");
      }
    }
    eventListener.onAdBreakTimesUsLoaded(getAdBreakTimesUs(adsManager.getAdCuePoints()));
  }

  // AdEvent.AdEventListener implementation.

  @Override
  public void onAdEvent(AdEvent adEvent) {
    if (DEBUG) {
      Log.d(TAG, "onAdEvent " + adEvent.getType());
    }
    if (released) {
      // The ads manager may pass CONTENT_RESUME_REQUESTED after it is destroyed.
      return;
    }
    switch (adEvent.getType()) {
      case LOADED:
        adsManager.start();
        break;
      case STARTED:
        // Note: This event is sometimes delivered several seconds after playAd is called.
        // See [Internal: b/37775441].
        Ad ad = adEvent.getAd();
        AdPodInfo adPodInfo = ad.getAdPodInfo();
        adCountInAdBreak = adPodInfo.getTotalAds();
        int adPosition = adPodInfo.getAdPosition();
        eventListener.onAdLoaded(adBreakIndex, adPosition - 1, ad);
        if (DEBUG) {
          Log.d(TAG, "Started ad " + adPosition + " of " + adCountInAdBreak + " in ad break "
              + adBreakIndex);
        }
        break;
      case CONTENT_PAUSE_REQUESTED:
        // After CONTENT_PAUSE_REQUESTED, IMA will playAd/pauseAd/stopAd to show one or more ads
        // before sending CONTENT_RESUME_REQUESTED.
        pauseContentInternal();
        break;
      case SKIPPED: // Fall through.
      case CONTENT_RESUME_REQUESTED:
        resumeContentInternal();
        break;
      case ALL_ADS_COMPLETED:
        // Do nothing. The ads manager will be released when the source is released.
      default:
        break;
    }
  }

  // AdErrorEvent.AdErrorListener implementation.

  @Override
  public void onAdError(AdErrorEvent adErrorEvent) {
    if (DEBUG) {
      Log.d(TAG, "onAdError " + adErrorEvent);
    }
    IOException exception = new IOException("Ad error: " + adErrorEvent, adErrorEvent.getError());
    eventListener.onLoadError(exception);
    // TODO: Provide a timeline to the player if it doesn't have one yet, so the content can play.
  }

  // ContentProgressProvider implementation.

  @Override
  public VideoProgressUpdate getContentProgress() {
    if (fakeContentProgressElapsedRealtimeMs != C.TIME_UNSET) {
      long contentEndTimeMs = C.usToMs(adTimeline.getContentEndTimeUs(imaPeriodIndex));
      long elapsedSinceEndMs = SystemClock.elapsedRealtime() - fakeContentProgressElapsedRealtimeMs;
      return new VideoProgressUpdate(contentEndTimeMs + elapsedSinceEndMs, contentDurationMs);
    }

    if (adTimeline == null || isAdDisplayed || imaPeriodIndex != playerPeriodIndex
        || contentDurationMs == C.TIME_UNSET) {
      return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
    }
    checkForContentComplete();
    long positionMs = C.usToMs(adTimeline.getContentStartTimeUs(imaPeriodIndex))
        + player.getCurrentPosition();
    return new VideoProgressUpdate(positionMs, contentDurationMs);
  }

  // VideoAdPlayer implementation.

  @Override
  public VideoProgressUpdate getAdProgress() {
    if (adTimeline == null || !isAdDisplayed || imaPeriodIndex != playerPeriodIndex
        || adTimeline.getPeriod(imaPeriodIndex, period).getDurationUs() == C.TIME_UNSET) {
      return VideoProgressUpdate.VIDEO_TIME_NOT_READY;
    }
    return new VideoProgressUpdate(player.getCurrentPosition(), period.getDurationMs());
  }

  @Override
  public void loadAd(String adUriString) {
    if (DEBUG) {
      Log.d(TAG, "loadAd at index " + adIndexInAdBreak + " in ad break " + adBreakIndex);
    }
    eventListener.onUriLoaded(adBreakIndex, adIndexInAdBreak, Uri.parse(adUriString));
    adIndexInAdBreak++;
  }

  @Override
  public void addCallback(VideoAdPlayerCallback videoAdPlayerCallback) {
    adCallbacks.add(videoAdPlayerCallback);
  }

  @Override
  public void removeCallback(VideoAdPlayerCallback videoAdPlayerCallback) {
    adCallbacks.remove(videoAdPlayerCallback);
  }

  @Override
  public void playAd() {
    if (DEBUG) {
      Log.d(TAG, "playAd");
    }
    Assertions.checkState(isAdDisplayed);
    if (playingAd && !pausedInAd) {
      // Work around an issue where IMA does not always call stopAd before resuming content.
      // See [Internal: b/38354028].
      if (DEBUG) {
        Log.d(TAG, "Unexpected playAd without stopAd");
      }
      stopAdInternal();
    }
    player.setPlayWhenReady(true);
    if (!playingAd) {
      playingAd = true;
      for (VideoAdPlayerCallback callback : adCallbacks) {
        callback.onPlay();
      }
    } else if (pausedInAd) {
      pausedInAd = false;
      for (VideoAdPlayerCallback callback : adCallbacks) {
        callback.onResume();
      }
    }
  }

  @Override
  public void stopAd() {
    if (!playingAd) {
      if (DEBUG) {
        Log.d(TAG, "Ignoring unexpected stopAd");
      }
      return;
    }
    if (DEBUG) {
      Log.d(TAG, "stopAd");
    }
    stopAdInternal();
  }

  @Override
  public void pauseAd() {
    if (DEBUG) {
      Log.d(TAG, "pauseAd");
    }
    if (released || !playingAd) {
      // This method is called after content is resumed, and may also be called after release.
      return;
    }
    pausedInAd = true;
    player.setPlayWhenReady(false);
    for (VideoAdPlayerCallback callback : adCallbacks) {
      callback.onPause();
    }
  }

  @Override
  public void resumeAd() {
    // This method is never called. See [Internal: b/18931719].
    throw new IllegalStateException();
  }

  // ExoPlayer.EventListener implementation.

  @Override
  public void onTimelineChanged(Timeline timeline, Object manifest) {
    if (timeline.isEmpty()) {
      // The player is being re-prepared and this source will be released.
      return;
    }
    if (adTimeline == null) {
      // TODO: Handle initial seeks after the first period.
      isAdDisplayed = timeline.getPeriod(0, period).isAd;
      imaPeriodIndex = 0;
      player.seekTo(0, 0);
    }
    adTimeline = (AdTimeline) timeline;
    contentDurationMs = C.usToMs(adTimeline.getContentDurationUs());
    lastContentPeriodIndex = adTimeline.getPeriodCount() - 1;
    while (adTimeline.isPeriodAd(lastContentPeriodIndex)) {
      // All timelines have at least one content period.
      lastContentPeriodIndex--;
    }
  }

  @Override
  public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
    // Do nothing.
  }

  @Override
  public void onLoadingChanged(boolean isLoading) {
    // Do nothing.
  }

  @Override
  public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
    if (playbackState == ExoPlayer.STATE_BUFFERING && playWhenReady) {
      checkForContentComplete();
    } else if (playbackState == ExoPlayer.STATE_ENDED && isAdDisplayed) {
      // IMA is waiting for the ad playback to finish so invoke the callback now.
      // Either CONTENT_RESUME_REQUESTED will be passed next, or playAd will be called again.
      for (VideoAdPlayerCallback callback : adCallbacks) {
        callback.onEnded();
      }
    }
  }

  @Override
  public void onRepeatModeChanged(int repeatMode) {
    // Do nothing.
  }

  @Override
  public void onPlayerError(ExoPlaybackException error) {
    if (isAdDisplayed && adTimeline.isPeriodAd(playerPeriodIndex)) {
      for (VideoAdPlayerCallback callback : adCallbacks) {
        callback.onError();
      }
    }
  }

  @Override
  public void onPositionDiscontinuity() {
    if (player.getCurrentPeriodIndex() == playerPeriodIndex + 1) {
      if (isAdDisplayed) {
        // IMA is waiting for the ad playback to finish so invoke the callback now.
        // Either CONTENT_RESUME_REQUESTED will be passed next, or playAd will be called again.
        for (VideoAdPlayerCallback callback : adCallbacks) {
          callback.onEnded();
        }
      } else {
        player.setPlayWhenReady(false);
        if (imaPeriodIndex == playerPeriodIndex) {
          // IMA hasn't sent CONTENT_PAUSE_REQUESTED yet, so fake the content position.
          Assertions.checkState(fakeContentProgressElapsedRealtimeMs == C.TIME_UNSET);
          fakeContentProgressElapsedRealtimeMs = SystemClock.elapsedRealtime();
        }
      }
    }
    playerPeriodIndex = player.getCurrentPeriodIndex();
  }

  @Override
  public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
    // Do nothing.
  }

  // Internal methods.

  /**
   * Resumes the player, ensuring the current period is a content period by seeking if necessary.
   */
  private void resumeContentInternal() {
    if (adTimeline != null) {
      if (imaPeriodIndex < lastContentPeriodIndex) {
        if (playingAd) {
          // Work around an issue where IMA does not always call stopAd before resuming content.
          // See [Internal: b/38354028].
          if (DEBUG) {
            Log.d(TAG, "Unexpected CONTENT_RESUME_REQUESTED without stopAd");
          }
          stopAdInternal();
        }
        while (adTimeline.isPeriodAd(imaPeriodIndex)) {
          imaPeriodIndex++;
        }
        synchronizePlayerToIma();
      }
    }
    player.setPlayWhenReady(true);
  }

  /**
   * Pauses the player, and ensures that the current period is an ad period by seeking if necessary.
   */
  private void pauseContentInternal() {
    // IMA is requesting to pause content, so stop faking the content position.
    fakeContentProgressElapsedRealtimeMs = C.TIME_UNSET;
    if (adTimeline != null && !isAdDisplayed) {
      // Seek to the next ad.
      while (!adTimeline.isPeriodAd(imaPeriodIndex)) {
        imaPeriodIndex++;
      }
      synchronizePlayerToIma();
    } else {
      // IMA is sending an initial CONTENT_PAUSE_REQUESTED before a pre-roll ad.
      Assertions.checkState(playerPeriodIndex == 0 && imaPeriodIndex == 0);
    }
    player.setPlayWhenReady(false);
  }

  /**
   * Stops the currently playing ad, seeking to the next content period if there is one. May only be
   * called when {@link #playingAd} is {@code true}.
   */
  private void stopAdInternal() {
    Assertions.checkState(playingAd);
    if (imaPeriodIndex != adTimeline.getPeriodCount() - 1) {
      player.setPlayWhenReady(false);
      imaPeriodIndex++;
      if (!adTimeline.isPeriodAd(imaPeriodIndex)) {
        eventListener.onAdBreakPlayedToEnd(adBreakIndex);
        adBreakIndex++;
        adIndexInAdBreak = 0;
      }
      synchronizePlayerToIma();
    } else {
      eventListener.onAdBreakPlayedToEnd(adTimeline.getAdBreakIndex(imaPeriodIndex));
    }
  }

  private void synchronizePlayerToIma() {
    if (playerPeriodIndex != imaPeriodIndex) {
      player.seekTo(imaPeriodIndex, 0);
    }

    isAdDisplayed = adTimeline.isPeriodAd(imaPeriodIndex);
    // If an ad is displayed, these flags will be updated in response to playAd/pauseAd/stopAd until
    // the content is resumed.
    playingAd = false;
    pausedInAd = false;
  }

  private void checkForContentComplete() {
    if (adTimeline == null || isAdDisplayed || sentContentComplete) {
      return;
    }
    long positionMs = C.usToMs(adTimeline.getContentStartTimeUs(imaPeriodIndex))
        + player.getCurrentPosition();
    if (playerPeriodIndex == lastContentPeriodIndex
        && positionMs + END_OF_CONTENT_POSITION_THRESHOLD_MS
        >= C.usToMs(adTimeline.getContentEndTimeUs(playerPeriodIndex))) {
      adsLoader.contentComplete();
      if (DEBUG) {
        Log.d(TAG, "adsLoader.contentComplete");
      }
      sentContentComplete = true;
    }
  }

  private static long[] getAdBreakTimesUs(List<Float> cuePoints) {
    if (cuePoints.isEmpty()) {
      // If no cue points are specified, there is a preroll ad break.
      return new long[] {0};
    }

    int count = cuePoints.size();
    long[] adBreakTimesUs = new long[count];
    for (int i = 0; i < count; i++) {
      double cuePoint = cuePoints.get(i);
      adBreakTimesUs[i] = cuePoint == -1.0 ? C.TIME_UNSET : (long) (C.MICROS_PER_SECOND * cuePoint);
    }
    return adBreakTimesUs;
  }

}


text:
<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Patents extends Migration
{
	public function up()
	{
		//
        $this->forge->addField([
            'id_p' => [
                'type' => 'INT',
                'auto_increment' => true
            ],
            'p_ip' => [
                'type' => 'VARCHAR',
                'constraint' => '20'
            ],
            'p_family' => [
                'type' => 'VARCHAR',
                'constraint' => '20'
			],
            'p_title' => [
                'type' => 'TEXT'
			],

			'created_at datetime default current_timestamp',
            'updated_at datetime default current_timestamp on update current_timestamp'
        ]);
        $this->forge->addKey('id_p', true);
        $this->forge->createTable('patents');
	}

	public function down()
	{
		//
	}
}


text:
<?php

namespace common\models;

use common\models\query\ProductTagQuery;
use Yii;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%product_tag}}".
 *
 * @property integer $product_id
 * @property integer $tag_id
 *
 * @property Product $product
 * @property Tag $tag
 */
class ProductTag extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_tag}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'tag_id'], 'required'],
            [['product_id', 'tag_id'], 'integer'],
            [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'id']],
            [['tag_id'], 'exist', 'skipOnError' => true, 'targetClass' => Tag::className(), 'targetAttribute' => ['tag_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'product_id' => 'Product ID',
            'tag_id' => 'Tag ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTag()
    {
        return $this->hasOne(Tag::className(), ['id' => 'tag_id']);
    }

    /**
     * @inheritdoc
     * @return ProductTagQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new ProductTagQuery(get_called_class());
    }
}


text:
from Module import AbstractModule

class Module(AbstractModule):
    def __init__(self):
        AbstractModule.__init__(self)

    def run(
        self, network, in_data, out_attributes, user_options, num_cores,
        out_path):
        from genomicode import alignlib

        alignlib.standardize_reference_genome(
            in_data.identifier, out_path, use_symlinks=True)

    def name_outfile(self, antecedents, user_options):
        return "reference.samtools"

    def set_out_attributes(self, in_data, out_attributes):
        from genomicode import alignlib

        ref = alignlib.create_reference_genome(in_data.identifier)

        is_indexed = "yes"
        if not ref.samtools_index:
            is_indexed = "no"

        attrs = out_attributes.copy()
        attrs["samtools_indexed"] = is_indexed
        return attrs


text:
'use strict';

const path = require('path');
const log4js = require('log4js');

const config = require(path.join(global.ROOT_PATH, "/config"));
log4js.configure(config.logger);

var logger = log4js.getLogger(config.logLevel);
logger.connectLogger = log4js.connectLogger(logger, {
  level: 'trace',
  format: config.logFormat
});

module.exports = logger;


text:
package org.hawkular.inventory.rest;

import org.hawkular.inventory.api.paging.Page;
import org.hawkular.inventory.api.paging.PageContext;
import org.hawkular.inventory.rest.json.Link;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Lukas Krejci
 * @author Heiko W. Rupp
 * @since 0.0.1
 */
final class ResponseUtil {

    /**
     * This method exists solely to concentrate usage of {@link javax.ws.rs.core.Response#created(java.net.URI)} into
     * one place until this JIRA is resolved somehow.
     *
     * @param info the UriInfo instance of the current request
     * @param id   the ID of a newly created entity under the base
     * @return the response builder with status 201 and location set to the entity with the provided id.
     */
    public static Response.ResponseBuilder created(UriInfo info, String id) {
        return Response.status(Response.Status.CREATED).location(info.getRequestUriBuilder().path(id).build());
    }

    public static <T> Response.ResponseBuilder pagedResponse(Response.ResponseBuilder response, UriInfo uriInfo,
            Page<T> page) {

        //extract the data out of the page
        List<T> data = new ArrayList<>(page);
        return pagedResponse(response, uriInfo, page, data);
    }

    public static <T> Response.ResponseBuilder pagedResponse(Response.ResponseBuilder response, UriInfo uriInfo,
                                                             Page<T> page, Object data) {
        response.entity(data);
        createPagingHeader(response, uriInfo, page);
        return response;
    }

    /**
     * Create the paging headers for collections and attach them to the passed builder. Those are represented as
     * Link: http headers that carry the URL for the pages and the respective relation.
     *
In addition a X-Total-Count header is created that contains the whole collection size.
     *
     * @param builder    The ResponseBuilder that receives the headers
     * @param uriInfo    The uriInfo of the incoming request to build the urls
     * @param resultList The collection with its paging information
     */
    public static void createPagingHeader(final Response.ResponseBuilder builder, final UriInfo uriInfo,
            final Page<?> resultList) {

        UriBuilder uriBuilder;

        PageContext pc = resultList.getPageContext();
        int page = pc.getPageNumber();

        List<Link> links = new ArrayList<>();

        if (pc.isLimited() && resultList.getTotalSize() > (pc.getPageNumber() + 1) * pc.getPageSize()) {
            int nextPage = page + 1;
            uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed
            uriBuilder.replaceQueryParam("page", nextPage);

            links.add(new Link("next", uriBuilder.build().toString()));
        }

        if (page > 0) {
            int prevPage = page - 1;
            uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed
            uriBuilder.replaceQueryParam("page", prevPage);
            links.add(new Link("prev", uriBuilder.build().toString()));
        }

        // A link to the last page
        if (pc.isLimited()) {
            long lastPage = resultList.getTotalSize() / pc.getPageSize();
            if (resultList.getTotalSize() % pc.getPageSize() == 0) {
                lastPage -= 1;
            }

            uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed
            uriBuilder.replaceQueryParam("page", lastPage);
            links.add(new Link("last", uriBuilder.build().toString()));
        }

        // A link to the current page
        uriBuilder = uriInfo.getRequestUriBuilder(); // adds ?q, ?per_page, ?page, etc. if needed

        StringBuilder linkHeader = new StringBuilder(new Link("current", uriBuilder.build().toString())
                .rfc5988String());

        //followed by the rest of the link defined above
        links.forEach((l) -> linkHeader.append(", ").append(l.rfc5988String()));

        //add that all as a single Link header to the response
        builder.header("Link", linkHeader.toString());

        // Create a total size header
        builder.header("X-Total-Count", resultList.getTotalSize());
    }
}


text:
package git

import (
	"errors"
	"fmt"
	"net/url"
	"path"

	gerritsource "k8s.io/test-infra/prow/gerrit/source"
)

// RemoteResolverFactory knows how to construct remote resolvers for
// authoritative central remotes (to pull from) and publish remotes
// (to push to) for a repository. These resolvers are called at run-time
// to determine remotes for git commands.
type RemoteResolverFactory interface {
	// CentralRemote returns a resolver for a remote server with an
	// authoritative version of the repository. This type of remote
	// is useful for fetching refs and cloning.
	CentralRemote(org, repo string) RemoteResolver
	// PublishRemote returns a resolver for a remote server with a
	// personal fork of the repository. This type of remote is most
	// useful for publishing local changes.
	PublishRemote(org, repo string) RemoteResolver
}

// RemoteResolver knows how to construct a remote URL for git calls
type RemoteResolver func() (string, error)

// LoginGetter fetches a GitHub login on-demand
type LoginGetter func() (login string, err error)

// TokenGetter fetches a GitHub OAuth token on-demand
type TokenGetter func() []byte

type sshRemoteResolverFactory struct {
	host     string
	username LoginGetter
}

// CentralRemote creates a remote resolver that refers to an authoritative remote
// for the repository.
func (f *sshRemoteResolverFactory) CentralRemote(org, repo string) RemoteResolver {
	remote := fmt.Sprintf("git@%s:%s/%s.git", f.host, org, repo)
	return func() (string, error) {
		return remote, nil
	}
}

// PublishRemote creates a remote resolver that refers to a user's remote
// for the repository that can be published to.
func (f *sshRemoteResolverFactory) PublishRemote(_, repo string) RemoteResolver {
	return func() (string, error) {
		org, err := f.username()
		if err != nil {
			return "", err
		}
		return fmt.Sprintf("git@%s:%s/%s.git", f.host, org, repo), nil
	}
}

type httpResolverFactory struct {
	host string
	// Optional, either both or none must be set
	username LoginGetter
	token    TokenGetter
}

// CentralRemote creates a remote resolver that refers to an authoritative remote
// for the repository.
func (f *httpResolverFactory) CentralRemote(org, repo string) RemoteResolver {
	return HttpResolver(func() (*url.URL, error) {
		return &url.URL{Scheme: "https", Host: f.host, Path: fmt.Sprintf("%s/%s", org, repo)}, nil
	}, f.username, f.token)
}

// PublishRemote creates a remote resolver that refers to a user's remote
// for the repository that can be published to.
func (f *httpResolverFactory) PublishRemote(_, repo string) RemoteResolver {
	return HttpResolver(func() (*url.URL, error) {
		if f.username == nil {
			return nil, errors.New("username not configured, no publish repo available")
		}
		o, err := f.username()
		if err != nil {
			return nil, err
		}
		return &url.URL{Scheme: "https", Host: f.host, Path: fmt.Sprintf("%s/%s", o, repo)}, nil
	}, f.username, f.token)
}

// HttpResolver builds http URLs that may optionally contain simple auth credentials, resolved dynamically.
func HttpResolver(remote func() (*url.URL, error), username LoginGetter, token TokenGetter) RemoteResolver {
	return func() (string, error) {
		remote, err := remote()
		if err != nil {
			return "", fmt.Errorf("could not resolve remote: %w", err)
		}

		if username != nil {
			name, err := username()
			if err != nil {
				return "", fmt.Errorf("could not resolve username: %w", err)
			}
			remote.User = url.UserPassword(name, string(token()))
		}

		return remote.String(), nil
	}
}

// pathResolverFactory generates resolvers for local path-based repositories,
// used in local integration testing only
type pathResolverFactory struct {
	baseDir string
}

// CentralRemote creates a remote resolver that refers to an authoritative remote
// for the repository.
func (f *pathResolverFactory) CentralRemote(org, repo string) RemoteResolver {
	return func() (string, error) {
		return path.Join(f.baseDir, org, repo), nil
	}
}

// PublishRemote creates a remote resolver that refers to a user's remote
// for the repository that can be published to.
func (f *pathResolverFactory) PublishRemote(org, repo string) RemoteResolver {
	return func() (string, error) {
		return path.Join(f.baseDir, org, repo), nil
	}
}

// gerritResolverFactory is meant to be used by Gerrit only. It's so different
// from GitHub that there is no way any of the remotes logic can be shared
// between these two providers. The resulting CentralRemote and PublishRemote
// are both the clone URI.
type gerritResolverFactory struct{}

func (f *gerritResolverFactory) CentralRemote(org, repo string) RemoteResolver {
	return func() (string, error) {
		return gerritsource.CloneURIFromOrgRepo(org, repo), nil
	}
}

func (f *gerritResolverFactory) PublishRemote(org, repo string) RemoteResolver {
	return func() (string, error) {
		return gerritsource.CloneURIFromOrgRepo(org, repo), nil
	}
}


text:
package com.gemstone.gemfire.internal.concurrent;

/**
 * These methods are the same ones on
 * the JDK 5 version java.util.concurrent.locks.ReentrantLock
 * @see CFactory
 * @author darrel
 * @deprecated use ReentrantLock
 */
public interface RL extends L {
  /**
   * Queries if this lock is held by the current thread.
   * @return true if current thread holds this lock and false otherwise
   */
  public boolean isHeldByCurrentThread();
}


text:
'use strict';

module.exports = {
  template: require('./template.html')
};


text:
namespace Microsoft.Azure.Management.Sql.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.Sql;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Represents a database transparent data encryption Scan.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class TransparentDataEncryptionActivity : SubResource
    {
        /// <summary>
        /// Initializes a new instance of the TransparentDataEncryptionActivity
        /// class.
        /// </summary>
        public TransparentDataEncryptionActivity()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the TransparentDataEncryptionActivity
        /// class.
        /// </summary>
        /// <param name="name">Resource name</param>
        /// <param name="id">The resource ID.</param>
        /// <param name="status">The status of the database. Possible values
        /// include: 'Encrypting', 'Decrypting'</param>
        /// <param name="percentComplete">The percent complete of the
        /// transparent data encryption scan for a database.</param>
        public TransparentDataEncryptionActivity(string name = default(string), string id = default(string), string status = default(string), double? percentComplete = default(double?))
            : base(name, id)
        {
            Status = status;
            PercentComplete = percentComplete;
            CustomInit();
        }

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

        /// <summary>
        /// Gets the status of the database. Possible values include:
        /// 'Encrypting', 'Decrypting'
        /// </summary>
        [JsonProperty(PropertyName = "properties.status")]
        public string Status { get; private set; }

        /// <summary>
        /// Gets the percent complete of the transparent data encryption scan
        /// for a database.
        /// </summary>
        [JsonProperty(PropertyName = "properties.percentComplete")]
        public double? PercentComplete { get; private set; }

    }
}


text:
function newObject(value)
	return function (action, v)
				if action == "get" then return value;
				elseif action == "set" then value = v;
				else error("invalid action");
				end
			end
end

d = newObject(10);

print(d("get"));

d("set", 100);

print(d("get"));


text:
package io.reist.visum.view;

import android.content.Context;
import android.support.annotation.NonNull;

import io.reist.visum.presenter.TestPresenter;

/**
 * Created by Reist on 16.06.16.
 */
public class TestVisumWidget extends VisumWidget<TestPresenter> implements VisumDynamicPresenterView {

    private TestPresenter presenter;

    public TestVisumWidget(Context context) {
        super(VisumViewTest.VIEW_ID, context);
    }

    @Override
    protected int getLayoutRes() {
        return 0;
    }

    @Override
    public TestPresenter getPresenter() {
        return presenter;
    }

    @Override
    public void setPresenter(TestPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    protected void inflate() {}

    @Override
    public void inject(@NonNull Object component) {
        ((VisumViewTest.TestSubComponent) component).inject(this);
    }

}


text:
Nodejs Sample - A simple e-commerce using Node.js + Express.js + Swig + Passport.js + Helmet.js + Gulp and implements MVC pattern.
==========

## What is it?
Baconpress is a template project that works with Node.js + Express.js + Swig + Passport.js + Helmet.js + Gulp and implements MVC pattern.

## Prerequisites
* Node.js - Download and Install [Node.js](http://www.nodejs.org/download/). You can also follow [this gist](https://gist.github.com/isaacs/579814) for a quick and easy way to install Node.js and npm
* MongoDB - Download and Install [MongoDB](http://docs.mongodb.org/manual/installation/) - Make sure `mongod` is running on the default port (27017). You can use mongo as a service, for example: https://mongolab.com/

### Tools Prerequisites
* NPM - Node.js package manage; should be installed when you install node.js.

## How can I use it?
* Clone this repository $git clone https://github.com/marcusvas/nodejs-sample.git
* $npm install
* $gulp
* Be happy ;)

###dependencies
    "bcrypt-nodejs":" native JS bcrypt library for NodeJS"
    "body-parser":" Node.js body parsing middleware"
    "compression":" Node.js compression middleware."
    "connect-ensure-login":" Login session ensuring middleware for Connect and Express."
    "connect-flash":" The flash is a special area of the session used for storing messages."
    "cookie-parser":" Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
    "email-templates":" Node.js module for rendering beautiful emails with ejs, jade, swig, hbs, or handlebars templates and email-friendly inline CSS using juice."
    "errorhandler":" Development-only error handler middleware "
    "express":" Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
    "express-session":" express-session
    "helmet":" help secure Express/Connect apps with various HTTP header  "
    "lodash":" lodash module bundles for Node.js/io.js "
    "method-override":" Override HTTP verbs. "
    "mongoose":" elegant mongodb object modeling for node.js "
    "morgan":" HTTP request logger middleware for node.js "
    "multer":" Node.js middleware for handling `multipart/form-data`. "
    "node-dir":" asynchronous file and directory operations for Node.js "
    "node-uuid":" Generate RFC-compliant UUIDs in JavaScript "
    "nodemailer":" Nodemailer is an easy to use module to send e-mails with Node.JS (using SMTP or sendmail or Amazon SES) and is unicode friendly - You can use any characters you like ✔"
    "nodemailer-sendgrid-transport":" "~0.1.0", /*  This module is a transport plugin for Nodemailer that makes it possible to send through SendGrid's Web API! "
    "passport":"  middleware para login "
    "passport-facebook":" login social "
    "passport-google-oauth":" login social "
    "passport-local":" login custom "
    "passport-local-mongoose":" login social "
    "passport-twitter":" login social "
    "serve-favicon":" favicon "
    "shortid":" /*Short id generator. Url-friendly. Non-predictable. Cluster-compatible. "
    "swig":"  "
    "unirest":""
    "winston":" "
    "express-validator":""


text:
package com.aws.blog;

public class Post {

    private String id;
    private String title;
    private String body;
    private String author;
    private String date ;

    public void setDate(String date) {
        this.date = date;
    }

    public String getDate() {
        return this.date ;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getAuthor() {
        return this.author ;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getBody() {
        return this.body ;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getTitle() {
        return this.title ;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return this.id ;
    }
}


text:
<ion-header>
  <ion-navbar>
    <ion-title>Fourth Page</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  Fourth Page
  <div>
    <button ion-button (click)="clickMe()">Go To Next Page</button>
  </div>
</ion-content>


text:
/**
 * Created by azibit on 10/10/15.
 */

var Reflux = require('reflux');
var Action = require('./store/NewReflux');

var todoCounter = 0,
    localStorageKey = "todos";

var NewRefluxStore = Reflux.createStore({

    listenables: ['Action'],

    getItemByKey: function (list, itemKey) {
        return _.find(list, function(item) {
            return item.key === itemKey;
        });
    },

    onEditItem: function(itemKey, newLabel) {
        var foundItem = getItemByKey(this.list,itemKey);
        if (!foundItem) {
            return;
        }
        foundItem.label = newLabel;
        this.updateList(this.list);
    },

    onAddItem: function(label) {
        this.updateList([{
            key: todoCounter++,
            created: new Date(),
            isComplete: false,
            label: label
        }].concat(this.list));
    },

    onRemoveItem: function(itemKey) {
        this.updateList(_.filter(this.list,function(item){
            return item.key!==itemKey;
        }));
    }

});

module.exports = NewRefluxStore;


text:
from enum import Enum

from pyflink.java_gateway import get_gateway

__all__ = ['ExecutionMode']

class ExecutionMode(Enum):
    """
    The execution mode specifies how a batch program is executed in terms
    of data exchange: pipelining or batched.

    :data:`PIPELINED`:

    Executes the program in a pipelined fashion (including shuffles and broadcasts),
    except for data exchanges that are susceptible to deadlocks when pipelining.
    These data exchanges are performed in a batch manner.

    An example of situations that are susceptible to deadlocks (when executed in a
    pipelined manner) are data flows that branch (one data set consumed by multiple
    operations) and re-join later.

    :data:`PIPELINED_FORCED`:

    Executes the program in a pipelined fashion (including shuffles and broadcasts),
    **including** data exchanges that are susceptible to deadlocks when
    executed via pipelining.

    Usually, PIPELINED is the preferable option, which pipelines most
    data exchanges and only uses batch data exchanges in situations that are
    susceptible to deadlocks.

    This option should only be used with care and only in situations where the
    programmer is sure that the program is safe for full pipelining and that
    Flink was too conservative when choosing the batch exchange at a certain
    point.

    :data:`BATCH`:

    This mode executes all shuffles and broadcasts in a batch fashion, while
    pipelining data between operations that exchange data only locally
    between one producer and one consumer.

    :data:`BATCH_FORCED`:

    This mode executes the program in a strict batch way, including all points
    where data is forwarded locally from one producer to one consumer. This mode
    is typically more expensive to execute than the BATCH mode. It does
    guarantee that no successive operations are ever executed concurrently.
    """

    PIPELINED = 0
    PIPELINED_FORCED = 1
    BATCH = 2
    BATCH_FORCED = 3

    @staticmethod
    def _from_j_execution_mode(j_execution_mode) -> 'ExecutionMode':
        return ExecutionMode[j_execution_mode.name()]

    def _to_j_execution_mode(self):
        gateway = get_gateway()
        JExecutionMode = gateway.jvm.org.apache.flink.api.common.ExecutionMode
        return getattr(JExecutionMode, self.name)


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;

namespace BrockAllen.MembershipReboot
{
    public class UserClaim
    {
        public UserClaim()
        {
        }

        public UserClaim(string type, string value)
        {
            if (String.IsNullOrWhiteSpace(type)) throw new ArgumentNullException("type");
            if (String.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value");

            this.Type = type;
            this.Value = value;
        }

        [StringLength(150)]
        [Required]
        public virtual string Type { get; protected internal set; }

        [StringLength(150)]
        [Required]
        public virtual string Value { get; protected internal set; }
    }

    public class UserClaimComparer : IComparer, IComparer<UserClaim>
    {
        public int Compare(object x, object y)
        {
            return Compare(x as UserClaim, y as UserClaim);
        }

        public int Compare(UserClaim x, UserClaim y)
        {
            int temp;
            return (temp = string.Compare(x.Type, y.Type, StringComparison.Ordinal)) != 0
                ? temp
                : string.Compare(x.Value, y.Value, StringComparison.Ordinal);
        }
    }

    public static class UserClaimCollectionExtensions
    {
        public static UserClaimCollection ToCollection(this IEnumerable<UserClaim> claims)
        {
            return new UserClaimCollection(claims);
        }
    }

    public class UserClaimCollection : System.Collections.Generic.HashSet<UserClaim>
    {
        public static readonly UserClaimCollection Empty = new UserClaimCollection();

        public static implicit operator UserClaimCollection(UserClaim[] claims)
        {
            return new UserClaimCollection(claims);
        }

        public static implicit operator UserClaimCollection(Claim[] claims)
        {
            return new UserClaimCollection(claims);
        }

        public UserClaimCollection()
        {
        }

        public UserClaimCollection(System.Collections.Generic.IEnumerable<UserClaim> claims)
        {
            if (claims != null)
            {
                foreach (var claim in claims)
                {
                    this.Add(claim);
                }
            }
        }
        public UserClaimCollection(System.Collections.Generic.IEnumerable<Claim> claims)
        {
            if (claims != null)
            {
                foreach (var claim in claims)
                {
                    this.Add(claim.Type, claim.Value);
                }
            }
        }

        public void Add(string type, string value)
        {
            this.Add(new UserClaim(type, value));
        }
    }
}


text:
<?php

namespace Omnipay\SagePay\Message;

/**
 * Sage Pay Server Purchase Request
 */
class ServerPurchaseRequest extends ServerAuthorizeRequest
{
    protected $action = 'PAYMENT';
}


text:
{% extends "module.html" %}
{% block content %}
    {{ input }}
{% endblock %}