text:
require 'open-uri'
require 'nokogiri'
require 'yaml'
require 'uri'

class Import
  def self.username(username)
    data = {}
    begin
      xml = Nokogiri::XML(open("http://#{username}.tumblr.com/api/read"))
    rescue OpenURI::HTTPError
      raise "Username not found"
    end

    data['Title'] = xml.search('tumblelog')[0]['title']
    data['Description'] = xml.search('tumblelog')[0].content

    data['Posts'] = []
    xml.search('posts post').each do |xpost|
      post = {
        'PostId' => xpost['id'].to_i,
        'Permalink' => xpost['url'],
        'Type' => xpost['type'].capitalize,
        'Timestamp' => xpost['unix-timestamp'].to_i,
        'Tags' => xpost.search('tag').collect{ |tag| tag.content }
      }

      post['Type'] = "Text" if post['Type'] == "Regular"
      post['Type'] = "Chat" if post['Type'] == "Conversation"

      post.store('Title', xpost.search("#{xpost['type']}-title")[0].content) rescue nil

      post.store('Caption',xpost.search("#{xpost['type']}-caption")[0].content) rescue nil

      post.store('LinkURL',xpost.search("#{xpost['type']}-link-url")[0].content) rescue nil

      post.store('Source',xpost.search("#{xpost['type']}-source")[0].content) rescue nil

      case post['Type']
      when "Photo"
        xpost.search('photo-url').each do |photo|
          post["PhotoURL-#{photo['max-width']}"] = photo.content
        end
      when "Link"
        begin
          post['Name'] = xpost.search("link-text")[0].content
        rescue
        end
      when "Video"
        post['Player'] = xpost.search("video-player")[0].content
      when "Text"
        post['Body'] = xpost.search("regular-body")[0].content
      end

      data['Posts'].push post
    end

    # Pages
    begin
      xml = Nokogiri::XML(open("http://#{username}.tumblr.com/api/pages"))
      data['Pages'] = []

      xml.search('pages').children.each do |re|
        case re.name
        when "redirect"
          data['Pages'].push({
            "Label" => re['link-title'],
            "URL"   => re['redirect-to']
          })
        when "page"
          data['Pages'].push({
            "Label"   => re['link-title'],
            "URL"     => URI.split(re['url'])[5],
            "Title"   => re['title'],
            "InTheme" => (re['render-in-theme'] == "true"),
            "Body"    => re.content
          })
        end
      end
      # Do pages
    rescue OpenURI::HTTPError
      # No pages
    end

    YAML::dump(data)
  end
end


text:
using Konves.ChordPro.DirectiveHandlers;
using Konves.ChordPro.Directives;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Konves.ChordPro.UnitTests.DirectiveHandlers
{
	[TestClass]
	public class ColumnsHandlerTestFixture
	{
		[TestMethod]
		[TestCategory("DirectiveHandler")]
		public void TryParseTest_LongForm()
		{
			// Arrange
			int number = 3;
			string input = $"{{columns: {number}}}";
			DirectiveComponents components = DirectiveComponents.Parse(input);
			DirectiveHandler sut = ColumnsHandler.Instance;
			Directive directive;

			// Act
			bool result = sut.TryParse(components, out directive);

			// Assert
			Assert.IsTrue(result);
			Assert.IsInstanceOfType(directive, typeof(ColumnsDirective));
			Assert.AreEqual(number, (directive as ColumnsDirective).Number);
		}

		[TestMethod]
		[TestCategory("DirectiveHandler")]
		public void TryParseTest_ShortForm()
		{
			// Arrange
			int number = 3;
			string input = $"{{col: {number}}}";
			DirectiveComponents components = DirectiveComponents.Parse(input);
			DirectiveHandler sut = ColumnsHandler.Instance;
			Directive directive;

			// Act
			bool result = sut.TryParse(components, out directive);

			// Assert
			Assert.IsTrue(result);
			Assert.IsInstanceOfType(directive, typeof(ColumnsDirective));
			Assert.AreEqual(number, (directive as ColumnsDirective).Number);
		}

		[TestMethod]
		[TestCategory("DirectiveHandler")]
		public void TryParseTest_NaN()
		{
			// Arrange
			string input = $"{{columns: NaN}}";
			DirectiveComponents components = DirectiveComponents.Parse(input);
			DirectiveHandler sut = ColumnsHandler.Instance;
			Directive directive;

			// Act
			bool result = sut.TryParse(components, out directive);

			// Assert
			Assert.IsFalse(result);
			Assert.IsNull(directive);
		}

		[TestMethod]
		[TestCategory("DirectiveHandler")]
		public void GetStringTest_LongForm()
		{
			// Arrange
			int number = 3;
			Directive directive = new ColumnsDirective(number);
			string expectedText = $"{{columns: {number}}}";
			DirectiveHandler sut = ColumnsHandler.Instance;

			// Act
			string text = sut.GetString(directive, shorten: false);

			// Assert
			Assert.AreEqual(expectedText, text);
		}

		[TestMethod]
		[TestCategory("DirectiveHandler")]
		public void GetStringTest_ShortForm()
		{
			// Arrange
			int number = 3;
			Directive directive = new ColumnsDirective(number);
			string expectedText = $"{{col: {number}}}";
			DirectiveHandler sut = ColumnsHandler.Instance;

			// Act
			string text = sut.GetString(directive, shorten: true);

			// Assert
			Assert.AreEqual(expectedText, text);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
Imports System
Imports System.Net
Imports Independentsoft.Exchange

Namespace Sample
    Class Module1
        Shared Sub Main(ByVal args As String())

            Dim credential As New NetworkCredential("username", "password")
            Dim service As New Service("https://myserver/ews/Exchange.asmx", credential)

            service.RequestServerVersion = RequestServerVersion.Exchange2010SP1

            Try

                Dim timeZone As TimeZoneDefinition = GetTimeZone(service, "Berlin") ''find time zone based on name
                ''Dim timeZone As TimeZoneDefinition = GetTimeZone(service, "UTC-08:00") ''find time zone based on offset

                'Daily recurrence next 10 days
                Dim recurrence As New Recurrence()
                recurrence.Pattern = New DailyRecurrencePattern(1)
                recurrence.Range = New NumberedRecurrenceRange(DateTime.Today, 10)

                Dim appointment As New Appointment()
                appointment.Subject = "Daily recurrence next 10 days"
                appointment.Body = New Body("Body text")
                appointment.StartTime = DateTime.Today.AddHours(15)
                appointment.EndTime = DateTime.Today.AddHours(16)
                appointment.Recurrence = recurrence
                appointment.StartTimeZone = timeZone
                appointment.EndTimeZone = timeZone

                Dim itemId As ItemId = service.CreateItem(appointment)

            Catch ex As ServiceRequestException
                Console.WriteLine("Error: " + ex.Message)
                Console.WriteLine("Error: " + ex.XmlMessage)
                Console.Read()
            Catch ex As WebException
                Console.WriteLine("Error: " + ex.Message)
                Console.Read()
            End Try

        End Sub

        Private Shared Function GetTimeZone(ByVal service As Service, ByVal name As String) As TimeZoneDefinition

            Dim Response As GetServerTimeZonesResponse = service.GetServerTimeZones()

            For Each timeZone As TimeZoneDefinition In Response.TimeZoneDefinitions

                If timeZone.Name.IndexOf(name) > 0 Then
                    Return timeZone
                End If
            Next

            Return Nothing

        End Function
    End Class
End Namespace


text:
package org.apache.wicket.examples;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.response.filter.IResponseFilter;
import org.apache.wicket.util.string.AppendingStringBuffer;
import org.apache.wicket.core.util.string.JavaScriptUtils;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.time.Duration;

/**
 * Displays server host name (combination of name, ipaddress and unique id, which is either based)
 * and time it took to handle the request in the browser's status bar like this:
 * window.defaultStatus = 'Host: myhost/192.168.1.66/someid, handled in: 0.01s'
 *
 * @author eelco hillenius
 */
public class ServerHostNameAndTimeFilter implements IResponseFilter
{
	private String host;

	/**
	 * Construct, trying system property 'examples.hostname' for the server id or else current time
	 * milis.
	 */
	public ServerHostNameAndTimeFilter()
	{
		String hostId = null;
		try
		{
			hostId = System.getProperty("examples.hostname");
		}
		catch (SecurityException ignored)
		{
		}
		if (Strings.isEmpty(hostId))
		{
			hostId = String.valueOf(System.currentTimeMillis());
		}

		setHostName(hostId);
	}

	/**
	 * Construct with an id.
	 *
	 * @param hostId
	 *            a unique id indentifying this server instance
	 */
	public ServerHostNameAndTimeFilter(String hostId)
	{
		if (hostId == null)
		{
			throw new IllegalArgumentException("hostId may not be null");
		}

		setHostName(hostId);
	}

	/**
	 * @see IResponseFilter#filter(AppendingStringBuffer)
	 */
	public AppendingStringBuffer filter(AppendingStringBuffer responseBuffer)
	{
		int index = responseBuffer.indexOf("");
		long timeTaken = System.currentTimeMillis() - RequestCycle.get().getStartTime();

		if (index != -1)
		{
			AppendingStringBuffer script = new AppendingStringBuffer(75);
			script.append("\n");
			script.append(JavaScriptUtils.SCRIPT_OPEN_TAG);
			script.append("\n\twindow.defaultStatus='");
			script.append("Host: ");
			script.append(host);
			script.append(", handled in: ");
			script.append(Duration.milliseconds(timeTaken));
			script.append("';\n");
			script.append(JavaScriptUtils.SCRIPT_CLOSE_TAG);
			script.append("\n");
			responseBuffer.insert(index + 6, script);
		}
		return responseBuffer;
	}

	/**
	 * Fill host name property.
	 *
	 * @param hostId
	 */
	private void setHostName(String hostId)
	{
		try
		{
			InetAddress localMachine = InetAddress.getLocalHost();
			String hostName = localMachine.getHostName();
			String address = localMachine.getHostAddress();
			host = ((!Strings.isEmpty(hostName)) ? hostName + "/" + address : address) + "/" +
				hostId;
		}
		catch (UnknownHostException ignored)
		{
		}

		if (Strings.isEmpty(host))
		{
			host = "<unknown>";
		}
	}
}


text:
<!doctype html>

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

test page


text:
/*jshint strict: false */

////////////////////////////////////////////////////////////////////////////////
/// @brief global configuration
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var actions = require("@arangodb/actions");
var configuration = require("@arangodb/configuration");

// -----------------------------------------------------------------------------
// --SECTION--                                                           actions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief _admin/configuration/versions
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url: "_admin/configuration/notifications/versions",
  prefix: false,

  callback : function (req, res) {
    var json;

    try {
      switch (req.requestType) {
        case actions.GET:
          actions.resultOk(req, res, actions.HTTP_OK, configuration.notifications.versions());
          break;

        case actions.PUT:
          json = actions.getJsonBody(req, res, actions.HTTP_BAD);

          if (json === undefined) {
            return;
          }

          configuration.notifications.setVersions(json);

          actions.resultOk(req, res, actions.HTTP_OK, {});
          break;

        default:
          actions.resultUnsupported(req, res);
      }
    }
    catch (err) {
      actions.resultException(req, res, err, undefined, false);
    }
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\time\TimePicker;

\reinvently\ondemand\core\modules\settings\assets\ExtraFeeAsset::register($this);

/* @var $this yii\web\View */
/* @var $model reinvently\ondemand\core\modules\settings\models\ExtraFee */
/* @var $form yii\widgets\ActiveForm */
/* @var $tariffs reinvently\ondemand\core\modules\settings\models\Tariff[] */

$dayPeriod = new \DatePeriod(
    (new \DateTime())->setDate(null, null, 1),
    new \DateInterval("P1D"),
    (new \DateTime())->setDate(null, null, 31)->modify("+1 days")
);

$weekdayPeriod = new DatePeriod(
    new DateTime("Monday this week"),
    new DateInterval("P1D"),
    new DateTime("Monday next week")
);

$monthPeriod = new DatePeriod(
    new DateTime("Jan this year"),
    new DateInterval("P1M"),
    new DateTime("Dec next year")
);

$yearPeriod = new DatePeriod(
    new DateTime("this year"),
    new DateInterval("P1Y"),
    new DateTime("+15 years")
);

$dayList = [];
foreach($dayPeriod as $d){
    $dayList[(int)$d->format("j")] = $d->format("j");
}

$weekdayList = [];
foreach($weekdayPeriod as $w){
    $weekdayList[(int)$w->format("N")] = $w->format("l");
}

$monthList = [];
foreach($monthPeriod as $m){
    $monthList[$m->format("n")] = $m->format("F");
}

$yearList = [];
foreach($yearPeriod as $y) {
    $yearList[$y->format("Y")] = $y->format("Y");
}

$errors = $model->getErrors();
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'tariffId')->dropDownList($tariffs) ?>

    <?= $form->field($model, 'description')->textarea() ?>

    <div class="form-group<?php if(isset($errors["timeStart"])) {?> has-error <?php } ?>" style="float: left; margin-right:40px">
        Time From (UTC)
        <?= TimePicker::widget([
            'name' => 'ExtraFee[timeStart]',
            'value' => $model->extraFeeTime ? (new DateTime($model->extraFeeTime->timeStart))->format("g:i:s A") : '00:00:00 AM',
            'pluginOptions' => [
                'showSeconds' => true,
                'showMeridian' => true
            ],
            'containerOptions' => [
                "style" => "width: 270px"
            ]
        ])
        ?>

            <div style="margin-top: 10px; margin-left: 10px; color:<?php if(!isset($errors["timeStart"])) { ?>green;<?php } ?> height: 20px">

                    <?php
                    $timeStart = $model->extraFeeTime ? $model->extraFeeTime->timeStart : '00:00:00';
                    echo (new DateTime($timeStart))->setTimezone(new DateTimeZone('America/Chicago'))->format("g:i:s A")
                    ?>

                (Dallas)

        <?php if(isset($errors["timeStart"])) {?>

<?=is_array($errors["timeStart"][0]) ? implode("
", $errors["timeStart"][0]) : $errors["timeStart"][0] ?>

        <?php } ?>

    <div class="form-group<?php if(isset($errors["timeFinish"])) {?> has-error <?php } ?>" style="float: left">
        Time To (UTC)
        <?= TimePicker::widget([
            'name' => 'ExtraFee[timeFinish]',
            'value' => $model->extraFeeTime ? (new DateTime($model->extraFeeTime->timeFinish))->format("g:i:s A") : '11:59:59 PM',
            'pluginOptions' => [
                'showSeconds' => true,
                'showMeridian' => true
            ],

            'containerOptions' => [
                "style" => "width: 270px"
            ]
        ])
        ?>
        <div style="margin-top: 10px; margin-left: 10px; color:<?php if(!isset($errors["timeFinish"])) { ?>green;<?php } ?> height: 20px">

                <?php
                $timeFinish = $model->extraFeeTime ? $model->extraFeeTime->timeFinish : '23:59:59';
                echo (new DateTime($timeFinish))->setTimezone(new DateTimeZone('America/Chicago'))->format("g:i:s A");
                ?>

            (Dallas)

        <?php if(isset($errors["timeFinish"])) {?>

<?=is_array($errors["timeFinish"][0]) ? implode("
", $errors["timeFinish"][0]) : $errors["timeFinish"][0] ?>

        <?php } ?>

        Day

            <?= Html::dropDownList(
                "ExtraFee[days]",
                isset($selectedDays) ? $selectedDays : null,
                $dayList,
                [
                    'multiple' => true,
                    'size' => 10,
                    "style" => "width: 50px",
                    "id" => "extraFeeDays"
                ])
            ?>

        Weekday

            <?= Html::dropDownList(
                "ExtraFee[weekdays]",
                isset($selectedWeekdays) ? $selectedWeekdays : array_keys($weekdayList),
                $weekdayList,
                [
                    'multiple' => true,
                    'size' => count($weekdayList),
                    "style" => "clear: both",
                    "id" => "extraFeeWeekdays",
                    "disabled" => (isset($selectedDays) and !empty($selectedDays)) ? true : false
                ])
            ?>

        Month

            <?= Html::dropDownList(
                "ExtraFee[months]",
                isset($selectedMonths) ? $selectedMonths : array_keys($monthList),
                $monthList,
                [
                    'multiple' => true,
                    'size' => count($monthList),
                ])
            ?>

        Year

            <?= Html::dropDownList(
                "ExtraFee[years]",
                isset($selectedYears) ? $selectedYears : array_slice(array_keys($yearList), 0, 5),
                $yearList,
                [
                    'multiple' => true,
                    'size' => 7,
                ])
            ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
namespace chrono {

/// Abstract interface class for math functions of the type A=f(B)
/// where A and B are vectors of real values (to the limit, also
/// single scalar values).

class ChFx {
  public:
    /// INTERFACE:
    /// Evaluate A=f(B)
    /// Pure virtual member: it _must_ be implemented by inherited classes.
    /// The parameters B and the results A are column-matrices (vectors of scalars).
    virtual void Eval(ChMatrix<>& A,       ///< result output variables here
                      const ChMatrix<>& B  ///< input variables here
                      ) = 0;
};

/// Class for A=f(B) math functions, where the function
/// is defined by wrapping a C function of the 'old' type,
/// i.e. a pointer to simple C call that works over arrays of doubles and return one value:
///   double (*func)(double p[], void* my_data);
/// as often used in C/C++ math libraries.

class ChFxCfunctionS : public ChFx {
  public:
    /// Create the function wrapper.
    ChFxCfunctionS(double (*mfunc)(double p[], void* my_data),  ///< the pointer to the C function
                   int minvars,                                 ///< the number of input vars (the size of double p[])
                   void* mdata = 0  ///< generic user data, if needed as my_data for C function.
                   ) {
        func = mfunc;
        n_invars = minvars;
        user_data = mdata;
        invars = new double[n_invars];
    }
    virtual ~ChFxCfunctionS() { delete[] invars; }

    /// INTERFACE:
    /// Evaluate A=f(B)
    virtual void Eval(ChMatrix<>& A,       ///< result  here
                      const ChMatrix<>& B  ///< input here
                      ) {
        for (int i = 0; i < A.GetRows(); i++)
            invars[i] = B(i, 0);
        double out = this->func(this->invars, this->user_data);
        A(0, 0) = out;
    }

  private:
    void* user_data;
    int n_invars;
    double* invars;
    double (*func)(double p[], void* my_data);
};

/// Class for A=f(B) math functions, where the function
/// is defined by wrapping a C function of the 'old' type,
/// i.e. a pointer to simple C call that works over arrays of values and return array of values:
///   double (*func)(double p[], void* my_data);
/// as often used in C/C++ math libraries.

class ChFxCfunction : public ChFx {
  public:
    /// Create the function wrapper.
    ChFxCfunction(void (*mfunc)(double in[], double ou[], void* my_data),  ///< the pointer to the C function
                  int minvars,     ///< the number of input vars (the size of double in[])
                  int moutvars,    ///< the number of output vars (the size of double ou[])
                  void* mdata = 0  ///< generic user data, if needed as my_data for C function.
                  ) {
        func = mfunc;
        n_invars = minvars;
        n_outvars = moutvars;
        user_data = mdata;
        invars = new double[n_invars];
        outvars = new double[n_outvars];
    }
    virtual ~ChFxCfunction() {
        delete[] invars;
        delete[] outvars;
    }

    /// INTERFACE:
    /// Evaluate A=f(B)
    virtual void Eval(ChMatrix<>& A,       ///< results here
                      const ChMatrix<>& B  ///< input here
                      ) {
        for (int i = 0; i < A.GetRows(); i++)
            invars[i] = B(i, 0);
        this->func(this->invars, this->outvars, this->user_data);
        for (int j = 0; j < B.GetRows(); j++)
            A(j, 0) = outvars[j];
    }

  private:
    void* user_data;
    int n_invars;
    int n_outvars;
    double* invars;
    double* outvars;
    void (*func)(double in[], double out[], void* my_data);
};

}  // END_OF_NAMESPACE____

#endif


text:
package backend

import (
	"log"

	"github.com/DiscoViking/roguemike/api"
	"github.com/DiscoViking/roguemike/events"
)

type GameManager interface {
	Tick()
	Loop()
	GetState() (g *GameState)
	Spawn(e *Entity)
}

type GameState struct {
	Entities []*Entity
	Actors   []*Actor
	Player   *Actor
}

func NewGameManager(broker events.Broker) GameManager {
	mgr := gameManager{}
	mgr.state = &GameState{}
	mgr.state.Player = NewPlayer(broker)
	mgr.state.Entities = []*Entity{&mgr.state.Player.Entity}
	mgr.state.Actors = []*Actor{mgr.state.Player}
	mgr.broker = broker
	return &mgr
}

type gameManager struct {
	state  *GameState
	broker events.Broker
}

// Can't currently spawn actors.  Only entities.  This needs to be fixed,
// probably by making entity an interface.
func (mgr *gameManager) Spawn(e *Entity) {
	mgr.state.Entities = append(mgr.state.Entities, e)
}

func (mgr *gameManager) Tick() {
	for _, actor := range mgr.state.Actors {
		action := actor.ChooseAction(mgr.state)
		action.apply(actor, mgr.state)
	}

	mgr.pushUpdate()
}

func (mgr *gameManager) Loop() {
	for {
		mgr.Tick()
	}
}

func (mgr *gameManager) GetState() (g *GameState) {
	return mgr.state
}

func (mgr *gameManager) pushUpdate() {
	update := api.WorldUpdate{}
	update.Entities = []api.EntityData{}
	for _, entity := range mgr.state.Entities {
		log.Printf("Entity %#v", entity)
		update.Entities = append(update.Entities, *entity.Data())
	}

	mgr.broker.Publish(update)
}

func (state *GameState) IsTraversable(position api.Coords) bool {
	for _, entity := range state.Entities {
		if entity.X == position.X && entity.Y == position.Y {
			return false
		}
	}

	return true
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Clidemia fuertesii Cogn.

### Remarks
null


text:
This is a sample that depicts how to integrate the `msal-node-extensions` library to your [electron](https://www.electronjs.org/) application that has been bundled by [webpack](https://webpack.js.org/).

## Getting started
To get started using this sample, you need to do the following:

**1. Change the MSAL Electron Configuration** \
Navigate to the `main.ts` file in the src folder and replace the `<CLIENT_ID>` with your client ID. Follow this [steps](https://docs.microsoft.com/en-us/graph/toolkit/get-started/build-an-electron-app#add-new-application-registration-in-azure-ad-to-get-a-client-id) to generate the client ID from Azure.

```js
// Initialize the electron authenticator
const config: MsalElectronConfig = {
    clientId: '<CLIENT_ID>', // <<== Replace this placeholder with your client ID
    mainWindow: mainWindow, //BrowserWindow instance that requires auth
    scopes: [
        'user.read',
        'people.read',
        'user.readbasic.all',
        'contacts.read',
        'presence.read.all',
        'presence.read',
        'user.read.all',
        'calendars.read',
        'Sites.Read.All',
        'Sites.ReadWrite.All',
    ],
    cachePlugin: new PersistenceCachePlugin(persistence),
};
```

**2. Run `npm install`** \
Run `npm install` or your preferred alternative to it, to install the dependencies necessary to run the sample.

```bash
npm install
```

**3. Start your application** \
To start your application, run the command below:

```bash
npm run start
```

> NOTE: If you encounter any errors related to having some of the binaries built with a different NODE_VERSION, run `npm run rebuild` to try rebuild the application with the right NODE_VERSION target


text:
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        boolean[] t = new boolean[s.length()+1];
        t[0] = true; //set first to be true, why?
        //Because we need initial state

        for(int i=0; i<s.length(); i++){
            //should continue from match position
            if(!t[i])
                continue;

            for(String a: dict){
                int len = a.length();
                int end = i + len;
                if(end > s.length())
                    continue;

                if(t[end])
		            continue; // not break

                if(s.substring(i, end).equals(a)){
                    t[end] = true;
                }
            }
        }

        return t[s.length()];
    }
}


text:
import string
import random
import time
import logging
import json
import os
import re
import tarfile
import tempfile
import warnings
import yaml
import zipfile
from datetime import datetime
from typing import Mapping, Callable

import kfp
import kfp_server_api

from kfp.compiler import compiler
from kfp.compiler._k8s_helper import sanitize_k8s_name

from kfp._auth import get_auth_token, get_gcp_access_token

def _add_generated_apis(target_struct, api_module, api_client):
  '''Initializes a hierarchical API object based on the generated API module.
  PipelineServiceApi.create_pipeline becomes target_struct.pipelines.create_pipeline
  '''
  Struct = type('Struct', (), {})

  def camel_case_to_snake_case(name):
      import re
      return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name).lower()

  for api_name in dir(api_module):
      if not api_name.endswith('ServiceApi'):
          continue

      short_api_name = camel_case_to_snake_case(api_name[0:-len('ServiceApi')]) + 's'
      api_struct = Struct()
      setattr(target_struct, short_api_name, api_struct)
      service_api = getattr(api_module.api, api_name)
      initialized_service_api = service_api(api_client)
      for member_name in dir(initialized_service_api):
          if member_name.startswith('_') or member_name.endswith('_with_http_info'):
              continue

          bound_member = getattr(initialized_service_api, member_name)
          setattr(api_struct, member_name, bound_member)
  models_struct = Struct()
  for member_name in dir(api_module.models):
      if not member_name[0].islower():
          setattr(models_struct, member_name, getattr(api_module.models, member_name))
  target_struct.api_models = models_struct

KF_PIPELINES_ENDPOINT_ENV = 'KF_PIPELINES_ENDPOINT'
KF_PIPELINES_UI_ENDPOINT_ENV = 'KF_PIPELINES_UI_ENDPOINT'
KF_PIPELINES_DEFAULT_EXPERIMENT_NAME = 'KF_PIPELINES_DEFAULT_EXPERIMENT_NAME'
KF_PIPELINES_OVERRIDE_EXPERIMENT_NAME = 'KF_PIPELINES_OVERRIDE_EXPERIMENT_NAME'

class Client(object):
  """ API Client for KubeFlow Pipeline.
  """

  # in-cluster DNS name of the pipeline service
  IN_CLUSTER_DNS_NAME = 'ml-pipeline.{}.svc.cluster.local:8888'
  KUBE_PROXY_PATH = 'api/v1/namespaces/{}/services/ml-pipeline:http/proxy/'

  LOCAL_KFP_CONTEXT = os.path.expanduser('~/.config/kfp/context.json')

  # TODO: Wrap the configurations for different authentication methods.
  def __init__(self, host=None, client_id=None, namespace='kubeflow', other_client_id=None, other_client_secret=None, existing_token=None):
    """Create a new instance of kfp client.

    Args:
      host: the host name to use to talk to Kubeflow Pipelines. If not set, the in-cluster
          service DNS name will be used, which only works if the current environment is a pod
          in the same cluster (such as a Jupyter instance spawned by Kubeflow's
          JupyterHub). If you have a different connection to cluster, such as a kubectl
          proxy connection, then set it to something like "127.0.0.1:8080/pipeline.
          If you connect to an IAP enabled cluster, set it to
          https://<your-deployment>.endpoints.<your-project>.cloud.goog/pipeline".
      client_id: The client ID used by Identity-Aware Proxy.
      namespace: the namespace where the kubeflow pipeline system is run.
      other_client_id: The client ID used to obtain the auth codes and refresh tokens.
          Reference: https://cloud.google.com/iap/docs/authentication-howto#authenticating_from_a_desktop_app.
      other_client_secret: The client secret used to obtain the auth codes and refresh tokens.
      existing_token: pass in token directly, it's used for cases better get token outside of SDK, e.x. GCP Cloud Functions
          or caller already has a token
    """
    host = host or os.environ.get(KF_PIPELINES_ENDPOINT_ENV)
    self._uihost = os.environ.get(KF_PIPELINES_UI_ENDPOINT_ENV, host)
    config = self._load_config(host, client_id, namespace, other_client_id, other_client_secret, existing_token)
    api_client = kfp_server_api.api_client.ApiClient(config)
    _add_generated_apis(self, kfp_server_api, api_client)
    self._job_api = kfp_server_api.api.job_service_api.JobServiceApi(api_client)
    self._run_api = kfp_server_api.api.run_service_api.RunServiceApi(api_client)
    self._experiment_api = kfp_server_api.api.experiment_service_api.ExperimentServiceApi(api_client)
    self._pipelines_api = kfp_server_api.api.pipeline_service_api.PipelineServiceApi(api_client)
    self._upload_api = kfp_server_api.api.PipelineUploadServiceApi(api_client)
    self._load_context_setting_or_default()

  def _load_config(self, host, client_id, namespace, other_client_id, other_client_secret, existing_token):
    config = kfp_server_api.configuration.Configuration()

    host = host or ''
    # Preprocess the host endpoint to prevent some common user mistakes.
    # This should only be done for non-IAP cases (when client_id is None). IAP requires preserving the protocol.
    if not client_id:
      host = re.sub(r'^(http|https)://', '', host).rstrip('/')

    if host:
      config.host = host

    token = None

    # "existing_token" is designed to accept token generated outside of SDK. Here is an example.
    #
    # https://cloud.google.com/functions/docs/securing/function-identity
    # https://cloud.google.com/endpoints/docs/grpc/service-account-authentication
    #
    # import requests
    # import kfp
    #
    # def get_access_token():
    #     url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token'
    #     r = requests.get(url, headers={'Metadata-Flavor': 'Google'})
    #     r.raise_for_status()
    #     access_token = r.json()['access_token']
    #     return access_token
    #
    # client = kfp.Client(host='<KFPHost>', existing_token=get_access_token())
    #
    if existing_token:
      token = existing_token
    elif client_id:
      token = get_auth_token(client_id, other_client_id, other_client_secret)
    elif self._is_inverse_proxy_host(host):
      token = get_gcp_access_token()

    if token:
      config.api_key['authorization'] = token
      config.api_key_prefix['authorization'] = 'Bearer'
      return config

    if host:
      # if host is explicitly set with auth token, it's probably a port forward address.
      return config

    import kubernetes as k8s
    in_cluster = True
    try:
      k8s.config.load_incluster_config()
    except:
      in_cluster = False
      pass

    if in_cluster:
      config.host = Client.IN_CLUSTER_DNS_NAME.format(namespace)
      return config

    try:
      k8s.config.load_kube_config(client_configuration=config)
    except:
      print('Failed to load kube config.')
      return config

    if config.host:
      config.host = config.host + '/' + Client.KUBE_PROXY_PATH.format(namespace)
    return config

  def _is_inverse_proxy_host(self, host):
    if host:
      return re.match(r'\S+.googleusercontent.com/{0,1}$', host)
    if re.match(r'\w+', host):
      warnings.warn(
          'The received host is %s, please include the full endpoint address '
          '(with ".(pipelines/notebooks).googleusercontent.com")' % host)
    return False

  def _is_ipython(self):
    """Returns whether we are running in notebook."""
    try:
      import IPython
      ipy = IPython.get_ipython()
      if ipy is None:
        return False
    except ImportError:
      return False

    return True

  def _get_url_prefix(self):
    if self._uihost:
      # User's own connection.
      if self._uihost.startswith('http://') or self._uihost.startswith('https://'):
        return self._uihost
      else:
        return 'http://' + self._uihost

    # In-cluster pod. We could use relative URL.
    return '/pipeline'

  def _load_context_setting_or_default(self):
    if os.path.exists(Client.LOCAL_KFP_CONTEXT):
      with open(Client.LOCAL_KFP_CONTEXT, 'r') as f:
        self._context_setting = json.load(f)
    else:
      self._context_setting = {
        'namespace': '',
      }

  def set_user_namespace(self, namespace):
    """Set user namespace into local context setting file.
       This function should only be used when Kubeflow Pipelines is in the multi-user mode.
    Args:
      namespace: kubernetes namespace the user has access to.
    """
    self._context_setting['namespace'] = namespace
    with open(Client.LOCAL_KFP_CONTEXT, 'w') as f:
      json.dump(self._context_setting, f)

  def get_user_namespace(self):
    """Get user namespace in context config.
    Returns:
      namespace: kubernetes namespace from the local context file or empty if it wasn't set.
    """
    return self._context_setting['namespace']

  def create_experiment(self, name, description=None, namespace=None):
    """Create a new experiment.
    Args:
      name: the name of the experiment.
      description: description of the experiment.
      namespace: kubernetes namespace where the experiment should be created.
        For single user deployment, leave it as None;
        For multi user, input a namespace where the user is authorized.
    Returns:
      An Experiment object. Most important field is id.
    """
    namespace = namespace or self.get_user_namespace()
    experiment = None
    try:
      experiment = self.get_experiment(experiment_name=name, namespace=namespace)
    except:
      # Ignore error if the experiment does not exist.
      pass

    if not experiment:
      logging.info('Creating experiment {}.'.format(name))

      resource_references = []
      if namespace:
        key = kfp_server_api.models.ApiResourceKey(id=namespace, type=kfp_server_api.models.ApiResourceType.NAMESPACE)
        reference = kfp_server_api.models.ApiResourceReference(key=key, relationship=kfp_server_api.models.ApiRelationship.OWNER)
        resource_references.append(reference)

      experiment = kfp_server_api.models.ApiExperiment(
        name=name,
        description=description,
        resource_references=resource_references)
      experiment = self._experiment_api.create_experiment(body=experiment)

    if self._is_ipython():
      import IPython
      html = \
          ('Experiment link here'
          % (self._get_url_prefix(), experiment.id))
      IPython.display.display(IPython.display.HTML(html))
    return experiment

  def list_experiments(self, page_token='', page_size=10, sort_by='', namespace=None):
    """List experiments.
    Args:
      page_token: token for starting of the page.
      page_size: size of the page.
      sort_by: can be '[field_name]', '[field_name] des'. For example, 'name des'.
      namespace: kubernetes namespace where the experiment was created.
        For single user deployment, leave it as None;
        For multi user, input a namespace where the user is authorized.
    Returns:
      A response object including a list of experiments and next page token.
    """
    namespace = namespace or self.get_user_namespace()
    response = self._experiment_api.list_experiment(
      page_token=page_token,
      page_size=page_size,
      sort_by=sort_by,
      resource_reference_key_type=kfp_server_api.models.api_resource_type.ApiResourceType.NAMESPACE,
      resource_reference_key_id=namespace)
    return response

  def get_experiment(self, experiment_id=None, experiment_name=None, namespace=None):
    """Get details of an experiment
    Either experiment_id or experiment_name is required
    Args:
      experiment_id: id of the experiment. (Optional)
      experiment_name: name of the experiment. (Optional)
      namespace: kubernetes namespace where the experiment was created.
        For single user deployment, leave it as None;
        For multi user, input the namespace where the user is authorized.
    Returns:
      A response object including details of a experiment.
    Throws:
      Exception if experiment is not found or None of the arguments is provided
    """
    namespace = namespace or self.get_user_namespace()
    if experiment_id is None and experiment_name is None:
      raise ValueError('Either experiment_id or experiment_name is required')
    if experiment_id is not None:
      return self._experiment_api.get_experiment(id=experiment_id)
    next_page_token = ''
    while next_page_token is not None:
      list_experiments_response = self.list_experiments(page_size=100, page_token=next_page_token, namespace=namespace)
      next_page_token = list_experiments_response.next_page_token
      for experiment in list_experiments_response.experiments:
        if experiment.name == experiment_name:
          return self._experiment_api.get_experiment(id=experiment.id)
    raise ValueError('No experiment is found with name {}.'.format(experiment_name))

  def _extract_pipeline_yaml(self, package_file):
    def _choose_pipeline_yaml_file(file_list) -> str:
      yaml_files = [file for file in file_list if file.endswith('.yaml')]
      if len(yaml_files) == 0:
        raise ValueError('Invalid package. Missing pipeline yaml file in the package.')

      if 'pipeline.yaml' in yaml_files:
        return 'pipeline.yaml'
      else:
        if len(yaml_files) == 1:
          return yaml_files[0]
        raise ValueError('Invalid package. There is no pipeline.yaml file and there are multiple yaml files.')

    if package_file.endswith('.tar.gz') or package_file.endswith('.tgz'):
      with tarfile.open(package_file, "r:gz") as tar:
        file_names = [member.name for member in tar if member.isfile()]
        pipeline_yaml_file = _choose_pipeline_yaml_file(file_names)
        with tar.extractfile(tar.getmember(pipeline_yaml_file)) as f:
          return yaml.safe_load(f)
    elif package_file.endswith('.zip'):
      with zipfile.ZipFile(package_file, 'r') as zip:
        pipeline_yaml_file = _choose_pipeline_yaml_file(zip.namelist())
        with zip.open(pipeline_yaml_file) as f:
          return yaml.safe_load(f)
    elif package_file.endswith('.yaml') or package_file.endswith('.yml'):
      with open(package_file, 'r') as f:
        return yaml.safe_load(f)
    else:
      raise ValueError('The package_file '+ package_file + ' should ends with one of the following formats: [.tar.gz, .tgz, .zip, .yaml, .yml]')

  def list_pipelines(self, page_token='', page_size=10, sort_by=''):
    """List pipelines.
    Args:
      page_token: token for starting of the page.
      page_size: size of the page.
      sort_by: one of 'field_name', 'field_name des'. For example, 'name des'.
    Returns:
      A response object including a list of pipelines and next page token.
    """
    return self._pipelines_api.list_pipelines(page_token=page_token, page_size=page_size, sort_by=sort_by)

  # TODO: provide default namespace, similar to kubectl default namespaces.
  def run_pipeline(self, experiment_id, job_name, pipeline_package_path=None, params={}, pipeline_id=None, version_id=None):
    """Run a specified pipeline.

    Args:
      experiment_id: The string id of an experiment.
      job_name: name of the job.
      pipeline_package_path: local path of the pipeline package(the filename should end with one of the following .tar.gz, .tgz, .zip, .yaml, .yml).
      params: a dictionary with key (string) as param name and value (string) as as param value.
      pipeline_id: the string ID of a pipeline.
      version_id: the string ID of a pipeline version.
        If both pipeline_id and version_id are specified, version_id will take precendence.
        If only pipeline_id is specified, the default version of this pipeline is used to create the run.

    Returns:
      A run object. Most important field is id.
    """
    job_config = self._create_job_config(
      experiment_id=experiment_id,
      params=params,
      pipeline_package_path=pipeline_package_path,
      pipeline_id=pipeline_id,
      version_id=version_id)
    run_body = kfp_server_api.models.ApiRun(
        pipeline_spec=job_config.spec, resource_references=job_config.resource_references, name=job_name)

    response = self._run_api.create_run(body=run_body)

    if self._is_ipython():
      import IPython
      html = ('Run link here'
              % (self._get_url_prefix(), response.run.id))
      IPython.display.display(IPython.display.HTML(html))
    return response.run

  def create_recurring_run(self, experiment_id, job_name, description=None, start_time=None, end_time=None, interval_second=None, cron_expression=None, max_concurrency=1, no_catchup=None, params={}, pipeline_package_path=None, pipeline_id=None, version_id=None, enabled=True):
    """Create a recurring run.
    Args:
      experiment_id: The string id of an experiment.
      job_name: name of the job.
      description: An optional job description.
      start_time: The RFC3339 time string of the time when to start the job.
      end_time: The RFC3339 time string of the time when to end the job.
      interval_second: Integer indicating the seconds between two recurring runs in for a periodic schedule.
      cron_expression: A cron expression representing a set of times, using 5 space-separated fields, e.g. "0 0 9 ? * 2-6".
      max_concurrency: Integer indicating how many jobs can be run in parallel.
      no_catchup: Whether the recurring run should catch up if behind schedule.
        For example, if the recurring run is paused for a while and re-enabled
        afterwards. If no_catchup=False, the scheduler will catch up on (backfill) each
        missed interval. Otherwise, it only schedules the latest interval if more than one interval
        is ready to be scheduled.
        Usually, if your pipeline handles backfill internally, you should turn catchup
        off to avoid duplicate backfill. (default: {False})
      pipeline_package_path: Local path of the pipeline package(the filename should end with one of the following .tar.gz, .tgz, .zip, .yaml, .yml).
      params: A dictionary with key (string) as param name and value (string) as param value.
      pipeline_id: The string ID of a pipeline.
      version_id: The string ID of a pipeline version.
        If both pipeline_id and version_id are specified, pipeline_id will take precendence
        This will change in a future version, so it is recommended to use version_id by itself.
      enabled: A bool indicating whether the recurring run is enabled or disabled.
    Returns:
      A Job object. Most important field is id.
    """
    job_config = self._create_job_config(
      experiment_id=experiment_id,
      params=params,
      pipeline_package_path=pipeline_package_path,
      pipeline_id=pipeline_id,
      version_id=version_id)

    if all([interval_second, cron_expression]) or not any([interval_second, cron_expression]):
      raise ValueError('Either interval_second or cron_expression is required')
    if interval_second is not None:
      trigger = kfp_server_api.models.ApiTrigger(
        periodic_schedule=kfp_server_api.models.ApiPeriodicSchedule(
          start_time=start_time, end_time=end_time, interval_second=interval_second)
      )
    if cron_expression is not None:
      trigger = kfp_server_api.models.ApiTrigger(
        cron_schedule=kfp_server_api.models.ApiCronSchedule(
        start_time=start_time, end_time=end_time, cron=cron_expression)
      )

    job_body = kfp_server_api.models.ApiJob(
        enabled=enabled,
        pipeline_spec=job_config.spec,
        resource_references=job_config.resource_references,
        name=job_name,
        description=description,
        no_catchup=no_catchup,
        trigger=trigger,
        max_concurrency=max_concurrency)
    return self._job_api.create_job(body=job_body)

  def _create_job_config(self, experiment_id, params, pipeline_package_path, pipeline_id, version_id):
    """Create a JobConfig with spec and resource_references.
    Args:
      experiment_id: The string id of an experiment.
      pipeline_package_path: Local path of the pipeline package(the filename should end with one of the following .tar.gz, .tgz, .zip, .yaml, .yml).
      params: A dictionary with key (string) as param name and value (string) as param value.
      pipeline_id: The string ID of a pipeline.
      version_id: The string ID of a pipeline version.
        If both pipeline_id and version_id are specified, pipeline_id will take precendence
        This will change in a future version, so it is recommended to use version_id by itself.
    Returns:
      A JobConfig object with attributes spec and resource_reference.
    """

    class JobConfig:
      def __init__(self, spec, resource_references):
        self.spec = spec
        self.resource_references = resource_references

    pipeline_json_string = None
    if pipeline_package_path:
      pipeline_obj = self._extract_pipeline_yaml(pipeline_package_path)
      pipeline_json_string = json.dumps(pipeline_obj)
    api_params = [kfp_server_api.ApiParameter(
        name=sanitize_k8s_name(name=k, allow_capital_underscore=True),
        value=str(v)) for k,v in params.items()]
    resource_references = []
    key = kfp_server_api.models.ApiResourceKey(id=experiment_id,
                                        type=kfp_server_api.models.ApiResourceType.EXPERIMENT)
    reference = kfp_server_api.models.ApiResourceReference(key=key,
                                                           relationship=kfp_server_api.models.ApiRelationship.OWNER)
    resource_references.append(reference)

    if version_id:
      key = kfp_server_api.models.ApiResourceKey(id=version_id,
                                                 type=kfp_server_api.models.ApiResourceType.PIPELINE_VERSION)
      reference = kfp_server_api.models.ApiResourceReference(key=key,
                                                             relationship=kfp_server_api.models.ApiRelationship.CREATOR)
      resource_references.append(reference)

    spec = kfp_server_api.models.ApiPipelineSpec(
        pipeline_id=pipeline_id,
        workflow_manifest=pipeline_json_string,
        parameters=api_params)
    return JobConfig(spec=spec, resource_references=resource_references)

  def create_run_from_pipeline_func(self, pipeline_func: Callable, arguments: Mapping[str, str], run_name=None, experiment_name=None, pipeline_conf: kfp.dsl.PipelineConf = None, namespace=None):
    '''Runs pipeline on KFP-enabled Kubernetes cluster.
    This command compiles the pipeline function, creates or gets an experiment and submits the pipeline for execution.

    Args:
      pipeline_func: A function that describes a pipeline by calling components and composing them into execution graph.
      arguments: Arguments to the pipeline function provided as a dict.
      run_name: Optional. Name of the run to be shown in the UI.
      experiment_name: Optional. Name of the experiment to add the run to.
      namespace: kubernetes namespace where the pipeline runs are created.
        For single user deployment, leave it as None;
        For multi user, input a namespace where the user is authorized
    '''
    #TODO: Check arguments against the pipeline function
    pipeline_name = pipeline_func.__name__
    run_name = run_name or pipeline_name + ' ' + datetime.now().strftime('%Y-%m-%d %H-%M-%S')
    try:
      (_, pipeline_package_path) = tempfile.mkstemp(suffix='.zip')
      compiler.Compiler().compile(pipeline_func, pipeline_package_path, pipeline_conf=pipeline_conf)
      return self.create_run_from_pipeline_package(pipeline_package_path, arguments, run_name, experiment_name, namespace)
    finally:
      os.remove(pipeline_package_path)

  def create_run_from_pipeline_package(self, pipeline_file: str, arguments: Mapping[str, str], run_name=None, experiment_name=None, namespace=None):
    '''Runs pipeline on KFP-enabled Kubernetes cluster.
    This command compiles the pipeline function, creates or gets an experiment and submits the pipeline for execution.

    Args:
      pipeline_file: A compiled pipeline package file.
      arguments: Arguments to the pipeline function provided as a dict.
      run_name: Optional. Name of the run to be shown in the UI.
      experiment_name: Optional. Name of the experiment to add the run to.
      namespace: kubernetes namespace where the pipeline runs are created.
        For single user deployment, leave it as None;
        For multi user, input a namespace where the user is authorized
    '''

    class RunPipelineResult:
      def __init__(self, client, run_info):
        self._client = client
        self.run_info = run_info
        self.run_id = run_info.id

      def wait_for_run_completion(self, timeout=None):
        timeout = timeout or datetime.datetime.max - datetime.datetime.min
        return self._client.wait_for_run_completion(self.run_id, timeout)

      def __repr__(self):
        return 'RunPipelineResult(run_id={})'.format(self.run_id)

    #TODO: Check arguments against the pipeline function
    pipeline_name = os.path.basename(pipeline_file)
    experiment_name = experiment_name or os.environ.get(KF_PIPELINES_DEFAULT_EXPERIMENT_NAME, None)
    overridden_experiment_name = os.environ.get(KF_PIPELINES_OVERRIDE_EXPERIMENT_NAME, experiment_name)
    if overridden_experiment_name != experiment_name:
      import warnings
      warnings.warn('Changing experiment name from "{}" to "{}".'.format(experiment_name, overridden_experiment_name))
    experiment_name = overridden_experiment_name or 'Default'
    run_name = run_name or pipeline_name + ' ' + datetime.now().strftime('%Y-%m-%d %H-%M-%S')
    experiment = self.create_experiment(name=experiment_name, namespace=namespace)
    run_info = self.run_pipeline(experiment.id, run_name, pipeline_file, arguments)
    return RunPipelineResult(self, run_info)

  def list_runs(self, page_token='', page_size=10, sort_by='', experiment_id=None, namespace=None):
    """List runs.
    Args:
      page_token: token for starting of the page.
      page_size: size of the page.
      sort_by: one of 'field_name', 'field_name des'. For example, 'name des'.
      experiment_id: experiment id to filter upon
      namespace: kubernetes namespace to filter upon.
        For single user deployment, leave it as None;
        For multi user, input a namespace where the user is authorized.
    Returns:
      A response object including a list of experiments and next page token.
    """
    namespace = namespace or self.get_user_namespace()
    if experiment_id is not None:
      response = self._run_api.list_runs(page_token=page_token, page_size=page_size, sort_by=sort_by, resource_reference_key_type=kfp_server_api.models.api_resource_type.ApiResourceType.EXPERIMENT, resource_reference_key_id=experiment_id)
    elif namespace:
      response = self._run_api.list_runs(page_token=page_token, page_size=page_size, sort_by=sort_by, resource_reference_key_type=kfp_server_api.models.api_resource_type.ApiResourceType.NAMESPACE, resource_reference_key_id=namespace)
    else:
      response = self._run_api.list_runs(page_token=page_token, page_size=page_size, sort_by=sort_by)
    return response

  def list_recurring_runs(self, page_token='', page_size=10, sort_by='', experiment_id=None):
    """List recurring runs.
    Args:
      page_token: token for starting of the page.
      page_size: size of the page.
      sort_by: one of 'field_name', 'field_name des'. For example, 'name des'.
      experiment_id: experiment id to filter upon
    Returns:
      A response object including a list of recurring_runs and next page token.
    """
    if experiment_id is not None:
      response = self._job_api.list_jobs(page_token=page_token, page_size=page_size, sort_by=sort_by, resource_reference_key_type=kfp_server_api.models.api_resource_type.ApiResourceType.EXPERIMENT, resource_reference_key_id=experiment_id)
    else:
      response = self._job_api.list_jobs(page_token=page_token, page_size=page_size, sort_by=sort_by)
    return response

  def get_recurring_run(self, job_id):
    """Get recurring_run details.
    Args:
      id of the recurring_run.
    Returns:
      A response object including details of a recurring_run.
    Throws:
      Exception if recurring_run is not found.
    """
    return self._job_api.get_job(id=job_id)

  def get_run(self, run_id):
    """Get run details.
    Args:
      id of the run.
    Returns:
      A response object including details of a run.
    Throws:
      Exception if run is not found.
    """
    return self._run_api.get_run(run_id=run_id)

  def wait_for_run_completion(self, run_id, timeout):
    """Wait for a run to complete.
    Args:
      run_id: run id, returned from run_pipeline.
      timeout: timeout in seconds.
    Returns:
      A run detail object: Most important fields are run and pipeline_runtime
    """
    status = 'Running:'
    start_time = datetime.now()
    while status is None or status.lower() not in ['succeeded', 'failed', 'skipped', 'error']:
      get_run_response = self._run_api.get_run(run_id=run_id)
      status = get_run_response.run.status
      elapsed_time = (datetime.now() - start_time).seconds
      logging.info('Waiting for the job to complete...')
      if elapsed_time > timeout:
        raise TimeoutError('Run timeout')
      time.sleep(5)
    return get_run_response

  def _get_workflow_json(self, run_id):
    """Get the workflow json.
    Args:
      run_id: run id, returned from run_pipeline.
    Returns:
      workflow: json workflow
    """
    get_run_response = self._run_api.get_run(run_id=run_id)
    workflow = get_run_response.pipeline_runtime.workflow_manifest
    workflow_json = json.loads(workflow)
    return workflow_json

  def upload_pipeline(self, pipeline_package_path, pipeline_name=None):
    """Uploads the pipeline to the Kubeflow Pipelines cluster.
    Args:
      pipeline_package_path: Local path to the pipeline package.
      pipeline_name: Optional. Name of the pipeline to be shown in the UI.
    Returns:
      Server response object containing pipleine id and other information.
    """

    response = self._upload_api.upload_pipeline(pipeline_package_path, name=pipeline_name)
    if self._is_ipython():
      import IPython
      html = 'Pipeline link here' % (self._get_url_prefix(), response.id)
      IPython.display.display(IPython.display.HTML(html))
    return response

  def get_pipeline(self, pipeline_id):
    """Get pipeline details.
    Args:
      id of the pipeline.
    Returns:
      A response object including details of a pipeline.
    Throws:
      Exception if pipeline is not found.
    """
    return self._pipelines_api.get_pipeline(id=pipeline_id)

  def delete_pipeline(self, pipeline_id):
    """Delete pipeline.
    Args:
      id of the pipeline.
    Returns:
      Object. If the method is called asynchronously,
      returns the request thread.
    Throws:
      Exception if pipeline is not found.
    """
    return self._pipelines_api.delete_pipeline(id=pipeline_id)


text:
[Andrew Tedstone](http://atedstone.github.io), October 2016

[Pandas website](http://pandas.pydata.org)

Pandas is your data analysis toolkit. It's the best option for opening up all sorts of datasets, checking them, quickly plotting them, manipulating them, computing statistics using Pandas-aware packages, and exporting to new files.

Below is a very brief tutorial that covers the most important aspects of the package. For more info, check out the tutorials and documentation on the website above. I also recommend the book 'Python for Data Analysis' by Wes McKinney, who wrote the Pandas software.

## Toy weather data

The file [weather.csv](weather.csv) contains a few days of selected weather data from Solheimajokull, a glacier in southern Iceland. Download it and save it with your other course files.

We're going to use it as an example dataset for Pandas. In this case, the data are labelled with dates and times, but you don't have to use Pandas like this - you can load up any tabulated data you like.

## Open the data

You might first want to open the CSV file up in Excel to see it presented in a way you are familiar with.

Let's use the Pandas function that loads CSV files into a Pandas DataFrame. Note that we also need to import matplotlib first:

```python
import matplotlib.pyplot as plt
import pandas as pd
weather = pd.read_csv('weather.csv', index_col='Date', parse_dates=True)
```

There's a couple of things to note about our `read_csv` command. First, we are telling Pandas that our index/label column, which aligns all the values in the other columns, is called 'Date'. Second, we want Pandas to 'parse', or convert the date/time strings into special datetime objects which are calendar- and clock-aware. For more information on this take a look at the [Pandas documentation on time series](http://pandas.pydata.org/pandas-docs/stable/timeseries.html).

Let's take a quick look at what the dataset contains:

```python
weather.head()
```
```
                     AirTemp  Humidity  WindSpd
Date
2013-08-28 17:00:00     12.1      63.8      0.3
2013-08-28 17:30:00     10.8      72.6      1.4
2013-08-28 18:00:00     10.5      73.5      2.0
2013-08-28 18:30:00      9.7      74.5      1.2
2013-08-28 19:00:00      9.8      75.9      1.8

```

The `head()` command shows us the structure of the dataset and the first few lines of data. Here we can see that we have three columns: Air Temperature, Humidity and Wind Speed. These are all indexed, or labelled, together by Date.

We can calculate some summary statistics for the whole dataset:

```python
weather.describe()
```
```
          AirTemp    Humidity     WindSpd
count  292.000000  292.000000  292.000000
mean     8.253767   75.866781    2.757192
std      1.627139   10.426909    2.199402
min      4.500000   45.100000    0.300000
25%      7.200000   68.800000    0.700000
50%      8.100000   75.850000    2.250000
75%      9.225000   84.675000    4.400000
max     18.400000   91.400000    8.500000

```

From the output above we can see that the dataset has 292 rows. The mean air temperature during the period of observations is 8.3 degrees celsius. Humidity has a standard deviation of 10.4 %. The maximum wind speed observed was 8.5 metres per second.

Let's plot the time series of air temperatures:

```python
weather['AirTemp'].plot()
# If the plot doesn't appear, run this line as well:
plt.show()
```

Pandas pops up a plot labelled with the dates and the name of the time series you are looking at, which should look a bit like the following (ignore the different styling):

![Air temperature time series](air_temp.png)

Now close the window.

You can pull out bits of data by date or time. Let's just look at the data for 29 August 2013:

```python
weather['2013-08-29']
```
```
                     AirTemp  Humidity  WindSpd
Date
2013-08-29 00:00:00      8.4      82.5      1.2
2013-08-29 00:30:00      8.2      76.2      2.1
2013-08-29 01:00:00      8.0      71.2      1.7
 ... all the data between these times shown ...
2013-08-29 22:30:00     10.2      89.0      2.3
2013-08-29 23:00:00      9.9      90.6      3.1
2013-08-29 23:30:00      9.9      90.9      2.7
```

You can chain the indexing with `.describe()` to get summary statistics about just this portion of the dataset:

```python
weather['2013-08-29'].describe()
```
```
         AirTemp   Humidity    WindSpd
count  48.000000  48.000000  48.000000
mean    8.552083  83.787500   1.808333
std     0.976313   6.961769   0.684116
min     6.600000  71.200000   0.600000
25%     7.900000  76.425000   1.275000
50%     8.500000  88.150000   1.800000
75%     9.300000  89.550000   2.300000
max    10.200000  91.100000   3.100000
```

We can see that 48 observations were made on 29 August and that the maximum air temperature was 10.2 degrees celsius.

Or we can pull out a range of dates and times, in this case just for 6 hours of the 29th Aug:

```python
weather['2013-08-29 15:00':'2013-08-29 21:00']
```
```
                     AirTemp  Humidity  WindSpd
Date
2013-08-29 15:00:00      9.0      90.0      1.3
2013-08-29 15:30:00      9.2      90.0      1.8
2013-08-29 16:00:00      8.8      90.0      0.6
2013-08-29 16:30:00      7.9      89.3      1.0
2013-08-29 17:00:00      7.6      89.8      0.8
2013-08-29 17:30:00      8.5      89.7      0.9
2013-08-29 18:00:00      8.5      89.1      1.2
2013-08-29 18:30:00      9.1      88.0      2.2
2013-08-29 19:00:00      8.7      89.1      0.9
2013-08-29 19:30:00      9.5      89.4      1.4
2013-08-29 20:00:00      9.7      88.9      1.6
2013-08-29 20:30:00     10.0      88.6      3.0
2013-08-29 21:00:00     10.1      88.3      2.3
```

At the moment, we can see that the data have a 30 minute resolution. What about daily averages?

```python
weather_daily_avg = weather.resample('24H').mean()
weather_daily_avg['WindSpd'].plot()
plt.show()
```

![Daily average wind speed](wind_24h.png)

*Note, the resampling interface to Pandas has changed recently. If the code above just calculates a single value, then you need to use the old function, like this:*

```python
weather_daily_avg = weather.resample('24H', how='mean')
```

Using our original 30-minute data, we can also look at average temperature throughout a 24 hour cycle. To do this we need to 'group' the data by hour of the day and then take the average of all those values.

```python
temp_cycle = weather['AirTemp'].groupby(weather.index.hour).mean()
temp_cycle.plot()
plt.xlabel('Hour of day')
plt.ylabel('Temperature')
plt.show()
```

![Average temperature at each hour during recording period](air_temp_cycle.png)

If you want, you can compare this average daily temperature cycle back to the full temperature time series. Hopefully you'll see that the peak temperature of around 9.5 degrees C at 18:00 is a feature of the original data set.

Lastly, let's export our average daily values to a new file:

```python
weather_daily_avg.to_csv('weather_daily_avg.csv')
```


text:
/**
 * File:   ScaConverterService.java
 * Author: Thomas Calmant
 * Date:   12 janv. 2012
 */
package org.psem2m.sca.converter.core;

import java.io.File;
import java.io.IOException;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osgi.framework.BundleException;
import org.psem2m.composer.config.IComposerConfigHandler;
import org.psem2m.composer.model.ComponentsSetBean;
import org.psem2m.isolates.base.IIsolateLoggerSvc;
import org.psem2m.isolates.base.activators.CPojoBase;
import org.psem2m.sca.converter.model.Composite;

/**
 * The SCA loader service
 *
 * @author Thomas Calmant
 */
@Component(name = "psem2m-composer-sca-converter-factory", publicFactory = false)
@Provides(specifications = IComposerConfigHandler.class)
@Instantiate(name = "psem2m-composer-sca-converter-factory")
public class ScaConverterService extends CPojoBase implements
        IComposerConfigHandler {

    /** The converter */
    private SCAConverter pConverter;

    /** The logger */
    @Requires
    private IIsolateLoggerSvc pLogger;

    /** The parser */
    private SCAParser pParser;

    /*
     * (non-Javadoc)
     *
     * @see
     * org.psem2m.composer.config.IComposerConfigHandler#canHandle(java.lang
     * .String)
     */
    @Override
    public boolean canHandle(final String aFileName) {

        // Accept all files ending with ".composite"
        return aFileName.toLowerCase().endsWith(".composite");
    }

    /*
     * (non-Javadoc)
     *
     * @see org.psem2m.isolates.base.activators.CPojoBase#invalidatePojo()
     */
    @Override
    @Invalidate
    public void invalidatePojo() throws BundleException {

        pLogger.logInfo(this, "invalidatePojo", "SCA Converter gone");
        pParser = null;
        pConverter = null;
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.psem2m.composer.config.IComposerConfigHandler#load(java.lang.String)
     */
    @Override
    public ComponentsSetBean load(final String aFileName) {

        final File file = new File(aFileName).getAbsoluteFile();
        final File folder = file.getParentFile();

        // Parse...
        final Composite sca;
        try {
            sca = pParser.parse(folder, file);

        } catch (final Exception e) {
            pLogger.logWarn(this, "load",
                    "Error parsing the SCA composition in ", folder, " : ", e);
            return null;
        }

        return pConverter.convertToComposer(sca);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.psem2m.isolates.base.activators.CPojoBase#validatePojo()
     */
    @Override
    @Validate
    public void validatePojo() throws BundleException {

        pConverter = new SCAConverter();
        try {
            pParser = new SCAParser();

        } catch (final Exception e) {
            pLogger.logSevere(this, "validatePojo",
                    "Can't set up the SCA parser :", e);
            return;
        }

        pLogger.logInfo(this, "validatePojo", "SCA Converter Ready");
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.psem2m.composer.config.IComposerConfigHandler#write(org.psem2m.composer
     * .model.ComponentsSetBean, java.lang.String)
     */
    @Override
    public void write(final ComponentsSetBean aComponentsSet,
            final String aFileName) throws IOException {

        // Does nothing
        pLogger.logSevere(this, "write", "Not implemented.");

        throw new IOException("Not implemented");
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.soldiersofmobile.todoekspert.activities.AddTodoActivity">

    <EditText
        android:id="@+id/taskEditText"
        android:hint="What to do?"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/doneCheckBox"
        android:layout_below="@id/taskEditText"
        android:text="Is it done?"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/saveButton"
        android:text="Add Todo"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>


text:
<?php
/**
 * Created by PhpStorm.
 * User: aj
 * Date: 18/10/2018
 * Time: 10.32
 */

namespace CLImax\Enum;

class TableDirection
{
    const TOP_TO_BOTTOM = 'topToBottom';
    const LEFT_TO_RIGHT = 'leftToRight';
}


text:
package com.example.sahilnaran.integration.githubapi.resources.repositories.models.responses;

import com.google.gson.annotations.SerializedName;

public class RepositoriesResponseModel {

    @SerializedName("id")
    private String repositoryId;

    @SerializedName("owner")
    private OwnerResponseModel ownerResponseModel;

    @SerializedName("name")
    private String name;

    @SerializedName("full_name")
    private String fullName;

    @SerializedName("description")
    private String description;

    @SerializedName("private")
    private boolean isPrivate;

    @SerializedName("fork")
    private boolean isFork;

    @SerializedName("url")
    private String url;

    @SerializedName("html_url")
    private String htmlUrl;

    public String getRepositoryId() {
        return repositoryId;
    }

    public OwnerResponseModel getOwnerResponseModel() {
        return ownerResponseModel;
    }

    public String getName() {
        return name;
    }

    public String getFullName() {
        return fullName;
    }

    public String getDescription() {
        return description;
    }

    public boolean isPrivate() {
        return isPrivate;
    }

    public boolean isFork() {
        return isFork;
    }

    public String getUrl() {
        return url;
    }

    public String getHtmlUrl() {
        return htmlUrl;
    }
}


text:
using System;

using LinqToDB.Mapping;

namespace Tests.DataProvider
{
	[Table(Name="ALLTYPES")]
	public class ALLTYPE
	{
		[PrimaryKey, Identity] public int       ID                { get; set; } // INTEGER
		[Column,     Nullable] public long?     BIGINTDATATYPE    { get; set; } // BIGINT
		[Column,     Nullable] public int?      INTDATATYPE       { get; set; } // INTEGER
		[Column,     Nullable] public short?    SMALLINTDATATYPE  { get; set; } // SMALLINT
		[Column,     Nullable] public decimal?  DECIMALDATATYPE   { get; set; } // DECIMAL
		[Column,     Nullable] public decimal?  DECFLOATDATATYPE  { get; set; } // DECFLOAT
		[Column,     Nullable] public float?    REALDATATYPE      { get; set; } // REAL
		[Column,     Nullable] public double?   DOUBLEDATATYPE    { get; set; } // DOUBLE
		[Column,     Nullable] public char      CHARDATATYPE      { get; set; } // CHARACTER
		[Column,     Nullable] public string    VARCHARDATATYPE   { get; set; } // VARCHAR(20)
		[Column,     Nullable] public string    CLOBDATATYPE      { get; set; } // CLOB(1048576)
		[Column,     Nullable] public string    DBCLOBDATATYPE    { get; set; } // DBCLOB(100)
		[Column,     Nullable] public object    BINARYDATATYPE    { get; set; } // CHARACTER
		[Column,     Nullable] public string    VARBINARYDATATYPE { get; set; } // VARCHAR(5)
		[Column,     Nullable] public byte[]    BLOBDATATYPE      { get; set; } // BLOB(10)
		[Column,     Nullable] public string    GRAPHICDATATYPE   { get; set; } // GRAPHIC(10)
		[Column,     Nullable] public DateTime? DATEDATATYPE      { get; set; } // DATE
		[Column,     Nullable] public TimeSpan? TIMEDATATYPE      { get; set; } // TIME
		[Column,     Nullable] public DateTime? TIMESTAMPDATATYPE { get; set; } // TIMESTAMP
		[Column,     Nullable] public string    XMLDATATYPE       { get; set; } // XML
	}
}


text:
from __future__ import unicode_literals

import os
from setuptools import setup, find_packages

def read_file(filename):
    """Read a file into a string"""
    path = os.path.abspath(os.path.dirname(__file__))
    filepath = os.path.join(path, filename)
    try:
        return open(filepath).read()
    except IOError:
        return ''

setup(
    name='django-ad-code',
    version=__import__('adcode').__version__,
    author='Mark Lavin',
    author_email='markdlavin@gmail.com',
    packages=find_packages(exclude=['example']),
    include_package_data=True,
    url='https://github.com/mlavin/django-ad-code',
    license='BSD',
    description=' '.join(__import__('adcode').__doc__.splitlines()).strip(),
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'Framework :: Django',
        'Framework :: Django :: 1.8',
        'Framework :: Django :: 1.9',
        'Framework :: Django :: 1.10',
        'Framework :: Django :: 1.11',
        'Framework :: Django :: 2.0',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
    long_description=read_file('README.rst'),
    test_suite="runtests.runtests",
    zip_safe=False,  # because we're including media that Django needs
)


text:
package gaws

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"math"
	"net/http"
	"time"

	"github.com/smartystreets/go-aws-auth"
)

// MaxTries is the number of times to retry a failing AWS request.
var MaxTries int = 5

// gawsError is the error document returned from many AWS requests.
type gawsError struct {
	Type    string `json:"__type"`
	Message string `json:"message"`
}

var exceededRetriesError = gawsError{Type: "GawsExceededMaxRetries", Message: "The maximum number of retries for this request was exceeded."}

// Error formats the gawsError into an error message.
func (e gawsError) Error() string {
	return fmt.Sprintf("%v: %v", e.Type, e.Message)
}

type retryPredicate func(int, []byte) (bool, error)

// AWSRequest is a request to AWS. It is used instead of http.Request to facilitate retries.
type AWSRequest struct {
	RetryPredicate retryPredicate
	URL            string
	Method         string
	Headers        map[string]string
	Body           []byte
}

func (r *AWSRequest) getRequest() *http.Request {

	payload := bytes.NewReader(r.Body)
	req, _ := http.NewRequest(r.Method, r.URL, payload)

	for k, v := range r.Headers {
		req.Header.Set(k, v)
	}

	awsauth.Sign(req)
	return req
}

// Do makes the request to AWS and retries with an exponential backoff.
func (r *AWSRequest) Do() ([]byte, error) {
	client := &http.Client{}
	var lastBody []byte

	for try := 1; try < MaxTries; try++ {
		req := r.getRequest()
		resp, err := client.Do(req)

		if err != nil {
			return make([]byte, 0), err
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)

		if err != nil {
			return body, err
		}

		shouldRetry, err := r.RetryPredicate(resp.StatusCode, body)
		if shouldRetry {
			lastBody = body

			// Exponential backoff for the retry
			sleepDuration := time.Duration(100 * math.Pow(2.0, float64(try)))
			time.Sleep(sleepDuration * time.Millisecond)
		} else {
			return body, err
		}
	}
	return lastBody, exceededRetriesError
}


text:
package cgroups

import (
	"bufio"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/dotcloud/docker/pkg/mount"
)

// https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt
func FindCgroupMountpoint(subsystem string) (string, error) {
	mounts, err := mount.GetMounts()
	if err != nil {
		return "", err
	}

	for _, mount := range mounts {
		if mount.Fstype == "cgroup" {
			for _, opt := range strings.Split(mount.VfsOpts, ",") {
				if opt == subsystem {
					return mount.Mountpoint, nil
				}
			}
		}
	}
	return "", ErrNotFound
}

// Returns the relative path to the cgroup docker is running in.
func GetThisCgroupDir(subsystem string) (string, error) {
	f, err := os.Open("/proc/self/cgroup")
	if err != nil {
		return "", err
	}
	defer f.Close()

	return parseCgroupFile(subsystem, f)
}

func GetInitCgroupDir(subsystem string) (string, error) {
	f, err := os.Open("/proc/1/cgroup")
	if err != nil {
		return "", err
	}
	defer f.Close()

	return parseCgroupFile(subsystem, f)
}

func ReadProcsFile(dir string) ([]int, error) {
	f, err := os.Open(filepath.Join(dir, "cgroup.procs"))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	var (
		s   = bufio.NewScanner(f)
		out = []int{}
	)

	for s.Scan() {
		if t := s.Text(); t != "" {
			pid, err := strconv.Atoi(t)
			if err != nil {
				return nil, err
			}
			out = append(out, pid)
		}
	}
	return out, nil
}

func parseCgroupFile(subsystem string, r io.Reader) (string, error) {
	s := bufio.NewScanner(r)
	for s.Scan() {
		if err := s.Err(); err != nil {
			return "", err
		}
		text := s.Text()
		parts := strings.Split(text, ":")
		for _, subs := range strings.Split(parts[1], ",") {
			if subs == subsystem {
				return parts[2], nil
			}
		}
	}
	return "", ErrNotFound
}


text:
package org.elasticsearch.index.reindex;

import org.elasticsearch.script.ScriptService;

import java.util.Date;
import java.util.Map;

import static org.hamcrest.Matchers.containsString;

public class UpdateByQueryWithScriptTests
        extends AbstractAsyncBulkIndexByScrollActionScriptTestCase<UpdateByQueryRequest, BulkIndexByScrollResponse> {

    public void testModifyingCtxNotAllowed() {
        /*
         * Its important that none of these actually match any of the fields.
         * They don't now, but make sure they still don't match if you add any
         * more. The point of have many is that they should all present the same
         * error message to the user, not some ClassCastException.
         */
        Object[] options = new Object[] {"cat", new Object(), 123, new Date(), Math.PI};
        for (String ctxVar: new String[] {"_index", "_type", "_id", "_version", "_parent", "_routing", "_timestamp", "_ttl"}) {
            try {
                applyScript((Map<String, Object> ctx) -> ctx.put(ctxVar, randomFrom(options)));
            } catch (IllegalArgumentException e) {
                assertThat(e.getMessage(), containsString("Modifying [" + ctxVar + "] not allowed"));
            }
        }
    }

    @Override
    protected UpdateByQueryRequest request() {
        return new UpdateByQueryRequest();
    }

    @Override
    protected AbstractAsyncBulkIndexByScrollAction<UpdateByQueryRequest> action(ScriptService scriptService, UpdateByQueryRequest request) {
        return new TransportUpdateByQueryAction.AsyncIndexBySearchAction(task, logger, null, threadPool, request, listener(),
                scriptService, null);
    }
}


text:
package org.apache.bookkeeper.replication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.client.LedgerHandle;
import org.apache.bookkeeper.client.LedgerHandleAdapter;
import org.apache.bookkeeper.meta.LedgerManager;
import org.apache.bookkeeper.meta.LedgerManagerFactory;
import org.apache.bookkeeper.meta.LedgerUnderreplicationManager;
import org.apache.bookkeeper.meta.ZkLedgerUnderreplicationManager;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.proto.BookieServer;
import org.apache.bookkeeper.replication.ReplicationException.CompatibilityException;
import org.apache.bookkeeper.replication.ReplicationException.UnavailableException;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Integration tests verifies the complete functionality of the
 * Auditor-rereplication process: Auditor will publish the bookie failures,
 * consequently ReplicationWorker will get the notifications and act on it.
 */
public class BookieAutoRecoveryTest extends BookKeeperClusterTestCase {
    private static final Logger LOG = LoggerFactory
            .getLogger(BookieAutoRecoveryTest.class);
    private static final byte[] PASSWD = "admin".getBytes();
    private static final byte[] data = "TESTDATA".getBytes();
    private static final String openLedgerRereplicationGracePeriod = "3000"; // milliseconds

    private DigestType digestType;
    private LedgerManagerFactory mFactory;
    private LedgerUnderreplicationManager underReplicationManager;
    private LedgerManager ledgerManager;

    private final String UNDERREPLICATED_PATH = baseClientConf
            .getZkLedgersRootPath() + "/underreplication/ledgers";

    public BookieAutoRecoveryTest() throws IOException, KeeperException,
            InterruptedException, UnavailableException, CompatibilityException {
        super(3);

        baseConf.setLedgerManagerFactoryClassName(
                "org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory");
        baseConf.setOpenLedgerRereplicationGracePeriod(openLedgerRereplicationGracePeriod);
        baseConf.setAuditorStaleBookieInterval(1);
        baseConf.setAuditorPeriodicBookieCheckInterval(2);
        baseConf.setAuditorPeriodicCheckInterval(2);
        baseClientConf.setLedgerManagerFactoryClassName(
                "org.apache.bookkeeper.meta.HierarchicalLedgerManagerFactory");
        this.digestType = DigestType.MAC;
        setAutoRecoveryEnabled(true);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        baseConf.setZkServers(zkUtil.getZooKeeperConnectString());
        // initialize urReplicationManager
        mFactory = LedgerManagerFactory.newLedgerManagerFactory(baseClientConf,
                zkc);
        underReplicationManager = mFactory.newLedgerUnderreplicationManager();
        LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory
                .newLedgerManagerFactory(baseClientConf, zkc);
        ledgerManager = newLedgerManagerFactory.newLedgerManager();
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
        if (null != mFactory) {
            mFactory.uninitialize();
            mFactory = null;
        }
        if (null != underReplicationManager) {
            underReplicationManager.close();
            underReplicationManager = null;
        }
        if (null != ledgerManager) {
            ledgerManager.close();
            ledgerManager = null;
        }
    }

    /**
     * Test verifies publish urLedger by Auditor and replication worker is
     * picking up the entries and finishing the rereplication of open ledger
     */
    @Test(timeout = 90000)
    public void testOpenLedgers() throws Exception {
        List<LedgerHandle> listOfLedgerHandle = createLedgersAndAddEntries(1, 5);
        LedgerHandle lh = listOfLedgerHandle.get(0);
        int ledgerReplicaIndex = 0;
        BookieSocketAddress replicaToKillAddr = LedgerHandleAdapter
                .getLedgerMetadata(lh).getEnsembles().get(0L).get(0);

        final String urLedgerZNode = getUrLedgerZNode(lh);
        ledgerReplicaIndex = getReplicaIndexInLedger(lh, replicaToKillAddr);

        CountDownLatch latch = new CountDownLatch(1);
        assertNull("UrLedger already exists!",
                watchUrLedgerNode(urLedgerZNode, latch));

        LOG.info("Killing Bookie :" + replicaToKillAddr);
        killBookie(replicaToKillAddr);

        // waiting to publish urLedger znode by Auditor
        latch.await();
        latch = new CountDownLatch(1);
        LOG.info("Watching on urLedgerPath:" + urLedgerZNode
                + " to know the status of rereplication process");
        assertNotNull("UrLedger doesn't exists!",
                watchUrLedgerNode(urLedgerZNode, latch));

        // starting the replication service, so that he will be able to act as
        // target bookie
        startNewBookie();
        int newBookieIndex = bs.size() - 1;
        BookieServer newBookieServer = bs.get(newBookieIndex);

        LOG.debug("Waiting to finish the replication of failed bookie : "
                + replicaToKillAddr);
        latch.await();

        // grace period to update the urledger metadata in zookeeper
        LOG.info("Waiting to update the urledger metadata in zookeeper");

        verifyLedgerEnsembleMetadataAfterReplication(newBookieServer,
                listOfLedgerHandle.get(0), ledgerReplicaIndex);
    }

    /**
     * Test verifies publish urLedger by Auditor and replication worker is
     * picking up the entries and finishing the rereplication of closed ledgers
     */
    @Test(timeout = 90000)
    public void testClosedLedgers() throws Exception {
        List<Integer> listOfReplicaIndex = new ArrayList<Integer>();
        List<LedgerHandle> listOfLedgerHandle = createLedgersAndAddEntries(1, 5);
        closeLedgers(listOfLedgerHandle);
        LedgerHandle lhandle = listOfLedgerHandle.get(0);
        int ledgerReplicaIndex = 0;
        BookieSocketAddress replicaToKillAddr = LedgerHandleAdapter
                .getLedgerMetadata(lhandle).getEnsembles().get(0L).get(0);

        CountDownLatch latch = new CountDownLatch(listOfLedgerHandle.size());
        for (LedgerHandle lh : listOfLedgerHandle) {
            ledgerReplicaIndex = getReplicaIndexInLedger(lh, replicaToKillAddr);
            listOfReplicaIndex.add(ledgerReplicaIndex);
            assertNull("UrLedger already exists!",
                    watchUrLedgerNode(getUrLedgerZNode(lh), latch));
        }

        LOG.info("Killing Bookie :" + replicaToKillAddr);
        killBookie(replicaToKillAddr);

        // waiting to publish urLedger znode by Auditor
        latch.await();

        // Again watching the urLedger znode to know the replication status
        latch = new CountDownLatch(listOfLedgerHandle.size());
        for (LedgerHandle lh : listOfLedgerHandle) {
            String urLedgerZNode = getUrLedgerZNode(lh);
            LOG.info("Watching on urLedgerPath:" + urLedgerZNode
                    + " to know the status of rereplication process");
            assertNotNull("UrLedger doesn't exists!",
                    watchUrLedgerNode(urLedgerZNode, latch));
        }

        // starting the replication service, so that he will be able to act as
        // target bookie
        startNewBookie();
        int newBookieIndex = bs.size() - 1;
        BookieServer newBookieServer = bs.get(newBookieIndex);

        LOG.debug("Waiting to finish the replication of failed bookie : "
                + replicaToKillAddr);

        // waiting to finish replication
        latch.await();

        // grace period to update the urledger metadata in zookeeper
        LOG.info("Waiting to update the urledger metadata in zookeeper");

        for (int index = 0; index < listOfLedgerHandle.size(); index++) {
            verifyLedgerEnsembleMetadataAfterReplication(newBookieServer,
                    listOfLedgerHandle.get(index),
                    listOfReplicaIndex.get(index));
        }
    }

    /**
     * Test stopping replica service while replication in progress. Considering
     * when there is an exception will shutdown Auditor and RW processes. After
     * restarting should be able to finish the re-replication activities
     */
    @Test(timeout = 90000)
    public void testStopWhileReplicationInProgress() throws Exception {
        int numberOfLedgers = 2;
        List<Integer> listOfReplicaIndex = new ArrayList<Integer>();
        List<LedgerHandle> listOfLedgerHandle = createLedgersAndAddEntries(
                numberOfLedgers, 5);
        closeLedgers(listOfLedgerHandle);
        LedgerHandle handle = listOfLedgerHandle.get(0);
        BookieSocketAddress replicaToKillAddr = LedgerHandleAdapter
                .getLedgerMetadata(handle).getEnsembles().get(0L).get(0);
        LOG.info("Killing Bookie:" + replicaToKillAddr);

        // Each ledger, there will be two events : create urLedger and after
        // rereplication delete urLedger
        CountDownLatch latch = new CountDownLatch(listOfLedgerHandle.size());
        for (int i = 0; i < listOfLedgerHandle.size(); i++) {
            final String urLedgerZNode = getUrLedgerZNode(listOfLedgerHandle
                    .get(i));
            assertNull("UrLedger already exists!",
                    watchUrLedgerNode(urLedgerZNode, latch));
            int replicaIndexInLedger = getReplicaIndexInLedger(
                    listOfLedgerHandle.get(i), replicaToKillAddr);
            listOfReplicaIndex.add(replicaIndexInLedger);
        }

        LOG.info("Killing Bookie :" + replicaToKillAddr);
        killBookie(replicaToKillAddr);

        // waiting to publish urLedger znode by Auditor
        latch.await();

        // Again watching the urLedger znode to know the replication status
        latch = new CountDownLatch(listOfLedgerHandle.size());
        for (LedgerHandle lh : listOfLedgerHandle) {
            String urLedgerZNode = getUrLedgerZNode(lh);
            LOG.info("Watching on urLedgerPath:" + urLedgerZNode
                    + " to know the status of rereplication process");
            assertNotNull("UrLedger doesn't exists!",
                    watchUrLedgerNode(urLedgerZNode, latch));
        }

        // starting the replication service, so that he will be able to act as
        // target bookie
        startNewBookie();
        int newBookieIndex = bs.size() - 1;
        BookieServer newBookieServer = bs.get(newBookieIndex);

        LOG.debug("Waiting to finish the replication of failed bookie : "
                + replicaToKillAddr);
        while (true) {
            if (latch.getCount() < numberOfLedgers || latch.getCount() <= 0) {
                stopReplicationService();
                LOG.info("Latch Count is:" + latch.getCount());
                break;
            }
            // grace period to take breath
            Thread.sleep(1000);
        }

        startReplicationService();

        LOG.info("Waiting to finish rereplication processes");
        latch.await();

        // grace period to update the urledger metadata in zookeeper
        LOG.info("Waiting to update the urledger metadata in zookeeper");

        for (int index = 0; index < listOfLedgerHandle.size(); index++) {
            verifyLedgerEnsembleMetadataAfterReplication(newBookieServer,
                    listOfLedgerHandle.get(index),
                    listOfReplicaIndex.get(index));
        }
    }

    /**
     * Verify the published urledgers of deleted ledgers(those ledgers where
     * deleted after publishing as urledgers by Auditor) should be cleared off
     * by the newly selected replica bookie
     */
    @Test(timeout = 30000)
    public void testNoSuchLedgerExists() throws Exception {
        List<LedgerHandle> listOfLedgerHandle = createLedgersAndAddEntries(2, 5);
        CountDownLatch latch = new CountDownLatch(listOfLedgerHandle.size());
        for (LedgerHandle lh : listOfLedgerHandle) {
            assertNull("UrLedger already exists!",
                    watchUrLedgerNode(getUrLedgerZNode(lh), latch));
        }
        BookieSocketAddress replicaToKillAddr = LedgerHandleAdapter
                .getLedgerMetadata(listOfLedgerHandle.get(0)).getEnsembles()
                .get(0L).get(0);
        killBookie(replicaToKillAddr);
        replicaToKillAddr = LedgerHandleAdapter
                .getLedgerMetadata(listOfLedgerHandle.get(0)).getEnsembles()
                .get(0L).get(0);
        killBookie(replicaToKillAddr);
        // waiting to publish urLedger znode by Auditor
        latch.await();

        latch = new CountDownLatch(listOfLedgerHandle.size());
        for (LedgerHandle lh : listOfLedgerHandle) {
            assertNotNull("UrLedger doesn't exists!",
                    watchUrLedgerNode(getUrLedgerZNode(lh), latch));
        }

        // delete ledgers
        for (LedgerHandle lh : listOfLedgerHandle) {
            bkc.deleteLedger(lh.getId());
        }
        startNewBookie();

        // waiting to delete published urledgers, since it doesn't exists
        latch.await();

        for (LedgerHandle lh : listOfLedgerHandle) {
            assertNull("UrLedger still exists after rereplication",
                    watchUrLedgerNode(getUrLedgerZNode(lh), latch));
        }
    }

    /**
     * Test that if a empty ledger loses the bookie not in the quorum for entry 0, it will
     * still be openable when it loses enough bookies to lose a whole quorum.
     */
    @Test(timeout=10000)
    public void testEmptyLedgerLosesQuorumEventually() throws Exception {
        LedgerHandle lh = bkc.createLedger(3, 2, 2, DigestType.CRC32, PASSWD);
        CountDownLatch latch = new CountDownLatch(1);
        String urZNode = getUrLedgerZNode(lh);
        watchUrLedgerNode(urZNode, latch);

        BookieSocketAddress replicaToKill = LedgerHandleAdapter
            .getLedgerMetadata(lh).getEnsembles().get(0L).get(2);
        LOG.info("Killing last bookie, {}, in ensemble {}", replicaToKill,
                 LedgerHandleAdapter.getLedgerMetadata(lh).getEnsembles().get(0L));
        killBookie(replicaToKill);

        getAuditor().submitAuditTask().get(); // ensure auditor runs

        assertTrue("Should be marked as underreplicated", latch.await(5, TimeUnit.SECONDS));
        latch = new CountDownLatch(1);
        Stat s = watchUrLedgerNode(urZNode, latch); // should be marked as replicated
        if (s != null) {
            assertTrue("Should be marked as replicated", latch.await(10, TimeUnit.SECONDS));
        }

        replicaToKill = LedgerHandleAdapter
            .getLedgerMetadata(lh).getEnsembles().get(0L).get(1);
        LOG.info("Killing second bookie, {}, in ensemble {}", replicaToKill,
                 LedgerHandleAdapter.getLedgerMetadata(lh).getEnsembles().get(0L));
        killBookie(replicaToKill);

        getAuditor().submitAuditTask().get(); // ensure auditor runs

        assertTrue("Should be marked as underreplicated", latch.await(5, TimeUnit.SECONDS));
        latch = new CountDownLatch(1);
        s = watchUrLedgerNode(urZNode, latch); // should be marked as replicated
        if (s != null) {
            assertTrue("Should be marked as replicated", latch.await(5, TimeUnit.SECONDS));
        }

        // should be able to open ledger without issue
        bkc.openLedger(lh.getId(), DigestType.CRC32, PASSWD);
    }

    private int getReplicaIndexInLedger(LedgerHandle lh,
            BookieSocketAddress replicaToKill) {
        SortedMap<Long, ArrayList<BookieSocketAddress>> ensembles = LedgerHandleAdapter
                .getLedgerMetadata(lh).getEnsembles();
        int ledgerReplicaIndex = -1;
        for (BookieSocketAddress addr : ensembles.get(0L)) {
            ++ledgerReplicaIndex;
            if (addr.equals(replicaToKill)) {
                break;
            }
        }
        return ledgerReplicaIndex;
    }

    private void verifyLedgerEnsembleMetadataAfterReplication(
            BookieServer newBookieServer, LedgerHandle lh,
            int ledgerReplicaIndex) throws BKException, InterruptedException {
        LedgerHandle openLedger = bkc
                .openLedger(lh.getId(), digestType, PASSWD);

        BookieSocketAddress BookieSocketAddress = LedgerHandleAdapter
                .getLedgerMetadata(openLedger).getEnsembles().get(0L)
                .get(ledgerReplicaIndex);
        assertEquals("Rereplication has been failed and ledgerReplicaIndex :"
                + ledgerReplicaIndex, newBookieServer.getLocalAddress(),
                BookieSocketAddress);
    }

    private void closeLedgers(List<LedgerHandle> listOfLedgerHandle)
            throws InterruptedException, BKException {
        for (LedgerHandle lh : listOfLedgerHandle) {
            lh.close();
        }
    }

    private List<LedgerHandle> createLedgersAndAddEntries(int numberOfLedgers,
            int numberOfEntries) throws InterruptedException, BKException {
        List<LedgerHandle> listOfLedgerHandle = new ArrayList<LedgerHandle>(
                numberOfLedgers);
        for (int index = 0; index < numberOfLedgers; index++) {
            LedgerHandle lh = bkc.createLedger(3, 3, digestType, PASSWD);
            listOfLedgerHandle.add(lh);
            for (int i = 0; i < numberOfEntries; i++) {
                lh.addEntry(data);
            }
        }
        return listOfLedgerHandle;
    }

    private String getUrLedgerZNode(LedgerHandle lh) {
        return ZkLedgerUnderreplicationManager.getUrLedgerZnode(
                UNDERREPLICATED_PATH, lh.getId());
    }

    private Stat watchUrLedgerNode(final String znode,
            final CountDownLatch latch) throws KeeperException,
            InterruptedException {
        return zkc.exists(znode, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == EventType.NodeDeleted) {
                    LOG.info("Recieved Ledger rereplication completion event :"
                            + event.getType());
                    latch.countDown();
                }
                if (event.getType() == EventType.NodeCreated) {
                    LOG.info("Recieved urLedger publishing event :"
                            + event.getType());
                    latch.countDown();
                }
            }
        });
    }
}