text:
<?php
namespace Podlove\Settings\Expert\Tab;
use \Podlove\Settings\Settings;
use \Podlove\Settings\Expert\Tab;

class Website extends Tab {
	public function init() {

		// always flush rewrite rules here for custom_episode_slug setting
		if ($this->is_active()) {
			set_transient( 'podlove_needs_to_flush_rewrite_rules', true );
		}

		add_settings_section(
			/* $id 		 */ 'podlove_settings_general',
			/* $title 	 */ __( '', 'podlove-podcasting-plugin-for-wordpress' ),
			/* $callback */ function () { echo '
' . __( 'Website Settings', 'podlove-podcasting-plugin-for-wordpress' ) . '
'; },
			/* $page	 */ Settings::$pagehook
		);

		add_settings_section(
			/* $id 		 */ 'podlove_settings_files',
			/* $title 	 */ __( '', 'podlove-podcasting-plugin-for-wordpress' ),
			/* $callback */ function () { echo '
' . __( 'Files & Downloads', 'podlove-podcasting-plugin-for-wordpress' ) . '
'; },
			/* $page	 */ Settings::$pagehook
		);

		add_settings_section(
			/* $id 		 */ 'podlove_settings_feeds',
			/* $title 	 */ __( '', 'podlove-podcasting-plugin-for-wordpress' ),
			/* $callback */ function () { echo '
' . __( 'Feeds', 'podlove-podcasting-plugin-for-wordpress' ) . '
'; },
			/* $page	 */ Settings::$pagehook
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_merge_episodes',
			/* $title    */ sprintf(
				'%s',
				__( 'Combine blog & podcast', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {
				?>
				<input name="podlove_website[merge_episodes]" id="merge_episodes" type="checkbox" <?php checked( \Podlove\get_setting( 'website', 'merge_episodes' ), 'on' ) ?>>
				<?php
				echo __( 'Include episode posts on the front page and in the blog feed', 'podlove-podcasting-plugin-for-wordpress' );
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_general'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_hide_wp_feed_discovery',
			/* $title    */ sprintf(
				'%s',
				__( 'Hide blog feeds', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {
				?>
				<input name="podlove_website[hide_wp_feed_discovery]" id="hide_wp_feed_discovery" type="checkbox" <?php checked( \Podlove\get_setting( 'website', 'hide_wp_feed_discovery' ), 'on' ) ?>>
				<?php
				echo __( 'Hide default WordPress feeds for blog and comments (no auto-discovery).', 'podlove-podcasting-plugin-for-wordpress' );
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_general'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_custom_episode_slug',
			/* $title    */ sprintf(
				'%s',
				__( 'Permalink structure for episodes', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {

				$use_post_permastruct = \Podlove\get_setting( 'website', 'use_post_permastruct' );
				$custom_episode_slug  = \Podlove\get_setting( 'website', 'custom_episode_slug' );

				if ( $blog_prefix = \Podlove\get_blog_prefix() ) {
					$custom_episode_slug = preg_replace( '|^/?blog|', '', $custom_episode_slug );
				}

				\Podlove\load_template('expert_settings/website/custom_episode_slug', compact('use_post_permastruct', 'custom_episode_slug'));
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_general'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_episode_archive',
			/* $title    */ sprintf(
				'%s',
				__( 'Episode pages', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {

				$enable_episode_archive = \Podlove\get_setting( 'website', 'episode_archive' );
				$episode_archive_slug   = \Podlove\get_setting( 'website', 'episode_archive_slug' );

				if ( $blog_prefix = \Podlove\get_blog_prefix() ) {
					$episode_archive_slug = preg_replace( '|^/?blog|', '', $episode_archive_slug );
				}

				\Podlove\load_template('expert_settings/website/episode_archive', compact('enable_episode_archive', 'episode_archive_slug', 'blog_prefix'));
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_general'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_landing_page',
			/* $title    */ sprintf(
				'%s',
				__( 'Podcast landing page', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {

				$landing_page = \Podlove\get_setting( 'website', 'landing_page' );

				$landing_page_options = array(
					array( 'value' => 'homepage', 'text' => __('Front page', 'podlove-podcasting-plugin-for-wordpress') ),
					array( 'value' => 'archive',  'text' => __('Episode pages', 'podlove-podcasting-plugin-for-wordpress') ),
					array( 'text' => '––––––––––', 'disabled' => true ),
				);

				$pages_query = new \WP_Query( array(
					'post_type' => 'page',
					'nopaging'  => true
				) );

				if ( $pages_query->have_posts() ) {
					while ( $pages_query->have_posts() ) {
						$pages_query->the_post();
						$landing_page_options[] = array('value' => get_the_ID(), 'text' => get_the_title());
					}
				}

				wp_reset_postdata();

				\Podlove\load_template('expert_settings/website/landing_page', compact('landing_page', 'landing_page_options'));
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_general'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_url_template',
			/* $title    */ sprintf(
				'%s',
				__( 'Episode Asset URL Template.', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {
				?>
				<input name="podlove_website[url_template]" id="url_template" type="text" value="<?php echo \Podlove\get_setting( 'website', 'url_template' ) ?>" class="large-text podlove-check-input">

						<?php echo __( 'Is used to generate URLs. You probably don\'t want to change this.', 'podlove-podcasting-plugin-for-wordpress' ); ?>

				<?php
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_files'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_ssl_verify_peer',
			/* $title    */ sprintf(
				'%s',
				__( 'Check for Assets with SSL-peer-verification.', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {
				?>
				<input name="podlove_website[ssl_verify_peer]" id="ssl_verify_peer" type="checkbox" <?php checked( \Podlove\get_setting( 'website', 'ssl_verify_peer' ), 'on' ) ?>>
				<?php echo __('If you provide your assets via https with a self-signed or not verifiable SSL-certificate, podlove should display your assets as non exiting. You might solve this by deactivating the ssl peer verification for asset checking. (Detailed: This sets "CURLOPT_SSL_VERIFYPEER" to FALSE.)', 'podlove-podcasting-plugin-for-wordpress') ?>
				<?php
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_files'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_feeds_skip_redirect',
			/* $title    */ sprintf(
				'%s',
				__( 'Allow to skip feed redirects', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ function () {
				?>
				<input name="podlove_website[feeds_skip_redirect]" id="feeds_skip_redirect" type="checkbox" <?php checked( \Podlove\get_setting( 'website', 'feeds_skip_redirect' ), 'on' ) ?>>
				<?php echo __('If you need to debug you feeds while using a feed proxy, add ?redirect=no to the feed URL to skip the redirect.', 'podlove-podcasting-plugin-for-wordpress') ?>
				<?php
			},
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_feeds'
		);

		add_settings_field(
			/* $id       */ 'podlove_setting_feeds_force_protocol',
			/* $title    */ sprintf(
				'%s',
				__( 'Website Protocol', 'podlove-podcasting-plugin-for-wordpress' )
			),
			/* $callback */ [$this, 'feeds_force_protocol'],
			/* $page     */ Settings::$pagehook,
			/* $section  */ 'podlove_settings_feeds'
		);

		register_setting( Settings::$pagehook, 'podlove_website', function($options) {
			/**
			 * handle checkboxes
			 */
			$checkboxes = array(
				'merge_episodes',
				'hide_wp_feed_discovery',
				'use_post_permastruct',
				'episode_archive',
				'ssl_verify_peer',
				'feeds_skip_redirect'
			);
			foreach ( $checkboxes as $checkbox_key ) {
				if ( ! isset( $options[ $checkbox_key ] ) )
					$options[ $checkbox_key ] = 'off';
			}

			/**
			 * handle permastructs
			 */
			$prefix = $blog_prefix = '';
			$iis7_permalinks = iis7_supports_permalinks();

			if ( ! got_mod_rewrite() && ! $iis7_permalinks )
				$prefix = '/index.php';

			if ( is_multisite() && ! is_subdomain_install() && is_main_site() )
				$blog_prefix = '';

			// Episode permastruct
			if ( array_key_exists( 'custom_episode_slug', $options ) ) {
				$options['custom_episode_slug'] = preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $options['custom_episode_slug'] ) );

				if ( $prefix && $blog_prefix ) {
					$options['custom_episode_slug'] = $prefix . preg_replace( '#^/?index\.php#', '', $options['custom_episode_slug'] );
				} else {
					$options['custom_episode_slug'] = $blog_prefix . $options['custom_episode_slug'];
				}
			}

			// Archive slug
			if ( array_key_exists( 'episode_archive_slug', $options ) ) {
				$options['episode_archive_slug'] = preg_replace( '#/+#', '/', '/' . str_replace( '#', '', $options['episode_archive_slug'] ) );

				if ( $prefix && $blog_prefix ) {
					$options['episode_archive_slug'] = $prefix . preg_replace( '#^/?index\.php#', '', $options['episode_archive_slug'] );
				} else {
					$options['episode_archive_slug'] = $blog_prefix . $options['episode_archive_slug'];
				}
			}

			return $options;
		} );
	}

	public function feeds_force_protocol() {
		$this->feeds_force_protocol_setting();
		$this->feeds_force_protocol_issues();
	}

	private function feeds_force_protocol_setting()
	{
		$options = [
			'default'    => __('Hands Off (leave everything as configured by WordPress)', 'podlove-podcasting-plugin-for-wordpress'),
			'http'       => __('1 - Website is delivered via http (including podcast feeds)', 'podlove-podcasting-plugin-for-wordpress'),
			'https'      => __('2 - Website is delivered via https (including podcast feeds)', 'podlove-podcasting-plugin-for-wordpress'),
			'http_feeds' => __('3 - Website is delivered via https (excluding podcast feeds which will be delivered via http)', 'podlove-podcasting-plugin-for-wordpress')
		];

		\Podlove\load_template('expert_settings/website/feeds_force_protocol', compact('options'));
	}

	private function feeds_force_protocol_issues()
	{
		$force = \Podlove\get_setting('website', 'feeds_force_protocol');

		$home_url = parse_url(\get_option('home'));
		$site_url = parse_url(\get_option('siteurl'));

		$issues = [];

		if ($force == 'http') {
			// todo: explain where home/site url are set
			if ($home_url['scheme'] !== 'http') {
				$issues[] = sprintf(__('You claim your website is all http but your WordPress Address (home url) scheme is %s', 'podlove-podcasting-plugin-for-wordpress'), $home_url['scheme']);
			}
			if ($site_url['scheme'] !== 'http') {
				$issues[] = sprintf(__('You claim your website is all http but your Site Address (site url) scheme is %s', 'podlove-podcasting-plugin-for-wordpress'), $home_url['scheme']);
			}
		} elseif ($force == 'https' || $force == 'http_feeds') {
			// todo: explain where home/site url are set
			if ($home_url['scheme'] !== 'https') {
				$issues[] = sprintf(__('You claim your website is all https but your WordPress Address (home url) scheme is %s', 'podlove-podcasting-plugin-for-wordpress'), $home_url['scheme']);
			}
			if ($site_url['scheme'] !== 'https') {
				$issues[] = sprintf(__('You claim your website is all https but your Site Address (site url) scheme is %s', 'podlove-podcasting-plugin-for-wordpress'), $home_url['scheme']);
			}
		}

		\Podlove\load_template('expert_settings/website/feeds_force_protocol_issues', compact('issues'));
	}

}


text:
title: Hello, world!
template: index.jade
---

OHAI

redpajama_set_name: RedPajamaGithub


text:
package net.bolbat.utils.lang;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

/**
 * {@link ToStringUtils} test.
 *
 * @author Alexandr Bolbat
 */
public class ToStringUtilsTest {

	@Test
	public void complexArraysTest() {
		final Object[] nullArray = null;
		Assert.assertEquals("[]", ToStringUtils.toString(nullArray));
		Assert.assertEquals("[1]", ToStringUtils.toString(new Integer[] { 1 }));
		Assert.assertEquals("[1,2,3,4,5]", ToStringUtils.toString(new Integer[] { 1, 2, 3, 4, 5 }));
		Assert.assertEquals("[1,2,3,4,5,6,7,8,9,10,...]", ToStringUtils.toString(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }));
		Assert.assertEquals("[]", ToStringUtils.toString(nullArray, 0));
		Assert.assertEquals("[...]", ToStringUtils.toString(new Integer[] { 1, 2, 3, 4, 5 }, 0));
		Assert.assertEquals("[1,2]", ToStringUtils.toString(new Integer[] { 1, 2 }, 5));
		Assert.assertEquals("[1,2,3,4,5,...]", ToStringUtils.toString(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, 5));
	}

	@Test
	public void complexCollectionsTest() {
		final Collection<Object> nullCollection = null;
		Assert.assertEquals("[]", ToStringUtils.toString(nullCollection));
		Assert.assertEquals("[1]", ToStringUtils.toString(Arrays.asList(1)));
		Assert.assertEquals("[1,2,3,4,5]", ToStringUtils.toString(Arrays.asList(1, 2, 3, 4, 5)));
		Assert.assertEquals("[1,2,3,4,5,6,7,8,9,10,...]", ToStringUtils.toString(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)));
		Assert.assertEquals("[]", ToStringUtils.toString(nullCollection, 0));
		Assert.assertEquals("[...]", ToStringUtils.toString(Arrays.asList(1, 2, 3, 4, 5), 0));
		Assert.assertEquals("[1,2]", ToStringUtils.toString(Arrays.asList(1, 2), 5));
		Assert.assertEquals("[1,2,3,4,5,...]", ToStringUtils.toString(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), 5));
	}

	@Test
	public void complexMapsTest() {
		final Map<Object, Object> nullMap = null;
		Assert.assertEquals("[]", ToStringUtils.toString(nullMap));
		Assert.assertEquals("[]", ToStringUtils.toString(nullMap, 0));

		final Map<Object, Object> map = new HashMap<>();
		map.put("key1", "value1");
		Assert.assertEquals("[key1|value1]", ToStringUtils.toString(map));
		Assert.assertEquals("[...]", ToStringUtils.toString(map, 0));

		map.put("key2", "value2");
		map.put("key3", "value3");
		map.put("list1", Arrays.asList(1, 2, 3));
		Assert.assertTrue(ToStringUtils.toString(map).contains("key1|value1"));
		Assert.assertTrue(ToStringUtils.toString(map).contains("key2|value2"));
		Assert.assertTrue(ToStringUtils.toString(map).contains("key3|value3"));
		Assert.assertTrue(ToStringUtils.toString(map).contains("list1|[1,2,3]"));

		map.put("list2", Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12));
		Assert.assertTrue(ToStringUtils.toString(map).contains("list2|[1,2,3,4,5,6,7,8,9,10,...]"));
		Assert.assertFalse(ToStringUtils.toString(map, 12).contains("list2|[1,2,3,4,5,6,7,8,9,10,...]"));

		final Map<Object, Object> bigMap = new HashMap<>();
		for (int i = 0; i < 15; i++)
			bigMap.put("key" + i, "value" + i);

		Assert.assertTrue(ToStringUtils.toString(bigMap).contains("...]"));
		Assert.assertFalse(ToStringUtils.toString(bigMap, 15).contains("...]"));
	}

	@Test
	public void toTypeNameTest() {
		Assert.assertEquals("int", ToStringUtils.toTypeName(int.class));
		Assert.assertEquals("java.lang.String", ToStringUtils.toTypeName(String.class));

		// array types + multidimensional array types
		Assert.assertEquals("int[]", ToStringUtils.toTypeName(new int[0].getClass()));
		Assert.assertEquals("long[][]", ToStringUtils.toTypeName(new long[0][0].getClass()));
		Assert.assertEquals("double[][][]", ToStringUtils.toTypeName(new double[0][0][0].getClass()));
		Assert.assertEquals("java.lang.String[]", ToStringUtils.toTypeName(new String[0].getClass()));
		Assert.assertEquals("java.lang.Integer[][]", ToStringUtils.toTypeName(new Integer[0][0].getClass()));
		Assert.assertEquals("java.lang.Object[][][]", ToStringUtils.toTypeName(new Object[0][0][0].getClass()));
	}

	@Test
	public void toMethodNameTest() {
		int validatedMethods = 0;
		final Method[] methods = MethodTest.class.getMethods();
		for (final Method method : methods) {
			final String methodName = ToStringUtils.toMethodName(method);
			switch (method.getName()) {
				case "method1":
					Assert.assertEquals("method1()", methodName);
					validatedMethods++;
					break;
				case "method2":
					Assert.assertEquals("method2(java.lang.String,int,java.lang.Object[])", methodName);
					validatedMethods++;
					break;
				case "method3":
					Assert.assertEquals("method3(java.lang.String[],int[][],java.lang.Object[])", methodName);
					validatedMethods++;
					break;
				default:
					continue;
			}
		}
		Assert.assertEquals(3, validatedMethods);
	}

	public static class MethodTest {
		public void method1() {
		}

		public void method2(final String param1, final int param2, final Object... params) {
		}

		public void method3(final String[] param1, final int[][] param2, final Object... params) {
		}
	}

}


text:
namespace serial_port_compile {

struct write_some_handler
{
  write_some_handler() {}
  void operator()(const asio::error_code&, std::size_t) {}
#if defined(ASIO_HAS_MOVE)
  write_some_handler(write_some_handler&&) {}
private:
  write_some_handler(const write_some_handler&);
#endif // defined(ASIO_HAS_MOVE)
};

struct read_some_handler
{
  read_some_handler() {}
  void operator()(const asio::error_code&, std::size_t) {}
#if defined(ASIO_HAS_MOVE)
  read_some_handler(read_some_handler&&) {}
private:
  read_some_handler(const read_some_handler&);
#endif // defined(ASIO_HAS_MOVE)
};

void test()
{
#if defined(ASIO_HAS_SERIAL_PORT)
  using namespace asio;

  try
  {
    io_context ioc;
    char mutable_char_buffer[128] = "";
    const char const_char_buffer[128] = "";
    serial_port::baud_rate serial_port_option;
    archetypes::lazy_handler lazy;
    asio::error_code ec;

    // basic_serial_port constructors.

    serial_port port1(ioc);
    serial_port port2(ioc, "null");
    serial_port::native_handle_type native_port1 = port1.native_handle();
    serial_port port3(ioc, native_port1);

#if defined(ASIO_HAS_MOVE)
    serial_port port4(std::move(port3));
#endif // defined(ASIO_HAS_MOVE)

    // basic_serial_port operators.

#if defined(ASIO_HAS_MOVE)
    port1 = serial_port(ioc);
    port1 = std::move(port2);
#endif // defined(ASIO_HAS_MOVE)

    // basic_io_object functions.

    serial_port::executor_type ex = port1.get_executor();
    (void)ex;

#if !defined(ASIO_NO_DEPRECATED)
    io_context& ioc_ref = port1.get_io_context();
    (void)ioc_ref;

    io_context& ioc_ref2 = port1.get_io_service();
    (void)ioc_ref2;
#endif // !defined(ASIO_NO_DEPRECATED)

    // basic_serial_port functions.

    serial_port::lowest_layer_type& lowest_layer = port1.lowest_layer();
    (void)lowest_layer;

    const serial_port& port5 = port1;
    const serial_port::lowest_layer_type& lowest_layer2 = port5.lowest_layer();
    (void)lowest_layer2;

    port1.open("null");
    port1.open("null", ec);

    serial_port::native_handle_type native_port2 = port1.native_handle();
    port1.assign(native_port2);
    serial_port::native_handle_type native_port3 = port1.native_handle();
    port1.assign(native_port3, ec);

    bool is_open = port1.is_open();
    (void)is_open;

    port1.close();
    port1.close(ec);

    serial_port::native_handle_type native_port4 = port1.native_handle();
    (void)native_port4;

    port1.cancel();
    port1.cancel(ec);

    port1.set_option(serial_port_option);
    port1.set_option(serial_port_option, ec);

    port1.get_option(serial_port_option);
    port1.get_option(serial_port_option, ec);

    port1.send_break();
    port1.send_break(ec);

    port1.write_some(buffer(mutable_char_buffer));
    port1.write_some(buffer(const_char_buffer));
    port1.write_some(buffer(mutable_char_buffer), ec);
    port1.write_some(buffer(const_char_buffer), ec);

    port1.async_write_some(buffer(mutable_char_buffer), write_some_handler());
    port1.async_write_some(buffer(const_char_buffer), write_some_handler());
    int i1 = port1.async_write_some(buffer(mutable_char_buffer), lazy);
    (void)i1;
    int i2 = port1.async_write_some(buffer(const_char_buffer), lazy);
    (void)i2;

    port1.read_some(buffer(mutable_char_buffer));
    port1.read_some(buffer(mutable_char_buffer), ec);

    port1.async_read_some(buffer(mutable_char_buffer), read_some_handler());
    int i3 = port1.async_read_some(buffer(mutable_char_buffer), lazy);
    (void)i3;
  }
  catch (std::exception&)
  {
  }
#endif // defined(ASIO_HAS_SERIAL_PORT)
}

} // namespace serial_port_compile

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

ASIO_TEST_SUITE
(
  "serial_port",
  ASIO_TEST_CASE(serial_port_compile::test)
)


text:
using System;
using System.Collections.Generic;
using System.Text;

/// Author: Leopoldo Lee Agdeppa III

namespace NPanday.ProjectImporter.Parser.SlnParser
{
    public enum Semantics
    {
        PROJECT,
        END_PROJECT,
        PROJECT_SECTION,
        END_PROJECT_SECTION,
        GLOBAL,
        END_GLOBAL,
        GLOBAL_SECTION,
        END_GLOBAL_SECTION,

        QUOTED_STRING,
        EQUALS,
        OPEN_PARENTHESIS,
        CLOSE_PARENTHESIS,
        COMMA,
        STRING_VALUE,
        EOL

    }
}


text:
package org.mule.mvel2.integration;

/**
 * This interface allows an external property handler to resolve a property against the provided context.
 *
 * @see org.mule.mvel2.optimizers.impl.asm.ProducesBytecode
 */
public interface PropertyHandler {
  /**
   * Retrieves the value of the property.
   *
   * @param name            - the name of the property to be resolved.
   * @param contextObj      - the current context object.
   * @param variableFactory - the root variable factory provided by the runtime.
   * @return - the value of the property.
   */
  public Object getProperty(String name, Object contextObj, VariableResolverFactory variableFactory);

  /**
   * Sets the value of the property.
   *
   * @param name            - the name of the property to be resolved.
   * @param contextObj      - the current context object.
   * @param variableFactory - the root variable factory provided by the runtime.
   * @param value           - the value to be set to the resolved property
   * @return - the resultant value of the property (should normally be the same as the value passed)
   */
  public Object setProperty(String name, Object contextObj, VariableResolverFactory variableFactory, Object value);
}


text:
Vmdb::Gettext::Domains.add_domain(
  'ManageIQ_Providers_Ovirt',
  ManageIQ::Providers::Ovirt::Engine.root.join('locale').to_s,
  :po
)


text:
#ifndef KYTHE_CXX_INDEXER_PROTO_COMMENTS_H_
#define KYTHE_CXX_INDEXER_PROTO_COMMENTS_H_

#include <string>

namespace kythe {

// Strips protobuf comment markers and leading/trailing whitespace from each
// line of `source`, and returns the stripped result.
std::string StripCommentMarkers(const std::string& source);

}  // namespace kythe

#endif  // KYTHE_CXX_INDEXER_PROTO_COMMENTS_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

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

  <title>Module: ApplicationHelper</title>

  <link rel="stylesheet" href="./rdoc.css" type="text/css" media="screen" />

          Home
          Classes
          Methods

In Files

app/helpers/application_helper.rb

Files

README.rdoc

Class/Module Index

        <form action="#" method="get" accept-charset="utf-8" class="initially-hidden">
        <fieldset>
          <legend>Quicksearch</legend>
          <input type="text" name="quicksearch" value=""
            class="quicksearch-field" />
        </fieldset>
        </form>

ApplicationController

ApplicationHelper

BootstrapFlashHelper

Event

EventSerializer

EventsController

EventsHelper

Item

ItemSerializer

ItemsController

ItemsHelper

PeopleController

PeopleHelper

Person

PersonSerializer

Setting

SettingSerializer

SettingsController

SettingsHelper

User

No matching classes.

ApplicationHelper

[Validate]

Generated with the Darkfish
      Rdoc Generator 2.


text:
<!doctype html>

  <title>Error</title>
  <?php include 'stylesheets.php'; ?>
  <?php include 'scripts.php'; ?>

    <?php include 'header.php'; ?>

Runtime Error

<?php echo nl2br(htmlspecialchars($statusMessage)); ?>

    <?php include 'footer.php'; ?>


text:
package jcrib;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;

import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import jcrib.cards.Card;
import jcrib.cards.Face;
import jcrib.cards.Hand;
import jcrib.cards.Suit;

/**
 * Demo Cribbage application that uses the library.
 *
 * @author malensek
 */
public class Demo {

    private static Game game;
    private static BufferedReader commandLine;
    private static int stateToken = 0;

    public static void main(String[] args)
    throws Exception {

        /* Quiet the logger for the Demo */
        final Logger logger = Logger.getLogger("jcrib");
        logger.setLevel(Level.WARNING);

        /* Use fancy characters instead of just suit letters */
        Suit.enableFancyChars();

        InputStreamReader inputStream = new InputStreamReader(System.in);
        commandLine = new BufferedReader(inputStream);

        /* Get player details */
        String player1, player2;
        if (args.length >= 2) {
            player1 = args[0];
            player2 = args[1];
        } else {
            System.out.print("Player 1 Name: ");
            player1 = commandLine.readLine();
            System.out.print("Player 2 Name: ");
            player2 = commandLine.readLine();
        }
        System.out.println();
        System.out.println("Hello, " + player1 + " and " + player2 + "!");

        game = new Game(new Player(player1), new Player(player2));

        /* Determine who goes first */
        cutDeck();
        System.out.println(game.getDealer().getName() + " deals first!");

        while (true) {
            /* Have players place cards into the crib */
            for (Player player : game.getPlayers()) {
                crib(player, 2);
            }

            System.out.println("Beginning play.");
            Card starter = game.getStarterCard();
            System.out.println("Starter Card: " + starter);
            if (starter.getFace() == Face.Jack) {
                System.out.println("Starter is a Jack.  Dealer scores 2 for "
                        + "his heels!");
            }

            while (true) {
                Player currentPlayer = game.getCurrentPlayer();
                Card[] hand = currentPlayer.getHand().toCardArray();
                Arrays.sort(hand);
                System.out.println("Turn: " + currentPlayer.getName() + " ("
                        + currentPlayer.getPoints() + ")");
                printHand(hand);

                /* Find the largest card that can be played */
                int maxCard = game.getLargestPlayableCard();
                int maxLength = 0;
                for (Card card : hand) {
                    if (card.getValue() > maxCard) {
                        break;
                    }
                    maxLength++;
                }

                int index = printPrompt(currentPlayer, 0, maxLength);
                int handIndex = currentPlayer.getHand().getIndex(hand[index]);
                Result result = game.executeAction(
                        currentPlayer, GameState.Play, stateToken, handIndex);

                if (result.hasScore()) {
                    for (Score score : result.getScores()) {
                        System.out.println(score);
                    }
                }

                if (result.stateChanged()) {
                    break;
                }

                printPlay();
            }

            System.out.println("Finished pegging:");
            for (Player player : game.getPlayers()) {
                System.out.println(player.getName() + " " + player.getPoints());
            }

            List<Score> cribScore = game.getCribScore();
            Map<String, List<Score>> handScores = game.getHandScores();

            for (String playerName : handScores.keySet()) {
                System.out.println(playerName + "'s hand score:");
                for (Score score : handScores.get(playerName)) {
                    System.out.println(score);
                }
                if (playerName.equals(game.getDealer().getName())) {
                    System.out.println("Crib score:");
                    for (Score score : cribScore) {
                        System.out.println(score);
                    }
                }
            }

            game.finishRound();

            System.out.println("Current score:");
            for (Player player : game.getPlayers()) {
                System.out.println(player.getName() + " " + player.getPoints());
            }
        }
    }

    public static void printPlay() {
        String play = " ";
        for (Card card : game.getCardsInPlay()) {
            play += card + " ";
        }
        System.out.println("[" + play + "]" + " - "
                + game.getCurrentPlayTotal());
    }

    public static int printPrompt(Player player) {
        return printPrompt(player, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public static int printPrompt(Player player, int min, int max) {
        System.out.print(player.getName() + "> ");
        String line = "";
        int num = 0;
        try {
            line = commandLine.readLine();
            num = Integer.parseInt(line);

            if (num < min || num >= max) {
                /* Try again */
                return printPrompt(player, min, max);
            }
        } catch (Exception e) {
            if (line.equals("quit")) {
                System.out.println("Goodbye!");
                System.exit(0);
            }
            System.out.println("Invalid number!");
            return printPrompt(player, min, max);
        }
        return num;
    }

    public static void printHand(Card[] hand) {
        System.out.print(" ");
        for (Card card : hand) {
            /* Add extra padding for 10s to keep spacing equal */
            if (card.getOrdinal() != 10) {
                System.out.print(" ");
            }

            System.out.print(card + " ");
        }
        System.out.println();

        for (int i = 0; i < hand.length; ++i) {
            System.out.print("  " + i + " ");
        }
        System.out.println();
    }

    public static void cutDeck() throws IllegalPlayException,
           InvalidStateException, InvalidStateTokenException {

        Result result = null;

        System.out.println("Please cut the deck (enter a number 0-51):");

        for (Player player : game.getPlayers()) {
            int card = printPrompt(player, 0, 52);
            result = game.executeAction(player,
                    GameState.Cut, stateToken, card);
            System.out.println(player.getName()
                    + " drew " + player.getCutCard());
        }

        if (!result.stateChanged()) {
            System.out.println("Tie!  Please cut the deck again.");
            cutDeck();
        }
    }

    public static void crib(Player player, int numCards)
    throws IllegalPlayException, InvalidStateException,
                      InvalidStateTokenException {
        System.out.println("Move " + numCards + " cards to the crib.");
        for (int i = 0; i < numCards; ++i) {
            System.out.println(player.getName() + "'s cards:");
            Hand hand = player.getHand();
            Card[] cards = hand.toCardArray();
            Arrays.sort(cards);
            printHand(cards);
            int index = printPrompt(player, 0, hand.getCards().size());
            int handIndex = hand.getIndex(cards[index]);
            game.executeAction(player, GameState.Crib, stateToken, handIndex);
        }
    }
}


text:
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')
);

$service = new \yii\di\ServiceLocator();
$service->set("cache",'common\cache\Base64Cache');

$application = new yii\web\Application($config);
$application->set('locator',$service);
$application->run();


text:
FILE=data/js/shader/simple.js

node tools/js2embree.js "$FILE"  -p > ../embree/examples/renderer/device_singleray/materials/shadejs_material.h


text:
package org.apache.jackrabbit.vault.fs.impl.io;

import java.io.IOException;
import java.util.Optional;

import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.jackrabbit.vault.fs.io.DocViewAnalyzerListener;
import org.apache.jackrabbit.vault.fs.io.DocViewParser;
import org.apache.jackrabbit.vault.fs.io.DocViewParser.XmlParseException;
import org.apache.jackrabbit.vault.fs.io.DocViewParserHandler;
import org.apache.jackrabbit.vault.util.DocViewNode2;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

/**
 * Implements a docview analyzer that scans the XML for nodes.
 */
public class DocViewAnalyzer implements DocViewParserHandler {

    /**
     * the default logger
     */
    static final Logger log = LoggerFactory.getLogger(DocViewAnalyzer.class);

    /**
     * listener that receives node events
     */
    private final DocViewAnalyzerListener listener;

    /**
     * Analyzes the given source
     * @param listener listener that receives node events
     * @param session repository session for namespace mappings
     * @param rootPath path of the root node
     * @param source input source
     *
     * @throws IOException if an i/o error occurs
     */
    public static void analyze(DocViewAnalyzerListener listener,
                               Session session, String rootPath,
                               InputSource source)
            throws IOException {
        try {
            DocViewParser docViewParser = new DocViewParser(session);
            docViewParser.parse(rootPath, source, new DocViewAnalyzer(listener));
        } catch (XmlParseException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * Creates a new analyzer that will receive SAX events and generates the list
     * of included created nodes.
     *
     * @param listener listener that receives node events
     */
    private DocViewAnalyzer(DocViewAnalyzerListener listener) {
        this.listener = listener;
    }

    @Override
    public void startDocViewNode(@NotNull String nodePath, @NotNull DocViewNode2 docViewNode,@NotNull Optional<DocViewNode2> parentDocViewNode, int line, int column)
        throws IOException, RepositoryException {
        if (docViewNode.getProperties().isEmpty()) {
            listener.onNode(nodePath, true, "");
        } else {
            listener.onNode(nodePath, false, docViewNode.getPrimaryType().orElse(""));
        }
    }

    @Override
    public void endDocViewNode(@NotNull String nodePath, @NotNull DocViewNode2 docViewNode, @NotNull Optional<DocViewNode2> parentDocViewNode, int line, int column)
            throws IOException, RepositoryException {
    }

}


text:
set -xe

sudo chown airflow:airflow airflow

# That file exists in Composer < 1.19.2 and is responsible for linking name
# `python` to python3 exec, in Composer >= 1.19.2 name `python` is already
# linked to python3 and file no longer exist.
if [ -f /var/local/setup_python_command.sh ]; then
    /var/local/setup_python_command.sh
fi

pip3 install --upgrade -r composer_requirements.txt

airflow db init

# Allow non-authenticated access to UI for Airflow 2.*
if ! grep -Fxq "AUTH_ROLE_PUBLIC = 'Admin'" /home/airflow/airflow/webserver_config.py; then
  echo "AUTH_ROLE_PUBLIC = 'Admin'" >> /home/airflow/airflow/webserver_config.py
fi

airflow scheduler &
exec airflow webserver


text:
package org.guvnor.ala.docker.config;

import org.guvnor.ala.config.ProvisioningConfig;
import org.guvnor.ala.config.RuntimeConfig;

/*
 * Represents the Docker Runtime Configuration specific settings to run to Docker Images
 * @see ProvisioningConfig
 * @see RuntimeConfig
 */
public interface DockerRuntimeConfig extends ProvisioningConfig,
                                             RuntimeConfig {

    /*
     * Get the Docker Image Name to be executed
     * @return String with the Docker Image name.
     */
    String getImage();

    /*
     * Get the Docker Image Exposed port number
     * @return String with the Docker Image exposed port number.
     */
    String getPort();

    /*
     * Get the Docker Pull value, to decide if the Image needs to be pulled from a public
     *  registry or not.
     * @return String with the Docker Pull value.
     */
    boolean isPull();
}


text:
import * as React from 'react';
import { ShengnianShorthandContent } from '../..';

export interface BreadcrumbSectionProps {
  [key: string]: any;

  /** An element type to render as (string or function). */
  as?: any;

  /** Style as the currently active section. */
  active?: boolean;

  /** Primary content. */
  children?: React.ReactNode;

  /** Additional classes. */
  className?: string;

  /** Shorthand for primary content. */
  content?: ShengnianShorthandContent;

  /** Render as an `a` tag instead of a `div` and adds the href attribute. */
  href?: string;

  /** Render as an `a` tag instead of a `div`. */
  link?: boolean;

  /**
   * Called on click. When passed, the component will render as an `a`
   * tag by default instead of a `div`.
   *
   * @param {SyntheticEvent} event - React's original SyntheticEvent.
   * @param {object} data - All props.
   */
  onClick?: (event: React.MouseEvent<HTMLAnchorElement>, data: BreadcrumbSectionProps) => void;
}

declare const BreadcrumbSection: React.ComponentClass<BreadcrumbSectionProps>;

export default BreadcrumbSection;


text:
namespace blink {

PerformanceObserver* PerformanceObserver::create(
    ExecutionContext* executionContext,
    PerformanceBase* performance,
    PerformanceObserverCallback* callback) {
  ASSERT(isMainThread());
  return new PerformanceObserver(executionContext, performance, callback);
}

PerformanceObserver::PerformanceObserver(ExecutionContext* executionContext,
                                         PerformanceBase* performance,
                                         PerformanceObserverCallback* callback)
    : m_executionContext(executionContext),
      m_callback(this, callback),
      m_performance(performance),
      m_filterOptions(PerformanceEntry::Invalid),
      m_isRegistered(false) {}

void PerformanceObserver::observe(const PerformanceObserverInit& observerInit,
                                  ExceptionState& exceptionState) {
  if (!m_performance) {
    exceptionState.throwTypeError(
        "Window may be destroyed? Performance target is invalid.");
    return;
  }

  PerformanceEntryTypeMask entryTypes = PerformanceEntry::Invalid;
  if (observerInit.hasEntryTypes() && observerInit.entryTypes().size()) {
    const Vector<String>& sequence = observerInit.entryTypes();
    for (const auto& entryTypeString : sequence)
      entryTypes |= PerformanceEntry::toEntryTypeEnum(entryTypeString);
  }
  if (entryTypes == PerformanceEntry::Invalid) {
    exceptionState.throwTypeError(
        "A Performance Observer MUST have at least one valid entryType in its "
        "entryTypes attribute.");
    return;
  }
  m_filterOptions = entryTypes;
  if (m_isRegistered)
    m_performance->updatePerformanceObserverFilterOptions();
  else
    m_performance->registerPerformanceObserver(*this);
  m_isRegistered = true;
}

void PerformanceObserver::disconnect() {
  if (m_performance) {
    m_performance->unregisterPerformanceObserver(*this);
  }
  m_performanceEntries.clear();
  m_isRegistered = false;
}

void PerformanceObserver::enqueuePerformanceEntry(PerformanceEntry& entry) {
  ASSERT(isMainThread());
  m_performanceEntries.push_back(&entry);
  if (m_performance)
    m_performance->activateObserver(*this);
}

bool PerformanceObserver::shouldBeSuspended() const {
  return m_executionContext->isContextSuspended();
}

void PerformanceObserver::deliver() {
  ASSERT(!shouldBeSuspended());

  if (m_performanceEntries.isEmpty())
    return;

  PerformanceEntryVector performanceEntries;
  performanceEntries.swap(m_performanceEntries);
  PerformanceObserverEntryList* entryList =
      new PerformanceObserverEntryList(performanceEntries);
  m_callback->call(this, entryList, this);
}

DEFINE_TRACE(PerformanceObserver) {
  visitor->trace(m_executionContext);
  visitor->trace(m_callback);
  visitor->trace(m_performance);
  visitor->trace(m_performanceEntries);
}

DEFINE_TRACE_WRAPPERS(PerformanceObserver) {
  visitor->traceWrappers(m_callback);
}

}  // namespace blink


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `zero_memory` fn in crate `core`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, zero_memory">

    <title>core::ptr::zero_memory - Rust</title>

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

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

core::<wbr>ptr

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Function core::<wbr>ptr::<wbr>zero_memory<wbr><a class='stability Deprecated' title='use `write_bytes` instead'>Deprecated
            [-] [+]
        [src]

pub unsafe fn zero_memory<T>(dst: *mut T, count: usize)

Zeroes out count * size_of::<T> bytes of memory at dst. count may be
0.

Safety

Beyond accepting a raw pointer, this is unsafe because it will not drop the
contents of dst, and may be used to create invalid instances of T.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
package org.springframework.security.oauth2.client;

import org.springframework.lang.Nullable;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;

/**
 * Implementations of this interface are responsible for the overall management of
 * {@link OAuth2AuthorizedClient Authorized Client(s)}.
 *
 *

 * The primary responsibilities include:
 *

 *
Authorizing (or re-authorizing) an OAuth 2.0 Client by leveraging an
 * {@link OAuth2AuthorizedClientProvider}(s).

 *
Delegating the persistence of an {@link OAuth2AuthorizedClient}, typically using an
 * {@link OAuth2AuthorizedClientService} OR {@link OAuth2AuthorizedClientRepository}.

 *

 *
 * @author Joe Grandja
 * @since 5.2
 * @see OAuth2AuthorizedClient
 * @see OAuth2AuthorizedClientProvider
 * @see OAuth2AuthorizedClientService
 * @see OAuth2AuthorizedClientRepository
 */
@FunctionalInterface
public interface OAuth2AuthorizedClientManager {

	/**
	 * Attempt to authorize or re-authorize (if required) the {@link ClientRegistration
	 * client} identified by the provided
	 * {@link OAuth2AuthorizeRequest#getClientRegistrationId() clientRegistrationId}.
	 * Implementations must return {@code null} if authorization is not supported for the
	 * specified client, e.g. the associated {@link OAuth2AuthorizedClientProvider}(s)
	 * does not support the {@link ClientRegistration#getAuthorizationGrantType()
	 * authorization grant} type configured for the client.
	 *
	 *

	 * In the case of re-authorization, implementations must return the provided
	 * {@link OAuth2AuthorizeRequest#getAuthorizedClient() authorized client} if
	 * re-authorization is not supported for the client OR is not required, e.g. a
	 * {@link OAuth2AuthorizedClient#getRefreshToken() refresh token} is not available OR
	 * the {@link OAuth2AuthorizedClient#getAccessToken() access token} is not expired.
	 * @param authorizeRequest the authorize request
	 * @return the {@link OAuth2AuthorizedClient} or {@code null} if authorization is not
	 * supported for the specified client
	 */
	@Nullable
	OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest);

}


text:
from argparse import ArgumentParser
import sys

def print_and_exit(msg):
    sys.stderr.write(msg + '\n')
    sys.exit(1)

def main():
    parser = ArgumentParser(
        description="Concatenate two files into a single file")
    parser.add_argument(
        '-o', '--output', dest='output', required=True,
        help='The output file. stdout is used if not given',
        type=str, action='store')
    parser.add_argument(
        'files', metavar='files',  nargs='+',
        help='The files to concatenate')

    args = parser.parse_args()

    if len(args.files) < 2:
        print_and_exit('fewer than 2 inputs provided')
    data = ''
    for filename in args.files:
        with open(filename, 'r') as f:
            data += f.read()
        if len(data) != 0 and data[-1] != '\n':
            data += '\n'
    assert len(data) > 0 and "cannot cat empty files"
    with open(args.output, 'w') as f:
        f.write(data)

if __name__ == '__main__':
    main()
    sys.exit(0)


text:
using namespace node;

static Handle<Value> VException(const char *msg) {
  HandleScope scope;
  return ThrowException(Exception::Error(String::New(msg)));
};

Persistent<FunctionTemplate> SecurityBuffer::constructor_template;

SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() {
  this->size = size;
  this->data = calloc(size, sizeof(char));
  this->security_type = security_type;
  // Set up the data in the sec_buffer
  this->sec_buffer.BufferType = security_type;
  this->sec_buffer.cbBuffer = (unsigned long)size;
  this->sec_buffer.pvBuffer = this->data;
}

SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() {
  this->size = size;
  this->data = data;
  this->security_type = security_type;
  // Set up the data in the sec_buffer
  this->sec_buffer.BufferType = security_type;
  this->sec_buffer.cbBuffer = (unsigned long)size;
  this->sec_buffer.pvBuffer = this->data;
}

SecurityBuffer::~SecurityBuffer() {
  free(this->data);
}

Handle<Value> SecurityBuffer::New(const Arguments &args) {
  HandleScope scope;
  SecurityBuffer *security_obj;

  if(args.Length() != 2)
    return VException("Two parameters needed integer buffer type and  [32 bit integer/Buffer] required");

  if(!args[0]->IsInt32())
    return VException("Two parameters needed integer buffer type and  [32 bit integer/Buffer] required");

  if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1]))
    return VException("Two parameters needed integer buffer type and  [32 bit integer/Buffer] required");

  // Unpack buffer type
  uint32_t buffer_type = args[0]->ToUint32()->Value();

  // If we have an integer
  if(args[1]->IsInt32()) {
    security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value());
  } else {
    // Get the length of the Buffer
    size_t length = Buffer::Length(args[1]->ToObject());
    // Allocate space for the internal void data pointer
    void *data = calloc(length, sizeof(char));
    // Write the data to out of V8 heap space
    memcpy(data, Buffer::Data(args[1]->ToObject()), length);
    // Create new SecurityBuffer
    security_obj = new SecurityBuffer(buffer_type, length, data);
  }

  // Wrap it
  security_obj->Wrap(args.This());
  // Return the object
  return args.This();
}

Handle<Value> SecurityBuffer::ToBuffer(const Arguments &args) {
  HandleScope scope;

  // Unpack the Security Buffer object
  SecurityBuffer *security_obj = ObjectWrap::Unwrap<SecurityBuffer>(args.This());
  // Create a Buffer
  Buffer *buffer = Buffer::New((char *)security_obj->data, (size_t)security_obj->size);

  // Return the buffer
  return scope.Close(buffer->handle_);
}

void SecurityBuffer::Initialize(Handle<Object> target) {
  // Grab the scope of the call from Node
  HandleScope scope;
  // Define a new function template
  Local<FunctionTemplate> t = FunctionTemplate::New(New);
  constructor_template = Persistent<FunctionTemplate>::New(t);
  constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
  constructor_template->SetClassName(String::NewSymbol("SecurityBuffer"));

  // Set up method for the Kerberos instance
  NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer);

  // Set up class
  target->Set(String::NewSymbol("SecurityBuffer"), constructor_template->GetFunction());
}


text:
export default function comments(state=[], action){
  switch (action.type) {
    case 'ADD_COMMENT':
      console.log('Add comment');
      return [...state, {
          commentId: action.commentId,
          commentContent: action.commentContent,
          postId: action.postId,
          author: action.author,
          commentDate: action.commentDate
        }
      ];
    default:
      console.log('Add comment default');
      return state;
  }
}


text:
package org.apache.pdfbox.cos;

import java.io.IOException;

/**
 * This class represents an abstract number in a PDF document.
 *
 * @author Ben Litchfield
 */
public abstract class COSNumber extends COSBase {

  /**
   * @deprecated Use the {@link COSInteger#ZERO} constant instead
   */
  @Deprecated
  public static final COSInteger ZERO = COSInteger.ZERO;

  /**
   * @deprecated Use the {@link COSInteger#ONE} constant instead
   */
  @Deprecated
  public static final COSInteger ONE = COSInteger.ONE;

  /**
   * This will get the float value of this number.
   *
   * @return The float value of this object.
   */
  public abstract float floatValue();

  /**
   * This will get the double value of this number.
   *
   * @return The double value of this number.
   */
  public abstract double doubleValue();

  /**
   * This will get the integer value of this number.
   *
   * @return The integer value of this number.
   */
  public abstract int intValue();

  /**
   * This will get the long value of this number.
   *
   * @return The long value of this number.
   */
  public abstract long longValue();

  /**
   * This factory method will get the appropriate number object.
   *
   * @param number The string representation of the number.
   * @return A number object, either float or int.
   * @throws IOException If the string is not a number.
   */
  public static COSNumber get(String number) throws IOException {
    if (number.length() == 1) {
      char digit = number.charAt(0);
      if ('0' <= digit && digit <= '9') {
        return COSInteger.get(digit - '0');
      } else if (digit == '-' || digit == '.') {
        // See https://issues.apache.org/jira/browse/PDFBOX-592
        return COSInteger.ZERO;
      } else {
        throw new IOException("Not a number: " + number);
      }
    } else if (number.indexOf('.') == -1 && (number.toLowerCase().indexOf('e') == -1)) {
      try {
        if (number.charAt(0) == '+') {
          return COSInteger.get(Long.parseLong(number.substring(1)));
        }
        return COSInteger.get(Long.parseLong(number));
      } catch (NumberFormatException e) {
        // might be a huge number, see PDFBOX-3116
        return new COSFloat(number);
      }
    } else {
      return new COSFloat(number);
    }
  }
}


text:
package droidicus.aquaregia.init;

import droidicus.aquaregia.command.CommandAquaRegia;
import droidicus.aquaregia.command.CommandAquaRegiaHelp;
import droidicus.aquaregia.command.CommandRunTests;
import droidicus.aquaregia.command.ISubCommandManager;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;

/**
 * Registers this mod's commands.
 *
 * @author Choonster
 */
public class ModCommands {

    /**
     * Register the commands.
     *
     * @param event The server starting event
     */
    public static void registerCommands(FMLServerStartingEvent event) {
        event.registerServerCommand(new CommandAquaRegia(event.getServer()));
    }

    /**
     * Register the sub-commands of the {@code /aquaregia} command.
     *
     * @param subCommandManager The sub-command manager of the command
     */
    public static void registerSubCommands(ISubCommandManager subCommandManager) {
        subCommandManager.registerSubCommand(new CommandAquaRegiaHelp(subCommandManager));
//		subCommandManager.registerSubCommand(new CommandRotateVector());
        subCommandManager.registerSubCommand(new CommandRunTests());
//		subCommandManager.registerSubCommand(new CommandMaxHealthAdd());
//		subCommandManager.registerSubCommand(new CommandMaxHealthSet());
//		subCommandManager.registerSubCommand(new CommandMaxHealthGet());
    }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Content_For_Promotion_Extractor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Content_For_Promotion_Extractor.Tests
{
    [TestClass()]
    public class RelationshipTests
    {
        [TestMethod()]
        public void ToStringTest()
        {
            Assert.Fail();
        }
    }
}


text:
Hi {{ username }}, welcome to Abidria!

Click here to confirm your email and finish your register process.

Or if you prefer copy & paste the link below:

{{ confirmation_url }}

If you haven't registered on Abidria app, just ignore this mail. We won't mail you again.


text:
namespace Widget_WIN32
{
    bool createWindow(const char*wt);
}

namespace Widget_Linux
{
    bool createWindow(const char*wt, uint32_t x, uint32_t y);
}


text:
namespace solar {

	struct win32_opengl_engine_setup_params {
		MAKE_PROPERTY(win32_opengl_engine_setup_params, win32_windowed_app_setup_params, windowed_app_setup_params, win32_windowed_app_setup_params());
		MAKE_PROPERTY(win32_opengl_engine_setup_params, win32_file_system_setup_params, file_system_setup_params, win32_file_system_setup_params());
	};

	class win32_opengl_engine {
	public:
		win32_clipboard _win32_clipboard;
		win32_file_system _win32_file_system;
		win32_directory_change_watcher _win32_directory_change_watcher;
		win32_windowed_app _win32_windowed_app;
		win32_mouse_device _win32_mouse_device;
		win32_keyboard_device _win32_keyboard_device;
		file_change_watcher _file_change_watcher;
		resource_system _resource_system;
		win32_opengl_context _opengl_context;
		opengl_render_device _opengl_render_device;
		opengl_texture_factory _opengl_texture_factory;
		opengl_shader_program_factory _opengl_shader_program_factory;
		opengl_font_renderer_shader_program_provider _opengl_font_renderer_shader_program_provider;
		opengl_mesh_factory _opengl_mesh_factory;
		opengl_prim2d _opengl_prim2d;
		opengl_prim2d_lines _opengl_prim2d_lines;
		win32_opengl_engine_settings _engine_settings;
		setting_registry _setting_registry;
		cursor _cursor;

	public:
		win32_opengl_engine();
		~win32_opengl_engine();

		bool setup(const win32_opengl_engine_setup_params& params);
		void teardown();
		int run();

	private:
		void add_and_load_all_settings(const win32_opengl_engine_setup_params& params);
	};

}


text: var cancellableModule = angular.module('http.cancellable', []);


text:
.. _git-rebase:

Resolving merge conflicts
~~~~~~~~~~~~~~~~~~~~~~~~~

If the change that you submitted has a merge conflict,
you need to manually resolve it using :command:`git rebase`.

Rebasing is used to integrate changes from one branch into another to
resolve conflicts when multiple commits happen on the same file.

.. warning::

   Never do a rebase on public (master) branches.

#. You submit a change.

#. Somebody else submits a change and that change merges.
   Now your change has a merge conflict.

#. Update your local repository:

   .. code-block:: console

      $ git remote update
      $ git pull --ff-only origin master

#. Download your change:

   .. code-block:: console

      $ git review -d $PARENT_CHANGE_NUMBER

#. Rebase your change:

   .. code-block:: console

      $ git rebase origin/master

#. Resolve conflicts manually:

   Conflicts are marked in a file with clear line breaks:

   .. code-block:: console

      <<<<<<< HEAD
      Second line.
      =======
      Third line.
      >>>>>>> feature/topic branch.

   <<<<<<<: Indicates the start of the lines that had a merge conflict.

   =======: Indicates separation of the two conflicting changes.

   >>>>>>>: Indicates the end of the lines that had a merge conflict.

   You need to resolve a conflict by manually editing the file.
   You also need to delete the '<<<<<<<', '=======', and'>>>>>>>'
   in the file.

#. Add the files to the stage:

   .. code-block:: console

      $ git add $FILENAME

#. Complete the rebase process:

   .. code-block:: console

      $ git rebase --continue

#. Send the rebased patch again for review:

   .. code-block:: console

      $ git review


text:
<?php
    include "../Urabe.php";
    include "../AvalonId.php";
    //Campos de la tabla
    define('TABLE', 'nameless_category');
    define('FIELD_ID', 'id_store');
    define('FIELD_NAME', 'name');
    define('STDIN',fopen("php://stdin","r"));
    //Obtiene la entrada del tipo de web service
    $method = $_SERVER['REQUEST_METHOD'];
    $bodyMethods = array("PUT", "POST", "DELETE");
    //Put, Post y DELETE necesitan body
    if(in_array($method,$bodyMethods))
    {
        $input = file_get_contents('php://input');
        $input = json_decode($input);
    }
    //El administrador de conexión
    $conn = new UrabeMySql(new AvalonId());
    $result = "";
    switch ($method)
    {
        case 'GET':
        //Realizá el parseo de la información de la clase de categorías.
        $parseMethod = function ($row)
       {
           return '{ '.
                    '"'.FIELD_ID.'": '.$row["id_store"].', '.
                    '"'.FIELD_NAME.'": "'.$row["name"].'"'.
                ' }';
        };
        if(isset($_GET['store_id']))
        {
            $query = "SELECT * FROM ".TABLE." WHERE ".FIELD_ID."= ".$_GET['store_id'];
            $result = $conn->Select($query, $parseMethod);
        }
        else
            $result = $conn->SelectAll(TABLE, $parseMethod);
        break;
        case 'PUT':
            $store_id = $input->id_store;
            $fields = array(FIELD_NAME);
            $values = array($input->name);
            $result = $conn->UpdateByCondition(TABLE, $fields, $values, FIELD_ID, $store_id;
            if(!$result)
                $result = 0;
        break;
        case 'POST':
            $fields = array(FIELD_NAME);
            $values = array($input->name);
            $result = $conn->Insert(TABLE, $fields, $values);
            if(!$result)
                $result = 0;
        break;
        case 'DELETE':
          $store_id = $input->id_store;
          $result = $conn->DeleteByCondition(TABLE, FIELD_ID, $store_id);
            if(!$result)
                $result = 0;
        break;
    }
    $conn->Close();
    echo $result;
?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lachnum olivaceosulphureum Rick

### Remarks
null


text:
namespace aura {
class Window;
}

namespace ash {

class DesksTemplatesDialog;

// DesksTemplatesDialogController controls when to show the various confirmation
// dialogs for modifying desk templates.
class ASH_EXPORT DesksTemplatesDialogController : public views::WidgetObserver {
 public:
  DesksTemplatesDialogController();
  DesksTemplatesDialogController(const DesksTemplatesDialogController&) =
      delete;
  DesksTemplatesDialogController& operator=(
      const DesksTemplatesDialogController&) = delete;
  ~DesksTemplatesDialogController() override;

  // Convenience function to get the controller instance, which is created and
  // owned by OverviewSession.
  static DesksTemplatesDialogController* Get();

  const views::Widget* dialog_widget() const { return dialog_widget_; }

  // Shows the dialog. The dialog will look slightly different depending on the
  // type. The `template_name` is used for the replace and delete dialogs, which
  // show the name of the template which will be replaced and deleted in the
  // dialog description.
  void ShowUnsupportedAppsDialog(
      aura::Window* root_window,
      const std::vector<aura::Window*>& unsupported_apps,
      DesksController::GetDeskTemplateCallback callback,
      std::unique_ptr<DeskTemplate> desk_template);
  void ShowReplaceDialog(aura::Window* root_window,
                         const std::u16string& template_name);
  // Show the delete template dialog when user press the delete button.
  // The `template_name` shows the name of the template which will be deleted in
  // the dialog description.
  void ShowDeleteDialog(aura::Window* root_window,
                        const std::u16string& template_name,
                        base::OnceClosure on_accept_callback);

  // views::WidgetObserver:
  void OnWidgetDestroying(views::Widget* widget) override;

 private:
  // Creates and shows the dialog on `root_window`.
  void CreateDialogWidget(std::unique_ptr<DesksTemplatesDialog> dialog,
                          aura::Window* root_window);

  // Callbacks for when a user has either accepted the unsupported apps dialog
  // or not.
  void OnUserAcceptedUnsupportedAppsDialog();
  void OnUserCanceledUnsupportedAppsDialog();

  // Pointer to the widget (if any) that contains the current dialog.
  views::Widget* dialog_widget_ = nullptr;

  // When a caller creates an unsupported apps dialog, they provide a callback
  // for the result. Since we can only bind the callback once, we have to store
  // the callback and DeskTemplate until we know what the user's choice is.
  DesksController::GetDeskTemplateCallback unsupported_apps_callback_;
  std::unique_ptr<DeskTemplate> unsupported_apps_template_;

  base::ScopedObservation<views::Widget, views::WidgetObserver>
      dialog_widget_observation_{this};

  base::WeakPtrFactory<DesksTemplatesDialogController> weak_ptr_factory_{this};
};

}  // namespace ash

#endif  // ASH_WM_DESKS_TEMPLATES_DESKS_TEMPLATES_DIALOG_CONTROLLER_H_


text:
import {computeDispatch} from '../webgpu_util';
import {WebGPUProgram} from './webgpu_program';

export const RELU = 'return max(a, 0.0);';

export const SIGMOID = `return 1.0 / (1.0 + exp(-1.0 * a));`;

export class UnaryOpProgram implements WebGPUProgram {
  outputShape: number[];
  userCode: string;
  dispatchLayout: {x: number[]};
  dispatch: [number, number, number];
  variableNames = ['A'];

  constructor(outputShape: number[], op: string) {
    this.outputShape = outputShape;
    this.dispatchLayout = {x: this.outputShape.map((d, i) => i)};
    this.dispatch = computeDispatch(this.dispatchLayout, this.outputShape);

    this.userCode = `
      float unaryOperation(float a) {
        ${op}
      }

      void main() {
        uint index = gl_GlobalInvocationID.x;
        float a = getAAtOutCoords();
        setOutput(index, unaryOperation(a));
      }
    `;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using GmailWebClient.Filters;
using GmailWebClient.Models;

namespace GmailWebClient.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public HttpStatusCodeResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        //
        // POST: /Account/LogOff

        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public HttpStatusCodeResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                        new
                            {
                                GmailAccount = model.Email,
                                GmailPassword = model.GmailPassword
                            });
                    WebSecurity.Login(model.UserName, model.Password);
                    return new HttpStatusCodeResult(HttpStatusCode.OK);
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        //
        // POST: /Account/Disassociate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Disassociate(string provider, string providerUserId)
        {
            string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
            ManageMessageId? message = null;

            // Удалять связь учетной записи, только если текущий пользователь — ее владелец
            if (ownerAccount == User.Identity.Name)
            {
                // Транзакция используется, чтобы помешать пользователю удалить учетные данные последнего входа
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
                {
                    bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
                    if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
                    {
                        OAuthWebSecurity.DeleteAccount(provider, providerUserId);
                        scope.Complete();
                        message = ManageMessageId.RemoveLoginSuccess;
                    }
                }
            }

            return RedirectToAction("Manage", new { Message = message });
        }

        //
        // GET: /Account/Manage

        public ActionResult Manage(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Пароль изменен."
                : message == ManageMessageId.SetPasswordSuccess ? "Пароль задан."
                : message == ManageMessageId.RemoveLoginSuccess ? "Внешняя учетная запись удалена."
                : "";
            ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.ReturnUrl = Url.Action("Manage");
            return View();
        }

        //
        // POST: /Account/Manage

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Manage(LocalPasswordModel model)
        {
            bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            ViewBag.HasLocalPassword = hasLocalAccount;
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (hasLocalAccount)
            {
                if (ModelState.IsValid)
                {
                    // В ряде случаев при сбое ChangePassword породит исключение, а не вернет false.
                    bool changePasswordSucceeded;
                    try
                    {
                        changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                    }
                    catch (Exception)
                    {
                        changePasswordSucceeded = false;
                    }

                    if (changePasswordSucceeded)
                    {
                        return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
                    }
                    else
                    {
                        ModelState.AddModelError("", "Неправильный текущий пароль или недопустимый новый пароль.");
                    }
                }
            }
            else
            {
                // У пользователя нет локального пароля, уберите все ошибки проверки, вызванные отсутствующим
                // полем OldPassword
                ModelState state = ModelState["OldPassword"];
                if (state != null)
                {
                    state.Errors.Clear();
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
                        return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("", String.Format("Не удалось создать локальную учетную запись. Возможно, учетная запись \"{0}\" уже существует.", User.Identity.Name));
                    }
                }
            }

            // Появление этого сообщения означает наличие ошибки; повторное отображение формы
            return View(model);
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        }

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // Если текущий пользователь вошел в систему, добавляется новая учетная запись
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // Новый пользователь, запрашиваем желаемое имя участника
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            }
        }

        //
        // POST: /Account/ExternalLoginConfirmation

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Добавление нового пользователя в базу данных
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Проверка наличия пользователя в базе данных
                    if (user == null)
                    {
                        // Добавление имени в таблицу профиля
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "Имя пользователя уже существует. Введите другое имя пользователя.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

        //
        // GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            List<ExternalLogin> externalLogins = new List<ExternalLogin>();
            foreach (OAuthAccount account in accounts)
            {
                AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);

                externalLogins.Add(new ExternalLogin
                {
                    Provider = account.Provider,
                    ProviderDisplayName = clientData.DisplayName,
                    ProviderUserId = account.ProviderUserId,
                });
            }

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Вспомогательные методы
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }

            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }

            public override void ExecuteResult(ControllerContext context)
            {
                OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // Полный список кодов состояния см. по адресу http://go.microsoft.com/fwlink/?LinkID=177550
            //.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Имя пользователя уже существует. Введите другое имя пользователя.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "Имя пользователя для данного адреса электронной почты уже существует. Введите другой адрес электронной почты.";

                case MembershipCreateStatus.InvalidPassword:
                    return "Указан недопустимый пароль. Введите допустимое значение пароля.";

                case MembershipCreateStatus.InvalidEmail:
                    return "Указан недопустимый адрес электронной почты. Проверьте значение и повторите попытку.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "Указан недопустимый ответ на вопрос для восстановления пароля. Проверьте значение и повторите попытку.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "Указан недопустимый вопрос для восстановления пароля. Проверьте значение и повторите попытку.";

                case MembershipCreateStatus.InvalidUserName:
                    return "Указано недопустимое имя пользователя. Проверьте значение и повторите попытку.";

                case MembershipCreateStatus.ProviderError:
                    return "Поставщик проверки подлинности вернул ошибку. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";

                case MembershipCreateStatus.UserRejected:
                    return "Запрос создания пользователя был отменен. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";

                default:
                    return "Произошла неизвестная ошибка. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";
            }
        }
        #endregion
    }
}


text:
type: post102
title:  Using Processing Units for Scaling
categories: XAP102TUT
weight: 100
parent: first-xap-app.html
---

{{%ssummary%}}{{%/ssummary%}}

In this step we will use a car wash analogy to compare the traditional tier based approach for architecting enterprise application with GigaSpaces' Space Based approach, and explain the concept of _Processing Units_.

Once in a while you need to wash your car. Some people keep their car in superb condition and wash it very often, while others transform it skillfully into a mega-junk-mobile and take it to the car wash very rarely, if ever. But the fact remains that most people will bring their car to the car wash at one stage or another

# Washing Your Car The Tier-Based Way

In a tier-based architecture, our system is composed of several disparate physical tiers - meaning the database, the messaging queue and the application server. So every time your application needs to get something done, it typically goes through all these components. Imagine using this approach to wash your car. Each tier is analogous to a phase in our washing process: Firstly, the dirty car is transported to a soaping warehouse, where it is covered with soap. The next stop is transporting the "soaped" car to a different warehouse, where it is watered to rinse off the soap. The last step is transporting the car to yet another warehouse, which specializes in drying water marks, to dry and wipe all the water off of it.

Fortunately, we don't clean cars this way, because transporting the car to each of the warehouses (which might be geographically remote from one another) would take a considerable amount of time.

{{% align center %}}
![Tierbased2.jpg](/attachment_files/Tierbased2.jpg)
{{% /align %}}

{{% align center %}}
{{% sub %}}Diagram 1. Car wash, the tier based way: a different warehouse for each step in the process.{{% /sub %}}
{{% /align %}}

# Washing the Car Using Space-Based Architecture

What we actually do, is send the car a single warehouse, which has all the services available in the same place (we call this colocation). That way this services can be accessed much faster. One local machine soaps it, another local washing machine waters it, and finally a third local machine uses hot air to dry it and remove all the water marks. This an all-in-one warehouse, containing a depot to hold the car and all the collocated services for washing, rinsing and drying it. In the GigaSpaces language, we call this a _Processing Unit_ - in this case a carwash processing unit.

Going back to the real world (where enterprise applications live...), imagine that your application will have all the services it needs in the same location (operating system process to be specific). So it will not go through separate physical layers just to access the data or send and receive messages. This is the concept behind GigaSpaces' Processing Unit.

{{% align center %}}
![Spacebased.jpg](/attachment_files/Spacebased.jpg)
{{% /align %}}

{{% align center %}}
{{% sub %}}Diagram 2. An all-in-one "washing unit" containing soaping, watering and drying services.{{% /sub %}}
{{% /align %}}

# Scaling Easily with Self Contained Processing Units

Self contained Processing Units also have the advantage that they can be easily scaled. If we have more cars to wash than a single unit can handle, the system can be scaled almost linearly, by simply adding more car washing units.

{{% align center %}}
![Spacebasedscaled.jpg](/attachment_files/Spacebasedscaled.jpg)
{{% /align %}}

{{% align center %}}
{{% sub %}}Diagram 3. Scaling the system by adding more "car washing units".{{% /sub %}}
{{% /align %}}

# XAP Processing Unit

Now let's translate this to the enterprise application terminology. In the diagram below you can see a GigaSpaces Processing Unit instance, which runs within a Processing Unit Container. (This is in fact a JVM with a thin layer that knows how to run processing units.)

You can see the _Space_ (the "car depot") in the center of the processing unit. The space holds objects in the local JVM memory, making them accessible to all the local services (the "washing services"). The space can also act as a messaging layer, by notifying the relevant service when a particular object is written to it. The services can then respond to the message by processing it, and writing it back to the space. They can also use the space to retrieve additional pieces of information needed for the processing. A client application can interact with the space-side services by writing objects to the Processing Unit's space and reading them after they are processed. We can linearly scale the system by simply adding more Processing Unit instances, since the processing units are entirely independent of one another.

{{% align center %}}
![Spacebasedreal.jpg](/attachment_files/Spacebasedreal.jpg)
{{% /align %}}

{{% align center %}}
{{% sub %}}Diagram 4. A Processing Unit with 3 services collocated with a space.{{% /sub %}}
{{% /align %}}

# What About My Data?

In many cases, the space cannot store all of the relevant data that your application needs within the memory of a single JVM. In such cases we need to divide the data between the instances intelligently. We call this _Data Partitioning_. Let's return to the carwash example to illustrate this.
Imagine that each car model has to be washed in a slightly different manner to achieve optimal results. So we actually have a plan specific to each model that needs to stored in the car wash warehouse and be accessed by each of the services. In the tier based approach, we would put all of the plans in a central plan repository (which is the database)


text:
//
//  DemandModel.h
//  JianGuo
//
//  Created by apple on 17/1/7.
//  Copyright © 2017年 ningcol. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface DemandModel : NSObject

/** 任务ID */
@property (nonatomic, copy) NSString*  demandId;

/** 用户ID */
@property (nonatomic, copy) NSString*  userId;

/** 用户的学校 */
@property (nonatomic, copy) NSString*  userSchoolName;

/** 学校id */
@property (nonatomic, copy) NSString*  schoolId;

/** 任务发布到的学校 */
@property (nonatomic, copy) NSString*  schoolName;

/** 头像 */
@property (nonatomic, copy) NSString*  headImg;

/** 头像 */
@property (nonatomic, copy) NSArray*  images;

/** 报名人数 */
@property (nonatomic, copy) NSString*  enrollCount;

/** 需求的发布时间 */
@property (nonatomic, copy) NSString*  createTime;

/** 需求所属城市code */
@property (nonatomic, copy) NSString*  cityCode;

/** 需求类型 */
@property (nonatomic, copy) NSString*  type;

/** 评论数 */
@property (nonatomic, copy) NSString*  commentCount;

/** 点赞数 */
@property (nonatomic, copy) NSString*  likeCount;

/** 是否关注 */
@property (nonatomic, copy) NSString*  isFollow;

/** 所属城市 */
@property (nonatomic, copy) NSString*  cityName;

/** 任务描述 */
@property (nonatomic, copy) NSString*  demandDesc;

//以下是老接口数据

/** 数据ID */
@property (nonatomic, copy) NSString*  id;

/** 赏金 */
@property (nonatomic, copy) NSString*  money;

/** 昵称 */
@property (nonatomic, copy) NSString*  nickname;

/** 头像 */
@property (nonatomic, copy) NSString*  head_img_url;

/** 发需求的人的性别 */
@property (nonatomic, copy) NSString*  sex;

/** 是不是匿名 */
@property (nonatomic, copy) NSString*  anonymous;

/** 所属区域 */
@property (nonatomic, copy) NSString*  area;

/** 所属城市 */
@property (nonatomic, copy) NSString*  city;

/** 需求图片 */
@property (nonatomic, copy) NSString* d_image;

/** 需求状态 */
@property (nonatomic, copy) NSString* d_status;

/** 需求类型 */
@property (nonatomic, copy) NSString* d_type;

/** 需求描述 */
@property (nonatomic, copy) NSString* d_describe;

/** 需求标题 */
@property (nonatomic, copy) NSString* title;

/** 评论数组 */
@property (nonatomic, strong) NSArray* commentEntitys;

/** 点赞数 */
@property (nonatomic, copy) NSString*  like_count;

/** 点赞数 */
@property (nonatomic, copy) NSString*  like_status;

/** 报名状态 */
@property (nonatomic, copy) NSString*  enroll_status;

/** 报名人数 */
@property (nonatomic, copy) NSString*  enroll_count;

/** 报名人ID */
@property (nonatomic, copy) NSString*  enroll_user_id;

/** 发需求者的用户ID */
@property (nonatomic, copy) NSString*  b_user_id;

/** 需求的发布时间 */
@property (nonatomic, copy) NSString*  create_time;

/** 评论总数 */
@property (nonatomic, copy) NSString*  comment_count;

/** 学校ID */
@property (nonatomic, copy) NSString*  school_id;

/** 学校名称 */
@property (nonatomic, copy) NSString*  school_name;

/** 发布者电话 */
@property (nonatomic, copy) NSString*  tel;

@end


text:
import React from 'react';
import { TableRow, TableRowColumn } from '@material-ui/core/Table';

const Depreciation = ({ style, depreciation }) => {
  return (
    <TableRow>
      <TableRowColumn>

Depreciation over three years

      </TableRowColumn>
      <TableRowColumn>

          {!isNaN(depreciation) &&
            isFinite(depreciation) &&
            '$' + depreciation.toFixed(2)}

      </TableRowColumn>
    </TableRow>
  );
};

export default Depreciation;


text:
<?php
// enquire button snippet
// appears on about, wheels, fitting, frames
?>

>>> enquire


text:
import Helper from 'ima-helpers';
import CacheFactory from 'cache/CacheFactory';
import Cache from 'cache/CacheImpl';
import MapStorage from 'storage/MapStorage';

describe('ima.cache.CacheImpl', () => {
  let cache = null;
  let cacheStorage = null;
  let cacheFactory = null;

  beforeEach(() => {
    cacheStorage = new MapStorage();
    cacheFactory = new CacheFactory();
    cache = new Cache(cacheStorage, cacheFactory, Helper, {
      enabled: true,
      ttl: 1000
    });
    Date.now = () => 1000;
    cache.set('aaa', 123);
  });

  it('should store value for key', () => {
    cache.set('bbb', 456);
    cache.set('ccc', 321, 2000);

    Date.now = () => 2001;

    expect(cache.has('aaa')).toBe(false);
    expect(cache.has('bbb')).toBe(false);
    expect(cache.has('ccc')).toBe(true);
  });

  describe('set method', () => {
    it('should store deep clone', () => {
      let object = {
        number: 1,
        boolean: true,
        string: 'text',
        array: [1, 2, 3, [4, 5]],
        object: {
          number: 1,
          boolean: true,
          string: 'text',
          array: [1, 2, 3, [4, 5], { number: 1 }]
        }
      };

      cache.set('object', object);

      object.object.number = 2;
      object.object.array[3] = 4;
      object.object.array[4].number = 2;

      let cacheObject = cache.get('object');

      expect(cacheObject.object.number).toEqual(1);
      expect(cacheObject.object.array[3]).toEqual([4, 5]);
      expect(cacheObject.object.array[4].number).toEqual(1);
    });

    it('should returns deep clone', () => {
      let object = {
        number: 1,
        boolean: true,
        string: 'text',
        array: [1, 2, 3, [4, 5]],
        object: {
          number: 1,
          boolean: true,
          string: 'text',
          array: [1, 2, 3, [4, 5], { number: 1 }]
        }
      };

      cache.set('object', object);
      let cloneObject = cache.get('object');

      cloneObject.object.number = 2;
      cloneObject.object.array[3] = 4;
      cloneObject.object.array[4].number = 2;

      expect(cache.get('object')).toEqual(object);
    });

    it('should return same value for instance of Promise', () => {
      let promise = Promise.resolve('promise');
      spyOn(Helper, 'clone').and.stub();

      cache.set('promise', promise);

      expect(Helper.clone).not.toHaveBeenCalled();
      expect(cache.get('promise')).toEqual(promise);
    });
  });

  it('should return false for undefined cacheEntry', () => {
    spyOn(cacheStorage, 'has').and.returnValue(true);

    expect(cache.has('bbb')).toBe(false);
  });

  it('should return cached value for exist key', () => {
    expect(cache.get('aaa')).toEqual(123);
  });

  it('should return null for not exist key', () => {
    expect(cache.get('bbb')).toEqual(null);
  });

  it('should cleared cache', () => {
    cache.clear();

    expect(cache.has('aaa')).toBe(false);
  });

  it('should cache disabled', () => {
    cache.disable();

    expect(cache.has('aaa')).toBe(false);
  });

  it('should serialize and deserialize', () => {
    let serialization = cache.serialize();
    cache.clear();
    cache.deserialize(serialization);

    expect(cache.has('aaa')).toBe(false);
  });

  it('should serialize only instances of the CacheEntry', () => {
    spyOn(cacheFactory, 'createCacheEntry').and.returnValue({ foo: 'bar' });

    cache.set('myKey', {
      foo: 'bar'
    });
    const serialization = cache.serialize();

    expect(serialization).toEqual(
      JSON.stringify({
        aaa: {
          value: 123,
          ttl: 1000
        }
      })
    );
  });

  it('should serialize javascript Infinity value ttl to "Infinity" string ttl', () => {
    cache.clear();
    cache.set('key', 'value', Infinity);
    const serialization = cache.serialize();

    expect(serialization).toEqual(
      JSON.stringify({
        key: {
          value: 'value',
          ttl: 'Infinity'
        }
      })
    );
  });

  it('should serialize number value ttl to string', () => {
    cache.clear();
    cache.set('key', 'value', 60000);
    const serialization = cache.serialize();

    expect(serialization).toEqual(
      JSON.stringify({
        key: {
          value: 'value',
          ttl: 60000
        }
      })
    );
  });

  it('should deserialize "Infinity" string value ttl to javascript Infinity value', () => {
    const serialization = {
      key: {
        value: 'value',
        ttl: 'Infinity'
      }
    };
    cache.clear();
    cache.deserialize(serialization);

    expect(cache._cache.get('key')._ttl).toEqual(Infinity);
  });

  it('should throw error for serialize if value is instance of Promise', () => {
    spyOn(console, 'warn');

    cache.set('promise', Promise.resolve('promise'));

    expect(() => {
      cache.serialize();
    }).toThrow();
    expect(console.warn).toHaveBeenCalled();
  });

  describe('_canSerializeValue method', () => {
    beforeEach(() => {
      spyOn(console, 'warn');
    });

    it('should return false for Date', () => {
      expect(cache._canSerializeValue(new Date())).toBe(false);
    });

    it('should return false for RegExp', () => {
      expect(cache._canSerializeValue(new RegExp('/'))).toBe(false);
    });

    it('should return false for resolved promise', () => {
      expect(cache._canSerializeValue(Promise.resolve(1))).toBe(false);
    });

    it('should return false for object with bad type of keys', () => {
      let object = {
        date: new Date()
      };

      expect(cache._canSerializeValue(object)).toBe(false);
    });

    it('should return true for serializable object', () => {
      let object = {
        number: 1,
        string: 'string',
        boolean: true,
        array: [1, 2, 3, { string: 'string' }],
        object: {
          number: 1
        }
      };

      expect(cache._canSerializeValue(object)).toBe(true);
    });
  });
});


text:
layout: 2014post
type: news
title: "Beating the Bechdel Test"
tagline: As posted in Metro.ca
image: 2014-07-24-Metro.png

---
This article appeared in the July 24, 2014 edition of [Metro](http://metronews.ca/news/london/1107021/beating-the-bechdel-test-londoner-hopegrown-productions-set-a-standard/)

> The start of an acting career carries all sorts of challenges for young women, but London's about to welcome three who are setting their own standards.
>
> Londoner Miriam Cummings is part of Hopegrown Productions, a theatre group which has three female members determined to play strong roles and tell stories that are relevant to our times.
>
> They're doing it, too.
>
> "The intention of Hopegrown Productions is essentially to aid in providing good roles for young women on the stage," said Cummings, who is 23.
>
> It's all about the Bechdel Test. Coined by Alison Bechdel in her 1980s comic strip Dykes To Watch Out For, it's a measure of how a work of fiction treats women.
>
> To pass the test, the story must include at least two women, and they must talk to each other — but about something other than a man.
>
> "A shocking amount of film does not pass the test," Cummings said. "We found a similar thing when we were searching for a play to put on for our first production.
>
> "We were just coming out of our undergraduate degrees, all three of us. We wanted to put on something in the Montreal Fringe Festival. We had a spot. But we felt a bit put out."
>
> Also involved are young actors Samantha Megarry, from Burlington, and Lindsey Heubner, from Ottawa. All studied together at Concordia University in Montreal.
>
> The trio wanted a "meaty role" for women, but, unable to find one that was good enough or one that was in a show they could afford the rights to, decided instead to have one written for them.
>
> They began with Around Miss Julie, written by Harry Standjofski, and now they're coming to London with a new play, Lotus, by Caitlin Murphy.
>
> With the poster tagline "You can't run from your problems once they've gone viral," it's about the consequences of a gruesome photo appearing on a girl's Facebook page.
>
> "The method really works," Cummings said about their determination to gain strong roles for young women. "We've kind of adapted the idea of working with playwrights that want to create and produce new work that fits with our method."
>
> Lotus is to be staged Aug. 5-9 at The Arts Project (203 Dundas St.).