text:
import json
import os
import platform
import stat
import sys
import textwrap
import unittest

import pytest
from mock import patch
from requests import ConnectionError

from conans import DEFAULT_REVISION_V1
from conans.client.tools.files import untargz
from conans.model.manifest import FileTreeManifest
from conans.model.package_metadata import PackageMetadata
from conans.model.ref import ConanFileReference, PackageReference
from conans.paths import CONANFILE, CONANINFO, CONAN_MANIFEST, EXPORT_TGZ_NAME
from conans.test.utils.test_files import temp_folder, uncompress_packaged_files
from conans.test.utils.tools import (NO_SETTINGS_PACKAGE_ID, TestClient, TestRequester, TestServer,
                                     GenConanfile)
from conans.util.env_reader import get_env
from conans.util.files import load, mkdir, save

class BadConnectionUploader(TestRequester):
    fail_on = 1

    def __init__(self, *args, **kwargs):
        super(BadConnectionUploader, self).__init__(*args, **kwargs)
        self.counter_fail = 0

    def put(self, *args, **kwargs):
        self.counter_fail += 1
        if self.counter_fail == self.fail_on:
            raise ConnectionError("Can't connect because of the evil mock")
        else:
            return super(BadConnectionUploader, self).put(*args, **kwargs)

class TerribleConnectionUploader(BadConnectionUploader):
    def put(self, *args, **kwargs):
        raise ConnectionError("Can't connect because of the evil mock")

class FailPairFilesUploader(BadConnectionUploader):

    def put(self, *args, **kwargs):
        self.counter_fail += 1
        if self.counter_fail % 2 == 1:
            raise ConnectionError("Pair file, error!")
        else:
            return super(BadConnectionUploader, self).put(*args, **kwargs)

def test_try_upload_bad_recipe():
    client = TestClient(default_server_user=True)
    client.save({"conanfile.py": GenConanfile("Hello0", "1.2.1")})
    client.run("export . frodo/stable")
    ref = ConanFileReference.loads("Hello0/1.2.1@frodo/stable")
    os.unlink(os.path.join(client.cache.package_layout(ref).export(), CONAN_MANIFEST))
    client.run("upload %s" % str(ref), assert_error=True)
    assert "Cannot upload corrupted recipe" in client.out

def test_upload_with_pattern():
    client = TestClient(default_server_user=True)
    for num in range(3):
        client.save({"conanfile.py": GenConanfile("hello{}".format(num), "1.2.1")})
        client.run("export . frodo/stable")

    client.run("upload hello* --confirm")
    for num in range(3):
        assert "Uploading hello%s/1.2.1@frodo/stable" % num in client.out

    client.run("upload hello0* --confirm")
    assert "Uploading hello0/1.2.1@frodo/stable" in client.out
    assert "Recipe is up to date, upload skipped" in client.out
    assert "Hello1" not in client.out
    assert "Hello2" not in client.out

def test_upload_with_pattern_and_package_error():
    client = TestClient()
    client.save({"conanfile.py": GenConanfile("Hello1", "1.2.1")})
    client.run("export . frodo/stable")
    client.run("upload Hello* --confirm -p 234234234", assert_error=True)
    assert "-p parameter only allowed with a valid recipe reference" in client.out

def test_check_upload_confirm_question():
    client = TestClient(default_server_user=True)
    client.save({"conanfile.py": GenConanfile("Hello1", "1.2.1")})
    client.run("export . frodo/stable")
    with patch.object(sys.stdin, "readline", return_value="y"):
        client.run("upload Hello*")
    assert "Uploading Hello1/1.2.1@frodo/stable" in client.out

    client.save({"conanfile.py": GenConanfile("Hello2", "1.2.1")})
    client.run("export . frodo/stable")

    with patch.object(sys.stdin, "readline", return_value="n"):
        client.run("upload Hello*")
    assert "Uploading Hello2/1.2.1@frodo/stable" not in client.out

@pytest.mark.skipif(get_env("TESTING_REVISIONS_ENABLED", False),
                    reason="We cannot know the folder of the revision without knowing the hash of "
                           "the contents")
class UploadTest(unittest.TestCase):

    def _get_client(self, requester=None):
        servers = {}
        # All can write (for avoid authentication until we mock user_io)
        self.test_server = TestServer([("*/*@*/*", "*")], [("*/*@*/*", "*")],
                                      users={"lasote": "mypass"})
        servers["default"] = self.test_server
        test_client = TestClient(servers=servers, users={"default": [("lasote", "mypass")]},
                                 requester_class=requester)
        save(test_client.cache.default_profile_path, "")
        return test_client

    def setUp(self):
        self.client = self._get_client()
        self.ref = ConanFileReference.loads("Hello/1.2.1@frodo/stable#%s" % DEFAULT_REVISION_V1)
        self.pref = PackageReference(self.ref, "myfakeid", DEFAULT_REVISION_V1)
        reg_folder = self.client.cache.package_layout(self.ref).export()

        self.client.run('upload %s' % str(self.ref), assert_error=True)
        self.assertIn("ERROR: Recipe not found: '%s'" % str(self.ref), self.client.out)

        files = {}

        fake_metadata = PackageMetadata()
        fake_metadata.recipe.revision = DEFAULT_REVISION_V1
        fake_metadata.packages[self.pref.id].revision = DEFAULT_REVISION_V1
        self.client.save({"metadata.json": fake_metadata.dumps()},
                         path=self.client.cache.package_layout(self.ref).base_folder())
        self.client.save(files, path=reg_folder)
        self.client.save({CONANFILE: GenConanfile().with_name("Hello").with_version("1.2.1"),
                          "include/math/lib1.h": "//copy",
                          "my_lib/debug/libd.a": "//copy",
                          "my_data/readme.txt": "//copy",
                          "my_bin/executable": "//copy"}, path=reg_folder)
        mkdir(self.client.cache.package_layout(self.ref).export_sources())
        manifest = FileTreeManifest.create(reg_folder)
        manifest.time = '123123123'
        manifest.save(reg_folder)
        self.test_server.server_store.update_last_revision(self.ref)

        self.server_pack_folder = self.test_server.server_store.package(self.pref)

        package_folder = self.client.cache.package_layout(self.ref).package(self.pref)
        save(os.path.join(package_folder, "include", "lib1.h"), "//header")
        save(os.path.join(package_folder, "lib", "my_lib", "libd.a"), "//lib")
        save(os.path.join(package_folder, "res", "shares", "readme.txt"),
             "//res")
        save(os.path.join(package_folder, "bin", "my_bin", "executable"), "//bin")
        save(os.path.join(package_folder, CONANINFO),
             """[recipe_hash]\n%s""" % manifest.summary_hash)
        FileTreeManifest.create(package_folder).save(package_folder)
        self.test_server.server_store.update_last_package_revision(self.pref)

        os.chmod(os.path.join(package_folder, "bin", "my_bin", "executable"),
                 os.stat(os.path.join(package_folder, "bin", "my_bin", "executable")).st_mode |
                 stat.S_IRWXU)

        expected_manifest = FileTreeManifest.create(package_folder)
        expected_manifest.save(package_folder)

        self.server_reg_folder = self.test_server.server_store.export(self.ref)
        self.assertFalse(os.path.exists(self.server_reg_folder))
        self.assertFalse(os.path.exists(self.server_pack_folder))

    def test_upload_error(self):
        """Cause an error in the transfer and see some message"""

        # Check for the default behaviour
        client = self._get_client(BadConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("upload Hello* --confirm")
        self.assertIn("Can't connect because of the evil mock", client.out)
        self.assertIn("Waiting 5 seconds to retry...", client.out)

        # This will fail in the first put file, so, as we need to
        # upload 3 files (conanmanifest, conanfile and tgz) will do it with 2 retries
        client = self._get_client(BadConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("upload Hello* --confirm --retry-wait=0")
        self.assertIn("Can't connect because of the evil mock", client.out)
        self.assertIn("Waiting 0 seconds to retry...", client.out)

        # but not with 0
        client = self._get_client(BadConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*"),
                 "somefile.txt": ""}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("upload Hello* --confirm --retry 0 --retry-wait=1", assert_error=True)
        self.assertNotIn("Waiting 1 seconds to retry...", client.out)
        self.assertIn("ERROR: Hello0/1.2.1@frodo/stable: Upload recipe to 'default' failed: "
                      "Execute upload again to retry upload the failed files: "
                      "conan_export.tgz. [Remote: default]", client.out)

        # Try with broken connection even with 10 retries
        client = self._get_client(TerribleConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("upload Hello* --confirm --retry 10 --retry-wait=0", assert_error=True)
        self.assertIn("Waiting 0 seconds to retry...", client.out)
        self.assertIn("ERROR: Hello0/1.2.1@frodo/stable: Upload recipe to 'default' failed: "
                      "Execute upload again to retry upload the failed files", client.out)

        # For each file will fail the first time and will success in the second one
        client = self._get_client(FailPairFilesUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("install Hello0/1.2.1@frodo/stable --build")
        client.run("upload Hello* --confirm --retry 3 --retry-wait=0 --all")
        self.assertEqual(str(client.out).count("ERROR: Pair file, error!"), 5)

    def test_upload_error_with_config(self):
        """Cause an error in the transfer and see some message"""

        # This will fail in the first put file, so, as we need to
        # upload 3 files (conanmanifest, conanfile and tgz) will do it with 2 retries
        client = self._get_client(BadConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run('config set general.retry_wait=0')
        client.run("upload Hello* --confirm")
        self.assertIn("Can't connect because of the evil mock", client.out)
        self.assertIn("Waiting 0 seconds to retry...", client.out)

        # but not with 0
        client = self._get_client(BadConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*"),
                 "somefile.txt": ""}
        client.save(files)
        client.run("export . frodo/stable")
        client.run('config set general.retry=0')
        client.run('config set general.retry_wait=1')
        client.run("upload Hello* --confirm", assert_error=True)
        self.assertNotIn("Waiting 1 seconds to retry...", client.out)
        self.assertIn("ERROR: Hello0/1.2.1@frodo/stable: Upload recipe to 'default' failed: "
                      "Execute upload again to retry upload the failed files: "
                      "conan_export.tgz. [Remote: default]", client.out)

        # Try with broken connection even with 10 retries
        client = self._get_client(TerribleConnectionUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run('config set general.retry=10')
        client.run('config set general.retry_wait=0')
        client.run("upload Hello* --confirm", assert_error=True)
        self.assertIn("Waiting 0 seconds to retry...", client.out)
        self.assertIn("ERROR: Hello0/1.2.1@frodo/stable: Upload recipe to 'default' failed: "
                      "Execute upload again to retry upload the failed files", client.out)

        # For each file will fail the first time and will success in the second one
        client = self._get_client(FailPairFilesUploader)
        files = {"conanfile.py": GenConanfile("Hello0", "1.2.1").with_exports("*")}
        client.save(files)
        client.run("export . frodo/stable")
        client.run("install Hello0/1.2.1@frodo/stable --build")
        client.run('config set general.retry=3')
        client.run('config set general.retry_wait=0')
        client.run("upload Hello* --confirm --all")
        self.assertEqual(str(client.out).count("ERROR: Pair file, error!"), 5)

    def test_upload_same_package_dont_compress(self):
        # Create a manifest for the faked package
        pack_path = self.client.cache.package_layout(self.pref.ref).package(self.pref)
        package_path = self.client.cache.package_layout(self.pref.ref).package(self.pref)
        expected_manifest = FileTreeManifest.create(package_path)
        expected_manifest.save(pack_path)

        self.client.run("upload %s --all" % str(self.ref))
        self.assertIn("Compressing recipe", self.client.out)
        self.assertIn("Compressing package", str(self.client.out))

        self.client.run("upload %s --all" % str(self.ref))
        self.assertNotIn("Compressing recipe", self.client.out)
        self.assertNotIn("Compressing package", str(self.client.out))
        self.assertIn("Package is up to date", str(self.client.out))

    def test_upload_with_no_valid_settings(self):
        # Check if upload is still working even if the specified setting is not valid.
        # If this test fails, will fail in Linux/OSx
        conanfile = textwrap.dedent("""
            from conans import ConanFile
            class TestConan(ConanFile):
                name = "Hello"
                version = "1.2"
                settings = {"os": ["Windows"]}
            """)
        self.client.save({CONANFILE: conanfile})
        self.client.run("export . lasote/stable")
        self.assertIn("WARN: Conanfile doesn't have 'license'", self.client.out)
        self.client.run("upload Hello/1.2@lasote/stable")
        self.assertIn("Uploading conanmanifest.txt", self.client.out)

    def test_single_binary(self):
        # Try to upload an package without upload conans first
        self.client.run('upload %s -p %s' % (self.ref, str(self.pref.id)))
        self.assertIn("Uploading %s to remote" % str(self.ref), self.client.out)

    def test_simple(self):
        # Upload package
        self.client.run('upload %s' % str(self.ref))
        self.server_reg_folder = self.test_server.server_store.export(self.ref)

        self.assertTrue(os.path.exists(self.server_reg_folder))
        if not self.client.cache.config.revisions_enabled:
            self.assertFalse(os.path.exists(self.server_pack_folder))

        # Upload package
        self.client.run('upload %s -p %s' % (str(self.ref), str(self.pref.id)))

        self.server_pack_folder = self.test_server.server_store.package(self.pref)

        self.assertTrue(os.path.exists(self.server_reg_folder))
        self.assertTrue(os.path.exists(self.server_pack_folder))

        # Test the file in the downloaded conans
        files = ['my_lib/debug/libd.a',
                 CONANFILE,
                 CONAN_MANIFEST,
                 'include/math/lib1.h',
                 'my_data/readme.txt',
                 'my_bin/executable']

        self.assertTrue(os.path.exists(os.path.join(self.server_reg_folder, CONANFILE)))
        self.assertTrue(os.path.exists(os.path.join(self.server_reg_folder, EXPORT_TGZ_NAME)))
        tmp = temp_folder()
        untargz(os.path.join(self.server_reg_folder, EXPORT_TGZ_NAME), tmp)
        for f in files:
            if f not in (CONANFILE, CONAN_MANIFEST):
                self.assertTrue(os.path.exists(os.path.join(tmp, f)))
            else:
                self.assertFalse(os.path.exists(os.path.join(tmp, f)))

        folder = uncompress_packaged_files(self.test_server.server_store, self.pref)

        self.assertTrue(os.path.exists(os.path.join(folder, "include", "lib1.h")))
        self.assertTrue(os.path.exists(os.path.join(folder, "lib", "my_lib/libd.a")))
        self.assertTrue(os.path.exists(os.path.join(folder, "res", "shares/readme.txt")))

        if platform.system() != "Windows":
            self.assertEqual(os.stat(os.path.join(folder, "bin", "my_bin/executable")).st_mode &
                             stat.S_IRWXU, stat.S_IRWXU)

    def test_upload_all(self):
        """Upload recipe and package together"""
        # Try to upload all conans and packages
        self.client.run('user -p mypass -r default lasote')
        self.client.run('upload %s --all' % str(self.ref))
        lines = [line.strip() for line in str(self.client.out).splitlines()
                 if line.startswith("Uploading")]
        self.assertEqual(lines, ["Uploading to remote 'default':",
                                 "Uploading Hello/1.2.1@frodo/stable to remote 'default'",
                                 "Uploading conan_export.tgz -> Hello/1.2.1@frodo/stable",
                                 "Uploading conanfile.py -> Hello/1.2.1@frodo/stable",
                                 "Uploading conanmanifest.txt -> Hello/1.2.1@frodo/stable",
                                 "Uploading package 1/1: myfakeid to 'default'",
                                 "Uploading conan_package.tgz -> Hello/1.2.1@frodo/stable:myfa",
                                 "Uploading conaninfo.txt -> Hello/1.2.1@frodo/stable:myfa",
                                 "Uploading conanmanifest.txt -> Hello/1.2.1@frodo/stable:myfa",
                                 ])
        if self.client.cache.config.revisions_enabled:
            layout = self.client.cache.package_layout(self.ref)
            rev = layout.recipe_revision()
            self.ref = self.ref.copy_with_rev(rev)
            prev = layout.package_revision(self.pref)
            self.pref = self.pref.copy_with_revs(rev, prev)

        server_reg_folder = self.test_server.server_store.export(self.ref)
        server_pack_folder = self.test_server.server_store.package(self.pref)

        self.assertTrue(os.path.exists(server_reg_folder))
        self.assertTrue(os.path.exists(server_pack_folder))

    def test_force(self):
        # Tries to upload a package exported after than remote version.
        # Upload all recipes and packages
        self.client.run('upload %s --all' % str(self.ref))

        if self.client.cache.config.revisions_enabled:
            layout = self.client.cache.package_layout(self.ref)
            rev = layout.recipe_revision()
            self.ref = self.ref.copy_with_rev(rev)
            prev = layout.package_revision(self.pref)
            self.pref = self.pref.copy_with_revs(rev, prev)

        self.server_reg_folder = self.test_server.server_store.export(self.ref)
        self.server_pack_folder = self.test_server.server_store.package(self.pref)

        self.assertTrue(os.path.exists(self.server_reg_folder))
        self.assertTrue(os.path.exists(self.server_pack_folder))

        # Fake datetime from exported date and upload again

        old_digest = self.client.cache.package_layout(self.ref).recipe_manifest()
        old_digest.file_sums["new_file"] = "012345"
        fake_digest = FileTreeManifest(2, old_digest.file_sums)
        fake_digest.save(self.client.cache.package_layout(self.ref).export())

        self.client.run('upload %s' % str(self.ref), assert_error=True)
        self.assertIn("Remote recipe is newer than local recipe", self.client.out)

        self.client.run('upload %s --force' % str(self.ref))
        self.assertIn("Uploading %s" % str(self.ref),
                      self.client.out)

        # Repeat transfer, to make sure it is uploading again
        self.client.run('upload %s --force' % str(self.ref))
        self.assertIn("Uploading conan_export.tgz", self.client.out)
        self.assertIn("Uploading conanfile.py", self.client.out)

    def test_upload_json(self):
        conanfile = textwrap.dedent("""
            from conans import ConanFile

            class TestConan(ConanFile):
                name = "test"
                version = "0.1"

                def package(self):
                    self.copy("mylib.so", dst="lib")
            """)

        client = self._get_client()
        client.save({"conanfile.py": conanfile,
                     "mylib.so": ""})
        client.run("create . danimtb/testing")

        # Test conflict parameter error
        client.run("upload test/0.1@danimtb/* --all -p ewvfw --json upload.json", assert_error=True)

        json_path = os.path.join(client.current_folder, "upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        self.assertTrue(output["error"])
        self.assertEqual(0, len(output["uploaded"]))

        # Test invalid reference error
        client.run("upload fake/0.1@danimtb/testing --all --json upload.json", assert_error=True)
        json_path = os.path.join(client.current_folder, "upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        self.assertTrue(output["error"])
        self.assertEqual(0, len(output["uploaded"]))

        # Test normal upload
        client.run("upload test/0.1@danimtb/testing --all --json upload.json")
        self.assertTrue(os.path.exists(json_path))
        json_content = load(json_path)
        output = json.loads(json_content)
        output_expected = {"error": False,
                           "uploaded": [
                               {
                                   "recipe": {
                                       "id": "test/0.1@danimtb/testing",
                                       "remote_url": "unknown",
                                       "remote_name": "default",
                                       "time": "unknown"
                                   },
                                   "packages": [
                                       {
                                           "id": NO_SETTINGS_PACKAGE_ID,
                                           "time": "unknown"
                                       }
                                   ]
                               }
                           ]}
        self.assertEqual(output_expected["error"], output["error"])
        self.assertEqual(len(output_expected["uploaded"]), len(output["uploaded"]))

        for i, item in enumerate(output["uploaded"]):
            self.assertEqual(output_expected["uploaded"][i]["recipe"]["id"], item["recipe"]["id"])
            self.assertEqual(output_expected["uploaded"][i]["recipe"]["remote_name"],
                             item["recipe"]["remote_name"])
            for j, subitem in enumerate(item["packages"]):
                self.assertEqual(output_expected["uploaded"][i]["packages"][j]["id"],
                                 subitem["id"])


text:
/*
This module adds the necessary methods and key bindings to show and hide a form
for jumping to any slide number in the deck (and processes that form
accordingly). The form-showing state is indicated by the presence of a class on
the deck container.
*/
(function($, deck, undefined) {
	var $d = $(document);

	/*
	Extends defaults/options.

	options.classes.goto
		This class is added to the deck container when showing the Go To Slide
		form.

	options.selectors.gotoForm
		The element that matches this selector is the form that is submitted
		when a user hits enter after typing a slide number in the gotoInput
		element.

	options.selectors.gotoInput
		The element that matches this selector is the text input field for
		entering a slide number in the Go To Slide form.

	options.keys.goto
		The numeric keycode used to toggle between showing and hiding the Go To
		Slide form.
	*/
	$.extend(true, $[deck].defaults, {
		classes: {
			goto: 'deck-goto'
		},

		selectors: {
			gotoForm: '.goto-form',
			gotoInput: '#goto-slide'
		},

		keys: {
			goto: 71 // g
		}
	});

	/*
	jQuery.deck('showGoTo')

	Shows the Go To Slide form by adding the class specified by the goto class
	option to the deck container.
	*/
	$[deck]('extend', 'showGoTo', function() {
		$[deck]('getContainer').addClass($[deck]('getOptions').classes.goto);
		$($[deck]('getOptions').selectors.gotoInput).focus();
	});

	/*
	jQuery.deck('hideGoTo')

	Hides the Go To Slide form by removing the class specified by the goto class
	option from the deck container.
	*/
	$[deck]('extend', 'hideGoTo', function() {
		$[deck]('getContainer').removeClass($[deck]('getOptions').classes.goto);
		$($[deck]('getOptions').selectors.gotoInput).blur();
	});

	/*
	jQuery.deck('toggleGoTo')

	Toggles between showing and hiding the Go To Slide form.
	*/
	$[deck]('extend', 'toggleGoTo', function() {
		$[deck]($[deck]('getContainer').hasClass($[deck]('getOptions').classes.goto) ? 'hideGoTo' : 'showGoTo');
	});

	$d.bind('deck.init', function() {
		// Bind key events
		$d.bind('keydown.deck', function(e) {
			if (e.which == $[deck]('getOptions').keys.goto) {
				e.preventDefault();
				$[deck]('toggleGoTo');
			}
		});

		// Process form submittal, go to the slide entered
		$($[deck]('getOptions').selectors.gotoForm)
		.unbind('submit.deck')
		.bind('submit.deck', function(e) {
			var $field = ($($[deck]('getOptions').selectors.gotoInput)),
			i = parseInt($field.val(), 10);

			if (!($.isNaN(i) || i < 1 || i > $[deck]('getSlides').length)) {
				$[deck]('go', i - 1);
				$[deck]('hideGoTo');
				$field.val('');
			}

			e.preventDefault();
		});
	});
})(jQuery, 'deck');

redpajama_set_name: RedPajamaGithub


text:
<?php
defined('PHPFOX') or exit('No dice!');
?>

<form action="{url link='admincp.custom.relationships'}" method="post">

		{phrase var='custom.add_status'}

			Status name:

			{if isset($aEdit)}
				{module name='language.admincp.form' type='text' id='new' var_name=$aEdit.phrase.new}
			{else}
				{module name='language.admincp.form' type='text' id='new'}
			{/if}

			{phrase var='custom.you_can_add_a_language_phrase_if_you_enter_it_like_this'}:

			{l}phrase var='module.phrase_var'{r}

			{phrase var='custom.otherwise_the_script_will_create_the_language_phrase_for_you'}

			{phrase var='custom.feed_when_confirmed'}:

			{if isset($aEdit)}
				{module name='language.admincp.form' type='text' id='feed_with' var_name=$aEdit.phrase.feed_with}
			{else}
				{module name='language.admincp.form' type='text' id='feed_with'}
			{/if}

				{phrase var='custom.this_is_the_message_for_the_feed_when_the_relationship_has_been_confirmed'}

			{phrase var='custom.feed_before_confirming'}:

			{if isset($aEdit)}
				{module name='language.admincp.form' type='text' id='feed_new' var_name=$aEdit.phrase.feed_new}
			{else}
				{module name='language.admincp.form' type='text' id='feed_new'}
			{/if}

				{phrase var='custom.this_message_will_be_shown_in_the_feed_when_a_user_has_set_a_relationship'}

			{phrase var='custom.requires_confirmation'}:

		    <input type="checkbox" name="val[confirmation]" {if isset($aEdit) && $aEdit.confirmation == 1}checked="checked" {/if}>

			       {phrase var='custom.if_this_field_is_enabled_this_relationship_status_requires_that_both_users_agree_on_displaying_their_relationship'}

			{phrase var='custom.for_all_these_phrases_the_following_transformations_apply'}:

{l}with_user_name{r} {phrase var='custom.user_name_of_the_receiving_party'}

{l}with_full_name{r} {phrase var='custom.full_name_of_the_receiving_party'}

{l}user_name{r} {phrase var='custom.sender_s_user_name'}

{l}full_name{r} {phrase var='custom.sender_s_full_name'}

{l}their{r} {phrase var='custom.sender_s_possessive_adjective_his_her'}

		<input type="submit" value="{if isset($aEdit)} {phrase var='custom.edit_status'} {else}{phrase var='custom.add_status'}{/if}" class="button">

</form>
{if !isset($aEdit)}

	<form action="{url link='admincp.custom.relationships'}" method="post">

			{phrase var='custom.manage_relationship_statuses'}

			{if (isset($aStatuses) && is_array($aStatuses) && !empty($aStatuses))}

					 {phrase var='custom.delete'}
					 {phrase var='custom.edit'}
					 {phrase var='custom.status_name'}
					 {phrase var='custom.feed_when_confirmed'}
					 {phrase var='custom.feed_when_new'}
					 {phrase var='custom.confirmation'}

				{foreach from=$aStatuses name=status item=aStatus}

								{img theme='misc/delete.png' style='vertical-align:middle;'}

								{img theme='misc/page_white_edit.png' style='vertical-align:middle;'}

						 {if isset($aStatus.phrase.new)} {module name='language.admincp.form' type='label' id=$aStatus.relation_id var_name=$aStatus.phrase.new} {/if}
						 {if isset($aStatus.phrase.feed_with)} {module name='language.admincp.form' type='label' id=$aStatus.relation_id var_name=$aStatus.phrase.feed_with} {/if}
						 {if isset($aStatus.phrase.feed_new)} {module name='language.admincp.form' type='label' id=$aStatus.relation_id var_name=$aStatus.phrase.feed_new}  {/if}
						 <input type="checkbox" disabled="disabled" name="confirmation" {if $aStatus.confirmation == 1}checked="checked"{/if}>

				{/foreach}

			{else}
				{phrase var='custom.no_relationship_statuses_have_been_added'}
			{/if}

	</form>
{/if}


text:
Konfa
=====

[![Build Status](https://travis-ci.org/promoteinternational/konfa.svg)](https://travis-ci.org/promoteinternational/konfa)

Facilitates application configuration and tries to address a couple of common issues

 * Bugs attributed to misspelt configuration variable names
 * Forgotten configuration options that nobody knows what they do or where they are used
 * Seamlessly reading configuration values from either the environment or YAML (or any other source for that matter)

Basic Usage
-----------

```ruby
require 'konfa'

class MyAppConfig < Konfa::Base
  def self.allowed_variables
    {
      show_stuff: 'yes',             # You can describe what the variable is for here
      stuff_id: nil,                 # ID of the stuff we're using
      lasers: 'off',
      tasers: 'on',
    }
  end
end

# ... somewhere early in execution ..."

MyAppConfig.init_with(:yaml, 'config/values.yaml')

# ... later on in the app ...

if MyAppConfig.true?(:show_stuff)
   SomeStuff.connect( MyAppConfig.get(:stuff_id) )
end

MyAppConfig.get(:no_such_variable) # Kabooom

```

allowed_variables
-----------

Valid configuration variables has to be declared and returned by the ```allowed_variables``` hash. If you do not want to provide a default value, just use ```nil```.

Values
------
For the sake of simplicity, values are always converted to, and treated as, strings. The rationale behind this is to be able to initialize configuration values from sources that does not support specific datatypes (such as the environment)

Complex values, such as arrays or hashes, are not supported out of the box, but can easily be implemented if needed:

```ruby
class MyAppConfig < Konfa::Base
  def self.allowed_variables
    {
      :numbers => 'one, two, three'
    }
  end

  def self.as_list(key)
    get(key).split(/\s*,\s*/)
  end
end

MyAppConfig.get(:numbers)     => 'one,two,three'
MyAppConfig.as_list(:numbers) => ['one','two','three']
```

Booleans
--------
Because values are converted to strings, you can use the ```true?``` and ```false?``` methods to safely treat a value as a boolean. The strings ```"on"```, ```"1"```, ```"yes"``` and ```"true"``` will be treated as boolean true, and anything else (including nil) will be false.

So
```ruby
# given
#   :bool => 'yes'

MyAppConfig.get(:bool) # => "yes"
MyAppConfig.true?(:bool) # => true
MyAppConfig.false?(:bool) # => false
```

Settings values
---------------
Konfa does not provide an interface to set values. But if you *really* want to, you can do

```ruby
  MyAppConfig.send(:store, :key, 'value')
```

This could be useful for testing, but you really shouldn't set config values from within the application.

with_config
-----------
The ```with_config``` method is useful when code needs to be executed with
temporary settings. It can be used like this

```ruby
# given
#   :var => 'off'

MyAppConfig.with_config(:var => 'on') do
  MyAppConfig.get(:var) # => "on" inside this block
end

MyAppConfig.get(:var) # => "off" again
```

Original configuration values will be restored even if the block raises an exception.

This could be useful in testing. Another alternative is the RSpec plugin

Testing
-------

The RSpec plugin makes it easy to stub config variables with less typing manual
checking. It can be used like this

```ruby
require 'konfa/rspec'

describe Something
  include_context 'with konfa', MyKonfaSubclass

  it 'does something' do
    let_config(:my_variable, 'testing value')
    expect(code_that_returns_my_variable).to eq 'testing value'
  end
end
```

It will ensure ```my_variables``` exists and it will allow the tested code to be
executed with temporary values without having to worry about modifying global
configuration that may disrupt subsequent examples.

Populate with values from environment
-------------------------------------
Calling ```init_with(:env)``` populates values from the environment. Konfa will only import variables with a specific prefix to avoid collisions with existing variables.

```ruby
# in myapp.rb
class MyAppConfig < Konfa::Base

  def self.env_variable_prefix
    'MYAPP_'
  end

  def self.allowed_variables
    {
      show_stuff: 'yes',
      lang: 'sv'
    }
  end
end

MyAppConfig.init_with(:env)

puts "I speak #{MyAppConfig.get(:lang)} and I will #{MyAppConfig.true?(:show_stuff) ? "" : "not"} show stuff"
```

```bash
# In a console

$ export MYAPP_SHOW_STUFF=no
$ export MYAPP_LANG=pt
$ export LANG=en_US
$ ruby myapp.rb
I speak pt and I will not show stuff
```

Populate with values from YAML
------------------------------
The YAML initializer will read values from the given yaml file. Only key/values are supported.

*Note on YAML and booleans*

Ruby's YAML implementation will cast the words ```yes```, ```true```, ```on```, ```off```, ```false``` and ```no```
into a Boolean. This applies to both keys and values. Because Konfa assumes that all values are strings, values are
always converted to a String. This means that the word ```yes``` will result in the string ```"true"```.
To avoid this, please quote the word in your YAML source. Like so:

```YAML
---
my_key_1: yes     # Will result in Konfa.get(:my_key) => "true"
my_key_2: 'yes'   # Will result in Konfa.get(:my_key) => "yes"
```

after_initialize
----------------
Your subclass may implement a class method called ```after_initialize``` that will be called immediately after Konfa has
been initialized with configuration values. This is useful if you for example want to configure logging or something
else when you have to be sure that you have all config values.

Konfa's base implementation does nothing, so there's no point in calling ```super``` here.

```ruby
class MyAppConfig < Konfa::Base
  def self.allowed_variables
    {
      log_file: nil
    }
  end

  def self.after_initialize
    Logger.file = get(:log_file)
  end
end
```

Notes on initializing
-------------------

## Initialization is deferred by default

Konfa will initialize its values when a variable is first read (when for instance
calling `get`, `true?` or `dump`). Initialization can be triggered earlier by calling
the `init`method.

The default behaviour:

```ruby

MyAppConfig.init_with(:yaml, 'path_to_yaml_file')

# ... things happens, and later on in the execution:

MyAppConfig.get(:my_var) # Konfa will read the yaml file, populate the
                         # configuration and then return the value of `my_var`
```

Initialize earlier:

```ruby

MyAppConfig.init_with(:yaml, 'path_to_yaml_file')

MyAppConfig.init # Konfa will now read the yaml file and populate the configuration
                 # It's also possible to chain:
                 #     MyAppConfig.init_with(:yaml, '...').init

# ... things happens, and later on in the execution:

MyAppConfig.get(:my_var)
```

From a design perspective, it is desireble to initialize Konfa as early as possible,
as it will fail early if bad configuration values are found. Do not use this method
unless there is a good reason to.

You may override the ```init?``` method for implementing own logic on when to
run the initialization code. This method is invoked at every time a value is
accessed.

## Custom initialization methods

If you want to initialize Konfa with values from another source (for example a
database), you need to implement an initialization method. Extend the module
`Konfa::Initializer::ClassMethods` with your own method and call `init_with`.

***NOTE:*** your initializer method name must be prefixed with: `init_with_` to
avoid collisions in the configuration class.

```ruby

module Konfa
  module Initializer
    module ClassMethods
      def init_with_numbers
        self.store('my_var', '01234')
      end
    end
  end
end

class MyAppConfig < Konfa::Base
  def self.allowed_variables
    {
      my_var: nil,
    }
  end
end

MyAppConfig.init_with(:numbers) # Don't include prefix in symbol

MyAppConfig.get(:my_var) # => 01234
```

## Version 0.5.x

Konfa 0.5 introduces new methods for initializing configurations, meant to provide
a simpler interface and a cleaner way of using multiple YAML files and/or multiple
initializers. Catching errors early is strongly encouraged, therefore,
`initialize!` must be called explicitly when finished loading configurations.

```ruby
require 'konfa'

class MyAppConfig < Konfa::Base
  def self.allowed_variables
    {
      lasers: 'off',
      tasers: 'on',
    }
  end

  def self.env_variable_prefix
    'MY_APP_'
  end
end

MyAppConfig.read_from(:yaml, 'config/values.yaml', 'config/local_overrides.yaml' )
MyAppConfig.read_from(:env)
MyAppConfig.initialize! # after_initialize is invoked once

if MyAppConfig.true?(:lasers)
  # do stuff
end
```

**NOTE¹:** when using `read_from`, accessing variables without initializing
first will raise an exception in Konfa 1.0.
**NOTE²:** the old initialization interface is now deprecated and will be
removed in Konfa 1.0.


text:
/* This file is automatically generated; do not edit.     */
/* Add the files to be included into Makefile.am instead. */

#include <qle/currencies/africa.hpp>
#include <qle/currencies/america.hpp>
#include <qle/currencies/asia.hpp>


text:
package butterknife.internal;

import com.google.common.base.Joiner;
import com.google.testing.compile.JavaFileObjects;
import org.junit.Test;

import javax.tools.JavaFileObject;

import static com.google.common.truth.Truth.ASSERT;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;

public class OnItemLongClickTest {
  @Test public void itemLongClick() {
    JavaFileObject source = JavaFileObjects.forSourceString("test.Test", Joiner.on('\n').join(
        "package test;",
        "import android.app.Activity;",
        "import butterknife.OnItemLongClick;",
        "public class Test extends Activity {",
        "  @OnItemLongClick(1) boolean doStuff() { return false; }",
        "}"
    ));

    JavaFileObject expectedSource = JavaFileObjects.forSourceString("test/Test$$ViewBinder",
        Joiner.on('\n').join(
            "package test;",
            "import android.view.View;",
            "import butterknife.ButterKnife.Finder;",
            "import butterknife.ButterKnife.ViewBinder;",
            "public class Test$$ViewBinder<T extends test.Test> implements ViewBinder<T> {",
            "  @Override public void bind(final Finder finder, final T target, Object source) {",
            "    View view;",
            "    view = finder.findRequiredView(source, 1, \"method 'doStuff'\");",
            "    ((android.widget.AdapterView<?>) view).setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() {",
            "      @Override public boolean onItemLongClick(android.widget.AdapterView<?> p0, android.view.View p1, int p2, long p3) {",
            "        return target.doStuff();",
            "      }",
            "    });",
            "  }",
            "  @Override public void unbind(T target) {",
            "  }",
            "}"
        ));

    ASSERT.about(javaSource()).that(source)
        .processedWith(new ButterKnifeProcessor())
        .compilesWithoutError()
        .and()
        .generatesSources(expectedSource);
  }
}


text:
<!DOCTYPE html>

    <title>Technical Update (4/1/2016)</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="Digital Public Library of America, Stanford University, and DuraSpace, with funding from the Institute of Museum and Library Services, are working together to build a next-generation repository solution
" />
    <meta name="keywords" content="" />

      <link rel="stylesheet" href="/archive/css/skel.css" />
      <link rel="stylesheet" href="/archive/css/style.css" />
      <link rel="stylesheet" href="/archive/css/style-xlarge.css" />

Hydra-In-a-Box

Home

Blog

Presentations & Demos

FAQ

Wiki

Mailing List

Contact Us

Submit your ideas

Technical Update (4/1/2016)

Apr 1, 2016 • Mike Giarlo

After an invigorating week at LDCX and Samvera community meetings, the Hydra-in-a-Box technical team hit the ground running on Monday in what was our second development sprint. We'll be sharing our progress via weekly demonstrations, the first of which is now available.

The first milestone for the current series of sprints is June 1st, 2016, at which time we plan to demonstrate a multi-tenant Hydra-in-a-Box repository application deployed to Amazon Web Services, which:

supports the management of top-priority content types: image-based works and generic multi-file works

offers a user interface for dynamic configuration of the application (without having to touch code files)

provides an administrative dashboard with reporting widgets

allows for batch import of content and metadata

Our tickets for the above feature work are viewable on Waffle and the application code is in a Samvera Labs repository on GitHub. The team is also actively working with the Samvera community on tickets for the Sufia 7.0.0 release.

We'll be sharing these weekly demos here on the blog every Friday. Stay tuned for more and, in the meantime, please don't hesitate to let us know what's on your mind such as how to make these demos more useful to you.

            ← Previous post

            Next post →

Hydra-In-A-Box

Blog

Presentations & Demos

FAQ

Wiki

Mailing List

Contact Us

Project Partners

Digital Public Library of America

Stanford University

DuraSpace

Institute of Museum and Library Services

Samvera Community

Submit your ideas!

We'd love to hear your ideas for features and functionality for Hydra-in-a-Box. To submit your idea, please use our form, or visit our project on GitHub!

Twitter

GitHub

RSS Feed

© Hydra-In-a-Box. All rights reserved.

Design: TEMPLATED

Jekyll Template: Cloud Cannon


text:
static void cleanup(void) __attribute__ ((destructor));

main() {
   printf("Some actions happen in the main() function..\n");
   printf("and then when main() exits, the destructor is called..\n");

   exit(0);
}

void cleanup(void) {
   printf("In the cleanup function now..\n");
}


text:
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))

from bakery.app import app, db

ctx = app.test_request_context('/')
ctx.push()

from bakery.models import User

user = User.get_or_init(login='offline')
user.name = 'Offline User'
user.email = 'fake@mail.tldr'
user.github_access_token = 'fake'

db.session.add(user)
db.session.commit()

ctx.pop()


text:
#ifndef __ttl_impl_data_holder__hpp
#define __ttl_impl_data_holder__hpp

namespace ttl
{
	struct data_holder_base {};

	template< typename T >
	struct data_holder : data_holder_base
	{
		enum { const_value = 0 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef T& return_type;
		typedef const T& const_return_type;
		typedef const T& param_type;

		T d;

		data_holder() : d() {}
		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		const_return_type get() const { return d; }
		return_type get() { return d; }
		const_pointer operator&() const { return &d; }
		pointer operator&() { return &d; }
		const_reference operator*() const { return d; }
		reference operator*() { return d; }
	};

	template< typename T >
	struct data_holder< const T > : data_holder_base
	{
		enum { const_value = 1 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef const T& return_type;
		typedef const T& const_return_type;
		typedef const T& param_type;

		const T d;

		data_holder() : d() {}
		data_holder( param_type d_ ) : d(d_) {}

		const_return_type get() const { return d; }
		const_pointer operator&() const { return &d; }
		const_reference operator*() const { return d; }
	};

	template< typename T >
	struct data_holder<T&> : data_holder_base
	{
		enum { const_value = 0 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef T& return_type;
		typedef const T& const_return_type;
		typedef T& param_type;

		T& d;

		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		const_return_type get() const { return d; }
		return_type get() { return d; }
		const_pointer operator&() const { return &d; }
		pointer operator&() { return &d; }
		const_reference operator*() const { return d; }
		reference operator*() { return d; }
	};

	template< typename T >
	struct data_holder<const T&> : data_holder_base
	{
		enum { const_value = 0 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef const T& return_type;
		typedef const T& const_return_type;
		typedef const T& param_type;

		const T& d;

		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		const_return_type get() const { return d; }
		const_pointer operator&() const { return &d; }
		const_reference operator*() const { return d; }
	};

	template< typename T >
	struct data_holder<T*> : data_holder_base
	{
		enum { const_value = 0 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef T* return_type;
		typedef const T* const_return_type;
		typedef T* param_type;

		T* d;

		data_holder() : d(0) {}
		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		const_return_type get() const { return d; }
		return_type get() { return d; }
		const_pointer operator&() const { return d; }
		pointer operator&() { return d; }
		const_reference operator*() const { return *d; }
		reference operator*() { return *d; }
	};

	template<>
	struct data_holder<void*> : data_holder_base
	{
		enum { const_value = 0 };

		typedef void type;
		typedef void* pointer;

		typedef void* return_type;
		typedef void* param_type;

		void* d;

		data_holder() : d(0) {}
		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		return_type get() { return d; }
		pointer operator&() { return d; }
	};

	template< typename T >
	struct data_holder<const T*> : data_holder_base
	{
		enum { const_value = 0 };

		typedef T type;
		typedef T& reference;
		typedef const T& const_reference;
		typedef T* pointer;
		typedef const T* const_pointer;

		typedef const T* return_type;
		typedef const T* const_return_type;
		typedef const T* param_type;

		const T* d;

		data_holder() : d(0) {}
		data_holder( param_type d_ ) : d(d_) {}

		void set( param_type d_ ) { d = d_; }
		const_return_type get() const { return d; }
		const_pointer operator&() const { return d; }
		const_reference operator*() const { return *d; }
	};

}

#endif //__data_holder__hpp


text:
{{> header}}

                        Contacto

En este formulario nos puedes enviar cualquier sugerencia, incidencia o comentario. Te contestaremos lo más rápido posible.

            <form role="form">

                        Nombre
                        <input type="text" class="form-control">

                        Email
                        <input type="email" class="form-control">

                        Teléfono
                        <input type="tel" class="form-control">

                        Mensaje
                        <textarea class="form-control" rows="6"></textarea>

                        <input type="hidden" name="save" value="contact">
                        <button type="submit" class="btn btn-default">Enviar comentario</button>

            </form>

{{> footer}}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>ChartLegend example</title>

      <canvas id="example" width="450" height="180"></canvas>


text:
<?php declare(strict_types=1);

namespace PHPUnit\Metadata;

use function array_filter;
use function array_merge;
use function count;
use Countable;
use IteratorAggregate;

/**
 * @internal This class is not covered by the backward compatibility promise for PHPUnit
 * @psalm-immutable
 */
final class MetadataCollection implements Countable, IteratorAggregate
{
    /**
     * @psalm-var list<Metadata>
     */
    private array $metadata;

    /**
     * @psalm-param list<Metadata> $metadata
     */
    public static function fromArray(array $metadata): self
    {
        return new self(...$metadata);
    }

    private function __construct(Metadata ...$metadata)
    {
        $this->metadata = $metadata;
    }

    /**
     * @psalm-return list<Metadata>
     */
    public function asArray(): array
    {
        return $this->metadata;
    }

    public function count(): int
    {
        return count($this->metadata);
    }

    public function isEmpty(): bool
    {
        return $this->count() === 0;
    }

    public function isNotEmpty(): bool
    {
        return $this->count() > 0;
    }

    public function getIterator(): MetadataCollectionIterator
    {
        return new MetadataCollectionIterator($this);
    }

    public function mergeWith(self $other): self
    {
        return new self(
            ...array_merge(
                $this->asArray(),
                $other->asArray()
            )
        );
    }

    public function isAfter(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isAfter();
                }
            )
        );
    }

    public function isAfterClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isAfterClass();
                }
            )
        );
    }

    public function isBackupGlobals(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isBackupGlobals();
                }
            )
        );
    }

    public function isBackupStaticProperties(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isBackupStaticProperties();
                }
            )
        );
    }

    public function isBeforeClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isBeforeClass();
                }
            )
        );
    }

    public function isBefore(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isBefore();
                }
            )
        );
    }

    public function isCodeCoverageIgnore(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCodeCoverageIgnore();
                }
            )
        );
    }

    public function isCovers(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCovers();
                }
            )
        );
    }

    public function isCoversClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCoversClass();
                }
            )
        );
    }

    public function isCoversDefaultClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCoversDefaultClass();
                }
            )
        );
    }

    public function isCoversMethod(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCoversMethod();
                }
            )
        );
    }

    public function isCoversFunction(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCoversFunction();
                }
            )
        );
    }

    public function isExcludeGlobalVariableFromBackup(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isExcludeGlobalVariableFromBackup();
                }
            )
        );
    }

    public function isExcludeStaticPropertyFromBackup(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isExcludeStaticPropertyFromBackup();
                }
            )
        );
    }

    public function isCoversNothing(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isCoversNothing();
                }
            )
        );
    }

    public function isDataProvider(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isDataProvider();
                }
            )
        );
    }

    public function isDepends(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isDependsOnClass() || $metadata->isDependsOnMethod();
                }
            )
        );
    }

    public function isDependsOnClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isDependsOnClass();
                }
            )
        );
    }

    public function isDependsOnMethod(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isDependsOnMethod();
                }
            )
        );
    }

    public function isDoesNotPerformAssertions(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isDoesNotPerformAssertions();
                }
            )
        );
    }

    public function isGroup(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isGroup();
                }
            )
        );
    }

    public function isRunClassInSeparateProcess(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRunClassInSeparateProcess();
                }
            )
        );
    }

    public function isRunInSeparateProcess(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRunInSeparateProcess();
                }
            )
        );
    }

    public function isRunTestsInSeparateProcesses(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRunTestsInSeparateProcesses();
                }
            )
        );
    }

    public function isTest(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isTest();
                }
            )
        );
    }

    public function isPreCondition(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isPreCondition();
                }
            )
        );
    }

    public function isPostCondition(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isPostCondition();
                }
            )
        );
    }

    public function isPreserveGlobalState(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isPreserveGlobalState();
                }
            )
        );
    }

    public function isRequiresMethod(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresMethod();
                }
            )
        );
    }

    public function isRequiresFunction(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresFunction();
                }
            )
        );
    }

    public function isRequiresOperatingSystem(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresOperatingSystem();
                }
            )
        );
    }

    public function isRequiresOperatingSystemFamily(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresOperatingSystemFamily();
                }
            )
        );
    }

    public function isRequiresPhp(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresPhp();
                }
            )
        );
    }

    public function isRequiresPhpExtension(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresPhpExtension();
                }
            )
        );
    }

    public function isRequiresPhpunit(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresPhpunit();
                }
            )
        );
    }

    public function isRequiresSetting(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isRequiresSetting();
                }
            )
        );
    }

    public function isTestDox(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isTestDox();
                }
            )
        );
    }

    public function isTestWith(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isTestWith();
                }
            )
        );
    }

    public function isUses(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isUses();
                }
            )
        );
    }

    public function isUsesClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isUsesClass();
                }
            )
        );
    }

    public function isUsesDefaultClass(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isUsesDefaultClass();
                }
            )
        );
    }

    public function isUsesMethod(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isUsesMethod();
                }
            )
        );
    }

    public function isUsesFunction(): self
    {
        return new self(
            ...array_filter(
                $this->metadata,
                static function (Metadata $metadata): bool {
                    return $metadata->isUsesFunction();
                }
            )
        );
    }
}


text:
package com.tle.webtests.pageobject.searching;

import com.tle.webtests.framework.PageContext;
import com.tle.webtests.pageobject.AbstractPage;
import com.tle.webtests.pageobject.WaitingPageObject;
import com.tle.webtests.pageobject.generic.component.EquellaSelect;
import org.openqa.selenium.By;
import org.openqa.selenium.NotFoundException;

public class FilterByItemStatusSectionPage extends AbstractPage<FilterByItemStatusSectionPage> {
  private EquellaSelect statusList;
  private AbstractResultList<?, ?> resultsPageObject;

  public FilterByItemStatusSectionPage(
      PageContext context, AbstractResultList<?, ?> resultsPageObject) {
    super(context, By.id("status"));
    setMustBeVisible(false);
    this.resultsPageObject = resultsPageObject;
  }

  @Override
  public void checkLoaded() throws NotFoundException {
    super.checkLoaded();
    statusList = new EquellaSelect(context, driver.findElement(loadedBy));
  }

  public void setItemStatusFilter(String status) {
    String selectedValue = statusList.getSelectedValue();

    if (!status.equals(selectedValue)) {
      WaitingPageObject<?> updateWaiter = resultsPageObject.getUpdateWaiter();
      statusList.selectByValue(status);
      updateWaiter.get();
    }
  }
}


text:
namespace naive {

static MainLooper* g_looper = nullptr;

// static
MainLooper* MainLooper::Get() {
  if (!g_looper)
    g_looper = new MainLooper();
  return g_looper;
}

void MainLooper::AddFd(int fd, base::HandlerFunc handler) {
  if (std::find_if(fds_.begin(), fds_.end(),
                   [fd](pollfd& pfd) { return pfd.fd == fd; }) != fds_.end())
    return;

  fds_.push_back({.fd = fd, .events = POLLIN});
  handlers_.push_back(handler);
}

void MainLooper::AddHandler(base::HandlerFunc handler) {
  handlers_.push_back(handler);
}

void MainLooper::Run() {
  for (;;) {
    for (size_t i = 0; i < handlers_.size(); i++)
      handlers_[i]();
    poll(fds_.data(), fds_.size(), 1);
  }
}

}  // namespace naive


text:
<?php

namespace Kunstmaan\AdminBundle\Helper\AdminPanel;

interface AdminPanelActionInterface
{
    /**
     * @return array
     */
    public function getUrl();

    /**
     * @return string
     */
    public function getLabel();

    /**
     * @return string
     */
    public function getIcon();

    /**
     * @return string
     */
    public function getTemplate();
}


text:
package com.sharksharding.core.shard;

import java.util.Arrays;
import java.util.List;

/**
 * 解析分库分表字段
 *
 * @author gaoxianglong
 *
 * @version 1.4.0
 */
public class ResolveShardkey {
	/**
	 * 从分库分表算法中解shardkey
	 *
	 * @author gaoxianglong
	 *
	 * @param shardConfigInfo
	 *            分库分表配置信息
	 *
	 * @return List<String> shardKeys
	 */
	public static List<String> getShardKeys(ShardConfigInfo shardConfigInfo) {
		final String dbRuleArray = shardConfigInfo.getDbRuleArray();
		final String tbRuleArray = shardConfigInfo.getTbRuleArray();
		String shardKey = null;
		if (null != dbRuleArray) {
			shardKey = dbRuleArray.split("\\#")[1];
			return Arrays.asList(shardKey.split("\\|"));
		} else if (null != tbRuleArray) {
			shardKey = tbRuleArray.split("\\#")[1];
			return Arrays.asList(shardKey.split("\\|"));
		}
		return null;
	}
}


text:
@interface TSZTitleLabel : UILabel

// 传入一个比例
@property (nonatomic ,assign)CGFloat scale;
@end


text:
package org.opentosca.toscana.retrofit.util;

import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RetrofitLoggerWrapper implements HttpLoggingInterceptor.Logger {

    private final Logger logger;

    public RetrofitLoggerWrapper(String endpoint) {
        logger = LoggerFactory.getLogger("TOSCAna-API - " + endpoint);
    }

    @Override
    public void log(String message) {
        logger.info(message);
    }
}


text:
require 'test_helper'

class Donatable::Test < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, Donatable
  end
end


text:
class GenHash : public KParts::Plugin
{
    Q_OBJECT
public:
    GenHash( QObject* parent, const QVariantList & );
    ~GenHash() {}

public slots:
    void calcGenHash();

private:

    void sandbox_init();
    void readByteArryFromFile();

    void calcMD5();

    int pipe_fd[2];
    int pipe_result_fd[2];
    int child_pid;
    int status;
    char buff[1024];

};

#endif


text:
#import "PlaybackSegment_Internal.h"
#import "Trace.h"

@implementation PlaybackSegment

#pragma mark -
#pragma mark Properties:

@synthesize clip;
@synthesize initialPlaybackTime;
@synthesize initialPlaybackRate;
@synthesize segmentId;
@synthesize error;
@synthesize status;

#pragma mark -
#pragma mark Internal Properties:

// viewIndex property.
//
// getter method of the viewIndex property.
//
// Arguments:   none.
//
// Returns:
// The value of viewIndex.
//
- (int32_t) viewIndex
{
    return (viewIndex);
}

// setter method of the viewIndex property.
//
// Arguments:
// [newViewIndex]   int32_t to be set.
//
// Returns: none.
//
- (void) setViewIndex:(int32_t)newViewIndex
{
    viewIndex = newViewIndex;
}

#pragma mark -
#pragma mark Destructor:

- (void) dealloc
{
    SEQUENCER_LOG(@"PlaybackSegment dealloc called.");

    [clip release];
    [error release];

    [super dealloc];
}

@end


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Poria wakefieldi Rodway & Cleland

### Remarks
null


text:
namespace net {
namespace ct {

SignedTreeHead::SignedTreeHead() = default;

SignedTreeHead::SignedTreeHead(Version version,
                               const base::Time& timestamp,
                               uint64_t tree_size,
                               const char sha256_root_hash[kSthRootHashLength],
                               const DigitallySigned& signature,
                               const std::string& log_id)
    : version(version),
      timestamp(timestamp),
      tree_size(tree_size),
      signature(signature),
      log_id(log_id) {
  memcpy(this->sha256_root_hash, sha256_root_hash, kSthRootHashLength);
}

SignedTreeHead::SignedTreeHead(const SignedTreeHead& other) = default;

SignedTreeHead::~SignedTreeHead() = default;

void PrintTo(const SignedTreeHead& sth, std::ostream* os) {
  (*os) << "{\n"
        << "\t\"version\": " << sth.version << ",\n"
        << "\t\"timestamp\": " << sth.timestamp << ",\n"
        << "\t\"tree_size\": " << sth.tree_size << ",\n"
        << "\t\"sha256_root_hash\": \""
        << base::HexEncode(sth.sha256_root_hash, kSthRootHashLength)
        << "\",\n\t\"log_id\": \""
        << base::HexEncode(sth.log_id.data(), sth.log_id.size()) << "\"\n"
        << "}";
}

bool operator==(const SignedTreeHead& lhs, const SignedTreeHead& rhs) {
  return std::tie(lhs.version, lhs.timestamp, lhs.tree_size, lhs.log_id) ==
             std::tie(rhs.version, rhs.timestamp, rhs.tree_size, rhs.log_id) &&
         memcmp(lhs.sha256_root_hash, rhs.sha256_root_hash,
                kSthRootHashLength) == 0 &&
         lhs.signature.SignatureParametersMatch(
             rhs.signature.hash_algorithm, rhs.signature.signature_algorithm) &&
         lhs.signature.signature_data == rhs.signature.signature_data;
}

bool operator!=(const SignedTreeHead& lhs, const SignedTreeHead& rhs) {
  return !(lhs == rhs);
}

}  // namespace ct
}  // namespace net


text:
<bill session="110" type="h" number="2067" updated="2009-01-08T21:10:41-05:00">
	<status><introduced date="1177560000" datetime="2007-04-26"/></status>

	<introduced date="1177560000" datetime="2007-04-26"/>
	<titles>
		<title type="short" as="introduced">Good Samaritan Protection for Construction, Architectural, and Engineering Volunteers Act</title>
		<title type="official" as="introduced">To provide construction, architectural, and engineering entities with qualified immunity from liability for negligence when providing services or equipment on a volunteer basis in response to a declared emergency or disaster.</title>
	</titles>
	<sponsor id="400660"/>
	<cosponsors>
		<cosponsor id="400627" joined="2007-11-15"/>
		<cosponsor id="400059" joined="2007-11-13"/>
		<cosponsor id="400096" joined="2007-10-02"/>
		<cosponsor id="400260" joined="2008-02-06"/>
		<cosponsor id="400132" joined="2007-10-15"/>
		<cosponsor id="400406" joined="2007-05-14"/>
		<cosponsor id="409888" joined="2007-11-05"/>
		<cosponsor id="400370" joined="2007-04-26"/>
		<cosponsor id="400416" joined="2007-04-26"/>
		<cosponsor id="400277" joined="2007-04-26"/>
		<cosponsor id="400255" joined="2007-04-26"/>
		<cosponsor id="400617" joined="2007-04-26"/>
		<cosponsor id="400315" joined="2008-05-21"/>
		<cosponsor id="400636" joined="2007-11-14"/>
	</cosponsors>
	<actions>
		<action date="1177560000" datetime="2007-04-26"><text>Referred to the House Committee on the Judiciary.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	4/26/2007--Introduced.
Good Samaritan Protection for Construction, Architectural, and Engineering Volunteers Act - Grants construction companies and architectural and engineering firms and their employees immunity from liability for negligence, except for gross negligence or willful misconduct, when providing emergency assistance on a voluntary basis in response to a declared emergency or disaster, in good faith, and without expectation of compensation.

</bill>


text:
'use strict';

// Config HTTP Error Handling
angular.module('material')
	.config(function($mdThemingProvider, $mdIconProvider){

		//$mdIconProvider
		//	.defaultIconSet("./assets/svg/avatars.svg", 128)
		//	.icon("menu"       , "./assets/svg/menu.svg"        , 24)
		//	.icon("share"      , "./assets/svg/share.svg"       , 24)
		//	.icon("google_plus", "./assets/svg/google_plus.svg" , 512)
		//	.icon("hangouts"   , "./assets/svg/hangouts.svg"    , 512)
		//	.icon("twitter"    , "./assets/svg/twitter.svg"     , 512)
		//	.icon("phone"      , "./assets/svg/phone.svg"       , 512);

		$mdThemingProvider.theme('default')
			.primaryPalette('blue-grey')
			.accentPalette('orange');

	});