text:
author: slowe
categories: Information
comments: true
date: 2018-10-05T12:00:00Z
tags:
- Networking
- Hardware
- Security
- Storage
- Virtualization
- AWS
- Kubernetes
- vSphere
- OpenStack
- Terraform
- Ansible
- Linux
- Fedora
- CLI
- BSD
- Go
title: 'Technology Short Take 105'
url: /2018/10/05/technology-short-take-105/
---

Welcome to Technology Short Take #105! Here's another collection of articles and blog posts about some of the common technologies that modern IT professionals will typically encounter. I hope that something I've included here proves to be useful for you.<!--more-->

## Networking

* Jon Williams discusses [deploying Anycast DNS using OpenBSD and BGP][link-22].
* Brian Boucheron provides a great article on [how to inspect and debug Kubernetes network primitives][link-23]. The information in this article is a great foundation upon which to build, in my opinion.

## Servers/Hardware

* The big news in the hardware space recently was [the article regarding the purported Chinese hardware supply chain attack][link-30]. This has generated a _lot_ of discussion. First, we have [Amazon's reply][link-31], in which they categorically deny all such claims. [Apple's response][link-33] similarly denies the allegations in the report. Of the (innumerable) articles commenting on the hardware hack, [this article by Joe FitzPatrick][link-32] and [this ErrataSec article][link-34] caught my eye. Both articles point out the incredible difficulty of finding such a hardware hack, and point out that exploiting software vulnerabilities would probably be a much faster/easier way to accomplish the same goal. Will we ever know the truth as to whether this actually happened? Probably not.

## Security

* I suspect I'll find myself here at some point, so Jeff Geerling's script to [get AWS STS session tokens for MFA with AWS CLI][link-2] is probably going to be handy when that time comes.
* Sathyajith Bhat covers [five open source tools for container security][link-10].
* Cory O'Daniel explains [how to use role-based access control to assign Pod Security Policies (PSPs) to Kubernetes workloads][link-11].

## Cloud Computing/Cloud Management

* I talk about Terraform a fair amount (and I use it a fair amount). Many times that's in the context of a public cloud (since that's where I spend most of my time), but here's [an example of using it for vSphere and OpenStack][link-5].
* Chris Herrera tackles a little bit of the "why" in [this article on Kubernetes cluster design][link-8].
* Bob Killen [discusses exposing StatefulSets in Kubernetes][link-9].
* Lots of folks are super-bullish on Helm, but Bartlomiej Antoniak suggests users [think twice before using Helm][link-13].
* Robert Verdam has a two-part series on deploying an application to AWS with Terraform and Ansible ([part 1][link-14], [part 2][link-15]). Of particular interest---to me, anyway---was Robert's use of the Terraform provider+inventory script, which I'm exploring for use in some of my own projects.
* The `kubespy` tool, released by the Pulumi folks, looks interesting. Have a look at [part 1][link-16] and [part 2][link-17] of their blog posts about the CLI tool.
* Grant Orchard has a three-part series (so far) on VMware Cloud Assembly ([part 1][link-19], [part 2][link-20], [part 3][link-21]).
* The folks at Platform9 recently open-sourced a tool called `etcdadm` (inspired by `kubeadm`). The GitHub repository is [here][link-28], and the blog post with the announcement is [here][link-29].

## Operating Systems/Applications

* Sayan Chowdhury talks about [Fedora 28 AMIs gaining Elastic Network Adapter (ENA) support][link-1].
* I've been looking into Dropbox replacements; [Syncthing][link-3] is a leading candidate at the moment. Here's [an article on Syncthing][link-4] that provides some basic details. If any Syncthing users have any feedback they'd like to share, [hit me up on Twitter][link-99].
* [This][link-6] looks interesting, although I don't (personally) have a use case just yet. It might be worth watching as eBPF grows in importance in the Linux community, though.
* I mentioned [this article on Pandoc][link-7] in a tweet recently. I'm a long-time Pandoc user, but I hadn't thought/didn't know about using the `-s` parameter with an external YAML file to control styling for different output formats. That's a neat trick.
* Matthew Green [rants on Chrome's new forced login policy][link-12]. I'm not a fan, either.
* Here's a nice deep dive [on Linux executables][link-18].
* I'm (increasingly) not a fan of Google services, but I thought it was interesting to find [this Google Hangouts desktop client][link-26].

## Storage

I don't have anything to share this time, but I'll stay alert for content or links to include next time.

## Virtualization

* William Lam explores some of the [caveats/gotchas of Nested ESXi on VMware Cloud on AWS (VMC)][link-27]. Some of these gotchas are fairly significant (no inter-host networking for VMs running on nested HV's, for example).

## Career/Soft Skills

* I found a couple of resources for folks interested in learning Golang. First up is [this Go study group][link-24], which has both US and India meeting times. Next up is [Awesome Go][link-25], which is---in the author's words---"a curated list of awesome Go frameworks, libraries, and software."

That's all for this Technology Short Take. Thanks for reading! If you have questions, comments, or suggestions for improvement, feel free to [contact me on Twitter][link-99]. Have a great weekend!

[link-1]: https://words.yudocaa.in/fedora-amis-gets-ena-support/
[link-2]: https://www.jeffgeerling.com/blog/2018/getting-aws-sts-session-tokens-mfa-aws-cli-and-kubectl-eks-automatically
[link-3]: https://syncthing.net/
[link-4]: https://opensource.com/article/18/9/take-control-your-data-syncthing
[link-5]: https://github.com/trodemaster/tfe-openstack-vsphere/
[link-6]: https://github.com/jessfraz/bpfd
[link-7]: https://opensource.com/article/18/9/intro-pandoc
[link-8]: https://medium.com/hashmapinc/tips-for-designing-a-kubernetes-cluster-d020f0b728ee
[link-9]: https://itnext.io/exposing-statefulsets-in-kubernetes-698730fb92a1
[link-10]: https://opensource.com/article/18/8/tools-container-security
[link-11]: https://medium.com/coryodaniel/kubernetes-assigning-pod-security-policies-with-rbac-2ad2e847c754
[link-12]: https://blog.cryptographyengineering.com/2018/09/23/why-im-leaving-chrome/
[link-13]: https://medium.com/virtuslab/think-twice-before-using-helm-25fbb18bc822
[link-14]: https://robertverdam.nl/2018/09/03/deploying-an-application-to-aws-with-terraform-and-ansible-part-1-terraform/
[link-15]: https://robertverdam.nl/2018/09/22/deploying-an-application-to-aws-with-terraform-and-ansible-part-2-ansible/
[link-16]: https://blog.pulumi.com/kubespy-and-the-lifecycle-of-a-kubernetes-pod-in-four-images
[link-17]: https://blog.pulumi.com/kubespy-trace-a-real-time-view-into-the-heart-of-a-kubernetes-service
[link-18]: https://ownyourbits.com/2018/05/23/the-real-power-of-linux-executables/
[link-19]: https://grantorchard.com/tango/introducing-cas/
[link-20]: https://grantorchard.com/tango/blueprinting-intro/
[link-21]: https://grantorchard.com/tango/blueprint-versioning/
[link-22]: https://jonwillia.ms/2018/09/23/anycast-dns-openbsd
[link-23]: https://dev.to/digitalocean/how-to-inspect-and-debug-kubernetes-networking-primitives-d7n
[link-24]: https://gophersource.com/study-group/
[link-25]: https://awesome-go.com/
[link-26]: https://github.com/yakyak/yakyak
[link-27]: https://www.virtuallyghetto.com/2018/09/nested-esxi-on-vmware-cloud-on-aws-vmc.html
[link-28]: https://github.com/platform9/etcdadm
[link-29]: https://platform9.com/blog/were-open-sourcing-etcdadm-heres-what-it-means-for-kubernetes-in-production/
[link-30]: https://www.bloomberg.com/news/features/2018-10-04/the-big-hack-how-china-used-a-tiny-chip-to-infiltrate-america-s-top-companies
[link-31]: https://aws.amazon.com/blogs/security/setting-the-record-straight-on-bloomberg-businessweeks-erroneous-article/
[link-32]: https://securinghardware.com/articles/hardware-implants/
[link-33]: https://www.apple.com/newsroom/2018/10/what-businessweek-got-wrong-about-apple/
[link-34]: https://blog.erratasec.com/2018/10/notes-on-bloomberg-supermicro-supply.html
[link-99]: https://twitter.com/scott_lowe


text:
import React, { Component } from 'react';

export default class Author extends Component {
  render() {
    // let { author, id, isYou } = this.props;
    let { author, isYou } = this.props;

    return (

        {author}
        {isYou ?  (You) : ''}

    );
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class once extends core{
	//############################ VALIDATION ##################################################
	function validate_email(){
		$isValid = true;
		$atIndex = strrpos($this->data['email'], "@");
		$domain = substr($this->data['email'], $atIndex+1);
		$local = substr($email, 0, $atIndex);
		if (is_bool($atIndex) && !$atIndex){
			$this->set_error('Email without @ ?');
		}
		if (strlen($domain)==0){
			$this->set_error('Domain cannot be empty');
			$isValid=false;
		}
		if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){
			$this->set_error('Domain not found in DNS');
		}
		if(!preg_match("/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i",$this->data['email'])){
			$this->set_error('Invalid email format');
		}
	}
	//############################ CONTACT ##################################################
	function send_message(){
		if($this->once_csrf_token_check($this->data['csrf_token'])){
			// Check if recaptcha is acvited
			if($this->data['recaptcha_contact']){
				// Load library
				require_once($this->data['root_path'].'/once/libs/recaptcha/php/recaptchalib.php');
				// Create a new instance
				$reCaptcha = new ReCaptcha($this->data['recaptcha_secret']);

				// The response from reCAPTCHA
				$resp = null;

				// The error code from reCAPTCHA, if any
				$error = null;

				// Was there a reCAPTCHA response?
				if ($_POST["g-recaptcha-response"]) {
					$resp = $reCaptcha->verifyResponse(
						$_SERVER["REMOTE_ADDR"],
						$_POST["g-recaptcha-response"]
					);
				}

				if ($resp != null && $resp->success) {
					// Continiue code
				}else{
					$this->set_error('Recaptcha response is wrong, check if it configured properly');
					$this->set_error($error);
				}
			}

			// Check email if is ok
			$this->validate_email();

			// Check if sending email is acvited
			if($this->data['contact_mailme']==1 && $this->error==0){
				//SMTP needs accurate times, and the PHP time zone MUST be set
				//This should be done in your php.ini, but this is how to do it if you don't have access to that
				date_default_timezone_set('Etc/UTC');
				// Load library
				require_once($this->data['root_path'].'/once/libs/phpmailer/phpmailerautoload.php');
				// Create a new instance
				$mail = new PHPMailer;
				// Some funny options for SSL websites
				$mail->SMTPOptions = array(
					'ssl' => array(
						'verify_peer' => false,
						'verify_peer_name' => false,
						'allow_self_signed' => true
					)
				);
				// Tell PHPMailer to use SMTP
				$mail->isSMTP();
				// Enable SMTP debugging
				// 0 = off (for production use)
				// 1 = client messages
				// 2 = client and server messages
				$mail->SMTPDebug = $this->data['contact_debug'];
				// Ask for HTML-friendly debug output
				$mail->Debugoutput = 'html';
				// Set the hostname of the mail server
				$mail->Host = $this->data['contact_host'];
				// Set the SMTP port number - likely to be 25, 465 or 587
				$mail->Port = $this->data['contact_port'];
				// Whether to use SMTP authentication
				$mail->SMTPAuth = true;
				// Username to use for SMTP authentication
				$mail->Username = $this->data['contact_username'];
				// Password to use for SMTP authentication
				$mail->Password = $this->data['contact_password'];
				// Set who the message is to be sent from
				$mail->setFrom($this->data['contact_from'], 'Contact Form');
				// Set an alternative reply-to address
				$mail->addReplyTo($this->data['email'], $this->data['name']);
				// Set who the message is to be sent to
				$mail->addAddress($this->data['contact_to'], 'Contact Form');
				// Set the subject line
				$mail->Subject = $this->data['name'].' wrote:';
				// Read an HTML message body from an external file, convert referenced images to embedded,
				// convert HTML into a basic plain-text alternative body
				$mail->msgHTML($this->data['message']);//file_get_contents('contents.html'), dirname(__FILE__)
				// Replace the plain text body with one created manually
				$mail->AltBody = $this->data['message'];
				// Attach an image file
				// $mail->addAttachment('images/phpmailer_mini.png');

				// Send the message, check for errors
				if(!$mail->send()){
					$this->set_error($mail->ErrorInfo);
				}
			}

			if($this->data['contact_mailbox']==1 && $this->error==0){
				// Check if user exist and person exists on contact list already
				$stmt = $this->pdo->prepare("SELECT * FROM edit_users WHERE email=:email LIMIT 1");
				$stmt->bindParam(':email', $this->data['email'], PDO::PARAM_STR, 30);
				$stmt->execute();
				if($stmt->rowCount()){
					$this->item=$stmt->fetch(PDO::FETCH_ASSOC);
					// Get the user name from DB
					$this->data['user_id']=$this->item['id'];
				}else{
					// Set it as Guest
					$this->data['user_id']=0;
				}

				// Insert new contact if not exist
				$stmt2 = $this->pdo->prepare("SELECT * FROM edit_mailbox_contacts WHERE email=:email LIMIT 1");
				$stmt2->bindParam(':email', $this->data['email'], PDO::PARAM_STR, 30);
				$stmt2->execute();
				if(!$stmt2->rowCount()){
					$stmt = $this->pdo->prepare("
						INSERT INTO edit_mailbox_contacts (user_id, email)
						VALUES(".$this->data['user_id'].", '".$this->data['email']."')
					");
					$stmt->execute();
				}

				// Prepare statements to get selected id.
				$stmt = $this->pdo->prepare("
					INSERT INTO edit_mailbox (user_id, title, message, time)
					VALUES('".$this->data['user_id']."', '".$this->data['title']."', '".$this->data['message']."', ".$this->data['time'].")
				");
				$stmt->execute();

				// Get last insert
				$this->item=array(
					"id" => $this->pdo->lastInsertId()
				);

				// Check last insert
				if(!$this->item['id']){
					// Return error if item not created
					$this->set_error('Can not insert item to: edit_mailbox');
				}
			}

			if($this->data['contact_mailme']==0 && $this->data['contact_mailbox']==0){
				$this->set_error('Your contact variables $_CONFIG[contact_mailme] and $_CONFIG[contact_mailbox] are both not configured');
			}
		}
		return $this->once_response();
	}
}
?>


text:
package AsposePdfCloud::Object::WordCountResponse;

require 5.6.0;
use strict;
use warnings;
use utf8;
use JSON qw(decode_json);
use Data::Dumper;
use Module::Runtime qw(use_module);
use Log::Any qw($log);
use Date::Parse;
use DateTime;

use base "AsposePdfCloud::Object::BaseObject";

#
#
#
#NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
#

my $swagger_types = {
    'WordsPerPage' => 'WordCount',
    'Code' => 'string',
    'Status' => 'string'
};

my $attribute_map = {
    'WordsPerPage' => 'WordsPerPage',
    'Code' => 'Code',
    'Status' => 'Status'
};

# new object
sub new {
    my ($class, %args) = @_;
    my $self = {
        #
        'WordsPerPage' => $args{'WordsPerPage'},
        #
        'Code' => $args{'Code'},
        #
        'Status' => $args{'Status'}
    };

    return bless $self, $class;
}

# get swagger type of the attribute
sub get_swagger_types {
    return $swagger_types;
}

# get attribute mappping
sub get_attribute_map {
    return $attribute_map;
}

1;


text:
struct ht_kv_s {
  char *key;
  void *value;
  struct ht_kv_s *next;
};

typedef struct ht_kv_s ht_kv_t;

struct hashtable_s {
  int size;
  int (*destroy_value)(void *);
  int item_count;
  struct ht_kv_s **table;
};

typedef struct hashtable_s hashtable_t;

hashtable_t *ht_create( int size, int (*free_value)(void *) );
void  ht_destroy( hashtable_t *hashtable);
int ht_hash( hashtable_t *hashtable, char *key );
ht_kv_t *ht_pair( char *key, void *value );
void ht_set( hashtable_t *hashtable, char *key, void *value );
void *ht_get( hashtable_t *hashtable, char *key );
int  ht_size(hashtable_t *hashtable);

#endif


text:
require 'test_helper'

class Evergreen::AccountsControllerTest < ActionController::TestCase
  context "on GET to edit" do
    setup do
      @user = Factory :user
      @request.session[:user_id] = @user.id
      get :edit
    end

    should_respond_with :success
    should_render_template :edit
    should_assign_to(:user) { @user }
    should_not_set_the_flash
    should_render_a_form
    should_not_have_missing_translations
  end

  context "on PUT to update with valid attributes" do
    setup do
      @user = Factory :user
      @request.session[:user_id] = @user.id
      User.any_instance.expects(:update_attributes!).returns(true)
      put :update
    end

    should_respond_with :redirect
    should_assign_to(:user) { @user }
    should_set_the_flash_to I18n.t('evergreen.accounts.update.success')
  end

  context "on PUT to update with invalid attributes" do
    setup do
      @user = Factory :user
      @request.session[:user_id] = @user.id
      User.any_instance.expects(:update_attributes!).raises(
        ActiveRecord::RecordInvalid.new(@user))
      put :update
    end

    should_respond_with :success
    should_render_template :edit
    should_assign_to(:user) { @user }
    should_not_set_the_flash
  end
end


text:
int find_index(char *str, char *name) {
  char *pos;
  int n = 0;

  if (!(pos = strstr(str, name)))
    return 0;
  for (int i = 0; str + i != pos; i++) {
    if (isspace(str[i]))
      n++;
  }
  return n;
}

int get_index_value(char *str, int index)
{
  int i = -1;
  int space = 0;

  if (index == 0)
    return 0;
  while (str[++i])
  {
    if (str[i] == ' ')
      space++;
    if (space == index)
      return strtoull(&str[i], NULL, 0);
  }
  return 0;
}

int poll_tcp_metrics(monikor_t *mon, struct timeval *clock)
{
  char *stats;
  char *stat;
  char *value;
  char *end;
  int n = 0;

  if (!(stats = monikor_read_file("/proc/net/snmp")))
    return 0;
  stat = strstr(stats, "Tcp:");
  value = strstr(stat + 1, "Tcp:");
  if (!(end = strchr(stat, '\n')))
    return 0;
  *end = '\0';
  if (!(end = strchr(value, '\n')))
    return 0;
  *end = 0;
  n += monikor_metric_push(mon, monikor_metric_integer("network.tcp.active",
    clock, get_index_value(value, find_index(stat, "ActiveOpens")), MONIKOR_METRIC_TIMEDELTA));
  n += monikor_metric_push(mon, monikor_metric_integer("network.tcp.passive",
    clock, get_index_value(value, find_index(stat, "PassiveOpens")), MONIKOR_METRIC_TIMEDELTA));
  n += monikor_metric_push(mon, monikor_metric_integer("network.tcp.failed",
    clock, get_index_value(value, find_index(stat, "AttemptFails")), MONIKOR_METRIC_TIMEDELTA));
  n += monikor_metric_push(mon, monikor_metric_integer("network.tcp.resets",
    clock, get_index_value(value, find_index(stat, "EstabResets")), MONIKOR_METRIC_TIMEDELTA));
  n += monikor_metric_push(mon, monikor_metric_integer("network.tcp.current",
    clock, get_index_value(value, find_index(stat, "CurrEstab")), 0));
  free(stats);
  return n;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * All information about a single entity available to WebRef. Next available tag: 7
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class RepositoryWebrefWebrefEntity extends com.google.api.client.json.GenericJson {

  /**
   * Information about links (e.g. implications) between the annotated entities.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<RepositoryWebrefWebrefEntityRelationship> annotatedRelationship;

  /**
   * All annotations of this entity on the given document.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefEntityAnnotations annotations;

  /**
   * Information about the collections of this entity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefWebrefEntityCollections collections;

  /**
   * Metadata and raw signals used by the annotator.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefEntityJoin entityJoin;

  /**
   * An identifier (usually a MID) for the entity. Consider using GetWebrefEntityMid() in the
   * adjacent webref-entities-util.h to read this.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private RepositoryWebrefWebrefEntityId id;

  /**
   * MRF equivalent representations of this entity as a compound, one for each unique MRF
   * representation. Populated for compounds. Each MRF expression contains a minimum FunctionCall
   * structure wrapped in a nameless Argument without signals and range data. This is not meant to
   * be directly usable as MRF, use QueryJoinToMeaningStructConverter to expand it into a usable
   * form. References to entities are made as component_reference ArgumentValue. Each compound
   * Mention of this entity (not all of its mentions need be compounds, some may be plain entity
   * mentions) have one or more compound_value fields claiming these MRF expressions via their
   * mrf_index. The compound_value has nested components, one for each unique
   * component_reference.index in the MRF expression. The processing expectation is that each
   * ArgumentValue which has a component_reference has its contents discarded and replaced with the
   * MRF for the target entity and mention named by the compound_value.component. If the target is
   * not a compound, the ArgumentValue becomes a simple mid value and the signals are taken from the
   * entity and the mention. If the target is a compound itself, the expansion continues
   * recursively. If the target is a compound with multiple MRFs, a cartesian product of recursive
   * expansions may need to be produced. Along with the component_reference we also emit an example
   * value, but this is purely for human consumption so it's easier to understand what the full
   * compound is like. The processing expectation remains that the ArgumentValue containing a
   * component_reference is completely discarded and rebuilt with the reference target value. If the
   * target has more than one MRF expression, it's not specified which one will be used as an
   * example, except that the choice is guaranteed to be deterministic from run to run.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<KnowledgeAnswersIntentQueryArgument> mrf;

  static {
    // hack to force ProGuard to consider KnowledgeAnswersIntentQueryArgument used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(KnowledgeAnswersIntentQueryArgument.class);
  }

  /**
   * Information about links (e.g. implications) between the annotated entities.
   * @return value or {@code null} for none
   */
  public java.util.List<RepositoryWebrefWebrefEntityRelationship> getAnnotatedRelationship() {
    return annotatedRelationship;
  }

  /**
   * Information about links (e.g. implications) between the annotated entities.
   * @param annotatedRelationship annotatedRelationship or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setAnnotatedRelationship(java.util.List<RepositoryWebrefWebrefEntityRelationship> annotatedRelationship) {
    this.annotatedRelationship = annotatedRelationship;
    return this;
  }

  /**
   * All annotations of this entity on the given document.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefEntityAnnotations getAnnotations() {
    return annotations;
  }

  /**
   * All annotations of this entity on the given document.
   * @param annotations annotations or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setAnnotations(RepositoryWebrefEntityAnnotations annotations) {
    this.annotations = annotations;
    return this;
  }

  /**
   * Information about the collections of this entity.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefWebrefEntityCollections getCollections() {
    return collections;
  }

  /**
   * Information about the collections of this entity.
   * @param collections collections or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setCollections(RepositoryWebrefWebrefEntityCollections collections) {
    this.collections = collections;
    return this;
  }

  /**
   * Metadata and raw signals used by the annotator.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefEntityJoin getEntityJoin() {
    return entityJoin;
  }

  /**
   * Metadata and raw signals used by the annotator.
   * @param entityJoin entityJoin or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setEntityJoin(RepositoryWebrefEntityJoin entityJoin) {
    this.entityJoin = entityJoin;
    return this;
  }

  /**
   * An identifier (usually a MID) for the entity. Consider using GetWebrefEntityMid() in the
   * adjacent webref-entities-util.h to read this.
   * @return value or {@code null} for none
   */
  public RepositoryWebrefWebrefEntityId getId() {
    return id;
  }

  /**
   * An identifier (usually a MID) for the entity. Consider using GetWebrefEntityMid() in the
   * adjacent webref-entities-util.h to read this.
   * @param id id or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setId(RepositoryWebrefWebrefEntityId id) {
    this.id = id;
    return this;
  }

  /**
   * MRF equivalent representations of this entity as a compound, one for each unique MRF
   * representation. Populated for compounds. Each MRF expression contains a minimum FunctionCall
   * structure wrapped in a nameless Argument without signals and range data. This is not meant to
   * be directly usable as MRF, use QueryJoinToMeaningStructConverter to expand it into a usable
   * form. References to entities are made as component_reference ArgumentValue. Each compound
   * Mention of this entity (not all of its mentions need be compounds, some may be plain entity
   * mentions) have one or more compound_value fields claiming these MRF expressions via their
   * mrf_index. The compound_value has nested components, one for each unique
   * component_reference.index in the MRF expression. The processing expectation is that each
   * ArgumentValue which has a component_reference has its contents discarded and replaced with the
   * MRF for the target entity and mention named by the compound_value.component. If the target is
   * not a compound, the ArgumentValue becomes a simple mid value and the signals are taken from the
   * entity and the mention. If the target is a compound itself, the expansion continues
   * recursively. If the target is a compound with multiple MRFs, a cartesian product of recursive
   * expansions may need to be produced. Along with the component_reference we also emit an example
   * value, but this is purely for human consumption so it's easier to understand what the full
   * compound is like. The processing expectation remains that the ArgumentValue containing a
   * component_reference is completely discarded and rebuilt with the reference target value. If the
   * target has more than one MRF expression, it's not specified which one will be used as an
   * example, except that the choice is guaranteed to be deterministic from run to run.
   * @return value or {@code null} for none
   */
  public java.util.List<KnowledgeAnswersIntentQueryArgument> getMrf() {
    return mrf;
  }

  /**
   * MRF equivalent representations of this entity as a compound, one for each unique MRF
   * representation. Populated for compounds. Each MRF expression contains a minimum FunctionCall
   * structure wrapped in a nameless Argument without signals and range data. This is not meant to
   * be directly usable as MRF, use QueryJoinToMeaningStructConverter to expand it into a usable
   * form. References to entities are made as component_reference ArgumentValue. Each compound
   * Mention of this entity (not all of its mentions need be compounds, some may be plain entity
   * mentions) have one or more compound_value fields claiming these MRF expressions via their
   * mrf_index. The compound_value has nested components, one for each unique
   * component_reference.index in the MRF expression. The processing expectation is that each
   * ArgumentValue which has a component_reference has its contents discarded and replaced with the
   * MRF for the target entity and mention named by the compound_value.component. If the target is
   * not a compound, the ArgumentValue becomes a simple mid value and the signals are taken from the
   * entity and the mention. If the target is a compound itself, the expansion continues
   * recursively. If the target is a compound with multiple MRFs, a cartesian product of recursive
   * expansions may need to be produced. Along with the component_reference we also emit an example
   * value, but this is purely for human consumption so it's easier to understand what the full
   * compound is like. The processing expectation remains that the ArgumentValue containing a
   * component_reference is completely discarded and rebuilt with the reference target value. If the
   * target has more than one MRF expression, it's not specified which one will be used as an
   * example, except that the choice is guaranteed to be deterministic from run to run.
   * @param mrf mrf or {@code null} for none
   */
  public RepositoryWebrefWebrefEntity setMrf(java.util.List<KnowledgeAnswersIntentQueryArgument> mrf) {
    this.mrf = mrf;
    return this;
  }

  @Override
  public RepositoryWebrefWebrefEntity set(String fieldName, Object value) {
    return (RepositoryWebrefWebrefEntity) super.set(fieldName, value);
  }

  @Override
  public RepositoryWebrefWebrefEntity clone() {
    return (RepositoryWebrefWebrefEntity) super.clone();
  }

}


text:
using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Autofac;
using Mina.Transport.Socket;
using Mina.Core.Session;
using CTPPV5.Rpc.Net.Message;
using CTPPV5.Infrastructure.Extension;
using CTPPV5.Infrastructure.Util;
using CTPPV5.Infrastructure;
using CTPPV5.Infrastructure.Consts;
using System.Text.RegularExpressions;

namespace CTPPV5.Rpc.Net.Client
{
    public class AsyncSessionFactoryImpl : IAsyncSessionFactory<DuplexMessage>
    {
        private DoubleCheckLock doubleCheckLock;
        private ConcurrentDictionary<string, IAsyncSession<DuplexMessage>> sessionMap;
        private object syncRoot = new object();
        private const int WRITER_IDLE_TIME = 60 * 5;
        private const int HEARTBEAT_TIMEOUT = 5;

        public AsyncSessionFactoryImpl()
        {
            doubleCheckLock = new DoubleCheckLock();
            sessionMap = new ConcurrentDictionary<string, IAsyncSession<DuplexMessage>>();
        }

        public IAsyncSession<DuplexMessage> OpenSession()
        {
            IPEndPoint endpoint = null;
            IAsyncSession<DuplexMessage> session = null;
            using (var scope = ObjectHost.Host.BeginLifetimeScope())
            {
                var selector = scope.Resolve<IRemoteEndPointSelector>();
                while (selector.TryPick(out endpoint))
                {
                    try
                    {
                        session = OpenSession(new ConnectionConfig(endpoint));
                        if (!session.Connected)
                        {
                            selector.MarkDown(endpoint);
                            session = null;
                        }
                        else break;
                    }
                    catch (Exception)
                    {
                        selector.MarkDown(endpoint);
                    }
                }
                if (session == null)
                    throw new SessionOpenException(endpoint);
                return session;
            }
        }

        /// <summary>
        /// open session with connectionstring
        /// </summary>
        /// <param name="connectionString">
        /// format: 127.0.0.1:1433;timeout=5;keepalive=true;
        /// </param>
        /// <returns></returns>
        public IAsyncSession<DuplexMessage> OpenSession(string connectionString)
        {
            ConnectionConfig config = null;
            if (!ConnectionConfig.TryParse(connectionString, out config))
            {
                throw new ArgumentException(
                    string.Format(ExceptionMessage.INVALID_SESSION_CONNECT_STRING, connectionString));
            }
            return OpenSession(config);
        }

        public IAsyncSession<DuplexMessage> OpenSession(IoSession ioSession)
        {
            IAsyncSession<DuplexMessage> session = null;
            using (var locker = doubleCheckLock.Accquire(
                () => sessionMap.TryGetValue(ioSession.RemoteEndPoint.ToString(), out session)))
            {
                if (locker.Locked)
                {
                    using (var scope = ObjectHost.Host.BeginLifetimeScope())
                    {
                        session = scope.Resolve<IAsyncSession<DuplexMessage>>(
                            new NamedParameter("heartbeatTimeout", HEARTBEAT_TIMEOUT),
                            new NamedParameter("writerIdleTime", WRITER_IDLE_TIME));
                        if (session.Open(ioSession))
                            sessionMap[ioSession.RemoteEndPoint.ToString()] = session;
                        else
                            throw new SessionOpenException(ioSession.RemoteEndPoint as IPEndPoint);
                    }
                }
                else
                {
                    sessionMap.TryRemove(ioSession.RemoteEndPoint.ToString(), out session);
                    throw new SessionOpenException(ioSession.RemoteEndPoint as IPEndPoint);
                }
            }

            return session;
        }

        private IAsyncSession<DuplexMessage> OpenSession(ConnectionConfig config)
        {
            IAsyncSession<DuplexMessage> session = null;
            using (var locker = doubleCheckLock.Accquire(
                () => !sessionMap.TryGetValue(config.EndPoint.ToString(), out session)))
            {
                if (locker.Locked)
                {
                    using (var scope = ObjectHost.Host.BeginLifetimeScope())
                    {
                        session = scope.Resolve<IAsyncSession<DuplexMessage>>(
                            new NamedParameter("heartbeatTimeout", HEARTBEAT_TIMEOUT),
                            new NamedParameter("writerIdleTime", WRITER_IDLE_TIME));
                        session.Open(config);
                        sessionMap[config.EndPoint.ToString()] = session;
                    }
                }
                else
                {
                    if (!session.Connected)
                    {
                        sessionMap.TryRemove(config.EndPoint.ToString(), out session);
                        session = OpenSession(config);
                    }
                }
            }

            return session;
        }
    }
}


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

<title>TypeSizes.VIntEncodedTypeSizes (apache-cassandra API)</title>
<meta name="date" content="2014-09-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.db

Class TypeSizes.VIntEncodedTypeSizes

java.lang.Object

org.apache.cassandra.db.TypeSizes

org.apache.cassandra.db.TypeSizes.VIntEncodedTypeSizes

Enclosing class:

TypeSizes

public static class TypeSizes.VIntEncodedTypeSizes
extends TypeSizes

Nested Class Summary

Nested classes/interfaces inherited from class org.apache.cassandra.db.TypeSizes

TypeSizes.NativeDBTypeSizes, TypeSizes.VIntEncodedTypeSizes

Field Summary

Fields inherited from class org.apache.cassandra.db.TypeSizes

NATIVE, VINT

Constructor Summary

Constructors

Constructor and Description

TypeSizes.VIntEncodedTypeSizes()

Method Summary

Methods

Modifier and Type
Method and Description

int
sizeof(boolean i)

int
sizeof(int i)

int
sizeof(long i)

int
sizeof(short i)

int
sizeof(java.util.UUID value)

int
sizeofVInt(long i)

Methods inherited from class org.apache.cassandra.db.TypeSizes

encodedUTF8Length, sizeof, sizeofWithLength, sizeofWithShortLength

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

TypeSizes.VIntEncodedTypeSizes

public TypeSizes.VIntEncodedTypeSizes()

Method Detail

sizeofVInt

public int sizeofVInt(long i)

sizeof

public int sizeof(long i)

Specified by:

sizeof in class TypeSizes

sizeof

public int sizeof(boolean i)

Specified by:

sizeof in class TypeSizes

sizeof

public int sizeof(short i)

Specified by:

sizeof in class TypeSizes

sizeof

public int sizeof(int i)

Specified by:

sizeof in class TypeSizes

sizeof

public int sizeof(java.util.UUID value)

Specified by:

sizeof in class TypeSizes

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2014 The Apache Software Foundation


text:
import matplotlib as mt
backend = mt.get_backend()
if backend == 'agg':
    mt.use('TKagg')
import pypiv
import numpy as np
import matplotlib.pyplot as plt
from glob import glob

def main():
    imgs = ['images/finger1.png', 'images/finger2.png']
    frames = [plt.imread(x) for x in imgs]
    frame_a, frame_b = frames[0], frames[1]

    frame_a_inv = np.copy(frame_a[::-1,::-1])
    frame_b_inv = np.copy(frame_b[::-1,::-1])

    piv = do_piv(frame_a, frame_b, True)
    piv_inv = do_piv(frame_a_inv, frame_b_inv, True)

    piv_noerror = do_piv(frame_a, frame_b, False)
    piv_inv_noerror = do_piv(frame_a_inv, frame_b_inv, False)

    u = piv.u
    ui = piv_inv.u[::-1, ::-1]

    u_noerror = piv_noerror.u
    ui_noerror = piv_inv_noerror.u[::-1, ::-1]

    u[np.isnan(u)] = 1000.
    ui[np.isnan(ui)] = -1000.

    u_noerror[np.isnan(u)] = 1000.
    ui_noerror[np.isnan(ui)] = -1000.

    f, (ax1, ax2) = plt.subplots(1, 2)
    f.canvas.set_window_title("Plot with outlier detection")
    ax1.imshow(u, interpolation='nearest')
    ax1.set_title("unrotated")
    ax2.imshow(-ui, interpolation='nearest')
    ax2.set_title("rotated")

    f, (ax1, ax2) = plt.subplots(1, 2)
    f.canvas.set_window_title("Plot without outlier detection")
    ax1.imshow(u_noerror, interpolation='nearest')
    ax1.set_title("unrotated")
    ax2.imshow(-ui_noerror, interpolation='nearest')
    ax2.set_title("rotated")

    print "difference with error: {}".format(np.sum(u+ui))
    print "difference without er: {}".format(np.sum(u_noerror+ui_noerror))

    plt.show()

def do_piv(frame_a, frame_b,outlier=True):
    """
    for finding the error use the boolean variable outlier
    to use or not use the outlier detection and replacement
    """

    #PIV1
    piv = pypiv.DirectPIV(frame_a, frame_b, window_size=32,
                            search_size=32, distance=16)
    piv.correlate_frames()
    if outlier:
        pypiv.filters.outlier_from_local_median(piv, 2.0)
        pypiv.filters.replace_outliers(piv)
    pypiv.filters.median_filter(piv)

    #PIV2
    piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=16)
    piv.correlate_frames()

    if outlier:
        pypiv.filters.outlier_from_local_median(piv, 2.0)
        pypiv.filters.replace_outliers(piv)
    pypiv.filters.median_filter(piv)

    #PIV3
    piv = pypiv.AdaptivePIV(piv, window_size=32,
                                  search_size=32, distance=8)
    piv.correlate_frames()
    if outlier:
        pypiv.filters.outlier_from_local_median(piv, 2.0)
        pypiv.filters.replace_outliers(piv)
    pypiv.filters.median_filter(piv)

    return piv

if __name__=='__main__':
    main()


text:
import { mount } from '@vue/test-utils';
import { TEST_HOST } from 'jest/helpers/test_constants';
import { formatDate } from '~/lib/utils/datetime_utility';
import RelatedIssuableItem from '~/vue_shared/components/issue/related_issuable_item.vue';
import IssueDueDate from '~/boards/components/issue_due_date.vue';
import { defaultAssignees, defaultMilestone } from './related_issuable_mock_data';

describe('RelatedIssuableItem', () => {
  let wrapper;

  function mountComponent({ mountMethod = mount, stubs = {}, props = {}, slots = {} } = {}) {
    wrapper = mountMethod(RelatedIssuableItem, {
      propsData: props,
      slots,
      stubs,
    });
  }

  const props = {
    idKey: 1,
    displayReference: 'gitlab-org/gitlab-test#1',
    pathIdSeparator: '#',
    path: `${TEST_HOST}/path`,
    title: 'title',
    confidential: true,
    dueDate: '1990-12-31',
    weight: 10,
    createdAt: '2018-12-01T00:00:00.00Z',
    milestone: defaultMilestone,
    assignees: defaultAssignees,
    eventNamespace: 'relatedIssue',
  };
  const slots = {
    dueDate: '

',
    weight: '

',
  };

  const findRemoveButton = () => wrapper.find({ ref: 'removeButton' });
  const findLockIcon = () => wrapper.find({ ref: 'lockIcon' });

  beforeEach(() => {
    mountComponent({ props, slots });
  });

  afterEach(() => {
    wrapper.destroy();
  });

  it('contains issuable-info-container class when canReorder is false', () => {
    expect(wrapper.props('canReorder')).toBe(false);
    expect(wrapper.find('.issuable-info-container').exists()).toBe(true);
  });

  it('does not render token state', () => {
    expect(wrapper.find('.text-secondary svg').exists()).toBe(false);
  });

  it('does not render remove button', () => {
    expect(wrapper.find({ ref: 'removeButton' }).exists()).toBe(false);
  });

  describe('token title', () => {
    it('links to computedPath', () => {
      expect(wrapper.find('.item-title a').attributes('href')).toEqual(wrapper.props('path'));
    });

    it('renders confidential icon', () => {
      expect(wrapper.find('.confidential-icon').exists()).toBe(true);
    });

    it('renders title', () => {
      expect(wrapper.find('.item-title a').text()).toEqual(props.title);
    });
  });

  describe('token state', () => {
    const tokenState = () => wrapper.find({ ref: 'iconElementXL' });

    beforeEach(() => {
      wrapper.setProps({ state: 'opened' });
    });

    it('renders if hasState', () => {
      expect(tokenState().exists()).toBe(true);
    });

    it('renders state title', () => {
      const stateTitle = tokenState().attributes('title');
      const formattedCreateDate = formatDate(props.createdAt);

      expect(stateTitle).toContain('Opened');
      expect(stateTitle).toContain(`<span class="text-tertiary">${formattedCreateDate}</span>`);
    });

    it('renders aria label', () => {
      expect(tokenState().attributes('aria-label')).toEqual('opened');
    });

    it('renders open icon when open state', () => {
      expect(tokenState().classes('issue-token-state-icon-open')).toBe(true);
    });

    it('renders close icon when close state', async () => {
      wrapper.setProps({
        state: 'closed',
        closedAt: '2018-12-01T00:00:00.00Z',
      });
      await wrapper.vm.$nextTick();

      expect(tokenState().classes('issue-token-state-icon-closed')).toBe(true);
    });
  });

  describe('token metadata', () => {
    const tokenMetadata = () => wrapper.find('.item-meta');

    it('renders item path and ID', () => {
      const pathAndID = tokenMetadata()
        .find('.item-path-id')
        .text();

      expect(pathAndID).toContain('gitlab-org/gitlab-test');
      expect(pathAndID).toContain('#1');
    });

    it('renders milestone icon and name', () => {
      const milestoneIcon = tokenMetadata().find('.item-milestone svg');
      const milestoneTitle = tokenMetadata().find('.item-milestone .milestone-title');

      expect(milestoneIcon.attributes('data-testid')).toBe('clock-icon');
      expect(milestoneTitle.text()).toContain('Milestone title');
    });

    it('renders due date component with correct due date', () => {
      expect(wrapper.find(IssueDueDate).props('date')).toBe(props.dueDate);
    });
  });

  describe('token assignees', () => {
    it('renders assignees avatars', () => {
      // Expect 2 times 2 because assignees are rendered twice, due to layout issues
      expect(wrapper.findAll('.item-assignees .user-avatar-link').length).toBeDefined();

      expect(wrapper.find('.item-assignees .avatar-counter').text()).toContain('+2');
    });
  });

  describe('remove button', () => {
    beforeEach(() => {
      wrapper.setProps({ canRemove: true });
    });

    it('renders if canRemove', () => {
      expect(findRemoveButton().exists()).toBe(true);
    });

    it('does not render the lock icon', () => {
      expect(findLockIcon().exists()).toBe(false);
    });

    it('renders disabled button when removeDisabled', async () => {
      wrapper.setData({ removeDisabled: true });
      await wrapper.vm.$nextTick();

      expect(findRemoveButton().attributes('disabled')).toEqual('disabled');
    });

    it('triggers onRemoveRequest when clicked', async () => {
      findRemoveButton().trigger('click');
      await wrapper.vm.$nextTick();
      const { relatedIssueRemoveRequest } = wrapper.emitted();

      expect(relatedIssueRemoveRequest.length).toBe(1);
      expect(relatedIssueRemoveRequest[0]).toEqual([props.idKey]);
    });
  });

  describe('when issue is locked', () => {
    const lockedMessage = 'Issues created from a vulnerability cannot be removed';

    beforeEach(() => {
      wrapper.setProps({
        isLocked: true,
        lockedMessage,
      });
    });

    it('does not render the remove button', () => {
      expect(findRemoveButton().exists()).toBe(false);
    });

    it('renders the lock icon with the correct title', () => {
      expect(findLockIcon().attributes('title')).toBe(lockedMessage);
    });
  });
});


text:
<bibtex>
  <entry tag="loremIpsum" category="book">
    <field name="title">Lorem ipsum</field>
    <field name="author">dolor sit</field>
    <field name="amet">consectetur adipisicing</field>
    <field name="elit">sed do eiusmod</field>
  </entry>
  <entry tag="khatt" category="online">
    <field name="title">Ubaydullāh ibn Abī Rāfi</field>
    <field name="author">Alī ibn Abī Ṭālib</field>
  </entry>
  <entry tag="temporIncididunt" category="article">
    <field name="title">ut labore et dolore magna aliqua.</field>
    <field name="author">Ut enim ad minim veniam</field>
  </entry>
</bibtex>


text:
namespace Google.Cloud.GkeBackup.V1.Snippets
{
    // [START gkebackup_v1_generated_BackupForGKE_ListBackupPlans_async_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.GkeBackup.V1;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedBackupForGKEClientSnippets
    {
        /// <summary>Snippet for ListBackupPlansAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task ListBackupPlansResourceNamesAsync()
        {
            // Create client
            BackupForGKEClient backupForGKEClient = await BackupForGKEClient.CreateAsync();
            // Initialize request argument(s)
            LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
            // Make the request
            PagedAsyncEnumerable<ListBackupPlansResponse, BackupPlan> response = backupForGKEClient.ListBackupPlansAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((BackupPlan item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListBackupPlansResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (BackupPlan item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<BackupPlan> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (BackupPlan item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END gkebackup_v1_generated_BackupForGKE_ListBackupPlans_async_flattened_resourceNames]
}


text:
#import "FBSimulatorHistory.h"
#import "FBSimulatorHistory+Private.h"

#import <FBControlCore/FBControlCore.h>

#import "FBSimulator+Helpers.h"

NSString *const FBSimulatorHistoryDiagnosticNameTerminationStatus = @"termination_status";

@implementation FBSimulatorHistory

- (instancetype)init
{
  self = [super init];
  if (!self) {
    return nil;
  }

  _timestamp = [NSDate date];
  _mutableLaunchedProcesses = [NSMutableOrderedSet orderedSet];
  _mutableProcessLaunchConfigurations = [NSMutableDictionary dictionary];
  _mutableProcessMetadata = [NSMutableDictionary dictionary];

  return self;
}

#pragma mark NSCopying

- (instancetype)copyWithZone:(NSZone *)zone
{
  FBSimulatorHistory *history = [self.class new];
  history.timestamp = self.timestamp;
  history.simulatorState = self.simulatorState;
  history.previousState = self.previousState;
  history.mutableLaunchedProcesses = [self.mutableLaunchedProcesses mutableCopy];
  history.mutableProcessLaunchConfigurations = [self.mutableProcessLaunchConfigurations mutableCopy];
  history.mutableProcessMetadata = [self.mutableProcessMetadata mutableCopy];
  return history;
}

#pragma mark NSCoding

- (instancetype)initWithCoder:(NSCoder *)coder
{
  self = [super init];
  if (!self) {
    return nil;
  }

  _timestamp = [coder decodeObjectForKey:NSStringFromSelector(@selector(timestamp))];
  _simulatorState = (FBSimulatorState) [[coder decodeObjectForKey:NSStringFromSelector(@selector(simulatorState))] unsignedIntegerValue];
  _previousState = [coder decodeObjectForKey:NSStringFromSelector(@selector(previousState))];
  _mutableLaunchedProcesses = [[coder decodeObjectForKey:NSStringFromSelector(@selector(mutableLaunchedProcesses))] mutableCopy];
  _mutableProcessLaunchConfigurations = [[coder decodeObjectForKey:NSStringFromSelector(@selector(mutableProcessLaunchConfigurations))] mutableCopy];
  _mutableProcessMetadata = [[coder decodeObjectForKey:NSStringFromSelector(@selector(mutableProcessMetadata))] mutableCopy];

  return self;
}

- (void)encodeWithCoder:(NSCoder *)coder
{
  [coder encodeObject:self.timestamp forKey:NSStringFromSelector(@selector(timestamp))];
  [coder encodeObject:@(self.simulatorState) forKey:NSStringFromSelector(@selector(simulatorState))];
  [coder encodeObject:self.previousState forKey:NSStringFromSelector(@selector(previousState))];
  [coder encodeObject:self.mutableLaunchedProcesses forKey:NSStringFromSelector(@selector(mutableLaunchedProcesses))];
  [coder encodeObject:self.mutableProcessLaunchConfigurations forKey:NSStringFromSelector(@selector(mutableProcessLaunchConfigurations))];
  [coder encodeObject:self.mutableProcessMetadata forKey:NSStringFromSelector(@selector(mutableProcessMetadata))];
}

#pragma mark Accessors

- (NSArray *)launchedProcesses
{
  return self.mutableLaunchedProcesses.array;
}

- (NSDictionary *)processLaunchConfigurations
{
  return [self.mutableProcessLaunchConfigurations copy];
}

- (NSDictionary *)processMetadata
{
  return [self.mutableProcessMetadata copy];
}

#pragma mark NSObject

- (NSUInteger)hash
{
  return self.timestamp.hash |
         (unsigned long) self.simulatorState |
         self.mutableLaunchedProcesses.hash |
        (self.mutableProcessLaunchConfigurations.hash ^
         self.mutableProcessMetadata.hash);
}

- (BOOL)isEqual:(FBSimulatorHistory *)object
{
  if (![object isKindOfClass:self.class]) {
    return NO;
  }
  return ((self.previousState == nil && object.previousState == nil) || [self.previousState isEqual:object.previousState]) &&
         [self.timestamp isEqual:object.timestamp] &&
         self.simulatorState == object.simulatorState &&
         [self.mutableLaunchedProcesses isEqualToOrderedSet:object.mutableLaunchedProcesses] &&
         [self.mutableProcessLaunchConfigurations isEqualToDictionary:object.mutableProcessLaunchConfigurations] &&
         [self.mutableProcessMetadata isEqualToDictionary:object.mutableProcessMetadata];
}

#pragma mark Description

- (NSString *)description
{
  return [NSString stringWithFormat:
    @"History -> %@",
    [FBSimulatorHistory describeDifferenceFrom:self.previousState to:self]
  ];
}

- (NSString *)recursiveChangeDescription
{
  NSMutableString *string = [NSMutableString string];
  [self recursiveChangeDescriptionWithMutableString:string];
  return string;
}

- (void)recursiveChangeDescriptionWithMutableString:(NSMutableString *)string
{
  if (self.previousState) {
    [self.previousState recursiveChangeDescriptionWithMutableString:string];
  }
  [string appendFormat:@"%@\n", [FBSimulatorHistory describeDifferenceFrom:self.previousState to:self]];
}

+ (NSString *)describeDifferenceFrom:(FBSimulatorHistory *)from to:(FBSimulatorHistory *)to
{
  NSParameterAssert(to);
  if (!from) {
    return @"Inital State";
  }
  NSMutableString *string = [NSMutableString stringWithFormat:@"%@ -> ", to.timestamp];
  if (to.simulatorState != from.simulatorState) {
    [string appendFormat:
      @"Simulator State from %@ to %@ | ",
      [FBSimulator stateStringFromSimulatorState:from.simulatorState],
      [FBSimulator stateStringFromSimulatorState:to.simulatorState]
    ];
  }
  if (![to.mutableLaunchedProcesses isEqualToOrderedSet:from.mutableLaunchedProcesses]) {
    [string appendFormat:
      @"Running Processes from %@ to %@ | ",
      [FBCollectionInformation oneLineDescriptionFromArray:from.mutableLaunchedProcesses.array atKeyPath:@"shortDescription"],
      [FBCollectionInformation oneLineDescriptionFromArray:to.mutableLaunchedProcesses.array atKeyPath:@"shortDescription"]
    ];
  }
  if (![to.mutableProcessMetadata isEqualToDictionary:from.mutableProcessMetadata]) {
    [string appendFormat:@"Process Metadata from %@ to %@ | ",
      [FBCollectionInformation oneLineDescriptionFromDictionary:from.mutableProcessMetadata],
      [FBCollectionInformation oneLineDescriptionFromDictionary:to.mutableProcessMetadata]
    ];
  }
  if (string.length == 0) {
    return @"No Changes";
  }
  return string;
}

@end


text:
<?php

namespace lib;

/**
* Tous les controlleurs
*/
abstract class Controller
{
	private $post;
	private $db;

	public function __construct($post, $db) {
		$this->post = $post;
		$this->db = $db;
	}

	abstract public function run($action);

	public function get404() {
		return ['error' => 404];
	}

	public function get($index) {
		return empty($this->post[$index]) ? null : $this->post[$index];
	}

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


text:
<?php

const SITE_URL = "http://darkoux.com/";
const SITE_ROOT = __DIR__;
$projects = array(
	'citizenshipper',
	'giftconnect',
	'buzzit',
	'fast',
	'ourhouse',
	'p28',
	'soundmap'
);

$bodyClass = "page-landing";

if(array_key_exists('project', $_GET)) {
	$project = $_GET['project'];
	if(! in_array($project, $projects)) {
		header("Location: " . SITE_URL);
		die();
	}

	$bodyClass = "page-project project-{$project}";
}

require_once('views/header.php');

if(isset($project)) {
	require_once(SITE_ROOT . "/views/project-header.php");
	require_once(SITE_ROOT . "/projects/{$project}/content.php");
	require_once(SITE_ROOT . "/views/outro.php");
}
else {
	require_once(SITE_ROOT . "/views/landing.php");
	require_once(SITE_ROOT . "/views/outro.php");
}

require_once('views/footer.php');


text:
<?php
return [
    /*'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'extensions' => require(__DIR__ . '/../vendor/yiisoft/extensions.php'),
    'components' => require(__DIR__ . '/components.php'),*/
];


text:
import { FieldSchema } from '@ephox/boulder';
import { Fun, Optional } from '@ephox/katamari';

import { Coupling } from '../../api/behaviour/Coupling';
import { Focusing } from '../../api/behaviour/Focusing';
import { Keying } from '../../api/behaviour/Keying';
import { Toggling } from '../../api/behaviour/Toggling';
import * as SketchBehaviours from '../../api/component/SketchBehaviours';
import * as Fields from '../../data/Fields';
import * as SketcherFields from '../../data/SketcherFields';
import * as InternalSink from '../../parts/InternalSink';
import * as PartType from '../../parts/PartType';
import * as AnchorLayouts from '../../positioning/mode/AnchorLayouts';
import { DropdownDetail, DropdownSpec } from '../types/DropdownTypes';

const schema = Fun.constant([
  FieldSchema.required('dom'),
  FieldSchema.required('fetch'),
  Fields.onHandler('onOpen'),
  Fields.onKeyboardHandler('onExecute'),
  FieldSchema.defaulted('getHotspot', Optional.some),
  FieldSchema.defaulted('getAnchorOverrides', Fun.constant({ })),
  AnchorLayouts.schema(),
  SketchBehaviours.field('dropdownBehaviours', [ Toggling, Coupling, Keying, Focusing ]),
  FieldSchema.required('toggleClass'),
  FieldSchema.defaulted('eventOrder', { }),
  FieldSchema.option('lazySink'),
  FieldSchema.defaulted('matchWidth', false),
  FieldSchema.defaulted('useMinWidth', false),
  FieldSchema.option('role')
].concat(
  SketcherFields.sandboxFields()
));

const parts: () => PartType.PartTypeAdt[] = Fun.constant([
  PartType.external<DropdownDetail, DropdownSpec>({
    schema: [
      Fields.tieredMenuMarkers(),
      // Defining a defaulted field isn't necessary when dealing with
      // external parts, because the post-boulder part spec is not passed
      // through to any of these functions (defaults, overrides etc.). So all
      // this does is make it a bit clearer what you should expect, but remember
      // that the default value here is irrelevant!
      FieldSchema.defaulted('fakeFocus', false)
    ],
    name: 'menu',
    defaults: (detail) => {
      return {
        onExecute: detail.onExecute
      };
    }
  }),

  InternalSink.partType()
]);

const name = Fun.constant('Dropdown');

export {
  name,
  schema,
  parts
};


text:
<?php

namespace App\Transformers;

use App\Models\Comment;
use League\Fractal\ParamBag;
use League\Fractal\TransformerAbstract as BaseTransformerAbstract;

class CommentTransformer extends BaseTransformerAbstract
{
    /**
     * Include resources without needing it to be requested.
     *
     * @var array
     */
    protected $defaultIncludes = ['user'];

    /**
     * Transform a model.
     *
     * @return array
     */
    public function transform(Comment $comment)
    {
        return [
            'id'      => $comment->id,
            'content' => $comment->content,
            'created_at' => $comment->created_at->toDateTimeString(),
        ];
    }

    /**
     * Includer user
     *
     * @param  Post   $post
     *
     * @return mixed
     */
    public function includeUser(Comment $comment)
    {
        return $this->item($comment->githubUser, new GithubUserTransformer());
    }
}


text:
namespace Microsoft.Azure.Management.DataLake.Store.Models
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Azure.Management.DataLake;
    using Microsoft.Azure.Management.DataLake.Store;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using System.Runtime;
    using System.Runtime.Serialization;

    /// <summary>
    /// Defines values for EncryptionConfigType.
    /// </summary>
    [JsonConverter(typeof(StringEnumConverter))]
    public enum EncryptionConfigType
    {
        [EnumMember(Value = "UserManaged")]
        UserManaged,
        [EnumMember(Value = "ServiceManaged")]
        ServiceManaged
    }
}


text:
Premature optimization

        <q>
        “Uno tiende a pensar en factores externos y termina perdiendo tiempo en problemas que quizás nunca sucedan..”</q>

          — Luciano (Lucho) Longo

Optimize later!

No sobre diseñar y no optimizar de más.

      Don't code for performance. Code for clarity, correctness and maintainability.

      Saber de complejidad algorítmica nos ayuda a distinguir lo que sí vale la pena optimizar

      (la optimización que no es prematura)


text:
using JetBrains.ActionManagement;
using JetBrains.Application.DataContext;
using JetBrains.Util;
using DataConstants = JetBrains.ProjectModel.DataContext.DataConstants;

namespace Codevolve.StyleDetect
{
    /// <summary>
    /// Detect style action to show statistics.
    /// </summary>
    [ActionHandler("Codevolve.StyleDetect.DetectStyle")]
    public class DetectStyleAction : IActionHandler
    {
        #region Implementation of IActionHandler

        /// <summary>
        /// Updates action visual presentation. If presentation.Enabled is set to false, Execute
        ///             will not be called.
        /// </summary>
        /// <param name="context">DataContext</param><param name="presentation">presentation to update</param><param name="nextUpdate">delegate to call</param>
        public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
        {
            var solution = context.GetData(DataConstants.SOLUTION);
            bool visible = solution != null;

            if (!visible)
            {
                presentation.Visible = false;
            }

            return visible;
        }

        /// <summary>
        /// Executes action. Called after Update, that set ActionPresentation.Enabled to true.
        /// </summary>
        /// <param name="context">DataContext</param><param name="nextExecute">delegate to call</param>
        public void Execute(IDataContext context, DelegateExecute nextExecute)
        {
            MessageBox.ShowInfo("Test");
        }

        #endregion
    }
}


text:
package com.badlogic.gdx.tools.flame;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.badlogic.gdx.graphics.g3d.particles.values.ScaledNumericValue;
import com.badlogic.gdx.tools.particleeditor.Chart;

/** @author Inferno */
class ScaledNumericPanel extends ParticleValuePanel<ScaledNumericValue> {
	Slider lowMinSlider, lowMaxSlider;
	Slider highMinSlider, highMaxSlider;
	JCheckBox relativeCheckBox;
	Chart chart;
	JPanel formPanel;
	JButton expandButton;
	JButton lowRangeButton;
	JButton highRangeButton;

	public ScaledNumericPanel (FlameMain editor, ScaledNumericValue value, String chartTitle, String name, String description) {
		this(editor, value, chartTitle, name, description, true);
	}

	public ScaledNumericPanel (FlameMain editor, ScaledNumericValue value, String chartTitle, String name, String description,
		boolean isAlwaysActive) {
		super(editor, name, description, isAlwaysActive);
		initializeComponents(chartTitle);
		setValue(value);
	}

	public JPanel getFormPanel () {
		return formPanel;
	}

	private void initializeComponents (String chartTitle) {
		JPanel contentPanel = getContentPanel();
		{
			formPanel = new JPanel(new GridBagLayout());
			contentPanel.add(formPanel, new GridBagConstraints(5, 5, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
				new Insets(0, 0, 0, 6), 0, 0));
			{
				JLabel label = new JLabel("High:");
				formPanel.add(label, new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
					new Insets(0, 0, 0, 6), 0, 0));
			}
			{
				highMinSlider = new Slider(0, -999999, 999999, 1f);
				formPanel.add(highMinSlider, new GridBagConstraints(3, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
			}
			{
				highMaxSlider = new Slider(0, -999999, 999999, 1f);
				formPanel.add(highMaxSlider, new GridBagConstraints(4, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 6, 0, 0), 0, 0));
			}
			{
				highRangeButton = new JButton("<");
				highRangeButton.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
				formPanel.add(highRangeButton, new GridBagConstraints(5, 1, 1, 1, 0.0, 0, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 1, 0, 0), 0, 0));
			}
			{
				JLabel label = new JLabel("Low:");
				formPanel.add(label, new GridBagConstraints(2, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE,
					new Insets(0, 0, 0, 6), 0, 0));
			}
			{
				lowMinSlider = new Slider(0, -999999, 999999, 1f);
				formPanel.add(lowMinSlider, new GridBagConstraints(3, 2, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
					new Insets(0, 0, 0, 0), 0, 0));
			}
			{
				lowMaxSlider = new Slider(0, -999999, 999999, 1f);
				formPanel.add(lowMaxSlider, new GridBagConstraints(4, 2, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
					new Insets(0, 6, 0, 0), 0, 0));
			}
			{
				lowRangeButton = new JButton("<");
				lowRangeButton.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
				formPanel.add(lowRangeButton, new GridBagConstraints(5, 2, 1, 1, 0.0, 0, GridBagConstraints.WEST,
					GridBagConstraints.NONE, new Insets(0, 1, 0, 0), 0, 0));
			}
		}
		{
			chart = new Chart(chartTitle) {
				public void pointsChanged () {
					value.setTimeline(chart.getValuesX());
					value.setScaling(chart.getValuesY());
				}
			};
			contentPanel.add(chart, new GridBagConstraints(6, 5, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				new Insets(0, 0, 0, 0), 0, 0));
			chart.setPreferredSize(new Dimension(150, 30));
		}
		{
			expandButton = new JButton("+");
			contentPanel.add(expandButton, new GridBagConstraints(7, 5, 1, 1, 1, 0, GridBagConstraints.SOUTHWEST,
				GridBagConstraints.NONE, new Insets(0, 5, 0, 0), 0, 0));
			expandButton.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8));
		}
		{
			relativeCheckBox = new JCheckBox("Relative");
			contentPanel.add(relativeCheckBox, new GridBagConstraints(7, 5, 1, 1, 0, 0, GridBagConstraints.NORTHWEST,
				GridBagConstraints.NONE, new Insets(0, 6, 0, 0), 0, 0));
		}

		lowMinSlider.addChangeListener(new ChangeListener() {
			public void stateChanged (ChangeEvent event) {
				ScaledNumericPanel.this.value.setLowMin(lowMinSlider.getValue());
				if (!lowMaxSlider.isVisible()) ScaledNumericPanel.this.value.setLowMax(lowMinSlider.getValue());
			}
		});
		lowMaxSlider.addChangeListener(new ChangeListener() {
			public void stateChanged (ChangeEvent event) {
				ScaledNumericPanel.this.value.setLowMax(lowMaxSlider.getValue());
			}
		});
		highMinSlider.addChangeListener(new ChangeListener() {
			public void stateChanged (ChangeEvent event) {
				ScaledNumericPanel.this.value.setHighMin(highMinSlider.getValue());
				if (!highMaxSlider.isVisible()) ScaledNumericPanel.this.value.setHighMax(highMinSlider.getValue());
			}
		});
		highMaxSlider.addChangeListener(new ChangeListener() {
			public void stateChanged (ChangeEvent event) {
				ScaledNumericPanel.this.value.setHighMax(highMaxSlider.getValue());
			}
		});

		relativeCheckBox.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				ScaledNumericPanel.this.value.setRelative(relativeCheckBox.isSelected());
			}
		});

		lowRangeButton.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				boolean visible = !lowMaxSlider.isVisible();
				lowMaxSlider.setVisible(visible);
				lowRangeButton.setText(visible ? "<" : ">");
				GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
				GridBagConstraints constraints = layout.getConstraints(lowRangeButton);
				constraints.gridx = visible ? 5 : 4;
				layout.setConstraints(lowRangeButton, constraints);
				Slider slider = visible ? lowMaxSlider : lowMinSlider;
				ScaledNumericPanel.this.value.setLowMax(slider.getValue());
			}
		});

		highRangeButton.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				boolean visible = !highMaxSlider.isVisible();
				highMaxSlider.setVisible(visible);
				highRangeButton.setText(visible ? "<" : ">");
				GridBagLayout layout = (GridBagLayout)formPanel.getLayout();
				GridBagConstraints constraints = layout.getConstraints(highRangeButton);
				constraints.gridx = visible ? 5 : 4;
				layout.setConstraints(highRangeButton, constraints);
				Slider slider = visible ? highMaxSlider : highMinSlider;
				ScaledNumericPanel.this.value.setHighMax(slider.getValue());
			}
		});

		expandButton.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				chart.setExpanded(!chart.isExpanded());
				boolean expanded = chart.isExpanded();
				GridBagLayout layout = (GridBagLayout)getContentPanel().getLayout();
				GridBagConstraints chartConstraints = layout.getConstraints(chart);
				GridBagConstraints expandButtonConstraints = layout.getConstraints(expandButton);
				if (expanded) {
					chart.setPreferredSize(new Dimension(150, 200));
					expandButton.setText("-");
					chartConstraints.weightx = 1;
					expandButtonConstraints.weightx = 0;
				} else {
					chart.setPreferredSize(new Dimension(150, 30));
					expandButton.setText("+");
					chartConstraints.weightx = 0;
					expandButtonConstraints.weightx = 1;
				}
				layout.setConstraints(chart, chartConstraints);
				layout.setConstraints(expandButton, expandButtonConstraints);
				relativeCheckBox.setVisible(!expanded);
				formPanel.setVisible(!expanded);
				chart.revalidate();
			}
		});

	}

	@Override
	public void setValue (ScaledNumericValue value) {
		super.setValue(value);
		if (this.value == null) return;
		setValue(lowMinSlider, this.value.getLowMin());
		setValue(lowMaxSlider, this.value.getLowMax());
		setValue(highMinSlider, this.value.getHighMin());
		setValue(highMaxSlider, this.value.getHighMax());
		chart.setValues(this.value.getTimeline(), this.value.getScaling());
		setValue(relativeCheckBox, this.value.isRelative());

		if ((this.value.getLowMin() == this.value.getLowMax() && lowMaxSlider.isVisible())
			|| (this.value.getLowMin() != this.value.getLowMax() && !lowMaxSlider.isVisible())) {
			lowRangeButton.doClick(0);
		}
		if (((this.value.getHighMin() == this.value.getHighMax()) && highMaxSlider.isVisible())
			|| ((this.value.getHighMin() != this.value.getHighMax()) && !highMaxSlider.isVisible())) highRangeButton.doClick(0);
	}

	public Chart getChart () {
		return chart;
	}

}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package inc.overlord.graph.dag;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Anand Chelian <achelian@yahoo.com>
 */
public class NodeTest {

    /**
     * Test of getData method, of class Node.
     */
    @Test
    public void testData() {
        String data = "foo";
        StringNode node = new StringNode(data);
        assertEquals(data, node.getData());
    }

    /**
     * Test of getNodes method, of class Node.
     */
    @Test
    public void testGetNodes() {
        String data1 = "data1", data2 = "data2";
        StringNode node1 = new StringNode(data1), node2 = new StringNode(data2);
        Set<StringNode> children = Collections.singleton(node2);
        node1.setChildren(children);
        assertEquals(children, node1.getChildren());
    }

    /**
     * Test of equals method, of class Node.
     */
    @Test
    public void testEquals() {
        String data1 = "data1", data2 = "data2";
        StringNode node1 = new StringNode(null), node2 = new StringNode(null);
        assertTrue(node1.equals(node2));
        node1 = new StringNode(data1);
        assertFalse(node1.equals(node2));
        node2 = new StringNode(data1);
        assertTrue(node1.equals(node2));
        node2 = new StringNode(data2);
        assertFalse(node1.equals(node2));
        String data3 = "data3";
        StringNode node3 = new StringNode(data3);
        Set<StringNode> children = new HashSet<StringNode>(Collections.singleton(node3));
        node1.children = children;
        assertNotEquals(node1, node2);
        node2.children = children;
        // TODO put this back in when collections work correctly
        //assertTrue(node1.equals(node2));
    }

    /**
     * Test of canEqual method, of class Node.
     */
    @Test
    public void testCanEqual() {
        StringNode node1 = new StringNode(null), node2 = new StringNode(null);
        assertTrue(node1.canEqual(node2));
        assertFalse(node1.canEqual(new Object()));
    }

    /**
     * Test of hashCode method, of class Node.
     */
    @Test
    public void testHashCode() {
        StringNode node1 = new StringNode(null), node2 = new StringNode(null);
        assertEquals(node1.hashCode(), node2.hashCode());
        StringNode instance = new StringNode(null);
        int expResult = 1023;
        int result = instance.hashCode();
        assertEquals(expResult, result);
        String data = "data";
        node1 = new StringNode(data);
        node2 = new StringNode(data);
        assertEquals(node1.hashCode(), node2.hashCode());
        StringNode node3 = new StringNode("data3");
        Set<StringNode> children = new HashSet<StringNode>();
        children.add(node3);
        node1.children = children;
        node2.children = children;
        assertEquals(node1.hashCode(), node2.hashCode());
    }

    /**
     * Test of toString method, of class Node.
     */
    @Test
    public void testToString() {
        StringNode node = new StringNode("data");
        String expResult = "StringNode(super=KeyedNode(super=Node(data=data, children=null)))";
        assertEquals(expResult, node.toString());
    }
}


text:
import cv2
import decimal
import json
import ijson.backends.yajl2_cffi as ijson
from sklearn_theano.feature_extraction import OverfeatTransformer

tr = OverfeatTransformer(output_layers=[8])

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)

with open('../workspace/ds.json') as inh:
    with open('../workspace/ds_deep.json', 'w') as outh:
        ds = ijson.items(inh, 'item')
        outh.write('[')

        for i, item in enumerate(ds):
            print 'running', i+1
            if i > 0:
                outh.write(',')
            img = cv2.imread('set1/' + item['file'])
            img = cv2.resize(img, (231, 231))
            item['deep'] = tr.transform(img)[0].tolist()
            json.dump(item, outh, cls=DecimalEncoder)

        outh.write(']')


text:
require 'uri'

module Faraday
  class Adapter
    class EMSynchrony < Faraday::Adapter
      include EMHttp::Options

      dependency do
        require 'em-synchrony/em-http'
        require 'em-synchrony/em-multi'
        require 'fiber'
      end

      self.supports_parallel = true

      def self.setup_parallel_manager(options = {})
        ParallelManager.new
      end

      def call(env)
        super
        request = EventMachine::HttpRequest.new(URI::parse(env[:url].to_s), connection_config(env))        #   end

        http_method = env[:method].to_s.downcase.to_sym

        # Queue requests for parallel execution.
        if env[:parallel_manager]
          env[:parallel_manager].add(request, http_method, request_config(env)) do |resp|
            save_response(env, resp.response_header.status, resp.response) do |resp_headers|
              resp.response_header.each do |name, value|
                resp_headers[name.to_sym] = value
              end
            end

            # Finalize the response object with values from `env`.
            env[:response].finish(env)
          end

        # Execute single request.
        else
          client = nil
          block = lambda { request.send(http_method, request_config(env)) }

          if !EM.reactor_running?
            EM.run do
              Fiber.new {
                client = block.call
                EM.stop
              }.resume
            end
          else
            client = block.call
          end

          save_response(env, client.response_header.status, client.response) do |resp_headers|
            client.response_header.each do |name, value|
              resp_headers[name.to_sym] = value
            end
          end
        end

        @app.call env
      rescue Errno::ECONNREFUSED
        raise Error::ConnectionFailed, $!
      end
    end
  end
end

require 'faraday/adapter/em_synchrony/parallel_manager'

# add missing patch(), options() methods
EventMachine::HTTPMethods.module_eval do
  ([:patch, :options] - instance_methods).each do |type|
    module_eval %[
      def #{type}(options = {}, &blk)
        f = Fiber.current
        conn = setup_request(:#{type}, options, &blk)
        if conn.error.nil?
          conn.callback { f.resume(conn) }
          conn.errback  { f.resume(conn) }
          Fiber.yield
        else
          conn
        end
      end
    ]
  end
end


text:
import requests
import time
from ast import literal_eval
from urlparse import urlparse, parse_qs

from ansible.module_utils.basic import AnsibleModule

DOCUMENTATION = """
---
author: "Romain Acciari"
module: influxdb
short_description: Write to InfluxDB
description:
  - This module is useful for sending data to InfluxDB from playbooks.
version_added: "0.1"
options:
    uri:
        description:
        - URI of the InfluxDB database.
        required: true
    measurement:
        description:
        - Measurement to store data.
        default: events
        required: false
    tags:
        description:
        - Tags to apply.
        required: false
    value:
        description:
        - Value to store.
        required: true
    epoch:
        description:
        - Epoch time to show value.
        default: current
        required: false
"""

EXAMPLES = """
# Send message "Ansible test" to the events measurement in graphite database
# Tagged with a specified hostname
---
- hosts: localhost
  tasks:
    - influxdb:
        uri: http://127.0.0.1:8086/write?u=root&p=root
        tags:
          host: myhostname
        value: Ansible test

# Send a message from localhost refering to an Ansible group from the
# inventory. Message customized with targeted hostname
---
- hosts: ansible_group
  tasks:
    - influxdb:
        uri: http://127.0.0.1:8086/write?u=root&p=root&db=graphite&precision=s
        measurement: events
        tags:
          host: "{{ inventory_hostname }}"
        value: Ansible test on {{ inventory_hostname }}
      delegate_to: localhost
"""

def main():

    module = AnsibleModule(
        argument_spec=dict(
            uri=dict(default=None),
            measurement=dict(default='events'),
            tags=dict(default=None),
            value=dict(default=None),
            epoch=dict(default=int(time.time()))
        )
    )

    uri = module.params.get('uri')
    measurement = module.params.get('measurement')
    tags = module.params.get('tags')
    value = module.params.get('value')
    epoch = module.params.get('epoch')

    # Prepare headers and parameters for Request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    parsed = urlparse(uri)
    params = parse_qs(parsed.query)
    influx_uri = parsed.scheme + "://" + parsed.netloc + parsed.path

    # Start building message
    data = '%s,' % measurement
    if tags:
        for k, v in literal_eval(tags).iteritems():
            data += '%s=%s,' % (k, str(v).replace(' ', '\ '))
        data = data[:-1] if data.endswith(',') else data

    data += ' value="%s" %s' % (value, str(epoch).replace(' ', '\ '))

    # Write data to InfluxDB using Request
    try:
        r = requests.Request('POST', influx_uri, headers=headers,
                             data=data, params=params)
        prepared = r.prepare()
        s = requests.Session()
        s.send(prepared)
    except Exception, e:
        module.fail_json(rc=1, msg='Failed to send data to InfluxDB %s: %s'
                         % (influx_uri, e))

    module.exit_json(changed=True, data=data)

main()


text:
package org.dcm4chex.archive.web.maverick;

/**
 *
 * @author gunter.zeilinger@tiani.com
 * @version $Revision: 943 $ $Date: 2004-02-01 22:21:46 +0800 (周日, 01 2月 2004) $
 * @since 28.01.2004
 */
public class CollapseStudyCtrl extends FolderCtrl {

    protected String perform() throws Exception {
        FolderForm folderForm = (FolderForm) getForm();
        folderForm.lookupStudy().getSeries().clear();
        return FOLDER;
    }

}


text:
@implementation JHCellConfig (DynamicHeight)

/// 简易方法
- (CGFloat)dynamicHeightCalResult
{
    return [self dynamicHeightWithConfiguration:nil identifier:nil usingCache:YES];;
}

/// 完整方法
- (CGFloat)dynamicHeightWithConfiguration:(void (^)(id cell))configuration
                               identifier:(NSString *)identifier
                               usingCache:(BOOL)usingCache
{
    // 高度缓存
    if (usingCache) {
        if (self.cachedHeight > 0) {
            return self.cachedHeight;
        };
    }

    CGFloat height = [self dynamicHeightWithConfiguration:configuration identifier:identifier];

    if (usingCache) {
            self.cachedHeight = height;
    }

    return height;
}

/// 高度计算
- (CGFloat)dynamicHeightWithConfiguration:(void (^)(id cell))configuration
                               identifier:(NSString *)identifier
{
    UITableView *tableView = self.tableView;
    NSAssert(tableView, @"need tableView. Call 'cellConfig.tableView = yourTableView' before height calculation");

    UITableViewCell *cell = [self templateCellForTableView:tableView identifier:identifier];

    // Manually calls to ensure consistent behavior with actual cells (that are displayed on screen).
    [cell prepareForReuse];

    // Customize and provide content for our template cell.
    if ([cell respondsToSelector:@selector(updateContentWithCellConfig:)]) {
        [(id<JHCellConfigProtocol>)cell updateContentWithCellConfig:self];
    }

    if (configuration) {
        configuration(cell);
    }

    CGFloat contentViewWidth = CGRectGetWidth(tableView.frame);

    // If a cell has accessory view or system accessory type, its content view's width is smaller
    // than cell's by some fixed values.
    if (cell.accessoryView) {
        contentViewWidth -= 16 + CGRectGetWidth(cell.accessoryView.frame);
    } else {
        static const CGFloat systemAccessoryWidths[] = {
            [UITableViewCellAccessoryNone] = 0,
            [UITableViewCellAccessoryDisclosureIndicator] = 34,
            [UITableViewCellAccessoryDetailDisclosureButton] = 68,
            [UITableViewCellAccessoryCheckmark] = 40,
            [UITableViewCellAccessoryDetailButton] = 48
        };
        contentViewWidth -= systemAccessoryWidths[cell.accessoryType];
    }

    CGSize fittingSize = CGSizeZero;

    if (@available(iOS 8.0,*)) {
        fittingSize = [cell.contentView systemLayoutSizeFittingSize:CGSizeMake(contentViewWidth, 0) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel];

    } else {
        cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
        NSLayoutConstraint *tempWidthConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
        [cell.contentView addConstraint:tempWidthConstraint];
        fittingSize = [cell.contentView  systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        [cell.contentView removeConstraint:tempWidthConstraint];
    }

    //    }

    // Add 1px extra space for separator line if needed, simulating default UITableViewCell.

    if (tableView.separatorStyle != UITableViewCellSeparatorStyleNone) {
        fittingSize.height += 1.0 / [UIScreen mainScreen].scale;
    }

    return fittingSize.height;

}

#pragma mark -
- (id)templateCellForTableView:(UITableView *)tableView
                    identifier:(NSString *)identifier
{
    NSString *cacheID = identifier.length > 0 ? identifier : self.className;

    NSMutableDictionary *templateCellsByIdentifiers = objc_getAssociatedObject(self, _cmd);
    if (!templateCellsByIdentifiers) {
        templateCellsByIdentifiers = @{}.mutableCopy;
        objc_setAssociatedObject(self, _cmd, templateCellsByIdentifiers, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    UITableViewCell *templateCell = templateCellsByIdentifiers[cacheID];

    if (!templateCell) {
        templateCell = [self cellOfCellConfigWithTableView:tableView];
        templateCellsByIdentifiers[cacheID] = templateCell;
        //        [self fd_debugLog:[NSString stringWithFormat:@"layout cell created - %@", identifier]];
    }

    return templateCell;
}

@end


text:
package com.sequenceiq.it.cloudbreak.testcase.e2e.sdx;

import static com.sequenceiq.cloudbreak.api.endpoint.v4.recipes.requests.RecipeV4Type.POST_CLOUDERA_MANAGER_START;
import static com.sequenceiq.it.cloudbreak.cloud.HostGroupType.IDBROKER;
import static com.sequenceiq.it.cloudbreak.cloud.HostGroupType.MASTER;
import static com.sequenceiq.it.cloudbreak.context.RunningParameter.key;

import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import com.sequenceiq.it.cloudbreak.assertion.datalake.RecipeTestAssertion;
import com.sequenceiq.it.cloudbreak.client.RecipeTestClient;
import com.sequenceiq.it.cloudbreak.client.SdxTestClient;
import com.sequenceiq.it.cloudbreak.client.StackTestClient;
import com.sequenceiq.it.cloudbreak.context.Description;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.ClouderaManagerTestDto;
import com.sequenceiq.it.cloudbreak.dto.ClusterTestDto;
import com.sequenceiq.it.cloudbreak.dto.ImageSettingsTestDto;
import com.sequenceiq.it.cloudbreak.dto.InstanceGroupTestDto;
import com.sequenceiq.it.cloudbreak.dto.recipe.RecipeTestDto;
import com.sequenceiq.it.cloudbreak.dto.sdx.SdxInternalTestDto;
import com.sequenceiq.it.cloudbreak.dto.stack.StackTestDto;
import com.sequenceiq.it.cloudbreak.exception.TestFailException;
import com.sequenceiq.it.cloudbreak.util.RecipeUtil;
import com.sequenceiq.it.cloudbreak.util.SdxUtil;
import com.sequenceiq.it.cloudbreak.util.ssh.SshJUtil;
import com.sequenceiq.sdx.api.model.SdxClusterStatusResponse;
import com.sequenceiq.sdx.api.model.SdxDatabaseAvailabilityType;
import com.sequenceiq.sdx.api.model.SdxDatabaseRequest;

public class InternalSdxRepairWithRecipeTest extends PreconditionSdxE2ETest {

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

    @Inject
    private SdxTestClient sdxTestClient;

    @Inject
    private RecipeTestClient recipeTestClient;

    @Inject
    private StackTestClient stackTestClient;

    @Inject
    private SshJUtil sshJUtil;

    @Inject
    private SdxUtil sdxUtil;

    @Inject
    private RecipeUtil recipeUtil;

    @Test(dataProvider = TEST_CONTEXT)
    @Description(
            given = "there is a running Cloudbreak, and an SDX cluster in available state",
            when = "recovery called on the IDBROKER and MASTER host group, where the EC2 instance had been stopped",
            then = "SDX recovery should be successful, the cluster should be up and running"
    )
    public void testSDXMultiRepairIDBRokerAndMasterWithRecipeFile(TestContext testContext) {
        String sdxInternal = resourcePropertyProvider().getName();
        String cluster = resourcePropertyProvider().getName();
        String clouderaManager = resourcePropertyProvider().getName();
        String recipeName = resourcePropertyProvider().getName();
        String stack = resourcePropertyProvider().getName();
        String imageSettings = resourcePropertyProvider().getName();
        String filePath = "/post-cm-start";
        String fileName = "post-cm-start";
        String masterInstanceGroup = "master";
        String idbrokerInstanceGroup = "idbroker";

        SdxDatabaseRequest sdxDatabaseRequest = new SdxDatabaseRequest();
        sdxDatabaseRequest.setAvailabilityType(SdxDatabaseAvailabilityType.NONE);
        sdxDatabaseRequest.setCreate(false);

        String selectedImageID = getLatestPrewarmedImageId(testContext);

        testContext
                .given(imageSettings, ImageSettingsTestDto.class)
                .withImageCatalog(commonCloudProperties().getImageCatalogName())
                .withImageId(selectedImageID)
                .given(clouderaManager, ClouderaManagerTestDto.class)
                .given(cluster, ClusterTestDto.class)
                .withBlueprintName(getDefaultSDXBlueprintName())
                .withValidateBlueprint(Boolean.FALSE)
                .withClouderaManager(clouderaManager)
                .given(RecipeTestDto.class)
                .withName(recipeName)
                .withContent(recipeUtil.generatePostCmStartRecipeContent(applicationContext))
                .withRecipeType(POST_CLOUDERA_MANAGER_START)
                .when(recipeTestClient.createV4())
                .given(masterInstanceGroup, InstanceGroupTestDto.class)
                .withHostGroup(MASTER)
                .withNodeCount(1)
                .withRecipes(recipeName)
                .given(idbrokerInstanceGroup, InstanceGroupTestDto.class)
                .withHostGroup(IDBROKER)
                .withNodeCount(1)
                .withRecipes(recipeName)
                .given(stack, StackTestDto.class)
                .withCluster(cluster)
                .withInstanceGroups(masterInstanceGroup, idbrokerInstanceGroup)
                .withImageSettings(imageSettings)
                .given(sdxInternal, SdxInternalTestDto.class)
                .withCloudStorage(getCloudStorageRequest(testContext))
                .withDatabase(sdxDatabaseRequest)
                .withStackRequest(key(cluster), key(stack))
                .when(sdxTestClient.createInternal(), key(sdxInternal))
                .await(SdxClusterStatusResponse.RUNNING, key(sdxInternal))
                .awaitForHealthyInstances()
                .then(RecipeTestAssertion.validateFilesOnHost(List.of(MASTER.getName(), IDBROKER.getName()), filePath, fileName, 1, null, null, sshJUtil))
                .then((tc, dto, client) -> {
                    if (!StringUtils.equalsIgnoreCase(dto.getResponse().getStackV4Response().getImage().getId(), selectedImageID)) {
                        throw new TestFailException(String.format("The datalake image Id (%s) do NOT match with the selected pre-warmed image Id: '%s'!",
                                dto.getResponse().getStackV4Response().getImage().getId(), selectedImageID));
                    }
                    return dto;
                })
                .then((tc, testDto, client) -> {
                    List<String> instanceIdsToStop = sdxUtil.getInstanceIds(testDto, client, MASTER.getName());
                    instanceIdsToStop.addAll(sdxUtil.getInstanceIds(testDto, client, IDBROKER.getName()));
                    getCloudFunctionality(tc).stopInstances(testDto.getName(), instanceIdsToStop);
                    return testDto;
                })
                .awaitForStoppedInstances()
                .when(sdxTestClient.repairInternal(MASTER.getName(), IDBROKER.getName()), key(sdxInternal))
                .await(SdxClusterStatusResponse.REPAIR_IN_PROGRESS, key(sdxInternal).withWaitForFlow(Boolean.FALSE))
                .await(SdxClusterStatusResponse.RUNNING, key(sdxInternal))
                .awaitForHealthyInstances()
                .then(RecipeTestAssertion.validateFilesOnHost(List.of(MASTER.getName(), IDBROKER.getName()), filePath, fileName, 1, null, null, sshJUtil))
                .validate();
    }
}


text:
title: Cache

access:
    admin.cache: true
    admin.super: true
    admin.maintenance: true
---


text:
@implementation NSImage (ImageRect)

- (NSRect)bounds
{
	NSRect imageRect;
	imageRect.origin = NSZeroPoint;
	imageRect.size = [self size];
	return imageRect;
}

- (void)drawAtPoint:(NSPoint)location
		   fraction:(CGFloat)opacity
{
	[self drawAtPoint:location
			 fromRect:[self bounds]
			operation:NSCompositeSourceOver
			 fraction:opacity];
}

@end


text:
layout: post
date: 2017-01-25
title: "Pronovias PRAMA 2016 Sleeveless Chapel Train Mermaid/Trumpet Open Back"
category: Pronovias
tags: [Pronovias,Mermaid/Trumpet,Open Back,V-neck,Chapel Train,Sleeveless,2016,Lace]
---
### Pronovias PRAMA
Just **$359.99**
### 2016  Sleeveless Chapel Train Mermaid/Trumpet Open Back

BRANDS	Pronovias

Silhouette	Mermaid/Trumpet

Trend	Open Back

Neckline	V-neck

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2016

Fabric	Lace

Buy it: [https://www.readybrides.com/en/pronovias/4188-pronovias-prama.html](https://www.readybrides.com/en/pronovias/4188-pronovias-prama.html)


text:
require 'geocoder/lookups/base'
require "geocoder/results/mapbox"

module Geocoder::Lookup
  class Mapbox < Base

    def name
      "Mapbox"
    end

    def query_url(query)
      "#{protocol}://api.mapbox.com/geocoding/v5/#{dataset}/#{url_query_string(query)}.json?access_token=#{configuration.api_key}"
    end

    private # ---------------------------------------------------------------

    def results(query)
      return [] unless data = fetch_data(query)
      if data['features']
        sort_relevant_feature(data['features'])
      elsif data['message'] =~ /Invalid\sToken/
        raise_error(Geocoder::InvalidApiKey, data['message'])
      else
        []
      end
    end

    def url_query_string(query)
      require 'cgi' unless defined?(CGI) && defined?(CGI.escape)
      if query.reverse_geocode?
        lat,lon = query.coordinates
        "#{CGI.escape lon},#{CGI.escape lat}"
      else
        CGI.escape query.text.to_s
      end
    end

    def dataset
      configuration[:dataset] || "mapbox.places"
    end

    def supported_protocols
      [:https]
    end

    def sort_relevant_feature(features)
      # Sort by descending relevance; Favor original order for equal relevance (eg occurs for reverse geocoding)
      features.sort_by do |feature|
        [feature["relevance"],-features.index(feature)]
      end.reverse
    end
  end
end