text:
package com.github.radium226.common;

import com.google.common.collect.ImmutableMap;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.primitives.Primitives;
import java.util.Map;

public final class ListenerList<T> {

    final private static Logger LOGGER = LoggerFactory.getLogger(ListenerList.class);

    private final Set<T> listeners = Sets.newHashSet();
    private final Class<T> listenerClass;

    private ListenerList(Class<T> listenerClass) {
        super();

        this.listenerClass = listenerClass;
    }

    public static <T> ListenerList<T> of(Class<T> listenerClass) {
        return new ListenerList<>(listenerClass);
    }

    public boolean add(T listener) {
        return listeners.add(listener);
    }

    public boolean remove(T listener) {
        return listeners.remove(listener);
    }

    public boolean contains(T listener) {
        return listeners.contains(listener);
    }

    public void fire(String methodName, Object... parameters) {
        for (T listener : listeners) {
            try {
                Class<?>[] parameterTypes = Lists.transform(Arrays.asList(parameters), (Object parameter) -> {
                    Class<?> type = parameter.getClass();
                    return Primitives.isWrapperType(type) ? Primitives.unwrap(type) : type;
                }).toArray(new Class<?>[0]);
                Method method = listenerClass.getMethod(methodName, parameterTypes);
                method.invoke(listener, parameters);
            } catch (IllegalAccessException | SecurityException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
                LOGGER.warn("Unable to invoke {}", methodName, e);
            }
        }
    }

}


text:
import axios from "axios";

import { PointApiResponse } from "../../shared/stat_types";
import { saveToFile } from "../../shared/util";
import { stringifyFn } from "../../utils/axios";
import { getTokensFromUrl } from "./util";

/* Start the loading spinner and gray out the background. */
function loadSpinner(): void {
  document.getElementById("screen").classList.add("d-block");
}

/* Remove the spinner and gray background. */
function removeSpinner(): void {
  document.getElementById("screen").classList.remove("d-block");
}

/**
 * Downloads data for all places of a certain type for the specified ptpv's in
 * the chart.
 */
function downloadBulkData(
  statVars: string[],
  placeType: string,
  ancestorDcid: string
): void {
  loadSpinner();
  axios
    .get("/api/place/places-in-names", {
      params: {
        dcid: ancestorDcid,
        placeType,
      },
    })
    .then((resp) => {
      const placeDcids = Object.keys(resp.data);
      const placeNames = resp.data;
      axios
        .get<PointApiResponse>("/api/observations/point", {
          params: {
            entities: placeDcids,
            variables: statVars,
          },
          paramsSerializer: stringifyFn,
        })
        .then((resp) => {
          if (resp.data && resp.data.data) {
            saveToCsv(placeDcids, placeNames, statVars, resp.data.data);
          } else {
            alert("There was an error loading the data");
          }
          removeSpinner();
        })
        .catch((error) => {
          let errorMsg = "There was an error loading the statistics";
          if (error.response) {
            errorMsg += ": " + error.response.data.message;
          }
          removeSpinner();
          alert(errorMsg);
        });
    })
    .catch(() => {
      removeSpinner();
      alert("There was an error loading places");
    });
}

// TODO(beets): Define interfaces for all responses
function saveToCsv(
  placeDcids: string[],
  placeNames: { [dcid: string]: string },
  statVars: string[],
  data: any
): void {
  const results = [];
  results.push("placeDcid,placeName," + statVars.join(","));
  for (const place of placeDcids.sort()) {
    const row = [`"${place}"`, `"${placeNames[place]}"`];
    for (const sv of statVars) {
      row.push(data[sv]["stat"][place]["value"] || "");
    }
    results.push(row.join(","));
  }
  const csv = results.join("\n");
  saveToFile("datacommons_data.csv", csv);
}

window.onload = function () {
  const statVars = Array.from(getTokensFromUrl("statsVar", "__"));
  const statVarDisplay = document.getElementById("statVars");
  statVarDisplay.innerText = statVars.join(", ");

  const links = document.getElementsByClassName("bulk-ref");
  for (let i = 0; i < links.length; i++) {
    const link = links.item(i) as HTMLElement;
    const ptype = link.dataset.ptype;
    link.addEventListener("click", function () {
      downloadBulkData(statVars, ptype, "country/USA");
    });
  }
};

redpajama_set_name: RedPajamaGithub


text:
layout: story
color: red #red, blue, green, cyan
pattern: 2 #one of: 1, 2, 3, 4
og-image: /assets/stories/bbs-hero.jpg # used for facebook & twitter card

title: Bürger baut Stadt - Mitbestimmung statt Baubestimmung
where: Berlin
when: Juni, 2015
links: # first one is used in subline
- name: buergerbautstadt.de
  url: http://buergerbautstadt.de/

- name: Beitrag vom Elektrischen Reporter (video)
  url: https://youtu.be/4xJCP3eecG8

header-images: #use 3:2 proportioned image
- src: /assets/stories/bbs-hero.jpg
  alt: Magdalena Noffke, Elektrischer Reporter
  caption: Magda © Elektrischer Reporter

lead: Magdalena Noffke und ihre MitstreiterInnen wollten wissen, was genau in ihrem Kiez gebaut wird. Die Informationen sind zwar öffentlich, aber nur schwer zugänglich. Also haben sie kurzerhand eine Website programmiert, die alle Bauvorhaben in Berlin zusammenstellt. Finden wir toll!

embed:

members:
- name: Magdalena Noffke
  username-twitter: magdalenanoffke
  username-github: MagdaN

- name: Jochen Klar
  username-twitter: jochenklar
  username-github: jochenklar

- name: Stefan Graupner
  username-twitter: eFrane
  username-github: eFrane

- name: Lucas Jacob
  username-github: LucasJ

---
## Die Idee
Wenn im eigenen Kiez gebaut wird, fragt man sich oft, was dort genau entsteht. So ginge es auch Magdalena Noffke und ihren Mitstreiterinnen. "Wir haben versucht, uns über diese ganzen Baustellen zu informieren", sagt Magdalena. Doch das war überhaupt nicht einfach. Viele Informationen sind zwar öffentlich, aber schwer zugänglich. Sie verstecken sich in Amtsblättern, die online eingescannt werden. Das heißt, durchsuchen kann man sie nicht.

## Die Erkenntnis

Bürger können bei Bauprojekten in ihrer Gegend durchaus mitreden – wenn sie denn rechtzeitig davon hören. "Es gibt eigentlich viel Bürgerbeteiligung, von der man aber nichts mitkriegt", sagt Magdalena. Meistens erfahren BewohnerInnen erst von Bauplänen, wenn die Bauzäune aufgestellt werden. Dann ist es aber schon zu spät, um sich einzubringen.

## Die Lösung
Auf einer Webseite Bauvorhaben übersichtlich darstellen. Wer seine E-Mail-Adresse einträgt, kann Nachrichten zu Bauplänen in bestimmten Bezirken erhalten. So können Bürgerinnen und Bürger schon früh mitreden, wie ihr Kiez in Zukunft aussehen soll.

Es hört sich alles so kompliziert an, dass man als Bürger abgeschreckt ist.

  Magdalena N.

## Schlimmstes Wort
*Bebauungsplanverfahren*. Baupläne sind in eine dicke Schicht Behördendeutsch eingepackt. Dabei geht es eigentlich nur darum, dass ein Gebiet für eine bestimmte Nutzung ausgewiesen ist – etwas als Wohngegend oder Einkaufszone. Wird diese Zuschreibung (im Behördendeutsch: Widmung) geändert, kann man mitreden. "Eigentlich ist es gar nicht so kompliziert", sagt auch Magdalena. "Aber es hört sich alles so kompliziert an, dass man als Bürger abgeschreckt ist."

## Der nächste Schritt
Die Bauvorhaben lassen sich übersichtlich finden, nun will Magdalena es auch einfacher machen, sich tatsächlich zu beteiligen. Dazu will sie eine Art Vorlage erstellen. Will eine Bürgerin ihre Meinung zu einem geplanten Bauvorhaben sagen, kann sie ihre eigenen Kommentare in die Vorlage einbauen und das ganze an das zuständige Amt schicken.


text:
package com.google.template.soy.soytree;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;

import com.google.common.base.Joiner;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.base.internal.IncrementingIdGenerator;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.soyparse.SoyFileParser;
import java.io.StringReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Unit tests for RawTextNode.
 *
 */
@RunWith(JUnit4.class)
public final class RawTextNodeTest {

  @Test
  public void testToSourceString() {
    RawTextNode rtn = new RawTextNode(0, "Aa`! \n \r \t { }", SourceLocation.UNKNOWN);
    assertEquals("Aa`! {\\n} {\\r} {\\t} {lb} {rb}", rtn.toSourceString());
  }

  @Test
  public void testTabCharNode() {
    TemplateNode template = parseTemplate("{\\t}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{\\t}");
    assertThat(charNode.getRawText()).isEqualTo("\t");
    assertThat(charNode.isCommandCharacter()).isTrue();
  }

  @Test
  public void testSpCharNode() {
    TemplateNode template = parseTemplate("{sp}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{sp}");
    assertThat(charNode.getRawText()).isEqualTo(" ");
  }

  @Test
  public void testNilCharNode() {
    TemplateNode template = parseTemplate("{nil}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{nil}");
    assertThat(charNode.getRawText()).isEmpty();
    assertThat(charNode.isEmpty()).isTrue();
    assertThat(charNode.isNilCommandChar()).isTrue();
  }

  @Test
  public void testCarriageReturnCharNode() {
    TemplateNode template = parseTemplate("{\\r}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{\\r}");
    assertThat(charNode.getRawText()).isEqualTo("\r");
  }

  @Test
  public void testNewlineCharNode() {
    TemplateNode template = parseTemplate("{\\n}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{\\n}");
    assertThat(charNode.getRawText()).isEqualTo("\n");
  }

  @Test
  public void testLeftBraceCharNode() {
    TemplateNode template = parseTemplate("{lb}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{lb}");
    assertThat(charNode.getRawText()).isEqualTo("{");
  }

  @Test
  public void testRightBraceCharNode() {
    TemplateNode template = parseTemplate("{rb}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{rb}");
    assertThat(charNode.getRawText()).isEqualTo("}");
  }

  @Test
  public void testNbspCharNode() {
    TemplateNode template = parseTemplate("{nbsp}");

    RawTextNode charNode = (RawTextNode) template.getChild(0);
    assertThat(charNode.toSourceString()).isEqualTo("{nbsp}");
    assertThat(charNode.getRawText()).isEqualTo("\u00A0");
  }

  /** Parses the given input as a template content. */
  private static TemplateNode parseTemplate(String input) {
    String soyFile =
        Joiner.on('\n')
            .join("{namespace ns}", "", "{template .t stricthtml=\"false\"}", input, "{/template}");
    SoyFileNode node =
        new SoyFileParser(
                new IncrementingIdGenerator(),
                new StringReader(soyFile),
                "test.soy",
                ErrorReporter.exploding())
            .parseSoyFile();
    if (node != null) {
      return (TemplateNode) node.getChild(0);
    }
    return null;
  }
}


text:
package com.sdp.netty;

import com.sdp.common.EMSGID;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * @author martji
 */

public class MDecoder extends FrameDecoder {
    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel,
                            ChannelBuffer buffer) throws Exception {
        if (buffer.readableBytes() < 8) {
            return null;// (1)
        }
        int dataLength = buffer.getInt(buffer.readerIndex());
        if (buffer.readableBytes() < dataLength + 4) {
            return null;// (2)
        }

        buffer.skipBytes(4);// (3)
        int id = buffer.readInt();
        int nodeRoute = buffer.readInt();
        byte[] decoded = new byte[dataLength - 8];

        buffer.readBytes(decoded);
        NetMsg msg = new NetMsg(decoded, id);// (4)
        msg.setMsgID(EMSGID.values()[id]);
        msg.setNodeRoute(nodeRoute);
        return msg;
    }
}


text:
<?php

// don't load directly
if ( ! function_exists( 'is_admin' ) ) {
	header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
	exit();
}

if ( ! class_exists( "Nav_Menu_Roles" ) ) :

class Nav_Menu_Roles {

	/**
	* @var Nav_Menu_Roles The single instance of the class
	* @since 1.5
	*/
	protected static $_instance = null;

	/**
	* @var string donate url
	* @since 1.5
	*/
	public static $donate_url = "https://inspirepay.com/pay/helgatheviking";

	/**
	* Main Nav Menu Roles Instance
	*
	* Ensures only one instance of Nav Menu Roles is loaded or can be loaded.
	*
	* @since 1.5
	* @static
	* @see Nav_Menu_Roles()
	* @return Nav_Menu_Roles - Main instance
	*/
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	* Cloning is forbidden.
	*
	* @since 1.5
	*/
	public function __clone() {
		_doing_it_wrong( __FUNCTION__, __( 'Cheatin’ huh?' , 'nav-menu-roles'), '1.5' );
	}

	/**
	* Unserializing instances of this class is forbidden.
	*
	* @since 1.5
	*/
	public function __wakeup() {
		_doing_it_wrong( __FUNCTION__, __( 'Cheatin’ huh?' , 'nav-menu-roles'), '1.5' );
	}

	/**
	* Nav_Menu_Roles Constructor.
	* @access public
	* @return Nav_Menu_Roles
	* @since  1.0
	*/
	function __construct(){

		// Admin functions
		add_action( 'admin_init', array( $this, 'admin_init' ) );

		// load the textdomain
		add_action( 'plugins_loaded', array( $this, 'load_text_domain' ) );

		// add a notice that NMR is conflicting with another plugin
		add_action( 'admin_notices', array( $this, 'admin_notice' ) );
		add_action( 'activated_plugin', array( $this, 'delete_transient' ) );
		add_action( 'deactivated_plugin', array( $this, 'delete_transient' ) );

		// switch the admin walker
		add_filter( 'wp_edit_nav_menu_walker', array( $this, 'edit_nav_menu_walker' ) );

		// add new fields via hook
		add_action( 'wp_nav_menu_item_custom_fields', array( $this, 'custom_fields' ), 10, 4 );

		// add some JS
		add_action( 'admin_enqueue_scripts' , array( $this, 'enqueue_scripts' ) );

		// save the menu item meta
		add_action( 'wp_update_nav_menu_item', array( $this, 'nav_update'), 10, 2 );

		// add meta to menu item
		add_filter( 'wp_setup_nav_menu_item', array( $this, 'setup_nav_item' ) );

		// exclude items via filter instead of via custom Walker
		if ( ! is_admin() ) {
			add_filter( 'wp_get_nav_menu_items', array( $this, 'exclude_menu_items' ) );
		}

	}

	/**
	* Include the custom admin walker
	*
	* @access public
	* @return void
	*/
	function admin_init() {
		include_once( plugin_dir_path( __FILE__ ) . 'inc/class.Walker_Nav_Menu_Edit_Roles.php');

		// Register Importer
		$this->register_importer();

		// save user notice
		$this->nag_ignore();
	}

	/**
	* Register the Importer
	* the regular Importer skips post meta for the menu items
	*
	* @access private
	* @return void
	*/
	function register_importer(){

		include_once( plugin_dir_path( __FILE__ ) . 'inc/class.Nav_Menu_Roles_Import.php');

		// Register the new importer
		if ( defined( 'WP_LOAD_IMPORTERS' ) ) {

			// Register the custom importer we've created.
			$roles_import = new Nav_Menu_Roles_Import();

			register_importer('nav_menu_roles', __('Nav Menu Roles', 'nav-menu-roles'), sprintf( __('Import %snav menu roles%s and other menu item meta skipped by the default importer', 'nav-menu-roles'), '', ''), array( $roles_import, 'dispatch' ) );

		}

	}

	/**
	* Make Plugin Translation-ready
	* CALLBACK FUNCTION FOR:  add_action( 'plugins_loaded', array( $this,'load_text_domain'));
	* @since 1.0
	*/

	function load_text_domain() {
		load_plugin_textdomain( 'nav-menu-roles', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
	}

	/**
	* Display a Notice if plugin conflicts with another
	* @since 1.5
	*/
	function admin_notice() {
		global $pagenow, $wp_filter;

		// quit early if not on the menus page
		if( ! in_array( $pagenow, array( 'nav-menus.php', 'plugins.php' ) ) ){
			return;
		}

		// Get any existing copy of our transient data
		if ( false === ( $conflicts = get_transient( 'nav_menu_roles_conflicts' ) ) ) {

			// It wasn't there, so regenerate the data and save the transient
			global $wp_filter;

			$filters = is_array( $wp_filter['wp_edit_nav_menu_walker'] ) ? array_shift( $wp_filter['wp_edit_nav_menu_walker'] ) : array();

			foreach( $filters as $filter ){
				// we expect to see NVR so collect everything else
				if( ! is_a( $filter['function'][0], 'Nav_Menu_Roles') ) {
					$conflicts[] = is_object( $filter['function'][0] ) ? get_class( $filter['function'][0] ) : $filter['function'][0];
				}

			}
		}

		// Check Transient for conflicts and show error
		if ( ! empty ( $conflicts ) ) {
			global $current_user ;
			$user_id = $current_user->ID;

			if ( ! get_user_meta( $user_id, 'nmr_ignore_notice' ) ) {

				echo '

';
				printf ( __( 'Nav Menu Roles has detected a possible conflict with the following functions or classes: %1$s. Please see the %2$sFAQ%3$s for more information and possible resolution. | %4$sHide Notice%3$s', 'nav-menu-roles' ),
				'' . implode( $conflicts, ', ' ) . '',
				'',
				'',
				'' );
				echo '

';

			}

		}

	}

	/**
	* Allow the notice to be dismissable
	* @since 1.6
	*/
	function nag_ignore() {
		global $current_user;
		$user_id = $current_user->ID;
		/* If user clicks to ignore the notice, add that to their user meta */
		if ( isset($_GET['nmr_nag_ignore']) && '0' == $_GET['nmr_nag_ignore'] ) {
			add_user_meta( $user_id, 'nmr_ignore_notice', 'true', true );
		}
	}

	/**
	* Delete the transient when a plugin is activated or deactivated
	* @since 1.5
	*/
	function delete_transient() {
		delete_transient( 'nav_menu_roles_conflicts' );
	}

	/**
	* Override the Admin Menu Walker
	* @since 1.0
	*/
	function edit_nav_menu_walker( $walker ) {
		return 'Walker_Nav_Menu_Edit_Roles';
	}

	/**
	* Add fields to hook added in Walker
	* This will allow us to play nicely with any other plugin that is adding the same hook
	* @params obj $item - the menu item
	* @params array $args
	* @since 1.6.0
	*/
	function custom_fields( $item_id, $item, $depth, $args ) {
		global $wp_roles;

		/**
		* Pass the menu item to the filter function.
		* This change is suggested as it allows the use of information from the menu item (and
		* by extension the target object) to further customize what filters appear during menu
		* construction.
		*/
		$display_roles = apply_filters( 'nav_menu_roles', $wp_roles->role_names, $item );

		/**
		* If no roles are being used, don't display the role selection radio buttons at all.
		* Unless something deliberately removes the WordPress roles from this list, nothing will
		* be functionally altered to the end user.
		* This change is suggested for the benefit of users constructing granular admin permissions
		* using extensive custom roles as it is an effective means of stopping admins with partial
		* permissions to the menu from accidentally removing all restrictions from a menu item to
		* which they do not have access.
		*/
		if( ! $display_roles ) return;

		/* Get the roles saved for the post. */
		$roles = get_post_meta( $item->ID, '_nav_menu_role', true );

		$checked_roles = is_array( $roles ) ? $roles : false;

		$logged_in_out = ! is_array( $roles ) ? $roles : false;

		?>

		<input type="hidden" name="nav-menu-role-nonce" value="<?php echo wp_create_nonce( 'nav-menu-nonce-name' ); ?>" />

		    <?php _e( "Display Mode", 'nav-menu-roles' ); ?>

		    <input type="hidden" class="nav-menu-id" value="<?php echo $item->ID ;?>" />

		        <input type="radio" class="nav-menu-logged-in-out" name="nav-menu-logged-in-out[<?php echo $item->ID ;?>]" id="nav_menu_logged_out-for-<?php echo $item->ID ;?>" <?php checked( 'out', $logged_in_out ); ?> value="out" />
		        <label for="nav_menu_logged_out-for-<?php echo $item->ID ;?>">
		            <?php _e( 'Logged Out Users', 'nav-menu-roles'); ?>

		        <input type="radio" class="nav-menu-logged-in-out" name="nav-menu-logged-in-out[<?php echo $item->ID ;?>]" id="nav_menu_logged_in-for-<?php echo $item->ID ;?>" <?php checked( 'in', $logged_in_out ); ?> value="in" />
		        <label for="nav_menu_logged_in-for-<?php echo $item->ID ;?>">
		            <?php _e( 'Logged In Users', 'nav-menu-roles'); ?>

		        <input type="radio" class="nav-menu-logged-in-out" name="nav-menu-logged-in-out[<?php echo $item->ID ;?>]" id="nav_menu_by_role-for-<?php echo $item->ID ;?>" <?php checked( '', $logged_in_out ); ?> value="" />
		        <label for="nav_menu_by_role-for-<?php echo $item->ID ;?>">
		            <?php _e( 'By Role', 'nav-menu-roles'); ?>

		    <?php _e( "Access Role", 'nav-menu-roles' ); ?>

		    <?php

		    /* Loop through each of the available roles. */
		    foreach ( $display_roles as $role => $name ) {

		        /* If the role has been selected, make sure it's checked. */
		        $checked = checked( true, ( is_array( $checked_roles ) && in_array( $role, $checked_roles ) ), false );

		        ?>

		        <input type="checkbox" name="nav-menu-role[<?php echo $item->ID ;?>][<?php echo $role; ?>]" id="nav_menu_role-<?php echo $role; ?>-for-<?php echo $item->ID ;?>" <?php echo $checked; ?> value="<?php echo $role; ?>" />
		        <label for="nav_menu_role-<?php echo $role; ?>-for-<?php echo $item->ID ;?>">
		        <?php echo esc_html( $name ); ?>

		<?php } ?>

		<?php
	}

	/**
	* Save the roles as menu item meta
	* @return null
	* @since 1.4
	*
	*/
	function enqueue_scripts( $hook ){
		if ( $hook == 'nav-menus.php' ){
			$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
			wp_enqueue_script( 'nav-menu-roles', plugins_url( 'js/nav-menu-roles' . $suffix . '.js' , __FILE__ ), array( 'jquery' ), '1.5', true );
		}
	}

	/**
	* Save the roles as menu item meta
	* @return string
	* @since 1.0
	*/
	function nav_update( $menu_id, $menu_item_db_id ) {
		global $wp_roles;

		$allowed_roles = apply_filters( 'nav_menu_roles', $wp_roles->role_names );

		// verify this came from our screen and with proper authorization.
		if ( ! isset( $_POST['nav-menu-role-nonce'] ) || ! wp_verify_nonce( $_POST['nav-menu-role-nonce'], 'nav-menu-nonce-name' ) )
			return;

		$saved_data = false;

		if ( isset( $_POST['nav-menu-logged-in-out'][$menu_item_db_id]  )  && in_array( $_POST['nav-menu-logged-in-out'][$menu_item_db_id], array( 'in', 'out' ) ) ) {
			$saved_data = $_POST['nav-menu-logged-in-out'][$menu_item_db_id];
		} elseif ( isset( $_POST['nav-menu-role'][$menu_item_db_id] ) ) {
			$custom_roles = array();
			// only save allowed roles
			foreach( $_POST['nav-menu-role'][$menu_item_db_id] as $role ) {
				if ( array_key_exists ( $role, $allowed_roles ) ) $custom_roles[] = $role;
			}
			if ( ! empty ( $custom_roles ) ) $saved_data = $custom_roles;
		}

		if ( $saved_data ) {
			update_post_meta( $menu_item_db_id, '_nav_menu_role', $saved_data );
		} else {
			delete_post_meta( $menu_item_db_id, '_nav_menu_role' );
		}
	}

	/**
	* Adds value of new field to $item object
	* is be passed to Walker_Nav_Menu_Edit_Custom
	* @since 1.0
	*/
	function setup_nav_item( $menu_item ) {

		$roles = get_post_meta( $menu_item->ID, '_nav_menu_role', true );

		if ( ! empty( $roles ) ) {
			$menu_item->roles = $roles;
		}
		return $menu_item;
	}

	/**
	* Exclude menu items via wp_get_nav_menu_items filter
	* this fixes plugin's incompatibility with theme's that use their own custom Walker
	* Thanks to Evan Stein @vanpop http://vanpop.com/
	* @since 1.2
	*/
	function exclude_menu_items( $items ) {

		$hide_children_of = array();

		// Iterate over the items to search and destroy
		foreach ( $items as $key => $item ) {

			$visible = true;

			// hide any item that is the child of a hidden item
			if( in_array( $item->menu_item_parent, $hide_children_of ) ){
				$visible = false;
				$hide_children_of[] = $item->ID; // for nested menus
			}

			// check any item that has NMR roles set
			if( $visible && isset( $item->roles ) ) {

				// check all logged in, all logged out, or role
				switch( $item->roles ) {
					case 'in' :
					$visible = is_user_logged_in() ? true : false;
						break;
					case 'out' :
					$visible = ! is_user_logged_in() ? true : false;
						break;
					default:
						$visible = false;
						if ( is_array( $item->roles ) && ! empty( $item->roles ) ) {
							foreach ( $item->roles as $role ) {
								if ( current_user_can( $role ) )
									$visible = true;
							}
						}

						break;
				}

			}

			// add filter to work with plugins that don't use traditional roles
			$visible = apply_filters( 'nav_menu_roles_item_visibility', $visible, $item );

			// unset non-visible item
			if ( ! $visible ) {
				$hide_children_of[] = $item->ID; // store ID of item
				unset( $items[$key] ) ;
			}

		}

		return $items;
}

} // end class

endif; // class_exists check

/**
* Launch the whole plugin
 * Returns the main instance of Nav Menu Roles to prevent the need to use globals.
 *
 * @since  1.5
 * @return Nav_Menu_Roles
*/
function Nav_Menu_Roles() {
	return Nav_Menu_Roles::instance();
}

// Global for backwards compatibility.
$GLOBALS['Nav_Menu_Roles'] = Nav_Menu_Roles();


text:
<?php

use yii\db\Migration;

class m161229_141407_addcol_to_paytype extends Migration
{
    public function up()
    {
        //$this->addColumn('{{%post}}', 'def', $this->integer()->comment('Использовать по умолчанию'));
        $this->addColumn('{{%pay_type}}', 'def', $this->integer()->comment('Использовать по умолчанию'));
    }

    public function down()
    {
        //$this->dropColumn('{{%post}}', 'def');
        $this->dropColumn('{{%pay_type}}', 'def');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
#pragma once

#include "../../../kinetis/include/px4_arch/io_timer.h"


text:
import pprint

import attr

class _unset(object):
    def __nonzero__(self):
        return False
unset = _unset()

_tristate = attr.validators.in_((True, False, unset))

@attr.s
class AttributeSet(object):
    """
    @ivar bold: True, False, or unset, indicating whether characters
    with these attributes will be bold, or if boldness should be
    inherited from the previous setting.

    @ivar underline: Similar to C{bold} but indicating the underlined
    state of characters.

    @ivar reverseVideo: Similar to C{bold} but indicating whether
    reverse video should be applied.

    @ivar blink: Similar to C{bold} but indicating whether foreground
    material should blink.

    @ivar fg: An integer between 0 and 9 inclusive or unset.
    Integer values indicate a color setting for the foreground,
    whereas unset indicates foreground color should be inherited from
    the previous settings.

    @ivar bg: Like C{fg} but for background color.
    """
    bold = attr.ib(default=False, validator=_tristate)
    underline = attr.ib(default=False, validator=_tristate)
    reverseVideo = attr.ib(default=False, validator=_tristate)
    blink = attr.ib(default=False, validator=_tristate)
    fg = attr.ib(
        default="9",
        validator=attr.validators.in_([unset] + list("012345679")),
    )
    bg = attr.ib(
        default="9",
        validator=attr.validators.in_([unset] + list("012345679")),
    )

    def __len__(self):
        return 6

    def __getitem__(self, index):
        return [self.bold, self.underline, self.reverseVideo, self.blink, self.fg, self.bg][index]

    def __setitem__(self, index, value):
        setattr(self, ['bold', 'underline', 'reverseVideo', 'blink', 'fg', 'bg'][index], value)

    def clone(self):
        return self.__class__(*self)

    def update(self, other):
        for i in range(len(self)):
            if other[i] is not unset:
                self[i] = other[i]
        return self

    _flags = {'bold': '1', 'underline': '4', 'reverseVideo': '7', 'blink': '5'}
    def toVT102(self, state):
        passive = []
        active = []
        reset = False

        for attr_ in 'bold', 'underline', 'reverseVideo', 'blink':
            was = getattr(state, attr_)
            willBe = getattr(self, attr_)

            if was is unset:
                if willBe is unset:
                    # Absolutely nothing to do here.
                    pass
                elif willBe:
                    # We're going to turn it on.  Yay.
                    active.append(self._flags[attr_])
                else:
                    # We're going to turn it off.  Yay.
                    reset = True
            elif was:
                if willBe is unset:
                    # Who cares!  But make a note.
                    passive.append(self._flags[attr_])
                elif willBe:
                    # Nothing to do!  But make a note.
                    passive.append(self._flags[attr_])
                else:
                    # Time to destroy!  Zoom.
                    reset = True
            else:
                if willBe is unset:
                    # Big woop!  Die.
                    pass
                elif willBe:
                    # Enablement now.
                    active.append(self._flags[attr_])
                else:
                    # Consensus is neat.
                    pass

        for x, attr_ in ('3', 'fg'), ('4', 'bg'):
            was = getattr(state, attr_)
            willBe = getattr(self, attr_)

            if was is unset:
                if willBe is unset:
                    # Boringly do nothing.
                    pass
                elif willBe == '9':
                    # Again there is no work.
                    pass
                else:
                    # Wee it is time for colorizing.
                    active.append(x + willBe)
            elif was == '9':
                if willBe is unset:
                    # We don't care.  Snore.
                    pass
                elif willBe == '9':
                    # We are happily already in the state desired.
                    pass
                else:
                    # Time for mashin'.
                    active.append(x + willBe)
            else:
                if willBe is unset:
                    # We don't care about the color.
                    passive.append(x + was)
                elif willBe == '9':
                    # Reset the entire state to put this back to normal
                    reset = True
                elif willBe == was:
                    # It is correct already.  Good night.
                    passive.append(x + was)
                else:
                    # Just switch the color
                    active.append(x + willBe)

        if reset:
            active.extend(passive)
            active.insert(0, '0')

        if active:
            return '\x1b[' + ';'.join(active) + 'm'
        return ''

class AttributeStack(object):
    def __init__(self, initialAttributes):
        self._stack = [initialAttributes]

    def __repr__(self):
        return pprint.pformat(self._stack)

    def __len__(self):
        return len(self._stack)

    def push(self, attrs):
        self._stack.append(self.get().clone().update(attrs))

    def duptop(self):
        self._stack.append(self.get().clone())

    def update(self, attrs):
        self.get().update(attrs)

    def pop(self):
        return self._stack.pop()

    def get(self):
        return self._stack[-1]

class fg:
    pass

class bg:
    pass

neutral = AttributeSet(unset, unset, unset, unset, unset, unset)

def _setup():
    for cls, attr_ in [(fg, 'fg'),
                      (bg, 'bg')]:
        for n, color in enumerate(['black', 'red', 'green', 'yellow', 'blue',
                                   'magenta', 'cyan', 'white']):
            value = neutral.clone()
            setattr(value, attr_, str(n))
            setattr(cls, color, value)
        cls.normal = neutral.clone()
        setattr(cls.normal, attr_, '9')

    for attr_ in 'bold', 'blink', 'reverseVideo', 'underline':
        value = neutral.clone()
        setattr(value, attr_, True)
        globals()[attr_] = value
_setup()
del _setup

def flatten(dag, currentAttrs=None, useColors=True):
    # XXX TODO: Add unicode handling!
    """
    Serialize a tree of strings and terminal codes to an iterable of strings,
    ready to be written to your favorite terminal device.

    @type currentAttrs: L{AttributeSet}
    @param currentAttrs: The current set of attributes.

    @param useColors: If False, terminal codes will be left out.
    """
    if currentAttrs is None:
        if not useColors:
            currentAttrs = AttributeSet()
        else:
            raise TypeError("currentAttrs is required when useColors is False")
    attrs = AttributeStack(currentAttrs)
    attrs.duptop()

    stack = [iter(dag)]
    dirty = False
    while stack:
        try:
            obj = stack[-1].next()
        except StopIteration:
            stack.pop()
            attrs.pop()
            if len(attrs):
                if useColors:
                    dirty = bool(attrs.get().toVT102(currentAttrs))
        else:
            if isinstance(obj, AttributeSet):
                attrs.update(obj)
                if useColors:
                    dirty = bool(attrs.get().toVT102(currentAttrs))
            elif isinstance(obj, (str, unicode)):
                if obj:
                    if dirty:
                        if useColors:
                            yield attrs.get().toVT102(currentAttrs)
                        currentAttrs = attrs.get().clone()
                        dirty = False
                    yield obj
            else:
                try:
                    newIter = iter(obj)
                except TypeError:
                    if dirty:
                        if useColors:
                            yield attrs.get().toVT102(currentAttrs)
                        currentAttrs = attrs.get().clone()
                        dirty = False
                    yield obj
                else:
                    stack.append(newIter)
                    attrs.duptop()
    if dirty and len(attrs):
        if useColors:
            yield attrs.get().toVT102(currentAttrs)

__all__ = [
    'fg', 'bg',
    'flatten']


text:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

//  middleware bodyParser()
//  POST
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

var port = process.env.PORT || 8888;

//路由
require('./routes/users.routes.js')(app);

//开启server
app.listen(port);
console.log('server start on port ' + port);


text:
#include "Sorting.h"

/************************************  bubble_sort  *************************************/

// worst case	Theta(n^2)
// best case	Theta(n)
std::vector<int> Sorting::bubble_sort(std::vector<int> A){

	// outer loop, after one loop one value will be in correct place
	for (int i = 0; i < A.size(); i++){
		bool swapped = false;

		// inner loop, swap adjacent items if left one is greater than right one
		for (int j = 0; j < A.size()-1; j++){
			if (A[j] > A[j+1]){
				int temp = A[j];
				A[j] = A[j+1];
				A[j+1] = temp;
				swapped = true;
			}
		}

		// break outer loop if no changes were made in the outer loop iteration (sorting finished)
		if (!swapped){
			break;
		}
	}

	// A is now sorted
	return A;
}

/************************************  selection_sort  *************************************/

// worst case	Theta(n^2)
// best case	Theta(n^2)
std::vector<int> Sorting::selection_sort(std::vector<int> A){

	// get the index of the minimum value between the i'th value and the last value
	for (int i = 0; i < A.size()-1; i++){
		int min = i;

		// update the minimum index if we find a smaller value than the value at the current min index
		for (int j = i + 1; j < A.size(); j++){
			if (A[j] < A[min]){
				min = j;
			}
		}

		// swap the i'th value with minimum value found in this iteration
		int temp = A[i];
		A[i] = A[min];
		A[min] = temp;
	}

	// A is now sorted
	return A;
}

/************************************  insertion_sort  *************************************/

// worst case:	Theta(n^2)
// best case:	Theta(n)
std::vector<int> Sorting::insertion_sort(std::vector<int> A){

	// "insert" each value starting from the 2nd value in the array
	for (int i = 1; i < A.size(); i++){

		// save a copy of the i'th value so we can place it accordingly at the end of the iteration
		int val = A[i];

		// look at the values to the left of 'i' and shift values one to the right until we see a value less than our stored copy or until we've shifted all values
		int j = i - 1;
		while (j >= 0 && A[j] > val){
			A[j+1] = A[j];
			j--;
		}

		// 'j+1' holds the index where the copy should be placed. Everything to the left of this index is sorted.
		A[j+1] = val;
	}

	// A is now sorted
	return A;
}

/************************************  merge_sort  *************************************/

// worst case:	Theta(nlogn)
// best case:	Theta(nlogn)
std::vector<int> Sorting::merge_sort(std::vector<int> A){

	// stop recursively calling once the argument is of size 1, and return that 1-item argument
	if (A.size() == 1){
		return A;
	}

	// otherwise, split the argument into two vectors
	int middle = (A.size()+1) / 2;
	std::vector<int> ALeft(A.begin(), A.begin()+middle);
	std::vector<int> ARight(A.begin()+middle, A.end());

	// recursively call merge_sort on each half of the argument
	ALeft = Sorting::merge_sort(ALeft);
	ARight = Sorting::merge_sort(ARight);

	// merge the two sorted halves into one sorted vector
	return Sorting::merge(ALeft, ARight);
}

std::vector<int> Sorting::merge(std::vector<int> ALeft, std::vector<int> ARight){

	// The merged vector that will be sorted (as long as the arguments are sorted)
	std::vector<int> result;

	// Method 1
	// advantage: the push_back method is amortized constant time
	//			  and as a result, the merge operation takes only Theta(n)

	// keep track of the size of each "half" (the left vector and the right vector)
	int ALSize = ALeft.size();
	int ARSize = ARight.size();

	// keep track of which values in each vector are to be pushed_back next into the result
	int ALIndex = 0;
	int ARIndex = 0;

	// keep on pushing values into the result while there are any that haven't been pushed yet
	while (ALSize > 0 || ARSize > 0){

		// if both halves still have values to be pushed, push the smaller one. If they're equal, push both
		if (ALSize > 0 && ARSize > 0){
			if (ALeft[ALIndex] < ARight[ARIndex]){
				result.push_back(ALeft[ALIndex]);
				ALSize--;
				ALIndex++;
			} else if (ALeft[ALIndex] > ARight[ARIndex]){
				result.push_back(ARight[ARIndex]);
				ARSize--;
				ARIndex++;
			} else{
				result.push_back(ALeft[ALIndex]);
				result.push_back(ARight[ARIndex]);
				ALSize--;
				ARSize--;
				ALIndex++;
				ARIndex++;
			}

		// else if only the left half has values remaining to be pushed, push them
		} else if (ALSize > 0){
			result.push_back(ALeft[ALIndex]);
			ALIndex++;
			ALSize--;

		// else if only the right half has values remaining to be pushed, push them
		} else if (ARSize > 0){
			result.push_back(ARight[ARIndex]);
			ARIndex++;
			ARSize--;
		}
	}

	/*
	// For readability
	// downside: each time we erase, we have to copy all items to the right of the 1st element into a new array, resulting in an O(n) operation
	//			 and as a result the merge operation takes O(n^2) instead of O(n)
	while (ALeft.size() > 0 || ARight.size() > 0){
		if (ALeft.size() > 0 && ARight.size() > 0){
			if (ALeft.front() < ARight.front()){
				result.push_back(ALeft.front());
				ALeft.erase(ALeft.begin());
			} else if (ALeft.front() > ARight.front()){
				result.push_back(ARight.front());
				ARight.erase(ARight.begin());
			} else{
				result.push_back(ALeft.front());
				ALeft.erase(ALeft.begin());
				result.push_back(ARight.front());
				ARight.erase(ARight.begin());
			}
		} else if (ALeft.size() > 0){
			result.push_back(ALeft.front());
			ALeft.erase(ALeft.begin());
		} else if (ARight.size() > 0){
			result.push_back(ARight.front());
			ARight.erase(ARight.begin());
		}
	}
	*/

	// result contains the merged and sorted vector
	return result;

}

/************************************  quick_sort  *************************************/

// worst case:	Theta(n^2)
// best case:	Theta(nlogn)
std::vector<int> Sorting::quick_sort(std::vector<int> A, int left, int right){

	// When quicksort is first called, no argument other than A needs to be given.
	// The index of the rightmost element is assigned to 'right'
	if (right == -100){
		right = A.size()-1;
	}

	// if the subvector to be worked on is of size > 1, recurse further. Otherwise don't do anything
	if (left < right){

		// in the subvector, find at what index the right-most value was placed
		int pivot = Sorting::partition(A, left, right);

		// recurse on the subvector left of the pivot and on the subvector right of the pivot
		A = Sorting::quick_sort(A, left, pivot-1);
		A = Sorting::quick_sort(A, pivot+1, right);
	}

	// A is now the sorted subvector
	return A;
}

// worst case:	Theta(n^2) (already sorted or reverse sorted):
// best case:	Theta(nlogn)
// The vector is sorted in place, no extra vectors are needed (saves memory)
void Sorting::quick_sort_in_place(std::vector<int>& A, int left, int right){

	// When quicksort is first called, no argument other than A needs to be given.
	// The index of the rightmost element is assigned to 'right'
	if (right == -100){
		right = A.size()-1;
	}

	// if the subvector to be worked on is of size > 1, recurse further. Otherwise don't do anything
	if (left < right){

		// in the subvector, find at what index the right-most value was placed
		int pivot = Sorting::partition(A, left, right);

		// recurse on the subvector left of the pivot and on the subvector right of the pivot
		Sorting::quick_sort_in_place(A, left, pivot-1);
		Sorting::quick_sort_in_place(A, pivot+1, right);
	}
}

// complexity:	Theta(n)
int Sorting::partition(std::vector<int>& A, int left, int right){

	// initialize index to the left-most index
	int index = left;

	// everything to the left of index is <= to the pivot (right-most element)
	for (int i = left; i < right; i++){
		if (A[i] <= A[right]){
			int temp = A[i];
			A[i] = A[index];
			A[index] = temp;
			index++;
		}
	}

	// swap the pivot with the value at the updated index
	int temp = A[index];
	A[index] = A[right];
	A[right] = temp;

	// this is where A will be partitioned
	return index;
}

/************************************  counting_sort  *************************************/

// worst case:	Theta(n+m) (m is the range of values in A)
// best case:	Theta(n+m)
std::vector<int> Sorting::counting_sort(std::vector<int> A){

	// return empty vector if input is empty
	if (A.empty()){
		return A;
	}

	// get min and max values
	int min = A[0];
	int max = A[0];
	for (int i = 0; i < A.size(); i++){
		if (A[i] > max){
			max = A[i];
		}
		if (A[i] < min){
			min = A[i];
		}
	}

	// fill a new vector of counters with zeros to hold a counter for each unique numbers in A
	int diff = max - min;
	std::vector<int> count(diff+1, 0);

	// as we iterate through A, update the counters by incrementing their corresponding values
	// using min as an offset allows us to sort vectors with negative numbers
	for (int i = 0; i < A.size(); i++){
		count[A[i]-min]++;
	}

	// empty A so that it can be rebuilt in sorted order
	A.clear();

	// iterate through the counters, pushing index i+min (offset taken care of) as many times as they were counted
	for (int i = 0; i < count.size(); i++){
		while (count[i] > 0){
			A.push_back(i+min);
			count[i]--;
		}
	}

	// A is now sorted
	return A;
}

/************************************  radix_sort (LSD) *************************************/

// worst case:	Theta(k(n+a)) where k is the max number of digits, n is the number of items in A, and a is the alphabet count
// best case:	Theta(k(n+a))
// supports only bases 1 through 10
// supports nonnegative integers only
std::vector<int> Sorting::radix_sort(std::vector<int> A, int base){

	// check for empty input vector or invalid base
	if (A.empty() || base < 1 || base > 10){
		std::cout << "Error: empty vector or invalid/unsupported base" << std::endl;
		return A;
	}

	// vector of buckets. 1 bucket for each possible digit value
	std::vector<std::list<int> > buckets(base, std::list<int>());

	// determine the max in order to determine number of digits we must iterate through
	int max = A[0];
	for (int i = 0; i < A.size(); i++){
		if (A[i] > max){
			max = A[i];
		}
	}

	// determine number of digits of the max number
	int digits = 0;
	while (max > 0){
		max = max / 10;
		digits++;
	}

	// mod by 10 to get the right most digit. divide by divisor (n^10) to cut off n digits
	const int mod = 10;
	int divisor = 1;

	// place into buckets and then pull out from buckets as many times as there are digits in the max number
	for (int i = 0; i < digits; i++){

		// place into buckets
		for (int j = 0; j < A.size(); j++){
			int index = (A[j] / divisor) % mod;
			(buckets[index]).push_back(A[j]);
		}

		// update A by pulling out from the buckets
		int location = 0;
		for (int j = 0; j < buckets.size(); j++){
			while (!(buckets[j]).empty()){
				A[location] = (buckets[j]).front();
				(buckets[j]).pop_front();
				location++;
			}
		}

		// update divisor in order to look at the next LSD in next iteration
		divisor *= 10;
	}

	// A is now sorted
	return A;
}

/************************************  bucket_sort  *************************************/

// For numbers evenly distributed from (0, 1]
// worst case:	Theta(n^2)
// best case:	Theta(n+k)
std::vector<float> Sorting::bucket_sort(std::vector<float> A){

	// return empty vector if input is empty
	if (A.empty()){
		return A;
	}

	// set up buckets
	const int num_buckets = A.size();
	std::vector<std::list<float> > buckets(num_buckets, std::list<float>());

	// place elements in corresponding buckets
	for (int i = 0; i < A.size(); i++){
		int index = static_cast<int>(A[i] * static_cast<float>(num_buckets));
		(buckets[index]).push_back(A[i]);
	}

	// sort buckets and rewrite A in sorted order
	int location = 0;
	for (int i = 0; i < buckets.size(); i++){
		(buckets[i]).sort();
		while (!(buckets[i]).empty()){
			A[location] = (buckets[i]).front();
			buckets[i].pop_front();
			location++;
		}
	}

	// A is now sorted
	return A;
}


text:
set -eux

PYBIN="/opt/python/${PYTHON_TAG}/bin/python"

# modern tools don't allow us to pass eg, --with-libyaml, so we force it via env
export PYYAML_FORCE_CYTHON=1
export PYYAML_FORCE_LIBYAML=1

# we're using a private build of libyaml, so set paths to favor that instead of whatever's laying around
export C_INCLUDE_PATH=libyaml/include:${C_INCLUDE_PATH:-}
export LIBRARY_PATH=libyaml/src/.libs:${LIBRARY_PATH:-}
export LD_LIBRARY_PATH=libyaml/src/.libs:${LD_LIBRARY_PATH:-}

# install deps
echo "::group::installing build deps"
# FIXME: installing Cython here won't be necessary once we fix tests, since the build is PEP517 and declares its own deps
"${PYBIN}" -m pip install build==0.1.0 Cython
echo "::endgroup::"

if [[ ${PYYAML_RUN_TESTS:-1} -eq 1 ]]; then
  echo "::group::running test suite"
  # FIXME: split tests out for easier direct execution w/o Makefile
  # run full test suite
  make testall PYTHON="${PYBIN}"
  echo "::endgroup::"
else
  echo "skipping test suite..."
fi

if [[ ${PYYAML_BUILD_WHEELS:-0} -eq 1 ]]; then
  echo "::group::building wheels"
  "${PYBIN}" -m build -w -o tempwheel .
  echo "::endgroup::"

  echo "::group::validating wheels"

  for whl in tempwheel/*.whl; do
    auditwheel repair --plat "${AW_PLAT}" "$whl" -w dist/
  done

  # ensure exactly one finished artifact
  shopt -s nullglob
  DISTFILES=(dist/*.whl)
  if [[ ${#DISTFILES[@]} -ne 1 ]]; then
    echo -e "unexpected dist content:\n\n$(ls)"
    exit 1
  fi

  "${PYBIN}" -m pip install dist/*.whl

  "${PYBIN}" packaging/build/smoketest.py

  ls -1 dist/

  echo "::endgroup::"

else
  echo "skipping wheel build..."
fi


text:
CodeWave is small and easy to use framework.

Originally the project was inspired by slim, hence used to have many similar features, but
that time is long gone. Now the framework's goal is to provide something, which other devs
might find useful along the way or at least give them an idea, that there is always a
different approach.

## Should I worry about the abandoned previous versions
Short answer is "No, you shouldn't", but you can if you insist. The situation with the old versions
is that, there was no community to drive them and version 2 went very, very wrong in after 2.4.0.

There ware bad decisions made, and supported and eventually they ate the version, hence could not be fixed
 without major breaks, which don't make too much sense as API changes and BC breaks should happen only in
 major versions, as per [Semantic Versioning](http://semver.org/).
 Keeping that in mind, there was a huge need to fix the mistakes. That is why v3 is not tagged still.
 A lot of planning is going on and many experiments before something actually makes it to the commit.
 Which results in not so many commits (Note to self, stop forgetting PSR2 validation before pushing).

 That said, you should feel perfectly safe with v3, it is not going to change for quite some time and if it does,
 well it will receive its proper support and maintenance (v2 will also get this if someone is interested in fixing the
 things I messed up with).

## Notable features in v3
 - Huge decoupling: this was supposed to be the case even in v2, but as I said above: 'There ware bad decisions made, and supported'
 - Swappable routing: The route dispatcher is instantiated using a callback, which allows it to be changed with almost everything.
 - Semi-middleware (Value Middleware, i.e Decorators): These decorators, are more of value decorators, as their intent is to allow, developers to
 reuse common logic, like decoding a base64 encoded json string and returning the json array/object(it is a minimal example). [ WIP :construction: ]

## Installation
Just add `"codewave/codewave": "@stable"` to your composer.json required section and use `composer update` to install

## Documentation
Will follow shortly, just have to make the finishing touches and it will be added.
But if you are not patient enough to wait for stable, want to see for your self what is
going on or you are interested in helping with the project, here is [the code to get you started](https://gist.github.com/DaGhostman/4217ca38261101a42864).

## Contributors
  - Dimitar Dimitrov a.k.a DaGhostman <daghostman[at]gmail.com>

### Stats
 [![Latest Stable Version](https://poser.pugx.org/codewave/codewave/v/stable.svg)](https://packagist.org/packages/codewave/codewave)

 [![Total Downloads](https://poser.pugx.org/codewave/codewave/downloads.svg)](https://packagist.org/packages/codewave/codewave)

 [![Build Status](https://travis-ci.org/DaGhostman/codewave.svg?branch=master)](https://travis-ci.org/DaGhostman/codewave)

 [![Coverage Status](https://coveralls.io/repos/DaGhostman/codewave/badge.svg)](https://coveralls.io/r/DaGhostman/codewave)

 [![License](https://poser.pugx.org/codewave/codewave/license.svg)](https://packagist.org/packages/codewave/wavecode)


text:
package okhttp3.internal.huc;

import okhttp3.Handshake;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.security.Permission;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSocketFactory;

/**
 * Implement an HTTPS connection by delegating to an HTTP connection for
 * everything but the HTTPS-specific stuff.
 */
abstract class DelegatingHttpsURLConnection extends HttpsURLConnection {
  private final HttpURLConnection delegate;

  public DelegatingHttpsURLConnection(HttpURLConnection delegate) {
    super(delegate.getURL());
    this.delegate = delegate;
  }

  protected abstract Handshake handshake();

  @Override public abstract void setHostnameVerifier(HostnameVerifier hostnameVerifier);

  @Override public abstract HostnameVerifier getHostnameVerifier();

  @Override public abstract void setSSLSocketFactory(SSLSocketFactory sslSocketFactory);

  @Override public abstract SSLSocketFactory getSSLSocketFactory();

  @Override public String getCipherSuite() {
    Handshake handshake = handshake();
    return handshake != null ? handshake.cipherSuite().javaName() : null;
  }

  @Override public Certificate[] getLocalCertificates() {
    Handshake handshake = handshake();
    if (handshake == null) return null;
    List<Certificate> result = handshake.localCertificates();
    return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null;
  }

  @Override public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
    Handshake handshake = handshake();
    if (handshake == null) return null;
    List<Certificate> result = handshake.peerCertificates();
    return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null;
  }

  @Override public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
    Handshake handshake = handshake();
    return handshake != null ? handshake.peerPrincipal() : null;
  }

  @Override public Principal getLocalPrincipal() {
    Handshake handshake = handshake();
    return handshake != null ? handshake.localPrincipal() : null;
  }

  @Override public void connect() throws IOException {
    connected = true;
    delegate.connect();
  }

  @Override public void disconnect() {
    delegate.disconnect();
  }

  @Override public InputStream getErrorStream() {
    return delegate.getErrorStream();
  }

  @Override public String getRequestMethod() {
    return delegate.getRequestMethod();
  }

  @Override public int getResponseCode() throws IOException {
    return delegate.getResponseCode();
  }

  @Override public String getResponseMessage() throws IOException {
    return delegate.getResponseMessage();
  }

  @Override public void setRequestMethod(String method) throws ProtocolException {
    delegate.setRequestMethod(method);
  }

  @Override public boolean usingProxy() {
    return delegate.usingProxy();
  }

  @Override public boolean getInstanceFollowRedirects() {
    return delegate.getInstanceFollowRedirects();
  }

  @Override public void setInstanceFollowRedirects(boolean followRedirects) {
    delegate.setInstanceFollowRedirects(followRedirects);
  }

  @Override public boolean getAllowUserInteraction() {
    return delegate.getAllowUserInteraction();
  }

  @Override public Object getContent() throws IOException {
    return delegate.getContent();
  }

  @SuppressWarnings("unchecked") // Spec does not generify
  @Override public Object getContent(Class[] types) throws IOException {
    return delegate.getContent(types);
  }

  @Override public String getContentEncoding() {
    return delegate.getContentEncoding();
  }

  @Override public int getContentLength() {
    return delegate.getContentLength();
  }

  @Override public String getContentType() {
    return delegate.getContentType();
  }

  @Override public long getDate() {
    return delegate.getDate();
  }

  @Override public boolean getDefaultUseCaches() {
    return delegate.getDefaultUseCaches();
  }

  @Override public boolean getDoInput() {
    return delegate.getDoInput();
  }

  @Override public boolean getDoOutput() {
    return delegate.getDoOutput();
  }

  @Override public long getExpiration() {
    return delegate.getExpiration();
  }

  @Override public String getHeaderField(int pos) {
    return delegate.getHeaderField(pos);
  }

  @Override public Map<String, List<String>> getHeaderFields() {
    return delegate.getHeaderFields();
  }

  @Override public Map<String, List<String>> getRequestProperties() {
    return delegate.getRequestProperties();
  }

  @Override public void addRequestProperty(String field, String newValue) {
    delegate.addRequestProperty(field, newValue);
  }

  @Override public String getHeaderField(String key) {
    return delegate.getHeaderField(key);
  }

  @Override public long getHeaderFieldDate(String field, long defaultValue) {
    return delegate.getHeaderFieldDate(field, defaultValue);
  }

  @Override public int getHeaderFieldInt(String field, int defaultValue) {
    return delegate.getHeaderFieldInt(field, defaultValue);
  }

  @Override public String getHeaderFieldKey(int position) {
    return delegate.getHeaderFieldKey(position);
  }

  @Override public long getIfModifiedSince() {
    return delegate.getIfModifiedSince();
  }

  @Override public InputStream getInputStream() throws IOException {
    return delegate.getInputStream();
  }

  @Override public long getLastModified() {
    return delegate.getLastModified();
  }

  @Override public OutputStream getOutputStream() throws IOException {
    return delegate.getOutputStream();
  }

  @Override public Permission getPermission() throws IOException {
    return delegate.getPermission();
  }

  @Override public String getRequestProperty(String field) {
    return delegate.getRequestProperty(field);
  }

  @Override public URL getURL() {
    return delegate.getURL();
  }

  @Override public boolean getUseCaches() {
    return delegate.getUseCaches();
  }

  @Override public void setAllowUserInteraction(boolean newValue) {
    delegate.setAllowUserInteraction(newValue);
  }

  @Override public void setDefaultUseCaches(boolean newValue) {
    delegate.setDefaultUseCaches(newValue);
  }

  @Override public void setDoInput(boolean newValue) {
    delegate.setDoInput(newValue);
  }

  @Override public void setDoOutput(boolean newValue) {
    delegate.setDoOutput(newValue);
  }

  @Override public void setIfModifiedSince(long newValue) {
    delegate.setIfModifiedSince(newValue);
  }

  @Override public void setRequestProperty(String field, String newValue) {
    delegate.setRequestProperty(field, newValue);
  }

  @Override public void setUseCaches(boolean newValue) {
    delegate.setUseCaches(newValue);
  }

  @Override public void setConnectTimeout(int timeoutMillis) {
    delegate.setConnectTimeout(timeoutMillis);
  }

  @Override public int getConnectTimeout() {
    return delegate.getConnectTimeout();
  }

  @Override public void setReadTimeout(int timeoutMillis) {
    delegate.setReadTimeout(timeoutMillis);
  }

  @Override public int getReadTimeout() {
    return delegate.getReadTimeout();
  }

  @Override public String toString() {
    return delegate.toString();
  }

  @Override public void setFixedLengthStreamingMode(int contentLength) {
    delegate.setFixedLengthStreamingMode(contentLength);
  }

  @Override public void setChunkedStreamingMode(int chunkLength) {
    delegate.setChunkedStreamingMode(chunkLength);
  }
}


text:
package com.github.reels_project.reels.query.jdbc.converter;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface JdbcValueConverter {
	Object getValue(ResultSet rs, int index, Class<?> propType) throws SQLException;
	Object toJdbcObject(Object value);
	String toLiteral(Object o);
}


text:
<?php
namespace Amsgames\LaravelShop\Http\Controllers\Shop;
use Validator;
use Shop;
use Illuminate\Http\Request;
use Amsgames\LaravelShop\Http\Controllers\Controller;
class CallbackController extends Controller
{
    /**
     * Process payment callback.
     *
     * @param Request $request   Request.
     *
     * @return redirect
     */
    protected function process(Request $request)
    {
        $validator = Validator::make(
            [
                'order_id'  => $request->get('order_id'),
                'status'    => $request->get('status'),
                'shoptoken' => $request->get('shoptoken'),
            ],
            [
                'order_id'  => 'required|exists:' . config('shop.order_table') . ',id',
                'status'    => 'required|in:success,fail',
                'shoptoken' => 'required|exists:' . config('shop.transaction_table') . ',token,order_id,' . $request->get('order_id'),
            ]
        );
        if ($validator->fails()) {
            abort(404);
        }
        $order = call_user_func(config('shop.order') . '::find', $request->get('order_id'));
        $transaction = $order->transactions()->where('token', $request->get('shoptoken'))->first();
        Shop::callback($order, $transaction, $request->get('status'), $request->all());
        $transaction->token = null;
        $transaction->save();
        return redirect()->route(config('shop.callback_redirect_route'), ['orderId' => $order->id]);
    }
}


text:
package com.bazaarvoice.emodb.auth.identity;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;

import java.util.Date;
import java.util.Set;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

/**
 * Base unit of identity for a client which can be authenticated in the application.
 */
abstract public class AuthIdentity {

    /**
     * Each identity is associated with an immutable ID distinct from the secret authentication key.  This is done
     * for several reasons:
     *
     *

     *

     *         Parts of the system may need associate resources with an ID.  For example, each databus subscription
     *         is associated with an API key.  By using a distinct  ID these parts of the system don't need to
     *         be concerned with safely storing the API key, since the ID is essentially a reference to the key.
     *

     *

     *         Parts of the system may need to determine whether an ID has permission to perform certain actions
     *         without actually logging the user in.  Databus fanout is a prime example of this.  Using IDs
     *         in the interface allows those parts of the system to validate authorization for permission without
     *         the ability to impersonate that user by logging them in.
     *

     *

     *         If an ID is compromised an administrator may want to replace it with a new ID without
     *         changing all internal references to that ID.
     *

     *

     *         User management can be performed without the identity owner divulging her authentication ID,
     *         such as over a chat client or in an email.
     *

     *

     */
    private final String _id;

    // Roles assigned to the identity
    private final Set<String> _roles;
    // Owner of the identity, such as an email address
    private String _owner;
    // Description of this identity
    private String _description;
    // Date this identity was issued
    private Date _issued;
    // Masked version of the authentication ID.
    private String _maskedId;

    protected AuthIdentity(String id, Set<String> roles) {
        checkArgument(!Strings.isNullOrEmpty(id), "id");
        _id = id;
        _roles = ImmutableSet.copyOf(requireNonNull(roles, "roles"));
    }

    public String getId() {
        return _id;
    }

    public Set<String> getRoles() {
        return _roles;
    }

    public String getOwner() {
        return _owner;
    }

    public void setOwner(String owner) {
        _owner = owner;
    }

    public String getDescription() {
        return _description;
    }

    public void setDescription(String description) {
        _description = description;
    }

    public Date getIssued() {
        return _issued;
    }

    public void setIssued(Date issued) {
        _issued = issued;
    }

    public String getMaskedId() {
        return _maskedId;
    }

    public void setMaskedId(String maskedId) {
        _maskedId = maskedId;
    }
}


text:
// Copyright (c) 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_OOM_H_
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_OOM_H_

#include <stddef.h>

#include "base/allocator/partition_allocator/allocation_guard.h"
#include "base/base_export.h"
#include "base/compiler_specific.h"

// The crash is generated in a NOINLINE function so that we can classify the
// crash as an OOM solely by analyzing the stack trace. It is tagged as
// NOT_TAIL_CALLED to ensure that its parent function stays on the stack.
[[noreturn]] BASE_EXPORT void NOT_TAIL_CALLED OnNoMemory(size_t size);

// OOM_CRASH(size) - Specialization of IMMEDIATE_CRASH which will raise a custom
// exception on Windows to signal this is OOM and not a normal assert.
// OOM_CRASH(size) is called by users of PageAllocator (including
// PartitionAlloc) to signify an allocation failure from the platform.
#define OOM_CRASH(size)                                     \
  do {                                                      \
    /* Raising an exception might allocate, allow that.  */ \
    base::internal::ScopedAllowAllocations guard{};         \
    OnNoMemory(size);                                       \
  } while (0)

#endif  // BASE_ALLOCATOR_PARTITION_ALLOCATOR_OOM_H_


text:
package sims.collision

import sims.math.Vector2D

/** Properties implemented by a collidable circle.
  * Note: this class does not define any physical properties, see sims.dynamics.Circle for that.
  * @see sims.dynamics.Circle */
trait Circle extends Collidable {

	/** Position of this circle. */
	def position: Vector2D

	/** Radius of this circle. */
	def radius: Double

	/** Returns this circle's axis aligned bounding box.
    * @see collision.AABB */
	override def aabb = new AABB(Vector2D(position.x - radius, position.y - radius), Vector2D(position.x + radius, position.y + radius))

	/** Checks if the point `point` is contained in this circle. */
	override def contains(point: Vector2D) = (point - position).length <= radius

	/** Returns the projection of this polygon onto the line given by the directional vector `axis`. */
	override def project(axis: Vector2D) = {
		val dir = axis.unit
		new Projection(
				axis,
				(position - dir * radius) dot dir,
				(position + dir * radius) dot dir
				)
	}

	override def support(direction: Vector2D) = position + direction.unit * radius
}


text:
package me.hatter.tools.resourceproxy.jsspserver.filter.impl;

public class DefaultRootFilter extends AbstractRootFilter {

    @Override
    protected String homePath() {
        return "index.jssp";
    }
}


text:
namespace mx
{
    namespace core
    {
        ThumbPosition::ThumbPosition()
        :ElementInterface()
        ,myAttributes( std::make_shared<EmptyPlacementAttributes>() )
        {}

        bool ThumbPosition::hasAttributes() const
        {
            return myAttributes->hasValues();
        }

        bool ThumbPosition::hasContents() const  { return false; }
        std::ostream& ThumbPosition::streamAttributes( std::ostream& os ) const
        {
            if ( myAttributes )
            {
                myAttributes->toStream( os );
            }
            return os;
        }

        std::ostream& ThumbPosition::streamName( std::ostream& os ) const  { os << "thumb-position"; return os; }
        std::ostream& ThumbPosition::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const
        {
            MX_UNUSED( indentLevel );
            isOneLineOnly = true;
            return os;
        }

        EmptyPlacementAttributesPtr ThumbPosition::getAttributes() const
        {
            return myAttributes;
        }

        void ThumbPosition::setAttributes( const EmptyPlacementAttributesPtr& value )
        {
            if ( value )
            {
                myAttributes = value;
            }
        }

        bool ThumbPosition::fromXElementImpl( std::ostream& message, ::ezxml::XElement& xelement )
        {
            return myAttributes->fromXElement( message, xelement );
        }

    }
}


text:
package api

import (
	"net/http"
	"testing"

	"github.com/google/martian/v3"
)

func TestApiForwarder(t *testing.T) {
	forwarder := NewForwarder("", 8181)

	req, err := http.NewRequest("GET", "https://martian.proxy/configure", nil)
	if err != nil {
		t.Fatalf("NewRequest(): got %v, want no error", err)
	}

	ctx, remove, err := martian.TestContext(req, nil, nil)
	if err != nil {
		t.Fatalf("TestContext(): got %v, want no error", err)
	}
	defer remove()

	if err := forwarder.ModifyRequest(req); err != nil {
		t.Fatalf("ModifyRequest(): got %v, want no error", err)
	}

	if got, want := req.URL.Scheme, "http"; got != want {
		t.Errorf("req.URL.Scheme: got %s, want %s", got, want)
	}
	if got, want := req.URL.Host, "localhost:8181"; got != want {
		t.Errorf("req.URL.Host: got %s, want %s", got, want)
	}

	if !ctx.SkippingLogging() {
		t.Errorf("ctx.SkippingLogging: got false, want true")
	}

	if !ctx.IsAPIRequest() {
		t.Errorf("ctx.IsApiRequest: got false, want true")
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia 29(3-4): 628 (1978)

#### Original name
Psilocybe galindoi Guzmán

### Remarks
null


text:
package controllers

import play.api.mvc.{AnyContent, Request}

sealed trait RequestType

object RequestType {
  def requestType(implicit request:Request[AnyContent]) = apply(request)

  private[this] def acc(t: String)(implicit request: Request[AnyContent]): Boolean =
    request.accepts("application/" + t) || request.accepts("text/" + t)
  def apply(implicit request:Request[AnyContent]): RequestType = {
    if (acc("html") || acc("x-www-form-urlencoded")) HttpRequest
    else if (acc("xml")) XmlRequest
    else if (acc("json")) JsonRequest
    else InvalidRequest
  }
}
case object JsonRequest extends RequestType
case object XmlRequest extends RequestType
case object HttpRequest extends RequestType
case object InvalidRequest extends RequestType


text:
@interface doModuleFactory : NSObject<doISingletonModuleFactory>
{
    id model;
}
-(id) init:(id) _model;
@end


text:
/**
 * This package contains classes that change internals of JBoss Logging discovery mechanism.
 * Effectively there's just static {@link org.jboss.logging.LoggerProvider}.
 */
package org.jboss.logging;


text:
<?php

namespace Cop\ImportBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;

class FeedLauncherCommand extends ContainerAwareCommand
{

    protected $locale;
    protected $source;

    protected function configure()
    {
        $this
            ->setName('import:launch')
            ->setDescription('launch the import')
            ->addArgument(
                'locale',
                InputArgument::REQUIRED
            )
            ->addArgument(
                'source',
                InputArgument::REQUIRED
            );
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->locale = $input->getArgument('locale');
        $this->source = $input->getArgument('source');

        $this->em = $this->getContainer()->get('doctrine')->getManager();

        $repositoryFeed = $this->em->getRepository('Cop\ImportBundle\Entity\FeedCSV');

        $this->canResetFeedTable();

        $this->feed  = $repositoryFeed->retrieveNextCsvFeed($this->source, $this->locale);

        $this->flagAsTreated();

        $env = $this->getContainer()->get('kernel')->getEnvironment();

        $csvFile = $this->feed->getSiteslug()  .
            '-'. strtolower($this->source) . '-' . $env . ".csv";

        $this->setPathToStore($csvFile);

        $this->copyFeed();

        /* @todo faire plus beau http://php-webdeveloper.com/?p=88 */
        echo exec("php app/console import:csv " . $this->source  . " " . $this->feed->getId()  . " " . $this->locale  . " " .  $csvFile);

    }

    public function flagAsTreated()
    {
        $repositoryFeedCSV = $this->em->getRepository('Cop\ImportBundle\Entity\FeedCSV');

        $feedupdated = $repositoryFeedCSV->find($this->feed->getId());
        $feedupdated->setFlagbatched('Y');

        $this->em->persist($feedupdated);
        $this->em->flush();
        $this->em->clear();

        $this->canResetFeedTable();
    }

    public function canResetFeedTable()
    {
        $this->em = $this->getContainer()->get('doctrine')->getManager();

        $repositoryFeedCSV = $this->em->getRepository('Cop\ImportBundle\Entity\FeedCSV');

        $flaggedActiveFeedsToProcess = $repositoryFeedCSV->findBy(
            array(
                'locale' => $this->locale,
                'source' => $this->source,
                'flagbatched' => 'N',
                'active' => 'Y'
            )
        );

        if(count($flaggedActiveFeedsToProcess) == 0)
        {
            $feeds = $repositoryFeedCSV->findBy(
                array(
                    'locale' => $this->locale,
                    'source' => $this->source,
                    'active' => 'Y'
                )
            );
            foreach($feeds as $feed)
            {
                $feed->setFlagbatched('N');
                $this->em->persist($feed);
            }
            $this->em->flush();
            $this->em->clear();
        }
    }

    protected function copyFeed()
    {

        try
        {
            $request = new \GuzzleHttp\Client();
            $response = $request->get(trim($this->feed->getFeed()));
            $response = $response->getBody()->getContents();

            // @todo separer en deux exception, ajouter ConnectException pour guzzle (url invalide)
            // @todo tojours le cas

            $fp = fopen($this->getPathToStore(), "wb");
            fwrite($fp, $response);
            fclose($fp);

            return true;
        }
        catch (\Exception $e)
        {
            // @todo  un vrai log et une action
            var_dump($e->getMessage());
            // Log the error or something
            return false;
        }

    }

    /**
     * @return mixed
     */
    public function getPathToStore()
    {
        return $this->pathToStore;
    }

    /**
     * @param mixed $pathToStore
     */
    public function setPathToStore($pathToStore)
    {
        $this->pathToStore = $pathToStore;
    }

}


text:
import {Component,ViewChild,ElementRef,ComponentFactoryResolver,ViewContainerRef,forwardRef,ContentChildren,QueryList} from '@angular/core';
import { base } from './base';
// Ext Class - Ext.button.Split
export class splitbuttonMetaData {
	public static XTYPE: string = 'splitbutton';
	public static INPUTNAMES: string[] = [
		'activeCounter',
		'alignOnScroll',
		'alignTarget',
		'allowDepress',
		'alwaysOnTop',
		'anchor',
		'animateShadow',
		'ariaAttributes',
		'ariaDescribedBy',
		'ariaLabel',
		'ariaLabelledBy',
		'arrowAlign',
		'arrowCls',
		'arrowHandler',
		'arrowTooltip',
		'arrowVisible',
		'autoEl',
		'autoRender',
		'autoScroll',
		'autoShow',
		'baseCls',
		'baseParams',
		'bind',
		'border',
		'childEls',
		'clickEvent',
		'cls',
		'columnWidth',
		'componentCls',
		'componentLayout',
		'constrain',
		'constraintInsets',
		'constrainTo',
		'contentEl',
		'controller',
		'data',
		'defaultAlign',
		'defaultListenerScope',
		'destroyMenu',
		'disabled',
		'disabledCls',
		'dock',
		'draggable',
		'enableToggle',
		'fixed',
		'flex',
		'floating',
		'focusCls',
		'focusOnToFront',
		'formBind',
		'frame',
		'glyph',
		'handleMouseEvents',
		'handler',
		'height',
		'hidden',
		'hideMode',
		'href',
		'hrefTarget',
		'html',
		'icon',
		'iconAlign',
		'iconCls',
		'id',
		'itemId',
		'keyMap',
		'keyMapEnabled',
		'keyMapTarget',
		'liquidLayout',
		'listeners',
		'liveDrag',
		'loader',
		'margin',
		'maskDefaults',
		'maskElement',
		'maxHeight',
		'maxWidth',
		'menu',
		'menuAlign',
		'minHeight',
		'minWidth',
		'modal',
		'modelValidation',
		'nameable',
		'overCls',
		'overflowText',
		'overflowX',
		'overflowY',
		'padding',
		'params',
		'plugins',
		'pressed',
		'preventDefault',
		'publishes',
		'reference',
		'region',
		'renderConfig',
		'renderData',
		'renderSelectors',
		'renderTo',
		'renderTpl',
		'repeat',
		'resizable',
		'resizeHandles',
		'saveDelay',
		'scale',
		'scope',
		'scrollable',
		'session',
		'shadow',
		'shadowOffset',
		'shareableName',
		'shim',
		'showEmptyMenu',
		'shrinkWrap',
		'stateEvents',
		'stateful',
		'stateId',
		'style',
		'tabIndex',
		'text',
		'textAlign',
		'toFrontOnShow',
		'toggleGroup',
		'toggleHandler',
		'tooltip',
		'tooltipType',
		'touchAction',
		'tpl',
		'tplWriteMode',
		'twoWayBindable',
		'ui',
		'uiCls',
		'userCls',
		'value',
		'viewModel',
		'weight',
		'width',
		'xtype',
		'flex',
		'platformConfig',
		'responsiveConfig',
		'fitToParent',
		'config'
];
	public static OUTPUTS: any[] = [
		{name:'activate',parameters:'splitbutton'},
		{name:'added',parameters:'splitbutton,container,pos'},
		{name:'afterlayoutanimation',parameters:'splitbutton'},
		{name:'afterrender',parameters:'splitbutton'},
		{name:'arrowclick',parameters:'splitbutton,e'},
		{name:'beforeactivate',parameters:'splitbutton'},
		{name:'beforedeactivate',parameters:'splitbutton'},
		{name:'beforedestroy',parameters:'splitbutton'},
		{name:'beforehide',parameters:'splitbutton'},
		{name:'beforerender',parameters:'splitbutton'},
		{name:'beforeshow',parameters:'splitbutton'},
		{name:'beforestaterestore',parameters:'splitbutton,state'},
		{name:'beforestatesave',parameters:'splitbutton,state'},
		{name:'beforetoggle',parameters:'splitbutton,pressed'},
		{name:'blur',parameters:'splitbutton,event'},
		{name:'boxready',parameters:'splitbutton,width,height'},
		{name:'click',parameters:'splitbutton,e'},
		{name:'deactivate',parameters:'splitbutton'},
		{name:'destroy',parameters:'splitbutton'},
		{name:'disable',parameters:'splitbutton'},
		{name:'enable',parameters:'splitbutton'},
		{name:'focus',parameters:'splitbutton,event'},
		{name:'focusenter',parameters:'splitbutton,event'},
		{name:'focusleave',parameters:'splitbutton,event'},
		{name:'glyphchange',parameters:'splitbutton,newGlyph,oldGlyph'},
		{name:'hide',parameters:'splitbutton'},
		{name:'iconchange',parameters:'splitbutton,oldIcon,newIcon'},
		{name:'menuhide',parameters:'splitbutton,menu'},
		{name:'menushow',parameters:'splitbutton,menu'},
		{name:'menutriggerout',parameters:'splitbutton,menu,e'},
		{name:'menutriggerover',parameters:'splitbutton,menu,e'},
		{name:'mouseout',parameters:'splitbutton,e'},
		{name:'mouseover',parameters:'splitbutton,e'},
		{name:'move',parameters:'splitbutton,x,y'},
		{name:'removed',parameters:'splitbutton,ownerCt'},
		{name:'render',parameters:'splitbutton'},
		{name:'resize',parameters:'splitbutton,width,height,oldWidth,oldHeight'},
		{name:'show',parameters:'splitbutton'},
		{name:'staterestore',parameters:'splitbutton,state'},
		{name:'statesave',parameters:'splitbutton,state'},
		{name:'textchange',parameters:'splitbutton,oldText,newText'},
		{name:'toggle',parameters:'splitbutton,pressed'},
		{name:'ready',parameters:''}
];
	public static OUTPUTNAMES: string[] = [
		'activate',
		'added',
		'afterlayoutanimation',
		'afterrender',
		'arrowclick',
		'beforeactivate',
		'beforedeactivate',
		'beforedestroy',
		'beforehide',
		'beforerender',
		'beforeshow',
		'beforestaterestore',
		'beforestatesave',
		'beforetoggle',
		'blur',
		'boxready',
		'click',
		'deactivate',
		'destroy',
		'disable',
		'enable',
		'focus',
		'focusenter',
		'focusleave',
		'glyphchange',
		'hide',
		'iconchange',
		'menuhide',
		'menushow',
		'menutriggerout',
		'menutriggerover',
		'mouseout',
		'mouseover',
		'move',
		'removed',
		'render',
		'resize',
		'show',
		'staterestore',
		'statesave',
		'textchange',
		'toggle',
		'ready'
];
}
@Component({
  selector: splitbuttonMetaData.XTYPE,
	inputs: splitbuttonMetaData.INPUTNAMES,
	outputs: splitbuttonMetaData.OUTPUTNAMES,
	providers: [{provide: base, useExisting: forwardRef(() => splitbutton)}],
	template: '<ng-template #dynamic></ng-template>'
})
export class splitbutton extends base {
	constructor(eRef:ElementRef,resolver:ComponentFactoryResolver,vcRef:ViewContainerRef) {
		super(eRef,resolver,vcRef,splitbuttonMetaData);
	}
	//@ContentChildren(base,{read:ViewContainerRef}) extbaseRef:QueryList<ViewContainerRef>;
	@ContentChildren(base,{read: base}) extbaseRef: QueryList<base>;
	@ViewChild('dynamic',{read:ViewContainerRef}) dynamicRef:ViewContainerRef;
	ngAfterContentInit() {this.AfterContentInit(this.extbaseRef);}
	ngOnInit() {this.OnInit(this.dynamicRef,splitbuttonMetaData);}
}


text:
@interface CommentTableView : BaseTableView<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,retain)NSDictionary * commentsdic;

@end


text:
package br.com.caelum.livraria.modelo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

@Entity
public class Livro {

	@Id
	@GeneratedValue
	private Integer id;

	private String titulo;
	private String isbn;
	private double preco;

	@Temporal (TemporalType.TIMESTAMP)
	private Calendar dataLancamento = Calendar.getInstance();

	@ManyToMany (fetch=FetchType.EAGER)
	private List<Autor> autores = new ArrayList<Autor>();

	public List<Autor> getAutores() {
		return autores;
	}

	public void adicionaAutor(Autor autor) {
		this.autores.add(autor);
	}

	public Livro() {
	}

	public Integer getId() {
		return id;
	}

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

	public String getTitulo() {
		return titulo;
	}

	public void setTitulo(String titulo) {
		this.titulo = titulo;
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public double getPreco() {
		return preco;
	}

	public void setPreco(double preco) {
		this.preco = preco;
	}

	public Calendar getDataLancamento() {
		return dataLancamento;
	}

	public void setDataLancamento(Calendar dataLancamento) {
		this.dataLancamento = dataLancamento;
	}

	public void removeAutor(Autor autor) {
		this.autores.remove(autor);
	}

}


text:
title: "Hello World!"
excerpt_separator: "<!--more-->"
categories:
  - Random
tags:
  - Hello World
---

# Who am I

Hi, I am Alan Duan, a Masters student @ Columbia University majoring in Computer Science. I did my undergrad in City University of Hong Kong studying business (more specifically, accounting) as well as a bit of comp sci.

I love:

* learning and reading and writing
* building cool stuff (the definition of coolness is something that many folks will use and then say "man, I really love that")
* teaching and sharing: the sense of achievement I get after helping someone understand a complex concept is my caffeine.
* efficiency and tools that boost my efficiency
* high-quality life -- good stuff to buy, interesting experiences to try out...

# Why blogging now (and here)

This is my first time running a blog. I started to write diaries since October 2014, but chose to keep it as a private places for myself to relieve stress, brainstorm, or sort things out. Now I am happy to share some of my knowledge and thoughts in a more public environment as I hope this will benefit more people.

I became a user of [Zhihu](http://www.zhihu.com) since February 2014 and joined [Quora](http://www.quora.com) since December 2015. By saying user I really mean reader: both of them offer very high quality contents (especially in the field of computer science). I have read and learned a lot (and randomly surfed on them a lot). Although they are great platforms to share knowledge, I simply do not want to limit myself by the questions being asked, nor am I willing to be judged by the number of upvotes. Also I see quarrels on Zhihu sometimes, and it makes me feel resistant to answering when there may be chances of getting into a fight where people care about winning more than finding out the truth.

That's why I decide to go for a more independent blog site and write my stuff there. I have been shopping between various full-fledged Content Management System websites and more light-weight, static sites like Github pages. I finally chose Github Pages + Jekyll because I want a platform where I can sit down and write (in Markdown) right away, without worrying about how to publish it or make things look nice with HTML/CSS/JS. But at the same time it has enough customizable features that I can discover and tweak later on. Again it's my first time doing this so let's see how it works as I am of course open to other great publishing platforms.

# So what is this blog all about
I already got a bunch of topics in my head that I want to write about, but of course it may change based on my schedule (and mood):

* Stuff on Python: An Intro to Python in 30 Minutes; On Writing Pythonic Codes

* Things that are related to the course I have taken/am taking/am TAing: A potpourri of machine learning, discrete math, operating system, C++, algorithms, etc. It will be a combination of Notes/Video tutorials/Exercises.

* Interview prep: If I saw a really interesting question or a fancy solution I will share it with you guys.

* Efficiency: I love tools that will boost efficiency (GTD and more!). I will recommend some iPhone/Mac OS apps that I use a lot day to day. I will also cover some great skills/toolkits that I think every computer science student (or really, everyone) can benefit a lot in the long-term. To name a few: git, LaTeX, Markdown, vim, email management)

* Learning: Here I want to include some learning strategies that may help college students learn better. I am a big of Feynman technique and Socratic method as I have benefited a lot myself from using them. I plan to share more about their effectiveness and how I apply them to my course work.

* Random stuff: Whatever I like (alternatively, tell me what you like!)

Alright I think this is an enough-long hello world (maybe too verbose compared to Python). Stay tuned and I wish to post something interesting very soon!


text:
module Paperclip
  module Multiple
    VERSION = "0.0.2"
  end
end


text:
<?xml version="1.0" ?>
<configuration>
    <about>
       Acerca
       <visible>false</visible>
       <width>375</width>
       <height>375</height>
       <content>
        <![CDATA[

        <textformat indent="25">

ArcGIS Viewer para Flex

ArcGIS API for Flex

Esri
</textformat>
        ]]>
        </content>

    </about>
</configuration>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>it.megadix.orientdb</groupId>
  <artifactId>orientdb-spring-samples</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>orientdb-spring</name>
  <description>Spring-OrientDB Integration library samples</description>

  <properties>
    <spring-orientdb.version>1.0-SNAPSHOT</spring-orientdb.version>
    <junit.version>4.8.1</junit.version>
    <spring.version>3.1.0.RELEASE</spring.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>it.megadix.orientdb</groupId>
      <artifactId>spring-orientdb</artifactId>
      <version>${spring-orientdb.version}</version>
    </dependency>

    <!--
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    -->

    <!--
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    -->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
      <version>2.1_3</version>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
using System;
using Prism.Ioc;
using Prism.Windows;
using Template10.Services.Serialization;
using Windows.Storage;

namespace Template10.Services.Settings
{
    public class LocalSettingsAdapter : ISettingsAdapter
    {
        private ApplicationDataContainer _container;

        public LocalSettingsAdapter()
          : this(Central.Container.Resolve<ISerializationService>())
        {
            // empty
        }

        public LocalSettingsAdapter(ISerializationService serializationService)
        {
            _container = ApplicationData.Current.LocalSettings;
            SerializationService = serializationService;
        }

        public ISerializationService SerializationService { get; }

        public string ReadString(string key)
            => _container.Values[key].ToString();

        public void WriteString(string key, string value)
            => _container.Values[key] = value;
    }
}


text:
package com.marcelmika.lims.persistence.service;

import com.marcelmika.lims.api.events.conversation.*;

/**
 * @author Ing. Marcel Mika
 * @link http://marcelmika.com
 * Date: 6/29/14
 * Time: 11:47 AM
 */
public interface ConversationPersistenceService {

    /**
     * Creates new conversation
     *
     * @param event request event for method
     * @return response event for  method
     */
    public CreateConversationResponseEvent createConversation(CreateConversationRequestEvent event);

    /**
     * Reads messages from conversation
     *
     * @param event request event for method
     * @return response event for method
     */
    public ReadSingleUserConversationResponseEvent readConversation(ReadSingleUserConversationRequestEvent event);

    /**
     * Returns a list of participants related to the conversation
     *
     * @param event request event for method
     * @return response event for method
     */
    public GetConversationParticipantsResponseEvent getParticipants(GetConversationParticipantsRequestEvent event);

    /**
     * Closes existing conversation. User remains in the conversation though.
     *
     * @param event request event for method
     * @return response event for method
     */
    public CloseConversationResponseEvent closeConversation(CloseConversationRequestEvent event);

    /**
     * Reset counter of unread messages (usually displayed in badge) for the particular user and conversation
     *
     * @param event request event for method
     * @return response event for method
     */
    public ResetUnreadMessagesCounterResponseEvent resetUnreadMessagesCounter(ResetUnreadMessagesCounterRequestEvent event);

    /**
     * Sends message to conversation
     *
     * @param event request event for method
     * @return response event for method
     */
    public SendMessageResponseEvent sendMessage(SendMessageRequestEvent event);

    /**
     * Get all opened conversations related to the particular buddy
     *
     * @param event request event for method
     * @return response event for  method
     */
    public GetOpenedConversationsResponseEvent getOpenedConversations(GetOpenedConversationsRequestEvent event);

}


text:
import test from 'ava';
import readChunk from 'read-chunk';
import isFlv from '..';

function check(filename) {
	return isFlv(readChunk.sync(filename, 0, 4));
}

test('should return true when passing an flv', t => {
	t.true(check('test/fixture.flv'));
	t.end();
});

test('should return false when not passing an flv', t => {
	t.false(check('test/fixture.avi'));
	t.end();
});


text:
<!DOCTYPE html>

    <title>Pick a hero</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link href="/static/css/style.css" rel="stylesheet" type="text/css">

    <form id="pick_hero_form" action="/sayings/{{ saying.id }}/hero/" method="post"  autocomplete="off">{% csrf_token %}

Pick your hero

        {% for hero in heroes %}
        <input type="radio" name="hero" value="{{ hero.id }}">

        {% endfor %}
	<input id="your_name_start_form_submit_button" type="submit" value="Choose" class="button">
	</form>


text:
layout: kanji
v4: 2791
v6: 479
kanji: 頃
keyword: about that time
elements: about that time, spoon, sitting on the ground, head, page, one, ceiling, drop, shellfish, clam, oyster, eye, animal legs, eight
strokes: 11
image: E9A083
on-yomi: ケイ、キョウ
kun-yomi: ころ、ごろ、しばら.く
permalink: /rtk/頃/
prev: 匂
next: 北
---

1) [Katsuo] 24-6-2007(164): An alarm clock with a unique design: You set it for, say, 7:00 am, and at about that time the clock reaches out with a spoon and hits you on the head.

2) [cameron_en] 29-11-2008(47): After spooning for hours it's about that time he got some head. Dayum woman.

3) [herman] 22-11-2008(9): About that time to sit down and get some head.

4) [usis35] 5-6-2010(7): 子供の頃 I used to hit my HEAD with a SPOON.

5) [manubear] 10-8-2012(4): When your host starts hitting himself on the head with a spoon, you realise it's about that time to make your excuses and leave! ( この頃 ).