text:
from __future__ import absolute_import, division, print_function, unicode_literals

from splunklib.searchcommands.internals import CommandLineParser, InputHeader, RecordWriterV1
from splunklib.searchcommands.decorators import Configuration, Option
from splunklib.searchcommands.validators import Boolean

from splunklib.searchcommands.search_command import SearchCommand

from contextlib import closing
from cStringIO import StringIO
from itertools import izip
from unittest import main, TestCase

import os

class TestInternals(TestCase):
    def setUp(self):
        TestCase.setUp(self)

    def test_command_line_parser(self):

        @Configuration()
        class TestCommandLineParserCommand(SearchCommand):

            required_option = Option(validate=Boolean(), require=True)
            unnecessary_option = Option(validate=Boolean(), default=True, require=False)

            class ConfigurationSettings(SearchCommand.ConfigurationSettings):

                @classmethod
                def fix_up(cls, command_class): pass

        # Command line without fieldnames

        options = ['required_option=true', 'unnecessary_option=false']

        command = TestCommandLineParserCommand()
        CommandLineParser.parse(command, options)

        for option in command.options.itervalues():
            if option.name in ['logging_configuration', 'logging_level', 'record', 'show_configuration']:
                self.assertFalse(option.is_set)
                continue
            self.assertTrue(option.is_set)

        expected = 'testcommandlineparser required_option="t" unnecessary_option="f"'
        self.assertEqual(expected, str(command))
        self.assertEqual(command.fieldnames, [])

        # Command line with fieldnames

        fieldnames = ['field_1', 'field_2', 'field_3']

        command = TestCommandLineParserCommand()
        CommandLineParser.parse(command, options + fieldnames)

        for option in command.options.itervalues():
            if option.name in ['logging_configuration', 'logging_level', 'record', 'show_configuration']:
                self.assertFalse(option.is_set)
                continue
            self.assertTrue(option.is_set)

        expected = 'testcommandlineparser required_option="t" unnecessary_option="f" field_1 field_2 field_3'
        self.assertEqual(expected, str(command))
        self.assertEquals(command.fieldnames, fieldnames)

        # Command line without any unnecessary options

        command = TestCommandLineParserCommand()
        CommandLineParser.parse(command, ['required_option=true'] + fieldnames)

        for option in command.options.itervalues():
            if option.name in ['unnecessary_option', 'logging_configuration', 'logging_level', 'record', 'show_configuration']:
                self.assertFalse(option.is_set)
                continue
            self.assertTrue(option.is_set)

        expected = 'testcommandlineparser required_option="t" field_1 field_2 field_3'
        self.assertEqual(expected, str(command))
        self.assertEquals(command.fieldnames, fieldnames)

        # Command line with missing required options, with or without fieldnames or unnecessary options

        options = ['unnecessary_option=true']
        self.assertRaises(ValueError, CommandLineParser.parse, command, options + fieldnames)
        self.assertRaises(ValueError, CommandLineParser.parse, command, options)
        self.assertRaises(ValueError, CommandLineParser.parse, command, [])

        # Command line with unrecognized options

        self.assertRaises(ValueError, CommandLineParser.parse, command, ['unrecognized_option_1=foo', 'unrecognized_option_2=bar'])

        # Command line with a variety of quoted/escaped text options

        @Configuration()
        class TestCommandLineParserCommand(SearchCommand):

            text = Option()

            class ConfigurationSettings(SearchCommand.ConfigurationSettings):

                @classmethod
                def fix_up(cls, command_class): pass

        strings = [
            r'"foo bar"',
            r'"foo/bar"',
            r'"foo\\bar"',
            r'"""foo bar"""',
            r'"\"foo bar\""',
            r'Hello\ World!',
            r'\"Hello\ World!\"']

        expected_values = [
            r'foo bar',
            r'foo/bar',
            r'foo\bar',
            r'"foo bar"',
            r'"foo bar"',
            r'Hello World!',
            r'"Hello World!"'
        ]

        for string, expected_value in izip(strings, expected_values):
            command = TestCommandLineParserCommand()
            argv = ['text', '=', string]
            CommandLineParser.parse(command, argv)
            self.assertEqual(command.text, expected_value)

        for string, expected_value in izip(strings, expected_values):
            command = TestCommandLineParserCommand()
            argv = [string]
            CommandLineParser.parse(command, argv)
            self.assertEqual(command.fieldnames[0], expected_value)

        for string, expected_value in izip(strings, expected_values):
            command = TestCommandLineParserCommand()
            argv = ['text', '=', string] + strings
            CommandLineParser.parse(command, argv)
            self.assertEqual(command.text, expected_value)
            self.assertEqual(command.fieldnames, expected_values)

        strings = [
            'some\\ string\\',
            r'some\ string"',
            r'"some string',
            r'some"string'
        ]

        for string in strings:
            command = TestCommandLineParserCommand()
            argv = [string]
            self.assertRaises(SyntaxError, CommandLineParser.parse, command, argv)

        return

    def test_command_line_parser_unquote(self):
        parser = CommandLineParser

        options = [
            r'foo',                 # unquoted string with no escaped characters
            r'fo\o\ b\"a\\r',       # unquoted string with some escaped characters
            r'"foo"',               # quoted string with no special characters
            r'"""foobar1"""',       # quoted string with quotes escaped like this: ""
            r'"\"foobar2\""',       # quoted string with quotes escaped like this: \"
            r'"foo ""x"" bar"',     # quoted string with quotes escaped like this: ""
            r'"foo \"x\" bar"',     # quoted string with quotes escaped like this: \"
            r'"\\foobar"',          # quoted string with an escaped backslash
            r'"foo \\ bar"',        # quoted string with an escaped backslash
            r'"foobar\\"',          # quoted string with an escaped backslash
            r'foo\\\bar',           # quoted string with an escaped backslash and an escaped 'b'
            r'""',                  # pair of quotes
            r'']                    # empty string

        expected = [
            r'foo',
            r'foo b"a\r',
            r'foo',
            r'"foobar1"',
            r'"foobar2"',
            r'foo "x" bar',
            r'foo "x" bar',
            '\\foobar',
            r'foo \ bar',
            'foobar\\',
            r'foo\bar',
            r'',
            r'']

        # Command line with an assortment of string values

        self.assertEqual(expected[-4], parser.unquote(options[-4]))

        for i in range(0, len(options)):
            self.assertEqual(expected[i], parser.unquote(options[i]))

        self.assertRaises(SyntaxError, parser.unquote, '"')
        self.assertRaises(SyntaxError, parser.unquote, '"foo')
        self.assertRaises(SyntaxError, parser.unquote, 'foo"')
        self.assertRaises(SyntaxError, parser.unquote, 'foo\\')

    def test_input_header(self):

        # No items

        input_header = InputHeader()

        with closing(StringIO('\r\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 0)

        # One unnamed single-line item (same as no items)

        input_header = InputHeader()

        with closing(StringIO('this%20is%20an%20unnamed%20single-line%20item\n\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 0)

        input_header = InputHeader()

        with closing(StringIO('this%20is%20an%20unnamed\nmulti-\nline%20item\n\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 0)

        # One named single-line item

        input_header = InputHeader()

        with closing(StringIO('Foo:this%20is%20a%20single-line%20item\n\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 1)
        self.assertEquals(input_header['Foo'], 'this is a single-line item')

        input_header = InputHeader()

        with closing(StringIO('Bar:this is a\nmulti-\nline item\n\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 1)
        self.assertEquals(input_header['Bar'], 'this is a\nmulti-\nline item')

        # The infoPath item (which is the path to a file that we open for reads)

        input_header = InputHeader()

        with closing(StringIO('infoPath:non-existent.csv\n\n'.encode())) as input_file:
            input_header.read(input_file)

        self.assertEquals(len(input_header), 1)
        self.assertEqual(input_header['infoPath'], 'non-existent.csv')

        # Set of named items

        collection = {
            'word_list': 'hello\nworld\n!',
            'word_1': 'hello',
            'word_2': 'world',
            'word_3': '!',
            'sentence': 'hello world!'}

        input_header = InputHeader()
        text = reduce(lambda value, item: value + '{}:{}\n'.format(item[0], item[1]), collection.iteritems(), '') + '\n'

        with closing(StringIO(text.encode())) as input_file:
            input_header.read(input_file)

        self.assertDictEqual(input_header, collection)

        # Set of named items with an unnamed item at the beginning (the only place that an unnamed item can appear)

        with closing(StringIO(('unnamed item\n' + text).encode())) as input_file:
            input_header.read(input_file)

        self.assertDictEqual(input_header, collection)

        # Test iterators, indirectly through items, keys, and values

        self.assertEqual(sorted(input_header.items()), sorted(collection.items()))
        self.assertEqual(sorted(input_header.keys()), sorted(collection.keys()))
        self.assertEqual(sorted(input_header.values()), sorted(collection.values()))

        return

    def test_messages_header(self):

        @Configuration()
        class TestMessagesHeaderCommand(SearchCommand):

            class ConfigurationSettings(SearchCommand.ConfigurationSettings):

                @classmethod
                def fix_up(cls, command_class): pass

        command = TestMessagesHeaderCommand()
        command._protocol_version = 1
        output_buffer = StringIO()
        command._record_writer = RecordWriterV1(output_buffer)

        messages = [
            (command.write_debug, 'debug_message'),
            (command.write_error, 'error_message'),
            (command.write_fatal, 'fatal_message'),
            (command.write_info, 'info_message'),
            (command.write_warning, 'warning_message')]

        for write, message in messages:
            write(message)

        command.finish()

        expected = (
            'debug_message=debug_message\r\n'
            'error_message=error_message\r\n'
            'error_message=fatal_message\r\n'
            'info_message=info_message\r\n'
            'warn_message=warning_message\r\n'
            '\r\n')

        self.assertEquals(output_buffer.getvalue(), expected)
        return

    _package_path = os.path.dirname(__file__)

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using UnityEngine;

namespace AssetUsageDetectorNamespace
{
	// Delegate to get the value of a variable (either field or property)
	public delegate object VariableGetVal( object obj );

	// Custom struct to hold a variable, its important properties and its getter function
	public struct VariableGetterHolder
	{
		public readonly MemberInfo variable;
		public readonly bool isSerializable;
		private readonly VariableGetVal getter;

		public string Name { get { return variable.Name; } }
		public bool IsProperty { get { return variable is PropertyInfo; } }

		public VariableGetterHolder( FieldInfo fieldInfo, VariableGetVal getter, bool isSerializable )
		{
			this.variable = fieldInfo;
			this.isSerializable = isSerializable;
			this.getter = getter;
		}

		public VariableGetterHolder( PropertyInfo propertyInfo, VariableGetVal getter, bool isSerializable )
		{
			this.variable = propertyInfo;
			this.isSerializable = isSerializable;
			this.getter = getter;
		}

		public object Get( object obj )
		{
			try
			{
				return getter( obj );
			}
			catch( Exception e )
			{
				Debug.LogException( e );
				return null;
			}
		}
	}

	// Credit: http://stackoverflow.com/questions/724143/how-do-i-create-a-delegate-for-a-net-property
	public interface IPropertyAccessor
	{
		object GetValue( object source );
	}

	// A wrapper class for properties to get their values more efficiently
	public class PropertyWrapper<TObject, TValue> : IPropertyAccessor where TObject : class
	{
		private readonly Func<TObject, TValue> getter;

		public PropertyWrapper( MethodInfo getterMethod )
		{
			getter = (Func<TObject, TValue>) Delegate.CreateDelegate( typeof( Func<TObject, TValue> ), getterMethod );
		}

		public object GetValue( object obj )
		{
			try
			{
				return getter( (TObject) obj );
			}
			catch
			{
				// Property getters may return various kinds of exceptions if their backing fields are not initialized (yet)
				return null;
			}
		}
	}
}


text:
permalink: /nl/bitcoin
redirect: /nl/
layout: redirect
sitemap: false
---


text:
import unittest
import pkgutil
import tests
import logging

logging.basicConfig(filename='tests.log', filemode='w', level=logging.DEBUG)
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for _loader, name, _ispkg in pkgutil.iter_modules(tests.__path__):
    if not name.startswith('__'):
        suite.addTest(loader.loadTestsFromName('tests.'+name))
unittest.TextTestRunner(verbosity=2).run(suite)


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.index = Ti.UI.createWindow({
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    $.__views.adView = Ti.UI.createView({
        id: "adView",
        top: "0",
        width: Ti.UI.FILL,
        height: "500"
    });
    $.__views.index.add($.__views.adView);
    exports.destroy = function() {};
    _.extend($, $.__views);
    Ti.API.info("Requesting Ads...");
    Admob = require("ti.admob");
    banner = Admob.createView({
        publisherId: "ca-app-pub-4951262838901192/5818956263",
        testing: false
    });
    if ("android" == Ti.Platform.osname) {
        banner.addEventListener(Admob.AD_RECEIVED, function() {
            Ti.API.info("Did receive ad!");
        });
        banner.addEventListener(Admob.AD_NOT_RECEIVED, function() {
            Ti.API.info("Failed to receive ad!");
        });
    } else {
        banner.addEventListener("didReceiveAd", function() {
            Ti.API.info("Did receive ad!");
        });
        banner.addEventListener("didFailToReceiveAd", function() {
            Ti.API.info("Failed to receive ad!");
        });
    }
    $.adView.add(banner);
    $.index.open();
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
package org.apache.ignite.internal.processors.cache;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.Callable;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.binary.BinaryInvalidTypeException;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.GridProcessorAdapter;
import org.apache.ignite.testframework.GridStringLogger;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;

/**
 * Tests of binary type mismatch logging.
 */
public class BinaryTypeMismatchLoggingTest extends GridCommonAbstractTest {
    /** */
    public static final String MESSAGE_PAYLOAD_VALUE = "expValType=Payload, actualValType=o.a.i.i.processors.cache.BinaryTypeMismatchLoggingTest$Payload";

    /** */
    private GridStringLogger capture;

    /**
     * @throws Exception In case of an error.
     */
    public void testValueReadCreateTable() throws Exception {
        Ignite ignite = startGrid(0);

        IgniteCache def = ignite.createCache("default");

        def.query(new SqlFieldsQuery("CREATE TABLE binary (id INT PRIMARY KEY, str VARCHAR) " +
            "WITH \"cache_name=binary, value_type=Payload\"").setSchema("PUBLIC"));

        def.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (1, 'foo');").setSchema("PUBLIC"));
        def.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (2, 'bar');").setSchema("PUBLIC"));

        GridTestUtils.assertThrowsAnyCause(
            log,
            new Callable<Object>() {
                @Override public Object call() {
                    return ignite.cache("binary").get(1);
                }
            },
            BinaryInvalidTypeException.class,
            "Payload");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testValueReadQueryEntities() throws Exception {
        Ignite ignite = startGrid(0);

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache binary = ignite.createCache(new CacheConfiguration<>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyFieldName("id").setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (1, 'foo');"));
        binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (2, 'bar');"));

        GridTestUtils.assertThrowsAnyCause(
            log,
            new Callable<Object>() {
                @Override public Object call() {
                    return ignite.cache("binary").get(1);
                }
            },
            BinaryInvalidTypeException.class,
            "Payload");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testEntryReadCreateTable() throws Exception {
        Ignite ignite = startGrid(0);

        IgniteCache def = ignite.createCache("default");

        def.query(new SqlFieldsQuery("CREATE TABLE binary (id INT PRIMARY KEY, str VARCHAR) " +
            "WITH \"cache_name=binary, key_type=IdKey, value_type=Payload\"").setSchema("PUBLIC"));

        def.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (1, 'foo');").setSchema("PUBLIC"));
        def.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (2, 'bar');").setSchema("PUBLIC"));

        GridTestUtils.assertThrowsAnyCause(
            log,
            new Callable<Object>() {
                @Override public Object call() {
                    return ignite.cache("binary").iterator().next();
                }
            },
            BinaryInvalidTypeException.class,
            "IdKey");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testEntryReadQueryEntities() throws Exception {
        Ignite ignite = startGrid(0);

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache binary = ignite.createCache(new CacheConfiguration<>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyType("IdKey").setKeyFields(Collections.singleton("id"))
                .setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (1, 'foo');"));
        binary.query(new SqlFieldsQuery("INSERT INTO binary (id, str) VALUES (2, 'bar');"));

        GridTestUtils.assertThrowsAnyCause(
            log,
            new Callable<Object>() {
                @Override public Object call() {
                    return ignite.cache("binary").iterator().next();
                }
            },
            BinaryInvalidTypeException.class,
            "IdKey");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testValueWriteCreateTable() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        IgniteCache def = ignite.createCache("default");

        def.query(new SqlFieldsQuery("CREATE TABLE binary (id INT PRIMARY KEY, str VARCHAR) " +
            "WITH \"cache_name=binary, value_type=Payload\"").setSchema("PUBLIC"));

        IgniteCache<Integer, Payload> binary = ignite.cache("binary");
        binary.put(1, new Payload("foo"));
        binary.put(2, new Payload("bar"));

        assertEquals(0, countRows(binary));

        String capturedMessages = this.capture.toString();

        assertContainsExactlyOnce(capturedMessages,
            "Key-value pair is not inserted into any SQL table [cacheName=binary, " + MESSAGE_PAYLOAD_VALUE + "]");
        assertContainsExactlyOnce(capturedMessages,
            "Value type(s) are specified via CacheConfiguration.indexedTypes or CacheConfiguration.queryEntities");
        assertContainsExactlyOnce(capturedMessages,
            "Make sure that same type(s) used when adding Object or BinaryObject to cache");
        assertContainsExactlyOnce(capturedMessages,
            "Otherwise, entries will be stored in cache, but not appear as SQL Table rows");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testValueWriteQueryEntities() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache<Integer, Object> binary = ignite.createCache(new CacheConfiguration<Integer, Object>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyFieldName("id").setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.put(1, new Payload("foo"));
        binary.put(2, new IdKey(2));

        assertEquals(0, countRows(binary));

        assertContainsExactlyOnce(capture.toString(), MESSAGE_PAYLOAD_VALUE);
        assertContainsExactlyOnce(capture.toString(),
            "expValType=Payload, actualValType=o.a.i.i.processors.cache.BinaryTypeMismatchLoggingTest$IdKey");
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testEntryWriteCreateTable() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        IgniteCache def = ignite.createCache("default");

        def.query(new SqlFieldsQuery("CREATE TABLE binary (id INT PRIMARY KEY, str VARCHAR) " +
            "WITH \"cache_name=binary, key_type=IdKey, value_type=Payload\"").setSchema("PUBLIC"));

        IgniteCache<Integer, Payload> binary = ignite.cache("binary");
        binary.put(1, new Payload("foo"));
        binary.put(2, new Payload("bar"));

        assertEquals(0, countRows(binary));

        assertContainsExactlyOnce(capture.toString(), MESSAGE_PAYLOAD_VALUE);

        capture.reset();

        def.query(new SqlFieldsQuery("CREATE TABLE binary2 (id INT PRIMARY KEY, str VARCHAR) " +
            "WITH \"cache_name=binary2, key_type=IdKey, value_type=Payload\"").setSchema("PUBLIC"));

        IgniteCache<Integer, Payload> binary2 = ignite.cache("binary2");
        binary2.put(1, new Payload("foo"));
        binary2.put(2, new Payload("bar"));

        assertEquals(0, countRows(binary2));

        assertContainsExactlyOnce(capture.toString(), MESSAGE_PAYLOAD_VALUE);
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testEntryWriteQueryEntities() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache<IdKey, Payload> binary = ignite.createCache(new CacheConfiguration<IdKey, Payload>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyType("IdKey").setKeyFields(Collections.singleton("id"))
                .setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.put(new IdKey(1), new Payload("foo"));
        binary.put(new IdKey(2), new Payload("bar"));

        assertEquals(0, countRows(binary));

        binary.destroy();

        binary = ignite.createCache(new CacheConfiguration<IdKey, Payload>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyType("IdKey").setKeyFields(Collections.singleton("id"))
                .setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.put(new IdKey(1), new Payload("foo"));
        binary.put(new IdKey(2), new Payload("bar"));

        assertEquals(0, countRows(binary));

        assertContainsExactlyOnce(capture.toString(), MESSAGE_PAYLOAD_VALUE);
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testEntryWriteCacheIsolation() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache<IdKey, Payload> regular = ignite.createCache(new CacheConfiguration<IdKey, Payload>()
            .setName("regular").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyType(getClass().getName() + "$IdKey").setKeyFields(Collections.singleton("id"))
                .setValueType(getClass().getName() + "$Payload").setFields(fields).setTableName("binary"))));

        IgniteCache<IdKey, Payload> binary = ignite.createCache(new CacheConfiguration<IdKey, Payload>()
            .setName("binary").setQueryEntities(Collections.singleton(new QueryEntity()
                .setKeyType("IdKey").setKeyFields(Collections.singleton("id"))
                .setValueType("Payload").setFields(fields).setTableName("binary"))));

        regular.put(new IdKey(1), new Payload("foo"));
        regular.put(new IdKey(2), new Payload("bar"));

        binary.put(new IdKey(1), new Payload("foo"));
        binary.put(new IdKey(2), new Payload("bar"));

        assertEquals(0, countRows(binary));
        assertEquals(2, countRows(regular));

        assertContainsExactlyOnce(capture.toString(), MESSAGE_PAYLOAD_VALUE);
    }

    /**
     * @throws Exception In case of an error.
     */
    public void testValueWriteMultipleQueryEntities() throws Exception {
        Ignite ignite = startGridWithLogCapture();

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", "java.lang.Integer");
        fields.put("str", "java.lang.String");

        IgniteCache<Integer, Payload> binary = ignite.createCache(new CacheConfiguration<Integer, Payload>()
            .setName("binary").setQueryEntities(Arrays.asList(
            new QueryEntity().setKeyType("Foo").setKeyFieldName("id")
                .setValueType("Bar").setFields(fields).setTableName("regular"),
            new QueryEntity().setKeyFieldName("id").setValueType("Payload").setFields(fields).setTableName("binary"))));

        binary.put(1, new Payload("foo"));
        binary.put(2, new Payload("bar"));

        assertEquals(0, countRows(binary));

        assertContainsExactlyOnce(capture.toString(),
            "valType=o.a.i.i.processors.cache.BinaryTypeMismatchLoggingTest$Payload");
    }

    /** */
    private <K> int countRows(IgniteCache<K, ?> binary) {
        SqlFieldsQuery qry = new SqlFieldsQuery("SELECT COUNT(*) FROM binary");

        List<List<?>> result = binary.query(qry).getAll();
        return Number.class.cast(result.get(0).get(0)).intValue();
    }

    /** */
    private void assertContainsExactlyOnce(String capturedMessages, String message) {
        assertTrue(capturedMessages.contains(message));

        assertEquals(-1, capturedMessages.indexOf(message, capturedMessages.indexOf(message) + 1));
    }

    /** */
    private IgniteEx startGridWithLogCapture() throws Exception {
        IgniteEx ignite = startGrid(0);

        this.capture = new GridStringLogger(false, this.log);

        GridTestUtils.setFieldValue(ignite.context().query(), GridProcessorAdapter.class,"log", capture);

        return ignite;
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        stopAllGrids();
    }

    /** */
    private static class IdKey {
        /** */
        @QuerySqlField
        private final int id;

        /** */
        public IdKey(int id) {
            this.id = id;
        }
    }

    /** */
    private static class Payload {
        /** */
        @QuerySqlField
        private final String str;

        /** */
        public Payload(String str) {
            this.str = str;
        }
    }
}


text:
{% extends 'base.html' %}
{% load i18n %}
{% block content %}

{% trans "Something went wrong" %}

{% blocktrans %}Something went wrong on our side. If this problem persist, please report it on the mailing list.{% endblocktrans %}

{% endblock %}


text:
EXTRA_FLAGS="-c dbg --test_timeout=300,450,1200,3600"
github/grpc/tools/internal_ci/linux/grpc_bazel_on_foundry_base.sh "${EXTRA_FLAGS}"


text:
module UnitTests(
  allUnitTests
  ) where

import Test.HUnit

import Data.List(foldl', sort, sortOn)
import qualified Data.Map as Map

import Translate(translateStringToSyntaxGraph)
import TranslateCore(SyntaxGraph(..), SgBind(..))
import Types(Embedder(..), Labeled(..), SgNamedNode, Edge(..), SyntaxNode(..),
             NodeName(..), NameAndPort(..), Named(..), mkEmbedder)
import Util(fromMaybeError)

-- Unit Test Helpers --

assertAllEqual :: (Eq a, Show a) => [a] -> Test
assertAllEqual items = case items of
  [] -> TestCase $ assertFailure "assertAllEqual: argument is empty list"
  (first : rest) -> TestList $ fmap (first ~=?) rest

-- TODO Remove the Lambda node's node list.
assertEqualSyntaxGraphs :: [String] -> Test
assertEqualSyntaxGraphs ls = assertAllEqual $ fmap (renameGraph . translateStringToSyntaxGraph) ls

-- BEGIN renameGraph --
type NameMap = [(NodeName, NodeName)]

-- TODO Revisit this function
renameNode
  :: NameMap -> Int -> SgNamedNode -> (SgNamedNode, NameMap, Int)
renameNode nameMap counter (Named nodeName syntaxNode)
  = (fmap mkEmbedder newNamedNode, nameMap3, newCounter) where
  newNodeName = NodeName counter
  nameMap2 = (nodeName, newNodeName) : nameMap
  (newSyntaxNode, nameMap3, newCounter) = renameSyntaxNode nameMap2 (emNode syntaxNode) (counter + 1)
  newNamedNode = Named newNodeName newSyntaxNode

maybeRenameNodeFolder ::
  ([Labeled (Maybe SgNamedNode)], NameMap, Int)
  -> Maybe SgNamedNode
  -> ([Labeled (Maybe SgNamedNode)], NameMap, Int)
maybeRenameNodeFolder (renamedNodes, nameMap, counter) mNode = case mNode of
  Nothing -> (pure Nothing : renamedNodes, nameMap, counter)
  Just node -> (pure (Just newNamedNode) : renamedNodes, newNameMap, newCounter)
    where
      (newNamedNode, newNameMap, newCounter) = renameNode nameMap counter node

renameSyntaxNode :: NameMap -> SyntaxNode -> Int  -> (SyntaxNode, NameMap, Int)
renameSyntaxNode nameMap node counter = case node of
  -- TODO Keep the Nothing subNodes
  PatternApplyNode s subNodes
    -> (PatternApplyNode s (reverse renamedSubNodes)
       , newNameMap
       , counter2)
    where
      (renamedSubNodes, newNameMap, counter2)
        = foldl'
          maybeRenameNodeFolder
          ([], nameMap, counter)
          (fmap laValue subNodes)
  _ -> (node, nameMap, counter)

renameNodeFolder :: ([SgNamedNode], NameMap, Int) -> SgNamedNode -> ([SgNamedNode], NameMap, Int)
renameNodeFolder state@(renamedNodes, nameMap, counter) node@(Named nodeName _) = case lookup nodeName nameMap of
  Nothing -> (newNamedNode:renamedNodes, newNameMap, newCounter) where
    (newNamedNode, newNameMap, newCounter) = renameNode nameMap counter node
  Just _ -> error $ "renameNode: node already in name map. State = " ++ show state ++ " Node = " ++ show node

renameNamePort :: NameMap -> NameAndPort -> NameAndPort
renameNamePort nameMap nameAndPort@(NameAndPort name port) = NameAndPort newName port where
  newName = fromMaybeError errorStr $ lookup name nameMap
  errorStr = "renameNamePort: name not found. name = " ++ show name ++ "\nNameAndPort = " ++ show nameAndPort ++ "\nNameMap = " ++ show nameMap

renameEdge :: NameMap -> Edge -> Edge
renameEdge nameMap (Edge options (np1, np2)) =
  Edge options (renameNamePort nameMap np1, renameNamePort nameMap np2)

renameSource :: NameMap -> SgBind -> SgBind
renameSource nameMap (SgBind str ref) = SgBind str newRef where
  newRef = case ref of
    Left _ -> ref
    Right namePort@(NameAndPort _ _) -> Right $ renameNamePort nameMap namePort

renameEmbed :: NameMap -> (NodeName, NodeName) -> (NodeName, NodeName)
renameEmbed nameMap (leftName, rightName) = (newLeftName, newRightName) where
  newLeftName = fromMaybeError "renameEmbed: leftName not found" (lookup leftName nameMap)
  newRightName = fromMaybeError "renameEmbed: RightName not found" (lookup rightName nameMap)

-- TODO May want to remove names for sub-nodes
removeNames :: SgNamedNode -> SyntaxNode
removeNames (Named _ (Embedder _ syntaxNode)) = syntaxNode

-- TODO Rename sinks
-- TODO Add unit tests for renameGraph
renameGraph :: SyntaxGraph -> SyntaxGraph
renameGraph (SyntaxGraph nodes edges sinks sources embedMap) =
  SyntaxGraph renamedNodes renamedEdges sinks renamedSources renamedEmbedMap
  where
    (renamedNodes, nameMap, _) = foldl' renameNodeFolder ([], [], 0) $ sortOn removeNames nodes
    renamedEdges = sort $ fmap (renameEdge nameMap) edges
    renamedSources = sort $ fmap (renameSource nameMap) sources
    renamedEmbedMap
      = Map.fromList $ sort $ renameEmbed nameMap <$> Map.toList embedMap

-- END renameGraph

-- END Unit Test Helpers --
-- Translate unit tests

applyTests :: Test
applyTests = TestList [
  TestLabel "dollarTests1" $ assertEqualSyntaxGraphs [
      "y = f x",
      "y = f $ x"
      ]
  ,
  TestLabel "dollarTests2" $ assertEqualSyntaxGraphs [
      "y = f (g x)",
      "y = f $ (g x)",
      "y = f $ g  $ x",
      "y = f (g  $ x)"
      ]
  ,
  TestLabel "dollarTests3" $ assertEqualSyntaxGraphs [
      "y = f 1 (g 2)",
      "y = f 1 $ g 2"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = f 3 4",
      "y = (f 3) 4"
      ]
  ]

composeApplyTests :: Test
composeApplyTests = TestList [
  TestLabel "composeApplyTests1" $ assertEqualSyntaxGraphs [
      "y = f (g x)",
      "y = (f . g) x",
      "y = f . g $ x"
      ]
  ,
  TestLabel "composeApplyTests2" $ assertEqualSyntaxGraphs [
      "y = f3 (f2 (f1 x))",
      "y = f3 . f2 . f1 $ x",
      "y = (f3 . f2 . f1) x"
      ]
  ]

infixTests :: Test
infixTests = TestList [
  TestLabel "infixTests1" $ assertEqualSyntaxGraphs [
      "y = (+) 1 2",
      "y = ((+) 1) 2",
      "y = 1 + 2",
      "y = (1 +) 2"
      ]
  ,
  TestLabel "infixTests2" $ assertEqualSyntaxGraphs [
      "y = f (1 +) 2",
      "y = f ((+) 1) 2"
      ]
  ]

letTests :: Test
letTests = TestList [
  TestLabel "letTests1" $ assertEqualSyntaxGraphs [
      "y = f 1",
      "y = let x = 1 in f x",
      "y = let {b = a; a = 1} in f b"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = 2",
      "y = let z = 2 in z",
      "y = let {z = 2; z2 = z} in z2"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = f y",
      "y = let x = f x in x"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = f 7 5",
      "y = let {a = 7; b = f a 5} in b"
     ]
  ,
  assertEqualSyntaxGraphs [
      "y x = x",
      "y x = let z = x in z"
      ]
  ,
  assertEqualSyntaxGraphs [
      "fibs = let {y = cons 0 (cons 1 (zipWith (+) y (tail y)))} in y",
      "fibs = cons 0 (cons 1 (zipWith (+) fibs (tail fibs)))"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y x = y x",
      "y = let {z = (\\x -> y x)} in z",
      "y = let {z x = y x} in z "
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = f 3 y",
      "y = x where x = f 3 y",
      "y = let x = f 3 y in x"
      ]
  ,
  -- TODO Fix this test. It fails due to the names in the lambda region (which
  -- are not renamed
  -- assertEqualSyntaxGraphs [
  --     "y x1 = f x1",
  --     "y x1 = let {x2 = x1; x3 = x2; x4 = f x3} in x4"
  --     ]
  -- ,
  -- TODO Fix this test. The second line has two apply icons instead of one.
  -- See VisualTranslateTests/letTests
  -- assertEqualSyntaxGraphs [
  --     "y x1 = (f x1) x1",
  --     "y x1 = let x2 = f x1 in x2 x1"
  --    ]

  assertEqualSyntaxGraphs [
      "y x = 3",
      "y x = let x = 3 in x"
      ]

  -- TODO Fix test. Second line should use compose apply.
  -- See VisualTranslateTests/letTests
  -- assertEqualSyntaxGraphs [
  --     "y = g $ f y",
  --     "y = let {a = f b; b = g a} in b"
  --     ]
  ]

negateTests :: Test
negateTests = TestList [
  assertEqualSyntaxGraphs [
      "y = negate 1",
      "y = -1"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = negate ((/) 1 2)",
      "y = -1/2"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = negate x",
      "y = -x"
      ]
  ]

enumTests :: Test
enumTests = TestList [
  assertEqualSyntaxGraphs [
      "y = enumFrom 1",
      "y = [1..]"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = enumFromThen 1 2",
      "y = [1,2..]"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = enumFromTo 0 10",
      "y = [0..10]"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = enumFromThenTo 0 1 10",
      "y = [0,1..10]"
      ]
  ]

patternTests :: Test
patternTests = TestList [
  assertEqualSyntaxGraphs [
      "y (F x) = x",
      "y = (\\(F x) -> x)"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = let {F x y = 3} in x y",
      "y = let {g = 3; F x y = g} in x y"
      ]
  ]

lambdaTests :: Test
lambdaTests = TestList [
  assertEqualSyntaxGraphs [
      "y x = (\\z -> x)",
      "y = (\\x -> (\\z -> x))"
      ]
  ,
  -- TODO These tests fail since the lambda node has a " tempvar" param name.
  -- assertEqualSyntaxGraphs [
  --     "y x = case x of {0 -> 1; 3 -> 5}",
  --     "{y 0 = 1; y 3 = 5}"
  --     ]
  -- ,
  -- assertEqualSyntaxGraphs [
  --     "y p = case p of {F x -> x; G x -> x}",
  --     "{y (F x) = x; y (G x) = x}"
  --     ]
  -- ,
  -- assertEqualSyntaxGraphs [
  --     -- TODO Since there are no patterns for z, this should just be "case p of"
  --     "y p z = case (p, z) of {((F x), z') -> x z'; ((G x), z') -> z' x}",
  --     "{y (F x) z = x z; y (G x) z = z x}"
  --     ]
  -- ,
  assertEqualSyntaxGraphs [
      "y x = f x y",
      "y x = z where z = f x y"
      ]
  ]

fmapTests :: Test
fmapTests = TestList [
  assertEqualSyntaxGraphs [
      "y = fmap f x",
      "y = f <$> x"
      ]
  ,
  assertEqualSyntaxGraphs [
      "y = f1 (fmap f2 (f3 x))",
      "y = f1 $ f2 <$> f3 x"
      ]
  ]

-- Yes, the commas get their own line
translateUnitTests :: Test
translateUnitTests = TestList [
  TestLabel "fmapTest" fmapTests
  ,
  TestLabel "applyTests" applyTests
  ,
  TestLabel "composeApplyTests" composeApplyTests
  ,
  TestLabel "infixTests" infixTests
  , TestLabel "letTests" letTests
  , TestLabel "negateTests" negateTests
  , TestLabel "enumTests" enumTests
  , TestLabel "patternTests" patternTests
  , TestLabel "lambdaTests" lambdaTests
  ]

allUnitTests :: Test
allUnitTests = TestList[
  TestLabel "translateTests" translateUnitTests
  ]


text:
package net.dv8tion.jda.api.interactions.commands.localization;

import net.dv8tion.jda.api.interactions.DiscordLocale;
import net.dv8tion.jda.internal.utils.Checks;

import javax.annotation.Nonnull;
import java.util.*;

/**
 * A default implementation for {@link LocalizationFunction}
 *

 * This implementation supports Java's {@link ResourceBundle} to be used as a localization source
 *
 *

 * You can look at a complete localization example here
 */
public class ResourceBundleLocalizationFunction implements LocalizationFunction
{
    private final Set<Bundle> bundles;

    private ResourceBundleLocalizationFunction(Set<Bundle> bundles)
    {
        this.bundles = bundles;
    }

    @Nonnull
    @Override
    public Map<DiscordLocale, String> apply(@Nonnull String localizationKey)
    {
        final Map<DiscordLocale, String> map = new HashMap<>();
        for (Bundle bundle : bundles)
        {
            final ResourceBundle resourceBundle = bundle.resourceBundle;
            if (resourceBundle.containsKey(localizationKey))
                map.put(bundle.targetLocale, resourceBundle.getString(localizationKey));
        }

        return map;
    }

    /**
     * Creates an empty {@link ResourceBundleLocalizationFunction} builder and adds the provided bundle and locale.
     *
This is the same as using {@code ResourceBundleLocalizationFunction.empty().addBundle(resourceBundle, locale)}
     *
     *
Example usage:
     *
This creates a LocalizationFunction from a French ResourceBundle (MyCommands_fr.properties)
     *
     *

     *     final LocalizationFunction localizationFunction = ResourceBundleLocalizationFunction
     *                 .fromBundle(ResourceBundle.getBundle("MyCommands", Locale.FRENCH), DiscordLocale.FRENCH)
     *                 .build();
     *

     *
     * @param  resourceBundle
     *         The resource bundle to get the localized strings from
     *
     * @param  locale
     *         The locale of the resources
     *
     * @throws IllegalArgumentException
     *

     *
If the resource bundle is null

     *
If the locale is null

     *
If the locale is {@link DiscordLocale#UNKNOWN}

     *

     *
     * @return The new builder
     */
    @Nonnull
    public static Builder fromBundle(@Nonnull ResourceBundle resourceBundle, @Nonnull DiscordLocale locale)
    {
        return new Builder()
                .addBundle(resourceBundle, locale);
    }

    /**
     * Creates a {@link ResourceBundleLocalizationFunction} builder with the provided bundles.
     *
This will insert the resource bundles with the specified name, with each specified locale.
     *
This is the same as using {@code ResourceBundleLocalizationFunction.empty().addBundles(baseName, locales)}
     *
     *
Example usage:
     *
This creates a LocalizationFunction from 2 resource bundles, one in Spanish (MyCommands_es_ES.properties) and one in French (MyCommands_fr.properties)
     *
     *

     *     final LocalizationFunction localizationFunction = ResourceBundleLocalizationFunction
     *                         .fromBundles("MyCommands", DiscordLocale.SPANISH, DiscordLocale.FRENCH)
     *                         .build();
     *

     *
     * @param  baseName
     *         The base name of the resource bundle, for example, the base name of {@code "MyBundle_fr_FR.properties"} would be {@code "MyBundle"}
     *
     * @param  locales
     *         The locales to get from the resource bundle
     *
     * @throws IllegalArgumentException
     *

     *
If the base name is null

     *
If the locales or one of the locale is null

     *
If one of the locale is {@link DiscordLocale#UNKNOWN}

     *

     *
     * @return The new builder
     */
    @Nonnull
    public static Builder fromBundles(@Nonnull String baseName, @Nonnull DiscordLocale... locales)
    {
        return new Builder().addBundles(baseName, locales);
    }

    /**
     * Creates an empty {@link ResourceBundleLocalizationFunction} builder.
     *
     * @return The empty builder
     */
    @Nonnull
    public static Builder empty()
    {
        return new Builder();
    }

    /**
     * Builder for {@link ResourceBundleLocalizationFunction}
     *
Use the factory methods in {@link ResourceBundleLocalizationFunction} to create instances of this builder
     *
     * @see ResourceBundleLocalizationFunction#fromBundle(ResourceBundle, DiscordLocale)
     * @see ResourceBundleLocalizationFunction#fromBundles(String, DiscordLocale...)
     */
    public static class Builder
    {
        private final Set<Bundle> bundles = new HashSet<>();

        protected Builder() {}

        /**
         * Adds a resource bundle to this builder
         *
         *
You can see {@link #fromBundle(ResourceBundle, DiscordLocale)} for an example
         *
         * @param  resourceBundle
         *         The {@link ResourceBundle} to get the localized strings from
         *
         * @param  locale
         *         The {@link DiscordLocale} of the resources
         *
         * @throws IllegalArgumentException
         *

         *
If the resource bundle is null

         *
If the locale is null

         *
If the locale is {@link DiscordLocale#UNKNOWN}

         *

         *
         * @return This builder for chaining convenience
         *
         * @see #fromBundle(ResourceBundle, DiscordLocale)
         */
        @Nonnull
        public Builder addBundle(@Nonnull ResourceBundle resourceBundle, @Nonnull DiscordLocale locale)
        {
            Checks.notNull(resourceBundle, "Resource bundle");
            Checks.notNull(locale, "Locale");
            Checks.check(locale != DiscordLocale.UNKNOWN,"Cannot use UNKNOWN DiscordLocale");

            bundles.add(new Bundle(locale, resourceBundle));
            return this;
        }

        /**
         * Adds a resource bundle to this builder
         *
This will insert the resource bundles with the specified name, with each specified locale.
         *
         *
You can see {@link #fromBundles(String, DiscordLocale...)} for an example
         *
         * @param  baseName
         *         The base name of the resource bundle, for example, the base name of {@code "MyBundle_fr_FR.properties"} would be {@code "MyBundle"}
         *
         * @param  locales
         *         The locales to get from the resource bundle
         *
         * @throws IllegalArgumentException
         *

         *
If the base name is null

         *
If the locales or one of the locale is null

         *
If one of the locale is {@link DiscordLocale#UNKNOWN}

         *

         *
         * @return This builder for chaining convenience
         * @see #fromBundles(String, DiscordLocale...)
         */
        @Nonnull
        public Builder addBundles(@Nonnull String baseName, @Nonnull DiscordLocale... locales)
        {
            Checks.notNull(baseName, "Base name");
            Checks.noneNull(locales, "Locale");

            for (DiscordLocale locale : locales)
            {
                Checks.check(locale != DiscordLocale.UNKNOWN,"Cannot use UNKNOWN DiscordLocale");

                final ResourceBundle resourceBundle = ResourceBundle.getBundle(baseName, Locale.forLanguageTag(locale.getLocale()));
                bundles.add(new Bundle(locale, resourceBundle));
            }
            return this;
        }

        /**
         * Builds the resource bundle localization function.
         *
         * @return The new {@link ResourceBundleLocalizationFunction}
         */
        @Nonnull
        public ResourceBundleLocalizationFunction build()
        {
            return new ResourceBundleLocalizationFunction(bundles);
        }
    }

    private static final class Bundle
    {
        private final DiscordLocale targetLocale;
        private final ResourceBundle resourceBundle;

        public Bundle(DiscordLocale targetLocale, ResourceBundle resourceBundle)
        {
            this.targetLocale = targetLocale;
            this.resourceBundle = resourceBundle;
        }

        @Override
        public boolean equals(Object o)
        {
            if (this == o) return true;
            if (!(o instanceof Bundle)) return false;

            Bundle bundle = (Bundle) o;

            if (!targetLocale.equals(bundle.targetLocale)) return false;
            return resourceBundle.equals(bundle.resourceBundle);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(targetLocale, resourceBundle);
        }
    }
}


text:
<?php

/* loginBundle:Default:testForm.html.twig */
class __TwigTemplate_3aab42e8a58ebbd18bfa626a18dbefb3c0c2c680258aeb0dd5c05b005a83f333 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        echo "
Connecté

";
    }

    public function getTemplateName()
    {
        return "loginBundle:Default:testForm.html.twig";
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }
}


text: ../src/hdata ni ./locs.tbl ./edges_ni.tbl


text:
var _ = require("lodash");

var package = require("./package.json");
var run = require("./lib/run");

var program = require("commander").command(package.name);
var args = process.argv.slice(2);

var localDir = "/tmp/" + package.name;

//==============================================================================

program
  .version(package.version, "-v, --version")
  .option("--connect <connect>", "Db connection string")
  .option("--to <to>", "Destination file")
  .option("--from <from>", "Source table, subquery or sql file")
  .option("--where <where>", "Query criteria")
  .option("--local-dir <local_dir>", "Local directory where remote files are synced, default=" + localDir, localDir)
  .option("--access-key <access_key>", "AWS access key")
  .option("--secret-key <secret_key>", "AWS secret key")
  .option("-f, --force [true|false]", "Non-interactive, default=false", function(v) {return v !== "false"}, false)
  .option("-d, --debug [true|false]", "Show debug messages, default=false", function(v) {return v !== "false"}, false)
  .parse(process.argv);

//-- show help for empty arguments...
!args.length && program.help();

//-- run the program...
run(program.opts());

//==============================================================================


text:
import {Component, Input} from "@angular/core";
@Component({
    selector: 'widget-one',
    styles: [`
:host {
    font-family: "Times New Roman";
    display: block;
    border: 2px solid green;
}
h4 {color: dodgerblue}
`],
    template: `
Widget One

{{messageTwo}}

`
})

export class WidgetOneComponent{
    @Input() messageTwo: any;
}


text:
package org.apache.flink.streaming.runtime.translators;

import org.apache.flink.annotation.Internal;
import org.apache.flink.streaming.api.graph.TransformationTranslator;
import org.apache.flink.streaming.api.transformations.BroadcastStateTransformation;

import java.util.Collection;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * A {@link TransformationTranslator} for the {@link BroadcastStateTransformation}.
 *
 * @param <IN1> The type of the elements in the non-broadcasted input of the {@link BroadcastStateTransformation}.
 * @param <IN2> The type of the elements in the broadcasted input of the {@link BroadcastStateTransformation}.
 * @param <OUT> The type of the elements that result from the {@link BroadcastStateTransformation}.
 */
@Internal
public class BroadcastStateTransformationTranslator<IN1, IN2, OUT>
		extends AbstractTwoInputTransformationTranslator<IN1, IN2, OUT, BroadcastStateTransformation<IN1, IN2, OUT>> {

	@Override
	protected Collection<Integer> translateForBatchInternal(
			final BroadcastStateTransformation<IN1, IN2, OUT> transformation,
			final Context context) {
		throw new UnsupportedOperationException("The Broadcast State Pattern is not support in BATCH execution mode.");
	}

	@Override
	protected Collection<Integer> translateForStreamingInternal(
			final BroadcastStateTransformation<IN1, IN2, OUT> transformation,
			final Context context) {
		checkNotNull(transformation);
		checkNotNull(context);

		return translateInternal(
				transformation,
				transformation.getNonBroadcastStream(),
				transformation.getBroadcastStream(),
				transformation.getOperatorFactory(),
				transformation.getStateKeyType(),
				transformation.getKeySelector(),
				null,
				context);
	}
}


text:
<!doctype html>

<title>CodeMirror: Solr mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">

<link rel="stylesheet" href="../../lib/codemirror.css">

CodeMirror

Home

Manual

Code

Language modes

Solr

Solr mode

    <textarea id="code" name="code">author:Camus

title:"The Rebel" and author:Camus

philosophy:Existentialism -author:Kierkegaard

hardToSpell:Dostoevsky~

published:[194* TO 1960] and author:(Sartre or "Simone de Beauvoir")</textarea>

MIME types defined: text/x-solr.


text:
temp-repo
=========

Temporary for showing off this form.


text:
package org.ray.api.test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.ray.api.Ray;
import org.ray.api.RayActor;
import org.ray.api.RayObject;
import org.ray.api.TestUtils;
import org.ray.api.WaitResult;
import org.ray.api.annotation.RayRemote;
import org.ray.api.options.ActorCreationOptions;
import org.ray.api.options.CallOptions;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Resources Management Test.
 */
public class ResourcesManagementTest extends BaseTest {

  @BeforeClass
  public void setUp() {
    System.setProperty("ray.resources", "CPU:4,RES-A:4");
  }

  @AfterClass
  public void tearDown() {
    System.clearProperty("ray.resources");
  }

  @RayRemote
  public static Integer echo(Integer number) {
    return number;
  }

  @RayRemote
  public static class Echo {

    public Integer echo(Integer number) {
      return number;
    }
  }

  @Test
  public void testMethods() {
    TestUtils.skipTestUnderSingleProcess();
    CallOptions callOptions1 =
        new CallOptions.Builder().setResources(ImmutableMap.of("CPU", 4.0)).createCallOptions();

    // This is a case that can satisfy required resources.
    // The static resources for test are "CPU:4,RES-A:4".
    RayObject<Integer> result1 = Ray.call(ResourcesManagementTest::echo, 100, callOptions1);
    Assert.assertEquals(100, (int) result1.get());

    CallOptions callOptions2 =
        new CallOptions.Builder().setResources(ImmutableMap.of("CPU", 4.0)).createCallOptions();

    // This is a case that can't satisfy required resources.
    // The static resources for test are "CPU:4,RES-A:4".
    final RayObject<Integer> result2 = Ray.call(ResourcesManagementTest::echo, 200, callOptions2);
    WaitResult<Integer> waitResult = Ray.wait(ImmutableList.of(result2), 1, 1000);

    Assert.assertEquals(1, waitResult.getReady().size());
    Assert.assertEquals(0, waitResult.getUnready().size());

    try {
      CallOptions callOptions3 =
          new CallOptions.Builder().setResources(ImmutableMap.of("CPU", 0.0)).createCallOptions();
      Assert.fail();
    } catch (RuntimeException e) {
      // We should receive a RuntimeException indicates that we should not
      // pass a zero capacity resource.
    }
  }

  @Test
  public void testActors() {
    TestUtils.skipTestUnderSingleProcess();

    ActorCreationOptions actorCreationOptions1 = new ActorCreationOptions.Builder()
        .setResources(ImmutableMap.of("CPU", 2.0)).createActorCreationOptions();
    // This is a case that can satisfy required resources.
    // The static resources for test are "CPU:4,RES-A:4".
    RayActor<Echo> echo1 = Ray.createActor(Echo::new, actorCreationOptions1);
    final RayObject<Integer> result1 = Ray.call(Echo::echo, echo1, 100);
    Assert.assertEquals(100, (int) result1.get());

    // This is a case that can't satisfy required resources.
    // The static resources for test are "CPU:4,RES-A:4".
    ActorCreationOptions actorCreationOptions2 = new ActorCreationOptions.Builder()
        .setResources(ImmutableMap.of("CPU", 8.0)).createActorCreationOptions();

    RayActor<ResourcesManagementTest.Echo> echo2 =
        Ray.createActor(Echo::new, actorCreationOptions2);
    final RayObject<Integer> result2 = Ray.call(Echo::echo, echo2, 100);
    WaitResult<Integer> waitResult = Ray.wait(ImmutableList.of(result2), 1, 1000);

    Assert.assertEquals(0, waitResult.getReady().size());
    Assert.assertEquals(1, waitResult.getUnready().size());
  }

}


text:
'''

    Copyright 2013 Joe Harris

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

'''

'''

    Classes used to format requests properly. Properly formatted requests then
    use a transport to connect to the API and send the response on to a parser.

'''

from urlparse import urlunsplit

from twisted.internet import defer
from twisted.python.failure import Failure

from txcloudflare.transport import HttpStreamReceiver
from txcloudflare.parse import Response
from txcloudflare.errors import RequestValidationException, TransportException

class Request(object):
    '''

        The request base class.

    '''

    def go(self, *a, **k):
        raise TransportException('go() must be overridden')

class HttpRequest(Request):
    '''

        An HTTP request providing some simple validation for requests as well as
        generating the required paramters for the transport.

    '''

    ACTION = ''
    METHOD = ''
    REQUIRED_PARAMS = ()
    OPTIONAL_PARAMS = ()
    PARAM_MAP = {}

    def __init__(self, request_name, transport):
        self.request_name = request_name
        self.transport = transport
        self.params = {}
        self.inverse_map = {}
        self.d = None
        for param_name,api_name in self.PARAM_MAP.items():
            self.inverse_map[api_name] = param_name

    def get_method(self):
        if self.METHOD not in self.transport.METHODS:
            raise RequestValidationException('invalid HTTP method specified: {0}'.format(self.METHOD))
        return self.METHOD

    def get_request_url(self):
        return urlunsplit((
            self.transport.TRANSPORT_SCHEME,
            self.transport.TRANSPORT_NETLOC,
            self.transport.TRANSPORT_URI,
            '',
            ''
        ))

    def get_post_data(self):
        return self.params

    def go(self):
        self.params['a'] = self.ACTION
        for k,v in self.transport.get_auth_params().items():
            self.params[k] = v
        self.d = defer.Deferred()
        method = self.get_method()
        url = self.get_request_url()
        post_data = self.get_post_data()
        self.transport.do_request(method=method, url=url, post_data=post_data).addBoth(self._got_reply)
        return self.d

    def _got_reply(self, r):
        # this means we got a twisted.web._newclient.Response object or a
        # twisted.python.failure.Failure object. Response() is the start of an
        # HTTP stream, Failure() means there was a transport error connecting
        # to the API (DNS resolution error, socket connection error, etc.)
        if isinstance(r, Failure):
            self.d.errback(TransportException(r))
        else:
            response = Response()
            response.request = self
            response.raw_headers = list(r.headers.getAllRawHeaders())
            r.deliverBody(HttpStreamReceiver(self, response, self.d))

    def validate(self):
        for p in self.REQUIRED_PARAMS:
            z = self.inverse_map.get(p, p)
            if p not in self.params:
                raise RequestValidationException('request "{0}" requires parameter: {1})'.format(self.request_name, z))
                return False
        for k,v in self.params.items():
            if k in self.REQUIRED_PARAMS:
                f = self.REQUIRED_PARAMS[k]
            else:
                f = self.OPTIONAL_PARAMS[k]
            try:
                self.params[k] = f(v)
            except:
                raise RequestValidationException('param "{0}" is required to be of type: {1})'.format(k, f))
                return False
        return True

    def pre_process(self, params):
        # pre-process the request parameters, overriden in child requests
        return params

    def post_process(self, data):
        # post process the returned JSON, now in a dict, overriden in child requests
        return data

    def __call__(self, *a, **k):
        for param_key,param_val in k.items():
            api_key = self.PARAM_MAP.get(param_key, None)
            if api_key in self.REQUIRED_PARAMS or api_key in self.OPTIONAL_PARAMS:
                self.params[api_key] = param_val
            elif param_key in self.REQUIRED_PARAMS or param_key in self.OPTIONAL_PARAMS:
                self.params[param_key] = param_val
        self.validate()
        self.params = self.pre_process(self.params)
        return self.go()

'''

    EOF

'''


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

    <title>Initialize (Groovy Documentation)</title>
    <meta name="date" content="2014-05-09">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="../../groovy.ico" type="image/x-icon" rel="shortcut icon">
    <link href="../../groovy.ico" type="image/x-icon" rel="icon">
    <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

                    Overview

                    Package
                      Class

                    Deprecated
                    Index
                    Help

            Groovy Documentation

            FRAMES
             NO FRAMES

                All Classes

            SUMMARY: NESTED | FIELD | CONSTR | METHOD

            DETAIL: FIELD | CONSTR | METHOD

        griffon-app.lifecycle

    [Groovy] Class Initialize

java.lang.Object
  griffon-app.lifecycle.Initialize

class Initialize

            Constructor Summary

            Initialize()

            Method Summary

            Methods inherited from class java.lang.Object

        java.lang.Object#wait(long, int), java.lang.Object#wait(long), java.lang.Object#wait(),
            java.lang.Object#equals(java.lang.Object), java.lang.Object#toString(), java.lang.Object#hashCode(),
            java.lang.Object#getClass(), java.lang.Object#notify(), java.lang.Object#notifyAll()

            Constructor Detail

    Initialize

Initialize()

Groovy Documentation


text:
local s = tls.createConnection()
s:on("connection", function(sck, c)
  sck:send("GET /repos/nodemcu/nodemcu-firmware/git/trees/master HTTP/1.0\r\nUser-agent: nodemcu/0.1\r\nHost: api.github.com\r\nConnection: close\r\nAccept: application/json\r\n\r\n")
end)

function startswith(String, Start)
  return string.sub(String, 1, string.len(Start)) == Start
end

local seenBlank = false
local partial
local wantval = { tree = 1, path = 1, url = 1 }
-- Make an sjson decoder that only keeps certain fields
local decoder = sjson.decoder({
  metatable =
  {
    __newindex = function(t, k, v)
      if wantval[k] or type(k) == "number" then
        rawset(t, k, v)
      end
    end
  }
})
local function handledata(s)
  decoder:write(s)
end

-- The receive callback is somewhat gnarly as it has to deal with find the end of the header
-- and having the newline sequence split across packets
s:on("receive", function(sck, c)
  if partial then
    c = partial .. c
    partial = nil
  end
  if seenBlank then
    handledata(c)
    return
  end
  while c do
    if startswith(c, "\r\n") then
      seenBlank = true
      c = c:sub(3)
      handledata(c)
      return
    end
    local s, e = c:find("\r\n")
    if s then
      -- Throw away line
      c = c:sub(e + 1)
    else
      partial = c
      c = nil
    end
  end
end)

local function getresult()
  local result = decoder:result()
  -- This gets the resulting decoded object with only the required fields
  print(result['tree'][4]['path'], "is at",
    result['tree'][4]['url'])
end

s:on("disconnection", getresult)
s:on("reconnection", getresult)

-- Make it all happen!
s:connect(443, "api.github.com")


text:
<!DOCTYPE html>

    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
  Class: DropboxApi::Results::DeleteBatchResultEntry

    — Documentation by YARD 0.9.19

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" charset="utf-8" />

    Index (D) »
    DropboxApi » Results
     »
    DeleteBatchResultEntry

        <svg width="24" height="24">
          <rect x="0" y="4" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="12" width="24" height="4" rx="1" ry="1"></rect>
          <rect x="0" y="20" width="24" height="4" rx="1" ry="1"></rect>
        </svg>

Class: DropboxApi::Results::DeleteBatchResultEntry

Inherits:

      Base

Object

Base

DropboxApi::Results::DeleteBatchResultEntry

        show all

Defined in:

lib/dropbox_api/results/delete_batch_result_entry.rb

      Class Method Summary
      collapse

      .new(result_data)  ⇒ Object

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from DropboxApi::Results::Base

Class Method Details

    .new(result_data)  ⇒ <tt>Object</tt>

3
4
5
6
7
8
9
10
11
12
13

# File 'lib/dropbox_api/results/delete_batch_result_entry.rb', line 3

def self.new(result_data)
  case result_data['.tag']
  when 'success'
    DropboxApi::Metadata::Resource.new result_data['metadata']
  when 'failure'
    DropboxApi::Errors::DeleteError
      .build('Delete operation failed', result_data['failure'])
  else
    raise NotImplementedError, "Unknown result type: #{result_data['.tag']}"
  end
end

  Generated on Fri May 31 17:53:36 2019 by
  yard
  0.9.19 (ruby-2.6.2).


text:
describe '测试加载十阅的源' do

  before do
    @list_url         = 'https://coding.net/u/shiweifu/p/OneReadRouter/git/raw/master/ten_read_list'

    @hacker_news      = 'https://news.ycombinator.com/'
    @hacker_news_selector = '.title>a'

    @jianshu_url      = 'http://www.jianshu.com/trending/now'
    @jianshu_selector = 'h4>a'
    @jianshu_base_url = 'http://www.jianshu.com'
  end

  it 'load tenread list' do
    @body_hash = []

    Http::get_json(@list_url, {}) do | result |
      @body_hash = result
    end

    wait 1 do
      @body_hash.class.should.equal Array
      (@body_hash.empty?).should.not == true
    end

  end

  it 'parse html' do
    @result = []

    Http::get_string(@jianshu_url, {}) do | html |
      document = HTMLDocument.documentWithString html
      list = document.nodesMatchingSelector(@jianshu_selector)
      @result = list.map { | r |
        {name: r.textContent, link: @jianshu_base_url + r.attributes['href']}
      }
    end

    wait 5 do
      @result.class.should.equal Array
      (@result.empty?).should.not == true
      p @result.to_s
    end
  end

end


text:
package com.rodrigodev.xgen4j.model.common.template.model;

import com.rodrigodev.xgen4j.model.common.clazz.ClassDefinition;
import com.rodrigodev.xgen4j.service.time.TimeService;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.experimental.Accessors;

import javax.inject.Inject;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

/**
 * Created by Rodrigo Quesada on 20/06/15.
 */
@Getter
public class ClassTemplateModel {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);

    public static class InjectedFields {

        @Inject TimeService timeService;

        @Inject
        public InjectedFields() {
        }
    }

    @NonNull private InjectedFields inj;
    @NonNull final private String name;
    @NonNull final private String packagePath;
    final private TypeTemplateModel parent;
    private String currentDate;

    private ClassTemplateModel(
            @NonNull InjectedFields injectedFields,
            @NonNull String name,
            @NonNull String packagePath,
            ClassDefinition parentClassDefinition
    ) {
        this.inj = injectedFields;
        this.name = name;
        this.packagePath = packagePath;
        this.parent = parentClassDefinition != null
                ? new TypeTemplateModel(parentClassDefinition.name(), parentClassDefinition.fullyQualifiedName())
                : null;
        this.currentDate = DATE_TIME_FORMATTER.format(inj.timeService.now());
    }

    protected ClassTemplateModel(@NonNull ClassTemplateModelBuilder builder) {
        this(builder.injectedFields, builder.name, builder.packagePath, builder.parent);
    }

    @Setter
    @Accessors(fluent = true)
    public static abstract class ClassTemplateModelBuilder<M extends ClassTemplateModel, B extends ClassTemplateModelBuilder<M, B>> {

        private InjectedFields injectedFields;
        private String name;
        private String packagePath;
        private ClassDefinition parent;

        public abstract M build();
    }
}


text:
Ext.define('Siesta.Harness.Browser.UI.TestGridContextMenu', {
    extend : 'Ext.menu.Menu',
    xtype  : 'testgridcontextmenu',

    items : [
        {
            itemId : 'uncheckOthers',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('uncheckOthersText')
        },
        {
            itemId : 'uncheckAll',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('uncheckAllText')
        },
        {
            itemId : 'checkAll',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('checkAllText')
        },
        {
            itemId : 'runThis',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('runThisText')
        },
        { xtype   : 'menuseparator' },
        {
            itemId : 'expandAll',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('expandAll')
        },
        {
            itemId : 'collapseAll',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('collapseAll')
        },
        { xtype   : 'menuseparator' },
        {
            itemId : 'filterToCurrentGroup',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('filterToCurrentGroup')
        },
        {
            itemId : 'filterToFailed',
            text   : Siesta.Resource('Siesta.Harness.Browser.UI.Viewport').get('filterToFailed')
        }
    ]
})


text:
+++
Title = "Chamada de Trabalhos (CFP)"
Type = "event"
Description = "Propose a talk for devopsdays Florianópolis 2020"
+++
  {{< cfp_dates >}}

**Link para submissões:** Em breve!

## Tipos de apresentações

Há dois tipos de apresentações no devopsdays:

1. Palestras de **50 minutos** apresentadas durante a conferência.
2. Palestras de **25 minutos** apresentadas durante a conferência.

## Critérios de escolha

A escolha das palestras é parte arte e parte ciência; aqui estão alguns fatores que consideramos quando ter o melhor programa para nossa audiência local:

- _grande apelo_: Como a sua apresentação se mostra para pessoas com diferentes experiências e conhecimentos? Apresentações muito técnicas precisam de mais níveis para fornecer valor para todos, os quais podem não ter o conhecimento específico na ferramenta.
- _novos palestrantes locais_: Você é o único que pode contar sua história. Nós estamos muito interessados nos desafios e experiência de sucessos local. Nós estamos felizes para ajudar/mentorar os novos palestrantes que nos procurarem.
- _vozes sub-representadas_: Nos gostaríamos de ouvir todas as vozes, incluso aquelas que são menos frequentes em eventos similares. Se você está num campo que não é considerado como um de tecnologia, você está em uma organização grande e tradicional, ou você é a única pessoa em sua organização com seus antecedentes, estamos interessados em sua experiência única.
- _não enviar palestras por terceiros_: Este é um evento orientado pela comunidade e palestrantes precisam estar diretamente engajados com os organizadores e atendentes. Se uma empresa de relações públicas ou o departamento está propondo uma palestra, você já deve saber como um palestrante estará distante do processo.
- _produtos e serviços_: Valorizamos muito nossos palestrantes e apoiadores, não iremos aceitar uma palestra que tenda a ser uma apresentação do seu produto.

## Mais informações

Se você faz parte de grupos pouco representados no universo de TI e gostaria de apresentar algo, mas não se sente seguro, [contate](/events/2020-florianopolis/contact/) diretamente nossos organizadores para que possamos fornecer subsídios como mentoria, por exemplo, para que faça uma grande palestra com total segurança.


text:
Version History and Release Notes
=================================

.. toctree::
   :maxdepth: 2
   :glob:

   introduction-version-history
   upgrading-from-9-0-to-10-0-versions
   feature-versions-10-x
   lts-versions-10-0
   development-release-series-91
   stable-release-series-90


text:
pytermarkcli.py - Simple tool to add watermarks to images

# cropper
cropper.py - Simple tool to crop images so you can get the right aspect ratio for wallpapers, etc :)


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\models\user\Charge */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'uid')->textInput() ?>

    <?= $form->field($model, 'amount')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'date_str')->textInput() ?>

    <?= $form->field($model, 'date_int')->textInput() ?>

    <?= $form->field($model, 'status')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32U5xx_HAL_CRYP_EX_H
#define STM32U5xx_HAL_CRYP_EX_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32u5xx_hal_def.h"

/** @addtogroup STM32U5xx_HAL_Driver
  * @{
  */

#if defined(AES)

/** @defgroup CRYPEx CRYPEx
  * @brief CRYP Extension HAL module driver.
  * @{
  */

/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup CRYPEx_Exported_Functions CRYPEx Exported Functions
  * @{
  */

/** @addtogroup CRYPEx_Exported_Functions_Group1 Extended AES processing functions
  * @{
  */
HAL_StatusTypeDef HAL_CRYPEx_AESGCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *pAuthTag, uint32_t Timeout);
HAL_StatusTypeDef HAL_CRYPEx_AESCCM_GenerateAuthTAG(CRYP_HandleTypeDef *hcryp, uint32_t *pAuthTag, uint32_t Timeout);
/**
  * @}
  */

/** @addtogroup CRYPEx_Exported_Functions_Group2 Wrap and Unwrap key functions
  * @{
  */
HAL_StatusTypeDef HAL_CRYPEx_UnwrapKey(CRYP_HandleTypeDef *hcryp, uint32_t *pInput, uint32_t Timeout);
HAL_StatusTypeDef HAL_CRYPEx_WrapKey(CRYP_HandleTypeDef *hcryp, uint32_t *pInput, uint32_t *pOutput, uint32_t Timeout);
/**
  * @}
  */

/** @addtogroup CRYPEx_Exported_Functions_Group3 Encrypt/Decrypt Shared key functions
  * @{
  */
HAL_StatusTypeDef HAL_CRYPEx_EncryptSharedKey(CRYP_HandleTypeDef *hcryp, uint32_t *pKey, uint32_t *pOutput, uint32_t ID,
                                              uint32_t Timeout);
HAL_StatusTypeDef HAL_CRYPEx_DecryptSharedKey(CRYP_HandleTypeDef *hcryp, uint32_t *pKey, uint32_t ID, uint32_t Timeout);
/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */
#endif /* AES */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* STM32U5xx_HAL_CRYP_EX_H */


text:
from twisted.application import service, internet
from twisted.internet import reactor
from twisted.spread import pb
import copy2_classes # needed to get ReceiverPond registered with Jelly

class Receiver(pb.Root):
    def remote_takePond(self, pond):
        print " got pond:", pond
        print " count %d" % pond.count()
        return "safe and sound" # positive acknowledgement
    def remote_shutdown(self):
        reactor.stop()

application = service.Application("copy_receiver")
internet.TCPServer(8800, pb.PBServerFactory(Receiver())).setServiceParent(
    service.IServiceCollection(application))


text:
<resources>
    <string name="app_name">MagicLocationLib</string>
</resources>


text:
cask 'scribus-dev' do
  version '1.5.4'
  sha256 '6f31b0b9bf27c952d820188343e2be73ab990be772e34551b030d9c04fa4f5b8'

  # sourceforge.net/scribus was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/scribus/scribus-devel/#{version}/scribus-#{version}.dmg"
  appcast 'https://sourceforge.net/projects/scribus/rss?path=/scribus-devel'
  name 'Scribus'
  homepage 'https://www.scribus.net/'

  conflicts_with cask: 'scribus'

  app 'Scribus.app'

  zap trash: [
               '~/Library/Application Support/Scribus',
               '~/Library/Preferences/Scribus',
               '~/Library/Saved Application State/net.scribus.savedState',
             ]
end


text:
<?php

class UM_Admin_Columns {

	function __construct() {

		$this->slug = 'ultimatemember';

		add_filter('manage_edit-um_form_columns', array(&$this, 'manage_edit_um_form_columns') );
		add_action('manage_um_form_posts_custom_column', array(&$this, 'manage_um_form_posts_custom_column'), 10, 3);

		add_filter('manage_edit-um_directory_columns', array(&$this, 'manage_edit_um_directory_columns') );
		add_action('manage_um_directory_posts_custom_column', array(&$this, 'manage_um_directory_posts_custom_column'), 10, 3);

		add_filter('post_row_actions', array(&$this, 'post_row_actions'), 99, 2);

	}

	/***
	***	@custom row actions
	***/
	function post_row_actions($actions, $post){
		//check for your post type
		if ($post->post_type =="um_form"){
			$actions['um_duplicate'] = 'duplicate_uri( $post->ID ) . '">' . __('Duplicate','ultimate-member') . '';
		}
		return $actions;
	}

	/***
	***	@duplicate a form
	***/
	function duplicate_uri( $id ) {
		$url = add_query_arg('um_adm_action', 'duplicate_form', admin_url('edit.php?post_type=um_form') );
		$url = add_query_arg('post_id', $id, $url);
		return $url;
	}

	/***
	***	@Custom columns for Form
	***/
	function manage_edit_um_form_columns($columns) {

		$admin = new UM_Admin_Metabox();

		$new_columns['cb'] = '<input type="checkbox" />';
		$new_columns['id'] = __('ID') . $admin->_tooltip( 'Unique ID for each form' );
		$new_columns['title'] = __('Title');
		$new_columns['mode'] = __('Type') . $admin->_tooltip( 'This is the type of the form' );
		$new_columns['shortcode'] = __('Shortcode') . $admin->_tooltip( 'Use this shortcode to display the form' );
		$new_columns['date'] = __('Date');

		return $new_columns;

	}

	/***
	***	@Custom columns for Directory
	***/
	function manage_edit_um_directory_columns($columns) {

		$admin = new UM_Admin_Metabox();

		$new_columns['cb'] = '<input type="checkbox" />';
		$new_columns['id'] = __('ID') . $admin->_tooltip( 'Unique ID for each form' );
		$new_columns['title'] = __('Title');
		$new_columns['shortcode'] = __('Shortcode') . $admin->_tooltip( 'Use this shortcode to display the member directory' );
		$new_columns['date'] = __('Date');

		return $new_columns;

	}

	/***
	***	@Display cusom columns for Form
	***/
	function manage_um_form_posts_custom_column($column_name, $id) {
		global $wpdb, $ultimatemember;

		switch ($column_name) {

			case 'id':
				echo ''.$id.'';
				break;

			case 'shortcode':
				echo $ultimatemember->shortcodes->get_shortcode( $id );
				break;

			case 'mode':
				$mode = $ultimatemember->query->get_attr('mode', $id);
				echo ''. $ultimatemember->form->display_form_type($mode, $id) . '';
				break;

		}

	}

	/***
	***	@Display cusom columns for Directory
	***/
	function manage_um_directory_posts_custom_column($column_name, $id) {
		global $wpdb, $ultimatemember;

		switch ($column_name) {

			case 'id':
				echo ''.$id.'';
				break;

			case 'shortcode':
				echo $ultimatemember->shortcodes->get_shortcode( $id );
				break;

		}

	}

}


text:
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.test import TestCase
from django.urls import reverse

from wagtail.core.models import Collection, Page, get_root_collection_id
from wagtail.documents.models import Document
from wagtail.tests.utils import WagtailTestUtils

class TestChooser(TestCase, WagtailTestUtils):
    """Test chooser panel rendered by `wagtaildocs:chooser` view"""

    _NO_DOCS_TEXT = "You haven't uploaded any documents."
    _NO_COLLECTION_DOCS_TEXT = "You haven't uploaded any documents in this collection."
    _UPLOAD_ONE_TEXT = "upload one now"  # text from the link that opens upload form

    def setUp(self):
        self.root_page = Page.objects.get(id=2)

    def login_as_superuser(self):
        self.login()

    def login_as_editor(self):
        user_model = get_user_model()

        # Create group with access to admin
        editors_group = Group.objects.create(name='The Editors')
        access_admin_perm = Permission.objects.get(
            content_type__app_label='wagtailadmin',
            codename='access_admin'
        )
        editors_group.permissions.add(access_admin_perm)

        # Create a non-superuser editor
        user_data = dict()
        user_data[user_model.USERNAME_FIELD] = 'editor@email.com'
        user_data['password'] = 'password'
        for field in user_model.REQUIRED_FIELDS:
            user_data[field] = field

        user = user_model.objects.create_user(**user_data)
        user.groups.add(editors_group)

        # Log in as a non-superuser editor
        self.login(user)

    def get(self, params=None):
        return self.client.get(reverse('wagtaildocs:chooser'), params or {})

    def test_chooser_docs_exist(self):
        # given an editor with access to admin panel
        self.login_as_editor()
        # and a document in the database
        doc_title = 'document.pdf'
        Document.objects.create(title=doc_title)

        # when opening chooser
        response = self.get()

        # then chooser template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/chooser.html')
        # and document is displayed
        self.assertContains(response, doc_title)
        # and no hints are displayed
        self.assertNotContains(response, self._NO_DOCS_TEXT)
        self.assertNotContains(response, self._NO_COLLECTION_DOCS_TEXT)
        self.assertNotContains(response, self._UPLOAD_ONE_TEXT)

    def test_chooser_no_docs_upload_allowed(self):
        # given a superuser and no documents in the database
        self.login_as_superuser()

        # when opening chooser
        response = self.get()

        # then chooser template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/chooser.html')
        # and hint "You haven't uploaded any documents. Why not upload one now?" is displayed
        self.assertContains(response, self._NO_DOCS_TEXT)
        self.assertContains(response, self._UPLOAD_ONE_TEXT)

    def test_chooser_no_docs_upload_forbidden(self):
        # given an editor with access to admin panel
        # and no documents in the database
        self.login_as_editor()

        # when opening chooser
        response = self.get()

        # then chooser template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/chooser.html')
        # and the following hint is displayed:
        # "You haven't uploaded any documents in this collection. Why not upload one now?"
        self.assertContains(response, self._NO_DOCS_TEXT)
        self.assertNotContains(response, self._UPLOAD_ONE_TEXT)

    def test_results_docs_exist(self):
        # given a superuser
        self.login_as_superuser()
        # and a document in the database
        doc_title = 'document.pdf'
        Document.objects.create(title=doc_title)

        # when searching for any documents at chooser panel
        response = self.get({'q': ''})

        # then results template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/results.html')
        # and document is displayed
        self.assertContains(response, doc_title)
        # and no hints are displayed
        self.assertNotContains(response, self._NO_DOCS_TEXT)
        self.assertNotContains(response, self._NO_COLLECTION_DOCS_TEXT)
        self.assertNotContains(response, self._UPLOAD_ONE_TEXT)

    def test_results_no_docs_upload_allowed(self):
        # given a superuser and no documents in the database
        self.login_as_superuser()

        # when searching for any documents at chooser panel
        response = self.get({'q': ''})

        # then results template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/results.html')
        # and hint "You haven't uploaded any documents. Why not upload one now?" is displayed
        self.assertContains(response, self._NO_DOCS_TEXT)
        self.assertContains(response, self._UPLOAD_ONE_TEXT)

    def test_results_no_docs_upload_forbidden(self):
        # given an editor with access to admin panel
        # and no documents in the database
        self.login_as_editor()

        # when searching for any documents at chooser panel
        response = self.get({'q': ''})

        # then results template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/results.html')
        # and hint "You haven't uploaded any documents." is displayed
        self.assertContains(response, self._NO_DOCS_TEXT)
        self.assertNotContains(response, self._UPLOAD_ONE_TEXT)

    def test_results_no_collection_docs_upload_allowed(self):
        # given a superuser
        self.login_as_superuser()
        # and a document in a collection
        root_id = get_root_collection_id()
        root = Collection.objects.get(id=root_id)
        doc_title = 'document.pdf'
        Document.objects.create(title=doc_title, collection=root)

        # when searching for documents in another collection at chooser panel
        non_root_id = root_id + 10**10
        response = self.get({'q': '', 'collection_id': non_root_id})

        # then results template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/results.html')
        # and the following hint is displayed:
        # "You haven't uploaded any documents in this collection. Why not upload one now?"
        self.assertContains(response, self._NO_COLLECTION_DOCS_TEXT)
        self.assertContains(response, self._UPLOAD_ONE_TEXT)

    def test_results_no_collection_docs_upload_forbidden(self):
        # given an editor with access to admin panel
        self.login_as_editor()
        # and a document in a collection
        root_id = get_root_collection_id()
        root = Collection.objects.get(id=root_id)
        Document.objects.create(collection=root)

        # when searching for documents in another collection at chooser panel
        non_root_id = root_id + 10**10
        response = self.get({'q': '', 'collection_id': non_root_id})

        # then results template is used
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtaildocs/chooser/results.html')
        # and hint "You haven't uploaded any documents in this collection." is displayed
        self.assertContains(response, self._NO_COLLECTION_DOCS_TEXT)
        self.assertNotContains(response, self._UPLOAD_ONE_TEXT)


text:
<?php

namespace Oro\Bundle\EmailBundle\Command\Manager;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;

use JMS\JobQueueBundle\Entity\Job;

use Oro\Bundle\BatchBundle\ORM\Query\BufferedQueryResultIterator;
use Oro\Bundle\EmailBundle\Command\AddAssociationCommand;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\Manager\EmailManager;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
use Oro\Bundle\EmailBundle\Entity\Manager\EmailActivityManager;
use Oro\Bundle\EmailBundle\Provider\EmailOwnersProvider;

class AssociationManager
{
    const EMAIL_BUFFER_SIZE = 100;

    /** @var DoctrineHelper */
    protected $doctrineHelper;

    /** @var EmailActivityManager */
    protected $emailActivityManager;

    /** @var EmailOwnersProvider */
    protected $emailOwnersProvider;

    /** @var EmailManager */
    protected $emailManager;

    public function __construct(
        DoctrineHelper $doctrineHelper,
        EmailActivityManager $emailActivityManager,
        EmailOwnersProvider $emailOwnersProvider,
        EmailManager $emailManager
    ) {
        $this->doctrineHelper = $doctrineHelper;
        $this->emailActivityManager = $emailActivityManager;
        $this->emailOwnersProvider = $emailOwnersProvider;
        $this->emailManager = $emailManager;
    }

    /**
     * Process of command oro:email:add-associations
     *
     * @param int[] $ids
     * @param string $targetClass
     * @param int $targetId
     *
     * @return int
     */
    public function processAddAssociation($ids, $targetClass, $targetId)
    {
        $target = $this->doctrineHelper->getEntityRepository($targetClass)->find($targetId);
        $countNewAssociations = 0;
        $emails =$this->emailManager->findEmailsByIds($ids);
        foreach ($emails as $email) {
            $result = $this->emailActivityManager->addAssociation($email, $target);

            if ($result) {
                $countNewAssociations++;
            }
        }

        $this->doctrineHelper->getEntityManager('Oro\Bundle\EmailBundle\Entity\Email')->flush();

        return $countNewAssociations;
    }

    /**
     * Process of command oro:email:update-email-owner-associations
     *
     * @param $ownerClassName
     * @param $ownerId
     *
     * @return int
     */
    public function processUpdateEmailOwner($ownerClassName, $ownerId)
    {
        $ownerQb = $this->createOwnerQb($ownerClassName, $ownerId);
        $owners = $this->getOwnerIterator($ownerQb);
        $dependenceJob = null;
        $countNewJob = 0;
        foreach ($owners as $owner) {
            $emailsQB = $this->emailOwnersProvider->getQBEmailsByOwnerEntity($owner);

            /** @var QueryBuilder $emailQB */
            foreach ($emailsQB as $emailQB) {
                $emailId = [];
                $emails = (new BufferedQueryResultIterator($emailQB))
                    ->setBufferSize(self::EMAIL_BUFFER_SIZE)
                    ->setPageCallback(function () use (
                        &$owner,
                        &$emailId,
                        &$dependenceJob,
                        &$ownerClassName,
                        &$countNewJob
                    ) {
                        $this->clear();
                        $job = $this->createJob($emailId, $ownerClassName, $owner->getId(), $dependenceJob);

                        $emailId = [];
                        $dependenceJob = $job;
                        $countNewJob++;
                    });

                foreach ($emails as $email) {
                    $emailId[] = $email->getId();
                }
            }
        }

        return $countNewJob;
    }

    /**
     * Clear UnitOfWork cache
     */
    protected function clear()
    {
        $clearClass = [
            'Oro\Bundle\EmailBundle\Entity\Email',
            'Oro\Bundle\EmailBundle\Entity\EmailBody',
            'Oro\Bundle\ActivityListBundle\Entity\ActivityList',
            'Oro\Bundle\EmailBundle\Entity\EmailThread'
        ];

        foreach ($clearClass as $item) {
            $this->getEmailEntityManager()->clear($item);
        }
    }

    /**
     * @param $emailId
     * @param $ownerClassName
     * @param $ownerId
     * @param $dependenceJob
     *
     * @return Job
     */
    protected function createJob($emailId, $ownerClassName, $ownerId, $dependenceJob)
    {
        foreach ($emailId as $id) {
            $arguments[] = '--id='.$id;
        }
        $arguments[] = '--targetClass=' . $ownerClassName;
        $arguments[] = '--targetId=' . $ownerId;

        $job = new Job(AddAssociationCommand::COMMAND_NAME, $arguments);
        if ($dependenceJob) {
            $job->addDependency($dependenceJob);
        }

        $jobEntityManager = $this->doctrineHelper->getEntityManager($job);
        $jobEntityManager->persist($job);
        $jobEntityManager->flush();

        return $job;
    }

    /**
     * @param string $class
     * @param array $ids
     *
     * @return QueryBuilder
     */
    protected function createOwnerQb($class, array $ids)
    {
        $qb = $this->doctrineHelper->getEntityRepositoryForClass($class)
            ->createQueryBuilder('o');

        return $qb
            ->andWhere($qb->expr()->in(
                sprintf('o.%s', $this->doctrineHelper->getSingleEntityIdentifierFieldName($class)),
                ':ids'
            ))
            ->setParameter('ids', $ids);
    }

    /**
     * @param QueryBuilder $ownerQb
     *
     * @return $this
     */
    protected function getOwnerIterator($ownerQb)
    {
        return (new BufferedQueryResultIterator($ownerQb))
            ->setBufferSize(1)
            ->setPageCallback(function () {
                $this->getEmailEntityManager()->flush();
                $this->getEmailEntityManager()->clear();
            });
    }

    /**
     * @return EntityManager
     */
    protected function getEmailEntityManager()
    {
        return $this->doctrineHelper->getEntityManagerForClass('OroEmailBundle:Email');
    }
}


text:
import {Hand} from "../Hand";
import {Card} from "../Card";
import {CardRankEvaluator} from "./CardRankEvaluator";
import {WinningHand} from "./WinningHand";
import {CardSuitEvaluator} from "./CardSuitEvaluator";
import {CardSorter} from "./CardSorter";
import {CardRankSequenceEvaluator} from "./CardRankSequenceEvaluator";
import {HandRanking, StandardHandRankings} from "./HandRanking";

export class Evaluator {

  constructor() {

  }

  evaluate(hand: Hand): WinningHand {
    let winningHand: WinningHand,
      boundaries = new CardSorter(),
      highestCard: Card,
      rank: CardRankEvaluator = new CardRankEvaluator();

    highestCard = boundaries.highestCard(hand.getCards());

    // One pair, two pair and three of a kind are the most likely outcomes.
    winningHand = rank.assess(hand);

    // Typescript cannot test an object to see if it is an instanceof an interface.
    if (typeof winningHand != 'object') {
      let sequence = new CardRankSequenceEvaluator(),
        suit: CardSuitEvaluator = new CardSuitEvaluator(),
        isSequence: boolean = sequence.isRankInSequence(hand);

      // Winning hand was not a rank-based win. Test suits.
      winningHand = suit.assess(hand);

      if (typeof winningHand != 'object') {
        // No winning hand, yet, test for a sequence.
        if (isSequence) {
          winningHand = new WinningHand(hand, HandRanking.createFromIndex(StandardHandRankings.Straight), Array<Array<Card>>(hand.getCards()));
        } else {
          winningHand = new WinningHand(hand, HandRanking.createFromIndex(StandardHandRankings.HighCard), Array<Array<Card>>([highestCard]));
        }
      }
    }

    return winningHand;
  }

}


text: require './rocks_ext.rb'


text:
import unittest

from kafka.tools.protocol.requests import ArgumentError
from kafka.tools.protocol.requests.api_versions_v0 import ApiVersionsV0Request

class ApiVersionsV0RequestTests(unittest.TestCase):
    def test_process_arguments(self):
        assert ApiVersionsV0Request.process_arguments([]) == {}

    def test_process_arguments_extra(self):
        self.assertRaises(ArgumentError, ApiVersionsV0Request.process_arguments, ['foo'])