text:
package com.genymobile.gnirehtet;

import android.net.VpnService;

import java.io.IOException;

/**
 * Provide a valid {@link RelayTunnel}, creating a new one if necessary.
 */
public class RelayTunnelProvider {

    private static final int DELAY_BETWEEN_ATTEMPTS_MS = 5000;

    private final VpnService vpnService;
    private RelayTunnel tunnel;
    private boolean first = true;
    private long lastFailureTimestamp;
    private RelayTunnelListener listener;

    public RelayTunnelProvider(VpnService vpnService) {
        this.vpnService = vpnService;
    }

    public synchronized RelayTunnel getCurrentTunnel() throws IOException, InterruptedException {
        if (tunnel != null) {
            return tunnel;
        }

        waitUntilNextAttemptSlot();

        // the tunnel variable may have changed during the waiting
        if (tunnel == null) {
            openTunnel();
        }
        return tunnel;
    }

    private void openTunnel() throws IOException {
        // the first connection must either notify "connected" or "disconnected"
        boolean notifyDisconnectedOnError = first;
        first = false;
        openTunnel(notifyDisconnectedOnError);
    }

    private void openTunnel(boolean notifyDisconnectedOnError) throws IOException {
        try {
            tunnel = RelayTunnel.open(vpnService);
            notifyConnected();
        } catch (IOException e) {
            touchFailure();
            if (notifyDisconnectedOnError) {
                notifyDisconnected();
            }
            throw e;
        }
    }

    public synchronized void invalidateTunnel() {
        if (tunnel != null) {
            touchFailure();
            tunnel.close();
            tunnel = null;
            notifyDisconnected();
        }
    }

    /**
     * Call {@link #invalidateTunnel()} only if {@code tunnelToInvalidate} is the current tunnel (or
     * is {@code null}).
     *
     * @param tunnelToInvalidate the tunnel to invalidate
     */
    public synchronized void invalidateTunnel(Tunnel tunnelToInvalidate) {
        if (tunnel == tunnelToInvalidate || tunnelToInvalidate == null) {
            invalidateTunnel();
        }
    }

    private void touchFailure() {
        lastFailureTimestamp = System.currentTimeMillis();
    }

    private void waitUntilNextAttemptSlot() throws InterruptedException {
        if (first) {
            // do not wait on first attempt
            return;
        }
        long delay = lastFailureTimestamp + DELAY_BETWEEN_ATTEMPTS_MS - System.currentTimeMillis();
        while (delay > 0) {
            wait(delay);
            delay = lastFailureTimestamp + DELAY_BETWEEN_ATTEMPTS_MS - System.currentTimeMillis();
        }
    }

    public void setListener(RelayTunnelListener listener) {
        this.listener = listener;
    }

    private void notifyConnected() {
        if (listener != null) {
            listener.notifyRelayTunnelConnected();
        }
    }

    private void notifyDisconnected() {
        if (listener != null) {
            listener.notifyRelayTunnelDisconnected();
        }
    }
}


text:
@interface YYEssenceViewController ()<UIScrollViewDelegate>

@property (nonatomic, weak) YYTitleButton *selectedTitleButton;

@property (nonatomic, weak) UIView *titleIndicatorView;

@property (nonatomic, weak) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray *titleButtons;

@end

@implementation YYEssenceViewController

- (NSMutableArray *)titleButtons
{
    if (!_titleButtons) {
        _titleButtons = [NSMutableArray array];
    }
    return _titleButtons;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setUpChildVcs];
    [self setUpNav];
    [self setUpScrollView];
    [self setUpTitlesView];
    [self addChildVcView];

}

- (void)setUpChildVcs
{
    YYAllViewController *all = [[YYAllViewController alloc] init];
    all.title = @"全部";
    [self addChildViewController:all];

    YYVideoViewController *video = [[YYVideoViewController alloc] init];
    video.title = @"视频";
    [self addChildViewController:video];

    YYVoiceViewController *voice = [[YYVoiceViewController alloc] init];
    voice.title = @"声音";
    [self addChildViewController:voice];

    YYPictureViewController *picture = [[YYPictureViewController alloc] init];
    picture.title = @"图片";
    [self addChildViewController:picture];

    YYWordViewController *word = [[YYWordViewController alloc] init];
    word.title = @"段子";
    [self addChildViewController:word];
}

- (void)setUpTitlesView
{
    //标题栏
    UIView *titlesView = [[UIView alloc] init];
    titlesView.frame = CGRectMake(0, 64, self.view.width, 40);
    titlesView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
    [self.view addSubview:titlesView];

    //添加标题
//    NSArray *titles = @[@"全部",@"视频",@"声音",@"图片",@"段子"];
    CGFloat titleButtonW = titlesView.width / 5;
    CGFloat titleButtonH = titlesView.height;
    for (int i = 0; i < 5; i++) {
        YYTitleButton *titleButton = [[YYTitleButton alloc] init];
        titleButton.tag = i;
        [titleButton addTarget:self action:@selector(titleButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [titlesView addSubview:titleButton];
        [self.titleButtons addObject:titleButton];
        titleButton.frame = CGRectMake(i * titleButtonW, 0, titleButtonW, titleButtonH);
        [titleButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [titleButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        titleButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [titleButton setTitle:self.childViewControllers[i].title forState:UIControlStateNormal];
    }
    //添加底部的指示器
    UIView *titleIndicatorView = [[UIView alloc] init];
    [titlesView addSubview:titleIndicatorView];
    YYTitleButton *firstTitleButton = titlesView.subviews.firstObject;
    titleIndicatorView.backgroundColor = [firstTitleButton titleColorForState:UIControlStateSelected];
    titleIndicatorView.height = 1;
    titleIndicatorView.bottom = titlesView.height;
    self.titleIndicatorView = titleIndicatorView;

    //默认状态下
    firstTitleButton.selected = YES;
    self.selectedTitleButton = firstTitleButton;
    [firstTitleButton.titleLabel sizeToFit];
    titleIndicatorView.width = firstTitleButton.titleLabel.width;
    titleIndicatorView.centerX = firstTitleButton.centerX;

}
//titleButton按钮的点击
- (void)titleButtonClick:(YYTitleButton *)titleButton
{

    self.selectedTitleButton.selected = NO;
    titleButton.selected = YES;
    self.selectedTitleButton = titleButton;

    [UIView animateWithDuration:0.25 animations:^{
        self.titleIndicatorView.width = titleButton.titleLabel.width;
        self.titleIndicatorView.centerX = titleButton.centerX;
    }];

    //滚动scrollView
    CGPoint offset = self.scrollView.contentOffset;

    offset.x = titleButton.tag * self.scrollView.width;

    [self.scrollView setContentOffset:offset animated:YES];

}
//设置ScrollView
- (void)setUpScrollView
{
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    scrollView.frame = self.view.bounds;
    scrollView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:scrollView];

    self.automaticallyAdjustsScrollViewInsets = NO;

    scrollView.contentSize = CGSizeMake(self.childViewControllers.count *scrollView.width, 0);
//    for (int i = 0; i < self.childViewControllers.count; i++) {
//        UITableViewController *vc = self.childViewControllers[i];
//        vc.tableView.contentInset = UIEdgeInsetsMake(104, 0, 49, 0);
//        vc.tableView.scrollIndicatorInsets = vc.tableView.contentInset;
//        vc.tableView.x = i * scrollView.width;
//        vc.tableView.y = 0;
//        vc.tableView.width = scrollView.width;
//        vc.tableView.height = scrollView.height;
//        [scrollView addSubview:vc.tableView];
//
//    }
    scrollView.delegate = self;
    scrollView.pagingEnabled = YES;
    self.scrollView = scrollView;

}

- (void)setUpNav
{
     self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"MainTagSubIcon" highlighted:@"MainTagSubIconClick" target:self action:@selector(btnClick)];
}

- (void)btnClick
{
    YYRecommendTagViewController *vc = [[YYRecommendTagViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - <UIScrollViewDelegate>

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{

    [self addChildVcView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    int index = scrollView.contentOffset.x / scrollView.width;
    YYTitleButton *titleButton = self.titleButtons[index];
    [self titleButtonClick:titleButton];
    [self addChildVcView];
}

- (void)addChildVcView
{

    UIScrollView *scrollView = self.scrollView;
    int index = scrollView.contentOffset.x / scrollView.width;
    UIViewController *willShowVc = self.childViewControllers[index];
    if (willShowVc.isViewLoaded) return;
    [scrollView addSubview:willShowVc.view];
    willShowVc.view.frame = scrollView.bounds;

}

@end

redpajama_set_name: RedPajamaGithub


text:
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_

#include <functional>
#include <string>
#include <vector>

#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/stringpiece.h"

namespace tsl {
class Env;
}  // namespace tsl
namespace tensorflow {
using Env = tsl::Env;
class DeviceAttributes;
class Device;
class WorkerCacheInterface;

// This callback should have the same definition as DeviceMgr::LookupDevice
// It assigns *device with pointer to Device of the given 'name', where 'name'
// is either a full device name, or just the replica-local suffix.
typedef std::function<Status(StringPiece name, Device** device)>
    LookupLocalDevice;

// Creates Remote Devices for the provided device attributes. Helpful when the
// list of attributes is known, and doesn't need to be discovered via RPC.
void AsRemoteDevices(
    Env* env,
    const protobuf::RepeatedPtrField<DeviceAttributes>& device_attributes,
    LookupLocalDevice lookup_local_device,
    std::vector<std::unique_ptr<Device>>* remote_devices);

// NewRemoteDevices discovers available devices on the
// 'worker_name'.  The implementation uses 'channel_cache' to
// discover how to communicate with the 'worker_name' (via gRPC, for
// example).
//
// NewRemoteDevices does not block.
//
// On success, the 'done' callback is given the OK status and a vector
// of Device*. The caller should take ownership of these devices.
//
// Otherwise, the 'done' callback is given an error status and the
// vector is empty.
typedef std::function<void(const Status&, std::vector<Device*>*)>
    NewRemoteDevicesDone;
void NewRemoteDevices(Env* env, WorkerCacheInterface* worker_cache,
                      const string& worker_name, NewRemoteDevicesDone done);

// Create Remote Device based on the given attributes.
std::unique_ptr<Device> NewRemoteDevice(Env* env,
                                        DeviceAttributes device_attribute);
}  // namespace tensorflow

#endif  // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_REMOTE_DEVICE_H_


text:
function options = setdefoptions(options, defaultOptions)
%SETOPTIONS Set options with default options
optionNames = fieldnames(defaultOptions);

for i = 1 : numel(optionNames)
	if ~isfield(options, optionNames{i})
		options.(optionNames{i}) = defaultOptions.(optionNames{i});
	end
end
end


text:
package com.amazonaws.services.config.model.transform;

import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * PutEvaluationsRequest Marshaller
 */
public class PutEvaluationsRequestMarshaller implements
        Marshaller<Request<PutEvaluationsRequest>, PutEvaluationsRequest> {

    public Request<PutEvaluationsRequest> marshall(
            PutEvaluationsRequest putEvaluationsRequest) {

        if (putEvaluationsRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<PutEvaluationsRequest> request = new DefaultRequest<PutEvaluationsRequest>(
                putEvaluationsRequest, "AmazonConfig");
        request.addHeader("X-Amz-Target", "StarlingDoveService.PutEvaluations");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
                    .createWriter(false, "1.1");

            jsonGenerator.writeStartObject();

            com.amazonaws.internal.SdkInternalList<Evaluation> evaluationsList = (com.amazonaws.internal.SdkInternalList<Evaluation>) putEvaluationsRequest
                    .getEvaluations();
            if (!evaluationsList.isEmpty()
                    || !evaluationsList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("Evaluations");
                jsonGenerator.writeStartArray();
                for (Evaluation evaluationsListValue : evaluationsList) {
                    if (evaluationsListValue != null) {

                        EvaluationJsonMarshaller.getInstance().marshall(
                                evaluationsListValue, jsonGenerator);
                    }
                }
                jsonGenerator.writeEndArray();
            }
            if (putEvaluationsRequest.getResultToken() != null) {
                jsonGenerator.writeFieldName("ResultToken").writeValue(
                        putEvaluationsRequest.getResultToken());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", jsonGenerator.getContentType());
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        tools:context="org.usfirst.frc.team4911.scouting.PreGameFragment" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Set-Up"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Display1"
            android:layout_marginBottom="20dp"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="MATCH INFORMATION"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline"/>

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:stretchColumns="1">
            <TableRow
                android:paddingTop="10dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="MATCH :"
                    android:textAppearance="@style/SpinnerLook"
                    android:paddingRight="@dimen/activity_horizontal_margin"
                    android:layout_gravity="center_vertical" />

                <EditText
                    android:id="@+id/etxt_pre_game_match_num"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number"
                    android:text="1" />
            </TableRow>
            <TableRow
                android:paddingTop="10dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TEAM :"
                    android:textAppearance="@style/SpinnerLook"
                    android:layout_gravity="center_vertical" />

                <org.usfirst.frc.team4911.scouting.ui.TeamSpinnerView
                    android:id="@+id/team_spinner_pre_game"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content" />
            </TableRow>
        </TableLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin">

            <Space
                android:layout_width="match_parent"
                android:layout_height="20dp" />

            <ToggleButton
                android:id="@+id/toggleButton_pre_game_no_show"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textOn="NO-SHOW [X]"
                android:textOff="NO-SHOW"/>

            <Space
                android:layout_width="match_parent"
                android:layout_height="30dp" />

            <Button
                android:id="@+id/btn_pre_game_start_game"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="START MATCH"
                android:backgroundTint="#32CD32" />
        </LinearLayout>
    </LinearLayout>
</ScrollView>


text:
define('xstyle/core/elemental', ['put-selector/put', 'xstyle/core/utils'], function(put, utils){
	// using delegation, listen for any input changes in the document and 'put' the value
	// TODO: add a hook so one could add support for IE8, or maybe this event delegation isn't really that useful
	var doc = document;
	var nextId = 1;
	var hasAddEventListener = !!doc.addEventListener;
	on(doc, 'change', null, function(event){
		var element = event.target;
		// get the variable computation so we can put the value
		var variable = element['-x-variable'];
		if(variable){
			if(variable.forElement){
				variable = variable.forElement(element);
			}
			if(variable && variable.put){ // if it can be put, we do so
				var oldType = typeof variable.valueOf();
				var value = element.value;
				// do type coercion
				if(oldType === 'number' && isFinite(value)){
					value = +value;
				}
				variable.put(value);
			}
		}
	});
	function on(target, event, selector, listener){
		// this function can be overriden to provide better event handling
		hasAddEventListener ?
			target.addEventListener(event, select, false) :
			target.attachEvent(event, select);
		function select(event){
			// do event delegation
			if(!selector || matchesSelector.call(event.target, selector)){
				listener(event);
			}
		}
	}

	// elemental section, this code is for property handlers that need to mutate the DOM for elements
	// that match it's rule
	var testDiv = doc.createElement('div');
	var features = {
		'dom-qsa2.1': !!testDiv.querySelectorAll
	};
	function has(feature){
		return features[feature];
	}
	// get the matches function, whatever it is called in this browser
	var matchesSelector = testDiv.matches || testDiv.matchesSelector ||
		testDiv.webkitMatchesSelector || testDiv.mozMatchesSelector ||
		testDiv.msMatchesSelector || testDiv.oMatchesSelector;
	var selectorRenderers = [];
	var renderQueue = [];
	var documentQueried;
	// probably want to inline our own DOM readiness code
	function domReady(callback){
		// TODO: support IE7-8
		if(/e/.test(doc.readyState||'')){
			// TODO: fix the issues with sync so this can be run immediately
			setTimeout(callback, 200);
		}else{
			doc.addEventListener('DOMContentLoaded', callback);
		}
	}
	domReady(function(){
		if(!documentQueried){
			documentQueried = true;
			if(has('dom-qsa2.1')){
				// if we have a query engine, it is fastest to use that
				for(var i = 0, l = selectorRenderers.length; i < l; i++){
					// find the matches and register the renderers
					findMatches(selectorRenderers[i]);
				}
				// render all the elements that are queued up
				renderWaiting();
			}else{
			//else rely on css expressions (or maybe we should use document.all and just scan everything)
				var all = doc.all;
				for(var i = 0, l = all.length; i < l; i++){
					update(all[i]);
				}
			}
		}
	});
	function findMatches(renderer){
		// find the elements for a given selector and apply the renderers to it
		var results = doc.querySelectorAll(renderer.selector);
		var name = renderer.name;
		for(var i = 0, l = results.length; i < l; i++){
			var element = results[i];
			var currentStyle = element.elementalStyle;
			var currentSpecificities = element.elementalSpecificities;
			if(!currentStyle){
				currentStyle = element.elementalStyle = {};
				currentSpecificities = element.elementalSpecificities = {};
			}
			// TODO: only override if the selector is equal or higher specificity
			// var specificity = renderer.selector.match(/ /).length;
			if(true || currentSpecificities[name] <= renderer.specificity){ // only process changes
				var elementRenderings = element.renderings;
				if(!elementRenderings){
					// put it in the queue
					elementRenderings = element.renderings = [];
					renderQueue.push(element);
				}

				elementRenderings.push({
					name: name,
					rendered: currentStyle[name] == renderer.propertyValue,
					renderer: renderer
				});
				currentStyle[name] = renderer.propertyValue;
			}
		}

	}
	var isCurrent;
	function renderWaiting(){
		// render all the elements in the queue to be rendered
		for(var i = 0; i < renderQueue.length; i++){
			var element = renderQueue[i];
			var renderings = element.renderings, currentStyle = element.elementalStyle;
			delete element.renderings;
			for(var j = 0; j < renderings.length; j++){
				var rendering = renderings[j];
				var renderer = rendering.renderer;
				var rendered = renderer.rendered;
				// determine if this renderer matches the current computed style
				isCurrent = currentStyle[rendering.name] == renderer.propertyValue;
				if(!rendered && isCurrent){
					try{
						renderer.render(element);
					}catch(e){
						console.error(e, e.stack);
						put(element, 'div.error', e.toString());
					}
				}
				if(rendered && !isCurrent && renderer.unrender){
					renderer.unrender(element);
					renderings.splice(j--, 1); // TODO: need to remove duplicate rendered items as well
				}
			}
		}
		renderQueue = [];
	}
	function update(element, selector){
		/* TODO: At some point, might want to use getMatchedCSSRules for faster access to matching rules
		if(typeof getMatchedCSSRules != 'undefined'){
			// webkit gives us fast access to which rules apply
			getMatchedCSSRules(element);
		}else{*/
		for(var i = 0, l = selectorRenderers.length; i < l; i++){
			var renderer = selectorRenderers[i];
			if((!selector || (selector == renderer.selector)) &&
				(matchesSelector ?
					// use matchesSelector if available
					// TODO: determine if it is higher specificity that other  same name properties
					matchesSelector.call(element, renderer.selector) :
					// else use IE's custom css property inheritance mechanism
					element.currentStyle[renderer.id])){
				renderer.render(element);
			}
		}
	}
	function addRenderer(rule, handler){
		var renderer = {
			selector: rule.selector,
			render: handler
		};
		if(!matchesSelector){
			// so we can match this rule by checking inherited styles
			rule.setStyle(renderer.id = ('x' + nextId++), 'true');
		}
		// the main entry point for adding elemental handlers for a selector. The handler
		// will be called for each element that is created that matches a given selector
		selectorRenderers.push(renderer);
		if(documentQueried){
			findMatches(renderer);
		}
		renderWaiting();
		/*if(!matchesSelector){
			// create a custom property to identify this rule in created elements
			return (renderers.triggerProperty = 'selector_' + encodeURIComponent(selector).replace(/%/g, '/')) + ': 1;' +
				(document.querySelectorAll ? '' :
					// we use css expressions for IE6-7 to find new elements that match the selector, since qSA is not available, wonder if it is better to just use document.all...
					 'zoom: expression(cssxRegister(this,"' + selector +'"));');
		}*/
		return {
			remove: function(){
				selectorRenderers.splice(selectorRenderers.indexOf(renderer), 1);
			}
		};
	}
	return {
		ready: domReady,
		on: on,
		addRenderer: addRenderer,
		// this should be called for newly created dynamic elements to ensure the proper rules are applied
		update: update,
		clearRenderers: function(){
			// clears all the renderers in use
			selectorRenderers = [];
		},
		observeForElement: function(observable, rule, callback){
			return utils.when(observable, function(contextualizable){
				function observe(observable){
					if(observable.observe){
						observable.observe(callback);
					}else{
						callback(observable);
					}
				}
				if(contextualizable.forElement){
					addRenderer(rule, function(element){
						observe(contextualizable.forElement(element));
					});
				}else{
					observe(contextualizable);
				}
			});
		}
	};
});


text:
namespace dlib
{

// ----------------------------------------------------------------------------------------
    inline void draw_surf_points (
        image_window& win,
        const std::vector<surf_point>& sp
    )
    {
        for (unsigned long i = 0; i < sp.size(); ++i)
        {
            const unsigned long radius = static_cast<unsigned long>(sp[i].p.scale*3);
            const point center(sp[i].p.center);
            point direction = center + point(radius,0);
            // SURF descriptors are rotated by sp[i].angle.  So we want to include a visual
            // indication of this rotation on our overlay.
            direction = rotate_point(center, direction, sp[i].angle);

            win.add_overlay(image_display::overlay_circle(center, radius, rgb_pixel(0,255,0)));
            // Draw a line showing the orientation of the SURF descriptor.
            win.add_overlay(center, direction, rgb_pixel(255,0,0));
        }
    }

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

}

#endif // DLIB_DRAW_SURf_POINTS_H_


text:
{% extends "base.html" %}
{% load staticfiles %}
{% load analysis_tags %}
{% block content %}

        {% include "analysis/pages/nav-sidebar.html" %}

Compare

Analysis 1

                        {% include "analysis/pages/compare/_info.html" with record=left %}

Analysis 2

You need to select the second analysis.
                        {% if records.count > 0 %}
                            Following are all the analyses of the file with provided MD5 or pattern {{hash}}:

                            {% include "analysis/pages/compare/_summary_table.html" %}
                        {% else %}
                            There is no analysis for the specified file or you selected the same selected analysis.

                        {% endif %}

                    ©2010-2018 Cuckoo Sandbox

                    Back to Top

{% endblock %}


text:
using Silphid.Options;

namespace Silphid.Loadzup
{
    public interface IOptions : IOptionsBase {}
}


text:
layout: post
title:  "Preventing Duplicate Selections with C# and jQuery Validation"
tags: asp.net c#
---

A few days ago, while working on a web page, I got to write my favorite type of code: validation.

![jQuery validation](/images/validation.png)

Ha ha. Actually I'd rather floss with a brick than write validation.

Anyway, I was writing validation for an ASP.NET/C# registration page. The page has three dropdown lists, each with the same list of courses. Students can register for up to three courses by choosing a course in each dropdown list. The validation I was writing needed to prevent a student from registering for a course multiple times. It seemed like there should be a simple solution, but it wasn't jumping out at me, so I started to pseudocode a naive solution.

{% gist 8260138 PreventingDuplicates1.txt %}

Okay, not very elegant. And not easily scalable <del>if</del> when I'm asked to add a fourth dropdown.
I started coding it out a little more in the hopes of seeing a pattern.

{% gist 8260138 PreventingDuplicates2.txt %}

Then I had a "eureka" moment: I could put the values in an array, get the count of unique items, and check if the number of values is equal to the number of unique values.

{% gist 8260138 PreventingDuplicates1.cs %}

This works because I don't care how many duplicates there are, or which values are duplicated. I just want to know if duplicates exist.

However, it's not quite complete. If a student registers for only one course, say "History 101", dropdown list 1 will have the value "HI 101" and dropdowns 2 and 3 will be empty strings. Since ```"" == ""```, I'll need to allow multiple empty strings.

{% gist 8260138 PreventingDuplicates2.cs %}

Boom. And in jQuery:

{% gist 8260138 PreventingDuplicates.js %}

I still don't like writing validation, but…it has its interesting moments. ∎


text:
namespace AirlineSystem.Web.Controllers
{
    using System.Web.Mvc;

    using AirlineSystem.Data;

    public class HomeController : BaseController
    {
        public HomeController(IAirlineSystemData data) : base(data)
        {
        }

        public ActionResult Index()
        {
            return this.View();
        }

        public ActionResult OurMission()
        {
            return this.View();
        }

        public ActionResult Contact()
        {
            return this.View();
        }

        public ActionResult Error()
        {
            return this.View();
        }
    }
}


text:
{% extends 'base.html' %}
{% load thumbnail %}
{% load cms_tags %}

{% block breadcrumb %}
    Главная»
     Каталог »
    Корзина

{% endblock %}

{% block title %}Корзина{% endblock title %}

{% block content %}

Ваша корзина товаров

    {% if cart.item_count > 0 %}

Товары в наличии

        Изображение
        Продукт
        Количество
        Цена
        Стоимость

      {% for item in cart.list_items  %}
        {% with product=item.obj %}

                  {% if product.stock == 1 %}

                {% if product.item_image_set.first.file %}
                    {% thumbnail product.item_image_set.first.file "50x50" crop="center" as im %}

                    {% endthumbnail %}
                {% else %}

               {% endif %}

              {{ product.item.title }} ({{ product.title }})

                  <input type="number" class="form-control cart-quantity input-number" data-step="{{ product.item.min_lot }}" value="{{ item.quantity }}" min="0" max="999">

                    <button class="btn btn-default" type="button" onclick="cart.changeQuantity('{{ product.pk }}', $(this).parent().prev('.cart-quantity').val())" title="Изменить количество">

                    </button>

            {% if user and not user.is_anonymous  %}

                {% autoescape off %}{% get_discount product.price_2 user product.item %}{% endautoescape %}

                {% else %}
                {{ product.price_1 }}
            {% endif %}

          {% if user and not user.is_anonymous  %}
              {% get_discount_summ product.price_2 user product.item item.quantity %} руб.
          {% else %}
              {% mult product.price_1 item.quantity %} руб.
          {% endif %}

                <button class="btn btn-danger" onclick="cart.remove('{{ product.pk }}')"></button>

      {% endif %}
        {% endwith %}
      {% endfor %}

Итого:  {{ real_count_cart }} руб.

    {% if user and not user.is_anonymous  %}

Ваша скидка: {% get_discount_dif cart.list_items user %} руб.

Итого со скидкой:  {% get_discount_all cart.list_items user %} руб.

    {% endif %}

Товары в ожидании

        Изображение
        Продукт
        Количество
        Цена
        Стоимость

      {% for item in cart.list_items  %}
        {% with product=item.obj %}

      {% if product.stock == 2 %}

                {% if product.item_image_set.first.file %}
                    {% thumbnail product.item_image_set.first.file "50x50" crop="center" as im %}

                    {% endthumbnail %}
                {% else %}

               {% endif %}

              {{ product.item.title }} ({{ product.title }})

                  <input type="number" class="form-control cart-quantity input-number" data-step="{{ product.item.min_lot }}" value="{{ item.quantity }}" min="0" max="999">

                    <button class="btn btn-default" type="button" onclick="cart.changeQuantity('{{ product.pk }}', $(this).parent().prev('.cart-quantity').val())" title="Изменить количество">

                    </button>

            {% if user and not user.is_anonymous  %}    {{ product.price_2 }}

                {% else %}
                {{ product.price_1 }}
            {% endif %}

                р.

          {% if user and not user.is_anonymous  %}
            {% mult product.price_2 item.quantity %} р.
          {% else %}
          {% mult product.price_1 item.quantity %} р.
          {% endif %}

                <button onclick="cart.remove('{{ product.pk }}')">Удалить</button>

      {% endif %}

        {% endwith %}
      {% endfor %}

Данные заказа

     {% if user and not user.is_anonymous  %}

            <form action="{% url "shop:order-success-post"%}"  method="post">
       {% csrf_token %}

    Имя:     {{ userprofile.name }}

    Компания: {{ userprofile.company_name }}

     Необходима доставка: <input type="checkbox" id="dost_need_check" name="dost_need">

Адрес доставки:

    <input type="text" size="40" class="form-control" name="dost_adres" value="{{ userprofile.adres }}">

    <input type="hidden" name="user_name" value="{{ user }}">

    <input type="hidden" name="your_name" value="{{ userprofile.name }}">
    <input type="hidden" name="phone" value="{{ userprofile.phone }}">
    <input type="hidden" name="company_name" value="{{ userprofile.company_name }}">
    <input type="hidden" name="email" value="{{ user.email }}">
    <input type="hidden" name="inn" value="{{ userprofile.inn }}">

    {% else %}

   <form action="{% url "shop:order-success-post"%}"  method="post">
       {% csrf_token %}

   {{ form.as_table }}

Адрес доставки:
    <input type="text" size="40" class="form-control" name="dost_adres" value="{{ userprofile.adres }}">

    {% endif %}

    Вернуться в магазин

    <input type="submit" class="button button--grey button--main btn" style="width: 125px;" value="Оформить заказ">

        {% else %}

Ваша корзина пуста

            Вернуться в магазин
        {% endif %}

    </form>

{% endblock %}


text:
import { IPromise } from 'angular';

import { $q } from 'ngimport';

import { ISearchResultFormatter } from '../search/searchResult/searchResultFormatter.registry';
import { ISearchResult } from '../search/search.service';
import { searchResultFormatterRegistry } from '../search/searchResult/searchResultFormatter.registry';

export interface ISecurityGroupSearchResult extends ISearchResult {
  name: string;
  region: string;
  application: string;
}

export class SecurityGroupSearchResultFormatter implements ISearchResultFormatter {

  public get displayName() { return 'Security Groups'; }
  public get order() { return 6; }
  public get icon() { return 'exchange'; }
  public displayFormatter(searchResult: ISecurityGroupSearchResult): IPromise<string> {
    return $q.when(searchResult.name + ' (' + searchResult.region + ')');
  }
}

searchResultFormatterRegistry.register('securityGroups', new SecurityGroupSearchResultFormatter());


text:
namespace hue { namespace ast {

class Conditional : public Expression {
public:
  Conditional() : Expression(TConditional), testExpression_(0), trueBlock_(0), falseBlock_(0) {}

  Expression* testExpression() const { return testExpression_; }
  void setTestExpression(Expression* expr) { testExpression_ = expr; }

  Block* trueBlock() const { return trueBlock_; }
  void setTrueBlock(Block* B) { trueBlock_ = B; }

  Block* falseBlock() const { return falseBlock_; }
  void setFalseBlock(Block* B) { falseBlock_ = B; }

  virtual const Type *resultType() const {
    assert(trueBlock_);
    const Type* trueT = trueBlock_->resultType();
    const Type* falseT = falseBlock_->resultType();
    return Type::highestFidelity(trueT, falseT);
  }

  virtual void setResultType(const Type* T) {
    assert(trueBlock_);
    trueBlock_->setResultType(T);
    assert(falseBlock_);
    falseBlock_->setResultType(T);
  }

  virtual std::string toString(int level = 0) const {
    std::ostringstream ss;
    //NodeToStringHeader(level, ss);
    ss << "(if " << (testExpression_ ? testExpression_->toString(level) : "nil");
    NodeToStringHeader(level+1, ss);
    ss << (trueBlock_ ? trueBlock_->toString(level+1) : "nil");
    if (level == 0) ss << "\n"; else NodeToStringHeader(level, ss);
    ss << "else ";
    NodeToStringHeader(level+1, ss);
    ss << (falseBlock_ ? falseBlock_->toString(level+1) : "nil")
       << ")";
    return ss.str();
  }

private:
  Expression* testExpression_;
  Block* trueBlock_;
  Block* falseBlock_;
};

}} // namespace hue.ast
#endif // HUE__AST_CONDITIONALS_H


text:
if $(gls &>/dev/null)
then
  alias ls="gls -F --color"
  alias l="gls -lAh --color"
  alias ll="gls -l --color"
  alias la='gls -A --color'
fi

alias clearcache="sudo dscacheutil -flushcache"
alias tmux="TERM=screen-256color-bce tmux -2"


text:
*   [dzakhar](https://github.com/dzakhar)
*   [JaccovG](https://github.com/JaccovG)

## Introduction

This folder contains kernel implementations which use optimized
[embARC MLI Library](https://github.com/foss-for-synopsys-dwc-arc-processors/embarc_mli).
It allows acceleration of inference operations which use int8 (asymmetric
quantization).

## Usage

embARC MLI Library is used by default to speed up execution of some kernels for
asymmetrically quantized layers. This means that usual project generation for
ARC specific target implies usage of embARC MLI.

For example:

```
make -f tensorflow/lite/micro/tools/make/Makefile TARGET=arc_emsdp OPTIMIZED_KERNEL_DIR=arc_mli generate_person_detection_int8_make_project
```

In case MLI implementation can't be used, kernels in this folder fallback to
TFLM reference implementations. For applications which may not benefit from MLI
library, projects can be generated without these implementations by adding
`ARC_TAGS=no_arc_mli` in the command line, which can reduce overall code size:

```
make -f tensorflow/lite/micro/tools/make/Makefile TARGET=arc_emsdp OPTIMIZED_KERNEL_DIR=arc_mli ARC_TAGS=no_arc_mli generate_person_detection_int8_make_project
```

For ARC EM SDP board, a pre-compiled MLI library is downloaded and used in the
application. For a custom target ARC-based platform, MLI sources are downloaded
and compiled during project generation phase. To build library from sources for
ARC EM SDP platform, add `BUILD_ARC_MLI=true` option to make command:

```
make -f tensorflow/lite/micro/tools/make/Makefile TARGET=arc_emsdp OPTIMIZED_KERNEL_DIR=arc_mli BUILD_ARC_MLI=true generate_person_detection_int8_make_project
```

If an application exclusively uses accelerated MLI kernel implementations, one
can strip out TFLM reference kernel implementations to reduce code size of
application. Build application with `MLI_ONLY=true` option in generated project
(after the project was built):

```
cd tensorflow/lite/micro/tools/make/gen/arc_emsdp_arc/prj/person_detection_int8/make

make app MLI_ONLY=true
```

if you try this and application execution fails, then most probably MLI can't be
used for some nodes and you need to revert to using TFLM reference kernels.

## Limitations

Currently, the MLI Library provides optimized implementation only for int8
(asymmetric) versions of the following kernels: 1. Convolution 2D – Per axis
quantization only, `dilation_ratio==1` 2. Depthwise Convolution 2D – Per axis
quantization only, `dilation_ratio==1` 3. Average Pooling 4. Max Pooling 5.
Fully Connected

Currently only
[/tensorflow/lite/micro/examples/person_detection](/tensorflow/lite/micro/examples/person_detection)
is quantized using this specification. Other examples can be executed on
ARC-based targets, but will only use reference kernels.

## Scratch Buffers and Slicing

The following information applies only for ARC EM SDP and other targets with XY
memory. embARC MLI uses specific optimizations which assumes node operands are
in XY memory and/or DCCM (Data Closely Coupled Memory). As operands might be
quite big and may not fit in available XY memory, special slicing logic is
applied which allows kernel calculations to be split into multiple parts. For
this reason, internal static buffers are allocated in these X, Y and DCCM memory
banks and used to execute sub-calculations.

All this is performed automatically and invisible to the user. Half of the DCCM
memory bank and the full XY banks are occupied for MLI specific needs. If the
user needs space in XY memory for other tasks, these arrays can be reduced by
setting specific sizes. For this, add the following option to build command
replacing **<size[a|b|c]>** with required values:

```
EXT_CFLAGS="-DSCRATCH_MEM_Z_SIZE=<size_a> -DSCRATCH_MEM_X_SIZE=<size_b> -DSCRATCH_MEM_Y_SIZE=<size_c>"
```

For example, to reduce sizes of arrays placed in DCCM and XCCM to 32k and 8k
respectively, use next command:

```
make app EXT_CFLAGS="-DSCRATCH_MEM_Z_SIZE=32*1024 -DSCRATCH_MEM_X_SIZE=8*1024"
```

## License

TensorFlow's code is covered by the Apache2 License included in the repository,
and third party dependencies are covered by their respective licenses, in the
third_party folder of this package.


text:
package org.opentosca.csarrepo.model;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.opentosca.csarrepo.model.join.CsarFileOpenToscaServer;
import org.opentosca.csarrepo.model.join.OpenToscaServerUser;

/**
 *
 * Hibernate annotated class for OpenTosca Server
 *
 * @author Dennis Przytarski, Thomas Kosch (mail@thomaskosch.com)
 *
 */
@Entity
@Table(name = "open_tosca_server")
public class OpenToscaServer {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "open_tosca_server_id")
	private long id;

	@Column(name = "address")
	private URL address;

	@Column(name = "name")
	private String name;

	@OneToMany(mappedBy = "openToscaServer")
	@LazyCollection(LazyCollectionOption.FALSE)
	private List<CloudInstance> cloudInstances;

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "csarFileOpenToscaServerId.openToscaServer")
	@LazyCollection(LazyCollectionOption.FALSE)
	private List<CsarFileOpenToscaServer> csarFileOpenToscaServer = new ArrayList<CsarFileOpenToscaServer>();

	@OneToMany(cascade = CascadeType.ALL, mappedBy = "openToscaServerUserId.openToscaServer")
	@LazyCollection(LazyCollectionOption.FALSE)
	private List<OpenToscaServerUser> openToscaServerUser = new ArrayList<OpenToscaServerUser>();

	public OpenToscaServer() {
	}

	public OpenToscaServer(Long id) {
		this.id = id;
	}

	/**
	 * This method maps an Csar file instance to the corresponding OpenTosca in
	 * the database
	 *
	 * @param csarFile
	 *            A Csar file object
	 *
	 */
	public void addCsarFile(CsarFile csarFile) {
		CsarFileOpenToscaServer csarFileOpenToscaServer = new CsarFileOpenToscaServer(
				new CsarFileOpenToscaServer.CsarFileOpenToscaServerId(csarFile, this));

		csarFileOpenToscaServer.setCsarFile(csarFile);
		csarFileOpenToscaServer.setOpenToscaServer(this);

		this.csarFileOpenToscaServer.add(csarFileOpenToscaServer);
	}

	/**
	 * This method maps an User instance to the corresponding OpenTosca in the
	 * database
	 *
	 * @param user
	 *            A user object
	 *
	 */
	public void addUser(User user) {
		OpenToscaServerUser openToscaServerUser = new OpenToscaServerUser(
				new OpenToscaServerUser.OpenToscaServerUserId(this, user));

		openToscaServerUser.setOpenToscaServer(this);
		openToscaServerUser.setUser(user);

		this.openToscaServerUser.add(openToscaServerUser);
	}

	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @return the name of the OpenTosca instance
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name of the OpenTosca instance
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the address
	 */
	public URL getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address
	 */
	public void setAddress(URL address) {
		this.address = address;
	}

	/**
	 * @return cloud instances List containing the correlation of the respective
	 *         classes
	 */
	public List<CloudInstance> getCloudInstances() {
		return cloudInstances;
	}

	/**
	 * @param cloudInstances
	 *            cloud instances
	 */
	public void setCloudInstances(List<CloudInstance> cloudInstances) {
		this.cloudInstances = cloudInstances;
	}

	/**
	 * @return List containing the correlation of the respective classes
	 */
	public List<CsarFileOpenToscaServer> getCsarFileOpenToscaServer() {
		return csarFileOpenToscaServer;
	}

	/**
	 * @param csarFileOpenToscaServer
	 *            List containing the correlation of the respective classes
	 */
	public void setCsarFileOpenToscaServer(List<CsarFileOpenToscaServer> csarFileOpenToscaServer) {
		this.csarFileOpenToscaServer = csarFileOpenToscaServer;
	}

	/**
	 * @return List containing the correlation of the respective classes
	 */
	public List<OpenToscaServerUser> getOpenToscaServerUser() {
		return openToscaServerUser;
	}

	/**
	 * @param openToscaServerUser
	 *            List containing the correlation of the respective classes
	 */
	public void setOpenToscaServerUser(List<OpenToscaServerUser> openToscaServerUser) {
		this.openToscaServerUser = openToscaServerUser;
	}

}


text:
import { extractConvParamsFactory, extractSeparableConvParamsFactory, } from '../common';
export function extractorsFactory(extractWeights, paramMappings) {
    var extractConvParams = extractConvParamsFactory(extractWeights, paramMappings);
    var extractSeparableConvParams = extractSeparableConvParamsFactory(extractWeights, paramMappings);
    function extractDenseBlock3Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer) {
        if (isFirstLayer === void 0) { isFirstLayer = false; }
        var conv0 = isFirstLayer
            ? extractConvParams(channelsIn, channelsOut, 3, mappedPrefix + "/conv0")
            : extractSeparableConvParams(channelsIn, channelsOut, mappedPrefix + "/conv0");
        var conv1 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv1");
        var conv2 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv2");
        return { conv0: conv0, conv1: conv1, conv2: conv2 };
    }
    function extractDenseBlock4Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer) {
        if (isFirstLayer === void 0) { isFirstLayer = false; }
        var _a = extractDenseBlock3Params(channelsIn, channelsOut, mappedPrefix, isFirstLayer), conv0 = _a.conv0, conv1 = _a.conv1, conv2 = _a.conv2;
        var conv3 = extractSeparableConvParams(channelsOut, channelsOut, mappedPrefix + "/conv3");
        return { conv0: conv0, conv1: conv1, conv2: conv2, conv3: conv3 };
    }
    return {
        extractDenseBlock3Params: extractDenseBlock3Params,
        extractDenseBlock4Params: extractDenseBlock4Params
    };
}
//# sourceMappingURL=extractorsFactory.js.map


text:
package org.nd4j.linalg.api.ops.impl.shape;

import org.apache.commons.math3.util.FastMath;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.BaseOp;
import org.nd4j.linalg.api.ops.Op;
import org.nd4j.linalg.api.ops.ShapeOp;
import org.nd4j.linalg.util.ComplexUtil;

/**
 * Transpose function
 *
 * @author Adam Gibson
 */
public class Transpose extends ShapeOp {

    public Transpose() {}

    public Transpose(INDArray x, INDArray z) {
        super(x, z);
    }

    public Transpose(INDArray x, INDArray z, long n) {
        super(x, z, n);
    }

    public Transpose(INDArray x, INDArray y, INDArray z, long n) {
        super(x, y, z, n);
    }

    public Transpose(INDArray x) {
        super(x);
    }

    @Override
    public void exec(int... dimensions) {
        exec();
    }

    @Override
    public boolean isExecSpecial() {
        return true;
    }

    @Override
    public void exec() {
        if(x != z) {
            z.assign(x.transpose());
        }
        else {
            this.z = x.transpose();
        }

    }

    @Override
    public int opNum() {
        return 0;
    }

    @Override
    public String name() {
        return "transpose";
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, double other) {
        return ComplexUtil.abs(origin);
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, float other) {
        return ComplexUtil.abs(origin);
    }

    @Override
    public IComplexNumber op(IComplexNumber origin, IComplexNumber other) {
        return ComplexUtil.abs(origin);
    }

    @Override
    public float op(float origin, float other) {
        return FastMath.abs(origin);
    }

    @Override
    public double op(double origin, double other) {
        return FastMath.abs(origin);
    }

    @Override
    public double op(double origin) {
        return FastMath.abs(origin);
    }

    @Override
    public float op(float origin) {
        return FastMath.abs(origin);
    }

    @Override
    public IComplexNumber op(IComplexNumber origin) {
        return ComplexUtil.abs(origin);
    }

    @Override
    public Op opForDimension(int index, int dimension) {
        INDArray xAlongDimension = x.vectorAlongDimension(index, dimension);

        if (y() != null)
            return new Transpose(xAlongDimension, y.vectorAlongDimension(index, dimension),
                    z.vectorAlongDimension(index, dimension), xAlongDimension.length());
        else
            return new Transpose(xAlongDimension, z.vectorAlongDimension(index, dimension), xAlongDimension.length());

    }

    @Override
    public INDArray z() {
        return x().transpose();
    }

    @Override
    public Op opForDimension(int index, int... dimension) {
        INDArray xAlongDimension = x.tensorAlongDimension(index, dimension);

        if (y() != null)
            return new Transpose(xAlongDimension, y.tensorAlongDimension(index, dimension),
                    z.tensorAlongDimension(index, dimension), xAlongDimension.length());
        else
            return new Transpose(xAlongDimension, z.tensorAlongDimension(index, dimension), xAlongDimension.length());

    }
}


text:
package org.lpw.tephra.bean;

import org.springframework.stereotype.Component;

/**
 * @author lpw
 */
@Component("tephra.bean.context-close-listener.2")
public class ContextCloseListener2 implements ContextClosedListener {
    @Override
    public int getContextClosedSort() {
        return 2;
    }

    @Override
    public void onContextClosed() {
        ContainerTest.runContextCloseListener(getContextClosedSort());
    }
}


text:
<template name="pageSettingsContainer">

                {{> burger}}

                        {{pageTitle}}

			{{> Template.dynamic template=pageTemplate}}

</template>


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>{gr-$tpl.wxname}</title>
        <base href="." />
        <meta name="viewport" content="width=device-width,height=device-height,inital-scale=1.0,maximum-scale=1.0,user-scalable=no;" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <meta name="format-detection" content="telephone=no" />
<link href="__CSS__/allcss/cate{gr-$tpl.tpltypeid}_{gr-$tpl.color_id}.css" rel="stylesheet" type="text/css" />

<link href="__CSS__/135/iscroll.css" rel="stylesheet" type="text/css">

{gr-$zhidacode}

<if condition="$homeInfo['musicurl'] neq false">
<include file="Index:music"/>
</if>

<volist name="flash" id="so">

{gr-$so.info}

    <a href="<if condition="$so['url'] eq ''">{gr-:U('Wap/Index/flash',array('token'=>$so['token']))}<else/>{gr-$so.url|htmlspecialchars_decode}</if>">

</volist>

← prev

<volist name="flash" id="so">
    <li <if condition="$i eq 1">class="active"</if>>

</volist>

next →

<volist name="info" id="vo">
<if condition="$i lt 5">

<a href="<if condition="$vo['url'] eq ''">{gr-:U('Wap/Index/lists',array('classid'=>$vo['id'],'token'=>$vo['token']))}<else/>{gr-$vo.url|htmlspecialchars_decode}</if>">
{gr-$vo.name}

</if>
</volist>

<volist name="info" id="vo" key="tt">
<if condition="$tt gt 4">

<a href="<if condition="$vo['url'] eq ''">{gr-:U('Wap/Index/lists',array('classid'=>$vo['id'],'token'=>$vo['token']))}<else/>{gr-$vo.url|htmlspecialchars_decode}</if>">
{gr-$vo.name}

<?php if ($vo['sub']){
	foreach ($vo['sub'] as $res){
		if ($res['url']==''){
			$url=U('Wap/Index/lists',array('classid'=>$res['id'],'token'=>$res['token']));
		}else {
			$url=htmlspecialchars_decode($res['url']);
		}
		echo ''.$res['name'].'';
	}
}
?>

</if>
</volist>

 <if condition="$iscopyright eq 1">
{gr-$homeInfo.copyright}
<else/>
{gr-$siteCopyright}
</if>

 <include file="Index:styleInclude"/><include file="$cateMenuFileName"/>
 	<if condition="ACTION_NAME eq 'index'">

	<else />

	</if>
{gr-$shareScript}


text:
namespace nCubed.GooCal.Common
{
    /// <summary>
    /// Interface for authenticating to a specific Google Calendar.
    /// </summary>
    public interface ICalendarCredentials
    {
        /// <summary>
        /// The Google account user name.
        /// </summary>
        string UserName { get; }

        /// <summary>
        /// The Google account password.
        /// </summary>
        string Password { get; }

        /// <summary>
        /// The URL of a specific calendar.
        /// </summary>
        string CalendarUrl { get; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Luiz Torres Developer</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Luiz Torres

                        Sobre

                        Serviços

                        Contatos

                        Portifólio

                                Projetos

                        Blog

                                Em Breve!

                        Outras Páginas

                                Sidebar Page

                                FAQ

                                404

Blog Home One
                    Subheading

Home

Blog Home One

                    Blog Post Title

                    by Luiz Torres

 Posted on August 28, 2013 at 10:00 PM

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore, veritatis, tempora, necessitatibus inventore nisi quam quia repellat ut tempore laborum possimus eum dicta id animi corrupti debitis ipsum officiis rerum.

                Read More

Side Widget Well

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.


text:
<!DOCTYPE html>
<meta charset="utf-8">

  <title>Visualization of Consolidated Revenues</title>

A visualization of this Consolidated Revenues data set, licensed under the Open Government License - Prince Edward Island

Fiscal years can be selected from drop-down box.

Hover over segments for details. Amounts in 000's and rounded. Other graphs here

source here

and uses dimple

<select id="comboBox">
DATA_OPTIONS
</select>
<button type="button" id="animationButton">Stop animation</button>


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

<TITLE>
PSImageUtils (Apache FOP 1.1 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.render.ps

Class PSImageUtils

java.lang.Object
  org.apache.xmlgraphics.ps.PSImageUtils
      org.apache.fop.render.ps.PSImageUtils

public class PSImageUtils
extends org.apache.xmlgraphics.ps.PSImageUtils

Utility code for rendering images in PostScript.

Constructor Summary

PSImageUtils()

Method Summary

static void
drawForm(org.apache.xmlgraphics.ps.PSResource form,
         org.apache.xmlgraphics.image.loader.ImageInfo info,
         java.awt.Rectangle rect,
         org.apache.xmlgraphics.ps.PSGenerator generator)

          Draws a form at a given location.

static boolean
isImageInlined(org.apache.xmlgraphics.image.loader.ImageInfo info,
               PSRenderingContext renderingContext)

          Indicates whether the given image (identified by an ImageInfo object) shall be
 inlined rather than generated as a PostScript form.

Methods inherited from class org.apache.xmlgraphics.ps.PSImageUtils

getRGB, paintForm, paintForm, paintReusableImage, renderBitmapImage, renderEPS, renderEPS, translateAndScale, writeImage, writeImage, writeImage, writeReusableImage, writeReusableImage

Methods inherited from class java.lang.Object

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

Constructor Detail

PSImageUtils

public PSImageUtils()

Method Detail

isImageInlined

public static boolean isImageInlined(org.apache.xmlgraphics.image.loader.ImageInfo info,
                                     PSRenderingContext renderingContext)

Indicates whether the given image (identified by an ImageInfo object) shall be
 inlined rather than generated as a PostScript form.

Parameters:
info - the info object for the image
renderingContext - the rendering context

Returns:
true if the image shall be inlined, false if forms shall be used.

drawForm

public static void drawForm(org.apache.xmlgraphics.ps.PSResource form,
                            org.apache.xmlgraphics.image.loader.ImageInfo info,
                            java.awt.Rectangle rect,
                            org.apache.xmlgraphics.ps.PSGenerator generator)
                     throws java.io.IOException

Draws a form at a given location.

Parameters:
form - the form resource
info - the image info object representing the image in the form
rect - the target rectangle (coordinates in millipoints)
generator - the PostScript generator

Throws:

java.io.IOException - if an I/O error occurs

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 1.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved.


text:
<h0>Ruby Library</h0>

# Installation

We strongly encourage use of our official libraries for accessing the GoCardless API.

### Getting the library

Added to your Gemfile:

```ruby
gem 'gocardless'
```

Check out our [Ruby docs](/legacy/ruby) or view [source on Github](https://github.com/gocardless/gocardless-legacy-ruby).


text:
<?php

namespace Employee\Controller;

use Application\Controller\BaseController;
use Employee\Service\EmployeeServiceInterface;
use Auth\Service\AuthServiceInterface;
use Zend\View\Model\ViewModel;

/**
 *
 * @author jaimie <pacificnm@gmail.com>
 * @version 2.5.0
 *
 */
class DeleteController extends BaseController
{
    /**
     *
     * @var EmployeeServiceInterface
     */
    protected $employeeService;

    /**
     *
     * @var AuthServiceInterface
     */
    protected $authService;

    /**
     *
     * @param EmployeeServiceInterface $employeeService
     * @param AuthServiceInterface $authService
     */
    public function __construct(EmployeeServiceInterface $employeeService, AuthServiceInterface $authService)
    {
        $this->employeeService = $employeeService;

        $this->authService = $authService;
    }

    /**
     *
     * {@inheritDoc}
     * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $this->layout()->setVariable('pageTitle', 'Employee');

        $this->layout()->setVariable('pageSubTitle', 'Delete');

        $this->layout()->setVariable('activeMenuItem', 'admin');

        $this->layout()->setVariable('activeSubMenuItem', 'employee-index');

        $id = $this->params()->fromRoute('employeeId');

        $employeeEntity = $this->employeeService->get($id);

        if(! $employeeEntity) {
            $this->flashmessenger()->addErrorMessage('Unable to find the employee #' . $id);

            return $this->redirect()->toRoute('employee-index');
        }

        $request = $this->getRequest();

        if ($request->isPost()) {
            $del = $request->getPost('delete_confirmation', 'no');

            if ($del === 'yes') {

                $authEntity = $this->authService->get($employeeEntity->getAuthEntity()->getAuthId());

                if($authEntity) {
                    $this->authService->delete($authEntity);
                }

                $this->employeeService->delete($employeeEntity);

                $this->flashmessenger()->addSuccessMessage('The employee was deleted');

                return $this->redirect()->toRoute('employee-index');
            }

            return $this->redirect()->toRoute('employee-view', array('employeeId' => $id));
        }

        return new ViewModel(array(
            'employeeEntity' => $employeeEntity
        ));
    }
}


text:
What are protobufs?
-------------------
The documentation is available here: https://developers.google.com/protocol-buffers/docs/overview

How do I use them?
------------------
In general, you make a file of the form:
```
message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}
```

Then compile it with protoc: http://manpages.ubuntu.com/manpages/jaunty/en/man1/protoc.1.html
Into the language of your choice: https://code.google.com/p/protobuf/wiki/ThirdPartyAddOns

With one of:
```
protoc --lua_out=./ addressbook.proto
protoc --cpp_out=./ addressbook.proto
protoc --java_out=./ addressbook.proto
protoc --python_out=./ addressbook.proto
```

Or more generally:
```
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
```

Then you read in the file and encode a message based on that prototype:
```
import addressbook_pb2

person = addressbook_pb2.Person()
person.id = 1234
person.name = "John Doe"
person.email = "jdoe@example.com"
phone = person.phone.add()
phone.number = "555-4321"
phone.type = addressbook_pb2.Person.HOME

msg = person.SerializeToString()
```

or decode and access:

```
import addressbook_pb2

person = addressbook_pb2.Person()

input = msg

person.ParseFromString(msg)
new_var = person.id
```


text:
$script:projectPath = "$PSScriptRoot\..\.." | Convert-Path
$script:projectName = (Get-ChildItem -Path "$script:projectPath\*\*.psd1" | Where-Object -FilterScript {
        ($_.Directory.Name -match 'source|src' -or $_.Directory.Name -eq $_.BaseName) -and
        $(try
            {
                Test-ModuleManifest -Path $_.FullName -ErrorAction Stop
            }
            catch
            {
                $false
            })
    }).BaseName

$script:parentModule = Get-Module -Name $script:projectName -ListAvailable | Select-Object -First 1
$script:subModulesFolder = Join-Path -Path $script:parentModule.ModuleBase -ChildPath 'Modules'
Remove-Module -Name $script:parentModule -Force -ErrorAction 'SilentlyContinue'

$script:subModuleName = (Split-Path -Path $PSCommandPath -Leaf) -replace '\.Tests.ps1'
$script:subModuleFile = Join-Path -Path $script:subModulesFolder -ChildPath "$($script:subModuleName)/$($script:subModuleName).psm1"

Import-Module $script:subModuleFile -Force -ErrorAction Stop
#endregion HEADER

InModuleScope $script:subModuleName {
    Describe 'ComputerManagementDsc.Common\Get-TimeZoneId' {
        Context '"Get-TimeZone" not available and current timezone is set to "Pacific Standard Time"' {
            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Get-TimeZone'
            }

            Mock -CommandName Get-CimInstance -MockWith {
                @{
                    StandardName = 'Pacific Standard Time'
                }
            }

            It 'Returns "Pacific Standard Time"' {
                Get-TimeZoneId | Should -Be 'Pacific Standard Time'
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Get-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1
            }
        }

        Context '"Get-TimeZone" not available and current timezone is set to "Russia TZ 11 Standard Time"' {
            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Get-TimeZone'
            }

            Mock -CommandName Get-CimInstance -MockWith {
                @{
                    StandardName = 'Russia TZ 11 Standard Time'
                }
            }

            It 'Returns "Russia Time Zone 11"' {
                Get-TimeZoneId | Should -Be 'Russia Time Zone 11'
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Get-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1
            }
        }

        Context '"Get-TimeZone" available and current timezone is set to "Pacific Standard Time"' {
            function Get-TimeZone
            {
            }

            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Get-TimeZone'
            } -MockWith {
                'Get-TimeZone'
            }

            Mock `
                -CommandName Get-TimeZone `
                -MockWith {
                @{
                    StandardName = 'Pacific Standard Time'
                }
            }

            It 'Returns "Pacific Standard Time"' {
                Get-TimeZoneId | Should -Be 'Pacific Standard Time'
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Get-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName Get-TimeZone -Exactly -Times 1
            }
        }
    }

    Describe 'ComputerManagementDsc.Common\Test-TimezoneId' {
        Mock -CommandName Get-TimeZoneId -MockWith {
            'Russia Time Zone 11'
        }

        Context 'current timezone matches desired timezone' {
            It 'Should return $true' {
                Test-TimezoneId -TimeZoneId 'Russia Time Zone 11' | Should -BeTrue
            }
        }

        Context 'current timezone does not match desired timezone' {
            It 'Should return $false' {
                Test-TimezoneId -TimeZoneId 'GMT Standard Time' | Should -BeFalse
            }
        }
    }

    Describe 'ComputerManagementDsc.Common\Set-TimeZoneId' {
        Context '"Set-TimeZone" and "Add-Type" is not available, Tzutil Returns 0' {
            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Add-Type'
            }

            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Set-TimeZone'
            }

            Mock -CommandName 'TzUtil.exe' -MockWith {
                $global:LASTEXITCODE = 0
                return 'OK'
            }

            Mock -CommandName Add-Type

            It 'Should not throw an exception' {
                { Set-TimeZoneId -TimezoneId 'Eastern Standard Time' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Add-Type'
                } -Exactly -Times 1

                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Set-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName TzUtil.exe -Exactly -Times 1
                Assert-MockCalled -CommandName Add-Type -Exactly -Times 0
            }
        }

        Context '"Set-TimeZone" is not available but "Add-Type" is available' {
            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Add-Type'
            } -MockWith {
                'Add-Type'
            }

            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Set-TimeZone'
            }

            Mock -CommandName 'TzUtil.exe' -MockWith {
                $global:LASTEXITCODE = 0
                return 'OK'
            }

            Mock -CommandName Add-Type
            Mock -CommandName Set-TimeZoneUsingDotNet

            It 'Should not throw an exception' {
                { Set-TimeZoneId -TimezoneId 'Eastern Standard Time' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Add-Type'
                } -Exactly -Times 1

                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Set-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName TzUtil.exe -Exactly -Times 0
                Assert-MockCalled -CommandName Add-Type -Exactly -Times 0
                Assert-MockCalled -CommandName Set-TimeZoneUsingDotNet -Exactly -Times 1
            }
        }

        Context '"Set-TimeZone" is available' {
            function Set-TimeZone
            {
                param
                (
                    [System.String]
                    $id
                )
            }

            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Add-Type'
            }

            Mock `
                -CommandName Get-Command `
                -ParameterFilter {
                $Name -eq 'Set-TimeZone'
            } -MockWith {
                'Set-TimeZone'
            }

            Mock -CommandName Set-TimeZone

            It 'Should not throw an exception' {
                { Set-TimeZoneId -TimezoneId 'Eastern Standard Time' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Add-Type'
                } -Exactly -Times 0

                Assert-MockCalled `
                    -CommandName Get-Command `
                    -ParameterFilter {
                    $Name -eq 'Set-TimeZone'
                } -Exactly -Times 1

                Assert-MockCalled -CommandName Set-TimeZone -Exactly -Times 1
            }
        }
    }

    Describe 'ComputerManagementDsc.Common\Get-PowerPlan' {
        $mockBalancedPowerPlan = @{
            FriendlyName = 'Balanced'
            Guid         = [System.Guid]'381b4222-f694-41f0-9685-ff5bb260df2e'
        }

        $mockHighPerformancePowerPlan = @{
            'FriendlyName' = 'High performance'
            'Guid'         = [System.Guid]'8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
        }

        $mockPowerSaverPowerPlan = @{
            'FriendlyName' = 'Power saver'
            'Guid'         = [System.Guid]'a1841308-3541-4fab-bc81-f71556f20b4a'
        }

        Context 'Only one power plan is available and "PowerPlan" parameter is not specified' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return $mockBalancedPowerPlan
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return exactly one hashtable' {
                $result = Get-PowerPlan
                $result | Should -BeOfType [System.Collections.Hashtable]
                $result | Should -HaveCount 1
            }

        }

        Context 'Only one power plan is available and "PowerPlan" parameter is specified as Guid of the available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return $mockBalancedPowerPlan
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan '381b4222-f694-41f0-9685-ff5bb260df2e' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return a hashtable with the name and guid fo the power plan' {
                $result = Get-PowerPlan -PowerPlan '381b4222-f694-41f0-9685-ff5bb260df2e'
                $result | Should -BeOfType [System.Collections.Hashtable]
                $result | Should -HaveCount 1
                $result.FriendlyName | Should -Be 'Balanced'
                $result.guid | Should -Be '381b4222-f694-41f0-9685-ff5bb260df2e'
            }
        }

        Context 'Only one power plan is available and "PowerPlan" parameter is specified as Guid of a not available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return $mockBalancedPowerPlan
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return nothing' {
                $result = Get-PowerPlan -PowerPlan '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
                $result | Should -BeNullOrEmpty
            }
        }

        Context 'Only one power plan is available and "PowerPlan" parameter is specified as name of the available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return $mockBalancedPowerPlan
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan 'Balanced' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return a hashtable with the name and guid fo the power plan' {
                $result = Get-PowerPlan -PowerPlan 'Balanced'
                $result | Should -BeOfType [System.Collections.Hashtable]
                $result | Should -HaveCount 1
                $result.FriendlyName | Should -Be 'Balanced'
                $result.guid | Should -Be '381b4222-f694-41f0-9685-ff5bb260df2e'
            }
        }

        Context 'Only one power plan is available and "PowerPlan" parameter is specified as name of a not available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return $mockBalancedPowerPlan
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan 'High performance' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return nothing' {
                $result = Get-PowerPlan -PowerPlan 'High performance'
                $result | Should -BeNullOrEmpty
            }
        }

        Context 'Multiple power plans are available and "PowerPlan" parameter is not specified' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return @(
                    $mockBalancedPowerPlan
                    $mockHighPerformancePowerPlan
                    $mockPowerSaverPowerPlan
                )
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return an array with all available plans' {
                $result = Get-PowerPlan
                $result | Should -HaveCount 3
            }
        }

        Context 'Multiple power plans are available and "PowerPlan" parameter is specified as Guid of an available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return @(
                    $mockBalancedPowerPlan
                    $mockHighPerformancePowerPlan
                    $mockPowerSaverPowerPlan
                )
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan '381b4222-f694-41f0-9685-ff5bb260df2e' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return a hashtable with the name and guid fo the power plan' {
                $result = Get-PowerPlan -PowerPlan '381b4222-f694-41f0-9685-ff5bb260df2e'
                $result | Should -BeOfType [System.Collections.Hashtable]
                $result | Should -HaveCount 1
                $result.FriendlyName | Should -Be 'Balanced'
                $result.guid | Should -Be '381b4222-f694-41f0-9685-ff5bb260df2e'
            }
        }

        Context 'Multiple power plans are available and "PowerPlan" parameter is specified as Guid of a not available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return @(
                    $mockBalancedPowerPlan
                    $mockHighPerformancePowerPlan
                    $mockPowerSaverPowerPlan
                )
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan '9c5e7fda-e8bf-4a96-9a85-a7e23a8c635c' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return nothing' {
                $result = Get-PowerPlan -PowerPlan '9c5e7fda-e8bf-4a96-9a85-a7e23a8c635c'
                $result | Should -BeNullOrEmpty
            }
        }

        Context 'Multiple power plans are available and "PowerPlan" parameter is specified as name of an available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return @(
                    $mockBalancedPowerPlan
                    $mockHighPerformancePowerPlan
                    $mockPowerSaverPowerPlan
                )
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan 'High performance' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return a hashtable with the name and guid fo the power plan' {
                $result = Get-PowerPlan -PowerPlan 'High performance'
                $result | Should -BeOfType [System.Collections.Hashtable]
                $result | Should -HaveCount 1
                $result.FriendlyName | Should -Be 'High performance'
                $result.guid | Should -Be '8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c'
            }
        }

        Context 'Multiple power plans are available and "PowerPlan" parameter is specified as name of a not available plan' {
            Mock `
                -CommandName Get-PowerPlanUsingPInvoke `
                -MockWith {
                return @(
                    $mockBalancedPowerPlan
                    $mockHighPerformancePowerPlan
                    $mockPowerSaverPowerPlan
                )
            }

            It 'Should not throw an exception' {
                { Get-PowerPlan -PowerPlan 'Some unavailable plan' } | Should -Not -Throw
            }

            It 'Should call expected mocks' {
                Assert-MockCalled `
                    -CommandName Get-PowerPlanUsingPInvoke `
                    -Exactly -Times 1
            }

            It 'Should return nothing' {
                $result = Get-PowerPlan -PowerPlan 'Some unavailable plan'
                $result | Should -BeNullOrEmpty
            }
        }
    }

    Describe 'ComputerManagementDsc.Common\Get-RegistryPropertyValue' -Tag 'GetRegistryPropertyValue' {
        BeforeAll {
            $mockWrongRegistryPath = 'HKLM:\SOFTWARE\AnyPath'
            $mockCorrectRegistryPath = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\RS'
            $mockPropertyName = 'InstanceName'
            $mockPropertyValue = 'AnyValue'
        }

        Context 'When there are no properties in the registry' {
            BeforeAll {
                Mock -CommandName Get-ItemProperty -MockWith {
                    return @{
                        'UnknownProperty' = $mockPropertyValue
                    }
                }
            }

            It 'Should return $null' {
                $result = Get-RegistryPropertyValue -Path $mockWrongRegistryPath -Name $mockPropertyName
                $result | Should -BeNullOrEmpty

                Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 -Scope It
            }
        }

        Context 'When the call to Get-ItemProperty throws an error (i.e. when the path does not exist)' {
            BeforeAll {
                Mock -CommandName Get-ItemProperty -MockWith {
                    throw 'mocked error'
                }
            }

            It 'Should not throw an error, but return $null' {
                $result = Get-RegistryPropertyValue -Path $mockWrongRegistryPath -Name $mockPropertyName
                $result | Should -BeNullOrEmpty

                Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 -Scope It
            }
        }

        Context 'When there is a property present in the registry' {
            BeforeAll {
                $mockGetItemProperty_InstanceName = {
                    return @{
                        $mockPropertyName = $mockPropertyValue
                    }
                }

                $mockGetItemProperty_InstanceName_ParameterFilter = {
                    $Path -eq $mockCorrectRegistryPath `
                    -and $Name -eq $mockPropertyName
                }

                Mock -CommandName Get-ItemProperty `
                    -MockWith $mockGetItemProperty_InstanceName `
                    -ParameterFilter $mockGetItemProperty_InstanceName_ParameterFilter
            }

            It 'Should return the correct value' {
                $result = Get-RegistryPropertyValue -Path $mockCorrectRegistryPath -Name $mockPropertyName
                $result | Should -Be $mockPropertyValue

                Assert-MockCalled -CommandName Get-ItemProperty -Exactly -Times 1 -Scope It
            }
        }
    }
}


text:
package org.jtwig.parser.parboiled.node;

import org.jtwig.model.tree.OutputNode;
import org.jtwig.parser.parboiled.ParserContext;
import org.jtwig.parser.parboiled.base.LimitsParser;
import org.jtwig.parser.parboiled.base.PositionTrackerParser;
import org.jtwig.parser.parboiled.base.SpacingParser;
import org.jtwig.parser.parboiled.expression.AnyExpressionParser;
import org.parboiled.Rule;

public class OutputNodeParser extends NodeParser<OutputNode> {
    public OutputNodeParser(ParserContext context) {
        super(OutputNodeParser.class, context);
    }

    @Override
    public Rule NodeRule() {
        PositionTrackerParser positionTrackerParser = parserContext().parser(PositionTrackerParser.class);
        LimitsParser limitsParser = parserContext().parser(LimitsParser.class);
        SpacingParser spacingParser = parserContext().parser(SpacingParser.class);
        AnyExpressionParser anyExpressionParser = parserContext().parser(AnyExpressionParser.class);
        return Sequence(
                positionTrackerParser.PushPosition(),

                limitsParser.startOutput(),
                spacingParser.Spacing(),
                Mandatory(anyExpressionParser.ExpressionRule(), "Missing or invalid output expression"),
                spacingParser.Spacing(),

                Mandatory(limitsParser.endOutput(), "Expecting end of output code island"),

                push(new OutputNode(
                        positionTrackerParser.pop(1),
                        anyExpressionParser.pop()
                ))
        );
    }
}


text:
<?php

namespace BearCMS\Internal\Data2;

use BearCMS\Internal;

/**
 * @internal
 * @codeCoverageIgnore
 */
class BlogCategories
{

    /**
     *
     * @param string $rawData
     * @return \BearCMS\Internal\Data2\BlogCategory
     */
    private function makeBlogCategoryFromRawData(string $rawData): \BearCMS\Internal\Data2\BlogCategory
    {
        $rawData = json_decode($rawData, true);
        $blogCategory = new Internal\Data2\BlogCategory();
        $properties = ['id', 'name', 'status'];
        foreach ($properties as $property) {
            if (array_key_exists($property, $rawData)) {
                $blogCategory->$property = $rawData[$property];
            }
        }
        return $blogCategory;
    }

    /**
     * Retrieves information about the page specified
     *
     * @param string $id The page ID
     * @return \IvoPetkov\DataObject|null The page data or null if page not found
     * @throws \InvalidArgumentException
     */
    public function get(string $id): ?\BearCMS\Internal\Data2\BlogCategory
    {
        $data = Internal\Data::getValue('bearcms/blog/categories/category/' . md5($id) . '.json');
        if ($data !== null) {
            return $this->makeBlogCategoryFromRawData($data);
        }
        return null;
    }

    /**
     * Retrieves a list of all pages
     *
     * @return \IvoPetkov\DataList|\BearCMS\Internal\Data2\BlogCategory[] List containing all pages data
     */
    public function getList(): \IvoPetkov\DataList
    {
        $cacheKey = 'blog_categories_list';
        if (!isset(Internal\Data::$cache[$cacheKey])) {
            $list = Internal\Data::getList('bearcms/blog/categories/category/');
            array_walk($list, function (&$value) {
                $value = $this->makeBlogCategoryFromRawData($value);
            });

            $structureData = Internal\Data::getValue('bearcms/blog/categories/structure.json');
            $structureData = $structureData === null ? [] : json_decode($structureData, true);
            $flattenStructureData = [];
            foreach ($structureData as $itemData) {
                $flattenStructureData[] = $itemData['id'];
            }
            $flattenStructureData = array_flip($flattenStructureData);
            usort($list, function ($object1, $object2) use ($flattenStructureData) {
                return $flattenStructureData[$object1->id] - $flattenStructureData[$object2->id];
            });
            unset($flattenStructureData);
            Internal\Data::$cache[$cacheKey] = $list;
            unset($list);
        }
        return new \IvoPetkov\DataList(Internal\Data::$cache[$cacheKey]);
    }
}


text:
package ftp.broker;

import com.nurkiewicz.jdbcrepository.JdbcRepository;
import com.nurkiewicz.jdbcrepository.RowUnmapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

@Repository
public class PersistableServiceInstanceBindingRepository
        extends JdbcRepository<PersistableServiceInstanceBinding, String> {

    private static final String SERVICE_INSTANCE_BINDING_ID_NAME = "SERVICE_INSTANCE_BINDING_ID";

    private static final String SERVICE_INSTANCE_TABLE_NAME = "SERVICE_INSTANCE_BINDING";

    private static final RowUnmapper<PersistableServiceInstanceBinding> ROW_UNMAPPER =
            sib -> {
                Map<String, Object> map = new HashMap<>();
                map.put(SERVICE_INSTANCE_BINDING_ID_NAME, sib.getId());
                map.put("SERVICE_INSTANCE_ID", sib.getServiceInstanceId());
                map.put("URI", String.class.cast(sib.getCredentials().getOrDefault("uri", null)));
                map.put("SYSLOG_DRAIN_URL", sib.getSyslogDrainUrl());
                map.put("APP_GUID", sib.getAppGuid());
                return map;
            };

    private static final RowMapper<PersistableServiceInstanceBinding> ROW_MAPPER =
            (rs, i) -> new PersistableServiceInstanceBinding(
                    rs.getString(SERVICE_INSTANCE_BINDING_ID_NAME),
                    rs.getString("SERVICE_INSTANCE_ID"),
                    rs.getString("URI"),
                    rs.getString("SYSLOG_DRAIN_URL"),
                    rs.getString("APP_GUID"));

    public PersistableServiceInstanceBindingRepository() {
        super(ROW_MAPPER, ROW_UNMAPPER, SERVICE_INSTANCE_TABLE_NAME, SERVICE_INSTANCE_BINDING_ID_NAME);
    }

    @Override
    protected <S extends PersistableServiceInstanceBinding> S postCreate(S entity, Number generatedId) {
        entity.setPersisted(true);
        return entity;
    }

    @Override
    protected <S extends PersistableServiceInstanceBinding> S postUpdate(S entity) {
        entity.setPersisted(true);
        return entity;
    }
}


text:
var fs = require('fs');
var EventEmitter = require('events').EventEmitter;
var _ = require('underscore');
var debug = require('debug')('launchpad:remote-preview');

module.exports = function(configuration, callback) {
	if(!callback) {
		callback = configuration;
	}

	var api = function (url, options, callback) {
		var path = options.file;
		fs.writeFile(path, url, function(error) {
      debug('Wrote URL ' + url + ' to file ' + path);
			var emitter = new EventEmitter();
			_.extend(emitter, {
				id: path,
				stop: function(callback) {
          debug('Stopping remote-preview');
					callback(null, this);
				},
				status: function(callback) {
					// TODO fs.stat
					callback(null, path);
				}
			});
			callback(error, emitter);
		});
	};

	callback(null, api);
};


text:
//CPP:Qss/samplehold.cpp
#if !defined samplehold_h
#define samplehold_h

#include "simulator.h"
#include "event.h"
#include "stdarg.h"

#include "qss/qsstools.h"

class samplehold: public Simulator {
//parameters
double T,phi;

//states
double sigma;
double u[10];
int order;

//output
double y[10];

public:
	samplehold(const char *n): Simulator(n) {};
	void init(double, ...);
	double ta(double t);
	void dint(double);
	void dext(Event , double );
	Event lambda(double);
	void exit();
};
#endif


text:
class CreateRagnarok2Dungeons < ActiveRecord::Migration
  def change
    create_table :ragnarok2_dungeons do |t|

      t.integer :dungeon_id, :default=>0, :null=>false
      t.integer :map_index1, :limit => 8
      t.integer :map_index2, :limit => 8
      t.integer :map_index3, :limit => 8
      t.integer :dungeon_group_id
      t.string :name
      t.integer :map_level
      t.string :bind_value
      t.integer :map_min_level
      t.integer :map_max_level
      t.integer :quest_id, :limit => 8
      t.string :map_description
      t.integer :position_id

      t.timestamps
    end
    add_index :ragnarok2_dungeons, :dungeon_id, :unique => true
    add_index :ragnarok2_dungeons, :quest_id
  end
end