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.0">
  <title>Odo Video Demo</title>
  <link rel="stylesheet" href="../demo.css" />
  <link rel="stylesheet" href="styles/demo.css" />
  <link rel="stylesheet" href="css/odo-video.css" />

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/prismjs@1/themes/prism.css">

Odo Video

A lightweight html5 video wrapper.

Support

IE9. No flash fallback. IE9 will need a classList polyfill.

Dependencies

screenfull.js. Assumes ES2015 Promise and Object.assign are available.

      <video>
        <source src="https://giant.gfycat.com/CandidImmaterialDromedary.webm" type="video/webm">
        <source src="https://giant.gfycat.com/CandidImmaterialDromedary.mp4" type="video/mp4">

          Your browser does not support the video element. Source.

      </video>

Styles

      Try a different style for the controls.
      <select id="styles">
        <option value="" selected>Below</option>
        <option value="overlay">Overlay</option>
        <option value="overlay,on-top">Overlay & on top</option>
      </select>

Features

Autoplay support callbacks

Skinnable UI controls

Fullscreen mode

Click-to-seek

Dynamically update source

Hide controls & mouse in fullscreen when idle

Spacebar pauses video in fullscreen mode

Function to define control structure

Callback for updating controls on video progress

Callback for video data events

Markup

You may also add any attributes you normally would to the <video> element.

<div class="odo-video" id="video-wrapper">
  <video>
    <source src="https://giant.gfycat.com/CandidImmaterialDromedary.webm" type="video/webm">
    <source src="https://giant.gfycat.com/CandidImmaterialDromedary.mp4" type="video/mp4">
    <div>
      Your browser does not support the <code>video</code> element. <a href="https://gfycat.com/CandidImmaterialDromedary">Source.</a>
    </div>
  </video>
</div>

Setup

var player = new OdoVideo(document.querySelector('#video-wrapper'));

Control Styles

OdoVideo comes with three built-in styles: below (default), overlay, and on top. All you need to do is add a class (or multiple) to the main .odo-video element.

<div class="odo-video odo-video--overlay">
  <video>…</video>
</div>
<!-- or -->
<div class="odo-video odo-video--overlay odo-video--on-top">
  <video>…</video>
</div>

Control Layouts

OdoVideo comes with three built-in styles: none, inline progress (default), and stacked progress. There is also a fourth option: custom, which lets you define the structure of the controls.

      <video loop>
        <source src="https://giant.gfycat.com/DarkPersonalAfricanjacana.webm" type="video/webm">
        <source src="https://giant.gfycat.com/DarkPersonalAfricanjacana.mp4" type="video/mp4">

          Your browser does not support the video element. Source.

      </video>

// Stacked progress (the one above)
var instance = new OdoVideo(document.querySelector('#stacked'), {
  controls: OdoVideo.Controls.STACKED_PROGRESS
});

// No controls
var instance = new OdoVideo(document.querySelector('#video-wrapper'), {
  controls: OdoVideo.Controls.NONE
});

// Custom
var instance = new OdoVideo(document.querySelector('#video-wrapper'), {
  controls: OdoVideo.Controls.CUSTOM,
  layoutControls: function(elements) {
    // Create your layout here.
  },
  updateControls: function(seconds) {
    // Update any controls here.
    console.log(seconds, instance.getPrettyTime(seconds)); // 2, '0:02'
  }
});

Custom Layout - layoutControls(elements)

When using a custom controls layout, you must specify the layoutControls option. The elements has all the default controls. This is what OdoVideo does internally with the default layout:

Controls.prototype._createInline = function(elements) {
  elements.controls.appendChild(elements.playToggle);
  elements.controls.appendChild(elements.progressContainer);
  elements.controls.appendChild(elements.currentTime);
  elements.controls.appendChild(elements.volumeToggle);
  elements.controls.appendChild(elements.fullScreenToggle);
};

The elements.controls element is then appended to the OdoVideo element.

Custom Layout - updateControls(seconds)

When using a custom layout, you might need to update your controls display as the video progresses. This is a hook to do exactly that and nothing more. The function receives a float with the currentTime value of the video.

Autoplay

This component tests the browser to see if it can autoplay videos. It does this on page load by inserting a base64-encoded video into the page with the autoplay attribute set and then checks to see if it started. This test can occasionally give false negatives (mostly in IE) due to page load speed. OdoVideo will save the result of the autoplay test in the browser's localStorage as videoautoplay. To mitigate false negatives, if the test fails, OdoVideo will run the test again on the next page load - up to 3 times.

To provide a different fallback for browsers which cannot autoplay videos, use the autoplay promise of the instance or the static autoplay promise of the class.

In order to autoplay videos on iOS, there are some stipulations you must follow. Setting the muted and playsinline attributes should usually be all you need.

function handleAutoplay(canAutoplay) {
  if (canAutoplay) {
    console.log('Can autoplay');
  } else {
    console.log('Cannot autoplay');
  }
}

player.autoplay.then(handleAutoplay);

// Or

OdoVideo.autoplay.then(handleAutoplay);

API

Public methods of OdoVideo instances.

play()

Play the video.

pause()

Pause the video.

togglePlayback()

If the video is playing, pause it. If the video is paused, play it.

getElement()

Returns the main element of the OdoVideo component.

getVideoElement()

Returns the <video> element.

listenOnData(event, cb)

Fires a callback function when the video readyState is greater than 1, or the video event passed as the event parameter.

getCurrentTime()

Returns the video element’s currentTime property.

mute()

Mute the video.

unmute()

Unmute the video.

toggleVolume()

If the volume is muted, unmute it. If the volume is unmuted, mute it.

isMuted()

Returns whether the video is currently muted.

updateSource(src)

Update the current video source. This method changes the appropriate <source> src property because IE9 does not work when the <video>s src property or attribute is updated. The parameter is an absolute or relative path to the video, without the extension. .e.g. "/videos/cool-feature". OdoVideo will pick the correct extension/type based on its support.

getPrettyTime()

Converts a time value to MMSS, so 91 seconds is "1:31".

toggleFullscreen()

Request or exit from fullscreen.

dispose()

Remove all event listeners, references to DOM elements, and generated elements.

DOM Video Events

These exist within the OdoVideo.VideoEvent object.

LOADED_METADATA

      {
        name: 'loadedmetadata',
        readyState: 1
      }

Corresponds to the loadedmetadata event. Video metadata, such as dimensions and track, have been loaded.

LOADED_DATA

      {
        name: 'loadeddata',
        readyState: 2
      }

Corresponds to the loadeddata event. Video data for the current frame has been loaded, but not enough to play the next frame.

CAN_PLAY

      {
        name: 'canplay',
        readyState: 3
      }

Corresponds to the canplay event. The browser has downloaded enough of the video to play, but may still need buffering during playback.

CAN_PLAYTHROUGH

      {
        name: 'canplaythrough',
        readyState: 4
      }

Corresponds to the canplaythrough event. The browser has downloaded enough of the video to play without buffering.

Removing focus box.

Although not recommended, you may remove the focus state from the buttons.

.odo-video__play-toggle:focus,
.odo-video__volume:focus,
.odo-video__fullscreen:focus {
  box-shadow: none;
}

Options

pauseOnClick: true

When the video element is clicked, pause the video.

controls, layoutControls, updateControls

All described above.

Resources

MDN HTML Media Element

MDN Media Events

Fullscreen API

Controlling media with JavaScript on iOS


text:
package com.alorma.github.ui.activity;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.ImageView;

import com.alorma.github.R;
import com.alorma.github.sdk.bean.dto.response.User;
import com.alorma.github.sdk.services.user.GithubUsersClient;
import com.alorma.github.sdk.utils.GitskariosSettings;
import com.alorma.gitskarios.basesdk.client.BaseClient;
import com.alorma.github.sdk.services.user.BaseUsersClient;
import com.alorma.github.sdk.services.user.GetAuthUserClient;
import com.alorma.github.sdk.services.user.RequestUserClient;
import com.alorma.github.sdk.services.user.follow.CheckFollowingUser;
import com.alorma.github.sdk.services.user.follow.FollowUserClient;
import com.alorma.github.sdk.services.user.follow.OnCheckFollowingUser;
import com.alorma.github.sdk.services.user.follow.UnfollowUserClient;
import com.alorma.github.ui.activity.base.BackActivity;
import com.alorma.github.ui.activity.gists.GistsMainActivity;
import com.alorma.github.ui.cards.profile.BioCard;
import com.alorma.github.ui.cards.profile.GithubDataCard;
import com.alorma.github.ui.cards.profile.GithubPlanCard;
import com.alorma.github.ui.utils.PaletteUtils;
import com.alorma.github.ui.view.FABCenterLayout;
import com.alorma.github.utils.AttributesUtils;
import com.alorma.gitskarios.basesdk.client.StoreCredentials;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.octicons_typeface_library.Octicons;

import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Bernat on 15/07/2014.
 */
public class ProfileActivity extends BackActivity implements BaseClient.OnResultCallback<User>,
		PaletteUtils.PaletteUtilsListener, BioCard.BioCardListener,
		GithubDataCard.GithubDataCardListener,
		FABCenterLayout.FABScrollContentListener,
		OnCheckFollowingUser, GithubPlanCard.GithubDataCardListener, View.OnClickListener {

	private static final String USER = "USER";
	private static final String FROM_INTENT_FILTER = "FROM_INTENT_FILTER";

	private ImageView image;
	private FABCenterLayout fabLayout;

	private int avatarColor;
	private int avatarSecondaryColor;

	private User user;
	private boolean followingUser = false;
	private boolean isAuthUser;
	private IconicsDrawable fabDrawable;

	public static Intent createLauncherIntent(Context context) {
		return new Intent(context, ProfileActivity.class);
	}

	public static Intent createLauncherIntent(Context context, User user) {
		Intent intent = new Intent(context, ProfileActivity.class);
		if (user != null) {
			intent.putExtra(USER, user);
		}
		return intent;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile_activity);

		avatarColor = AttributesUtils.getAccentColor(this);
		avatarSecondaryColor = AttributesUtils.getPrimaryColor(this);

		fabLayout = (FABCenterLayout) findViewById(R.id.fabLayout);
		fabLayout.setFabViewVisibility(View.INVISIBLE, false);
		fabLayout.setVisibility(View.INVISIBLE);

		fabLayout.setFabScrollContentListener(this);
		image = (ImageView) findViewById(R.id.image);
	}

	@Override
	protected void getContent() {
		GithubUsersClient<User> requestClient;
		user = null;
		if (getIntent().getExtras() != null) {
			if (getIntent().getExtras().containsKey(USER)) {
				user = getIntent().getParcelableExtra(USER);
			}
		}

		StoreCredentials settings = new StoreCredentials(this);

		if (user != null) {
			if (user.login.equalsIgnoreCase(settings.getUserName())) {
                isAuthUser = true;
				requestClient = new GetAuthUserClient(this);
			} else {
				requestClient = new RequestUserClient(this, user.login);
				getToolbar().setTitle(user.login);
			}
		} else {
            isAuthUser = true;
			requestClient = new GetAuthUserClient(this);
		}

		showProgressDialog(R.style.SpotDialog_LoadingUser);

		requestClient.setOnResultCallback(this);
		requestClient.execute();
	}

	@Override
	public void onResponseOk(User user, Response r) {
		this.user = user;
		getToolbar().setTitle(user.login);

		hideProgressDialog();

		if (isAuthUser) {
			fabLayout.removeFab();

		} else {
			CheckFollowingUser checkFollowingUser = new CheckFollowingUser(this, user.login);
			checkFollowingUser.setOnCheckFollowingUser(this);
			checkFollowingUser.execute();
		}

		if (getSupportActionBar() != null) {
			new PaletteUtils().loadImageAndPalette(user.avatar_url, this);
		}

		fabLayout.setVisibility(View.VISIBLE);
	}

    @Override
    public void onImageLoaded(Bitmap loadedImage, Palette palette) {

        Palette.Swatch profileSwatchDark = PaletteUtils.getProfileSwatchDark(palette);
        Palette.Swatch profileSwatch = PaletteUtils.getProfileSwatch(palette);

        Drawable drawable = new BitmapDrawable(getResources(), loadedImage);

        image.setImageDrawable(drawable);
        if (profileSwatchDark != null && profileSwatch != null) {
            avatarColor = profileSwatchDark.getRgb();
            avatarSecondaryColor = profileSwatch.getRgb();

            try {
                if (avatarColor != 0) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(avatarColor);
                        getWindow().setNavigationBarColor(avatarColor);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        fillCardBio(user);

        fillCardGithubData(user);

        fillCardPlan(user);
    }

	private void fillCardBio(User user) {
		CardView view = (CardView) findViewById(R.id.bioCardLayout);
		view.setCardElevation(4);
		BioCard card = new BioCard(user, view, avatarColor);
		card.setBioCardListener(this);
	}

	private void fillCardGithubData(User user) {
		CardView view = (CardView) findViewById(R.id.dataCardLayout);
		view.setCardElevation(4);
		GithubDataCard dataCard = new GithubDataCard(user, view, avatarColor);
		dataCard.setGithubDataCardListener(this);
	}

	private void fillCardPlan(User user) {
		CardView view = (CardView) findViewById(R.id.planCardLayout);
		view.setCardElevation(4);
		if (user.plan != null) {
			GithubPlanCard dataCard = new GithubPlanCard(user, view, avatarColor);
			dataCard.setGithubDataCardListener(this);
		} else {
			view.setVisibility(View.GONE);
		}
	}

	@Override
	public void onFail(RetrofitError error) {
		hideProgressDialog();
	}

	@Override
	public void onCompanyRequest(String company) {
		Intent intent = new Intent(Intent.ACTION_SEARCH);
		intent.putExtra(SearchManager.QUERY, company);
		if (intent.resolveActivity(getPackageManager()) != null) {
			startActivity(intent);
		}
	}

	@Override
	public void onLocationRequest(String location) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri geo = Uri.parse("geo:0,0?q=" + location);
		intent.setData(geo);
		if (intent.resolveActivity(getPackageManager()) != null) {
			startActivity(intent);
		}
	}

	@Override
	public void onMailRequest(String mail) {
		Intent intent = new Intent(Intent.ACTION_SENDTO);
		intent.setData(Uri.parse("mailto:"));
		intent.putExtra(Intent.EXTRA_EMAIL, new String[]{mail});
		if (intent.resolveActivity(getPackageManager()) != null) {
			startActivity(intent);
		}
	}

	@Override
	public void onRepositoriesRequest(String username) {
		Intent intent = ReposActivity.launchIntent(this, username, user.type);
		startActivity(intent);
	}

	@Override
	public void onOrganizationsRequest(String username) {
		Intent intent = OrganizationsActivity.launchIntent(this, username);
		startActivity(intent);
	}

	@Override
	public void onGistsRequest(String username) {
		Intent intent = GistsMainActivity.createLauncherIntent(this, username);
		startActivity(intent);
	}

	@Override
	public void onStarredRequest(String username) {
		Intent intent = StarredReposActivity.launchIntent(this, username);
		startActivity(intent);
	}

	@Override
	public void onWatchedRequest(String username) {
		Intent intent = WatchedReposActivity.launchIntent(this, username);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		showProgressDialog(R.style.SpotDialog_LoadingUser);

		fabLayout.setFabClickListener(null, getTagFab());

		if (followingUser) {
			UnfollowUserClient unfollowUserClient = new UnfollowUserClient(this, user.login);
			unfollowUserClient.setOnCheckFollowingUser(this);
			unfollowUserClient.execute();
		} else {
			FollowUserClient followUserClient = new FollowUserClient(this, user.login);
			followUserClient.setOnCheckFollowingUser(this);
			followUserClient.execute();
		}
		fabLayout.setFabClickListener(null, null);
	}

	@Override
	public void onScrollFactor(int alpha, float factor) {
		if (getSupportActionBar() != null) {
			ColorDrawable cd = new ColorDrawable(avatarColor);

			if (alpha < 0) {
				alpha = -alpha;
			}

			if (alpha > 255) {
				alpha = 255;
			}

			cd.setAlpha(alpha);

			getSupportActionBar().setBackgroundDrawable(cd);
		}
	}

	@Override
	public void onCheckFollowUser(String username, boolean following) {
		followingUser = following;

		hideProgressDialog();

		fabDrawable = new IconicsDrawable(this, Octicons.Icon.oct_heart);
		if (following) {
			fabDrawable.color(avatarColor);
		} else {
			fabDrawable.color(PaletteUtils.colorTextFromBackgroundColor(avatarSecondaryColor));
		}
		fabDrawable.actionBarSize();
		fabLayout.setFabIcon(fabDrawable);

		fabLayout.setFabColor(avatarSecondaryColor);

		fabLayout.setFabColorPressed(avatarColor);

		fabLayout.setFabClickListener(this, getTagFab());
		fabLayout.setFabViewVisibility(View.VISIBLE, false);
	}

	public String getTagFab() {
		int string = followingUser ? R.string.unfollow : R.string.follow;
		return getString(string);
	}
}

redpajama_set_name: RedPajamaGithub


text:
/*Sydnee Wren
 * Homework 5
 */

import java.util.Scanner;

public class GradeReport {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);

		//user input
		System.out.print("Please enter your test grade (between 0 and 100): ");
		int grade = in.nextInt();
		int tries = 0;

		//error and tries
		do {
			if (grade < 0 || grade > 100) {
				System.out.println("Error! Please enter a grade between 0 and 100!");
				System.out.print("Please enter your test grade (between 0 and 100): ");
				grade = in.nextInt();
			}

			++tries;

		} while (tries < 2);

		//Prints grades
		 if (grade >= 0 || grade <= 100 ) {
			 switch (grade/10){
			case 1:
				System.out.println("AN F!!!! You bring dishonor upon your family. Go study!");
				break;
			case 2:
			case 3:
			case 4:
			case 5:
			case 6:
			case 7:
				System.out.println("Yikes! A C is too close failing. Crack open those notes and get some knowledge!");
				break;
			case 8:
				System.out.println("B's are no laughing matter! Still pretty good.");
				break;
			case 9:
				System.out.println("A! That's an awesome grade!");
				break;
			case 10:
				System.out.println("A+! That's a perfect score!");
				break;
			default:
				System.out.println("Error!");
			}
		in.close();
		}
	}
}


text:
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.DiagnosticsModule
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Tracing;

    /// <summary>
    /// Subscriber to ETW Event source events, which sends data to other Senders (F5 and Portal).
    /// </summary>
    internal class DiagnosticsListener : IDisposable
    {
        private readonly IList<IDiagnosticsSender> diagnosticsSenders = new List<IDiagnosticsSender>();
        private EventLevel logLevel = EventLevel.Error;
        private DiagnosticsEventListener eventListener;

        public DiagnosticsListener(IList<IDiagnosticsSender> senders)
        {
            if (senders == null || senders.Count < 1)
            {
                throw new ArgumentNullException(nameof(senders));
            }

            this.diagnosticsSenders = senders;
            this.eventListener = new DiagnosticsEventListener(this, this.LogLevel);
        }

        public EventLevel LogLevel
        {
            get => this.logLevel;

            set
            {
                if (this.LogLevel != value)
                {
                    var oldListener = this.eventListener;
                    this.eventListener = new DiagnosticsEventListener(this, value);
                    oldListener.Dispose();
                }

                this.logLevel = value;
            }
        }

        /// <summary>
        /// Sets LogLevel. Possible values LogAlways, Critical, Error, Warning, Informational and Verbose.
        /// </summary>
        public void SetLogLevel(string value)
        {
            // Once logLevel is set from configuration, restart listener with new value
            if (!string.IsNullOrEmpty(value))
            {
                EventLevel parsedValue;
                if (Enum.IsDefined(typeof(EventLevel), value) == true)
                {
                    parsedValue = (EventLevel)Enum.Parse(typeof(EventLevel), value, true);
                    this.LogLevel = parsedValue;
                }
            }
        }

        public void WriteEvent(TraceEvent eventData)
        {
            if (eventData.MetaData != null && eventData.MetaData.MessageFormat != null)
            {
                // check severity because it is not done in Silverlight EventSource implementation
                if (eventData.MetaData.Level <= this.LogLevel)
                {
                    foreach (var sender in this.diagnosticsSenders)
                    {
                        sender.Send(eventData);
                    }
                }
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.eventListener.Dispose();
            }
        }
    }
}


text:
<component name="ProjectCodeStyleConfiguration">
  <code_scheme name="Project" version="173">
    <option name="OTHER_INDENT_OPTIONS">
      <value>
        <option name="USE_TAB_CHARACTER" value="true" />
        <option name="SMART_TABS" value="true" />
      </value>
    </option>
    <option name="LINE_SEPARATOR" value="
" />
    <JavaCodeStyleSettings>
      <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="15" />
    </JavaCodeStyleSettings>
    <XML>
      <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
    </XML>
    <codeStyleSettings language="HTML">
      <indentOptions>
        <option name="USE_TAB_CHARACTER" value="true" />
        <option name="SMART_TABS" value="true" />
      </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="JavaScript">
      <indentOptions>
        <option name="USE_TAB_CHARACTER" value="true" />
      </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="PHP">
      <indentOptions>
        <option name="USE_TAB_CHARACTER" value="true" />
        <option name="SMART_TABS" value="true" />
      </indentOptions>
    </codeStyleSettings>
  </code_scheme>
</component>


text:
#include <aws/codepipeline/model/DeregisterWebhookWithThirdPartyResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::CodePipeline::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

DeregisterWebhookWithThirdPartyResult::DeregisterWebhookWithThirdPartyResult()
{
}

DeregisterWebhookWithThirdPartyResult::DeregisterWebhookWithThirdPartyResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

DeregisterWebhookWithThirdPartyResult& DeregisterWebhookWithThirdPartyResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
package language.lispy

import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import scala.util.parsing.combinator._

@RunWith(classOf[JUnitRunner])
class ParsingSuite extends FunSuite {
    import LispyParser._

    val trickySymbol = "a-Valid-symbol12?!*"

    // Ordered as test, expected, comment
    val listTests = List(
        ("()", LIST(List()), "Empty list"),
        ("(1)", LIST(List(NUMBER(1))), "List containing a single number"),
        ("(1 2 abcd)", LIST(List(NUMBER(1), NUMBER(2), SYMBOL("abcd"))), "1,2,3"),
        ("(() (1 abc #f))", LIST(List(LIST(List()), LIST(List(NUMBER(1), SYMBOL("abc"), BOOLEAN(false))))), "Nesting"))

    def testParsing[T, E](parser: Parser[T], text: String, expected: E) = {
        assert(parse(text)(parser) === expected)
    }

    test("Parsing symbols using symbol parser") {
        testParsing(symbol, trickySymbol, SYMBOL(trickySymbol.toLowerCase()))
    }

    test("Parsing symbols with expression parser") {
        testParsing(expr, trickySymbol, SYMBOL(trickySymbol.toLowerCase()))
    }

    test("Parsing numbers using number parser") {
        testParsing(number, "12345", NUMBER(12345))
        testParsing(number, "12345.12345", NUMBER(12345.12345))
    }

    test("Parsing numbers using expression parser") {
        testParsing(expr, "12345", NUMBER(12345))
        testParsing(expr, "12345.12345", NUMBER(12345.12345))
    }

    test("Parsing booleans using boolean parser") {
        testParsing(boolean, "#t", BOOLEAN(true))
        testParsing(boolean, "#f", BOOLEAN(false))
        testParsing(boolean, "#T", BOOLEAN(true))
        testParsing(boolean, "#F", BOOLEAN(false))
    }

    test("Parsing booleans using expression parser") {
        testParsing(boolean, "#t", BOOLEAN(true))
        testParsing(boolean, "#f", BOOLEAN(false))
        testParsing(boolean, "#T", BOOLEAN(true))
        testParsing(boolean, "#F", BOOLEAN(false))
    }

    test("Parsing simple lists using list parser") {
        listTests foreach (
            test => testParsing(list, test._1, test._2))
    }

    test("Parsing simple lists using expression parser") {
        listTests foreach (
            test => testParsing(expr, test._1, test._2))
    }

    test("Quoted list using expression parser") {
        listTests foreach (
            test => testParsing(expr, "'" + test._1, QUOTE(test._2)))
    }

    test("Quoted symbol, number") {
        testParsing(expr, "'a", QUOTE(SYMBOL("a")))
        testParsing(expr, "'12", QUOTE(NUMBER(12)))
    }

    test("Comments should be ignored until EOL") {
        testParsing(expr, "a;ignorethis", SYMBOL("a"))
        testParsing(expr, "12;", NUMBER(12))
    }

    test("Nested comments") {
        testParsing(expr, "a;b;c;d", SYMBOL("a"))
    }

    test("Comments should last only until EOL") {
        testParsing(program, "a; somecomment\nb;othercomment", List(SYMBOL("a"), SYMBOL("b")))
    }

    test("String parsing") {
        testParsing(expr, "\"\"", STRING(""))
        testParsing(expr, "\"hello world!\"", STRING("hello world!"))
    }
}


text:
import unittest
from asciimatics.paths import Path
from asciimatics.sprites import Sam, Arrow, Plot

class TestSprites(unittest.TestCase):
    def test_init(self):
        # Most of the function in these classes is actually in the Sprite
        # base Effect - so just check we can build these classes
        self.assertIsNotNone(Sam(None, Path()))
        self.assertIsNotNone(Arrow(None, Path()))
        self.assertIsNotNone(Plot(None, Path()))

if __name__ == '__main__':
    unittest.main()


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Slamby.TAU.Helper;
using Slamby.TAU.ViewModel;

namespace Slamby.TAU.Test
{
    [TestClass]
    public class MainViewModelTest
    {
        [TestMethod]
        public void LoadTest()
        {
            //GlobalStore.IsInTestMode = true;
            //var vm = new MainViewModel();
            //vm.LoadCommand.Execute(null);
        }
    }
}


text:
. ./scripts/planetlab/pl-common.sh

if [ ! -f "$JAR" ]; then
	echo "file $JAR not found" && exit 1
fi

# TOPOLOGY
DCS[0]=${EC2_PROD_EU_MICRO[0]}
DCSEQ[0]=${EC2_PROD_EU_MICRO[0]}

DCS[1]=${EC2_PROD_EU_MICRO[1]}
DCSEQ[1]=${EC2_PROD_EU_MICRO[1]}

DC_CLIENTS=("${PLANETLAB_NODES[@]}")

MACHINES="${DCS[*]} ${DCSEQ[*]} ${DC_CLIENTS[*]}"

DEPLOY=true

echo "==== KILLING EXISTING SERVERS AND CLIENTS ===="
. ./scripts/planetlab/pl-kill.sh $MACHINES
echo "==== DONE ===="

sleep 10

ant -buildfile smd-jar-build.xml

if [ ! -f "$JAR" ]; then
echo "file $JAR not found" && exit 1
fi

echo "==== DEPLOYING SWIFTCLOUD BINARIES ===="
if [ -n "$DEPLOY" ]; then
	deploy_swift_on_many $MACHINES
fi

C1=${PLANETLAB_NODES[0]}
C2=${PLANETLAB_NODES[1]}

DC1=${DCS[0]}
DC2=${DCS[0]}

DOC_PATCHES=swiftdoc-patches.zip
echo "==== COPYING DOC-PATCHES TO CLIENT1 ===="
copy_to_bg data/swiftdoc/$DOC_PATCHES $C1 $DOC_PATCHES

echo "==== STARTING SEQUENCERS AND DC SERVERS ===="
. ./scripts/planetlab/pl-start-servers-ds-seq.sh
servers_start DCS DCSEQ

echo "waiting a bit before starting clients"
sleep 10

echo "starting clients"
swift_app_cmd -Xmx1000m swift.application.swiftdoc.SwiftDocBenchmark

NOTIFICATIONS=true
ISOLATION=REPEATABLE_READS
CACHING=CACHED
ITERATIONS=1

echo "starting client 2"
run_cmd_bg $C2 $CMD $DC1 $ITERATIONS 2 $ISOLATION $CACHING $NOTIFICATIONS

echo "starting client 1"
run_cmd_bg $C1 $CMD $DC1 $ITERATIONS 1 $ISOLATION $CACHING $NOTIFICATIONS
wait $!

echo "killing servers"
echo "==== KILLING SERVERS AND CLIENTS ===="
. ./scripts/planetlab/pl-kill.sh $MACHINES

echo "collecting client log to result log"
run_cmd $C1 "cat stdout.txt" > results/result-swiftdoc-$ISOLATION-$CACHING-$NOTIFICATIONS.log
#less results/result-swiftdoc-$ISOLATION-$CACHING-$NOTIFICATIONS.log


text:
This example demonstrates the use of System::Windows::Forms::GroupBox control.

Windows :

![GitHub Logo](../../../docs/Pictures/Examples/Forms/GroupBoxW.png)

macOS :

![GitHub Logo](../../../docs/Pictures/Examples/Forms/GroupBoxM.png)

Ubuntu :

![GitHub Logo](../../../docs/Pictures/Examples/Forms/GroupBoxU.png)

Gnome :

![GitHub Logo](../../../docs/Pictures/Examples/Forms/GroupBoxG.png)

GnomeDark :

![GitHub Logo](../../../docs/Pictures/Examples/Forms/GroupBoxGD.png)


text:
package org.apache.activemq.artemis.tests.integration.clientcrash;

import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.api.core.client.ActiveMQClient;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientProducer;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory;
import org.apache.activemq.artemis.jms.client.ActiveMQTextMessage;
import org.jboss.logging.Logger;

/**
 * Code to be run in an external VM, via main()
 */
public class GracefulClient {
   private static final Logger log = Logger.getLogger(GracefulClient.class);

   // Constants ------------------------------------------------------------------------------------

   // Static ---------------------------------------------------------------------------------------

   public static void main(final String[] args) throws Exception {
      if (args.length != 2) {
         throw new Exception("require 2 arguments: queue name + message text");
      }
      String queueName = args[0];
      String messageText = args[1];

      try {
         ServerLocator locator = ActiveMQClient.createServerLocatorWithoutHA(new TransportConfiguration(NettyConnectorFactory.class.getName()));
         ClientSessionFactory sf = locator.createSessionFactory();
         ClientSession session = sf.createSession(false, true, true);
         ClientProducer producer = session.createProducer(queueName);
         ClientConsumer consumer = session.createConsumer(queueName);

         ClientMessage message = session.createMessage(ActiveMQTextMessage.TYPE, false, 0, System.currentTimeMillis(), (byte) 1);
         message.getBodyBuffer().writeString(messageText);
         producer.send(message);

         session.start();

         // block in receiving for 5 secs, we won't receive anything
         consumer.receive(5000);

         // this should silence any non-daemon thread and allow for graceful exit
         session.close();
         System.exit(0);
      } catch (Throwable t) {
         GracefulClient.log.error(t.getMessage(), t);
         System.exit(1);
      }
   }

   // Attributes -----------------------------------------------------------------------------------

   // Constructors ---------------------------------------------------------------------------------

   // Command implementation -----------------------------------------------------------------------

   // Public ---------------------------------------------------------------------------------------

   // Package protected ----------------------------------------------------------------------------

   // Protected ------------------------------------------------------------------------------------

   // Private --------------------------------------------------------------------------------------

   // Inner classes --------------------------------------------------------------------------------

}


text:
"""This module is deprecated. Please use `airflow.providers.docker.hooks.docker`."""

import warnings

# pylint: disable=unused-import
from airflow.providers.docker.hooks.docker import DockerHook  # noqa

warnings.warn(
    "This module is deprecated. Please use `airflow.providers.docker.hooks.docker`.",
    DeprecationWarning,
    stacklevel=2,
)


text:
static void button_interrupt(int irq, void *dev_id, struct pt_regs *regs);
static struct timer_list mygpiotimer;
static int GPIO_MAJOR = 0;
static int pressed = 0;
static int id;
static DECLARE_WAIT_QUEUE_HEAD(wait_queue);

int led = 0;

static void button_interrupt(int irq, void *dev_id, struct pt_regs *regs){
	wake_up_interruptible(&wait_queue);
}

void myGpiofunction(unsigned long data){
	if (pressed == 1) kill_proc(id,SIGUSR2,1);
	pressed = 0;
	mygpiotimer.expires = jiffies + TIMER_INTERVAL;
	add_timer(&mygpiotimer);
}

ssize_t gpio_write(struct file *inode, const char * gdata, size_t length, loff_t * off_what){
	get_user(id,(int *)gdata);
	init_timer(&mygpiotimer);
	mygpiotimer.expires = jiffies + TIMER_INTERVAL;
	mygpiotimer.function = &myGpiofunction;
	add_timer(&mygpiotimer);
	return length;
}

ssize_t gpio_read(struct file *inode, char *gdata, size_t length, loff_t *off_what){
	write_led();
	return length;
}

static int gpio_open(struct inode *inode, struct file *filp){
	int res;
	unsigned int gafr;

	gafr = 0x3;
	GAFR0_U &= ~gafr;

        printk("IRQ_BUTTON = %d\n",IRQ_BUTTON);
        printk("IRQ_TO_GPIO = %d\n",IRQ_TO_GPIO_2_80(IRQ_BUTTON));

	GPDR(IRQ_TO_GPIO_2_80(IRQ_BUTTON)) &= ~GPIO_bit(IRQ_TO_GPIO_2_80(IRQ_BUTTON));
	set_GPIO_IRQ_edge(IRQ_TO_GPIO_2_80(IRQ_BUTTON),GPIO_FALLING_EDGE);

	res = request_irq(IRQ_BUTTON,&button_interrupt,SA_INTERRUPT,"Button",NULL);
	if(res < 0)
		printk(KERN_ERR "%s: Request for IRQ %d failed\n",__FUNCTION__,IRQ_BUTTON);
	else {
		enable_irq(IRQ_BUTTON);
	}

	MOD_INC_USE_COUNT;
	return 0;
}

static int gpio_release(struct inode *inode, struct file *filp)
{
	free_irq(IRQ_BUTTON,NULL);
	disable_irq(IRQ_BUTTON);
	del_timer(&mygpiotimer);
	MOD_DEC_USE_COUNT;
	return 0;
}

static int write_led()
{
	unsigned int gafr;

	gafr = 0x3;
	GAFR0_U &= ~gafr;

	if(led == 0)
	{
		GPSR0 = GPSR0 | 0x20000;
		led =1;
	}else{
		GPCR0 = GPCR0 | 0x20000;
		led =0;
	}

}

static struct file_operations gpio_fops = {
	read: gpio_read,
	write: gpio_write,
	open:	gpio_open,
	release:	gpio_release,
};

int init_module(void){
	int result;
	result = register_chrdev(GPIO_MAJOR,"GPIO INTERRUPT",&gpio_fops);

	if(result < 0) {
		printk(KERN_WARNING"Can't get major %d\n",GPIO_MAJOR);
		return result;
	}

	if(GPIO_MAJOR == 0) GPIO_MAJOR = result;
	printk("init module, GPIO major number : %d\n",result);

	return 0;
}

void cleanup_module(void){
	unregister_chrdev(GPIO_MAJOR,"GPIO INTERRUPT");
	return;
}


text:
[![line-diff](http://i.imgur.com/LBR41CC.png)](#)

# line-diff

 [![Support me on Patreon][badge_patreon]][patreon] [![Buy me a book][badge_amazon]][amazon] [![PayPal][badge_paypal_donate]][paypal-donations] [![Ask me anything](https://img.shields.io/badge/ask%20me-anything-1abc9c.svg)](https://github.com/IonicaBizau/ama) [![Version](https://img.shields.io/npm/v/line-diff.svg)](https://www.npmjs.com/package/line-diff) [![Downloads](https://img.shields.io/npm/dt/line-diff.svg)](https://www.npmjs.com/package/line-diff) [![Get help on Codementor](https://cdn.codementor.io/badges/get_help_github.svg)](https://www.codementor.io/johnnyb?utm_source=github&utm_medium=button&utm_term=johnnyb&utm_campaign=github)

> Compare strings line by line.

## :cloud: Installation

```sh
# Using npm
npm install --save line-diff

# Using yarn
yarn add line-diff
```

## :clipboard: Example

```js
const LineDiff = require("line-diff")
    , fs = require("fs")

// Show differences between the two files
console.log(
    new LineDiff(
        fs.readFileSync(__dirname + "/1.txt", "utf-8")
      , fs.readFileSync(__dirname + "/2.txt", "utf-8")
    ).toString()
)
//   not modified
// - old
// - deleted
// -
// - 12345
// + new
// + 1234

console.log(
    new LineDiff(
        fs.readFileSync(__dirname + "/1.txt", "utf-8")
      , fs.readFileSync(__dirname + "/2.txt", "utf-8")
      , 3
    ).toString()
)
//   not modified
//   new
// - deleted
// -
// - 12345
// + 1234
```

## :question: Get Help

There are few ways to get help:

 1. Please [post questions on Stack Overflow](https://stackoverflow.com/questions/ask). You can open issues with questions, as long you add a link to your Stack Overflow question.
 2. For bug reports and feature requests, open issues. :bug:
 3. For direct and quick help, you can [use Codementor](https://www.codementor.io/johnnyb). :rocket:

## :memo: Documentation

### `Diff(oldLines, newLines, sensitivity)`
Compares strings line by line.

#### Params

- **String|Array** `oldLines`: The old lines.
- **String|Array** `newLines`: The new lines.
- **Number** `sensitivity`: A number representing how many changes should be there to consider that a line was changed (default: `0`).

#### Return
- **Diff** The `Diff` object containing:
 - `old_lines` (Array|String): The old lines.
 - `new_lines` (Array|String): The new lines.
 - `sensitivity` (Number): The diff sensitivity.
 - `changes` (Array): An array of `Change` objects.
 - `toString` (Function): A function to stringify the diff.

### `toString()`
Converts the lines comparison into a string.

#### Return
- **String** The stringified diff.

## :yum: How to contribute
Have an idea? Found a bug? See [how to contribute][contributing].

## :sparkling_heart: Support my projects
I open-source almost everything I can, and I try to reply to everyone needing help using these projects. Obviously,
this takes time. You can integrate and use these projects in your applications *for free*! You can even change the source code and redistribute (even resell it).

However, if you get some profit from this or just want to encourage me to continue creating stuff, there are few ways you can do it:

 - Starring and sharing the projects you like :rocket:
 - [![Buy me a book][badge_amazon]][amazon]—I love books! I will remember you after years if you buy me one. :grin: :book:
 - [![PayPal][badge_paypal]][paypal-donations]—You can make one-time donations via PayPal. I'll probably buy a ~~coffee~~ tea. :tea:
 - [![Support me on Patreon][badge_patreon]][patreon]—Set up a recurring monthly donation and you will get interesting news about what I'm doing (things that I don't share with everyone).
 - **Bitcoin**—You can send me bitcoins at this address (or scanning the code below): `1P9BRsmazNQcuyTxEqveUsnf5CERdq35V6`

    ![](https://i.imgur.com/z6OQI95.png)

Thanks! :heart:

## :dizzy: Where is this library used?
If you are using this library in one of your projects, add it in this list. :sparkles:

 - `css-modules-typescript-loader`
 - `diffr`
 - `@morlz/css-modules-typescript-loader`
 - `@alza54/css-modules-typescript-loader`
 - `@beisen/css-modules-typescript-loader`
 - `@kodyl/css-modules-typescript-loader`
 - `css-interface-loader`
 - `@personio/css-modules-typescript-loader`

## :scroll: License

[MIT][license] © [Ionică Bizău][website]

[license]: /LICENSE
[website]: https://ionicabizau.net
[contributing]: /CONTRIBUTING.md
[docs]: /DOCUMENTATION.md
[badge_patreon]: https://ionicabizau.github.io/badges/patreon.svg
[badge_amazon]: https://ionicabizau.github.io/badges/amazon.svg
[badge_paypal]: https://ionicabizau.github.io/badges/paypal.svg
[badge_paypal_donate]: https://ionicabizau.github.io/badges/paypal_donate.svg
[patreon]: https://www.patreon.com/ionicabizau
[amazon]: http://amzn.eu/hRo9sIZ
[paypal-donations]: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RVXDDLKKLQRJW


text:
import json
import requests
import re
import unittest
from testconfig import config
from bitcasa import BitcasaClient
from bitcasa.client import BASEURL
from urllib import urlencode
import urlparse
from StringIO import StringIO

class TestClient(unittest.TestCase):
    def setUp(self):
        if 'client' not in config:
            raise ValueError('No client section found in config')
        if 'client_id' not in config['client']:
            raise ValueError('client_id not found in client config')
        if 'secret' not in config['client']:
            raise ValueError('secret not found in client config')
        self.client_id = config['client']['client_id']
        self.secret = config['client']['secret']

        if 'user' not in config:
            raise ValueError('No user section found in config')
        if 'username' not in config['user']:
            raise ValueError('No username found in user config')
        if 'password' not in config['user']:
            raise ValueError('No password found in user config')
        if 'access_token' not in config['user']:
            raise ValueError('No access_token found in user config')
        self.username = config['user']['username']
        self.password = config['user']['password']
        self.access_token = config['user']['access_token']

    def test_login_url(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect)
        given_login_url = client.login_url
        query_string = urlencode({'client_id':self.client_id, 'redirect':redirect})
        expected_login_url = '{0}oauth2/authenticate?{1}'.format(BASEURL, query_string)

    def t_est_authentication(self):
        #Requests makes this difficult to test correctly, so just drop it for now.
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect)
        response = requests.get(client.login_url)
        self.assertEqual(response.status_code, 200)
        pattern = re.compile(r'<input type="hidden" name="csrf_token" value="(.+?)"/>')
        matches = pattern.findall(response.content)
        self.assertEqual(len(matches), 1)
        csrf_token = matches[0]
        params = {
                'user': self.username,
                'password': self.password,
                'redirect': redirect,
                'csrf_token': csrf_token
            }
        response = requests.post(client.login_url, params=params)#, allow_redirects=False)
        self.assertEqual(response.status_code, 200)
        parsed_url = urlparse.urlparse(response.url)
        parsed_qs  = urlparse.parse_qs(parsed_url.query)
        self.assertIn('authorization_code', parsed_qs)
        code = parsed_qs['authorization_code']
        client.authenticate(code)

    def test_create_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')

    def test_get_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        unittest_folder_again = client.get_folder(unittest_folder.path, unittest_folder.name)

    def test_delete_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)

    def test_copy_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        sub_folder = client.create_folder(unittest_folder.path, 'sub_folder')
        copy_folder = client.copy_folder(sub_folder.path, unittest_folder.path, 'sub_folder_copy')
        self.assertIn(unittest_folder.path, copy_folder.path)

    def test_rename_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        sub_folder = client.create_folder(unittest_folder.path, 'sub_folder')
        renamed_folder = client.rename_folder(sub_folder.path, 'renamed_sub_folder', 'overwrite')
        self.assertEqual(renamed_folder.name, 'renamed_sub_folder')
        self.assertEqual(sub_folder.path, renamed_folder.path)

    def test_rename_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        f = StringIO('this is a test')
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        new_result = client.rename_file(result.path, 'renamed_file', 'overwrite')
        self.assertEqual(new_result.name, 'renamed_file')
        self.assertEqual(result.path, new_result.path)

    def test_copy_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        f = StringIO('this is a test')
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        copied_result = client.copy_file(result.path, unittest_folder.path, 'test_file_copy.txt', 'overwrite')
        result_iter = result.read()
        contents = ''
        copied_contents = ''
        for chunk in result_iter:
            contents += chunk
        copied_iter = copied_result.read()
        for chunk in copied_iter:
            copied_contents += chunk
        self.assertEqual(contents, copied_contents)

    def test_move_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        f = StringIO('this is a test')
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        moved_result = client.move_file(result.path, unittest_folder.path, 'test_file_copy.txt', 'overwrite')
        result_iter = result.read()
        contents = ''
        moved_contents = ''
        for chunk in result_iter:
            contents += chunk
        moved_iter = moved_result.read()
        for chunk in moved_iter:
            moved_contents += chunk
        self.assertEqual(contents, moved_contents)

    def test_move_folder(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        sub_folder = client.create_folder(unittest_folder.path, 'sub_folder')
        unittest_folder_two = client.create_folder('/', 'unittest_two')
        moved_folder = client.move_folder(unittest_folder_two.path, sub_folder.path, 'moved_sub_folder', 'rename')
        paths = [i.path for i in sub_folder.items]
        self.assertIn(moved_folder.path, paths)

    def test_add_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        f = StringIO('this is a test')
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        self.assertIn(unittest_folder.path, result.path)
        self.assertEqual(result.name, filename)

    def test_read_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        original_contents = 'this is a test'
        f = StringIO(original_contents)
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        self.assertIn(unittest_folder.path, result.path)
        self.assertEqual(result.name, filename)
        returned_contents = ''
        for chunk in client.get_file_contents('test_download.txt', result.path):
            returned_contents += chunk
        self.assertEqual(original_contents, returned_contents)

    def test_delete_file(self):
        redirect = 'http://example.com'
        client = BitcasaClient(self.client_id, self.secret, redirect, self.access_token)
        unittest_folder = client.create_folder('/', 'unittest')
        client.delete_folder(unittest_folder.path)
        unittest_folder = client.create_folder('/', 'unittest')
        original_contents = 'this is a test'
        f = StringIO(original_contents)
        filename = 'test_file.txt'
        result = client.upload_file(f, filename, unittest_folder.path, 'overwrite')
        client.delete_file(result.path)


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Xunit;

namespace System.ComponentModel.Design.Tests
{
    public class DesignerOptionServiceTests : RemoteExecutorTestBase
    {
        [Fact]
        public void CreateOptionCollection_CreateMultipleTimes_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();

            DesignerOptionService.DesignerOptionCollection options1 = service.DoCreateOptionCollection(service.Options, "name", "value");
            Assert.Equal(0, options1.Count);
            Assert.NotEmpty(options1.Properties);
            Assert.Same(options1.Properties, options1.Properties);
            Assert.Same(service.Options, options1.Parent);

            DesignerOptionService.DesignerOptionCollection options2 = service.DoCreateOptionCollection(service.Options, "name", "value");
            Assert.Equal(2, service.Options.Count);
            Assert.Equal(0, options2.Count);
            Assert.NotEmpty(options2.Properties);
            Assert.Same(options2.Properties, options2.Properties);
            Assert.Same(service.Options, options2.Parent);

            Assert.Equal(new DesignerOptionService.DesignerOptionCollection[] { options1, options2 }, service.Options.Cast<object>());
        }

        [Fact]
        public void CreateOptionCollection_NullParent_ThrowsArgumentNullException()
        {
            var service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("parent", () => service.DoCreateOptionCollection(null, "name", "value"));
        }

        [Fact]
        public void CreateOptionCollection_NullName_ThrowsArgumentNullException()
        {
            var service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("name", () => service.DoCreateOptionCollection(service.Options, null, "value"));
        }

        [Fact]
        public void CreateOptionCollection_EmptyName_ThrowsArgumentException()
        {
            var service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentException>("name.Length", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value"));
        }

        [Fact]
        public void Options_Get_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.Options;
            Assert.Same(options, service.Options);

            Assert.Equal(0, options.Count);
            Assert.Empty(options.Properties);
            Assert.Same(options.Properties, options.Properties);
            Assert.Null(options.Parent);
        }

        [Fact]
        public void Options_IListProperties_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();
            IList options = service.Options;
            Assert.Same(options, service.Options);

            Assert.Equal(0, options.Count);
            Assert.True(options.IsFixedSize);
            Assert.True(options.IsReadOnly);
            Assert.False(options.IsSynchronized);
            Assert.Same(options, options.SyncRoot);
        }

        [Fact]
        public void IList_Modification_ThrowsNotSupportedException()
        {
            var service = new TestDesignerOptionService();
            IList options = service.Options;

            Assert.Throws<NotSupportedException>(() => options[0] = null);
            Assert.Throws<NotSupportedException>(() => options.Add(null));
            Assert.Throws<NotSupportedException>(() => options.Insert(0, null));
            Assert.Throws<NotSupportedException>(() => options.Remove(null));
            Assert.Throws<NotSupportedException>(() => options.RemoveAt(0));
            Assert.Throws<NotSupportedException>(() => options.Clear());
        }

        [Fact]
        public void IndexOf_ValueExists_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Equal(0, service.Options.IndexOf(options));
            Assert.Equal(0, ((IList)service.Options).IndexOf(options));
        }

        [Fact]
        public void IndexOf_NoSuchOptions_ReturnsNegativeOne()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Equal(-1, service.Options.IndexOf(service.Options));
            Assert.Equal(-1, service.Options.IndexOf(null));
            Assert.Equal(-1, ((IList)service.Options).IndexOf(service.Options));
        }

        [Fact]
        public void Contains_ValueExists_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Equal(0, service.Options.IndexOf(options));
            Assert.Equal(0, ((IList)service.Options).IndexOf(options));
        }

        [Fact]
        public void Contains_NoSuchOptions_ReturnsFalse()
        {
            var service = new TestDesignerOptionService();
            IList options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.False(options.Contains(service.Options));
            Assert.False(options.Contains(null));
        }

        [Theory]
        [InlineData("Name")]
        [InlineData("name")]
        public void Indexer_ValidName_ReturnsExpected(string name)
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Same(options, service.Options[name]);
        }

        [Theory]
        [InlineData(null)]
        [InlineData("NoSuchName")]
        public void Indexer_InvalidName_ReturnsNull(string name)
        {
            var service = new TestDesignerOptionService();
            service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Null(service.Options[name]);
        }

        [Fact]
        public void Indexer_ValidIndex_ReturnsExpected()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Same(options, service.Options[0]);
            Assert.Same(options, ((IList)service.Options)[0]);
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(1)]
        public void Indexer_InvalidIndex_ThrowsIndexOutOfRangeException(int index)
        {
            var service = new TestDesignerOptionService();
            service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.Throws<IndexOutOfRangeException>(() => service.Options[index]);
            Assert.Throws<IndexOutOfRangeException>(() => ((IList)service.Options)[index]);
        }

        [Fact]
        [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
        public void Properties_GetBeforeAddingChild_ReturnsNonEmpty()
        {
            var service = new TestDesignerOptionService();
            Assert.Empty(service.Options.Properties);

            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "name", "value");
            Assert.NotEmpty(service.Options.Properties);
        }

        [Fact]
        public void Properties_GetAfterAddingChild_ReturnsNonEmpty()
        {
            var service = new TestDesignerOptionService();

            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "name", "value");
            Assert.NotEmpty(service.Options.Properties);
        }

        [Fact]
        public void Properties_PropertyDescriptorAttributes_Success()
        {
            var value = new TestClass { Value = "Value" };

            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", value);
            PropertyDescriptor propertyDescriptor = Assert.IsAssignableFrom<PropertyDescriptor>(Assert.Single(options.Properties));
            PropertyDescriptor actualProperty = Assert.IsAssignableFrom<PropertyDescriptor>(Assert.Single(TypeDescriptor.GetProperties(value)));

            Assert.Equal(actualProperty.Attributes, propertyDescriptor.Attributes);
            Assert.Equal(actualProperty.ComponentType, propertyDescriptor.ComponentType);
            Assert.Equal(actualProperty.IsReadOnly, propertyDescriptor.IsReadOnly);
            Assert.Equal(actualProperty.PropertyType, propertyDescriptor.PropertyType);
            Assert.Equal(actualProperty.CanResetValue(value), propertyDescriptor.CanResetValue("InvalidComponent"));
            Assert.Equal(actualProperty.ShouldSerializeValue(value), propertyDescriptor.ShouldSerializeValue("InvalidComponent"));

            propertyDescriptor.ResetValue(null);
            Assert.Equal("Value", value.Value);
        }

        [Fact]
        public void DesignerOptionConverterGetPropertiesSupported_Invoke_ReturnsTrue()
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
            Assert.True(converter.GetPropertiesSupported());
        }

        [Fact]
        public void DesignerOptionConverterGetProperties_ValidValue_ReturnsExpected()
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", new TestClass());
            service.DoCreateOptionCollection(options, "Name", null);

            PropertyDescriptorCollection properties = converter.GetProperties(options);
            Assert.Equal(2, properties.Count);

            PropertyDescriptor optionsDescriptor = properties[0];
            Assert.Equal(typeof(DesignerOptionService.DesignerOptionCollection), optionsDescriptor.ComponentType);
            Assert.Equal(typeof(DesignerOptionService.DesignerOptionCollection), optionsDescriptor.PropertyType);
            Assert.Same(options[0], optionsDescriptor.GetValue(null));

            Assert.True(optionsDescriptor.IsReadOnly);
            Assert.False(optionsDescriptor.CanResetValue(null));
            Assert.False(optionsDescriptor.ShouldSerializeValue(null));

            optionsDescriptor.ResetValue(null);
            optionsDescriptor.SetValue(null, null);

            PropertyDescriptor propertyDescriptor = properties[1];
            Assert.Same(options.Properties[0], propertyDescriptor);
        }

        [Theory]
        [InlineData("Value")]
        [InlineData(null)]
        public void DesignerOptionConverterGetProperties_InvalidValue_ReturnsEmpty(object value)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
            Assert.Empty(converter.GetProperties(value));
        }

        [Fact]
        public void DesignerOptionConverter_ConvertToString_ReturnsExpected()
        {
            RemoteInvoke(() =>
            {
                CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;

                TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
                Assert.Equal("(Collection)", converter.ConvertToString(null));
            }).Dispose();
        }

        [Fact]
        public void DesignerOptionConverter_ConvertToNonString_ThrowsNotSupportedException()
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
            Assert.Throws<NotSupportedException>(() => converter.ConvertTo(null, typeof(object)));
        }

        [Fact]
        public void CopyTo_ValidRange_Success()
        {
            var service = new TestDesignerOptionService();

            DesignerOptionService.DesignerOptionCollection options1 = service.DoCreateOptionCollection(service.Options, "name", "value");
            DesignerOptionService.DesignerOptionCollection options2 = service.DoCreateOptionCollection(service.Options, "name", "value");

            var destination = new object[3];
            service.Options.CopyTo(destination, 1);

            Assert.Equal(new object[] { null, options1, options2 }, destination);
        }

        [Fact]
        public void Properties_GetWhenPopulateOptionCollectionOverriden_ReturnsExpected()
        {
            var service = new PopulatingDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.Options;
            Assert.Single(options);
            Assert.Equal("Name", options[0].Name);
        }

        private class PopulatingDesignerOptionService : DesignerOptionService
        {
            protected override void PopulateOptionCollection(DesignerOptionCollection options)
            {
                CreateOptionCollection(options, "Name", "Value");
            }
        }

        [Fact]
        public void ShowDialog_Invoke_ReturnsFalseByDefault()
        {
            var service = new TestDesignerOptionService();
            Assert.False(service.DoShowDialog(null, null));
        }

        [Fact]
        public void GetOptionValue_NotNested_ReturnsExpected()
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            service.DoCreateOptionCollection(service.Options, "Name", value);

            Assert.Equal("StringValue", iService.GetOptionValue("Name", "Value"));
        }

        [Fact]
        public void GetOptionValue_Nested_ReturnsExpected()
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "SubName", value);

            Assert.Equal("StringValue", iService.GetOptionValue("Name\\SubName", "Value"));
        }

        [Theory]
        [InlineData("NoSuchParentName\\SubName", "Value")]
        [InlineData("Name\\NoSuchSubName", "Value")]
        [InlineData("Name\\SubName", "NoSuchValue")]
        public void GetOptionValue_NoSuchValue_ReturnsNull(string pageName, string valueName)
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "SubName", value);

            Assert.Null(iService.GetOptionValue(pageName, valueName));
        }

        [Fact]
        public void GetOptionValue_NullPageName_ThrowsArgumentNullException()
        {
            IDesignerOptionService service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("pageName", () => service.GetOptionValue(null, "ValueName"));
        }

        [Fact]
        public void GetOptionValue_NullValueName_ThrowsArgumentNullException()
        {
            IDesignerOptionService service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("valueName", () => service.GetOptionValue("PageName", null));
        }

        [Fact]
        public void SetOptionValue_NotNested_ReturnsExpected()
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            service.DoCreateOptionCollection(service.Options, "Name", value);

            iService.SetOptionValue("Name", "Value", "abc");
            Assert.Equal("abc", value.Value);
        }

        [Fact]
        public void SetOptionValue_Nested_ReturnsExpected()
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "SubName", value);

            iService.SetOptionValue("Name\\SubName", "Value", "abc");
            Assert.Equal("abc", value.Value);
        }

        [Theory]
        [InlineData("NoSuchParentName\\SubName", "Value")]
        [InlineData("Name\\NoSuchSubName", "Value")]
        [InlineData("Name\\SubName", "NoSuchValue")]
        public void SetOptionValue_NoSuchValue_Nop(string pageName, string valueName)
        {
            var value = new TestClass { Value = "StringValue" };

            var service = new TestDesignerOptionService();
            IDesignerOptionService iService = service;
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "SubName", value);

            iService.SetOptionValue(pageName, valueName, "value");
        }

        [Fact]
        public void SetOptionValue_NullPageName_ThrowsArgumentNullException()
        {
            IDesignerOptionService service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("pageName", () => service.SetOptionValue(null, "ValueName", "value"));
        }

        [Fact]
        public void SetOptionValue_NullValueName_ThrowsArgumentNullException()
        {
            IDesignerOptionService service = new TestDesignerOptionService();
            AssertExtensions.Throws<ArgumentNullException>("valueName", () => service.SetOptionValue("PageName", null, "value"));
        }

        [Fact]
        public void ShowDialog_NonNestedValue_Success()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", "Value");

            Assert.True(options.ShowDialog());
            Assert.Equal("Value", service.ShowDialogValue);
        }

        [Fact]
        public void ShowDialog_NestedValue_Success()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "Name", "Value");

            Assert.True(options.ShowDialog());
            Assert.Equal("Value", service.ShowDialogValue);
        }

        [Fact]
        public void ShowDialog_NullValue_Success()
        {
            var service = new TestDesignerOptionService();
            DesignerOptionService.DesignerOptionCollection options = service.DoCreateOptionCollection(service.Options, "Name", null);
            service.DoCreateOptionCollection(options, "Name", null);

            Assert.False(options.ShowDialog());
            Assert.Equal("Default", service.ShowDialogValue);
        }

        private class TestDesignerOptionService : DesignerOptionService
        {
            public object ShowDialogValue { get; set; } = "Default";

            public DesignerOptionCollection DoCreateOptionCollection(DesignerOptionCollection parent, string name, object value)
            {
                return CreateOptionCollection(parent, name, value);
            }

            protected override bool ShowDialog(DesignerOptionCollection options, object optionObject)
            {
                ShowDialogValue = optionObject;
                return true;
            }

            public bool DoShowDialog(DesignerOptionCollection options, object optionObject)
            {
                return base.ShowDialog(options, optionObject);
            }
        }

        private class TestClass
        {
            public string Value { get; set; }
        }
    }
}


text:
package org.nd4j.autodiff.functions.impl.unary.transform.shape;

import org.nd4j.autodiff.ArrayField;
import org.nd4j.autodiff.functions.AbstractUnaryFunction;
import org.nd4j.autodiff.functions.DifferentialFunction;
import org.nd4j.autodiff.opstate.OpState;
import org.nd4j.autodiff.samediff.SameDiff;

public class Broadcast extends AbstractUnaryFunction<ArrayField> {

    public Broadcast(SameDiff sameDiff, DifferentialFunction<ArrayField> i_v, int[] shape) {
        super(sameDiff, i_v, shape,OpState.OpType.SHAPE,new Object[]{shape});
        this.shape = shape;
    }

    @Override
    public ArrayField doGetValue() {
        return sameDiff.getArrayFactory().broadcast(arg().getValue(true),shape);
    }

    @Override
    public double getReal() {
        return Math.floor(arg().getReal());
    }

    @Override
    public DifferentialFunction<ArrayField> diff(DifferentialFunction<ArrayField> i_v) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String functionName() {
        return "broadcast";
    }

}


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

import java.util.Set;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.hateoas.Resources;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import eu.bcvsolutions.idm.core.api.config.swagger.SwaggerConfig;
import eu.bcvsolutions.idm.core.api.dto.IdmRoleFormAttributeDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmRoleFormAttributeFilter;
import eu.bcvsolutions.idm.core.api.rest.BaseController;
import eu.bcvsolutions.idm.core.api.rest.BaseDtoController;
import eu.bcvsolutions.idm.core.api.service.IdmRoleFormAttributeService;
import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission;
import eu.bcvsolutions.idm.core.rest.AbstractRequestDtoController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import io.swagger.annotations.AuthorizationScope;

/**
 * Request controller for relation between role and definition of form-attribution. Is elementary part
 * of role form "sub-definition".
 *
 * @author Vít Švanda
 *
 */
@RestController
@RequestMapping(value = BaseDtoController.BASE_PATH + "/requests")
@Api(
		value = IdmRoleFormAttributeController.TAG,
		description = "Operations with role form attributes",
		tags = { IdmRoleFormAttributeController.TAG },
		produces = BaseController.APPLICATION_HAL_JSON_VALUE,
		consumes = MediaType.APPLICATION_JSON_VALUE)
public class IdmRequestRoleFormAttributeController extends AbstractRequestDtoController<IdmRoleFormAttributeDto, IdmRoleFormAttributeFilter> {

	protected static final String TAG = "Role attributes";
	protected static final String REQUEST_SUB_PATH = "/role-form-attributes";

	@Autowired
	public IdmRequestRoleFormAttributeController(IdmRoleFormAttributeService service) {
		super(service);
	}

	@Override
	public String getRequestSubPath(){
		return REQUEST_SUB_PATH;
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/{requestId}"+ REQUEST_SUB_PATH , method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_READ + "')")
	@ApiOperation(
			value = "Search role attributes (/search/quick alias)",
			nickname = "searchRoleFormAttributes",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") })
				})
	public Resources<?> find(
			@PathVariable @NotNull String requestId,
			@RequestParam(required = false) MultiValueMap<String, Object> parameters,
			@PageableDefault Pageable pageable) {
		return super.find(requestId, parameters, pageable);
	}

	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/search/quick", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_READ + "')")
	@ApiOperation(
			value = "Search role attributes",
			nickname = "searchQuickRoleFormAttributes",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") })
				})
	public Resources<?> findQuick(
			@PathVariable @NotNull String requestId,
			@RequestParam(required = false) MultiValueMap<String, Object> parameters,
			@PageableDefault Pageable pageable) {
		return super.find(requestId, parameters, pageable);
	}

	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/search/autocomplete", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_AUTOCOMPLETE + "')")
	@ApiOperation(
			value = "Autocomplete role attributes (selectbox usage)",
			nickname = "autocompleteRoleFormAttributes",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_AUTOCOMPLETE, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_AUTOCOMPLETE, description = "") })
				})
	public Resources<?> autocomplete(
			@PathVariable @NotNull String requestId,
			@RequestParam(required = false) MultiValueMap<String, Object> parameters,
			@PageableDefault Pageable pageable) {
		return super.autocomplete(requestId, parameters, pageable);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/search/count", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_COUNT + "')")
	@ApiOperation(
			value = "The number of entities that match the filter",
			nickname = "countRoleFormAttributes",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_COUNT, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_COUNT, description = "") })
				})
	public long count(@PathVariable @NotNull String requestId, @RequestParam(required = false) MultiValueMap<String, Object> parameters) {
		return super.count(requestId, parameters);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/{backendId}", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_READ + "')")
	@ApiOperation(
			value = "Role attribute detail",
			nickname = "getRoleFormAttribute",
			response = IdmRoleFormAttributeDto.class,
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") })
				})
	public ResponseEntity<?> get(
			@PathVariable @NotNull String requestId,
			@ApiParam(value = "Role attribute's uuid identifier.", required = true)
			@PathVariable @NotNull String backendId) {
		return super.get(requestId, backendId);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH, method = RequestMethod.POST)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_CREATE + "')"
			+ " or hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE + "')")
	@ApiOperation(
			value = "Create / update role attribute",
			nickname = "postRoleFormAttribute",
			response = IdmRoleFormAttributeDto.class,
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_CREATE, description = ""),
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE, description = "")}),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_CREATE, description = ""),
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE, description = "")})
				})
	public ResponseEntity<?> post(@PathVariable @NotNull String requestId, @Valid @RequestBody IdmRoleFormAttributeDto dto) {
		return super.post(requestId, dto);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/{backendId}", method = RequestMethod.PUT)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE + "')")
	@ApiOperation(
			value = "Update role attribute",
			nickname = "putRoleFormAttribute",
			response = IdmRoleFormAttributeDto.class,
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_UPDATE, description = "") })
				})
	public ResponseEntity<?> put(
			@PathVariable @NotNull String requestId,
			@ApiParam(value = "Role attribute's uuid identifier.", required = true)
			@PathVariable @NotNull String backendId,
			@Valid @RequestBody IdmRoleFormAttributeDto dto) {
		return super.put(requestId, backendId, dto);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/{backendId}", method = RequestMethod.DELETE)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_DELETE + "')")
	@ApiOperation(
			value = "Delete role attribute",
			nickname = "deleteRoleFormAttribute",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_DELETE, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_DELETE, description = "") })
				})
	public ResponseEntity<?> delete(
			@PathVariable @NotNull String requestId,
			@ApiParam(value = "Role attribute's uuid identifier.", required = true)
			@PathVariable @NotNull String backendId) {
		return super.delete(requestId, backendId);
	}

	@Override
	@ResponseBody
	@RequestMapping(value = "/{requestId}"+ REQUEST_SUB_PATH +   "/{backendId}/permissions", method = RequestMethod.GET)
	@PreAuthorize("hasAuthority('" + CoreGroupPermission.ROLEFORMATTRIBUTE_READ + "')")
	@ApiOperation(
			value = "What logged identity can do with given record",
			nickname = "getPermissionsOnRoleFormAttribute",
			tags = { IdmRoleFormAttributeController.TAG },
			authorizations = {
				@Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") }),
				@Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = {
						@AuthorizationScope(scope = CoreGroupPermission.ROLEFORMATTRIBUTE_READ, description = "") })
				})
	public Set<String> getPermissions(
			@PathVariable @NotNull String requestId,
			@ApiParam(value = "Role attribute's uuid identifier.", required = true)
			@PathVariable @NotNull String backendId) {
		return super.getPermissions(requestId, backendId);
	}
}