text:
package net.anotheria.moskito.webui.producers.api;

import net.anotheria.moskito.core.decorators.value.StatValueAO;
import net.anotheria.moskito.core.inspection.CreationInfo;
import net.anotheria.util.BasicComparable;
import net.anotheria.util.sorter.IComparable;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * Producer API Object.
 *
 * @author lrosenberg
 * @since 22.03.14 14:03
 */
public class ProducerAO implements Serializable, IComparable{

	/**
	 * Id of the producer.
	 */
	private String producerId;
	/**
	 * Category of the producer.
 	 */
	private String category;
	/**
	 * Subsystem producer belongs too.
	 */
	private String subsystem;
	/**
	 * Class name, short (class.getSimpleName());
	 */
	private String producerClassName;
	/**
	 * Class name, long (class.getName());
	 */
	private String fullProducerClassName;

	private List<StatValueAO> firstStatsValues;

	/**
	 * CreationInfo is set for all inspectable producers.
	 */
	private CreationInfo creationInfo;

	/**
	 * All stat values as list of lists. The included list contains one stat - line with multiple values.
	 */
	private List<StatLineAO> lines;

	/**
	 * Clazz name of the stats object contained in this producer (for decorator selection).
	 */
	private String statsClazzName;

	private boolean traceable;

	private boolean traced;

	public ProducerAO(){
		lines = new LinkedList<StatLineAO>();
	}

	public String getProducerId() {
		return producerId;
	}

	public void setProducerId(String producerId) {
		this.producerId = producerId;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getSubsystem() {
		return subsystem;
	}

	public void setSubsystem(String subsystem) {
		this.subsystem = subsystem;
	}

	public String getProducerClassName() {
		return producerClassName;
	}

	public void setProducerClassName(String producerClassName) {
		this.producerClassName = producerClassName;
	}

	/**
	 * Is inspectable, true if there is a creation info available.
	 * @return
	 */
	public boolean isInspectable() {
		return creationInfo!=null;
	}

	public String getStatsClazzName() {
		return statsClazzName;
	}

	public void setStatsClazzName(String aStatsClazzName) {
		statsClazzName = aStatsClazzName;
	}

	public List<StatValueAO> getFirstStatsValues() {
		return firstStatsValues;
	}

	public void setFirstStatsValues(List<StatValueAO> firstStatsValues) {
		this.firstStatsValues = firstStatsValues;
	}

	public void addStatLine(StatLineAO line){
		lines.add(line);
	}
	public List<StatLineAO> getLines() {
		return lines;
	}
	public CreationInfo getCreationInfo() {
		return creationInfo;
	}

	public void setCreationInfo(CreationInfo creationInfo) {
		this.creationInfo = creationInfo;
	}

	private int compareByValue(ProducerAO anotherProducer, int method){
		return firstStatsValues.get(method).compareTo(anotherProducer.firstStatsValues.get(method), method);

	}

	@Override public int compareTo(IComparable anotherComparable, int method) {
		ProducerAO anotherAO = (ProducerAO)anotherComparable;
		if (method< ProducerAOSortType.DYN_SORT_TYPE_LIMIT)
			return compareByValue(anotherAO, method);
		switch(method){
			case ProducerAOSortType.SORT_BY_ID:
				return BasicComparable.compareString(getProducerId(), anotherAO.getProducerId());
			case ProducerAOSortType.SORT_BY_CATEGORY:
				return BasicComparable.compareString(category, anotherAO.category);
			case ProducerAOSortType.SORT_BY_SUBSYSTEM:
				return BasicComparable.compareString(subsystem, anotherAO.subsystem);
			case ProducerAOSortType.SORT_BY_CLASS_NAME:
				return BasicComparable.compareString(getProducerClassName(), anotherAO.getProducerClassName());
			default:
				throw new RuntimeException("Unsupported sort method: "+method);
		}
	}

	public String getFullProducerClassName() {
		return fullProducerClassName;
	}

	public void setFullProducerClassName(String fullProducerClassName) {
		this.fullProducerClassName = fullProducerClassName;
	}

	@Override
	public String toString() {
		return "ProducerAO{" +
				"producerId='" + producerId + '\'' +
				", subsystem='" + subsystem + '\'' +
				", category='" + category + '\'' +
				'}';
	}

	public boolean isTraceable() {
		return traceable;
	}

	public void setTraceable(boolean traceable) {
		this.traceable = traceable;
	}

	public boolean isTraced() {
		return traced;
	}

	public void setTraced(boolean traced) {
		this.traced = traced;
	}
}


text:
package com.google.android.exoplayer2.extractor.mkv;

import androidx.annotation.IntDef;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.extractor.ExtractorInput;
import com.google.android.exoplayer2.util.Assertions;
import java.io.EOFException;
import java.io.IOException;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayDeque;

/**
 * Default implementation of {@link EbmlReader}.
 */
/* package */ final class DefaultEbmlReader implements EbmlReader {

  @Documented
  @Retention(RetentionPolicy.SOURCE)
  @IntDef({ELEMENT_STATE_READ_ID, ELEMENT_STATE_READ_CONTENT_SIZE, ELEMENT_STATE_READ_CONTENT})
  private @interface ElementState {}

  private static final int ELEMENT_STATE_READ_ID = 0;
  private static final int ELEMENT_STATE_READ_CONTENT_SIZE = 1;
  private static final int ELEMENT_STATE_READ_CONTENT = 2;

  private static final int MAX_ID_BYTES = 4;
  private static final int MAX_LENGTH_BYTES = 8;

  private static final int MAX_INTEGER_ELEMENT_SIZE_BYTES = 8;
  private static final int VALID_FLOAT32_ELEMENT_SIZE_BYTES = 4;
  private static final int VALID_FLOAT64_ELEMENT_SIZE_BYTES = 8;

  private final byte[] scratch;
  private final ArrayDeque<MasterElement> masterElementsStack;
  private final VarintReader varintReader;

  private EbmlProcessor processor;
  private @ElementState int elementState;
  private int elementId;
  private long elementContentSize;

  public DefaultEbmlReader() {
    scratch = new byte[8];
    masterElementsStack = new ArrayDeque<>();
    varintReader = new VarintReader();
  }

  @Override
  public void init(EbmlProcessor processor) {
    this.processor = processor;
  }

  @Override
  public void reset() {
    elementState = ELEMENT_STATE_READ_ID;
    masterElementsStack.clear();
    varintReader.reset();
  }

  @Override
  public boolean read(ExtractorInput input) throws IOException, InterruptedException {
    Assertions.checkNotNull(processor);
    while (true) {
      if (!masterElementsStack.isEmpty()
          && input.getPosition() >= masterElementsStack.peek().elementEndPosition) {
        processor.endMasterElement(masterElementsStack.pop().elementId);
        return true;
      }

      if (elementState == ELEMENT_STATE_READ_ID) {
        long result = varintReader.readUnsignedVarint(input, true, false, MAX_ID_BYTES);
        if (result == C.RESULT_MAX_LENGTH_EXCEEDED) {
          result = maybeResyncToNextLevel1Element(input);
        }
        if (result == C.RESULT_END_OF_INPUT) {
          return false;
        }
        // Element IDs are at most 4 bytes, so we can cast to integers.
        elementId = (int) result;
        elementState = ELEMENT_STATE_READ_CONTENT_SIZE;
      }

      if (elementState == ELEMENT_STATE_READ_CONTENT_SIZE) {
        elementContentSize = varintReader.readUnsignedVarint(input, false, true, MAX_LENGTH_BYTES);
        elementState = ELEMENT_STATE_READ_CONTENT;
      }

      @EbmlProcessor.ElementType int type = processor.getElementType(elementId);
      switch (type) {
        case EbmlProcessor.ELEMENT_TYPE_MASTER:
          long elementContentPosition = input.getPosition();
          long elementEndPosition = elementContentPosition + elementContentSize;
          masterElementsStack.push(new MasterElement(elementId, elementEndPosition));
          processor.startMasterElement(elementId, elementContentPosition, elementContentSize);
          elementState = ELEMENT_STATE_READ_ID;
          return true;
        case EbmlProcessor.ELEMENT_TYPE_UNSIGNED_INT:
          if (elementContentSize > MAX_INTEGER_ELEMENT_SIZE_BYTES) {
            throw new ParserException("Invalid integer size: " + elementContentSize);
          }
          processor.integerElement(elementId, readInteger(input, (int) elementContentSize));
          elementState = ELEMENT_STATE_READ_ID;
          return true;
        case EbmlProcessor.ELEMENT_TYPE_FLOAT:
          if (elementContentSize != VALID_FLOAT32_ELEMENT_SIZE_BYTES
              && elementContentSize != VALID_FLOAT64_ELEMENT_SIZE_BYTES) {
            throw new ParserException("Invalid float size: " + elementContentSize);
          }
          processor.floatElement(elementId, readFloat(input, (int) elementContentSize));
          elementState = ELEMENT_STATE_READ_ID;
          return true;
        case EbmlProcessor.ELEMENT_TYPE_STRING:
          if (elementContentSize > Integer.MAX_VALUE) {
            throw new ParserException("String element size: " + elementContentSize);
          }
          processor.stringElement(elementId, readString(input, (int) elementContentSize));
          elementState = ELEMENT_STATE_READ_ID;
          return true;
        case EbmlProcessor.ELEMENT_TYPE_BINARY:
          processor.binaryElement(elementId, (int) elementContentSize, input);
          elementState = ELEMENT_STATE_READ_ID;
          return true;
        case EbmlProcessor.ELEMENT_TYPE_UNKNOWN:
          input.skipFully((int) elementContentSize);
          elementState = ELEMENT_STATE_READ_ID;
          break;
        default:
          throw new ParserException("Invalid element type " + type);
      }
    }
  }

  /**
   * Does a byte by byte search to try and find the next level 1 element. This method is called if
   * some invalid data is encountered in the parser.
   *
   * @param input The {@link ExtractorInput} from which data has to be read.
   * @return id of the next level 1 element that has been found.
   * @throws EOFException If the end of input was encountered when searching for the next level 1
   *     element.
   * @throws IOException If an error occurs reading from the input.
   * @throws InterruptedException If the thread is interrupted.
   */
  private long maybeResyncToNextLevel1Element(ExtractorInput input) throws IOException,
      InterruptedException {
    input.resetPeekPosition();
    while (true) {
      input.peekFully(scratch, 0, MAX_ID_BYTES);
      int varintLength = VarintReader.parseUnsignedVarintLength(scratch[0]);
      if (varintLength != C.LENGTH_UNSET && varintLength <= MAX_ID_BYTES) {
        int potentialId = (int) VarintReader.assembleVarint(scratch, varintLength, false);
        if (processor.isLevel1Element(potentialId)) {
          input.skipFully(varintLength);
          return potentialId;
        }
      }
      input.skipFully(1);
    }
  }

  /**
   * Reads and returns an integer of length {@code byteLength} from the {@link ExtractorInput}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @param byteLength The length of the integer being read.
   * @return The read integer value.
   * @throws IOException If an error occurs reading from the input.
   * @throws InterruptedException If the thread is interrupted.
   */
  private long readInteger(ExtractorInput input, int byteLength)
      throws IOException, InterruptedException {
    input.readFully(scratch, 0, byteLength);
    long value = 0;
    for (int i = 0; i < byteLength; i++) {
      value = (value << 8) | (scratch[i] & 0xFF);
    }
    return value;
  }

  /**
   * Reads and returns a float of length {@code byteLength} from the {@link ExtractorInput}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @param byteLength The length of the float being read.
   * @return The read float value.
   * @throws IOException If an error occurs reading from the input.
   * @throws InterruptedException If the thread is interrupted.
   */
  private double readFloat(ExtractorInput input, int byteLength)
      throws IOException, InterruptedException {
    long integerValue = readInteger(input, byteLength);
    double floatValue;
    if (byteLength == VALID_FLOAT32_ELEMENT_SIZE_BYTES) {
      floatValue = Float.intBitsToFloat((int) integerValue);
    } else {
      floatValue = Double.longBitsToDouble(integerValue);
    }
    return floatValue;
  }

  /**
   * Reads a string of length {@code byteLength} from the {@link ExtractorInput}. Zero padding is
   * removed, so the returned string may be shorter than {@code byteLength}.
   *
   * @param input The {@link ExtractorInput} from which to read.
   * @param byteLength The length of the string being read, including zero padding.
   * @return The read string value.
   * @throws IOException If an error occurs reading from the input.
   * @throws InterruptedException If the thread is interrupted.
   */
  private String readString(ExtractorInput input, int byteLength)
      throws IOException, InterruptedException {
    if (byteLength == 0) {
      return "";
    }
    byte[] stringBytes = new byte[byteLength];
    input.readFully(stringBytes, 0, byteLength);
    // Remove zero padding.
    int trimmedLength = byteLength;
    while (trimmedLength > 0 && stringBytes[trimmedLength - 1] == 0) {
      trimmedLength--;
    }
    return new String(stringBytes, 0, trimmedLength);
  }

  /**
   * Used in {@link #masterElementsStack} to track when the current master element ends, so that
   * {@link EbmlProcessor#endMasterElement(int)} can be called.
   */
  private static final class MasterElement {

    private final int elementId;
    private final long elementEndPosition;

    private MasterElement(int elementId, long elementEndPosition) {
      this.elementId = elementId;
      this.elementEndPosition = elementEndPosition;
    }

  }

}

redpajama_set_name: RedPajamaGithub


text:
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';

import { AudioPlayback, NativePlayback, PlaybackMetadata } from './playback';
import { AudioValidation, NativeValidation, ValidationMetadata } from './validation';

@Injectable()
export class PlayerService {

  private playback: AudioPlayback;

  play(fileOrUrl: File | string): Observable<PlaybackMetadata> {
    this.stop();

    return this.nativePlayback(fileOrUrl).play();
  }

  seek(percent: number) {
    if (this.playback) {
      this.playback.seek(percent);
    }
  }

  stop() {
    if (this.playback) {
      this.playback.stop();
    }
  }

  checkFile(file: File): Observable<ValidationMetadata> {
    return this.nativeValidation(file).validate();
  }

  private nativePlayback(fileOrUrl: File | string): AudioPlayback {
    return this.playback = new NativePlayback(fileOrUrl);
  }

  private nativeValidation(fileOrUrl: File | string): AudioValidation {
    return new NativeValidation(fileOrUrl);
  }

}


text:
package com.soomla.cocos2dx.common;

import android.opengl.GLSurfaceView;

import com.soomla.BusProvider;
import com.soomla.events.CustomEvent;
import com.soomla.events.RewardGivenEvent;
import com.soomla.events.RewardTakenEvent;
import com.squareup.otto.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This bridge is used to populate events from the store to cocos2dx (through JNI).
 */
public class CoreEventHandlerBridge {

    private GLSurfaceView mGLThread;

    public CoreEventHandlerBridge() {
        BusProvider.getInstance().register(this);
    }

    @Subscribe
    public void onRewardGivenEvent(final RewardGivenEvent rewardGivenEvent) {
        mGLThread.queueEvent(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject parameters = new JSONObject();
                    parameters.put("method", CommonConsts.EVENT_REWARD_GIVEN);
                    parameters.put("reward", rewardGivenEvent.RewardId);
                    NdkGlue.getInstance().sendMessageWithParameters(parameters);
                } catch (JSONException e) {
                    throw new IllegalStateException(e);
                }
            }
        });
    }

    @Subscribe
    public void onRewardGivenEvent(final RewardTakenEvent rewardTakenEvent) {
        mGLThread.queueEvent(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject parameters = new JSONObject();
                    parameters.put("method", CommonConsts.EVENT_REWARD_TAKEN);
                    parameters.put("reward", rewardTakenEvent.RewardId);
                    NdkGlue.getInstance().sendMessageWithParameters(parameters);
                } catch (JSONException e) {
                    throw new IllegalStateException(e);
                }
            }
        });
    }

    @Subscribe
    public void onCustomEvent(final CustomEvent customEvent) {
        mGLThread.queueEvent(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject parameters = new JSONObject();
                    parameters.put("method", CommonConsts.EVENT_CUSTOM);
                    parameters.put("name", customEvent.getName());
                    parameters.put("extra", new JSONObject(customEvent.getExtra()));
                    NdkGlue.getInstance().sendMessageWithParameters(parameters);
                } catch (JSONException e) {
                    throw new IllegalStateException(e);
                }
            }
        });
    }

    public void setGlSurfaceView(GLSurfaceView glSurfaceView) {
        this.mGLThread = glSurfaceView;
    }
}


text:
'use strict';

angular.module(ApplicationConfiguration.applicationModuleName).factory('Utils', [factory]);

function factory() {
    return {
        parsePagingParams: parsePagingParams
    };

    function parsePagingParams(params) {
        var param = params.url();
        var orderBy = params.sorting() ? params.orderBy() : "";
        var filter = params.filter();
        var filters = "";
        var r = {
            page: param.page,
            page_size: param.count,
            order_by: orderBy
        };
        if (filter) {
            r['filter'] = {};
            Object.keys(filter).forEach(function(item) {
                if (filter[item].length != 0) {
                    r['filter'][item] = filter[item];
                }
            });
        }
        return r;
    }
}


text:
package com.gjy.nwpufindseats;

import com.gjy.nwpufindseats.R;
import com.gjy.nwpufindseats.Fragment.Fragment_webHtml;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class Activity_lost extends SlidingFragmentActivity implements OnClickListener{
		private ImageButton ivTitleBtnLeft;
		public static TextView commonTitle;
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setBehindContentView(R.layout.main_left_layout);	//由于是对SlidingFragmentActivity的继承,必须由此代码
			getSlidingMenu().setBehindWidth(0);//滑动为0,即禁止左滑
			// 支持进度条显示
			getWindow().requestFeature(Window.FEATURE_PROGRESS);
			setContentView(R.layout.activity_main);

			selectItem();
			setContentView(R.layout.activity_lost);
			commonTitle = (TextView) findViewById(R.id.ivTitleName);
			commonTitle.setText("失物招领");
			ivTitleBtnLeft = (ImageButton)this.findViewById(R.id.ivTitleBtnLeft);
			ivTitleBtnLeft.setOnClickListener(this);
		}
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.ivTitleBtnLeft:
					onBackPressed();
					break;
				default:
				break;
			}
		}

		private void selectItem() {
			// update the main content by replacing fragments
			Fragment fragment = new Fragment_webHtml();
			getSupportFragmentManager()
	         .beginTransaction()
	         .replace(R.id.frame, fragment)
	         .commit();
		}

}


text:
neo4j-pubnub
==============

Neo4j Integration with PubNub Data Stream

#INTRODUCTION
This application demonstrates the use of Neo4j database with PubNub data stream. With the help of PubNub data stream SDKs we can stream the data fetched from Neo4j to remote users.

This application builds a simple stockticker for fetching and dislaying major stock indices from the world. The application has two components.The server simulates a stock market feed and implements the PubNub broadcast server. The client runs as a front end web application for displaying the price counters.

#PRECONDITION

1. You will need python2 installed on the server computer with pymongo and PubNub's Python SDK installed. Refer to the official docs of PyMongo and PubNub SDKs for installation instructions
2. You will need a PubNub sandbox account to publish and subscribe your data. You need to add your publish and subscribe key on the server and client program. Search for the string "YOUR PUBNUB KEYS" in the code to locate the line where you need to add the keys". For more details refer the PubNub SDK documention for Python and Javascript.

#SETUP

##Server Setup
Open a console or terminal on the server and run the server program as follows ( Assuming that you are in the server directory)
> python stocktickerneo.py 80 8080


text:
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;

namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
    internal class ReferenceKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
    {
        public ReferenceKeywordRecommender()
            : base(SyntaxKind.ReferenceKeyword, isValidInPreprocessorContext: true)
        {
        }

        protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
        {
            var syntaxTree = context.SyntaxTree;
            return
                context.IsPreProcessorKeywordContext &&
                syntaxTree.IsInteractiveOrScript() &&
                syntaxTree.IsBeforeFirstToken(position, cancellationToken);
        }
    }
}


text:
#import "ABI11_0_0AIRMapMarker.h"
#import "ABI11_0_0AIRMapCallout.h"

#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>

#import "ABI11_0_0RCTConvert+MapKit.h"
#import "ABI11_0_0RCTComponent.h"
#import "ABI11_0_0AIRMap.h"
#import "ABI11_0_0SMCalloutView.h"

@class ABI11_0_0RCTBridge;

@interface ABI11_0_0AIRMapMarker : MKAnnotationView <MKAnnotation>

@property (nonatomic, strong) ABI11_0_0AIRMapCallout *calloutView;
@property (nonatomic, weak) ABI11_0_0AIRMap *map;
@property (nonatomic, weak) ABI11_0_0RCTBridge *bridge;

@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, copy) NSString *imageSrc;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) UIColor *pinColor;
@property (nonatomic, assign) NSInteger zIndex;

@property (nonatomic, copy) ABI11_0_0RCTBubblingEventBlock onPress;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onSelect;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onDeselect;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onCalloutPress;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onDragStart;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onDrag;
@property (nonatomic, copy) ABI11_0_0RCTDirectEventBlock onDragEnd;

- (MKAnnotationView *)getAnnotationView;
- (void)fillCalloutView:(ABI11_0_0SMCalloutView *)calloutView;
- (BOOL)shouldShowCalloutView;
- (void)showCalloutView;
- (void)hideCalloutView;

@end

@interface ABI11_0_0AIREmptyCalloutBackgroundView : ABI11_0_0SMCalloutBackgroundView
@end


text:
import React from 'react';
import {render} from '../../ReactTVEntry';

describe('[render] Style Map tests', () => {
  it('should transform style object into inline style', () => {
    const style = {
      div: {
        fontSize: 19,
        fontFamily: ['Helvetica', 'arial'],
        backgroundColor: 'blue',
        border: '1px solid yellow',
      },
      paragraph: {
        display: 'flex',
        opacity: 0.5,
        zIndex: 99,
      },
      empty: {},
    };

    const inlineStyle = {
      div:
        'font-size: 19px; font-family: Helvetica,arial; background-color: blue; border: 1px solid yellow;',
      paragraph: 'display: flex; opacity: 0.5; z-index: 99;',
    };

    const root = document.createElement('div');
    const ReactElement = (

cowboy bebop

    );

    const expectedElement = document.createElement('div');
    expectedElement.setAttribute('style', inlineStyle.div);
    const emptyElement = expectedElement.appendChild(
      document.createElement('div')
    );
    const paragraphElement = emptyElement.appendChild(
      document.createElement('p')
    );
    paragraphElement.setAttribute('style', inlineStyle.paragraph);

    paragraphElement.textContent = 'cowboy bebop';

    expect(render(ReactElement, root)).toEqual(expectedElement);
  });
});


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global

namespace Sodium.Interop
{
  internal static class SodiumLibrary
  {
    private const string Name = SodiumRuntimeConfig.LibraryName;

    static SodiumLibrary()
    {
      RuntimeShim.PinDllImportLibrary(Name);
      sodium_init();
    }

    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern void sodium_init();

    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern void randombytes_buf(byte[] buffer, int size);

    //randombytes_uniform
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int randombytes_uniform(int upperBound);

    //sodium_increment
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern void sodium_increment(byte[] buffer, long length);

    //sodium_compare
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sodium_compare(byte[] a, byte[] b, long length);

    //sodium_version_string
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr sodium_version_string();

    //crypto_hash
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_hash(byte[] buffer, byte[] message, long length);

    //crypto_hash_sha512
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_hash_sha512(byte[] buffer, byte[] message, long length);

    //crypto_hash_sha256
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_hash_sha256(byte[] buffer, byte[] message, long length);

    //crypto_generichash
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_generichash(byte[] buffer, int bufferLength, byte[] message, long messageLength, byte[] key, int keyLength);

    //crypto_generichash_blake2b_salt_personal
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_generichash_blake2b_salt_personal(byte[] buffer, int bufferLength, byte[] message, long messageLength, byte[] key, int keyLength, byte[] salt, byte[] personal);

    //crypto_onetimeauth
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_onetimeauth(byte[] buffer, byte[] message, long messageLength, byte[] key);

    //crypto_onetimeauth_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_onetimeauth_verify(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_pwhash_str
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash_str(byte[] buffer, byte[] password, long passwordLen, long opsLimit, int memLimit);

    //crypto_pwhash_str_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash_str_verify(byte[] buffer, byte[] password, long passLength);

    //crypto_pwhash
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash(byte[] buffer, long bufferLen, byte[] password, long passwordLen, byte[] salt, long opsLimit, int memLimit, int alg);

    //crypto_pwhash_scryptsalsa208sha256_str
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash_scryptsalsa208sha256_str(byte[] buffer, byte[] password, long passwordLen, long opsLimit, int memLimit);

    //crypto_pwhash_scryptsalsa208sha256
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash_scryptsalsa208sha256(byte[] buffer, long bufferLen, byte[] password, long passwordLen, byte[] salt, long opsLimit, int memLimit);

    //crypto_pwhash_scryptsalsa208sha256_str_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_pwhash_scryptsalsa208sha256_str_verify(byte[] buffer, byte[] password, long passLength);

    //crypto_sign_keypair
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_keypair(byte[] publicKey, byte[] secretKey);

    //crypto_sign_seed_keypair
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_seed_keypair(byte[] publicKey, byte[] secretKey, byte[] seed);

    //crypto_sign
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign(byte[] buffer, ref long bufferLength, byte[] message, long messageLength, byte[] key);

    //crypto_sign_open
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_open(byte[] buffer, ref long bufferLength, byte[] signedMessage, long signedMessageLength, byte[] key);

    //crypto_sign_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_detached(byte[] signature, ref long signatureLength, byte[] message, long messageLength, byte[] key);

    //crypto_sign_verify_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_verify_detached(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_sign_ed25519_sk_to_seed
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_ed25519_sk_to_seed(byte[] seed, byte[] secretKey);

    //crypto_sign_ed25519_sk_to_pk
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_ed25519_sk_to_pk(byte[] publicKey, byte[] secretKey);

    //crypto_sign_ed25519_pk_to_curve25519
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_ed25519_pk_to_curve25519(byte[] curve25519Pk, byte[] ed25519Pk);

    //crypto_sign_ed25519_sk_to_curve25519
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_sign_ed25519_sk_to_curve25519(byte[] curve25519Sk, byte[] ed25519Sk);

    //crypto_box_keypair
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_keypair(byte[] publicKey, byte[] secretKey);

    //crypto_box_easy
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_easy(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] publicKey, byte[] secretKey);

    //crypto_box_open_easy
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_open_easy(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] nonce, byte[] publicKey, byte[] secretKey);

    //crypto_box_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_detached(byte[] cipher, byte[] mac, byte[] message, long messageLength, byte[] nonce, byte[] pk, byte[] sk);

    //crypto_box_open_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_open_detached(byte[] buffer, byte[] cipherText, byte[] mac, long cipherTextLength, byte[] nonce, byte[] pk, byte[] sk);

    //crypto_scalarmult_bytes
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_scalarmult_bytes();

    //crypto_scalarmult_scalarbytes
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_scalarmult_scalarbytes();

    //crypto_scalarmult_primitive
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern byte crypto_scalarmult_primitive();

    //crypto_scalarmult_base
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_scalarmult_base(byte[] q, byte[] n);

    //crypto_scalarmult
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_scalarmult(byte[] q, byte[] n, byte[] p);

    //crypto_box_seal
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_seal(byte[] buffer, byte[] message, long messageLength, byte[] pk);

    //crypto_box_seal_open
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_box_seal_open(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] pk, byte[] sk);

    //crypto_secretbox_easy
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_secretbox_easy(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);

    //crypto_secretbox_open_easy
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_secretbox_open_easy(byte[] buffer, byte[] cipherText, long cipherTextLength, byte[] nonce, byte[] key);

    //crypto_secretbox_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_secretbox_detached(byte[] cipher, byte[] mac, byte[] message, long messageLength, byte[] nonce, byte[] key);

    //crypto_secretbox_open_detached
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_secretbox_open_detached(byte[] buffer, byte[] cipherText, byte[] mac, long cipherTextLength, byte[] nonce, byte[] key);

    //crypto_auth
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth(byte[] buffer, byte[] message, long messageLength, byte[] key);

    //crypto_auth_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth_verify(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_auth_hmacsha256
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth_hmacsha256(byte[] buffer, byte[] message, long messageLength, byte[] key);

    //crypto_auth_hmacsha256_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth_hmacsha256_verify(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_auth_hmacsha512
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth_hmacsha512(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_auth_hmacsha512_verify
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_auth_hmacsha512_verify(byte[] signature, byte[] message, long messageLength, byte[] key);

    //crypto_shorthash
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_shorthash(byte[] buffer, byte[] message, long messageLength, byte[] key);

    //crypto_stream_xor
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_stream_xor(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);

    //crypto_stream_chacha20_xor
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_stream_chacha20_xor(byte[] buffer, byte[] message, long messageLength, byte[] nonce, byte[] key);

    //sodium_bin2hex
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern IntPtr sodium_bin2hex(byte[] hex, int hexMaxlen, byte[] bin, int binLen);

    //sodium_hex2bin
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int sodium_hex2bin(IntPtr bin, int binMaxlen, string hex, int hexLen, string ignore, out int binLen, string hexEnd);

    //crypto_aead_chacha20poly1305_encrypt
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_aead_chacha20poly1305_encrypt(
      IntPtr cipher, out long cipherLength, byte[] message, long messageLength, byte[] additionalData,
      long additionalDataLength, byte[] nsec, byte[] nonce, byte[] key);

    //crypto_aead_chacha20poly1305_decrypt
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_aead_chacha20poly1305_decrypt(
      IntPtr message, out long messageLength, byte[] nsec, byte[] cipher, long cipherLength, byte[] additionalData,
      long additionalDataLength, byte[] nonce, byte[] key);

    //crypto_aead_aes256gcm_is_available
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_aead_aes256gcm_is_available();

    //crypto_aead_aes256gcm_encrypt
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_aead_aes256gcm_encrypt(
      IntPtr cipher, out long cipherLength, byte[] message, long messageLength, byte[] additionalData,
      long additionalDataLength, byte[] nsec, byte[] nonce, byte[] key);

    //crypto_aead_aes256gcm_decrypt
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_aead_aes256gcm_decrypt(
      IntPtr message, out long messageLength, byte[] nsec, byte[] cipher, long cipherLength, byte[] additionalData,
      long additionalDataLength, byte[] nonce, byte[] key);

    //crypto_generichash_state
    [StructLayout(LayoutKind.Sequential, Size = 384)]
    [SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
    internal struct _HashState
    {
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
      public ulong[] h;

      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
      public ulong[] t;

      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
      public ulong[] f;

      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
      public byte[] buf;

      public uint buflen;

      public byte last_node;
    }

    //crypto_generichash_init
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_generichash_init(IntPtr state, byte[] key, int keySize, int hashSize);

    //crypto_generichash_update
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_generichash_update(IntPtr state, byte[] message, long messageLength);

    //crypto_generichash_final
    [DllImport(Name, CallingConvention = CallingConvention.Cdecl)]
    internal static extern int crypto_generichash_final(IntPtr state, byte[] buffer, int bufferLength);
  }
}


text:
'use strict';

var config = require('meanio').loadConfig(),
    cookie = require('cookie'),
    cookieParser = require('cookie-parser'),
    socketio = require('socket.io');

module.exports = function (http) {
    var io = socketio.listen(http);

    // See http://stackoverflow.com/questions/19106861/socket-io-authorization-nodejs
    io.use(function (socket, next) {
        var data = socket.request;

        if (!data.headers.cookie) {
            return next(new Error('No cookie transmitted for socket'));
        }

        var parsedCookie = cookie.parse(data.headers.cookie);
        var sessionId = parsedCookie[config.sessionName];
        var parsedSessionId = cookieParser.signedCookie(parsedCookie[config.sessionName], config.sessionSecret);

        if (sessionId === parsedSessionId) {
            return next(new Error('Invalid cookie'));
        }

        next();
    });

    return io;
};


text:
/**
 * Form widget which contains fields (section 'fields', by default) and buttons (section 'buttons').
 */
croc.Class.define('croc.cmp.form.Form', {
    extend: croc.cmp.Widget,
    implement: croc.cmp.form.validation.IValidatable,
    include: croc.cmp.form.validation.MStandardValidatable,

    statics: {
        FIELD_ID_PREFIX: 'croc-form-field-'
    },

    events: {
        /**
         * валидация была пройдена, чтобы отменить стандартный сабмит формы, вызовите e.preventDefault()
         * @param {Event} e
         * @param {Object.<string, *>} value
         */
        submit: null,

        /**
         * @param {string} error
         */
        submitServerError: null,

        /**
         * активация формы (первое взаимодействие с одним из полей формы)
         * @param {croc.cmp.form.field.IField} field
         */
        activate: null,

        /**
         * возбуждается после инициализации состояния (_initSate), а также после каждого ресета
         */
        initState: null,

        /**
         * @param {Object} response
         * @param {boolean} staticSubmit
         */
        submitSuccessful: null,

        submitValidationFail: null,

        /**
         * @param {function} prevent
         */
        presubmit: null,

        postsubmit: null
    },

    properties: {
        /**
         * @type {boolean}
         */
        disabled: {
            value: false,
            model: true
        },

        status: {
            value: 'normal',
            check: ['normal', 'sentSuccess', 'sentFailure'],
            __setter: null
        },

        /**
         * Идёт ли отправка данных в данный момент
         * @type {boolean}
         */
        submitting: {
            value: false,
            __setter: null,
            event: true
        },

        /**
         * Предупреждать пользователя о несохранённых изменениях
         * @type {boolean}
         */
        warnUnsavedChanges: {
            value: false,
            option: true
        }
    },

    options: {
        /**
         * Экшен формы либо url, на который будет отправлен запрос
         * @type {string}
         */
        action: {},

        /**
         * Expected type of child widget associated with section name
         * @type {Object.<string, Function|Object|string|Array>}
         */
        checkChild: {
            value: {
                fields: 'croc.cmp.form.field.IField',
                buttons: 'croc.cmp.form.Button'
            }
        },

        /**
         * Значения, которые следует установить полям при их добавлении
         * @type {Object.<string, *>}
         */
        fieldsValues: null,

        /**
         * Предотвратить отправку формы на сервер
         * @type {boolean}
         */
        preventSubmit: false,

        /**
         * Конфигурация добавляемых лэйблов
         * @type {object}
         */
        labels: {
            extend: true,
            value: {
                /**
                 * размер подсказки
                 * @type {number}
                 */
                hintSize: 12,

                /**
                 * размер лэйблов (1-5)
                 * @type {string}
                 */
                size: '1',

                /**
                 * положение лэйблов
                 * @type {string}
                 */
                position: 'top'
            }
        },

        /**
         * Конфигурация для менеджера состояний
         * @type {Object}
         */
        stateManager: null,

        /**
         * Функция получения значений перед отправкой данных на сервер
         * @type {function():Object}
         */
        submitValuesFn: {},

        /**
         * Нужно ли триммить значения всех текстовых полей перед сабмитом
         * @type {boolean}
         */
        trimAllBeforeSubmit: true,

        /**
         * Нужно ли производить валидацию формы
         * @type {boolean}
         */
        validateForm: true,

        /**
         * Опции устанавливающие особенности валидации формы {@see croc.cmp.form.validation.Controller#validationBehavior}
         * @type {Object}
         */
        validationBehavior: null,

        /**
         * Игнорировать определённые поля, предупреждая о несохранённых изменениях
         * @type {Array.<string>}
         */
        warnUnsavedChangesIgnoreFields: null
    },

    construct: function() {
        this.__activateDisposer = new croc.util.Disposer();
        this.__alreadyDisabled = {};

        this.on('initChild', function(widget) {
            if (widget.getSection() === 'fields') {
                var size = this.getVar('fieldSize');
                if (size && croc.Interface.check(widget, 'croc.cmp.form.field.ISizable') &&
                    !_.contains(widget._passedOptions, 'size')) {
                    widget._model.set('size', size);
                }
            }
        }, this);

        this.on('addChild', function(widget) {
            if (widget.getSection() === 'buttons') {
                if (!this.__submitButton && widget.getType() === 'submit') {
                    this.__submitButton = widget;
                }
            }
            else if (widget.getSection() === 'fields') {
                this.__onAddField(widget);
            }
        }, this);

        this.on('removeChild', function(widget) {
            if (this.__submitButton === widget) {
                this.__submitButton = null;
            }
            if (widget.getSection() === 'fields') {
                this.__stateManager.removeItem(widget);
                if (this.__activateDisposer) {
                    this.__activateDisposer.removeObject(widget);
                }
            }
        }, this);

        croc.cmp.form.Form.superclass.construct.apply(this, arguments);
    },

    destruct: function() {
        this.__notifier.dispose();
    },

    members: {
        /**
         * Снимает фокус с выделенного поля формы, а затем возвращает его, для того чтобы зафиксировать изменения
         * этого поля.
         */
        commitChanges: function() {
            if (document.activeElement && document.activeElement.blur &&
                this.getElement().has(document.activeElement).length) {
                document.activeElement.blur();
                document.activeElement.focus();
            }

            this.getElement()
                .find('input[type=text], input[type=textarea], input[type=password]')
                .blur();
        },

        /**
         * @returns {string}
         */
        generateFieldId: function() {
            return this.generateUniqueId(croc.cmp.form.Form.FIELD_ID_PREFIX);
        },

        /**
         * Секция дочерних элементов по-умолчанию
         * @return {String}
         * @protected
         */
        getDefaultItemsSection: function() {
            return 'fields';
        },

        /**
         * Объект уведомлений
         * @return {croc.cmp.form.validation.Notifier}
         */
        getNotifier: function() {
            return this.__notifier;
        },

        /**
         * @returns {croc.cmp.form.StateManager}
         */
        getStateManager: function() {
            return this.__stateManager;
        },

        /**
         * Возвращает первую кнопку типа submit
         * @return {croc.cmp.form.Button}
         */
        getSubmitButton: function() {
            return this.__submitButton;
        },

        /**
         * Менеджер валидации
         * @return {croc.cmp.form.validation.Manager}
         */
        getValidationManager: function() {
            return this.__validationManager;
        },

        /**
         * Получить значения полей формы в виде объекта.
         * Алиас к {@link #getValues} для поддержки интерфейса {@link croc.cmp.form.validation.IValidatable}.
         * @return {Object.<string, *>}
         */
        getValue: function() {
            return this.getValues();
        },

        /**
         * Получить значения полей формы в виде объекта
         * @param {boolean} [complex=false]
         * @param {boolean} [includeEmpty=false]
         * @returns {Object.<string, *>}
         */
        getValues: function(complex, includeEmpty) {
            if (complex || includeEmpty) {
                var values = {};
                this.getItems().forEach(function(item) {
                    if (item.getIdentifier() && (includeEmpty || !item.isEmpty())) {
                        values[item.getIdentifier()] = complex ? item.getValue() : item.getPlainValue();
                    }
                });
                return values;
            }
            return _.assign({}, this.__stateManager.getValues());
        },

        /**
         * Passed element will be hidden on the first form update
         * @param {Element|jQuery} el
         * @param {string} [method='hide'] jquery hide method
         */
        hideElementOnUpdate: function(el, method) {
            this.__stateManager.once('updateStateChanged', function() {
                $(el)[method || 'hide']();
            });
        },

        /**
         * Отключить повторную валидацию поля при потере фокуса
         * @param {croc.cmp.form.field.IField} field
         */
        offFieldRevalidating: function(field) {
            this.__validationController.offFieldRevalidating(field);
        },

        /**
         * Сбросить значения и состояния полей
         */
        reset: function() {
            this.__validationManager.resetValidation();
            this.__stateManager.reset();

            if (!this.__activateDisposer) {
                this.__activateDisposer = new croc.util.Disposer();
                this.getItems().forEach(function(field) {
                    this.__setUpFieldActivation(field);
                }, this);
            }

            this.fireEvent('initState');
        },

        /**
         * Явно назначить кнопку отправки формы
         * @param {croc.cmp.form.Button} button
         */
        setSubmitButton: function(button) {
            this.__submitButton = button;
            if (button.getType() !== 'submit') {
                button.on('click', function() {
                    this.submit();
                }, this);
            }
        },

        /**
         * Passed element will be shown when form state changes and hidden when form state returns back
         * @param {Element|jQuery} el
         * @param {string} [method='toggle'] jquery toggle method
         */
        showElementIfChanged: function(el, method) {
            this.__stateManager.on('updateStateChanged', function(value) {
                $(el)[method || 'toggle'](value);
            });
        },

        /**
         * Отправить форму. Форма отправляется, только если пройдена валидация.
         * @returns {$.Deferred} resolve - если форма отправлена, reject в противном случае
         */
        submit: function() {
            return this.__submitController.submit();
        },

        /**
         * Изменить доступность поля (видимость/disable и необходимость валидации)
         * @param {string|croc.cmp.form.field.IField} field
         * @param {boolean} available
         * @param {boolean|string} [disable=false] делает поле недоступным не скрывая его
         * @param {string|function(jQuery, boolean)} [toggleMethod=null] null|fade|slide - метод анимации появления/скрытия поля
         */
        toggleField: function(field, available, disable, toggleMethod) {
            if (typeof field === 'string') {
                field = /** @type {croc.cmp.form.field.IField} */(this.getItem(field));
            }
            if (disable) {
                field.setDisabled(!available);
            }
            else {
                this.__toggleFieldVisibility(field, available, toggleMethod);

                if (available) {
                    this.__stateManager.addItem(field, {dontReset: field.getMeta().dontReset});
                }
                else {
                    this.__stateManager.removeItem(field);
                }
            }
            if (available) {
                this.__validationManager.addItem(field,
                    {identifier: field.getIdentifier(), suppressValid: field.getMeta().suppressValid});
            }
            else {
                this.__validationManager.removeItem(field);
            }
        },

        /**
         * Произвести валидацию полей формы
         * @returns {$.Deferred}
         */
        validate: function() {
            return this.__validationController.validate();
        },

        /**
         * Значения для отправки на сервер аяксом
         * @returns {Object}
         * @protected
         */
        _getSubmitValues: function() {
            return this.getValues();
        },

        /**
         * Инициализация модели виджета
         * @protected
         */
        _initModel: function() {
            croc.cmp.form.Form.superclass._initModel.apply(this, arguments);

            var options = this._options;
            this.__stateManager = new croc.cmp.form.StateManager(options.stateManager || {});
            this.__validationController = new croc.cmp.form.validation.Controller({
                form: this,
                notifierConf: options.notifier,
                validationBehavior: options.validationBehavior,
                validateForm: options.validateForm,
                fieldsInvalidMessages: options.fieldsInvalidMessages
            });
            this.__validationManager = this.__validationController.getManager();
            this.__notifier = this.__validationController.getNotifier();
            this.__submitController = new croc.cmp.form.internal.SubmitController({
                form: this,
                action: options.action,
                ajaxAction: options.ajaxAction,
                ajaxSubmitDelay: options.ajaxSubmitDelay,
                ajaxSubmitFn: options.ajaxSubmitFn,
                autoAjaxSubmit: options.autoAjaxSubmit,
                errorCodes: options.errorCodes,
                preventSubmit: options.preventSubmit,
                submitFailFunc: this._onSubmitFail.bind(this),
                submitSuccessFunc: this._onSubmitSuccess.bind(this),
                trimAllBeforeSubmit: this.trimAllBeforeSubmit,
                valuesFunc: (options.submitValuesFn || this._getSubmitValues).bind(this)
            });

            this.__submitController.bind(':changeSubmitting', this, '__submitting');
        },

        /**
         * После вызова состояние формы считается начальным
         * @protected
         */
        _initState: function() {
            if (this.__stateInited) {
                return;
            }
            this.__stateInited = true;

            this.__stateManager.saveState();

            //before unload
            if (this.getWarnUnsavedChanges()) {
                this._getDisposer().addListener(croc, 'system.page.beforeUnload', function(preventUnload) {
                    if (!this.getWarnUnsavedChanges() || this.__submitController.isSubmitPerformed()) {
                        return;
                    }

                    this.commitChanges();

                    var ignoreFields;
                    if (this.warnUnsavedChangesIgnoreFields) {
                        ignoreFields = [];
                        this.warnUnsavedChangesIgnoreFields.forEach(function(identifier) {
                            ignoreFields.push(this.getItem(identifier));
                        }, this);
                    }

                    if (this.__stateManager.getStateChanged(ignoreFields) || this.status === 'sentFailure') {
                        preventUnload('На странице есть несохраненные данные.');
                    }
                }, this);
            }

            this.__notifier.setTooltipAutoOpen(true);

            this.fireEvent('initState');
        },

        /**
         * Инициализация виджета после его отрисовки в DOM
         * @return {$.Deferred|undefined}
         * @protected
         */
        _initWidget: function() {
            croc.cmp.form.Form.superclass._initWidget.call(this);

            this.listenProperty('disabled', this.__applyDisabled, this);
            if (!this._partialInitialState) {
                this._initState();
            }
        },

        /**
         * ajax-запрос был выполнен неудачно
         * @protected
         */
        _onSubmitFail: function(response) {},

        /**
         * ajax-запрос был выполнен удачно
         * @param response
         * @param values
         * @protected
         */
        _onSubmitSuccess: function(response, values) {},

        /**
         * @param {croc.cmp.form.field.IField} field
         * @private
         */
        __activateForm: function(field) {
            if (this.__activateDisposer) {
                this.__activateDisposer.disposeAll();
                this.__activateDisposer = null;
                this.fireEvent('activate', field);
            }
        },

        /**
         * @private
         */
        __applyDisabled: function(value) {
            if (value) {
                this.__alreadyDisabled = {};
            }

            this.getItems().concat(this.getItems('buttons')).forEach(function(widget) {
                if (croc.Interface.check(widget, 'croc.cmp.form.field.IDisable') ||
                    croc.Class.check(widget, 'croc.cmp.form.Button')) {
                    if (!value) {
                        if (!this.__alreadyDisabled[widget.getUniqueId()]) {
                            widget.setDisabled(false);
                        }
                    }
                    else if (widget.getDisabled()) {
                        this.__alreadyDisabled[widget.getUniqueId()] = true;
                    }
                    else {
                        widget.setDisabled(true);
                    }
                }
            }, this);
        },

        /**
         * @private
         */
        __onAddField: function(item) {
            var field = /** @type {croc.cmp.form.field.IField} */(item);
            var meta = item.getMeta();

            this.__stateManager.addItem(field, {dontReset: field.getMeta().dontReset});

            //activation
            this.__setUpFieldActivation(field);

            //initial value
            var initialValue = this._options.fieldsValues && this._options.fieldsValues[field.getIdentifier()];
            if (initialValue) {
                var initValue = function() {
                    field.setValue(initialValue);
                    delete this._options.fieldsValues[field.getIdentifier()];
                }.bind(this);
                initValue();

                if (croc.isClient) {
                    //если значения будут перекрыты браузером
                    this._getDisposer().setTimeout(initValue, 100);
                }
            }

            //todo field defaults
            //if (meta.setDefaults) {
            //    (Array.isArray(meta.setDefaults) ? meta.setDefaults : [meta.setDefaults])
            //        .forEach(function(type) {
            //            croc.cmp.form.Form.setFieldDefaults(type, field);
            //        });
            //}
        },

        /**
         * @param {croc.cmp.form.field.IField} field
         * @private
         */
        __setUpFieldActivation: function(field) {
            if (this.__activateDisposer) {
                if (croc.Interface.check(field, 'croc.cmp.form.field.IHtmlControl')) {
                    this.__activateDisposer.addListener(field, 'changeFocused', function(value) {
                        if (value) {
                            this.__activateForm(field);
                        }
                    }, this);
                }
                this.__activateDisposer.addListener(field.getElement(), 'mousedown',
                    this.__activateForm.bind(this, field));
            }
        },

        /**
         * @param {string|croc.cmp.form.field.IField} field
         * @param {boolean} available
         * @param {string|Function} [toggleMethod=null] null|fade|slide - метод анимации появления/скрытия поля
         * @private
         */
        __toggleFieldVisibility: function(field, available, toggleMethod) {
            var el = field.getElement().closest(this.getSubElementSelector('fieldWrapper'));
            if (!el.length) {
                el = field.getElement();
            }

            if (typeof toggleMethod === 'function') {
                toggleMethod(el, available);
            }
            else {
                if (!toggleMethod) {
                    el.toggle(available);
                }
                else {
                    var method = available ?
                        {fade: 'fadeIn', slide: 'slideDown'}[toggleMethod] :
                        {fade: 'fadeOut', slide: 'slideUp'}[toggleMethod];
                    el[method]();
                }
            }
        }
    }
});


text:
package ru.training.addressbook.appmanager;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.BrowserType;

import java.util.concurrent.TimeUnit;

/**
 * Created by ws03 on 7/20/2017.
 */
public class ApplicationManager {

    WebDriver wd;

    private SessionHelper sessionHelper;
    private NavigationHelper navigationHelper;
    private GroupHelper groupHelper; //declaration on the class level
    private ContactHelper contactHelper;
    private String browser;

    public ApplicationManager(String browser) {
        this.browser = browser;
    }

    public void init() {

        if (browser.equals(BrowserType.FIREFOX)){
            wd = new FirefoxDriver(new FirefoxOptions().setLegacy(true).setBinary("C:/Program Files/Mozilla Firefox/firefox.exe"));
        } else if (browser.equals(BrowserType.CHROME)){
            wd = new ChromeDriver();
        } else if (browser.equals(BrowserType.IE)){
            wd = new InternetExplorerDriver();
        }

        wd.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
        wd.get("http://localhost:8080/addressbook/group.php");
        groupHelper = new GroupHelper(wd); // new object initialization for using in Helper
        navigationHelper = new NavigationHelper(wd); //new obj init for using in Helper
        sessionHelper = new SessionHelper(wd); //new obj init for using in Helper
        contactHelper = new ContactHelper(wd); //new obj init for using in Helper
        sessionHelper.login("admin", "secret");
    }

    public void stop() {
        wd.quit();
    }

    public GroupHelper getGroupHelper() {
        return groupHelper;
    }

    public NavigationHelper getNavigationHelper() {
        return navigationHelper;
    }

    public ContactHelper getContactHelper() {
        return contactHelper;
    }

}


text:
package org.apache.shardingsphere.traffic.rule.builder;

import org.apache.shardingsphere.infra.rule.builder.global.DefaultGlobalRuleConfigurationBuilder;
import org.apache.shardingsphere.traffic.api.config.TrafficRuleConfiguration;
import org.apache.shardingsphere.traffic.constant.TrafficOrder;

/**
 * Default traffic rule configuration builder.
 */
public final class DefaultTrafficRuleConfigurationBuilder implements DefaultGlobalRuleConfigurationBuilder<TrafficRuleConfiguration, TrafficRuleBuilder> {

    @Override
    public TrafficRuleConfiguration build() {
        return new TrafficRuleConfiguration();
    }

    @Override
    public int getOrder() {
        return TrafficOrder.ORDER;
    }

    @Override
    public Class<TrafficRuleBuilder> getTypeClass() {
        return TrafficRuleBuilder.class;
    }
}


text:
package com.vaadin.tests.push;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;

import com.vaadin.testbench.parallel.TestCategory;
import com.vaadin.tests.tb3.MultiBrowserTest;

@TestCategory("push")
public class PushFromInitTest extends MultiBrowserTest {
    @Test
    public void testPushFromInit() {
        openTestURL();

        waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                return ("3. " + PushFromInit.LOG_AFTER_INIT)
                        .equals(getLogRow(0));
            }
        });

    }
}


text:
<?php

/*
 * This file is part of the Symcloud Distributed-Storage.
 *
 * (c) Symcloud and Johannes Wachter
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symcloud\Component\Session;

use Symcloud\Component\FileStorage\ChunkFileManagerInterface;
use Symcloud\Component\MetadataStorage\Commit\CommitManagerInterface;
use Symcloud\Component\MetadataStorage\Reference\ReferenceManagerInterface;
use Symcloud\Component\MetadataStorage\Tree\TreeManagerInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class Repository implements RepositoryInterface
{
    /**
     * @var ChunkFileManagerInterface
     */
    private $chunkFileManager;

    /**
     * @var ReferenceManagerInterface
     */
    private $referenceManager;

    /**
     * @var TreeManagerInterface
     */
    private $treeManager;

    /**
     * @var CommitManagerInterface
     */
    private $commitManager;

    /**
     * Repository constructor.
     *
     * @param ChunkFileManagerInterface $chunkFileManager
     * @param ReferenceManagerInterface $referenceManager
     * @param TreeManagerInterface $treeManager
     * @param CommitManagerInterface $commitManager
     */
    public function __construct(
        ChunkFileManagerInterface $chunkFileManager,
        ReferenceManagerInterface $referenceManager,
        TreeManagerInterface $treeManager,
        CommitManagerInterface $commitManager
    ) {
        $this->chunkFileManager = $chunkFileManager;
        $this->referenceManager = $referenceManager;
        $this->treeManager = $treeManager;
        $this->commitManager = $commitManager;
    }

    /**
     * {@inheritdoc}
     */
    public function loginByName(UserInterface $user, $name)
    {
        $hash = $this->referenceManager->createHash($user, $name);

        return new Session(
            $this->chunkFileManager,
            $this->referenceManager,
            $this->treeManager,
            $this->commitManager,
            $user,
            $name,
            $hash
        );
    }

    /**
     * {@inheritdoc}
     */
    public function loginByHash(UserInterface $user, $hash)
    {
        return new Session(
            $this->chunkFileManager,
            $this->referenceManager,
            $this->treeManager,
            $this->commitManager,
            $user,
            null,
            $hash
        );
    }
}


text:
package org.infinispan.persistence.cassandra.configuration;

import org.infinispan.commons.configuration.io.ConfigurationWriter;
import org.infinispan.commons.util.Version;
import org.infinispan.configuration.serializing.AbstractStoreSerializer;
import org.infinispan.configuration.serializing.ConfigurationSerializer;

public class CassandraStoreConfigurationSerializer extends AbstractStoreSerializer implements ConfigurationSerializer<CassandraStoreConfiguration> {
   @Override
   public void serialize(ConfigurationWriter writer, CassandraStoreConfiguration configuration) {
      writer.writeStartElement(Element.CASSANDRA_STORE);
      writer.writeDefaultNamespace(CassandraStoreConfigurationParser.NAMESPACE + Version.getMajorMinor());
      configuration.attributes().write(writer);
      writeCommonStoreSubAttributes(writer, configuration);
      writeCommonStoreElements(writer, configuration);
      writer.writeEndElement();
   }
}


text:
"""initial migration

Revision ID: 7efdc169f59e
Revises: e53f1df2fad6
Create Date: 2016-11-20 22:46:54.224769

"""

# revision identifiers, used by Alembic.
revision = '7efdc169f59e'
down_revision = 'e53f1df2fad6'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    pass
    ### end Alembic commands ###


text:
def separate_comma(number)
    if number.to_s.size < 4
        return number.to_s
    else
        digits_array = number.to_s.split("").reverse
        new_array = digits_array.each_slice(3).to_a
        new_array.each do |slice|
            slice.insert(-1, ",")
        end
        number_string = new_array.flatten.join
        number_string.chop.reverse
    end
end

# 2. Refactored Solution

=begin
def separate_comma(number)
	if number.to_s.size < 4
		return number.to_s
	else
		digits_array = number.to_s.split("").reverse.each_slice(3).to_a
		digits_array.each do |slice|
			slice.insert(-1, ",")
		end
		digits_array.flatten.join.chop.reverse
	end
end
=end

# 3. Reflection
=begin

What was your process for breaking the problem down? What different approaches did you consider?
I stepped away from the computer and wrote out the problem with pen and paper in order to break it down.
I knew that I would have to reverse the digits in order to figure out where to place the commas so my first
goal was to determine how to do that. Next, I had to figure out what data type I would be working with and think
about what methods I knew how to do with that data type.

Was your pseudocode effective in helping you build a successful initial solution?
Yes, as it became apparent to me as I was writing the pseudocode what data structures I would be working with. The most
difficult part was figuring out when to remove the comma that was appearing before the first number in the final string without
removing any digits instead.

What new Ruby method(s) did you use when refactoring your solution? Describe your experience of using the Ruby documentation to implement it/them (any difficulties, etc.). Did it/they significantly change the way your code works? If so, how?
In first doing some research on all the ways of slicing up an array I discovered the #each_slice enumerable that basically
made this problem solvable for me. When I was refactoring I found that I could chain a lot of my methods together
in order to avoid having to use a bunch of new variables.

How did you initially iterate through the data structure?
I iterated through the data structure with a .each on every sub-array.

Do you feel your refactored solution is more readable than your initial solution? Why?
I feel like my refactored solution is more readable because I use fewer variables and fewer lines of code
and I was able to chain a lot of methods together.

=end


text:
package com.dystu.toolbar.utils;

import android.content.Context;

/**
 * Created by Administrator on 2015/5/26.
 */
public class Util {
    public static float dpToPixel(Context context, float dp) {
        float density = context.getResources().getDisplayMetrics().density;
        int pixelValue = (int) (dp * density + 0.5f);
        return pixelValue;
    }

}


text:
package encoders

import (
	"os"
	"path"

	"code.cloudfoundry.org/lager"
	"github.com/snickers/hls/segmenter"
	"github.com/snickers/snickers/db"
	"github.com/snickers/snickers/types"
)

// HLSEncode function is responsible for encoding adaptive bitrate outputs
func HLSEncode(logger lager.Logger, dbInstance db.Storage, jobID string) error {
	log := logger.Session("hls-encode")
	log.Info("started", lager.Data{"job": jobID})
	defer log.Info("finished")

	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		return err
	}

	job.Progress = "0%"
	job.Status = types.JobEncoding
	dbInstance.UpdateJob(job.ID, job)

	err = encodeInH264(logger, dbInstance, jobID)
	if err != nil {
		return err
	}
	hlsConfig := buildHLSConfig(job)
	err = segmenter.Segment(hlsConfig)
	if err != nil {
		return err
	}
	job.Progress = "100%"
	return nil
}

func encodeInH264(logger lager.Logger, dbInstance db.Storage, jobID string) error {
	h264Filename := path.Join(os.TempDir(), jobID+".mp4")
	os.Create(h264Filename)
	defer os.Remove(h264Filename)

	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		return err
	}

	oldLocalDestination := job.LocalDestination
	job.LocalDestination = h264Filename
	_, err = dbInstance.UpdateJob(jobID, job)
	if err != nil {
		return err
	}

	err = FFMPEGEncode(logger, dbInstance, jobID)
	if err != nil {
		return err
	}

	job.LocalDestination = oldLocalDestination
	job.LocalSource = h264Filename
	_, err = dbInstance.UpdateJob(jobID, job)
	if err != nil {
		return err
	}
	return nil
}

func buildHLSConfig(job types.Job) segmenter.HLSConfig {
	return segmenter.HLSConfig{
		SourceFile:      job.LocalSource,
		FileBase:        job.LocalDestination,
		SegmentDuration: 10,
	}
}


text:
\begin{figure}[H]
\newcommand{\wmgd}{1\columnwidth}
\newcommand{\hmgd}{3.0cm}
\newcommand{\mdrd}{figures/format}
\newcommand{\mbm}{\hspace{-0.3cm}}
\begin{tabular}{c}
\mbm \includegraphics[width=\wmgd,height=\hmgd]{\mdrd/format_all} \\ = \\

\mbm \includegraphics[width=\wmgd,height=\hmgd]{\mdrd/format_resid}
\end{tabular}
\end{figure}


text: A web-based game framework.