text:
package xyz.thepathfinder.chimneyswap;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;

import xyz.thepathfinder.chimneyswap.R;
import xyz.thepathfinder.chimneyswap.TradeChimneyActivity;

public class SelectionActivity extends AppCompatActivity {

    private final String TAG = "SelectionActivity";
    public static String cluster;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selection);
        RadioButton terreHauteButton = (RadioButton) this.findViewById(R.id.terre_haute);
        terreHauteButton.setChecked(true);
        SelectionActivity.cluster = "/root";
    }

    public void onClickEmployee(View view) {
        Intent intent = new Intent(this, EmployeeActivity.class);
        startActivity(intent);
    }

    public void onClickCustomer(View view) {
        Intent intent = new Intent(this, TradeChimneyActivity.class);
        startActivity(intent);
    }

    public void onClickChangeCluster(View view) {
        boolean checked = ((RadioButton) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.midwest:
                if (checked) {
                    SelectionActivity.cluster = "/root";
                }
                break;
            case R.id.terre_haute:
                if (checked) {
                    SelectionActivity.cluster = "/root";
                }
                break;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import url
from src.accounts.views import (
    logout_view,
    settings, password,
    register_view
)
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', logout_view, name='logout'),
    url(r'^register/', register_view, name='register'),
    url(r'^settings/$', settings, name='settings'),
    url(r'^settings/password/$', password, name='password'),
]


text:
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/redshift/model/Cluster.h>
#include <aws/redshift/model/ResponseMetadata.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{
  class AWS_REDSHIFT_API DeleteClusterResult
  {
  public:
    DeleteClusterResult();
    DeleteClusterResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DeleteClusterResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    inline const Cluster& GetCluster() const{ return m_cluster; }

    inline void SetCluster(const Cluster& value) { m_cluster = value; }

    inline void SetCluster(Cluster&& value) { m_cluster = std::move(value); }

    inline DeleteClusterResult& WithCluster(const Cluster& value) { SetCluster(value); return *this;}

    inline DeleteClusterResult& WithCluster(Cluster&& value) { SetCluster(std::move(value)); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DeleteClusterResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DeleteClusterResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    Cluster m_cluster;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace Redshift
} // namespace Aws


text:
package br.com.cotacaoDeMoedas.model;

import br.com.cotacaoDeMoedas.view.Observer;

public interface Subject {
	public void registerObserver(Observer o);
	public void removeObserver(Observer o);
	public void notifyObservers();
}


text:
package org.kie.dmn.model.v1_1;

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

public class DecisionTable extends Expression {

    private List<InputClause> input;
    private List<OutputClause> output;
    private List<DecisionRule> rule;
    private HitPolicy hitPolicy;
    private BuiltinAggregator aggregation;
    private DecisionTableOrientation preferredOrientation;
    private String outputLabel;

    public List<InputClause> getInput() {
        if ( input == null ) {
            input = new ArrayList<>();
        }
        return this.input;
    }

    public List<OutputClause> getOutput() {
        if ( output == null ) {
            output = new ArrayList<>();
        }
        return this.output;
    }

    public List<DecisionRule> getRule() {
        if ( rule == null ) {
            rule = new ArrayList<>();
        }
        return this.rule;
    }

    public HitPolicy getHitPolicy() {
        if ( hitPolicy == null ) {
            return HitPolicy.UNIQUE;
        } else {
            return hitPolicy;
        }
    }

    public void setHitPolicy( final HitPolicy value ) {
        this.hitPolicy = value;
    }

    public BuiltinAggregator getAggregation() {
        return aggregation;
    }

    public void setAggregation( final BuiltinAggregator value ) {
        this.aggregation = value;
    }

    public DecisionTableOrientation getPreferredOrientation() {
        if ( preferredOrientation == null ) {
            return DecisionTableOrientation.RULE_AS_ROW;
        } else {
            return preferredOrientation;
        }
    }

    public void setPreferredOrientation( final DecisionTableOrientation value ) {
        this.preferredOrientation = value;
    }

    public String getOutputLabel() {
        return outputLabel;
    }

    public void setOutputLabel( final String value ) {
        this.outputLabel = value;
    }

}


text:
//
//  NSDate+gyh.m
//  微博
//
//  Created by gyh on 15-4-18.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "NSDate+gyh.h"

@implementation NSDate (gyh)
/**
 *  是否为今天
 */
-(BOOL)isToday
{

    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear;

    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];

    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];

    return(selfCmps.year == nowCmps.year) && (selfCmps.month == nowCmps.month) && (selfCmps.day == nowCmps.day);
}

/**
 *  是否为昨天
 */
-(BOOL)isYesterday
{

    NSDate *nowDate = [[NSDate date]dateWithYMD];
    NSDate *selfDate = [self dateWithYMD];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];

    return cmps.day == 1;
}

-(NSDate *)dateWithYMD
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = @"yyyy-MM-dd";
    NSString *str = [fmt stringFromDate:self];
    return [fmt dateFromString:str];
}

/**
 *  是否为今年
 */
-(BOOL)isThisYear
{

    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitYear;

    // 1.获得当前时间的年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];

    // 2.获得self的年月日
    NSDateComponents *selfCmps = [calendar components:unit fromDate:self];

    return nowCmps.year == selfCmps.year;
}

- (NSDateComponents *)deltaWithNow
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];
}

/**
 *  返回当前时间
 */
+ (NSString *)currentTime
{
    NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
    fmt.dateFormat = @"MM-dd HH:mm";
    NSString *str = [fmt stringFromDate:[NSDate date]];
    return str;
}

@end


text:
Package: @supercollider/osc

asNTPTimeTag(time: OSCTimeType): NTPTimeTag


text:
package cloud.resources;

import cloud.DecoratedId;
import de.uniulm.omi.cloudiator.sword.api.domain.Resource;
import de.uniulm.omi.cloudiator.sword.api.util.IdScopedByLocation;
import de.uniulm.omi.cloudiator.sword.core.util.IdScopeByLocations;

/**
 * Created by daniel on 20.05.15.
 */
public class AbstractLocationScopedResource<T extends Resource>
    extends AbstractCredentialScopedResource<T>
    implements CredentialScoped, LocationScoped, RemoteResource {

    private final String location;
    private final String id;

    public AbstractLocationScopedResource(T resource, String cloud, String credential) {
        super(resource, cloud, credential);
        IdScopedByLocation idScopedByLocation = IdScopeByLocations.from(resource.id());
        this.id = idScopedByLocation.getId();
        this.location = idScopedByLocation.getLocationId();
    }

    @Override public String id() {
        return DecoratedId.of(credential(), cloud(), location, id).colosseumId();
    }

    @Override public String location() {
        return DecoratedId.of(credential(), cloud(), location, id).colosseumLocation();
    }
}


text:
<?php

namespace yii\base;

/**
 * InvalidParamException represents an exception caused by invalid parameters passed to a method.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class InvalidParamException extends Exception
{
	/**
	 * @return string the user-friendly name of this exception
	 */
	public function getName()
	{
		return \Yii::t('yii|Invalid Parameter');
	}
}


text:
namespace OpenApoc
{
const UString existingSaveItemId = "EXISTING_SAVE_SLOT";
const UString newSaveItemId = "NEW_SAVE_SLOT";

SaveMenu::SaveMenu(SaveMenuAction saveMenuAction, sp<GameState> state)
    : Stage(), menuform(ui().getForm("savemenu")), currentState(state),
      currentAction(saveMenuAction)
{
	activeTextEdit = nullptr;
}

SaveMenu::~SaveMenu() = default;

void SaveMenu::begin()
{
	if (currentState)
	{
		menuform->findControlTyped<Label>("TEXT_FUNDS")->setText(currentState->getPlayerBalance());
	}

	auto saveListBox = menuform->findControlTyped<ListBox>("LISTBOX_OPTIONS");

	UString titleLabelName;
	bool newItemSlotVisible = false;
	bool showAutoSaves = false;
	switch (currentAction)
	{
		case SaveMenuAction::LoadNewGame:
		case SaveMenuAction::Load:
			titleLabelName = "LABEL_LOADGAME";
			showAutoSaves = true;
			break;
		case SaveMenuAction::Save:
			titleLabelName = "LABEL_SAVEGAME";
			newItemSlotVisible = true;
			break;
		case SaveMenuAction::Delete:
			titleLabelName = "LABEL_DELETEGAME";
			break;
	}

	if (!titleLabelName.empty())
	{
		auto label = menuform->findControlTyped<Label>(titleLabelName);
		if (label)
		{
			label->setVisible(true);
		}
	}

	if (newItemSlotVisible == true)
	{
		auto newItemSlot = saveListBox->findControl(newSaveItemId);
		if (newItemSlot != nullptr)
		{
			newItemSlot->setVisible(true);
		}
	}

	// load menu items
	auto saves = saveManager.getSaveList();
	auto existingSlotControl = saveListBox->findControl(existingSaveItemId);
	if (existingSlotControl != nullptr)
	{
		for (auto it = saves.begin(); it != saves.end(); ++it)
		{
			if (it->getType() != SaveType::Manual && !showAutoSaves)
			{ // skip quicksave and autosave on save screen
				continue;
			}

			auto newControl = existingSlotControl->copyTo(saveListBox);
			newControl->setData(mksp<SaveMetadata>(*it));
			auto nameLabel = newControl->findControlTyped<Label>("LABEL_NAME");
			if (nameLabel != nullptr)
			{
				nameLabel->setText(it->getName());
			}

			auto saveTimeLabel = newControl->findControlTyped<Label>("LABEL_TIME");
			if (saveTimeLabel != nullptr)
			{
				std::time_t timestamp = it->getCreationDate();
				struct tm *tminfo = std::localtime(&timestamp);
				std::stringstream ss;
				if (timestamp != 0 && tminfo != nullptr)
				{
					char temp_time[1024];
					strftime(temp_time, sizeof(temp_time), "%d/%m/%y %T", tminfo);
					ss << temp_time;
				}
				saveTimeLabel->setText(ss.str());
			}

			GameTime gameTime(it->getGameTicks());
			auto gameDayLabel = newControl->findControlTyped<Label>("LABEL_INGAME_DAY");
			if (gameDayLabel != nullptr)
			{
				if (it->getGameTicks() == 0 && gameTime.getDay() == 0)
				{
					gameDayLabel->setText("");
				}
				else
				{
					gameDayLabel->setText("Day " + std::to_string(gameTime.getDay()));
				}
			}
			auto gameTimeLabel = newControl->findControlTyped<Label>("LABEL_INGAME_TIME");
			if (gameTimeLabel != nullptr)
			{
				if (it->getGameTicks() == 0 && gameTime.getDay() == 0)
				{
					gameTimeLabel->setText("");
				}
				else
				{
					gameTimeLabel->setText(gameTime.getLongTimeString());
				}
			}

			auto difficultyLabel = newControl->findControlTyped<Label>("LABEL_DIFFICULTY");
			if (difficultyLabel != nullptr)
			{
				difficultyLabel->setText(it->getDifficulty());
			}

			auto saveNameTextEdit = newControl->findControlTyped<TextEdit>("TEXTEDIT_SAVE_NAME");
			if (saveNameTextEdit != nullptr)
			{
				saveNameTextEdit->setVisible(false);
			}
		}
		existingSlotControl->setVisible(false);
	}
}

void SaveMenu::pause() {}

void SaveMenu::resume() {}

void SaveMenu::finish() {}

void SaveMenu::clearTextEdit(sp<TextEdit> textEdit)
{
	auto e = OpenApoc::FormsEvent();
	e.forms().RaisedBy = textEdit->shared_from_this();
	e.forms().EventFlag = FormEventType::LostFocus;
	textEdit->eventOccured(&e);

	// reset text
	textEdit->setVisible(false);
	auto listItem = textEdit->getParent();
	if (listItem)
	{
		auto nameLabel = listItem->findControlTyped<Label>("LABEL_NAME");
		if (nameLabel)
		{
			nameLabel->setVisible(true);
		}
	}
	activeTextEdit = nullptr;
}

void SaveMenu::beginEditing(sp<TextEdit> textEdit, sp<TextEdit> activeTextEdit)
{
	if (activeTextEdit != nullptr)
	{
		clearTextEdit(activeTextEdit);
	}

	auto e = OpenApoc::FormsEvent();
	e.forms().RaisedBy = textEdit->shared_from_this();
	e.forms().EventFlag = FormEventType::MouseClick;
	textEdit->eventOccured(&e);
	textEdit->setVisible(true);
	textEdit->setAllowedCharacters(
	    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,. -_");
	textEdit->setTextMaxSize(32);
	auto listItem = textEdit->getParent();
	if (listItem)
	{
		auto nameLabel = listItem->findControlTyped<Label>("LABEL_NAME");
		if (nameLabel)
		{
			nameLabel->setVisible(false);
			if (nameLabel->getParent() && nameLabel->getParent()->Name != "NEW_SAVE_SLOT")
			{
				textEdit->setText(nameLabel->getText());
			}
			else
			{
				textEdit->setText("");
			}
		}
	}
}

void SaveMenu::loadWithWarning(sp<Control> parent)
{
	if (parent->Name == existingSaveItemId)
	{
		sp<SaveMetadata> slot = parent->getData<SaveMetadata>();
		if (slot != nullptr)
		{
			std::function<void()> onSuccess = std::function<void()>([this, slot] {
				auto state = mksp<GameState>();
				auto task = saveManager.loadGame(*slot, state);
				fw().stageQueueCommand(
				    {StageCmd::Command::PUSH,
				     mksp<LoadingScreen>(nullptr, std::move(task), [state]() -> sp<Stage> {
					     if (state->current_battle)
					     {
						     return mksp<BattleView>(state);
					     }
					     else
					     {
						     return mksp<CityView>(state);
					     }
				     })});
			});
			sp<MessageBox> messageBox = mksp<MessageBox>(
			    MessageBox("Load game", "Unsaved progress will be lost. Continue?",
			               MessageBox::ButtonOptions::YesNo, std::move(onSuccess), nullptr));

			fw().stageQueueCommand({StageCmd::Command::PUSH, messageBox});
		}
	}
}

void SaveMenu::tryToLoadGame(sp<Control> slotControl)
{
	if (slotControl->Name == existingSaveItemId)
	{
		sp<SaveMetadata> slot = slotControl->getData<SaveMetadata>();
		if (slot != nullptr)
		{
			auto state = mksp<GameState>();
			auto task = saveManager.loadGame(*slot, state);
			fw().stageQueueCommand(
			    {StageCmd::Command::PUSH,
			     mksp<LoadingScreen>(nullptr, std::move(task), [state]() -> sp<Stage> {
				     if (state->current_battle)
				     {
					     return mksp<BattleView>(state);
				     }
				     else
				     {
					     return mksp<CityView>(state);
				     }
			     })});
		}
	}
}

void SaveMenu::tryToSaveGame(const UString &saveName, sp<Control> parent)
{
	if (parent->Name == newSaveItemId)
	{
		if (saveManager.newSaveGame(saveName, currentState))
		{
			fw().stageQueueCommand({StageCmd::Command::POP});
		}
		else
		{
			clearTextEdit(activeTextEdit);
		}
	}
	else
	{
		sp<SaveMetadata> slot = parent->getData<SaveMetadata>();
		std::function<void()> onSuccess = std::function<void()>([this, slot, saveName] {
			if (saveManager.overrideGame(*slot, saveName, currentState))
			{
				fw().stageQueueCommand({StageCmd::Command::POP});
			}
			else
			{
				clearTextEdit(activeTextEdit);
			}
		});
		std::function<void()> onCancel =
		    std::function<void()>([this] { clearTextEdit(activeTextEdit); });
		sp<MessageBox> messageBox = mksp<MessageBox>(MessageBox(
		    "Override saved game", "Do you really want to override " + slot->getName() + "?",
		    MessageBox::ButtonOptions::YesNo, std::move(onSuccess), std::move(onCancel)));

		fw().stageQueueCommand({StageCmd::Command::PUSH, messageBox});
	}
}

void SaveMenu::tryToDeleteSavedGame(sp<Control> &slotControl)
{
	sp<SaveMetadata> slot = slotControl->getData<SaveMetadata>();
	std::function<void()> onSuccess = std::function<void()>([this, slotControl, slot] {
		if (saveManager.deleteGame(slot))
		{
			// no way to pop
			slotControl->setVisible(false);
		}
	});
	sp<MessageBox> messageBox = mksp<MessageBox>(
	    MessageBox("Delete saved game", "Do you really want to delete " + slot->getName() + "?",
	               MessageBox::ButtonOptions::YesNo, std::move(onSuccess), nullptr));

	fw().stageQueueCommand({StageCmd::Command::PUSH, messageBox});
}

void SaveMenu::eventOccurred(Event *e)
{
	menuform->eventOccured(e);

	if (e->type() == EVENT_KEY_DOWN)
	{
		if (activeTextEdit && activeTextEdit->isFocused())
			return;
		if (e->keyboard().KeyCode == SDLK_ESCAPE || e->keyboard().KeyCode == SDLK_RETURN ||
		    e->keyboard().KeyCode == SDLK_KP_ENTER)
		{
			menuform->findControl("BUTTON_QUIT")->click();
			return;
		}
	}

	if (e->type() == EVENT_FORM_INTERACTION)
	{
		switch (e->forms().EventFlag)
		{
			case FormEventType::ButtonClick:
				if (e->forms().RaisedBy->Name == "BUTTON_QUIT")
				{
					fw().stageQueueCommand({StageCmd::Command::POP});
				}
				else
				{
					sp<Control> slotControl;
					switch (currentAction)
					{
						case SaveMenuAction::LoadNewGame:
							slotControl = e->forms().RaisedBy->getParent();
							if (slotControl)
							{
								tryToLoadGame(slotControl);
							}
							break;
						case SaveMenuAction::Load:
							slotControl = e->forms().RaisedBy->getParent();
							if (slotControl)
							{
								loadWithWarning(slotControl);
							}
							break;
						case SaveMenuAction::Save:
							slotControl = e->forms().RaisedBy->getParent();
							if (slotControl)
							{
								auto nameEdit =
								    slotControl->findControlTyped<TextEdit>("TEXTEDIT_SAVE_NAME");
								if (nameEdit && nameEdit != activeTextEdit)
								{
									beginEditing(nameEdit, activeTextEdit);
									activeTextEdit = nameEdit;
								}
							}
							break;
						case SaveMenuAction::Delete:
							slotControl = e->forms().RaisedBy->getParent();
							if (slotControl)
							{
								tryToDeleteSavedGame(slotControl);
							}
							break;
					}
				}
				break;
			case FormEventType::TextEditFinish:
			{
				sp<TextEdit> textEdit = std::static_pointer_cast<TextEdit>(e->forms().RaisedBy);
				auto slotControl = e->forms().RaisedBy->getParent();
				if (!slotControl || !textEdit || (textEdit != activeTextEdit))
				{
					return;
				}

				tryToSaveGame(textEdit->getText(), slotControl);
				break;
			}
			default:
				break;
		}
	}
}

void SaveMenu::update() { menuform->update(); }

void SaveMenu::render()
{
	fw().stageGetPrevious(this->shared_from_this())->render();
	fw().renderer->drawFilledRect(Vec2<float>(0, 0),
	                              Vec2<float>(fw().displayGetWidth(), fw().displayGetHeight()),
	                              Colour(0, 0, 0, 128));
	menuform->render();
}

bool SaveMenu::isTransition() { return false; }
}; // namespace OpenApoc


text:
<?php

namespace afpa\artistBundle\Twig\Extension;

class ajouterExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
			'ajouter' => new \Twig_Filter_Method($this, 'nouvelle_valeur')
        );
    }

    public function nouvelle_valeur($value)
    {
        if ($value<=90)
		{
        $value += 10;
		}
	    else $value=100;
        return $value;
    }

    public function getName()
    {
        return 'ajouter_extension';
    }

}


text:
//---------------------------------------------------------------------
// <copyright file="TestErrors.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Common
{
    #region Namespaces
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Test.Taupo.Astoria.Contracts.OData;
    using Microsoft.Test.Taupo.Common;
    #endregion Namespaces

    /// <summary>
    /// Helper class to create all interesting error payloads.
    /// </summary>
    public static class TestErrors
    {
        /// <summary>
        /// Creates a set of interesting error values.
        /// </summary>
        /// <param name="settings">The test descriptor settings to use.</param>
        /// <returns>List of test descriptors with interesting error values as payload.</returns>
        public static IEnumerable<PayloadTestDescriptor> CreateErrorTestDescriptors()
        {
            // error payloads
            IEnumerable<ODataErrorPayload> errors = new ODataErrorPayload[]
            {
                PayloadBuilder.Error().Code("ErrorCode"),
                PayloadBuilder.Error().Code("ErrorCode").Message("Error message"),
                PayloadBuilder.Error().Code("ErrorCode").Message(string.Empty),
                PayloadBuilder.Error().Message("Error message"),
                PayloadBuilder.Error().Message(string.Empty),
                PayloadBuilder.Error().Message("Error message"),
            };

            foreach (ODataErrorPayload errorPayload in errors)
            {
                yield return new PayloadTestDescriptor(){ PayloadElement = errorPayload.DeepCopy() };
            }

            // inner error payloads
            IEnumerable<ODataInternalExceptionPayload> innerErrors = new ODataInternalExceptionPayload[]
            {
                PayloadBuilder.InnerError(),
                PayloadBuilder.InnerError().Message("Inner error message"),
                PayloadBuilder.InnerError().StackTrace("Stack trace"),
                PayloadBuilder.InnerError().TypeName("Type name"),
                PayloadBuilder.InnerError().Message("Inner error message").StackTrace("Stack trace").TypeName("Type name"),
            };

            // create nested inner error payloads
            innerErrors = innerErrors.Concat(innerErrors.Select(inner =>
                PayloadBuilder.InnerError().Message("Outer inner error message").StackTrace("Stack trace").TypeName("Type name").InnerError(inner.DeepCopy())));

            // create a deeply nested inner error payload
            var deeplyNestedInnerError = PayloadBuilder.InnerError();
            foreach (var innerError in innerErrors)
            {
                var copyOfInnerError = innerError.DeepCopy();
                if (copyOfInnerError.InternalException == null)
                {
                    copyOfInnerError.InnerError(deeplyNestedInnerError);
                }
                else
                {
                    ExceptionUtilities.Assert(copyOfInnerError.InternalException.InternalException == null, "Did not expect inner error nesting beyond 2");
                    copyOfInnerError.InternalException.InnerError(deeplyNestedInnerError);
                }

                deeplyNestedInnerError = copyOfInnerError;
            }

            innerErrors = innerErrors.ConcatSingle(deeplyNestedInnerError);

            // put the inner errors into an empty error and all the other error payloads.
            foreach (ODataInternalExceptionPayload innerError in innerErrors)
            {
                yield return new PayloadTestDescriptor() { PayloadElement = PayloadBuilder.Error().InnerError(innerError.DeepCopy()) };

                foreach (ODataErrorPayload outerError in errors)
                {
                    yield return new PayloadTestDescriptor() { PayloadElement = outerError.DeepCopy().InnerError(innerError.DeepCopy()) };
                }
            }
        }
    }
}


text:
import iterFirst = require( '@stdlib/iter/first' );
import iterNone = require( '@stdlib/iter/none' );
import iterPipeline = require( './index' );

// TESTS //

// The function returns a pipeline function...
{
	iterPipeline( iterFirst, iterNone ); // $ExpectType PipelineFunction
	iterPipeline( [ iterFirst, iterNone ] ); // $ExpectType PipelineFunction
}

// The compiler throws an error if the function is provided a first argument which is not a function or an array of functions...
{
	iterPipeline( '5' ); // $ExpectError
	iterPipeline( 5 ); // $ExpectError
	iterPipeline( true ); // $ExpectError
	iterPipeline( false ); // $ExpectError
	iterPipeline( null ); // $ExpectError
	iterPipeline( undefined ); // $ExpectError
	iterPipeline( [ 1, 2, 3 ] ); // $ExpectError
	iterPipeline( {} ); // $ExpectError
}

// The compiler throws an error if the function is provided an argument which is not a function...
{
	iterPipeline( iterFirst, '5' ); // $ExpectError
	iterPipeline( iterFirst, true ); // $ExpectError
	iterPipeline( iterFirst, false ); // $ExpectError
	iterPipeline( iterFirst, null ); // $ExpectError
	iterPipeline( iterFirst, [] ); // $ExpectError
	iterPipeline( iterFirst, {} ); // $ExpectError
}

// The compiler throws an error if the function is provided insufficient arguments...
{
	iterPipeline(); // $ExpectError
}


text:
package it.unibz.krdb.obda.model;

/**
 * A common interface for TupleResultSet and GraphResultSet
 */
public interface ResultSet extends AutoCloseable{
	// NO-OP
}


text:
#include <linux/init.h>
#include <sound/core.h>

#include "seq_info.h"
#include "seq_clientmgr.h"
#include "seq_timer.h"

#ifdef CONFIG_PROC_FS
static struct snd_info_entry *queues_entry;
static struct snd_info_entry *clients_entry;
static struct snd_info_entry *timer_entry;

static struct snd_info_entry * __init
create_info_entry(char *name, void (*read)(struct snd_info_entry *,
					   struct snd_info_buffer *))
{
	struct snd_info_entry *entry;

	entry = snd_info_create_module_entry(THIS_MODULE, name, snd_seq_root);
	if (entry == NULL)
		return NULL;
	entry->content = SNDRV_INFO_CONTENT_TEXT;
	entry->c.text.read = read;
	if (snd_info_register(entry) < 0) {
		snd_info_free_entry(entry);
		return NULL;
	}
	return entry;
}

/* create all our /proc entries */
int __init snd_seq_info_init(void)
{
	queues_entry = create_info_entry("queues",
					 snd_seq_info_queues_read);
	clients_entry = create_info_entry("clients",
					  snd_seq_info_clients_read);
	timer_entry = create_info_entry("timer", snd_seq_info_timer_read);
	return 0;
}

int __exit snd_seq_info_done(void)
{
	snd_info_free_entry(queues_entry);
	snd_info_free_entry(clients_entry);
	snd_info_free_entry(timer_entry);
	return 0;
}
#endif


text:
FROM resin/rpi-raspbian:jessie

RUN	apt-get update \
	&& apt-get install libfontconfig

ARG	VERSION=3.1.1
ARG	VERSION_SUFFIX=1471857718

ADD	https://github.com/heziegl/rpi-grafana-build/raw/master/dist-$VERSION/grafana-$VERSION-$VERSION_SUFFIX.linux-arm.tar.gz /grafana.tar.gz

RUN	tar -xf /grafana.tar.gz \
	&& rm /grafana.tar.gz \
	&& mv /grafana-$VERSION-$VERSION_SUFFIX /grafana

ARG	PORT=3000

EXPOSE	$PORT

VOLUME  ["/data", "/etc/grafana"]
CMD     /grafana/bin/grafana-server --homepath=/grafana --config=/etc/grafana/grafana.ini


text:
package com.helger.commons.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Indicates that a method returns a mutable object. This annotation is meant to
 * indicate that the internal object is returned in a mutable way. If a copy of
 * the internal object is returned and is mutable, please use the
 * {@link ReturnsMutableCopy} annotation.
 *
 * @author Philip Helger
 */
@Retention (RetentionPolicy.CLASS)
@Target ({ ElementType.METHOD })
@Documented
public @interface ReturnsMutableObject
{
  /**
   * @return developer comment to explain why the mutable object is returned.
   */
  String value() default "";
}


text:
#ifndef _ADSKDMGR_H_
#define _ADSKDMGR_H_ 1

#include "acdocman.h"

//----- Defines
//-----     #pragma warning(disable: 4786)
//----- in your precompiled header to get rid of this warning

//----- 'DEBUG workaround' prevents the #include <map> statement in AdskDMgr.h
//----- from pulling in "use_ansi.h" that would force the debug CRT through #pragma-s.
#if defined(_DEBUG) && (defined (_AFXDLL) || !defined (_WINDLL)) && !defined(_FULLDEBUG_)
//----- The result of the above line is that arx/dbx application statically linked
//----- to MFC will use the debug version of the c++ runtime, all other
//----- configurations will use the release version.
#define _DMGR_DEBUG_WAS_DEFINED
#undef _DEBUG
#pragma message ("     Compiling STL header files in release mode.")
#endif
#include <map>
#ifdef _DMGR_DEBUG_WAS_DEFINED
#define _DEBUG
#undef _DMGR_DEBUG_WAS_DEFINED
#endif

template <class T> class AsdkDataManager : public AcApDocManagerReactor
{
public:
    AsdkDataManager()
    {
        acDocManager->addReactor(this);
    }
    ~AsdkDataManager()
    {
        acDocManager->removeReactor(this);
    }
    virtual void documentToBeDestroyed( AcApDocument *pDoc )
    {
        m_dataMap.erase(pDoc);
    }

    T& docData(AcApDocument* pDoc)
    {
        std::map<AcApDocument*, T>::iterator i;
        i = m_dataMap.find(pDoc);
        if (i==m_dataMap.end())
            return  m_dataMap[ pDoc ];
        else
            return (*i).second;
    }
    T& docData()
    {
        return docData(acDocManager->curDocument());
    }

private:
    std::map<AcApDocument*, T> m_dataMap;
} ;

#endif  //----- _ADSKDMGR_H_


text:
Reference
=========

.. automodule:: rest_assured.testcases
    :members:

.. automodule:: rest_assured.contrib.drf_fsm_transitions
    :members:


text:
namespace spmat
{
	namespace symbolic
	{
		const static size_t INT_NULL = SIZE_MAX;

		struct factor
		{
			typedef range_iterator<const size_t *> const_column_iterator;

			size_t nrow;
			size_t ncol;
			size_t nnz;
			size_t size;   // allocated elements

			// column oriented
			dense_vector<size_t> pc;
			dense_vector<size_t> ir;

			// row oriented
			dense_vector<size_t> pr;
			dense_vector<size_t> ic;
			dense_vector<size_t> nc;

			factor(size_t nrow, size_t ncol, size_t nnz);

			~factor();

			factor(const factor &);

			factor(factor &&);

			void expand(size_t n = 1);

			sparse to_sparse() const;

			factor transpose() const;

			const_column_iterator column(size_t j) const;

			bool operator ==(const factor &) const;
			bool operator !=(const factor &) const;
		};
	}
}


text:
class DataSource

  include Singleton

  def initialize
    @data = {}
    Sample.where(verified: true).each do |sample|
      #sample_url = [sample.image.url, sample.image.path].max_by(&:length)
      sample_url = sample.image.path
      sample_url = "https:" + sample.image.url if Rails.env.production?
      @data[sample.id] = MiniMagick::Image.open(sample_url).get_pixels
    end
  end

  def good_pixels_of_image(image_path)
    return MiniMagick::Image.open(sample_url).get_good_pixels if Rails.env.production?
  end

  # which_pixels takes :dark or :good
  def fetch_data_and_labels(image_ids, which_pixels = :good)
    case which_pixels
      when :good
        [image_ids.map{|id| good_pixels(@data[id])}, image_ids.map{|id| Sample.find(id).label}]
      when :dark
        [image_ids.map{|id| dark_pixels(@data[id])}, image_ids.map{|id| Sample.find(id).label}]
    end
  end

  def all_training_data(which_pixels = :good, no_dark = true)
    return fetch_data_and_labels Sample.where(verified: true).reject{|s| s.label == -100}.map(&:id), which_pixels if no_dark
    fetch_data_and_labels Sample.where(verified: true).ids, which_pixels
  end

  private

  def dark_pixels(image)
    #selecting every 10th row a little to the right from the coffee pan
    pixels = (3300..(400*400)).step(10*400).to_a
    pixels.map{|x| image[x]}
  end

  def good_pixels(image)
    good_pixels = [87311,95716,102082,89321,99481,101280,127705,116098,101682,95316,102080,119714,87711,144209,87712,116498,128107,144936,113372,102130]
    good_pixels.map do |x|
      (image[x-1] + image[x] + image[x-2]
      + image[x - 1 - 400] +  image[x - 400] + image[x - 2 - 400]
      + image[x - 1 + 400] +  image[x + 400] + image[x - 2 + 400]) / 9.0
    end
  end
end


text:
function Excalibur( keys )
local caster = keys.caster
local ability = keys.ability

ability:EndCooldown()
end

function ParticleAttach( keys )
local caster = keys.caster
local ability = keys.ability

caster.pParticle = ParticleManager:CreateParticle("particles/saber/oracle_fortune_channel.vpcf", PATTACH_POINT_FOLLOW, caster)
ParticleManager:SetParticleControlEnt(caster.pParticle, 0, caster, PATTACH_POINT_FOLLOW, "attach_attack2", caster:GetAbsOrigin(), true)
end

function ParticleRemove( keys )
local caster = keys.caster
local ability = keys.ability

ParticleManager:DestroyParticle( caster.pParticle, false )
end

function ExcaliburFinish( keys )
local ability = keys.ability
local caster = keys.caster
local casterPos = keys.caster:GetAbsOrigin()
local point = keys.target_points[1]
local direction = (point - casterPos):Normalized()
local dummyPoint = direction * 2000 + casterPos
local dummy = CreateUnitByName( "npc_dummy_unit", dummyPoint, false, caster, caster, caster:GetTeamNumber() )
ability:ApplyDataDrivenModifier( caster, dummy, "modifier_excalibur_dummy", {} )
local dummyPos = dummy:GetAbsOrigin()
local casterH = casterPos.y

local particle = ParticleManager:CreateParticle("particles/saber/luna_lucent_beam_impact_shared_ti_5_gold.vpcf", PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControlEnt(particle, 1, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", casterPos, true)
ParticleManager:SetParticleControlEnt(particle, 2, dummy, PATTACH_POINT_FOLLOW, "attach_hitloc", dummyPos, true)
ParticleManager:SetParticleControlEnt(particle, 5, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", casterPos, true)

Timers:CreateTimer( 1, function()
	ParticleManager:DestroyParticle( particle, false )
	dummy:ForceKill( true )
	return nil
	end
)
end


text:
import xbmcplugin
import xbmcgui
import sys

from BeautifulSoup import BeautifulSoup

from resources.lib import ronpaulchannel

thisPlugin = int(sys.argv[1])

def createListing():
  """
  Get list of most recent episodes
  """
  #req = urllib2.Request('http://www.ronpaulchannel.com/video/')
  #res = urllib2.urlopen(req)
  #html = res.read()
  #res.close()
  #soup = BeautifulSoup(html)
  #vids = soup.findAll('div', 'video-entry')
  vids = ronpaulchannel.getvideos()
  listing = []
  for vid in vids:
    # [label, label2, iconImage, thumbnailImage, path]
    item = [vid.__unicode__(), '', vid.thumbnail, vid.thumbnail, vid.url]
    listing.append(item)
  return listing

def sendToXbmc(listing):
  """
  Sends a listing to XBMC for display as a directory listing
  Plugins always result in a listing
  """
  global thisPlugin

  for item in listing:
    listItem = xbmcgui.ListItem(item)
    # handle, url, listitem [,isFolder=False, totalItems])
    xbmcplugin.addDirectoryItem(thisPlugin, '', listItem)

  xbmcplugin.endOfDirectory(thisPlugin)

sendToXbmc(createListing())


text:
- DEC Alpha 64
- HP Precision Architure RISC
- Sun Microsystems SPARC
- ARM (32 and 64 bit)
- Motorola 68000

## List three filesystem types Linux supports
- btrfs
- ext filesystem family (ext2, ext4, ext3 as a subset of ext4 driver)
- Filesystem over 9p (Plan 9 everything-protocol that can also do filesystems)
- Bonus: ZFS (not included in kernel source tree because of licensing issues)

# Kernel Modules
## Hello World
### Command Output
```
root@nude_organist:/host/308/lab-07/hello-world# lsmod
Module                  Size  Used by
root@nude_organist:/host/308/lab-07/hello-world# modinfo hello_world.ko
filename:       /host/308/lab-07/hello-world/hello_world.ko
description:    A simple hello world driver
author:         Jeramie Vens vens@iastate.edu
license:        GPL
depends:
vermagic:       4.4.3drahos mod_unload
root@nude_organist:/host/308/lab-07/hello-world# insmod hello_world.ko
Hello World!
root@nude_organist:/host/308/lab-07/hello-world# lsmod
Module                  Size  Used by
hello_world              867  0
root@nude_organist:/host/308/lab-07/hello-world# rmmod hello_world.ko
Goodbye World!
root@nude_organist:/host/308/lab-07/hello-world# lsmod
Module                  Size  Used by
root@nude_organist:/host/308/lab-07/hello-world#
```

The base kernel loads no modules. This is why the initial `lsmod` returns no modules in use.
The module info, created from the DRIVER_* definitions and the MODULE_* macros, can be
read from the kernel object and displayed with modinfo. The module is then inserted with
`insmod`. This causes the hello_init to run, because it is defined as the initialization
with module_init.

The module
then appears in the module list, and can be removed with `rmmod`. Like `insmod`, `rmmod`
calls the corresponding module lifecycle function hello_exit. This prints to the
kernel output (console), and the module is no longer loaded.

A note about printk output: Printk does not normally go to standard output. Instead,
it goes into the kernel ringbuffer, and is visible with the `dmesg` command. However,
User Mode Linux, when booted into single user mode, seems to redirect kernel
output to the console TTY output as well. Most 'real' systems will make this
output visible on one of the alternative console TTYs, especially during boot. This means
that loading and unloading these modules on a real system (not UML) will be a completely
silent operation, with the printk messages only showing up in dmesg.

## File Example
### `read()` vs `fops.read`
The read syscall greatly simplifies and abstracts the ideas of files to a single integer:
the file descriptior. This file descriptior (fd) is unique to the process, and hides a lot
of the ugly bits associated with the file. These ugly bits appear kernel-side, in the form
of extra parameters that show up in the prototype of device_read.

The buffer and length parameters are passed, unmodified, from the buf and count
params of the read() syscall.

The parameter `file`, as opposed to an integer fd, contains a bunch of the ugly details
about the file, such as the process handle, fd within the process, and other
bits of data. The buffer parameter is the pointer (within process address space, hence
the usage of put_user rather than simply the dereference operator) given as the `buf`
parameter to the read() syscall. The offset is the current seek position within the file.
'Real' files will modify the offset as they are read or written, and adjust it as appropriate
when seeking. A stream-oriented device driver, though, can simply leave it untouched if it does
not have a logical concept of position within a file.

This module could actually make use of the offset by using it as a replacement
for the msg_ptr pointer (See notes).

### Expectations
- The printk info will appear upon loading, as with the hello_world module. This is kernel output,
so it will not be redirectable (it is coming from the kernel itself, NOT from the standard
output of the insmod command) and will appear in dmesg.
- The cat from the file will work correctly. This output is redirectable, since it is actually coming
from cat, and from the file in turn. Nothing is added to dmesg during a read or open.
- Attempting to write to the file will cause the error output to appear. This is kernel output, just
like the insertion message, so it will be non-redirectable and in dmesg.
- Something will get angry and perror about the EINVAL returned by write().
- Unloading the module is silent.
- Everything will go horribly wrong when minor number 1 is used.
- Everything will go horribly wrong when the module is removed.

### Command Output
```
root@nude_organist:/host/308/lab-07/hello-file# insmod hello_file.ko
I was assigned major number 254. To talk to
the driver, create a dev file with
'mknod /dev/cpre308 c 254 0'.
Try various minor numbers. Try to cat and echo to
the device file.
root@nude_organist:/host/308/lab-07/hello-file# mknod /dev/cpre308-0 c 254 0
root@nude_organist:/host/308/lab-07/hello-file# cat /dev/cpre308-0
I already told you 0 times Hello World!
root@nude_organist:/host/308/lab-07/hello-file# cat /dev/cpre308-0
I already told you 1 times Hello World!
root@nude_organist:/host/308/lab-07/hello-file# echo "hello" > /dev/cpre308-0
Sorry, this operation isn't supported.
bash: echo: write error: Invalid argument
root@nude_organist:/host/308/lab-07/hello-file# mknod /dev/cpre308-1 c 254 1
root@nude_organist:/host/308/lab-07/hello-file# cat /dev/cpre308-0
I already told you 3 times Hello World!
root@nude_organist:/host/308/lab-07/hello-file# cat /dev/cpre308-1
I already told you 4 times Hello World!
root@nude_organist:/host/308/lab-07/hello-file# rmmod hello_file.ko
root@nude_organist:/host/308/lab-07/hello-file# cat /dev/cpre308-0
cat: /dev/cpre308-0: No such device or address
root@nude_organist:/host/308/lab-07/hello-file#
```

Most of my expectations were correct. However, things didn't go horribly wrong when a different
minor number was used. Things do go horribly wrong when the module is removed, ie. major number
was wrong. This highlights
the fundamental difference between major and minor numbers: The major number is used by the kernel to
route things to the correct module. The minor number is used within the module however it sees fit. This
module simply does not care about it.

Bonus: dmesg output
```
root@nude_organist:/host/308/lab-07/hello-file# dmesg | tail -n 6
[ 4309.180000] I was assigned major number 254. To talk to
[ 4309.180000] the driver, create a dev file with
[ 4309.180000] 'mknod /dev/cpre308 c 254 0'.
[ 4309.180000] Try various minor numbers. Try to cat and echo to
[ 4309.180000] the device file.
[ 4323.750000] Sorry, this operation isn't supported.
root@nude_organist:/host/308/lab-07/hello-file#
```

### Notes on given hello_file
- The "hello world" printout is actually given by reading the file. This can be confirmed
by redirecting the output of `cat`.
- All other messages (init, exit, write error) are kernel output. They are not coming
from the command, rather from the kernel itself. They cannot be redirected, but they do
show up in `dmesg`.
- The try_module_get(THIS_MODULE) and try_module_put(THIS_MODULE) calls are critically important.
They prevent the module from being unloaded while it a process has the device node open. The kernel
was compilef with `rmmod -f` enabled, though, so it can be force-unloaded. This could very well
cause kernel panics.
- The Device_Open count makes it so that only one process can have the file open at a time. While
this is pretty lame from a usability standpoint, it makes it possible to use a single,
static buffer for preparing the message. Otherwise, a bunch of work would be needed
to maintain dynamically allocated buffers on a per-instance basis, allocated
upon `open()` and deleted upon `close()` or termination.
- On that note, both `close()` and process termination are wrapped up by device_release, which
is why it is called release and not simply close.

By using offp instead of the msg_ptr hack, some unexpected
breakages could be avoided. For example, it would probably be possible to get some weirdness
to happen by doing weird tricks with dup() or fork() that would end up breaking the msg_ptr and
causing read() calls to fight over characters within the message. The offp is meant for
this use case.

To get complete multi-open support, offp would have to be combined with per-open-instance memory
allocation and message formatting/preparation.

# Lab Task: hello-file-complete
## Implementation notes
The reverser device driver is implemented as a stack. write() syscalls push bytes to the stack, while
read() syscalls pop them. This means that, once read and emptied, the device must be written to
before a read will return any bytes. Since cat reads as much as possible, some examples using head are
provided as well.

This implementation does not treat newlines differently than any other character, so output
read from the module can end up looking somewhat funky unless a newline is prepended to
the input.

## Building
Ensure that the LINUX_SRC variable is configured properly in the Makefile, then `make ARCH=um`.
The module retains the name hello_file.ko.

## Testing
Test the driver as follows:
```
# Setup
insmod hello_file.ko
mknod /dev/reverser c 254 0

# Stack is empty
cat /dev/reverser

# Put a newline at the bottom of the stack
echo > /dev/reverser
# Put 'Hello' on the stack
echo -n 'Hello' > /dev/reverser
# Put ' World!' on the stack
echo -n ' World!' > /dev/reverser

# cat the stack
cat /dev/reverser
# Now the stack is empty again
cat /dev/reverser

# Now test with partial reads
# Same setup as a one-liner
# The newline comes at the beginning of the input so it comes after the output
echo -n -e '\nHello\nWorld!' > /dev/reverser
# First read
head -c 7 /dev/reverser
# Put it back
echo -n -e ' Planet!' > /dev/reverser
# Finish it
cat /dev/reverser

# Cleanup
rmmod hello_file.ko
unlink /dev/reverser
```


text:
namespace Microsoft.Azure.Management.Reservations.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Reservation purchase details
    /// </summary>
    public partial class ReservationToPurchaseCalculateExchange
    {
        /// <summary>
        /// Initializes a new instance of the
        /// ReservationToPurchaseCalculateExchange class.
        /// </summary>
        public ReservationToPurchaseCalculateExchange()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ReservationToPurchaseCalculateExchange class.
        /// </summary>
        public ReservationToPurchaseCalculateExchange(PurchaseRequest properties = default(PurchaseRequest), Price billingCurrencyTotal = default(Price))
        {
            Properties = properties;
            BillingCurrencyTotal = billingCurrencyTotal;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "properties")]
        public PurchaseRequest Properties { get; set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "billingCurrencyTotal")]
        public Price BillingCurrencyTotal { get; set; }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Beatmaps.Timing;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
using osu.Game.Utils;

namespace osu.Game.Rulesets.Osu.Mods
{
    public abstract class InputBlockingMod : Mod, IApplicableToDrawableRuleset<OsuHitObject>, IUpdatableByPlayfield
    {
        public override double ScoreMultiplier => 1.0;
        public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(ModRelax), typeof(OsuModCinema) };
        public override ModType Type => ModType.Conversion;

        private const double flash_duration = 1000;

        private DrawableRuleset<OsuHitObject> ruleset = null!;

        protected OsuAction? LastAcceptedAction { get; private set; }

        /// <summary>
        /// A tracker for periods where alternate should not be forced (i.e. non-gameplay periods).
        /// </summary>
        /// <remarks>
        /// This is different from <see cref="Player.IsBreakTime"/> in that the periods here end strictly at the first object after the break, rather than the break's end time.
        /// </remarks>
        private PeriodTracker nonGameplayPeriods = null!;

        private IFrameStableClock gameplayClock = null!;

        public void ApplyToDrawableRuleset(DrawableRuleset<OsuHitObject> drawableRuleset)
        {
            ruleset = drawableRuleset;
            drawableRuleset.KeyBindingInputManager.Add(new InputInterceptor(this));

            var periods = new List<Period>();

            if (drawableRuleset.Objects.Any())
            {
                periods.Add(new Period(int.MinValue, getValidJudgementTime(ruleset.Objects.First()) - 1));

                foreach (BreakPeriod b in drawableRuleset.Beatmap.Breaks)
                    periods.Add(new Period(b.StartTime, getValidJudgementTime(ruleset.Objects.First(h => h.StartTime >= b.EndTime)) - 1));

                static double getValidJudgementTime(HitObject hitObject) => hitObject.StartTime - hitObject.HitWindows.WindowFor(HitResult.Meh);
            }

            nonGameplayPeriods = new PeriodTracker(periods);

            gameplayClock = drawableRuleset.FrameStableClock;
        }

        public void Update(Playfield playfield)
        {
            if (LastAcceptedAction != null && nonGameplayPeriods.IsInAny(gameplayClock.CurrentTime))
                LastAcceptedAction = null;
        }

        protected abstract bool CheckValidNewAction(OsuAction action);

        private bool checkCorrectAction(OsuAction action)
        {
            if (nonGameplayPeriods.IsInAny(gameplayClock.CurrentTime))
                return true;

            switch (action)
            {
                case OsuAction.LeftButton:
                case OsuAction.RightButton:
                    break;

                // Any action which is not left or right button should be ignored.
                default:
                    return true;
            }

            if (CheckValidNewAction(action))
            {
                LastAcceptedAction = action;
                return true;
            }

            ruleset.Cursor.FlashColour(Colour4.Red, flash_duration, Easing.OutQuint);
            return false;
        }

        private class InputInterceptor : Component, IKeyBindingHandler<OsuAction>
        {
            private readonly InputBlockingMod mod;

            public InputInterceptor(InputBlockingMod mod)
            {
                this.mod = mod;
            }

            public bool OnPressed(KeyBindingPressEvent<OsuAction> e)
                // if the pressed action is incorrect, block it from reaching gameplay.
                => !mod.checkCorrectAction(e.Action);

            public void OnReleased(KeyBindingReleaseEvent<OsuAction> e)
            {
            }
        }
    }
}


text:
package clip

import (
	"encoding/xml"
	"time"
)

type clipFile struct {
	Info Info `xml:"ClipContent"`
}

// Info is the metadata for a clip as desribed by the CLIP/*.XML files.
type Info struct {
	Name     string         `xml:"ClipName"`
	GlobalID string         `xml:"GlobalClipID"`
	Duration int            `xml:"Duration"`
	EditUnit string         `xml:"EditUnit"` // I don't actually know what this is.
	Video    []VideoEssence `xml:"EssenceList>Video"`
	Audio    []AudioEssence `xml:"EssenceList>Audio"`
	Metadata Metadata       `xml:"ClipMetadata"`
	// Added by us
	OutputFile string
	OutputDir  string // default; can be changed
}

// Metadata provides the clip's metadata.
type Metadata struct {
	Name         string `xml:"UserClipName"`
	DataSource   string
	CreationDate Time       `xml:"Access>CreationDate"`
	LastUpdate   Time       `xml:"Access>LastUpdateDate"`
	DeviceInfo   DeviceInfo `xml:"Device"`
	Start        Time       `xml:"Shoot>StartDate"`
	End          Time       `xml:"Shoot>EndDate"`
	Thumbnail    ThumbnailInfo
}

// VideoEssence provides metadata about the video in a clip.
type VideoEssence struct {
	Format    string `xml:"VideoFormat"`
	Codec     string
	FrameRate string
	// DropFrame        bool `xml:"FrameRate>DropFrameFlag,attr"`
	StartTimecode    string
	StartBinaryGroup string
	AspectRatio      string
	Index            EssenceIndex `xml:"VideoIndex"`

	// filename inserted by us
	Filename string
}

// AudioEssence provides metadata about the audio in a clip.
type AudioEssence struct {
	Format        string `xml:"AudioFormat"`
	SamplingRate  int
	BitsPerSample int
	Index         EssenceIndex `xml:"AudioIndex"`

	// filename inserted by us
	Filename string
}

// EssenceIndex stores the start position and length of an essence.
type EssenceIndex struct {
	StartByteOffset int
	DataSize        int
}

// DeviceInfo stores the type and serial number of the device that produced this
// clip.
type DeviceInfo struct {
	Manufacturer string
	Serial       string `xml:"SerialNo."`
	Model        string `xml:"ModelName"`
}

// ThumbnailInfo ...
type ThumbnailInfo struct {
	FrameOffset int
	Format      string `xml:"ThumbnailFormat"`
	Width       int
	Height      int
}

// Time is a wrapper for time.Time that can be unmarshalled from XML.
type Time struct {
	time.Time
}

const timestampLayout = "2006-01-02T15:04:05-07:00"

// UnmarshalXML does what it says on the tin: unmarshals XML into a time.Time.
func (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	var timeStr string
	err := d.DecodeElement(&timeStr, &start)
	if err != nil {
		return err
	}
	goTime, err := time.Parse(timestampLayout, timeStr)
	if err != nil {
		return err
	}
	*t = Time{goTime}
	return nil
}


text:
import java.io.Serializable;

/**
 * We use java.io.{@link Serializable} here for the sake of simplicity.
 * In production, Hazelcast Custom Serialization should be used.
 */
public class Trade implements Serializable {

    private final long time;
    private final String ticker;
    private final int quantity;
    private final int price; // in cents

    Trade(long time, String ticker, int quantity, int price) {
        this.time = time;
        this.ticker = ticker;
        this.quantity = quantity;
        this.price = price;
    }

    public long getTime() {
        return time;
    }

    public String getTicker() {
        return ticker;
    }

    public int getQuantity() {
        return quantity;
    }

    public int getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "Trade{time=" + time + ", ticker='" + ticker + '\'' + ", quantity=" + quantity
                + ", price=" + price + '}';
    }
}


text:
package eu.bcvsolutions.idm.core.eav.rest.impl;

import java.math.BigDecimal;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.util.MultiValueMap;

import com.google.common.collect.Lists;

import eu.bcvsolutions.idm.core.api.domain.TransactionContextHolder;
import eu.bcvsolutions.idm.core.api.dto.AbstractDto;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityContractDto;
import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleDto;
import eu.bcvsolutions.idm.core.api.dto.IdmTreeNodeDto;
import eu.bcvsolutions.idm.core.api.entity.AbstractEntity;
import eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoController;
import eu.bcvsolutions.idm.core.api.rest.AbstractReadWriteDtoControllerRestTest;
import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormValueFilter;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityContract;
import eu.bcvsolutions.idm.core.model.entity.IdmRole;
import eu.bcvsolutions.idm.core.model.entity.IdmTreeNode;
import eu.bcvsolutions.idm.core.security.api.domain.GuardedString;

/**
 * For values agenda tests.
 *
 * @author Roman Kučera
 * @author Radek Tomiška
 */
public class IdmFormValueControllerRestTest extends AbstractReadWriteDtoControllerRestTest<IdmFormValueDto> {

	@Autowired private FormService formService;
	@Autowired private IdmFormValueController controller;

	@Override
	protected AbstractReadWriteDtoController<IdmFormValueDto, ?> getController() {
		return controller;
	}

	@Override
	protected IdmFormValueDto prepareDto() {
		return prepareDto(PersistentType.SHORTTEXT);
	}

	protected IdmFormValueDto prepareDto(PersistentType peristentType) {
		// create definition one
		IdmFormAttributeDto attributeDefinitionOne = new IdmFormAttributeDto();
		attributeDefinitionOne.setCode(getHelper().createName());
		attributeDefinitionOne.setName(attributeDefinitionOne.getCode());
		attributeDefinitionOne.setPersistentType(peristentType);
		attributeDefinitionOne = formService.saveAttribute(IdmIdentityDto.class, attributeDefinitionOne);
		//
		IdmFormValueDto value = new IdmFormValueDto(attributeDefinitionOne);
		value.setShortTextValue(getHelper().createName());
		//
		return value;
	}

	@Override
	protected boolean isReadOnly() {
		return true;
	}

	@Override
	public void testGet() throws Exception {
		// ~ get is not available
	}

	@Override
	public void testPermissions() {
		// ~ get is not available
	}

	@Override
	protected boolean supportsBulkActions() {
		return true;
	}

	@Override
	protected IdmFormValueDto createDto(IdmFormValueDto value) {
		IdmIdentityDto identity = getHelper().createIdentity((GuardedString) null);
		//
		return formService.saveValues(identity, formService.getDefinition(IdmIdentityDto.class), Lists.newArrayList(value)).get(0);
	}

	protected List<IdmFormValueDto> find(String searchName, MultiValueMap<String, String> parameters, Authentication authentication) {
		// we need form defition in parameters
		parameters.set(IdmFormValueFilter.PARAMETER_DEFINITION_ID, formService.getDefinition(IdmIdentityDto.class).getId().toString());
		//
		return super.find(searchName, parameters, authentication);
	}

	@Override
	protected long count(MultiValueMap<String, String> parameters) {
		// we need form defition in parameters
		parameters.set(IdmFormValueFilter.PARAMETER_DEFINITION_ID, formService.getDefinition(IdmIdentityDto.class).getId().toString());
		//
		return super.count(parameters);
	}

	@Test
	public void testFindByText() {
		IdmFormValueDto valueOne = createDto();
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setText(((IdmFormAttributeDto) valueOne.getEmbedded().get(IdmFormValueDto.PROPERTY_FORM_ATTRIBUTE)).getCode());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByPersistentType() {
		IdmFormValueDto value = prepareDto(PersistentType.TEXT);
		String text = getHelper().createName();
		value.setValue(text);
		IdmFormValueDto valueOne = createDto(value);
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setStringValue(text);
		filter.setPersistentType(PersistentType.TEXT);
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByShortTextValue() {
		IdmFormValueDto value = prepareDto(PersistentType.SHORTTEXT);
		String text = getHelper().createName();
		value.setValue(text);
		IdmFormValueDto valueOne = createDto(value);
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setShortTextValue(text);
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByShortTextValueLike() {
		IdmFormValueDto value = prepareDto(PersistentType.SHORTTEXT);
		String suffix = getHelper().createName();
		value.setValue(getHelper().createName() + suffix);
		IdmFormValueDto valueOne = createDto(value);
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setShortTextValueLike(suffix);
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByStringValue() {
		IdmFormValueDto value = prepareDto(PersistentType.TEXT);
		String text = getHelper().createName();
		value.setValue(text);
		IdmFormValueDto valueOne = createDto(value);
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setStringValue(text);
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByStringValueLike() {
		IdmFormValueDto value = prepareDto(PersistentType.TEXT);
		String suffix = getHelper().createName();
		value.setValue(getHelper().createName() + suffix);
		IdmFormValueDto valueOne = createDto(value);
		createDto(); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setStringValueLike(suffix);
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByBooleanValue() {
		IdmFormValueDto value = prepareDto(PersistentType.BOOLEAN);
		value.setBooleanValue(true);
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.BOOLEAN);
		value.setBooleanValue(false);
		createDto(value); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setBooleanValue(true);
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByLongValue() {
		IdmFormValueDto value = prepareDto(PersistentType.LONG);
		value.setLongValue(1L);
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.LONG);
		value.setLongValue(2L);
		createDto(value); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setLongValue(1L);
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByDoubleValue() {
		IdmFormValueDto value = prepareDto(PersistentType.DOUBLE);
		value.setDoubleValue(BigDecimal.valueOf(1L));
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.DOUBLE);
		value.setDoubleValue(BigDecimal.valueOf(2L));
		createDto(value); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setDoubleValue(BigDecimal.valueOf(1L));
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByDateValue() {
		IdmFormValueDto value = prepareDto(PersistentType.DATETIME);
		ZonedDateTime now = ZonedDateTime.now().truncatedTo(ChronoUnit.MILLIS);
		value.setDateValue(now);
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.DATETIME);
		value.setDateValue(now.plusDays(2));
		createDto(value); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setDateValue(now);
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByDateValueFrom() {
		IdmFormValueDto value = prepareDto(PersistentType.DATETIME);
		ZonedDateTime now = ZonedDateTime.now();
		value.setDateValue(now);
		createDto(value);
		value = prepareDto(PersistentType.DATETIME);
		value.setDateValue(now.plusDays(2));
		IdmFormValueDto valueOne = createDto(value);
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setDateValueFrom(now.plusDays(1));
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByDateValueTill() {
		IdmFormValueDto value = prepareDto(PersistentType.DATETIME);
		ZonedDateTime now = ZonedDateTime.now();
		value.setDateValue(now);
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.DATETIME);
		value.setDateValue(now.plusDays(2));
		createDto(value);
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setDateValueTill(now.plusDays(1));
		filter.setTransactionId(TransactionContextHolder.getContext().getTransactionId());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void testFindByUuidValue() {
		IdmFormValueDto value = prepareDto(PersistentType.UUID);
		value.setUuidValue(UUID.randomUUID());
		IdmFormValueDto valueOne = createDto(value);
		value = prepareDto(PersistentType.UUID);
		value.setUuidValue(UUID.randomUUID());
		createDto(value); // other
		//
		IdmFormValueFilter<?> filter = new IdmFormValueFilter<>();
		filter.setUuidValue(valueOne.getUuidValue());
		List<IdmFormValueDto> results = find(filter);
		//
		Assert.assertEquals(1, results.size());
		Assert.assertTrue(results.stream().anyMatch(r -> r.getId().equals(valueOne.getId())));
	}

	@Test
	public void findValues() throws Exception {
		IdmIdentityDto ownerIdentity = getHelper().createIdentity((GuardedString) null);
		IdmRoleDto ownerRole = getHelper().createRole();
		IdmIdentityContractDto ownerIdentityContract = getHelper().createContract(ownerIdentity);
		IdmTreeNodeDto ownerTreeNode = null;
		try {
			getHelper().loginAdmin();
			ownerTreeNode = getHelper().createTreeNode();
		} finally {
			logout();
		}
		//
		Assert.assertEquals(1, prepareDataAndSearch(IdmIdentity.class, ownerIdentity));
		Assert.assertEquals(1, prepareDataAndSearch(IdmRole.class, ownerRole));
		Assert.assertEquals(1, prepareDataAndSearch(IdmTreeNode.class, ownerTreeNode));
		Assert.assertEquals(1, prepareDataAndSearch(IdmIdentityContract.class, ownerIdentityContract));
	}

	private int prepareDataAndSearch(Class<? extends AbstractEntity> type, AbstractDto owner) throws Exception {
		// create attribute
		IdmFormAttributeDto attribute = new IdmFormAttributeDto();
		String attributeName = getHelper().createName();
		attribute.setCode(attributeName);
		attribute.setName(attribute.getCode());
		attribute.setPersistentType(PersistentType.SHORTTEXT);

		// create definition
		IdmFormDefinitionDto definition = formService.createDefinition(type, getHelper().createName(), Lists.newArrayList(attribute));
		attribute = definition.getMappedAttributeByCode(attribute.getCode());

		// save value
		formService.saveValues(owner.getId(), type, attribute, Lists.newArrayList("one"));
		String response = getJsonAsString("/form-values", "definitionId=" + definition.getId(), 20l, 0l, null, null, getAdminAuthentication());
		return getEmbeddedList("formValues", response).size();
	}
}


text:
package innerclasses;

class D {}
abstract class E {}

class Z extends D {
  E makeE() { return new E() {}; }
}

public class MultiImplementation {
  static void takesD(D d) {}
  static void takesE(E e) {}
  public static void main(String[] args) {
    Z z = new Z();
    takesD(z);
    takesE(z.makeE());
  }
} ///:~


text:
layout: page
title: About
description: About the author
lang:
author:
twitter: tionosulis_
---
Hi,

My name's Sulistiono. I'm Indonesian. I love poem and **`</code>`**. Delta blues and coffee are always on my daily to do list.

Nothing much to say, but welcome and enjoy your surf.


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

import { App } from './models/app';

@Injectable()
export class AppService {

  private API_URI = 'http://localhost:3000';

  constructor(
    private _http: Http
  ) { }

  getApps(): Observable<App[]> {
    return this._http
      .get(`${this.API_URI}/apps`)
      .map((response: Response) => response.json());
  }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/analytics/data/v1alpha/data.proto

package com.google.analytics.data.v1alpha;

public interface FilterOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.analytics.data.v1alpha.Filter)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The dimension name or metric name. Must be a name defined in dimensions
   * or metrics.
   *

   *
   * string field_name = 1;
   *
   * @return The fieldName.
   */
  java.lang.String getFieldName();
  /**
   *
   *
   *

   * The dimension name or metric name. Must be a name defined in dimensions
   * or metrics.
   *

   *
   * string field_name = 1;
   *
   * @return The bytes for fieldName.
   */
  com.google.protobuf.ByteString getFieldNameBytes();

  /**
   *
   *
   *

   * Strings related filter.
   *

   *
   * .google.analytics.data.v1alpha.StringFilter string_filter = 2;
   *
   * @return Whether the stringFilter field is set.
   */
  boolean hasStringFilter();
  /**
   *
   *
   *

   * Strings related filter.
   *

   *
   * .google.analytics.data.v1alpha.StringFilter string_filter = 2;
   *
   * @return The stringFilter.
   */
  com.google.analytics.data.v1alpha.StringFilter getStringFilter();
  /**
   *
   *
   *

   * Strings related filter.
   *

   *
   * .google.analytics.data.v1alpha.StringFilter string_filter = 2;
   */
  com.google.analytics.data.v1alpha.StringFilterOrBuilder getStringFilterOrBuilder();

  /**
   *
   *
   *

   * A filter for in list values.
   *

   *
   * .google.analytics.data.v1alpha.InListFilter in_list_filter = 3;
   *
   * @return Whether the inListFilter field is set.
   */
  boolean hasInListFilter();
  /**
   *
   *
   *

   * A filter for in list values.
   *

   *
   * .google.analytics.data.v1alpha.InListFilter in_list_filter = 3;
   *
   * @return The inListFilter.
   */
  com.google.analytics.data.v1alpha.InListFilter getInListFilter();
  /**
   *
   *
   *

   * A filter for in list values.
   *

   *
   * .google.analytics.data.v1alpha.InListFilter in_list_filter = 3;
   */
  com.google.analytics.data.v1alpha.InListFilterOrBuilder getInListFilterOrBuilder();

  /**
   *
   *
   *

   * A filter for numeric or date values.
   *

   *
   * .google.analytics.data.v1alpha.NumericFilter numeric_filter = 4;
   *
   * @return Whether the numericFilter field is set.
   */
  boolean hasNumericFilter();
  /**
   *
   *
   *

   * A filter for numeric or date values.
   *

   *
   * .google.analytics.data.v1alpha.NumericFilter numeric_filter = 4;
   *
   * @return The numericFilter.
   */
  com.google.analytics.data.v1alpha.NumericFilter getNumericFilter();
  /**
   *
   *
   *

   * A filter for numeric or date values.
   *

   *
   * .google.analytics.data.v1alpha.NumericFilter numeric_filter = 4;
   */
  com.google.analytics.data.v1alpha.NumericFilterOrBuilder getNumericFilterOrBuilder();

  /**
   *
   *
   *

   * A filter for between two values.
   *

   *
   * .google.analytics.data.v1alpha.BetweenFilter between_filter = 5;
   *
   * @return Whether the betweenFilter field is set.
   */
  boolean hasBetweenFilter();
  /**
   *
   *
   *

   * A filter for between two values.
   *

   *
   * .google.analytics.data.v1alpha.BetweenFilter between_filter = 5;
   *
   * @return The betweenFilter.
   */
  com.google.analytics.data.v1alpha.BetweenFilter getBetweenFilter();
  /**
   *
   *
   *

   * A filter for between two values.
   *

   *
   * .google.analytics.data.v1alpha.BetweenFilter between_filter = 5;
   */
  com.google.analytics.data.v1alpha.BetweenFilterOrBuilder getBetweenFilterOrBuilder();

  public com.google.analytics.data.v1alpha.Filter.OneFilterCase getOneFilterCase();
}


text:
package portsbinding

import (
	"testing"

	"github.com/gophercloud/gophercloud/acceptance/clients"
	networking "github.com/gophercloud/gophercloud/acceptance/openstack/networking/v2"
	"github.com/gophercloud/gophercloud/acceptance/tools"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/ports"
)

func TestPortsbindingCRUD(t *testing.T) {
	client, err := clients.NewNetworkV2Client()
	if err != nil {
		t.Fatalf("Unable to create a network client: %v", err)
	}

	// Create Network
	network, err := networking.CreateNetwork(t, client)
	if err != nil {
		t.Fatalf("Unable to create network: %v", err)
	}
	defer networking.DeleteNetwork(t, client, network.ID)

	// Create Subnet
	subnet, err := networking.CreateSubnet(t, client, network.ID)
	if err != nil {
		t.Fatalf("Unable to create subnet: %v", err)
	}
	defer networking.DeleteSubnet(t, client, subnet.ID)

	// Define a host
	hostID := "localhost"

	// Create port
	port, err := CreatePortsbinding(t, client, network.ID, subnet.ID, hostID)
	if err != nil {
		t.Fatalf("Unable to create port: %v", err)
	}
	defer networking.DeletePort(t, client, port.ID)

	tools.PrintResource(t, port)

	// Update port
	newPortName := tools.RandomString("TESTACC-", 8)
	updateOpts := ports.UpdateOpts{
		Name: newPortName,
	}
	newPort, err := ports.Update(client, port.ID, updateOpts).Extract()
	if err != nil {
		t.Fatalf("Could not update port: %v", err)
	}

	tools.PrintResource(t, newPort)
}


text:
using NewsSite.IOC;
using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace NewsSite.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            UnityConfig.RegisterComponents();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (!Request.Url.Host.StartsWith("www") && !Request.Url.IsLoopback)
            {
                UriBuilder builder = new UriBuilder(Request.Url);
                builder.Host = "www." + Request.Url.Host;
                Response.StatusCode = 301;
                Response.AddHeader("Location", builder.ToString());
                Response.End();
            }
        }
    }
}


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

<title>QNASavedProgressHelper</title>
<meta name="date" content="2018-09-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.dev.yvgenijsharovskij.n5kanjiandkanjistoryquiz.qna

Class QNASavedProgressHelper

java.lang.Object

com.dev.yvgenijsharovskij.n5kanjiandkanjistoryquiz.qna.QNASavedProgressHelper

public class QNASavedProgressHelper
extends java.lang.Object

QNASavedProgressHelper is hereby defined here as the saved state of the quiz. The saved QNA progress is stored
 internally onPause(), in case the user exits the quiz without finishing it.

Since:

1.0

Author:

Yvgenij Sharovskij

Constructor Summary

Constructors

Constructor and Description

QNASavedProgressHelper(android.content.Context context)

Constructor to instantiate SharedPreferences to the default SharedPreferences.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
getContinueFromSavedProgress()

Gets the saved state to check if the user is continuing from a previously saved quiz session.

java.lang.String
getDuplicatePositiveControlAnswer()

Gets the QNA duplicate positive control (correct) answer from the SharedPreferences.

java.lang.String
getDuplicatePositiveControlQuestion()

Gets the QNA duplicate positive control question from the SharedPreferences.

java.util.ArrayList<java.lang.String>
getNonPrependedList(java.util.ArrayList<java.lang.String> input)

Returns the input list with a removed prepend for each list element for the entire list size.

boolean
getPreferenceKeyAsBoolean(java.lang.String key)

Gets a SharedPreferences key and value of type boolean.

int
getPreferenceKeyAsInt(java.lang.String key)

Checks if the SharedPreferences contains the key and returns its int value.

java.lang.String
getPreferenceKeyAsString(java.lang.String key)

Gets a SharedPreferences key and value of type String.

java.util.Set<java.lang.String>
getPreferenceKeyAsStringSet(java.lang.String key,
                           java.util.Set<java.lang.String> value)

Gets a SharedPreferences key and value of type StringSet.

java.util.ArrayList<java.lang.String>
getPrependedList(java.util.ArrayList<java.lang.String> input,
                int prepend,
                int size)

Returns the input list with a prepend for each list element up to the selected size.

java.util.ArrayList<java.lang.String>
getSavedProgressCorrectAnswer()

Gets the saved progress correct answer list.

java.util.ArrayList<java.lang.String>
getSavedProgressQuestion()

Gets the saved progress question list.

java.util.ArrayList<java.lang.String>
getSavedProgressSelectedAnswer()

Gets the saved progress selected question list.

boolean
isSavedProgressExisting()

Checks if the saved progress exists for the current quiz session.

void
removeQNASavedProgress()

Removes the saved QNA progress from the SharedPreferences.

void
setContinueFromSavedProgress(int progress)

Sets the saved state in case the user is continuing from a previously saved quiz session.

void
setDuplicatePositiveControlAnswer(java.lang.String duplicatePositiveControlAnswer)

Sets the QNA duplicate positive control (correct) answer in the SharedPreferences.

void
setDuplicatePositiveControlQuestion(java.lang.String duplicatePositiveControlQuestion)

Sets the QNA duplicate positive control question in the SharedPreferences.

void
setPreferenceKeyAsBoolean(java.lang.String key,
                         boolean value)

Sets a SharedPreferences key and value of type boolean.

void
setPreferenceKeyAsInt(java.lang.String key,
                     int value)

Sets a SharedPreferences key and value of type int.

void
setPreferenceKeyAsString(java.lang.String key,
                        java.lang.String value)

Sets a SharedPreferences key and value of type String.

void
setPreferenceKeyAsStringSet(java.lang.String key,
                           java.util.Set<java.lang.String> value)

Sets a SharedPreferences key and value of type StringSet.

void
setSavedProgress(java.util.ArrayList<java.lang.String> questionList,
                java.util.ArrayList<java.lang.String> selectedAnswerList,
                java.util.ArrayList<java.lang.String> correctAnswerList)

Saves the QNA progress when the user interrupts the quiz before it's complete.

Methods inherited from class java.lang.Object

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

Constructor Detail

QNASavedProgressHelper

public QNASavedProgressHelper(android.content.Context context)

Constructor to instantiate SharedPreferences to the default SharedPreferences.

Method Detail

setContinueFromSavedProgress

public void setContinueFromSavedProgress(int progress)

Sets the saved state in case the user is continuing from a previously saved quiz session.

Parameters:

progress - 1, if continuing from a previously saved state

getContinueFromSavedProgress

public int getContinueFromSavedProgress()

Gets the saved state to check if the user is continuing from a previously saved quiz session.

Returns:

1, if continuing from a previously saved state

setSavedProgress

public void setSavedProgress(java.util.ArrayList<java.lang.String> questionList,
                             java.util.ArrayList<java.lang.String> selectedAnswerList,
                             java.util.ArrayList<java.lang.String> correctAnswerList)

Saves the QNA progress when the user interrupts the quiz before it's complete.
 In order to have multiple saves of the same progress on multiple quiz tries,
 existing progress is added upon the current quiz progress.

 Note: utilizes a LinkedHashSet which is defined as a hash table and linked list implementation
 of the Set interface used to remember the order in which the elements were inserted into the set,
 and return its elements in that order.

 Note that the insertion order is not affected if an element is re-inserted into the set.

Parameters:

questionList - question list

selectedAnswerList - selected answer list

correctAnswerList - correct answer list

getSavedProgressQuestion

public java.util.ArrayList<java.lang.String> getSavedProgressQuestion()

Gets the saved progress question list.

Returns:

ArrayList<String>: the saved progress question list

getSavedProgressSelectedAnswer

public java.util.ArrayList<java.lang.String> getSavedProgressSelectedAnswer()

Gets the saved progress selected question list.

Returns:

ArrayList<String>: the saved progress selected question list

getSavedProgressCorrectAnswer

public java.util.ArrayList<java.lang.String> getSavedProgressCorrectAnswer()

Gets the saved progress correct answer list.

Returns:

ArrayList<String>: the saved progress correct answer list

isSavedProgressExisting

public boolean isSavedProgressExisting()

Checks if the saved progress exists for the current quiz session.

Returns:

Boolean: true, if the saved progress exists for the current quiz session

getPrependedList

public java.util.ArrayList<java.lang.String> getPrependedList(java.util.ArrayList<java.lang.String> input,
                                                              int prepend,
                                                              int size)

Returns the input list with a prepend for each list element up to the selected size.
 Used to sort the list, which is randomized onCreate.

Parameters:

input - the input list

prepend - the prepend

size - the list size()

Returns:

ArrayList<String>: the input list with a prepend for each list element up to the selected size

getNonPrependedList

public java.util.ArrayList<java.lang.String> getNonPrependedList(java.util.ArrayList<java.lang.String> input)

Returns the input list with a removed prepend for each list element for the entire list size.

Parameters:

input - the input list

Returns:

ArrayList<String>: he input list with a removed prepend for each list element for the entire list size

getPreferenceKeyAsInt

public int getPreferenceKeyAsInt(java.lang.String key)

Checks if the SharedPreferences contains the key and returns its int value.

Parameters:

key - SharedPreferences key

Returns:

int value of the key

setPreferenceKeyAsInt

public void setPreferenceKeyAsInt(java.lang.String key,
                                  int value)

Sets a SharedPreferences key and value of type int.

Parameters:

key - SharedPreferences key

value - int value of the key

getPreferenceKeyAsBoolean

public boolean getPreferenceKeyAsBoolean(java.lang.String key)

Gets a SharedPreferences key and value of type boolean.

Parameters:

key - SharedPreferences key

Returns:

boolean value of the key

setPreferenceKeyAsBoolean

public void setPreferenceKeyAsBoolean(java.lang.String key,
                                      boolean value)

Sets a SharedPreferences key and value of type boolean.

Parameters:

key - SharedPreferences key

value - boolean value of the key

setPreferenceKeyAsString

public void setPreferenceKeyAsString(java.lang.String key,
                                     java.lang.String value)

Sets a SharedPreferences key and value of type String.

Parameters:

key - SharedPreferences key

value - boolean value of the key

getPreferenceKeyAsString

public java.lang.String getPreferenceKeyAsString(java.lang.String key)

Gets a SharedPreferences key and value of type String.

Parameters:

key - SharedPreferences key

Returns:

String value of the key

getPreferenceKeyAsStringSet

public java.util.Set<java.lang.String> getPreferenceKeyAsStringSet(java.lang.String key,
                                                                   java.util.Set<java.lang.String> value)

Gets a SharedPreferences key and value of type StringSet.

Parameters:

key - SharedPreferences key

Returns:

StringSet value of the key

setPreferenceKeyAsStringSet

public void setPreferenceKeyAsStringSet(java.lang.String key,
                                        java.util.Set<java.lang.String> value)

Sets a SharedPreferences key and value of type StringSet.

Parameters:

key - SharedPreferences key

value - StringSet value of the key

getDuplicatePositiveControlQuestion

public java.lang.String getDuplicatePositiveControlQuestion()

Gets the QNA duplicate positive control question from the SharedPreferences.

Returns:

String: the QNA duplicate positive control question.

setDuplicatePositiveControlQuestion

public void setDuplicatePositiveControlQuestion(java.lang.String duplicatePositiveControlQuestion)

Sets the QNA duplicate positive control question in the SharedPreferences.

Parameters:

duplicatePositiveControlQuestion - the QNA duplicate positive control question

getDuplicatePositiveControlAnswer

public java.lang.String getDuplicatePositiveControlAnswer()

Gets the QNA duplicate positive control (correct) answer from the SharedPreferences.

Returns:

String: the QNA duplicate positive control answer.

setDuplicatePositiveControlAnswer

public void setDuplicatePositiveControlAnswer(java.lang.String duplicatePositiveControlAnswer)

Sets the QNA duplicate positive control (correct) answer in the SharedPreferences.

Parameters:

duplicatePositiveControlAnswer - the QNA duplicate positive control question

removeQNASavedProgress

public void removeQNASavedProgress()

Removes the saved QNA progress from the SharedPreferences.

 Note: commit() makes the commit immediately, whereas apply() handles it in the background.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module Cms::Addon
  module Captcha
    extend ActiveSupport::Concern
    extend SS::Addon

    included do
      field :captcha, type: String, default: "enabled"
      permit_params :captcha
    end

    def captcha_options
      [
        [I18n.t('cms.options.state.enabled'), 'enabled'],
        [I18n.t('cms.options.state.disabled'), 'disabled'],
      ]
    end

    def captcha_enabled?
      captcha == "enabled"
    end
  end
end


text:
<?php

defined('ROKBOOSTER_LIB') or die('Restricted access');

/**
 *
 */
class RokBooster_Compressor_FileGroup extends RokBooster_Compressor_AbstractGroup implements IteratorAggregate, ArrayAccess, Countable
{

	/**
	 * @var RokBooster_Compressor_File[]
	 */
	protected $files = array();

	/**
	 * @return string
	 */
	public function getChecksum()
	{
		$files_copy = $this->files;
		if (!isset($this->checksum)) {
			array_multisort($files_copy, SORT_ASC, SORT_STRING);
			$this->checksum = md5(implode('', $files_copy));
		}
		return $this->checksum;
	}

	/**
	 * @param RokBooster_Compressor_File $file
	 */
	public function addItem(RokBooster_Compressor_File $file)
	{
		if (!in_array($file->file, $this->files)) {
			$this->files[] = $file;
		}
	}

	/**
	 * @param RokBooster_Compressor_File $file
	 *
	 * @return bool
	 */
	public function fileBelongs(RokBooster_Compressor_File $file)
	{
		$belong     = false;
		$file_state = self::STATE_IGNORE;
		if (!$file->isExternal() && !$file->isIgnored()) {
			$file_state = self::STATE_INCLUDE;
		}
		if ($this->status == $file_state) {
			$belong = true;
		}
		return $belong;
	}

	/**
	 * @return ArrayIterator
	 */
	public function getIterator()
	{
		return new ArrayIterator($this->files);
	}

	/**
	 * @param $offset
	 *
	 * @return bool
	 */
	public function offsetExists($offset)
	{
		return isset($this->files);
	}

	/**
	 * @param $offset
	 * @param $value
	 */
	public function offsetSet($offset, $value)
	{
		$this->files[$offset] = $value;
	}

	/**
	 * @param $offset
	 *
	 * @return RokBooster_Compressor_File
	 */
	public function offsetGet($offset)
	{
		return $this->files[$offset];
	}

	/**
	 * @param $offset
	 */
	public function offsetUnset($offset)
	{
		unset($this->files[$offset]);
	}

	/**
	 * @return int|void
	 */
	public function count()
	{
		return count($this->files);
	}

	/**
	 *
	 */
	public function cleanup()
	{
		parent::cleanup();
		foreach ($this->files as &$file) {
			$file->content = null;
		}
	}
}


text:
<?php

class LanguageControllerTest extends TestCase
{
    /**
     * @test
     */
    public function a_user_can_see_languages_crud()
    {
        $this->signIn();

        $this->visit('admin')
            ->click('All Languages')
            ->seePageIs('admin/language');
    }
}