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;

/**
 * Description of a semantic Legos annotation. http://go/legos/project.md#semantic-intent-
 * annotations
 *
 *
 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 YoutubeDiscoveryLegosLegosSemanticRelationship extends com.google.api.client.json.GenericJson {

  /**
   * Confidence score. Thresholding at the confidence score at 0.XX yields annotations of precision
   * of at least XX%. Only filled in the intent definition Legos. Please use
   * IsSemanticAnnotationAtConfidenceThreshold() from
   * video/youtube/discovery/legos/annotations/public/legos_annotations_util.h to obtain only intent
   * definition Legos. For more information on the migration please look at go/legos-intent-
   * migration.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float confidence;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<YoutubeDiscoveryLegosLegosSemanticRelationshipContext> contexts;

  /**
   * DEPRECATED. Please use confidence instead. Will be set to the same value as confidence in early
   * January 2019. See go/legos-intent-migration for more information.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Double topicalityScore;

  /**
   * Confidence score. Thresholding at the confidence score at 0.XX yields annotations of precision
   * of at least XX%. Only filled in the intent definition Legos. Please use
   * IsSemanticAnnotationAtConfidenceThreshold() from
   * video/youtube/discovery/legos/annotations/public/legos_annotations_util.h to obtain only intent
   * definition Legos. For more information on the migration please look at go/legos-intent-
   * migration.
   * @return value or {@code null} for none
   */
  public java.lang.Float getConfidence() {
    return confidence;
  }

  /**
   * Confidence score. Thresholding at the confidence score at 0.XX yields annotations of precision
   * of at least XX%. Only filled in the intent definition Legos. Please use
   * IsSemanticAnnotationAtConfidenceThreshold() from
   * video/youtube/discovery/legos/annotations/public/legos_annotations_util.h to obtain only intent
   * definition Legos. For more information on the migration please look at go/legos-intent-
   * migration.
   * @param confidence confidence or {@code null} for none
   */
  public YoutubeDiscoveryLegosLegosSemanticRelationship setConfidence(java.lang.Float confidence) {
    this.confidence = confidence;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.util.List<YoutubeDiscoveryLegosLegosSemanticRelationshipContext> getContexts() {
    return contexts;
  }

  /**
   * @param contexts contexts or {@code null} for none
   */
  public YoutubeDiscoveryLegosLegosSemanticRelationship setContexts(java.util.List<YoutubeDiscoveryLegosLegosSemanticRelationshipContext> contexts) {
    this.contexts = contexts;
    return this;
  }

  /**
   * DEPRECATED. Please use confidence instead. Will be set to the same value as confidence in early
   * January 2019. See go/legos-intent-migration for more information.
   * @return value or {@code null} for none
   */
  public java.lang.Double getTopicalityScore() {
    return topicalityScore;
  }

  /**
   * DEPRECATED. Please use confidence instead. Will be set to the same value as confidence in early
   * January 2019. See go/legos-intent-migration for more information.
   * @param topicalityScore topicalityScore or {@code null} for none
   */
  public YoutubeDiscoveryLegosLegosSemanticRelationship setTopicalityScore(java.lang.Double topicalityScore) {
    this.topicalityScore = topicalityScore;
    return this;
  }

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

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

}

redpajama_set_name: RedPajamaGithub


text:
package org.storrent

import akka.actor.{ Actor, ActorSystem, Props}
import akka.testkit.{ TestActorRef, TestKit, TestLatch, ImplicitSender, TestProbe }
import scala.concurrent.duration._
import scala.concurrent.Await
import org.scalatest.{ WordSpec, BeforeAndAfterAll}
import org.scalatest.matchers.MustMatchers
import akka.util.ByteString

class BTProtocolSpec extends TestKit(ActorSystem("BTProtocolSpec"))
with ImplicitSender
with WordSpec
with MustMatchers
with BeforeAndAfterAll {
  import BTProtocol._
  import Frame._

  object fakeTCPClient {
  }

  trait fakeTCPClient extends TCPClientProvider {
    def recieve = Actor.emptyBehavior
  }

  val fakePeerConnect = TestProbe()

  def slicedBTProtocol = new BTProtocol("", 0, fakePeerConnect.ref ,Array.fill(20){0}, 16384*10, 16384) with fakeTCPClient

  // FIXME: this code is here because the client only supports recieving, for now
  def createChokeFrame(): ByteString = {
    val headerLenB = intToByte(1, 4)
    val headerIdB = ByteString(0)
    headerLenB ++ headerIdB
  }

  def createUnchokeFrame(): ByteString = {
    val headerLenB = intToByte(1, 4)
    val headerIdB = ByteString(1)
    headerLenB ++ headerIdB
  }

  def createHaveFrame(piece: Int): ByteString = {
    val headerLenB = intToByte(5, 4)
    val headerIdB = ByteString(4)
    val pieceB = intToByte(piece, 4)

    headerLenB ++ headerIdB ++ pieceB
  }

  def createHandshakeFrame(): ByteString = {
    ByteString(Array.fill(68){0.toByte})
  }

  "BTProtocol" should {
    "choke" in {
      val a = TestActorRef[BTProtocol](Props(slicedBTProtocol))
      a ! TCPClient.DataReceived(createHandshakeFrame())
      a ! TCPClient.DataReceived(createChokeFrame())
      fakePeerConnect.expectMsg(Choke())
    }
    "unchoke" in {
      val a = TestActorRef[BTProtocol](Props(slicedBTProtocol))
      a ! TCPClient.DataReceived(createHandshakeFrame())
      a ! TCPClient.DataReceived(createUnchokeFrame())
      fakePeerConnect.expectMsg(Unchoke())
    }
    "have" in {
      val a = TestActorRef[BTProtocol](Props(slicedBTProtocol))
      a ! TCPClient.DataReceived(createHandshakeFrame())
      a ! TCPClient.DataReceived(createHaveFrame(1))
      fakePeerConnect.expectMsg(Have(1))
    }
  }
}


text:
This test attempts to change the src of an IMG tag to all black listed ports to confirm that each fires an
    error event. It also tries the FTP ports for exemptions.


text:
//
//  FindHeader.h
//  KakaFind
//
//  Created by 陈振勇 on 16/7/19.
//  Copyright © 2016年 陈振勇. All rights reserved.
//

#ifndef FindHeader_h
#define FindHeader_h

#ifdef DEBUG
#define ZYLog(...) NSLog(__VA_ARGS__)
#else
#define ZYLog(...)
#endif

#define ZYLogFunc ZYLog(@"%s",__func__)

#define ZYRGBColor(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
#define ZYGlobalBgColor ZYRGBColor(244,248,251)

#define kScreenWidth CGRectGetWidth([UIScreen mainScreen].bounds)
#define kScreenHeight CGRectGetHeight([UIScreen mainScreen].bounds)

typedef enum {

    EyeSubjectsControllerTypeLatest,//最新
    EyeSubjectsControllerTypeMore,//更多
    EyeSubjectsControllerTypeCollect,//收藏
    EyeSubjectsControllerTypeShare,//分享

}EyeSubjectsControllerType;

#import "UIView+ZYExtension.h"
#import "UIImage+Extension.h"
#import "NSDate+EyeExtension.h"
#import "HttpTool.h"
#import <Masonry.h>
#import <MBProgressHUD.h>
#import <AFNetworking.h>
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>

/************ 百度地图  *********************/

#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件

#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件

#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件

#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件

#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件

#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件

#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件

#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件

/************ 百度地图  *********************/

/************ 网络请求地址  *********************/
#define HeadURL HeadURl

//广告
#define Ads_URL [HeadURL stringByAppendingString:@"qryAdvertisements"]
//首页广场栏目
#define SubjectPiazza_URL [HeadURL stringByAppendingString:@"qrySubjectPiazza"]
//话题
#define Subjects_URL [HeadURL stringByAppendingString:@"qrySubjects"]
//话题详情
#define SubjectDetail_URL [HeadURL stringByAppendingString:@"qrySubjectDetail"]
//媒体授权
#define MediaAccess_URL [HeadURL stringByAppendingString:@"acquireMediaAccess"]
//创建媒体记录
#define createMedias_URL [HeadURL stringByAppendingString:@"createMedias"]
//更新媒体状态
#define updateMediaState_URL [HeadURL stringByAppendingString:@"updateMediaState"]
//发表话题
#define submitSubject_URL [HeadURL stringByAppendingString:@"submitSubject"]
//话题评论
#define SubjectRemarks_URL [HeadURL stringByAppendingString:@"qrySubjectRemarks"]
//违章类型
#define Enums_URL [HeadURL stringByAppendingString:@"qryEnums"]

//话题交互接口
#define subjectInteractive_URL [HeadURL stringByAppendingString:@"subjectInteractive"]

//更新用户一般信息接口
#define updateUserInfo_URL [HeadURL stringByAppendingString:@"updateUserInfo"]

//查询系统设置接口
#define qryProfile_URL [HeadURL stringByAppendingString:@"qryProfile"]
//获取话题分享URL接口
#define qryShareSubject_URL [HeadURL stringByAppendingString:@"qryShareSubjectUrl"]

//删除话题
#define deleteSubject_URL [HeadURL stringByAppendingString:@"deleteSubject"]

//图片栏目id
#define PHOTO_SUBJ_COLUM_ID @"photo-subj-column-id"
//视频栏目id
#define VIDEO_SUBJ_COLUM_ID @"video-subj-column-id"
//游记栏目id
#define TRAVEL_SUBJ_COLUM_ID @"travel-subj-column-id"
//违章举报栏目id
#define TV_SUBJ_COLUM_ID @"tv-subj-column-id"
//轨迹栏目id
#define TRACK_SUBJ_COLUM_ID @"track-subj-column-id"

#define LoginToken [SettingConfig shareInstance].loginToken

/************ 友盟  *********************/
#import <UMSocial.h>
#define UMAppKey @"57860b88e0f55a54f00023ce"

/************ 友盟  *********************/

/************ 网络请求地址  *********************/

//系统单例
#define UserDefaults  [NSUserDefaults standardUserDefaults]
#define NotificationCenter  [NSNotificationCenter defaultCenter]
#define SharedApplication  [UIApplication sharedApplication]
#define APPDelegate     [[UIApplication sharedApplication] delegate]
#define FileManager [NSFileManager defaultManager]

#endif /* FindHeader_h */


text:
KTV-preordination-system
========================

2个小时写了一个KTV管理系统,based on sqlite3 nodejs express async and yeoman


text:
package com.HawkEngine.Core;

public class RaycastHitInformation
{
	public boolean hit;
	public GameObject hitObject;
	public Vector2 normal;
	public float fraction;
	public Vector2 point;
}


text:
<?php

	// 	Donut 				🍩
	//	Dictionary Toolkit
	// 		Version a.1
	//		Written by Thomas de Roo
	//		Licensed under MIT

	//	++	File: connection.cset.php

class pConnection extends PDO{

	public function __construct(){
		call_user_func_array('parent::__construct', func_get_args());
		// UTF-8, bardzo proszę
		$this->exec("SET NAMES UTF8");
		$this->query("SET CHARACTER_SET_RESULTS='UTF8'");
		$this->initConfig();
	}

	protected function initConfig(){
		$settings = $this->query("SELECT * FROM config");
		while($setting = $settings->fetchObject())
			define("CONFIG_".$setting->SETTING_NAME, $setting->SETTING_VALUE);
	}

	public function cacheQuery($sql, $force_no_cache = false, $force_no_count = false){
		// We need the queries hash
		$table_name = preg_match_all("/\b(FROM|INTO|UPDATE)\b\s*(\w+)/", $sql, $matches);

		// If query caching is disabled, we just need to execute the query
		if($force_no_cache or CONFIG_ENABLE_QUERY_CACHING == 0){
			// Only select queries can be cached
			if(!p::StartsWith($sql, "SELECT"))
				return $this->query($sql);
			$execute = $this->query($sql);
			$objects = array();
			while($object = $execute->fetchObject()){
				$objects[] = $object;
			}
			return new pCachedQuery($objects, $execute->rowCount(), $sql);
		}

		// If this is not a select query, it will change something, therefore the cache needs to be cleaned
		if(!p::StartsWith($sql, "SELECT")){
			$this->CleanCache('queries', $matches[2][0].'_');
		}

		// Only select queries can be cached
		if(!p::StartsWith($sql, "SELECT"))
			return $this->query($sql);

		// File infomation
		$hash = $matches[2][0]."_".md5($sql);
		$cache_file = p::FromRoot('cache/queries/'.$hash.'.cache');
		$cache_folder = p::FromRoot('cache/queries');
		$cache_time = CONFIG_QC_TIME;

		// If we are not writable, we have to run the query without cache
		if(!is_writable($cache_folder))
			return $this->query($sql);

		// We need to see if there are any queries like these done within the query_cache_time
		if(file_exists($cache_file)){

			// Our file exists... let's get its creation time
			$cache_file_time = filemtime($cache_file);

			// Is the file still valid?
			 if (time() - $cache_file_time < $cache_time)
			 	return unserialize(file_get_contents($cache_file));

			// If not we need to delete it and be a little recursive...
			elseif(unlink($cache_file))
				return $this->cacheQuery($sql, true, true);

		}

		// The query isn't cached... or it is unvalid and therefore deleted
		else{

		//We need to execute the query, cache it and return the cached object

			$execute = $this->query($sql);

			// If the rowCount is 0, we just don't cache then!
			if($execute->rowCount() == 0)
				return $execute;

			// Otherwise we need to do a little more...
			else{

				// Fetching the objects in order to cache them
				$objects  = array();

				while($object = $execute->fetchObject()){
					$objects[] = $object;
				}

				// Create the cached query
				$cache_query = new pCachedQuery($objects, $execute->rowCount(), $sql);

			}

			// Cache the whole thing, if we cannot do that, we need to fallback
			if(!file_put_contents($cache_file, serialize($cache_query)))
				return $this->cacheQuery($sql, true);

			return $cache_query;

		}

	}

	public function CleanCache($section = 'queries', $prefix = ''){
		foreach(glob(CONFIG_ROOT_PATH . '/cache/' . $section . '/'.$prefix.'*.cache') as $filename)
			unlink($filename);
		return true;
	}

}


text:
package org.apache.hadoop.ozone.om.helpers;

import org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyLocationList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * A list of key locations. This class represents one single version of the
 * blocks of a key.
 */
public class OmKeyLocationInfoGroup {
  private final long version;
  private final List<OmKeyLocationInfo> locationList;

  public OmKeyLocationInfoGroup(long version,
                                List<OmKeyLocationInfo> locations) {
    this.version = version;
    this.locationList = locations;
  }

  /**
   * Return only the blocks that are created in the most recent version.
   *
   * @return the list of blocks that are created in the latest version.
   */
  public List<OmKeyLocationInfo> getBlocksLatestVersionOnly() {
    List<OmKeyLocationInfo> list = new ArrayList<>();
    locationList.stream().filter(x -> x.getCreateVersion() == version)
        .forEach(list::add);
    return list;
  }

  public long getVersion() {
    return version;
  }

  public List<OmKeyLocationInfo> getLocationList() {
    return locationList;
  }

  public KeyLocationList getProtobuf() {
    return KeyLocationList.newBuilder()
        .setVersion(version)
        .addAllKeyLocations(
            locationList.stream().map(OmKeyLocationInfo::getProtobuf)
                .collect(Collectors.toList()))
        .build();
  }

  public static OmKeyLocationInfoGroup getFromProtobuf(
      KeyLocationList keyLocationList) {
    return new OmKeyLocationInfoGroup(
        keyLocationList.getVersion(),
        keyLocationList.getKeyLocationsList().stream()
            .map(OmKeyLocationInfo::getFromProtobuf)
            .collect(Collectors.toList()));
  }

  /**
   * Given a new block location, generate a new version list based upon this
   * one.
   *
   * @param newLocationList a list of new location to be added.
   * @return
   */
  OmKeyLocationInfoGroup generateNextVersion(
      List<OmKeyLocationInfo> newLocationList) throws IOException {
    // TODO : revisit if we can do this method more efficiently
    // one potential inefficiency here is that later version always include
    // older ones. e.g. v1 has B1, then v2, v3...will all have B1 and only add
    // more
    List<OmKeyLocationInfo> newList = new ArrayList<>();
    newList.addAll(locationList);
    for (OmKeyLocationInfo newInfo : newLocationList) {
      // all these new blocks will have addVersion of current version + 1
      newInfo.setCreateVersion(version + 1);
      newList.add(newInfo);
    }
    return new OmKeyLocationInfoGroup(version + 1, newList);
  }

  void appendNewBlocks(List<OmKeyLocationInfo> newLocationList)
      throws IOException {
    for (OmKeyLocationInfo info : newLocationList) {
      info.setCreateVersion(version);
      locationList.add(info);
    }
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("version:").append(version).append(" ");
    for (OmKeyLocationInfo kli : locationList) {
      sb.append(kli.getLocalID()).append(" || ");
    }
    return sb.toString();
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="jDepMonPU" transaction-type="JTA">
    <jta-data-source>java:/jDepMonDS</jta-data-source>
    <class>rs.in.zivanovic.jdepmon.ejb.entity.PomMonitor</class>
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <shared-cache-mode>ALL</shared-cache-mode>
    <properties/>
  </persistence-unit>
</persistence>


text:
//
// This file is part of - WebExtras
// Copyright (C) 2016 Mihir Mone
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;

namespace WebExtras.Core
{
  /// <summary>
  ///   A collection of list types
  /// </summary>
  [Serializable]
  public enum EList
  {
    /// <summary>
    ///   An ordered list
    /// </summary>
    [StringValue("ol")] Ordered,

    /// <summary>
    ///   An unordered list
    /// </summary>
    [StringValue("ul")] Unordered
  }
}


text:
package com.intellij.psi.impl.source;

import com.intellij.lang.ASTNode;
import com.intellij.lang.LighterAST;
import com.intellij.lang.LighterASTNode;
import com.intellij.lang.LighterLazyParseableNode;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.impl.java.stubs.impl.PsiJavaFileStubImpl;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.stubs.LightStubBuilder;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;

public class JavaLightStubBuilder extends LightStubBuilder {
  @NotNull
  @Override
  protected StubElement createStubForFile(@NotNull PsiFile file, @NotNull LighterAST tree) {
    if (!(file instanceof PsiJavaFile)) {
      return super.createStubForFile(file, tree);
    }

    String refText = "";
    LighterASTNode pkg = LightTreeUtil.firstChildOfType(tree, tree.getRoot(), JavaElementType.PACKAGE_STATEMENT);
    if (pkg != null) {
      LighterASTNode ref = LightTreeUtil.firstChildOfType(tree, pkg, JavaElementType.JAVA_CODE_REFERENCE);
      if (ref != null) {
        refText = JavaSourceUtil.getReferenceText(tree, ref);
      }
    }
    return new PsiJavaFileStubImpl((PsiJavaFile)file, refText, null, false);
  }

  @Override
  public boolean skipChildProcessingWhenBuildingStubs(@NotNull ASTNode parent, @NotNull ASTNode node) {
    IElementType parentType = parent.getElementType();
    IElementType nodeType = node.getElementType();

    if (checkByTypes(parentType, nodeType)) return true;

    if (nodeType == JavaElementType.CODE_BLOCK) {
      CodeBlockVisitor visitor = new CodeBlockVisitor();
      ((TreeElement)node).acceptTree(visitor);
      return visitor.result;
    }

    return false;
  }

  @Override
  protected boolean skipChildProcessingWhenBuildingStubs(@NotNull LighterAST tree, @NotNull LighterASTNode parent, @NotNull LighterASTNode node) {
    return checkByTypes(parent.getTokenType(), node.getTokenType()) || isCodeBlockWithoutStubs(node);
  }

  public static boolean isCodeBlockWithoutStubs(@NotNull LighterASTNode node) {
    if (node.getTokenType() == JavaElementType.CODE_BLOCK && node instanceof LighterLazyParseableNode) {
      CodeBlockVisitor visitor = new CodeBlockVisitor();
      ((LighterLazyParseableNode)node).accept(visitor);
      return visitor.result;
    }

    return false;
  }

  private static boolean checkByTypes(IElementType parentType, IElementType nodeType) {
    if (ElementType.IMPORT_STATEMENT_BASE_BIT_SET.contains(parentType)) {
      return true;
    }
    if (nodeType == JavaElementType.RECEIVER_PARAMETER) {
      return true;
    }
    if (nodeType == JavaElementType.PARAMETER && parentType != JavaElementType.PARAMETER_LIST) {
      return true;
    }
    if (nodeType == JavaElementType.PARAMETER_LIST && parentType == JavaElementType.LAMBDA_EXPRESSION) {
      return true;
    }
    if (nodeType == JavaDocElementType.DOC_COMMENT) {
      return true;
    }

    return false;
  }

  private static class CodeBlockVisitor extends RecursiveTreeElementWalkingVisitor implements LighterLazyParseableNode.Visitor {
    private static final TokenSet BLOCK_ELEMENTS = TokenSet.create(
      JavaElementType.ANNOTATION, JavaElementType.CLASS, JavaElementType.ANONYMOUS_CLASS,
      JavaElementType.LAMBDA_EXPRESSION, JavaElementType.METHOD_REF_EXPRESSION);

    private boolean result = true;

    @Override
    protected void visitNode(TreeElement element) {
      if (BLOCK_ELEMENTS.contains(element.getElementType())) {
        result = false;
        stopWalking();
        return;
      }
      super.visitNode(element);
    }

    private IElementType last;
    private boolean seenNew;

    @Override
    @SuppressWarnings("IfStatementWithIdenticalBranches")
    public boolean visit(IElementType type) {
      if (ElementType.JAVA_COMMENT_OR_WHITESPACE_BIT_SET.contains(type)) {
        return true;
      }

      // annotations, method refs & lambdas
      if (type == JavaTokenType.AT || type == JavaTokenType.ARROW || type == JavaTokenType.DOUBLE_COLON) {
        return (result = false);
      }
      // anonymous classes
      else if (type == JavaTokenType.NEW_KEYWORD) {
        seenNew = true;
      }
      else if (seenNew && type == JavaTokenType.SEMICOLON) {
        seenNew = false;
      }
      else if (seenNew && type == JavaTokenType.LBRACE && last != JavaTokenType.RBRACKET) {
        return (result = false);
      }
      // local classes
      else if (type == JavaTokenType.CLASS_KEYWORD && last != JavaTokenType.DOT) {
        return (result = false);
      }

      last = type;
      return true;
    }
  }
}


text:
<?xml version="1.1" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="Smoke test" verbose="1" data-provider-thread-count="1" parallel="false">

	<test name="Clients page">
		<parameter name="path" value="/"/>
		<classes>
			<class name="clients.Details_elements"/>
		    <class name="clients.Details"/>
		    <class name="clients.Navigation"/>
		    <class name="clients.Website"/>
		    <class name="clients.Link_visit_website"/>
		</classes>
	</test>

	<test name="JS Errors">
		<parameter name="path" value="/"/>
		<classes>
			<class name="home.JS_error_home"/>
			<class name="about.JS_error_about"/>
			<class name="clients.JS_error_clients"/>
			<class name="clients.JS_error_detail_clients"/>
			<class name="services.JS_error__services"/>
			<class name="contact.JS_error_contact"/>
			<class name="blog.JS_error_blog"/>
			<class name="blog.JS_error_post"/>
		</classes>
	</test>

	<test name="Homepage">
		<parameter name="path" value="/"/>
		<classes>
			<class name="home.Newsletter_empty"/>
		    <class name="home.Newsletter_invalid"/>
		    <class name="home.Newsletter_valid"/>
		    <class name="home.Banner"/>
		</classes>
	</test>

	<test name="About page">
		<parameter name="path" value="/"/>
		<classes>
		    <class name="about.Tabs"/>
		    <class name="about.Contact_us"/>
		</classes>
	</test>

	<test name="Services page">
		<parameter name="path" value="/"/>
		<classes>
		    <class name="services.Page"/>
		</classes>
	</test>

	<test name="Contact page">
		<parameter name="path" value="/"/>
		<classes>
		    <class name="contact.Form_invalid"/>
		    <class name="contact.Form_empty"/>
		    <class name="contact.Form_valid"/>
		    <class name="contact.Contact_email_change"/>
		</classes>
	</test>

	<test name="Blog page">
		<parameter name="path" value="/"/>
		<classes>
		    <class name="blog.Captcha_empty"/>
		    <class name="blog.Captcha_disable"/>
		    <class name="blog.Comment"/>
		    <class name="blog.Captche_enable"/>
		    <class name="blog.Details_page"/>
			<class name="blog.Blog_page"/>
			<class name="blog.Search"/>
		</classes>
	</test>

</suite>


text:
{% extends "base.html" %}
{% load compress %}

{% block title%}{{ post.title }} — Django México{% endblock %}
{% block title-content %}{{ post.title }}{% endblock %}
{% block description-content %}{{ post.description }}{% endblock %}
{% block og-url %}{{ post.full_url }}{% endblock %}
{% block og-title %}{{ post.title }}{% endblock %}
{% if post.image %}{% block og-image %}{{post.img_full_url}}{% endblock %}{% endif %}

{% block og-description %}{{ post.description }}{% endblock %}
{% if post.image %}{% block twitter-image %}{{post.img_full_url}}{% endblock %}{% endif %}

{% block extra-meta %}
<meta name="author" content="{{ post.author.username }}">
<meta property="og:type" content="article">
<meta property="article:publisher" content="https://django.mx/blog">
<meta property="article:author" content="{{ post.author.first_name }}">
<meta property="article:published_time" content="{{ post.created_at|date:"c" }}">

<link rel="canonical" href="{{post.full_url}}">
{% endblock %}

{% block activeblog %}class="active"{% endblock %}

{% block content %}

El blog de django.mx

{{ post.title }}

                {{ post.created_at }} por
                {{ post.author.username }}

            {% if post.image %}

            {% endif %}
            {{ post.content|safe|escape }}

            Tweet

            Please enable JavaScript to view the comments powered by Disqus.

En este blog trataremos de escribir tips y otras cosas útiles de django o python.

En otra parte

Twitter

Facebook

GitHub

{% endblock %}


text:
package logging

import (
	"bytes"
	"fmt"
	"sync"
	"time"

	"github.com/cossacklabs/acra/utils"
	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

// ---------- custom Loggers
// inspired by "github.com/bshuster-repo/logrus-logstash-hook"
// ----------

// TextFormatter returns a default logrus.TextFormatter with specific settings
func TextFormatter() Formatter {
	return &AcraTextFormatter{
		Formatter: &logrus.TextFormatter{
			FullTimestamp:    true,
			TimestampFormat:  time.RFC3339,
			QuoteEmptyFields: true,
		},
		Hooks: nil,
	}
}

// JSONFormatter returns a default logrus.JSONFormatter with specific settings
func JSONFormatter() Formatter {
	return &AcraJSONFormatter{
		Formatter: &logrus.JSONFormatter{
			FieldMap:        JSONFieldMap,
			TimestampFormat: time.RFC3339,
		},
		Hooks:  nil,
		Fields: nil,
	}
}

// CEFFormatter returns a default CEFTextFormatter with specific settings
func CEFFormatter() Formatter {
	return &AcraCEFFormatter{
		CEFTextFormatter: CEFTextFormatter{
			TimestampFormat: time.RFC3339,
		},
		Fields: nil,
		Hooks:  nil,
	}
}

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

// Using a pool to re-use of old entries when formatting messages.
// It is used in the Fire function.
var entryPool = sync.Pool{
	New: func() interface{} {
		return &logrus.Entry{}
	},
}

// copyEntry copies the entry `e` to a new entry and then adds all the fields in `fields` that are missing in the new entry data.
// It uses `entryPool` to re-use allocated entries.
func copyEntry(e *logrus.Entry, fields logrus.Fields) *logrus.Entry {
	ne := entryPool.Get().(*logrus.Entry)
	ne.Message = e.Message
	ne.Level = e.Level
	ne.Time = e.Time
	ne.Data = logrus.Fields{}
	for k, v := range fields {
		ne.Data[k] = v
	}
	for k, v := range e.Data {
		ne.Data[k] = v
	}
	return ne
}

// releaseEntry puts the given entry back to `entryPool`. It must be called if copyEntry is called.
func releaseEntry(e *logrus.Entry) {
	entryPool.Put(e)
}

// AcraTextFormatter provides log formatting as plaintext.
//
// Hooks may be used for additional post-processing of entries.
//
// Use `TextFormatter` to instantiate AcraTextFormatter.
type AcraTextFormatter struct {
	logrus.Formatter
	Hooks []FormatterHook
}

// SetServiceName set service name
func (f *AcraTextFormatter) SetServiceName(serviceName string) {
	// service name is ignored by plaintext formatter, so just do nothing
}

// SetHooks set formatter hooks
func (f *AcraTextFormatter) SetHooks(hooks []FormatterHook) {
	f.Hooks = hooks
}

// GetHooks get formatter hooks
func (f *AcraTextFormatter) GetHooks() []FormatterHook {
	return f.Hooks
}

// AcraJSONFormatter represents a format with specific fields.
//
// It has logrus.Formatter which formats the entry and logrus.Fields which
// are added to the JSON/CEF message if not given in the entry data.
//
// Hooks may be used for more fine-tuned post-processing of entries.
//
// Note: use the `JSONFormatter` function to set a default AcraJSON formatter.
type AcraJSONFormatter struct {
	logrus.Formatter
	logrus.Fields
	Hooks []FormatterHook
}

// SetServiceName set service name
func (f *AcraJSONFormatter) SetServiceName(serviceName string) {
	fields := log.Fields{FieldKeyProduct: serviceName}
	for k, v := range extraJSONFields {
		if _, ok := fields[k]; !ok {
			fields[k] = v
		}
	}
	f.Fields = fields
}

// SetHooks set formatter hooks
func (f *AcraJSONFormatter) SetHooks(hooks []FormatterHook) {
	f.Hooks = hooks
}

// GetHooks get formatter hooks
func (f *AcraJSONFormatter) GetHooks() []FormatterHook {
	return f.Hooks
}

// AcraCEFFormatter is based on CEFTextFormatter with extra logrus fields.
//
// Hooks may be used for more fine-tuned post-processing of entries.
type AcraCEFFormatter struct {
	CEFTextFormatter
	logrus.Fields
	Hooks []FormatterHook
}

// SetServiceName set service name
func (f *AcraCEFFormatter) SetServiceName(serviceName string) {
	fields := log.Fields{FieldKeyProduct: serviceName}
	for k, v := range extraJSONFields {
		if _, ok := fields[k]; !ok {
			fields[k] = v
		}
	}
	for k, v := range extraCEFFields {
		if _, ok := fields[k]; !ok {
			fields[k] = v
		}
	}
	f.Fields = fields
}

// SetHooks set formatter hooks
func (f *AcraCEFFormatter) SetHooks(hooks []FormatterHook) {
	f.Hooks = hooks
}

// GetHooks get formatter hooks
func (f *AcraCEFFormatter) GetHooks() []FormatterHook {
	return f.Hooks
}

// Constants showing extra filed added to loggers by default
var (
	// to be re-defined
	extraJSONFields = logrus.Fields{
		FieldKeyProduct:  "acra",
		FieldKeyUnixTime: 0,
		FieldKeyVersion:  utils.VERSION,
	}

	// to be re-defined
	extraCEFFields = logrus.Fields{
		FieldKeyVendor:    "cossacklabs",
		FieldKeyEventCode: EventCodeGeneral,
	}

	JSONFieldMap = logrus.FieldMap{
		logrus.FieldKeyTime:  "timestamp",
		logrus.FieldKeyMsg:   "msg",
		logrus.FieldKeyLevel: "level",
	}
)

// Format a log entry in standard plaintext format.
func (f *AcraTextFormatter) Format(e *logrus.Entry) ([]byte, error) {
	return formatEntry(e, f.Formatter, f.Hooks)
}

// Format formats an entry to a AcraJSON format according to the given Formatter and Fields.
//
// Note: the given entry is copied and not changed during the formatting process.
func (f AcraJSONFormatter) Format(e *logrus.Entry) ([]byte, error) {
	ne := copyEntry(e, f.Fields)
	if value, ok := ne.Data[FieldKeyUnixTime]; !ok || value == 0 {
		ne.Data[FieldKeyUnixTime] = unixTimeWithMilliseconds(e)
	}
	dataBytes, err := formatEntry(ne, f.Formatter, f.Hooks)
	releaseEntry(ne)
	return dataBytes, err
}

// Format formats an entry to a AcraCEF format according to the given Formatter and Fields.
//
// Note: the given entry is copied and not changed during the formatting process.
func (f *AcraCEFFormatter) Format(e *logrus.Entry) ([]byte, error) {
	ne := copyEntry(e, f.Fields)
	if value, ok := ne.Data[FieldKeyUnixTime]; !ok || value == 0 {
		ne.Data[FieldKeyUnixTime] = unixTimeWithMilliseconds(e)
	}
	dataBytes, err := formatEntry(ne, &f.CEFTextFormatter, f.Hooks)
	releaseEntry(ne)
	return dataBytes, err
}

// TimeToString return string representation of timestamp with milliseconds
func TimeToString(t time.Time) string {
	return nanosecondsToMillisecondsString(t.UnixNano())
}

func nanosecondsToMillisecondsString(nanos int64) string {
	millis := nanos / 1000000
	millisf := float64(millis) / 1000.0
	return fmt.Sprintf("%.3f", millisf)
}

func unixTimeWithMilliseconds(e *logrus.Entry) string {
	return TimeToString(e.Time)
}

func formatEntry(e *logrus.Entry, formatter log.Formatter, hooks []FormatterHook) ([]byte, error) {
	for _, hook := range hooks {
		err := hook.PreFormat(e)
		if err != nil {
			return nil, err
		}
	}
	serialized, err := formatter.Format(e)
	if err != nil {
		return nil, err
	}
	buffer := bytes.NewBuffer(serialized)
	for _, hook := range hooks {
		err := hook.PostFormat(e, buffer)
		if err != nil {
			return nil, err
		}
	}
	return buffer.Bytes(), nil
}


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

namespace Demontpx\UserBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class DemontpxUserExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yml');

        $root = 'demontpx_user.';

        $container->setParameter($root . 'roles', $config['roles']);
        $container->setParameter($root . 'fixtures', $config['fixtures']);

        $container->setParameter($root . 'gravatar.default_size', $config['gravatar']['default_size']);
        $container->setParameter($root . 'gravatar.default_rating', $config['gravatar']['default_rating']);
        $container->setParameter($root . 'gravatar.default_default', $config['gravatar']['default_default']);
        $container->setParameter($root . 'gravatar.default_force_default', $config['gravatar']['default_force_default']);

        $container->setAlias($root . 'entity_manager', $config['orm_entity_manager']);
    }
}


text:
package missinggo

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

// Calls suite with the used time.Now function used by MonotonicNow replaced
// with stdNow for the duration of the call.
func withCustomStdNow(stdNow func() time.Time, suite func()) {
	oldStdNow := stdNowFunc
	oldSkew := monotonicSkew
	defer func() {
		stdNowFunc = oldStdNow
		monotonicSkew = oldSkew
	}()
	stdNowFunc = stdNow
	suite()
}

// Returns a time.Now-like function that walks seq returning time.Unix(0,
// seq[i]) in successive calls.
func stdNowSeqFunc(seq []int64) func() time.Time {
	var i int
	return func() time.Time {
		defer func() { i++ }()
		return time.Unix(0, seq[i])
	}
}

func TestMonotonicTime(t *testing.T) {
	started := MonotonicNow()
	withCustomStdNow(stdNowSeqFunc([]int64{2, 1, 3, 3, 2, 3}), func() {
		i0 := MonotonicNow() // 0
		i1 := MonotonicNow() // 1
		assert.EqualValues(t, 0, i0.Sub(i1))
		assert.EqualValues(t, 2, MonotonicSince(i0)) // 2
		assert.EqualValues(t, 2, MonotonicSince(i1)) // 3
		i4 := MonotonicNow()
		assert.EqualValues(t, 2, i4.Sub(i0))
		assert.EqualValues(t, 2, i4.Sub(i1))
		i5 := MonotonicNow()
		assert.EqualValues(t, 3, i5.Sub(i0))
		assert.EqualValues(t, 3, i5.Sub(i1))
		assert.EqualValues(t, 1, i5.Sub(i4))
	})
	// Ensure that skew and time function are restored correctly and within
	// reasonable bounds.
	assert.True(t, MonotonicSince(started) >= 0 && MonotonicSince(started) < time.Second)
}


text:
#include <netinet/in.h>
#include "network/ChunkFactory.h"

namespace Network
{

// PUBLIC

ChunkFactory::ChunkFactory():   _sizeChunks(0),
    _chunkID(1),
    _packetID(1) {}

ChunkFactory::~ChunkFactory()
{
    _chunks.clear();
}

/**
 * @brief Convert a vector of Landmark into string to put it in chunk(s)
 * @details Iterates on a vector of Landmarks using processData()
 * @param landmarks_ Vector of landmark_ containing informations about the captured points
 */
void ChunkFactory::processData(const std::vector< Landmarks::Landmark* >& landmarks_)
{
    std::vector<Landmarks::Landmark*>::const_iterator it;
    for (it = landmarks_.begin() ; it != landmarks_.end(); ++it)
    {
        if (*it != NULL)
            processData((Landmarks::Landmark&)(*(*it))); // Get the reference from the pointer.
    }
}

/**
 * @brief Convert a Landmark into string to put it in chunk
 * @details Create the chunk header and add a landmark_ packet
 * to it using fromLandmarkToString().
 * Then it push the temporary chunk into the deque of chunks.
 * @param landmarks_ Class landmark_ containing informations about the captured points
 */
void ChunkFactory::processData(const Landmarks::Landmark& landmark_)
{
    _tmpChunk = MAGIC_NB_LANDMARK; // The Magic
    _tmpChunk += getNewChunkID(); // The Chunk ID
    _tmpChunk += fromLandmarkToString(landmark_); // The packet

    pushTmpChunkToChunks();
}

/**
 * @brief Convert a PointCloud of PointXYZRGBA into packets of string(s) to put in chunk(s)
 * @details
 * @param points PointCloud containing only 3D point informations about the captured points
 */
void ChunkFactory::processData(const pcl::PointCloud< pcl::PointXYZRGBA >& pointCloud)
{
    unsigned int cloudIndex = 0;
    unsigned int packetDone = 0;
    unsigned int totalPacketNeeded;
    std::string packet;
    std::string metadataPacket;

    totalPacketNeeded = calculateTotalPacketNeeded(pointCloud);

    while (packetDone < totalPacketNeeded)
    {
        packet = convertDataPacket(pointCloud, cloudIndex);
        metadataPacket = createPacketMetadata(++packetDone, totalPacketNeeded, packet);
        _tmpChunk = MAGIC_NB_POINTCLOUD; // The Magic
        _tmpChunk += getNewChunkID(); // The Chunk ID
        _tmpChunk += metadataPacket + packet; // The Packet
        pushTmpChunkToChunks();
    }
    ++_packetID;
}

// Getters
/**
 * @brief Return whether _chunks is empty or not
 * @return A boolean to tell you whether _chunks is empty or not.
 */
bool ChunkFactory::isFullChunkReady() const { return (_chunks.size() == 0) ? (false) : (true); }

/**
 * @brief Get a chunk already prepared by ChunkFactory
 * @return A chunk (string) ready to sent through UDP. If there is no chunk prepared, it will
 * send an empty string.
 */
std::string ChunkFactory::getChunk()
{
    std::string chunk = "";

    if (_chunks.size() != 0)
    {
        chunk = _chunks.back();
        _chunks.pop_back();
        decreaseSizeChunks(chunk.size());
    }
    return chunk;
}

// PRIVATE

/**
 * @brief Push the temporary chunk into the deque _chunks
 * @details If not empty, put the temporary chunk into the deque of
 * chunks and clear it. It also call increaseSizeChunks()
 */
void ChunkFactory::pushTmpChunkToChunks()
{
    if (_tmpChunk.size() > 0)
    {
        _chunks.push_front(_tmpChunk);
        increaseSizeChunks(_tmpChunk.size());
        _tmpChunk.erase();
    }
}

/**
 * @brief Convert the class Landmark into a string
 * @details The chosen variable converted into the string are:
 * pos, robotPos, id, life, totalTimeObserved, bearing, range.
 * @param landmark_ Class containing 3D information that we have to convert
 * @return Return a string containing chosen information of the class Landmark
 */
std::string ChunkFactory::fromLandmarkToString(const Landmarks::Landmark& landmark_)
{
    std::string strLandmark = "";

    strLandmark += fromPclPointToString(landmark_.pos);
    strLandmark += fromPclPointToString(landmark_.robotPos);
    strLandmark += encodeNbIntoString((void*) & (landmark_.id), sizeof(landmark_.id));
    strLandmark += encodeNbIntoString((void*) & (landmark_.life), sizeof(landmark_.life));
    strLandmark += encodeNbIntoString((void*) & (landmark_.totalTimeObserved), sizeof(landmark_.totalTimeObserved));
    strLandmark += encodeNbIntoString((void*) & (landmark_.bearing), sizeof(landmark_.bearing));
    strLandmark += encodeNbIntoString((void*) & (landmark_.range), sizeof(landmark_.range));

    return strLandmark;
}

/*
 * Calculate the total number of packet we need to do to send the cloud
 */
int ChunkFactory::calculateTotalPacketNeeded(const pcl::PointCloud< pcl::PointXYZRGBA >& cloud)
{
    unsigned int        totalPacketNeeded = 0;
    unsigned int        totalNbOfPoint = cloud.size();
    unsigned int        nbOfPointInPacket;

    nbOfPointInPacket = SIZE_IN_PACKET / SIZE_OF_POINT_XYZ;
    totalPacketNeeded = (totalNbOfPoint / nbOfPointInPacket);

    return ((totalNbOfPoint % nbOfPointInPacket) > 0) ? (++totalPacketNeeded) : (totalPacketNeeded) ;
}

std::string ChunkFactory::createPacketMetadata(unsigned int currentPacket, unsigned int totalPacket, std::string& packet)
{
    unsigned short      packetSize = (unsigned short)(packet.size());
    std::string         metadata = "";

    metadata += encodeNbIntoString((void*) & (_packetID), sizeof(_packetID));
    metadata += encodeNbIntoString((void*) & (currentPacket), sizeof(currentPacket));
    metadata += encodeNbIntoString((void*) & (totalPacket), sizeof(totalPacket));
    metadata += encodeNbIntoString((void*) & (packetSize), sizeof(packetSize));

    return metadata;
}

std::string ChunkFactory::convertDataPacket(const pcl::PointCloud< pcl::PointXYZRGBA >& cloud, unsigned int& cloudIndex)
{
    std::string packetData = "";
    unsigned int nbOfPoint;

    nbOfPoint = SIZE_IN_PACKET / SIZE_OF_POINT_XYZ;

    packetData += convertRangeOfPoint(cloud, cloudIndex, nbOfPoint);

    return packetData;
}

std::string ChunkFactory::convertRangeOfPoint(const pcl::PointCloud< pcl::PointXYZRGBA >& cloud, unsigned int& cloudIndex, unsigned int nbOfPoint)
{
    std::string convertedPoints = "";
    unsigned int i;

    for (i = 0; i < nbOfPoint; ++i)
        convertedPoints += fromPclPointRGBToString(cloud[cloudIndex + i]);

    cloudIndex += i;
    return convertedPoints;
}

int dumper4(const void* target)
{
    int* tmp = (int*)target;
    return (int)(*tmp);
}

long long dumper8(const void* target)
{
    long long* tmp = (long long*)target;
    return (long long)(*tmp);
}

/**
 * @brief Convert PointXYZ into a string
 * @details It convert in a string the variable x, y and z
 * So the length of the string would be sizeof(x) + sizeof(y) + sizeof(z)
 * @return An encoded string containing PointXYZ informations
 */
std::string ChunkFactory::fromPclPointToString(const pcl::PointXYZ& points)
{
    std::string stringPoints = "";

    //std::cout << points.x << " " << points.y << " " << points.z << std::endl;
    // std::cout << std::hex << dumper4(&points.x) << " " << dumper4(&points.y) << " " << dumper4(&points.z) << std::endl;

    stringPoints += encodeNbIntoString((void*) & (points.x), sizeof(points.x));
    stringPoints += encodeNbIntoString((void*) & (points.y), sizeof(points.y));
    stringPoints += encodeNbIntoString((void*) & (points.z), sizeof(points.z));

    return stringPoints;
}

void ChunkFactory::setTrueStringFromPoints(float data, std::string &stringPoints) {
    // float default_value = 0;
    // if (data == data)
  stringPoints += encodeNbIntoString((void*) & (data), sizeof(data));
    // else
    //     stringPoints += encodeNbIntoString((void*) & (default_value), sizeof(float));
    //std::cerr << "data in float "<< data << std::endl;
}
/**
 * @brief Convert PointXYZRGBA into a string
 * @details It convert in a string the variable x, y and z
 * So the length of the string would be sizeof(x) + sizeof(y) + sizeof(z)
 * @return An encoded string containing PointXYZRGBA informations
 */
std::string ChunkFactory::fromPclPointRGBToString(const pcl::PointXYZRGBA& points)
{
    std::string stringPoints = "";

    //std::cerr << points.x << " " << points.y << " " << points.z << std::endl;

    // std::cerr << (int)points.r << " " << (int)points.g << " " << (int)points.b << std::endl;
    // std::cerr << "size of points " << sizeof((float)points.r) << sizeof(uint8_t) << std::endl;
    // std::cout << std::hex << dumper4(&points.x) << " " << dumper4(&points.y) << " " << dumper4(&points.z) << std::endl;
    // std::cerr << "size of point.r == " << sizeof(float)  << std::endl;
    // std::cerr << "size of cloud == " << sizeof(points)  << std::endl;
    //To do to check if points.x is set, strange but that how it works
    setTrueStringFromPoints(points.x, stringPoints);
    setTrueStringFromPoints(points.y, stringPoints);
    setTrueStringFromPoints(points.z, stringPoints);
    setTrueStringFromPoints(points.r, stringPoints);
    setTrueStringFromPoints(points.g, stringPoints);
    setTrueStringFromPoints(points.b, stringPoints);
    // stringPoints += encodeNbIntoString((void*) & (((float)points.r)), sizeof(float));
    // stringPoints += encodeNbIntoString((void*) & (((float)points.g)), sizeof(float));
    // stringPoints += encodeNbIntoString((void*) & (((float)points.b)), sizeof(float));

    //std::cerr << "stringPoints to send " << stringPoints << std::endl;
    // if (points.x == points.x)
    //     stringPoints += encodeNbIntoString((void*) & (points.x), sizeof(points.x));
    // else
    //     stringPoints += encodeNbIntoString((void*) & (0), sizeof(float));
    // if (points.y == points.y)
    //     stringPoints += encodeNbIntoString((void*) & (points.y), sizeof(points.y));
    // else
    //     stringPoints += encodeNbIntoString((void*) & (0), sizeof(float));
    // if (points.z == points.z)
    //     stringPoints += encodeNbIntoString((void*) & (points.z), sizeof(points.z));
    // else
    //     stringPoints += encodeNbIntoString((void*) & (0), sizeof(float));
    // if (points.r == points.r)
    //     stringPoints += encodeNbIntoString((void*) & (points.r), sizeof(float));
    // else
    //     stringPoints += encodeNbIntoString((void*) & (0), sizeof(float));
    // stringPoints += encodeNbIntoString((void*) & (g), sizeof(float));
    // stringPoints += encodeNbIntoString((void*) & (b), sizeof(float));

    return stringPoints;
}

/**
 * @brief Convert any atomic variable into a string
 * @details Use a generic pointer to be able to read any function as a character string.
 * Then it uses the nbOfByte (which is a sizeof() of the variable) to read correctly Byte by
 * Byte the variable and add it to encoded (a string).
 * @param *nb A generic pointer pointing on the variable you want to encode
 * @param nbOfByte A sizeof() of the variable you want to encode
 * @return A string containing the bytes informations of the variable
 */
std::string ChunkFactory::encodeNbIntoString(void* nb, unsigned long nbOfByte)
{
    char* nb_ = (char*)nb;
    std::string encoded = "";

    for (long i = nbOfByte - 1; i >= 0; --i)
    {
        char tmp = 0;
        tmp |= nb_[i];
        encoded += tmp;
    }
    //  std::cout << std::hex << encoded;
    return encoded;
}

/// @brief Add the size of the added chunk into the deque of chunks _chunks
void ChunkFactory::increaseSizeChunks(unsigned int cSize) { _sizeChunks += cSize; }
/// @brief Subtract the size of the removed chunk from the deque of chunks _chunks
void ChunkFactory::decreaseSizeChunks(unsigned int cSize) { _sizeChunks -= cSize; }

/// @brief Return a new Chunk ID in a string and increase it
std::string ChunkFactory::getNewChunkID()
{
    std::string tmpChunkID = encodeNbIntoString((void*) & (_chunkID), sizeof(_chunkID));
    ++_chunkID;

    return tmpChunkID;
}

} // end of namespace


text:
'use strict';
var global = require('../internals/global');
var ArrayBufferViewCore = require('../internals/array-buffer-view-core');
var fails = require('../internals/fails');

var Int8Array = global.Int8Array;
var aTypedArray = ArrayBufferViewCore.aTypedArray;
var $toLocaleString = [].toLocaleString;
var $slice = [].slice;

// iOS Safari 6.x fails here
var TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {
  $toLocaleString.call(new Int8Array(1));
});

var FORCED = fails(function () {
  return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();
}) || !fails(function () {
  Int8Array.prototype.toLocaleString.call([1, 2]);
});

// `%TypedArray%.prototype.toLocaleString` method
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.tolocalestring
ArrayBufferViewCore.exportProto('toLocaleString', function toLocaleString() {
  return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);
}, FORCED);


text:
package com.palamida.util.collect;

import java.util.ListIterator;

/**
 * A {@link SortedCollection} which may contain duplicate elements and allows
 * users to access or remove elements by their integer index.
 *

 * This is the list analog to sorted set.
 *
 * @author Zhenya Leonov List
 * @param <E>
 *            the type of elements held in this list
 */
public interface Sortedlist<E> extends SortedCollection<E> {

	/**
	 * Returns the element at the specified position.
	 *
	 * @param index
	 *            index of the element to return
	 * @return the element at the specified position
	 * @throws IndexOutOfBoundsException
	 *             if the specified index is out of range
	 */
	public E get(int index);

	/**
	 * Removes and returns the element at the specified position (optional
	 * operation).
	 *
	 * @param index
	 *            the index of the element to be removed
	 * @return the element previously at the specified position
	 * @throws IndexOutOfBoundsException
	 *             if the specified index is out of range
	 */
	public E remove(int index);

	/**
	 * Returns the index of the first occurrence of the specified element, or -1
	 * if the element is not present.
	 *
	 * @param o
	 *            element to search for
	 * @return the index of the first occurrence of the specified element, or -1
	 *         if the element is not present
	 */
	public int indexOf(Object o);

	/**
	 * Returns the index of the last occurrence of the specified element, or -1
	 * if the element is not present.
	 *
	 * @param o
	 *            element to search for
	 * @return the index of the last occurrence of the specified element, or -1
	 *         if the element is not present
	 */
	public int lastIndexOf(Object o);

	/**
	 * Returns a list iterator over the elements in this sorted-list.
	 *

	 * The returned iterator does not support the
	 * {@link ListIterator#add(Object) add(E)} and
	 * {@link ListIterator#set(Object) set(E)} operations.
	 *
	 * @return a list iterator over the elements in this sorted-list
	 */
	public ListIterator<E> listIterator();

	/**
	 * Returns a list iterator over the elements in this sorted-list, starting
	 * at the specified position.
	 *

	 * The returned iterator does not support the
	 * {@link ListIterator#add(Object) add(E)} and
	 * {@link ListIterator#set(Object) set(E)} operations.
	 *
	 * @param index
	 *            index of the first element to be returned from the collection
	 *            iterator by a call to {@link ListIterator#next() next()}
	 * @return a list iterator over the elements in this sorted-list, starting
	 *         at the specified position
	 */
	public ListIterator<E> listIterator(int index);

	/**
	 * Returns a view of the portion of this sorted-list whose elements range
	 * between {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. If
	 * {@code fromIndex} and {@code toIndex} are equal, the returned sorted-list
	 * is empty. The returned sorted-list is backed by this sorted-list, so
	 * changes in the returned sorted-list are reflected in this sorted-list,
	 * and vice-versa.
	 *

	 * The returned sorted-list will throw an {@code IllegalArgumentException}
	 * on an attempt to insert an element outside its range.
	 *
	 * @param fromIndex
	 *            low endpoint (inclusive) of the returned sorted-list
	 * @param toIndex
	 *            high endpoint (exclusive) of the returned sorted-list
	 * @return a view of the portion of this sorted-list within the specified
	 *         range
	 * @throws IndexOutOfBoundsException
	 *             if
	 *             {@code fromIndex < 0 || toIndex > size || fromIndex > toIndex}
	 */
	public Sortedlist<E> sublist(int fromIndex, int toIndex);

	/**
	 * Returns the hash code value for this sorted-list. The hash code of a
	 * sorted-list is defined to be the result of the following calculation:
	 *
	 *

	 * int hashCode = 1;
	 * for (E e : this)
	 *     hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
	 *

	 *
	 * @return the hash code value for this sorted-list
	 */
	@Override
	public int hashCode();

	/**
	 * Compares the specified object with this sorted-list for equality. Returns
	 * {@code true} if and only if the specified object is also a sorted-list,
	 * both sorted-lists have the same size, and all corresponding pairs of
	 * elements in the two sorted-lists are equal according to the
	 * definition of this sorted-list.
	 *
	 * @return {@code true} if the specified object is {@code equal} to this
	 *         sorted-list
	 */
	@Override
	public boolean equals(Object o);

}


text:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from tastypie.api import Api
from django.contrib import admin
from Course.api import EnrollmentResource, AssignmentResource

from Course.views import *

admin.autodiscover()

v1_api = Api(api_name='v1')
v1_api.register(EnrollmentResource())
v1_api.register(AssignmentResource())

urlpatterns = patterns('',
    url(r'^$', signup),
    url(r'^api/', include(v1_api.urls)),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^openid/', include('django_openid_auth.urls')),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/',}, name='logout'),
    url(r'^charts/', chart),
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>ro.gov.ithub.infotranspub</groupId>
    <artifactId>alfa</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>alfa</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.7</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>

    <dependencies>

        <!-- Spring REST service -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.strategicgains</groupId>
            <artifactId>RestExpress</artifactId>
            <version>0.11.3</version>
        </dependency>

        <!-- Database -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.3.Final</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.2.5.Final</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgis</groupId>
            <artifactId>postgis-jdbc</artifactId>
            <version>1.3.3</version>
            <scope>compile</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.postgis</groupId>
                    <artifactId>postgis-stubs</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Utils -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

        <!-- Development tools -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!-- Testing -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <type>jar</type>
            <scope>test</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>


text:
import base64

from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log
from oslo_utils import importutils
from oslo_utils import strutils
import six

from manila import exception
from manila.i18n import _
from manila import utils

LOG = log.getLogger(__name__)
CONF = cfg.CONF

winrm_opts = [
    cfg.IntOpt(
        'winrm_conn_timeout',
        default=60,
        help='WinRM connection timeout.'),
    cfg.IntOpt(
        'winrm_operation_timeout',
        default=60,
        help='WinRM operation timeout.'),
    cfg.IntOpt(
        'winrm_retry_count',
        default=3,
        help='WinRM retry count.'),
    cfg.IntOpt(
        'winrm_retry_interval',
        default=5,
        help='WinRM retry interval in seconds'),
]

CONF.register_opts(winrm_opts)

DEFAULT_PORT_HTTP = 5985
DEFAULT_PORT_HTTPS = 5986

TRANSPORT_PLAINTEXT = 'plaintext'
TRANSPORT_SSL = 'ssl'

winrm = None

def setup_winrm():
    global winrm
    if not winrm:
        try:
            winrm = importutils.import_module('winrm')
        except ImportError:
            raise exception.ShareBackendException(
                _("PyWinrm is not installed"))

class WinRMHelper(object):
    def __init__(self, configuration=None):
        if configuration:
            configuration.append_config_values(winrm_opts)
            self._config = configuration
        else:
            self._config = CONF

        setup_winrm()

    def _get_conn(self, server):
        auth = self._get_auth(server)
        conn = WinRMConnection(
            ip=server['ip'],
            conn_timeout=self._config.winrm_conn_timeout,
            operation_timeout=self._config.winrm_operation_timeout,
            **auth)
        return conn

    def execute(self, server, command, check_exit_code=True,
                retry=True):
        retries = self._config.winrm_retry_count if retry else 1
        conn = self._get_conn(server)

        @utils.retry(exception=Exception,
                     interval=self._config.winrm_retry_interval,
                     retries=retries)
        def _execute():
            parsed_cmd, sanitized_cmd = self._parse_command(command)

            LOG.debug("Executing command: %s", sanitized_cmd)
            (stdout, stderr, exit_code) = conn.execute(parsed_cmd)

            sanitized_stdout = strutils.mask_password(stdout)
            sanitized_stderr = strutils.mask_password(stderr)
            LOG.debug("Executed command: %(cmd)s. Stdout: %(stdout)s. "
                      "Stderr: %(stderr)s. Exit code %(exit_code)s",
                      dict(cmd=sanitized_cmd, stdout=sanitized_stdout,
                           stderr=sanitized_stderr, exit_code=exit_code))

            if check_exit_code and exit_code != 0:
                raise processutils.ProcessExecutionError(
                    stdout=sanitized_stdout,
                    stderr=sanitized_stderr,
                    exit_code=exit_code,
                    cmd=sanitized_cmd)
            return (stdout, stderr)
        return _execute()

    def _parse_command(self, command):
        if isinstance(command, list) or isinstance(command, tuple):
            command = " ".join([six.text_type(c) for c in command])

        sanitized_cmd = strutils.mask_password(command)

        b64_command = base64.b64encode(command.encode("utf_16_le"))
        command = ("powershell.exe -ExecutionPolicy RemoteSigned "
                   "-NonInteractive -EncodedCommand %s" % b64_command)
        return command, sanitized_cmd

    def _get_auth(self, server):
        auth = {'username': server['username']}

        if server['use_cert_auth']:
            auth['cert_pem_path'] = server['cert_pem_path']
            auth['cert_key_pem_path'] = server['cert_key_pem_path']
        else:
            auth['password'] = server['password']
        return auth

class WinRMConnection(object):
    _URL_TEMPLATE = '%(protocol)s://%(ip)s:%(port)s/wsman'

    def __init__(self, ip=None, port=None, use_ssl=False,
                 transport=None, username=None, password=None,
                 cert_pem_path=None, cert_key_pem_path=None,
                 operation_timeout=None, conn_timeout=None):
        setup_winrm()

        use_cert = bool(cert_pem_path and cert_key_pem_path)
        transport = (TRANSPORT_SSL
                     if use_cert else TRANSPORT_PLAINTEXT)

        _port = port or self._get_default_port(use_cert)
        _url = self._get_url(ip, _port, use_cert)

        self._conn = winrm.protocol.Protocol(
            endpoint=_url, transport=transport,
            username=username, password=password,
            cert_pem=cert_pem_path, cert_key_pem=cert_key_pem_path)
        self._conn.transport.timeout = conn_timeout
        self._conn.set_timeout(operation_timeout)

    def _get_default_port(self, use_ssl):
        port = (DEFAULT_PORT_HTTPS
                if use_ssl else DEFAULT_PORT_HTTP)
        return port

    def _get_url(self, ip, port, use_ssl):
        if not ip:
            err_msg = _("No IP provided.")
            raise exception.ShareBackendException(msg=err_msg)

        protocol = 'https' if use_ssl else 'http'
        return self._URL_TEMPLATE % {'protocol': protocol,
                                     'ip': ip,
                                     'port': port}

    def execute(self, cmd):
        shell_id = None
        cmd_id = None

        try:
            shell_id = self._conn.open_shell()

            cmd_id = self._conn.run_command(shell_id, cmd)

            (stdout,
             stderr,
             exit_code) = self._conn.get_command_output(shell_id, cmd_id)
        finally:
            if cmd_id:
                self._conn.cleanup_command(shell_id, cmd_id)
            if shell_id:
                self._conn.close_shell(shell_id)

        return (stdout, stderr, exit_code)


text:
FactoryGirl.define do
  factory :scout do
  end
end


text:
package hudson.remoting;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * {@link OutputStream} that sends bits to an exported
 * {@link OutputStream} on a remote machine.
 */
final class ProxyOutputStream extends OutputStream {
    private Channel channel;
    private int oid;

    private PipeWindow window;

    /**
     * If bytes are written to this stream before it's connected
     * to a remote object, bytes will be stored in this buffer.
     */
    private ByteArrayOutputStream tmp;

    /**
     * Set to true if the stream is closed.
     */
    private boolean closed;

    /**
     * Creates unconnected {@link ProxyOutputStream}.
     * The returned stream accepts data right away, and
     * when it's {@link #connect(Channel,int) connected} later,
     * the data will be sent at once to the remote stream.
     */
    public ProxyOutputStream() {
    }

    /**
     * Creates an already connected {@link ProxyOutputStream}.
     *
     * @param oid
     *      The object id of the exported {@link OutputStream}.
     */
    public ProxyOutputStream(Channel channel, int oid) throws IOException {
        connect(channel,oid);
    }

    /**
     * Connects this stream to the specified remote object.
     */
    synchronized void connect(Channel channel, int oid) throws IOException {
        if(this.channel!=null)
            throw new IllegalStateException("Cannot connect twice");
        if(oid==0)
            throw new IllegalArgumentException("oid=0");
        this.channel = channel;
        this.oid = oid;

        window =  channel.getPipeWindow(oid);

        // if we already have bytes to write, do so now.
        if(tmp!=null) {
            byte[] b = tmp.toByteArray();
            tmp = null;
            _write(b,0,b.length);
        }
        if(closed)  // already marked closed?
            doClose();
    }

    public void write(int b) throws IOException {
        write(new byte[]{(byte)b},0,1);
    }

    public void write(byte b[], int off, int len) throws IOException {
        if(closed)
            throw new IOException("stream is already closed");
        _write(b, off, len);
    }

    /**
     * {@link #write(byte[])} without the close check.
     */
    private synchronized void _write(byte[] b, int off, int len) throws IOException {
        if(channel==null) {
            if(tmp==null)
                tmp = new ByteArrayOutputStream();
            tmp.write(b,off,len);
        } else {
            while (len>0) {
                int sendable;
                try {
                    sendable = Math.min(window.get(),len);
                } catch (InterruptedException e) {
                    throw (IOException)new InterruptedIOException().initCause(e);
                }

                channel.send(new Chunk(oid,b,off,sendable));
                window.decrease(sendable);
                off+=sendable;
                len-=sendable;
            }
        }
    }

    public synchronized void flush() throws IOException {
        if(channel!=null)
            channel.send(new Flush(oid));
    }

    public synchronized void close() throws IOException {
        closed = true;
        if(channel!=null)
            doClose();
    }

    private void doClose() throws IOException {
        channel.send(new EOF(oid));
        channel = null;
        oid = -1;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        // if we haven't done so, release the exported object on the remote side.
        if(channel!=null) {
            channel.send(new Unexport(oid));
            channel = null;
            oid = -1;
        }
    }

    /**
     * {@link Command} for sending bytes.
     */
    private static final class Chunk extends Command {
        private final int oid;
        private final byte[] buf;

        public Chunk(int oid, byte[] buf, int start, int len) {
            // to improve the performance when a channel is used purely as a pipe,
            // don't record the stack trace. On FilePath.writeToTar case, the stack trace and the OOS header
            // takes up about 1.5K.
            super(false);
            this.oid = oid;
            if (start==0 && len==buf.length)
                this.buf = buf;
            else {
                this.buf = new byte[len];
                System.arraycopy(buf,start,this.buf,0,len);
            }
        }

        protected void execute(final Channel channel) {
            final OutputStream os = (OutputStream) channel.getExportedObject(oid);
            channel.pipeWriter.submit(new Runnable() {
                public void run() {
                    try {
                        os.write(buf);
                    } catch (IOException e) {
                        try {
                            channel.send(new NotifyDeadWriter(e,oid));
                        } catch (ChannelClosedException x) {
                            // the other direction can be already closed if the connection
                            // shut down is initiated from this side. In that case, remain silent.
                        } catch (IOException x) {
                            // ignore errors
                            LOGGER.log(Level.WARNING, "Failed to notify the sender that the write end is dead",x);
                            LOGGER.log(Level.WARNING, "... the failed write was:",e);
                        }
                    } finally {
                        if (channel.remoteCapability.supportsPipeThrottling()) {
                            try {
                                channel.send(new Ack(oid,buf.length));
                            } catch (ChannelClosedException x) {
                                // the other direction can be already closed if the connection
                                // shut down is initiated from this side. In that case, remain silent.
                            } catch (IOException e) {
                                // ignore errors
                                LOGGER.log(Level.WARNING, "Failed to ack the stream",e);
                            }
                        }
                    }
                }
            });
        }

        public String toString() {
            return "Pipe.Chunk("+oid+","+buf.length+")";
        }

        private static final long serialVersionUID = 1L;
    }

    /**
     * {@link Command} for flushing.
     */
    private static final class Flush extends Command {
        private final int oid;

        public Flush(int oid) {
            super(false);
            this.oid = oid;
        }

        protected void execute(Channel channel) {
            final OutputStream os = (OutputStream) channel.getExportedObject(oid);
            channel.pipeWriter.submit(new Runnable() {
                public void run() {
                    try {
                        os.flush();
                    } catch (IOException e) {
                        // ignore errors
                    }
                }
            });
        }

        public String toString() {
            return "Pipe.Flush("+oid+")";
        }

        private static final long serialVersionUID = 1L;
    }

    /**
     * {@link Command} for releasing an export table.
     *
     * <p>
     * Unlike {@link EOF}, this just unexports but not closes the stream.
     */
    private static class Unexport extends Command {
        private final int oid;

        public Unexport(int oid) {
            this.oid = oid;
        }

        protected void execute(final Channel channel) {
            channel.pipeWriter.submit(new Runnable() {
                public void run() {
                    channel.unexport(oid);
                }
            });
        }

        public String toString() {
            return "Pipe.Unexport("+oid+")";
        }

        private static final long serialVersionUID = 1L;
    }

    /**
     * {@link Command} for sending EOF.
     */
    private static final class EOF extends Command {
        private final int oid;

        public EOF(int oid) {
            this.oid = oid;
        }

        protected void execute(final Channel channel) {
            final OutputStream os = (OutputStream) channel.getExportedObject(oid);
            channel.pipeWriter.submit(new Runnable() {
                public void run() {
                    channel.unexport(oid);
                    try {
                        os.close();
                    } catch (IOException e) {
                        // ignore errors
                    }
                }
            });
        }

        public String toString() {
            return "Pipe.EOF("+oid+")";
        }

        private static final long serialVersionUID = 1L;
    }

    /**
     * {@link Command} to notify the sender that it can send some more data.
     */
    private static class Ack extends Command {
        /**
         * The oid of the {@link OutputStream} on the receiver side of the data.
         */
        private final int oid;
        /**
         * The number of bytes that were freed up.
         */
        private final int size;

        private Ack(int oid, int size) {
            super(false); // performance optimization
            this.oid = oid;
            this.size = size;
        }

        protected void execute(Channel channel) {
            PipeWindow w = channel.getPipeWindow(oid);
            w.increase(size);
        }

        public String toString() {
            return "Pipe.Ack("+oid+','+size+")";
        }

        private static final long serialVersionUID = 1L;
    }

    /**
     * {@link Command} to notify the sender that the receiver is dead.
     */
    private static final class NotifyDeadWriter extends Command {
        private final int oid;

        private NotifyDeadWriter(Throwable cause, int oid) {
            super(cause);
            this.oid = oid;
        }

        @Override
        protected void execute(Channel channel) {
            PipeWindow w = channel.getPipeWindow(oid);
            w.dead(createdAt.getCause());
        }

        public String toString() {
            return "Pipe.Dead("+oid+")";
        }

        private static final long serialVersionUID = 1L;
    }

    private static final Logger LOGGER = Logger.getLogger(ProxyOutputStream.class.getName());
}