text:
require 'spec_helper'

RSpec.describe 'User updates wiki page' do
  include WikiHelpers

  let(:user) { create(:user) }

  before do
    project.add_maintainer(user)
    sign_in(user)
  end

  context 'when wiki is empty' do
    before do |example|
      visit(project_wikis_path(project))

      wait_for_svg_to_be_loaded(example)

      click_link "Create your first page"
    end

    context 'in a user namespace' do
      let(:project) { create(:project, :wiki_repo) }

      it 'redirects back to the home edit page' do
        page.within(:css, '.wiki-form .form-actions') do
          click_on('Cancel')
        end

        expect(current_path).to eq wiki_path(project.wiki)
      end

      it 'updates a page that has a path', :js do
        fill_in(:wiki_title, with: 'one/two/three-test')

        page.within '.wiki-form' do
          fill_in(:wiki_content, with: 'wiki content')
          click_on('Create page')
        end

        expect(current_path).to include('one/two/three-test')
        expect(find('.wiki-pages')).to have_content('three')

        first(:link, text: 'three').click

        expect(find('.nav-text')).to have_content('three')

        click_on('Edit')

        expect(current_path).to include('one/two/three-test')
        expect(page).to have_content('Edit Page')

        fill_in('Content', with: 'Updated Wiki Content')
        click_on('Save changes')

        expect(page).to have_content('Updated Wiki Content')
      end

      it_behaves_like 'wiki file attachments'
    end
  end

  context 'when wiki is not empty' do
    let(:project_wiki) { create(:project_wiki, project: project, user: project.creator) }
    let!(:wiki_page) { create(:wiki_page, wiki: project_wiki, title: 'home', content: 'Home page') }

    before do
      visit(project_wikis_path(project))

      click_link('Edit')
    end

    context 'in a user namespace' do
      let(:project) { create(:project, :wiki_repo) }

      it 'updates a page', :js do
        # Commit message field should have correct value.
        expect(page).to have_field('wiki[message]', with: 'Update home')

        fill_in(:wiki_content, with: 'My awesome wiki!')
        click_button('Save changes')

        expect(page).to have_content('Home')
        expect(page).to have_content("Last edited by #{user.name}")
        expect(page).to have_content('My awesome wiki!')
      end

      it 'updates the commit message as the title is changed', :js do
        fill_in(:wiki_title, with: '& < > \ \ { } &')

        expect(page).to have_field('wiki[message]', with: 'Update & < > \ \ { } &')
      end

      it 'correctly escapes the commit message entities', :js do
        fill_in(:wiki_title, with: 'Wiki title')

        expect(page).to have_field('wiki[message]', with: 'Update Wiki title')
      end

      it 'shows a validation error message' do
        fill_in(:wiki_content, with: '')
        click_button('Save changes')

        expect(page).to have_selector('.wiki-form')
        expect(page).to have_content('Edit Page')
        expect(page).to have_content('The form contains the following error:')
        expect(page).to have_content("Content can't be blank")
        expect(find('textarea#wiki_content').value).to eq('')
      end

      it 'shows the emoji autocompletion dropdown', :js do
        find('#wiki_content').native.send_keys('')
        fill_in(:wiki_content, with: ':')

        expect(page).to have_selector('.atwho-view')
      end

      it 'shows the error message' do
        wiki_page.update(content: 'Update')

        click_button('Save changes')

        expect(page).to have_content('Someone edited the page the same time you did.')
      end

      it 'updates a page' do
        fill_in('Content', with: 'Updated Wiki Content')
        click_on('Save changes')

        expect(page).to have_content('Updated Wiki Content')
      end

      it 'cancels editing of a page' do
        page.within(:css, '.wiki-form .form-actions') do
          click_on('Cancel')
        end

        expect(current_path).to eq(project_wiki_path(project, wiki_page))
      end

      it_behaves_like 'wiki file attachments'
    end

    context 'in a group namespace' do
      let(:project) { create(:project, :wiki_repo, namespace: create(:group, :public)) }

      it 'updates a page', :js do
        # Commit message field should have correct value.
        expect(page).to have_field('wiki[message]', with: 'Update home')

        fill_in(:wiki_content, with: 'My awesome wiki!')

        click_button('Save changes')

        expect(page).to have_content('Home')
        expect(page).to have_content("Last edited by #{user.name}")
        expect(page).to have_content('My awesome wiki!')
      end

      it_behaves_like 'wiki file attachments'
    end
  end

  context 'when the page is in a subdir' do
    let!(:project) { create(:project, :wiki_repo) }
    let(:project_wiki) { create(:project_wiki, project: project, user: project.creator) }
    let(:page_name) { 'page_name' }
    let(:page_dir) { "foo/bar/#{page_name}" }
    let!(:wiki_page) { create(:wiki_page, wiki: project_wiki, title: page_dir, content: 'Home page') }

    before do
      visit(project_wiki_edit_path(project, wiki_page))
    end

    it 'moves the page to the root folder' do
      fill_in(:wiki_title, with: "/#{page_name}")

      click_button('Save changes')

      expect(current_path).to eq(project_wiki_path(project, page_name))
    end

    it 'moves the page to other dir' do
      new_page_dir = "foo1/bar1/#{page_name}"

      fill_in(:wiki_title, with: new_page_dir)

      click_button('Save changes')

      expect(current_path).to eq(project_wiki_path(project, new_page_dir))
    end

    it 'remains in the same place if title has not changed' do
      original_path = project_wiki_path(project, wiki_page)

      fill_in(:wiki_title, with: page_name)

      click_button('Save changes')

      expect(current_path).to eq(original_path)
    end

    it 'can be moved to a different dir with a different name' do
      new_page_dir = "foo1/bar1/new_page_name"

      fill_in(:wiki_title, with: new_page_dir)

      click_button('Save changes')

      expect(current_path).to eq(project_wiki_path(project, new_page_dir))
    end

    it 'can be renamed and moved to the root folder' do
      new_name = 'new_page_name'

      fill_in(:wiki_title, with: "/#{new_name}")

      click_button('Save changes')

      expect(current_path).to eq(project_wiki_path(project, new_name))
    end

    it 'squishes the title before creating the page' do
      new_page_dir = "  foo1 /  bar1  /  #{page_name}  "

      fill_in(:wiki_title, with: new_page_dir)

      click_button('Save changes')

      expect(current_path).to eq(project_wiki_path(project, "foo1/bar1/#{page_name}"))
    end

    it_behaves_like 'wiki file attachments'
  end

  context 'when an existing page exceeds the content size limit' do
    let_it_be(:project) { create(:project, :wiki_repo) }
    let!(:wiki_page) { create(:wiki_page, wiki: project.wiki, content: "one\ntwo\nthree") }

    before do
      stub_application_setting(wiki_page_max_content_bytes: 10)

      visit wiki_page_path(wiki_page.wiki, wiki_page, action: :edit)
    end

    it 'allows changing the title if the content does not change' do
      fill_in 'Title', with: 'new title'
      click_on 'Save changes'

      expect(page).to have_content('Wiki was successfully updated.')
    end

    it 'shows a validation error when trying to change the content' do
      fill_in 'Content', with: 'new content'
      click_on 'Save changes'

      expect(page).to have_content('The form contains the following error:')
      expect(page).to have_content('Content is too long (11 Bytes). The maximum size is 10 Bytes.')
    end
  end
end


text:
using System;
using System.Xml;
using Autofac;
using PicklesDoc.Pickles.DocumentationBuilders.HTML;
using PicklesDoc.Pickles.ObjectModel;
using NFluent;
using TechTalk.SpecFlow;

namespace PicklesDoc.Pickles.Test.DocumentationBuilders.HTML.AutomationLayer
{
  [Binding]
  public class StepDefinitions
  {
    [Given(@"I have this feature description")]
    public void GivenIHaveThisFeatureDescription(string multilineText)
    {
      CurrentScenarioContext.Feature = new Feature
      {
        Name = "a feature",
        Description = multilineText
      };
    }

    [Given(@"I have this feature file")]
    public void GivenIHaveThisFeatureFile(string multilineText)
    {
      CurrentScenarioContext.Feature = new Feature
        {
          Name = "a feature",
          Description = multilineText
        };
    }

    [When(@"I generate the documentation")]
    public void WhenIGenerateTheDocumentation()
    {
      var configuration = CurrentScenarioContext.Container.Resolve<Configuration>();
      var htmlFeatureFormatter = CurrentScenarioContext.Container.Resolve<HtmlFeatureFormatter>();

      CurrentScenarioContext.Html = htmlFeatureFormatter.Format(CurrentScenarioContext.Feature);
    }

    [Then(@"the result should be")]
    public void ThenTheResultShouldBe(string multilineText)
    {
      var actual = CurrentScenarioContext.Html.ToString();
      actual = actual.Replace(" xmlns=\"http://www.w3.org/1999/xhtml\"", string.Empty);

      actual = FormatXml(actual);
      multilineText = FormatXml(multilineText);

      Check.That(actual).IsEqualTo(multilineText);
    }

    private static string FormatXml(string xmlDocument)
    {
      using (var sw = new System.IO.StringWriter())
      {
        using (XmlWriter xw = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, NewLineHandling = NewLineHandling.Replace, NewLineChars = Environment.NewLine }))
        {
          xw.WriteRaw(xmlDocument);
          xw.Flush();

          return sw.ToString();
        }
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Öst. Z. Pilzk. 16: 150 (2007)

#### Original name
Conocybe papillata Hauskn. & L. Nagy

### Remarks
null


text:
import sys, os
sys.path.insert(0, os.path.abspath('..'))

# Sphinx configuration
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'sphinxarg.ext'
]

source_suffix = '.rst'
master_doc = 'index'

project = 'Student Robotics match scheduler'
copyright = '2015, Student Robotics'

from sr.comp.scheduler.metadata import VERSION as version
release = version

html_theme = 'default'


text:
package org.apache.cloudstack.api.response;

import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import org.apache.cloudstack.ha.HAConfig;

import java.util.List;

@EntityReference(value = HAConfig.class)
public final class HAProviderResponse extends BaseResponse {
    @SerializedName(ApiConstants.HA_PROVIDER)
    @Param(description = "the HA provider")
    private String provider;

    @SerializedName(ApiConstants.TYPE)
    @Param(description = "the HA provider resource type detail")
    private List<String> supportedResourceTypes;

    public HAProviderResponse() {
        super("haprovider");
    }

    public String getProvider() {
        return provider;
    }

    public void setProvider(String provider) {
        this.provider = provider;
    }

    public List<String> getSupportedResourceTypes() {
        return supportedResourceTypes;
    }

    public void setSupportedResourceTypes(List<String> supportedResourceTypes) {
        this.supportedResourceTypes = supportedResourceTypes;
    }
}


text:
/* Generic sysexits */
/* $OpenLDAP: pkg/ldap/include/ac/sysexits.h,v 1.12.2.6 2011/01/04 23:49:57 kurt Exp $ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 1998-2011 The OpenLDAP Foundation.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */

#ifndef _AC_SYSEXITS_H_
#define _AC_SYSEXITS_H_

#ifdef HAVE_SYSEXITS_H
#	include <sysexits.h>
#else
#	include <sysexits-compat.h>
#endif

#endif /* _AC_SYSEXITS_H_ */


text:
var f = require('flates')
  , scripts =
    [ '/dep/jquery.min.js'
    , '/dep/foundation.min.js'
    , '/client.js'
    ]
  , links =
    [ '/dep/normalize.css'
    , '/dep/foundation.css'
    , '/style.css'
    ]
  , example = { class: 'example large-10 large-offset-1 coloums'}

module.exports = function () {
  return f.d() + links.map(function(link) {
    return f.link({href: link, rel: 'stylesheet' })
  }).join('') + f.div({ class: 'row' },
      [ f.h1('JS scope')
      , f.p('An attempt to explain lexical, block level scope.')
      , f.aside({ class: 'warning'},
          [ 'This website is serving as a playground for some odd technology'
          , 'with the intention that it will one day be suitable for the purpose'
          , 'of learning about scope in JavaScript.'
          ].join(' ')
        )
      , f.p(
        [ "A quick overview of scope in JavaScript, we'll look at this all in"
        , 'detail in a second:'
        , 'Any variable available in the scope in which a function is declared'
        , 'is available inside that function. Declaring something new in a scope'
        , 'shadows any outer uses of the same name, rendering them unreachable.'
        , 'Functions are the only unit of scope, other blocks are part of the'
        , 'function they are contained within.'
        , 'All arguments to a function are declared inside that scope'
        , 'if they are set or not. Along with the magical "this" and'
        , '"arguments" variables.'
        ].join(' '))
      , f.p(
        [ 'One way to think about scope is as a series of concentric circles'
        , 'with the inner circles able to acces the variables in all outer'
        , 'circles, but outer circles not able to get to the inner ones.'
        , 'These outer circles are always availible whenever the function'
        , 'is invoked, even if it has been returned out of the scope it'
        , 'was defined in. This is know as closure, and it allows many of'
        , 'the poweful abstractions used in JavaScript.'
        ].join(' '))
      , f.p('Insert demo here')
      , f.p(
        [ 'The inner function can always acces the outer scope:'
        , f.pre(example,
          [ 'var a = 0'
          , 'function inner () {'
          , '  a += 1'
          , '}'
          , ''
          , 'inner()'
          , 'console.log(a) // 1'
          , 'inner()'
          , 'console.log(a) // 2'
          , 'inner()'
          , 'console.log(a) // 3'
          ].join('\n'))
        ].join(' '))
      , f.p(
        [ 'Inner scope shadows outer:'
        , f.pre(example,
          [ 'var a = 0'
          , 'function inner () {'
          , '  var a = 1'
          , '  console.log(a)'
          , '}'
          , ''
          , 'inner() // 1'
          , 'console.log(a) // 0'
          ].join('\n'))
        ].join(' '))
      , f.p(
        [ 'Closure:'
        , f.pre(example,
          [ ''
          , 'function inner () {'
          , '  var a = 0'
          , '  return function () {'
          , '    a += 1'
          , '    console.log(a)'
          , '  }'
          , '}'
          , ''
          , 'var b = inner()'
          , 'b() // 1'
          , 'b() // 2'
          , 'b() // 3'
          ].join('\n'))
        ].join(' '))
      , f.p(
        [ 'If a variable used, but not declared in a scope then'
        , 'it will be looked up in each outer scope until it is'
        , 'found and that one will be used. If it is not found then'
        , 'it will be automatically declared as a global variable.'
        ].join(' '))
      ]
    ) + scripts.map(function (script) {
      return f.script({ src: script })
    }).join('')
}


text:
(function() {

	'use strict';

	angular.module('controllers.login', [
		'ngRoute',
		'services.global',
		'services.auth',
		'services.validate',
		'resources.user'
	]).controller('LoginController', [
		'$scope',
		'$location',
		'$routeParams',
		'GlobalService',
		'AuthService',
		'ValidateService',
		'User',
		function($scope, $location, $routeParams, GlobalService, AuthService, ValidateService, User) {
			$scope.branch = GlobalService.Branch($routeParams.branch, true);
			if (AuthService.isOnline()) {
				if (AuthService.isAdmin()) {
					$location.path('/admin');
				} else {
					$location.path('/'+$scope.branch+'/pedidos');
				}
				return;
			}

			var _reset = function(data, value) {
				for(var key in data) {
					data[key] = value;
				}
			};

			$scope.user = {
				login: {
					email: '',
					password: '',
				},
				register: {
					firstName: '',
					lastName: '',
					phone: '',
					address: '',
					email: '',
					password: '',
					passwordRepeat: ''
				}
			};

			$scope.errors = {
				login: {
					email: false,
					password: false,
				},
				register: {
					firstName: false,
					lastName: false,
					phone: false,
					address: false,
					email: false,
					password: false,
					passwordRepeat: false
				}
			};

			$scope.signIn = function(){
				var i, key, invalidFields;
				_reset($scope.errors.login);
				invalidFields = ValidateService.All($scope.user.login);
				if(!invalidFields.length) {
					AuthService.login($scope.user.login.email, $scope.user.login.password).then(function(user) {
						if(angular.isString(user.id) && user.id.length){
							if (user.isAdmin) {
								$location.path('/admin');
							} else {
								$location.path('/'+$scope.branch+'/pedidos');
							}
						} else {
							$scope.errors.login.email = true;
							$scope.errors.login.password = true;
						}
					}, function () {//In case of error
						$scope.errors.login.email = true;
						$scope.errors.login.password = true;
					});
				} else {
					for (i = 0; i < invalidFields.length; i++) {
						key =invalidFields[i];
						$scope.errors.login[key] = true;
					};
				}
			};

			$scope.signUp = function(){
				var i, key, user, invalidFields;
				_reset($scope.errors.register);
				invalidFields = ValidateService.All($scope.user.register);
				if(!invalidFields.length) {
					user = new User($scope.user.register);
					AuthService.register(user).then(function(newUser) {
						console.log(newUser.id, typeof newUser.id);
						if(angular.isString(newUser.id) && newUser.id.length){
							$location.path('/'+$scope.branch+'/pedidos');
						}  else {
							console.log('show signup error');
						}
					});
				} else {
					for (i = 0; i < invalidFields.length; i++) {
						key =invalidFields[i];
						$scope.errors.register[key] = true;
					};
				}
			};
		}
	]);
})();


text:
/* tslint:disable:max-file-line-count */
import * as assert from 'assert'

import {
  SessionStorage,
  SessionStorageClearCommand,
  SessionStorageCommand,
  SessionStorageRemoveItemCommand,
  SessionStorageSetItemCommand,
  SessionStorageSinks,
  SessionStorageSources,
  clear,
  removeItem,
  setItem,
} from './'
import { async, sync } from 'most-subject'
import { just, never } from 'most'

describe(`SessionStorage`, () => {
  describe(`given SessionStorageSinks`, () => {
    it(`returns SessionStorageSources`, () => {
      const sinks: SessionStorageSinks =
        {
          sessionStorage$: just(clear()),
        }

      const sources: SessionStorageSources = SessionStorage(sinks)

      const { sessionStorage } = sources

      assert.strictEqual(typeof sessionStorage.getItem, 'function')
    })
  })

  describe(`clear`, () => {
    describe(`when called`, () => {
      it(`returns a SessionStorageClearCommand`, () => {
        const clearCommand: SessionStorageClearCommand = clear()

        assert.strictEqual(clearCommand.method, 'clear')
      })
    })

    describe(`when passed to SessionStorage component`, () => {
      before(() => {
        window.sessionStorage.setItem('a', '1')
        window.sessionStorage.setItem('b', '2')
      })

      it(`clears sessionStorage keys and values`, () => {
        const sessionStorage$ = sync<SessionStorageCommand>()

        SessionStorage({ sessionStorage$ })

        sessionStorage$.next(clear())

        assert.strictEqual(window.sessionStorage.length, 0)
      })
    })
  })

  describe(`removeItem`, () => {
    describe(`when given a string representing a key`, () => {
      it(`returns a SessionRemoveItemCommand containing given key`, () => {
        const sinks: SessionStorageSinks =
          {
            sessionStorage$: never(),
          }

        SessionStorage(sinks)

        const command: SessionStorageRemoveItemCommand = removeItem('a')

        assert.strictEqual(command.method, 'removeItem')
        assert.strictEqual(command.key, 'a')

        const command2: SessionStorageRemoveItemCommand = removeItem('b')

        assert.strictEqual(command2.method, 'removeItem')
        assert.strictEqual(command2.key, 'b')
      })
    })

    describe(`when passed to SessionStorage component`, () => {
      before(() => {
        window.sessionStorage.setItem('a', '1')
        window.sessionStorage.setItem('b', '2')
      })

      after(() => {
        window.sessionStorage.clear()
      })

      it(`removes given key:value from sessionStorage`, () => {
        const sessionStorage$ = sync<SessionStorageCommand>()

        const sinks: SessionStorageSinks =
          {
            sessionStorage$,
          }

        SessionStorage(sinks)

        sessionStorage$.next(removeItem(`a`))

        assert.strictEqual(window.sessionStorage.length, 1)
        assert.strictEqual(window.sessionStorage.getItem('a'), null)
      })
    })
  })

  describe('setItem', () => {
    describe(`when given a string representing a key and a string representing value`, () => {
      it(`returns a SessionStorageSetItemCommand`, () => {
        const sinks: SessionStorageSinks =
          {
            sessionStorage$: never(),
          }

        SessionStorage(sinks)

        const command: SessionStorageSetItemCommand = setItem('a', '1')

        assert.strictEqual(command.method, 'setItem')
        assert.strictEqual(command.key, 'a')
        assert.strictEqual(command.value, '1')

        const command2: SessionStorageSetItemCommand = setItem('b', '2')

        assert.strictEqual(command2.method, 'setItem')
        assert.strictEqual(command2.key, 'b')
        assert.strictEqual(command2.value, '2')
      })
    })

    describe(`when passed to SessionStorage component`, () => {
      before(() => {
        window.sessionStorage.clear()
      })

      after(() => {
        window.sessionStorage.clear()
      })

      it(`adds given key:value to sessionStorage`, () => {
        const sessionStorage$ = sync<SessionStorageCommand>()

        const sinks: SessionStorageSinks =
          {
            sessionStorage$,
          }

        SessionStorage(sinks)

        sessionStorage$.next(setItem(`a`, `1`))

        assert.strictEqual(window.sessionStorage.length, 1)
        assert.strictEqual(window.sessionStorage.getItem(`a`), `1`)
      })
    })
  })

  describe(`SessionStorageSource`, () => {
    describe(`getItem`, () => {
      describe(`given a string representing a key`, () => {
        beforeEach(() => {
          window.sessionStorage.clear()
        })

        it(`returns a stream of corresponding values`, () => {
          const sessionStorage$ = async<SessionStorageCommand>()

          const sinks: SessionStorageSinks =
            {
              sessionStorage$,
            }

          const sources: SessionStorageSources = SessionStorage(sinks)

          const { sessionStorage } = sources

          const promise = sessionStorage
            .getItem(`a`)
            .take(2)
            .reduce((a: Array<string>, b: string) => a.concat(b), [])

          sessionStorage$.next(setItem('a', '1'))

          return promise.then((values: Array<string>) => {
            assert.deepEqual(values, [null, `1`])
          })
        })

        it(`returns a stream of updated values`, (done) => {
          const sessionStorage$ = async<SessionStorageCommand>()

          const sinks: SessionStorageSinks =
            {
              sessionStorage$,
            }

          const sources: SessionStorageSources = SessionStorage(sinks)

          const { sessionStorage } = sources

          const a$ = sessionStorage
            .getItem(`a`)
            .take(4)

          const expected = [null, `1`, `2`, `3`]

          a$.observe((value) => {
            assert.strictEqual(value, expected.shift())

            if (expected.length === 0)
              done()
          })

          sessionStorage$.next(setItem(`a`, `1`))
          sessionStorage$.next(setItem(`a`, `2`))
          sessionStorage$.next(setItem(`a`, `3`))
        })
      })
    })

    describe('length', () => {
      describe(`when called`, () => {
        beforeEach(() => {
          window.sessionStorage.clear()
        })

        it(`returns a stream of sessionStorage length`, () => {
          const sessionStorage$ = async<SessionStorageCommand>()

          const sinks: SessionStorageSinks =
            {
              sessionStorage$,
            }

          const sources: SessionStorageSources = SessionStorage(sinks)

          const { sessionStorage } = sources

          const promise = sessionStorage
            .length()
            .take(4)
            .reduce((a: Array<number>, b: number) => a.concat(b), [])

          sessionStorage$.next(setItem('a', '1'))
          sessionStorage$.next(setItem(`b`, `2`))
          sessionStorage$.next(removeItem(`a`))

          return promise.then((values: Array<number>) => {
            assert.deepEqual(values, [0, 1, 2, 1])
          })
        })
      })
    })
  })
})


text:
#include <linux/export.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/errno.h>
#include <linux/spinlock.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <video/imx-ipu-v3.h>

#include "ipu-prv.h"

struct ipu_smfc {
	struct ipu_smfc_priv *priv;
	int chno;
	bool inuse;
};

struct ipu_smfc_priv {
	void __iomem *base;
	spinlock_t lock;
	struct ipu_soc *ipu;
	struct ipu_smfc channel[4];
	int use_count;
};

/*SMFC Registers */
#define SMFC_MAP	0x0000
#define SMFC_WMC	0x0004
#define SMFC_BS		0x0008

int ipu_smfc_set_burstsize(struct ipu_smfc *smfc, int burstsize)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;
	u32 val, shift;

	spin_lock_irqsave(&priv->lock, flags);

	shift = smfc->chno * 4;
	val = readl(priv->base + SMFC_BS);
	val &= ~(0xf << shift);
	val |= burstsize << shift;
	writel(val, priv->base + SMFC_BS);

	spin_unlock_irqrestore(&priv->lock, flags);

	return 0;
}
EXPORT_SYMBOL_GPL(ipu_smfc_set_burstsize);

int ipu_smfc_map_channel(struct ipu_smfc *smfc, int csi_id, int mipi_id)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;
	u32 val, shift;

	spin_lock_irqsave(&priv->lock, flags);

	shift = smfc->chno * 3;
	val = readl(priv->base + SMFC_MAP);
	val &= ~(0x7 << shift);
	val |= ((csi_id << 2) | mipi_id) << shift;
	writel(val, priv->base + SMFC_MAP);

	spin_unlock_irqrestore(&priv->lock, flags);

	return 0;
}
EXPORT_SYMBOL_GPL(ipu_smfc_map_channel);

int ipu_smfc_set_watermark(struct ipu_smfc *smfc, u32 set_level, u32 clr_level)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;
	u32 val, shift;

	spin_lock_irqsave(&priv->lock, flags);

	shift = smfc->chno * 6 + (smfc->chno > 1 ? 4 : 0);
	val = readl(priv->base + SMFC_WMC);
	val &= ~(0x3f << shift);
	val |= ((clr_level << 3) | set_level) << shift;
	writel(val, priv->base + SMFC_WMC);

	spin_unlock_irqrestore(&priv->lock, flags);

	return 0;
}
EXPORT_SYMBOL_GPL(ipu_smfc_set_watermark);

int ipu_smfc_enable(struct ipu_smfc *smfc)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;

	spin_lock_irqsave(&priv->lock, flags);

	if (!priv->use_count)
		ipu_module_enable(priv->ipu, IPU_CONF_SMFC_EN);

	priv->use_count++;

	spin_unlock_irqrestore(&priv->lock, flags);

	return 0;
}
EXPORT_SYMBOL_GPL(ipu_smfc_enable);

int ipu_smfc_disable(struct ipu_smfc *smfc)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;

	spin_lock_irqsave(&priv->lock, flags);

	priv->use_count--;

	if (!priv->use_count)
		ipu_module_disable(priv->ipu, IPU_CONF_SMFC_EN);

	if (priv->use_count < 0)
		priv->use_count = 0;

	spin_unlock_irqrestore(&priv->lock, flags);

	return 0;
}
EXPORT_SYMBOL_GPL(ipu_smfc_disable);

struct ipu_smfc *ipu_smfc_get(struct ipu_soc *ipu, unsigned int chno)
{
	struct ipu_smfc_priv *priv = ipu->smfc_priv;
	struct ipu_smfc *smfc, *ret;
	unsigned long flags;

	if (chno >= 4)
		return ERR_PTR(-EINVAL);

	smfc = &priv->channel[chno];
	ret = smfc;

	spin_lock_irqsave(&priv->lock, flags);

	if (smfc->inuse) {
		ret = ERR_PTR(-EBUSY);
		goto unlock;
	}

	smfc->inuse = true;
unlock:
	spin_unlock_irqrestore(&priv->lock, flags);
	return ret;
}
EXPORT_SYMBOL_GPL(ipu_smfc_get);

void ipu_smfc_put(struct ipu_smfc *smfc)
{
	struct ipu_smfc_priv *priv = smfc->priv;
	unsigned long flags;

	spin_lock_irqsave(&priv->lock, flags);
	smfc->inuse = false;
	spin_unlock_irqrestore(&priv->lock, flags);
}
EXPORT_SYMBOL_GPL(ipu_smfc_put);

int ipu_smfc_init(struct ipu_soc *ipu, struct device *dev,
		  unsigned long base)
{
	struct ipu_smfc_priv *priv;
	int i;

	priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
	if (!priv)
		return -ENOMEM;

	ipu->smfc_priv = priv;
	spin_lock_init(&priv->lock);
	priv->ipu = ipu;

	priv->base = devm_ioremap(dev, base, PAGE_SIZE);
	if (!priv->base)
		return -ENOMEM;

	for (i = 0; i < 4; i++) {
		priv->channel[i].priv = priv;
		priv->channel[i].chno = i;
	}

	pr_debug("%s: ioremap 0x%08lx -> %p\n", __func__, base, priv->base);

	return 0;
}

void ipu_smfc_exit(struct ipu_soc *ipu)
{
}


text:
<?php

namespace app\models;

use Yii;
use app\components\EnglishBehavior;

/**
 * This is the model class for table "dominant".
 *
 * @property integer $id
 * @property string $name
 * @property string $name_eng
 *
 * @property Main[] $mains
 */
class Dominant extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dominant';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            EnglishBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'name_eng'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'name_eng' => 'Name Eng',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMains()
    {
        return $this->hasMany(Main::className(), ['dominant' => 'id']);
    }
}


text:
Rails.application.routes.draw do
  # Resources for testing
  resources :users, :only => [:index] do
    get :expire, :on => :member
    get :accept, :on => :member

    authenticate do
      post :exhibit, :on => :member
    end
  end

  resources :admins, :only => [:index] do
    get :expire, :on => :member
  end

  # Users scope
  devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }

  as :user do
    match "/as/sign_in", :to => "devise/sessions#new"
  end

  match "/sign_in", :to => "devise/sessions#new"

  # Admin scope
  devise_for :admin, :path => "admin_area", :controllers => { :sessions => :"admins/sessions" }, :skip => :passwords

  match "/admin_area/home", :to => "admins#index", :as => :admin_root
  match "/anywhere", :to => "foo#bar", :as => :new_admin_password

  authenticate(:admin) do
    match "/private", :to => "home#private", :as => :private
  end

  authenticate(:admin, lambda { |admin| admin.active? }) do
    match "/private/active", :to => "home#private", :as => :private_active
  end

  authenticated :admin do
    match "/dashboard", :to => "home#admin_dashboard"
  end

  authenticated :admin, lambda { |admin| admin.active? } do
    match "/dashboard/active", :to => "home#admin_dashboard"
  end

  authenticated do
    match "/dashboard", :to => "home#user_dashboard"
  end

  unauthenticated do
    match "/join", :to => "home#join"
  end

  # Routes for constraints testing
  devise_for :headquarters_admin, :class_name => "Admin", :path => "headquarters", :constraints => {:host => /192\.168\.1\.\d\d\d/}

  constraints(:host => /192\.168\.1\.\d\d\d/) do
    devise_for :homebase_admin, :class_name => "Admin", :path => "homebase"
  end

  devise_for :skip_admin, :class_name => "Admin", :skip => :all

  # Routes for format=false testing
  devise_for :htmlonly_admin, :class_name => "Admin", :skip => [:confirmations, :unlocks], :path => "htmlonly_admin", :format => false, :skip_helpers => [:confirmations, :unlocks]
  devise_for :htmlonly_users, :class_name => "User", :only => [:confirmations, :unlocks], :path => "htmlonly_users", :format => false, :skip_helpers => true

  # Other routes for routing_test.rb
  devise_for :reader, :class_name => "User", :only => :passwords

  scope :host => "sub.example.com" do
    devise_for :sub_admin, :class_name => "Admin"
  end

  namespace :publisher, :path_names => { :sign_in => "i_dont_care", :sign_out => "get_out" } do
    devise_for :accounts, :class_name => "Admin", :path_names => { :sign_in => "get_in" }
  end

  scope ":locale", :module => :invalid do
    devise_for :accounts, :singular => "manager", :class_name => "Admin",
      :path_names => {
        :sign_in => "login", :sign_out => "logout",
        :password => "secret", :confirmation => "verification",
        :unlock => "unblock", :sign_up => "register",
        :registration => "management", :cancel => "giveup"
      }, :failure_app => lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, :module => :devise
  end

  namespace :sign_out_via, :module => "devise" do
    devise_for :deletes, :sign_out_via => :delete, :class_name => "Admin"
    devise_for :posts, :sign_out_via => :post, :class_name => "Admin"
    devise_for :delete_or_posts, :sign_out_via => [:delete, :post], :class_name => "Admin"
  end

  match "/set", :to => "home#set"
  match "/unauthenticated", :to => "home#unauthenticated"
  match "/custom_strategy/new"

  root :to => "home#index"
end


text:
Gomory::Gomory(const rapidjson::Value& root, std::string model_path_,
               std::string solution_path_) : BaseModel(root, model_path_,
                                                       solution_path_) {
	// Load required user-defined parameters.
	max_cuts = root["maxCuts"].GetInt();
	away_epsilon = root["awayEpsilon"].GetDouble();
	purge_epsilon = root["purgeEpsilon"].GetDouble();
	use_lex = root["useLexicographic"].GetBool();
	use_rounds = root["useRounds"].GetBool();
	use_fgmi = root["useMixedCut"].GetBool();
	use_purging = root["usePurging"].GetBool();

	// Set up the Gurobi environment variable.
	grb_error = GRBloadenv(&env, "gurobi.log");

	// Ensure Gurobi behaves only as a very accurate linear programming solver.
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_BARCONVTOL, 0.0);
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_FEASIBILITYTOL, 1.0e-9);
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_HEURISTICS, 0.0);
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_MARKOWITZTOL, 0.999);
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_NODELIMIT, 0.0);
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_OPTIMALITYTOL, 1.0e-9);
	grb_error = GRBsetintparam(env, GRB_INT_PAR_CUTS, 0);
	grb_error = GRBsetintparam(env, GRB_INT_PAR_PRESOLVE, 0);
	grb_error = GRBsetintparam(env, GRB_INT_PAR_QUAD, 1);

	// Turn off Gurobi shell output.
	grb_error = GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);

	// Set the timeout option.
	grb_error = GRBsetdblparam(env, GRB_DBL_PAR_TIMELIMIT, 60.0);

	// Read in the mixed-integer model.
	grb_error = GRBreadmodel(env, model_path.c_str(), &model);

	// Convert the read-in model to a linear program.
	SetupModel();
}

void Gomory::Optimize(void) {
	grb_error = GRBoptimize(model);

	int model_status;
	grb_error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &model_status);

	// If the model timed out, exit.
	if (model_status != 2) {
		std::cout << INT_MAX << "," << INT_MAX << "," << INT_MAX << "," << INT_MAX << std::endl;
		std::exit(0);
	}
}

template <typename T> int sgn(T val) {
	return (T(0) < val) - (val < T(0));
}

void Gomory::LexSimplex(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);

	double sol_j;
	grb_error = GRBgetdblattrelement(model, "X", 0, &sol_j);

	int id[1] = {0};
	double vid[1] = {1.0};

	grb_error = GRBaddconstr(model, 1, id, vid, GRB_GREATER_EQUAL, sol_j - 1.0e-8, NULL);
	grb_error = GRBaddconstr(model, 1, id, vid, GRB_LESS_EQUAL, sol_j + 1.0e-8, NULL);

	del_lex_constr_ids[0] = num_constrs;
	del_lex_constr_ids[1] = num_constrs + 1;

	for (int j = 1; j < num_vars; j++) {
		for (int k = 0; k < num_vars; k++) {
			if (k < j) {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 0.0);
			} else {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, original_obj_coeffs[k]);
			}
		}

		Optimize();

		int id[1] = {j};
		double vid[1] = {1.0};

		grb_error = GRBgetdblattrelement(model, "X", j, &sol_j);
		grb_error = GRBaddconstr(model, 1, id, vid, GRB_GREATER_EQUAL, sol_j - 1.0e-8, NULL);
		grb_error = GRBaddconstr(model, 1, id, vid, GRB_LESS_EQUAL, sol_j + 1.0e-8, NULL);

		del_lex_constr_ids[2*j+0] = num_constrs + 2*j + 0;
		del_lex_constr_ids[2*j+1] = num_constrs + 2*j + 1;
	}

	Optimize();

	// Restore the objective to that of the original problem.
	grb_error = GRBdelconstrs(model, 2*num_vars, del_lex_constr_ids);

	for (int j = 0; j < num_vars; j++) {
		grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, j, original_obj_coeffs[j]);
	}

	Optimize();
}

void Gomory::SetupModel(void) {
	// Get important information about the original model.
	grb_error = GRBgetintattr(model, "NumVars", &num_vars);
	grb_error = GRBgetintattr(model, "NumIntVars", &num_int_vars);
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
	original_num_constrs = num_constrs;

	// Allocate arrays to store integer variable ids and values.
	int_var_ids = (int*)malloc(num_int_vars*sizeof(int));
	int_var_vals = (double*)malloc(num_int_vars*sizeof(double));

	// Allocate arrays to store cut coefficient data.
	cut_coeff_ids = (int*)malloc(num_vars*sizeof(int));
	cut_coeff_vals = (double*)malloc(num_vars*sizeof(double));

	// Allocate arrays to be used with the lexicographic method.
	del_lex_constr_ids = (int*)malloc(2*num_vars*sizeof(int));
	original_obj_coeffs = (double*)malloc(num_vars*sizeof(double));

	// If a variable is not continuous, make it continuous.
	for (int j = 0, k = 0; j < num_vars; j++) {
		cut_coeff_ids[j] = j;

		char variable_type;
		grb_error = GRBgetcharattrelement(model, GRB_CHAR_ATTR_VTYPE, j, &variable_type);

		if (variable_type != GRB_CONTINUOUS) {
			grb_error = GRBsetcharattrelement(model, GRB_CHAR_ATTR_VTYPE, j, GRB_CONTINUOUS);
			int_var_ids[k++] = j;
		}
	}

	grb_error = GRBgetdblattrlist(model, GRB_DBL_ATTR_OBJ, num_vars,
	                              cut_coeff_ids, original_obj_coeffs);

	// Correctly size the matrices and vectors required for cuts.
	basis_size = num_vars;
	B.resize(basis_size, basis_size);
	B_inv.resize(basis_size, basis_size);
	r.resize(basis_size);
	c_beta.resize(basis_size);
	a_beta_r.resize(basis_size);

	// Set the total number of cuts used thus far to zero.
	num_cuts = 0;
}

int Gomory::UpdateVariableData(void) {
	grb_error = GRBgetdblattrlist(model, "X", num_int_vars, int_var_ids, int_var_vals);

	for (int k = 0; k < num_int_vars; k++) {
		if (fabs(int_var_vals[k] - round(int_var_vals[k])) >= away_epsilon) {
			// Add the variable to the set if it's fractional.
			frac_int_vars.insert(int_var_ids[k]);
		} else {
			// Remove the variable from the set if it's integer.
			frac_int_vars.erase(int_var_ids[k]);
		}
	}

	// Return the number of fractional variables.
	return (int)frac_int_vars.size();
}

void Gomory::UpdateBasisData(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);

	for (int i = 0, basis_count = 0; i < num_constrs; i++) {
		if (basis_count < basis_size) {
			int cbasis;
			grb_error = GRBgetintattrelement(model, GRB_INT_ATTR_CBASIS, i, &cbasis);

			if (cbasis == -1) {
				for (int j = 0; j < basis_size; j++) {
					double tmp_a_val;
					grb_error = GRBgetcoeff(model, i, j, &tmp_a_val);
					B(j, basis_count) = tmp_a_val;
				}

				double tmp_c_val;
				grb_error = GRBgetdblattrelement(model, GRB_DBL_ATTR_RHS, i, &tmp_c_val);
				c_beta(basis_count) = tmp_c_val;
				basis_count++;
			}
		} else {
			break;
		}
	}

	// Get the basis inverse.
	B_inv = B.inverse();
}

int Gomory::AddPureCut(int cut_var_index) {
	if (use_lex) {
		LexSimplex();
		UpdateBasisData();
	}

	// Compute r.
	for (int i = 0; i < basis_size; i++) {
		r(i) = -floor(B_inv(i, cut_var_index));
	}

	// Compute constants for the cut.
	double c_beta_r = c_beta.transpose() * r;
	a_beta_r = B * r;

	for (int i = 0; i < num_vars; i++) {
		cut_coeff_vals[i] = round(a_beta_r(i));
	}

	cut_coeff_vals[cut_var_index] += 1.0;

	double y_bar_i;
	grb_error = GRBgetdblattrelement(model, "X", cut_var_index, &y_bar_i);
	double rhs = c_beta_r + floor(y_bar_i);
	grb_error = GRBaddconstr(model, num_vars, cut_coeff_ids, cut_coeff_vals,
	                         GRB_LESS_EQUAL, round(rhs), NULL);

	if (use_lex) {
		Optimize();
	}

	// Return number of generated cuts.
	return 1;
}

int Gomory::AddMixedCut(int cut_var_index) {
	if (use_lex) {
		LexSimplex();
		UpdateBasisData();
	}

	for (int i = 0; i < basis_size; i++) {
		r(i) = fmax(0.0, -floor(B_inv(i, cut_var_index)));
	}

	double c_beta_r = c_beta.transpose() * r;
	a_beta_r = B * r;

	double y_bar_i;
	grb_error = GRBgetdblattrelement(model, "X", cut_var_index, &y_bar_i);

	for (int i = 0; i < num_vars; i++) {
		cut_coeff_vals[i] = a_beta_r(i);

		if (i == cut_var_index) {
			cut_coeff_vals[i] -= (y_bar_i - floor(y_bar_i) - 1.0);
		}
	}

	double rhs = -((y_bar_i - floor(y_bar_i) - 1.0) * floor(y_bar_i) - c_beta_r);
	grb_error = GRBaddconstr(model, num_vars, cut_coeff_ids, cut_coeff_vals,
	                         GRB_LESS_EQUAL, rhs, NULL);

	if (use_lex) {
		Optimize();
	}

	// Return the number of cuts generated.
	return 1;
}

int Gomory::AddPureRounds(void) {
	std::set<int>::iterator it;

	for (it = frac_int_vars.begin(); it != frac_int_vars.end(); ++it) {
		AddPureCut(*it);
	}

	return frac_int_vars.size();
}

int Gomory::AddMixedRounds(void) {
	std::set<int>::iterator it;

	for (it = frac_int_vars.begin(); it != frac_int_vars.end(); ++it) {
		AddMixedCut(*it);
	}

	return frac_int_vars.size();
}

int Gomory::GetLexIndex(void) {
	return *frac_int_vars.begin();
}

int Gomory::GetRandomIndex(void) {
	int set_index = rand() % frac_int_vars.size();

	std::set<int>::const_iterator it = frac_int_vars.begin();
	if (set_index != 0) {
		advance(it, set_index - 1);
	}

	return *it;
}

int Gomory::PurgeCuts(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
	std::vector<int> purge_cut_ids;

	for (int i = original_num_constrs; i < num_constrs; i++) {
		double constraint_slack;
		grb_error = GRBgetdblattrelement(model, "Slack", i, &constraint_slack);

		if (fabs(constraint_slack) > purge_epsilon) {
			purge_cut_ids.push_back(i);
		}
	}

	grb_error = GRBdelconstrs(model, (int)purge_cut_ids.size(), purge_cut_ids.data());
	Optimize();

	return purge_cut_ids.size();
}

void Gomory::PrintStep(void) {
	static bool started_print = false;
	if (started_print == false) {
		started_print = true;
		std::cout << "ncuts,nconstrs,det,obj" << std::endl;
	}

	double current_obj;
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &current_obj);
	std::cout << num_cuts << "," << num_constrs << "," << B.determinant()
	          << "," << current_obj << std::endl;
}

int Gomory::Step(void) {
	if (objective_value != old_objective_value && use_purging) {
		PurgeCuts();
		old_objective_value = objective_value;
	}

	UpdateBasisData();

	if (num_vars == num_int_vars) {
		if (use_rounds) {
			num_cuts += use_fgmi ? AddMixedRounds() : AddPureRounds();
		} else {
			int cut_var_id = use_lex ? GetLexIndex() : GetRandomIndex();
			num_cuts += use_fgmi ? AddMixedCut(cut_var_id) : AddPureCut(cut_var_id);
		}
	} else {
		if (use_rounds) {
			num_cuts += AddMixedRounds();
		} else {
			int cut_var_id = use_lex ? GetLexIndex() : GetRandomIndex();
			num_cuts += AddMixedCut(cut_var_id);
		}
	}

	Optimize();
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);

	return UpdateVariableData();
}

void Gomory::Run(void) {
	Optimize();
	int num_frac_vars = UpdateVariableData();
	UpdateBasisData();
	PrintStep();

	while (num_frac_vars > 0 && num_cuts < max_cuts) {
		num_frac_vars = Step();
		PrintStep();
	}

	grb_error = GRBwrite(model, solution_path.c_str());
}

Gomory::~Gomory(void) {
	free(cut_coeff_vals);
	free(cut_coeff_ids);
	free(int_var_vals);
	free(int_var_ids);
	free(del_lex_constr_ids);
	free(original_obj_coeffs);
}


text:
/* @flow */
import Blockchain from './Blockchain';

export default Blockchain;


text:
package org.datavec.api.records.reader.impl.misc;

import org.datavec.api.records.reader.impl.FileRecordReader;
import org.datavec.api.writable.DoubleWritable;
import org.datavec.api.writable.Writable;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MatlabRecordReader extends FileRecordReader {

    private List<List<Writable>> records = new ArrayList<>();
    private Iterator<List<Writable>> currIter;

    @Override
    public boolean hasNext() {
        return super.hasNext();
    }

    @Override
    public List<Writable> next() {
        //use the current iterator
        if (currIter != null && currIter.hasNext())
            return new ArrayList<>(currIter.next());
        records.clear();
        //next file
        List<Writable> next = super.next();
        String val = next.iterator().next().toString();
        StringReader reader = new StringReader(val);
        int c;
        char chr;
        StringBuilder fileContent;
        boolean isComment;

        List<Writable> currRecord = new ArrayList<>();
        fileContent = new StringBuilder();
        isComment = false;
        records.add(currRecord);
        try {
            // determine number of attributes
            while ((c = reader.read()) != -1) {
                chr = (char) c;

                // comment found?
                if (chr == '%')
                    isComment = true;

                // end of line reached
                if ((chr == '\n') || (chr == '\r')) {
                    isComment = false;
                    if (fileContent.length() > 0)
                        currRecord.add(new DoubleWritable(new Double(fileContent.toString())));

                    if (currRecord.size() > 0) {
                        currRecord = new ArrayList<>();
                        records.add(currRecord);
                    }
                    fileContent = new StringBuilder();
                    continue;
                }

                // skip till end of comment line
                if (isComment)
                    continue;

                // separator found?
                if ((chr == '\t') || (chr == ' ')) {
                    if (fileContent.length() > 0) {
                        currRecord.add(new DoubleWritable(new Double(fileContent.toString())));
                        fileContent = new StringBuilder();
                    }
                } else {
                    fileContent.append(chr);
                }
            }

            // last number?
            if (fileContent.length() > 0)
                currRecord.add(new DoubleWritable(new Double(fileContent.toString())));

            currIter = records.iterator();

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new IllegalStateException("Unable to determine structure as Matlab ASCII file: " + ex);
        }
        throw new IllegalStateException("Strange state detected");
    }

    @Override
    public List<Writable> record(URI uri, DataInputStream dataInputStream) throws IOException {
        throw new UnsupportedOperationException("Reading Matlab data from DataInputStream: not yet implemented");
    }
}


text:
<?php

defined('_JEXEC') or die;

if (!class_exists('PlgSystemRegularLabsInstallerScript'))
{
	require_once __DIR__ . '/script.install.helper.php';

	class PlgSystemRegularLabsInstallerScript extends PlgSystemRegularLabsInstallerScriptHelper
	{
		public $name           = 'REGULAR_LABS_LIBRARY';
		public $alias          = 'regularlabs';
		public $extension_type = 'plugin';
		public $show_message   = false;

		public function onBeforeInstall($route)
		{
			if (!$this->isNewer())
			{
				return false;
			}

			return true;
		}

		public function onAfterInstall($route)
		{
			if ($route != 'update')
			{
				return;
			}

			$this->deleteOldFiles();
		}

		public function uninstall($adapter)
		{
			$this->deleteLibrary();
		}

		private function deleteLibrary()
		{
			$this->delete(
				[
					JPATH_LIBRARIES . '/regularlabs',
				]
			);
		}

		private function deleteOldFiles()
		{
			$this->delete(
				[
					JPATH_PLUGINS . '/system/regularlabs/helpers',
				]
			);
		}

		private function deleteOldLibraryFiles()
		{
			$this->delete(
				[
					JPATH_LIBRARIES . '/regularlabs/helpers/assignments',
					JPATH_LIBRARIES . '/regularlabs/helpers/assignment.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/assignments.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/cache.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/field.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/functions.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/groupfield.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/helper.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/html.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/htmlfix.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/licenses.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/mobile_detect.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/parameters.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/protect.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/string.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/tags.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/text.php',
					JPATH_LIBRARIES . '/regularlabs/helpers/version.php',
				]
			);
		}
	}
}


text:
A valid parentheses string is either empty `(""), "(" + A + ")", or A + B`, where A and B are valid parentheses strings, and + represents string concatenation.  For example, `"", "()", "(())()", and "(()(()))"` are all valid parentheses strings.

A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into `S = A+B`, with A and B nonempty valid parentheses strings.

Given a valid parentheses string S, consider its primitive decomposition: `S = P_1 + P_2 + ... + P_k`, where `P_i` are primitive valid parentheses strings.

Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.

### Example 1:
```
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
```

### Example 2:
```
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
```

### Example 3:
```
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
```

### Note:
1. S.length <= 10000
2. S[i] is "(" or ")"
3. S is a valid parentheses string

## Solution
Instead of using stack to match open and close parentheses then check stack size 0 for primitive string, primitive string will have equal number of opened and closed parenthesis.

#GOOGL

#Stack


text:
class AddStatusToPaymentProvider < ActiveRecord::Migration
  def change
    add_column :invoicing_engine_payment_providers, :status, :text
  end
end


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

<title>L-Index</title>
<meta name="date" content="2013-08-04">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C E G I K L O R S V W

L

loadAdbKeyPair(AdbBase64, File, File) - Static method in class com.cgutman.adblib.AdbCrypto

Creates a new AdbCrypto object from a key pair loaded from files.

A C E G I K L O R S V W

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
using LANSearch.Data.Search.Solr;
using LANSearch.Data.Search.Solr.Filters;
using LANSearch.Models.Search;
using Mizore.CommunicationHandler.RequestHandler;
using Mizore.CommunicationHandler.ResponseHandler;
using Mizore.DataMappingHandler.Reflection;
using Mizore.SolrServerHandler;
using Nancy;
using System;
using System.Collections.Generic;

namespace LANSearch.Data.Search
{
    public class SearchManager
    {
        public SearchManager(AppConfig config)
        {
            SolrServer = new HttpSolrServer(config.SearchServerUrl);
            SolrMapper = new ReflectionDataMapper<File>();
        }

        public List<IFilter> GetFilters()
        {
            return new List<IFilter> { new Solr.Filters.Server(), new Extension(), new Size() };
        }

        public ISolrServerHandler SolrServer { get; protected set; }

        public ReflectionDataMapper<File> SolrMapper { get; protected set; }

        public SearchModel Search(Request request)
        {
            var query = new SolrHandler(request);
            return query.SolrSearch();
        }

        public void UnindexServer(int id)
        {
            if (id <= 0) return;
            var solrRequest = new UpdateRequest(SolrServer.GetUriBuilder());
            solrRequest.DeleteByQuery(string.Format("server:{0}", id));
            SolrServer.Request<UpdateResponse>(solrRequest);
        }

        public SearchModel SearchByQuery(string query, DateTime lastExecution)
        {
            if (string.IsNullOrWhiteSpace(query)) return null;

            var handler = new SolrHandler(query, lastExecution);
            return handler.SolrSearch();
        }
    }
}


text:
/**
 * This program and the accompanying materials
 * are made available under the terms of the License
 * which accompanies this distribution in the file LICENSE.txt
 */
package com.archimatetool.jasperreports.commandline;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.osgi.util.NLS;

import com.archimatetool.commandline.AbstractCommandLineProvider;
import com.archimatetool.commandline.CommandLineState;
import com.archimatetool.editor.utils.StringUtils;
import com.archimatetool.jasperreports.JasperReportsExporter;
import com.archimatetool.jasperreports.JasperReportsPlugin;
import com.archimatetool.model.IArchimateModel;

/**
 * Command Line interface for Jasper Reports
 *
 * Typical usage - (should be all on one line):
 *
 * Archi -consoleLog -nosplash -application com.archimatetool.commandline.app
   --loadModel "/pathToModel/model.archimate"
   --jasper.createReport "pathToFolder"
   --jasper.filename "filename"
   --jasper.title "title"
   --jasper.format "html,rtf"
 *
 * @author Phillip Beauvoir
 */
public class JasperReportsProvider extends AbstractCommandLineProvider {

    static final String PREFIX = Messages.JasperReportsProvider_0;

    static final String OPTION_JASPER_CREATE_REPORT = "jasper.createReport"; //$NON-NLS-1$
    static final String OPTION_JASPER_FILENAME = "jasper.filename"; //$NON-NLS-1$
    static final String OPTION_JASPER_TITLE = "jasper.title"; //$NON-NLS-1$
    static final String OPTION_JASPER_TEMPLATE = "jasper.template"; //$NON-NLS-1$
    static final String OPTION_JASPER_LOCALE = "jasper.locale"; //$NON-NLS-1$
    static final String OPTION_JASPER_FORMAT = "jasper.format"; //$NON-NLS-1$

    public JasperReportsProvider() {
    }

    @Override
    public void run(CommandLine commandLine) throws Exception {
        if(!hasCorrectOptions(commandLine)) {
            return;
        }

        IArchimateModel model = CommandLineState.getModel();

        if(model == null) {
            throw new IOException(Messages.JasperReportsProvider_1);
        }

        // Folder
        String path = commandLine.getOptionValue(OPTION_JASPER_CREATE_REPORT);
        if(!StringUtils.isSet(path)) {
            logError(Messages.JasperReportsProvider_2);
            return;
        }

        File folderOutput = new File(path);
        folderOutput.mkdirs();
        if(!folderOutput.exists()) {
            logError(NLS.bind(Messages.JasperReportsProvider_3, folderOutput.getPath()));
            return;
        }

        // Filename
        String filename = commandLine.getOptionValue(OPTION_JASPER_FILENAME);
        if(!StringUtils.isSet(filename)) {
            logError(Messages.JasperReportsProvider_4);
            return;
        }

        // Template file
        File templateFile = new File(JasperReportsPlugin.INSTANCE.getJasperReportsFolder(), Messages.JasperReportsProvider_20 + "/main.jrxml"); //$NON-NLS-1$
        String template = commandLine.getOptionValue(OPTION_JASPER_TEMPLATE);
        if(StringUtils.isSet(template)) {
            templateFile = new File(template);
            if(!templateFile.exists()) {
                logError(NLS.bind(Messages.JasperReportsProvider_5, templateFile.getPath()));
                return;
            }
        }

        // Title
        String title = commandLine.getOptionValue(OPTION_JASPER_TITLE);
        if(!StringUtils.isSet(title)) {
            logError(Messages.JasperReportsProvider_6);
            return;
        }

        // Locale
        Locale locale = null;
        String loc = commandLine.getOptionValue(OPTION_JASPER_LOCALE);
        if(StringUtils.isSet(loc)) {
            locale = Locale.forLanguageTag(loc.replace('_', '-'));
        }

        // Export options
        int exportOptions = 0;

        String format = commandLine.getOptionValue(OPTION_JASPER_FORMAT);
        if(StringUtils.isSet(format)) {
            format = format.toLowerCase();

            exportOptions |= format.contains("pdf") ? JasperReportsExporter.EXPORT_PDF : 0; //$NON-NLS-1$
            exportOptions |= format.contains("html") ? JasperReportsExporter.EXPORT_HTML : 0; //$NON-NLS-1$
            exportOptions |= format.contains("rtf") ? JasperReportsExporter.EXPORT_RTF : 0; //$NON-NLS-1$
            exportOptions |= format.contains("ppt") ? JasperReportsExporter.EXPORT_PPT : 0; //$NON-NLS-1$
            exportOptions |= format.contains("odt") ? JasperReportsExporter.EXPORT_ODT : 0; //$NON-NLS-1$
            exportOptions |= format.contains("docx") ? JasperReportsExporter.EXPORT_DOCX : 0; //$NON-NLS-1$
        }

        if(exportOptions == 0) {
            exportOptions = JasperReportsExporter.EXPORT_PDF;
        }

        logMessage(NLS.bind(Messages.JasperReportsProvider_7, model.getName(), folderOutput.getPath()));

        JasperReportsExporter exporter = new JasperReportsExporter(model, folderOutput, filename, templateFile, title, locale, exportOptions);

        exporter.export(new NullProgressMonitor() {
            @Override
            public void subTask(String name) {
                logMessage(name);
            }
        });

        logMessage(Messages.JasperReportsProvider_8);
    }

    @Override
    protected String getLogPrefix() {
        return PREFIX;
    }

    @Override
    public Options getOptions() {
        Options options = new Options();

        Option option = Option.builder()
                .longOpt(OPTION_JASPER_CREATE_REPORT)
                .hasArg()
                .argName(Messages.JasperReportsProvider_9)
                .desc(Messages.JasperReportsProvider_10)
                .build();
        options.addOption(option);

        option = Option.builder()
                .longOpt(OPTION_JASPER_FILENAME)
                .hasArg()
                .argName(Messages.JasperReportsProvider_11)
                .desc(Messages.JasperReportsProvider_12)
                .build();
        options.addOption(option);

        option = Option.builder()
                .longOpt(OPTION_JASPER_TITLE)
                .hasArg()
                .argName(Messages.JasperReportsProvider_13)
                .desc(Messages.JasperReportsProvider_14)
                .build();
        options.addOption(option);

        option = Option.builder()
                .longOpt(OPTION_JASPER_TEMPLATE)
                .hasArg()
                .argName("main.jrxml") //$NON-NLS-1$
                .desc(Messages.JasperReportsProvider_15)
                .build();
        options.addOption(option);

        option = Option.builder()
                .longOpt(OPTION_JASPER_LOCALE)
                .hasArg()
                .argName(Messages.JasperReportsProvider_16)
                .desc(Messages.JasperReportsProvider_17)
                .build();
        options.addOption(option);

        option = Option.builder()
                .longOpt(OPTION_JASPER_FORMAT)
                .hasArg()
                .argName(Messages.JasperReportsProvider_18)
                .desc(Messages.JasperReportsProvider_19)
                .build();
        options.addOption(option);

        return options;
    }

    private boolean hasCorrectOptions(CommandLine commandLine) {
        return commandLine.hasOption(OPTION_JASPER_CREATE_REPORT);
    }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('pfss', '0041_auto_20150602_1813'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='creaturegroup',
            options={'ordering': ['Grouping', 'name']},
        ),
        migrations.AlterField(
            model_name='creaturegroup',
            name='Grouping',
            field=models.ForeignKey(default=3, to='pfss.Grouping'),
            preserve_default=False,
        ),
    ]


text:
class AddSlugToHackathons < ActiveRecord::Migration
  def change
    add_column :hackathons, :slug, :string
    add_index :hackathons, :slug, unique: true
  end
end


text:
using System;
using System.IO;

namespace IgorSoft.PowerShellCloudProvider.Interface.IO
{
    [System.Diagnostics.DebuggerDisplay("{DebuggerDisplay,nq}")]
    public class DirectoryInfoContract : FileSystemInfoContract
    {
        public new DirectoryId Id => (DirectoryId)base.Id;

        public DirectoryInfoContract Parent { get; internal set; }

        public override string FullName => (Parent?.FullName ?? string.Empty) + Name + Path.DirectorySeparatorChar;

        public override string Mode => "d----";

        public DirectoryInfoContract(string id, string name, DateTimeOffset created, DateTimeOffset updated) : base(new DirectoryId(id), name, created, updated)
        {
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Debugger Display")]
        [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
        private string DebuggerDisplay => $"{nameof(DirectoryInfoContract)} {Id} ({Name})";
    }
}


text:
<?php

namespace MatryoshkaModelWrapperRestTest;

use Matryoshka\Model\Wrapper\Rest\RestClient;
use Zend\Http\Response;

/**
 * Class RestClientTest
 */
class RestClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var RestClient
     */
    protected $restClient;

    /**
     * @return array
     */
    public function providerServiceResponse()
    {
        return [
            ['get', [null, ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['get', [11, ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['head', [null, ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['options', [['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['patch', [null, ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['post', [['test' => 'test'], ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['put', [null, ['test' => 'test'], ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            ['delete', [null, ['test' => 'test']], '{"test": "test"}', 'application/json', 'json'],
            // ['get', ['id', ['test' => 'test']], '<test>test</test>', 'application/xml', 'json'],
        ];
    }

    /**
     * @return array
     */
    public function providerServiceRequestResponseException()
    {
        // params
        // [$method, $params, $responseContent, $responseContentType, $responseStatusCode, $format, $exceptionType]

        $apiProblemResponse = '{
            "type": "http://example.com/probs/out-of-credit",
            "title": "You do not have enough credit.",
            "detail": "Your current balance is 30, but that costs 50.",
            "instance": "http://example.net/account/12345/msgs/abc",
            "balance": 30,
            "accounts": ["http://example.net/account/12345","http://example.net/account/67890"]
        }';

        return [
            // Bad Responses
            ['get', [null], '{"test": "test"}', 'application/json', 500, 'json'],
            ['post', [['test' => 'test']], '{"test": "test"}', 'application/json', 500, 'json'],
            ['delete', ['id'], '', 'application/json', 500, 'json'],
            [
                'get',
                [null],
                $apiProblemResponse,
                'application/problem+json',
                500,
                'json',
                '\Matryoshka\Service\Api\Exception\ApiProblem\DomainException'
            ],
            [
                'get',
                ['id'],
                '',
                'application/problem+json',
                502,
                'json',
                '\Matryoshka\Service\Api\Exception\ApiProblem\DomainException'
            ],
            [
                'get',
                ['id'],
                '',
                'application/invalid-response-format',
                502,
                'json',
                '\Matryoshka\Service\Api\Exception\InvalidFormatException'
            ],
            ['get', ['id'], null, '', 502, 'json'], //content-type missing

            //Bad requests
            [
                'post',
                [['test' => 'test']],
                '',
                'application/json',
                502,
                'invalid-request-format',
                '\Matryoshka\Service\Api\Exception\InvalidFormatException'
            ],
        ];
    }

    public function setUp()
    {
        $this->restClient = new RestClient('resource');
    }

    public function testGetResourceName()
    {
        $this->assertSame('resource', $this->restClient->getResourceName());
    }

    public function testGetSetUriResourceStrategy()
    {
        $this->assertInstanceOf(
            'Matryoshka\Model\Wrapper\Rest\UriResourceStrategy\UriResourceStrategyInterface',
            $this->restClient->getUriResourceStrategy()
        );
        $strategy = $this->getMock('Matryoshka\Model\Wrapper\Rest\UriResourceStrategy\UriResourceStrategyInterface');
        /** @var $strategy \Matryoshka\Model\Wrapper\Rest\UriResourceStrategy\UriResourceStrategyInterface */
        $this->restClient->setUriResourceStrategy($strategy);
        $this->assertSame($strategy, $this->restClient->getUriResourceStrategy());
    }

    /**
     * @param $method
     * @param array $params
     * @param $contentResponse
     * @param $responseContentType
     * @param $typeResponse
     * @dataProvider providerServiceResponse
     */
    public function testHttpMethod($method, array $params, $contentResponse, $responseContentType, $typeResponse)
    {
        $httpClient = $this->getMockBuilder('Zend\Http\Client')
            ->disableOriginalConstructor()
            ->setMethods(['dispatch', 'getResponse'])
            ->getMock();

        $response = new Response();
        $response->setContent($contentResponse);
        $response->getHeaders()->addHeaderLine('Content-Type', $responseContentType);

        $httpClient->expects($this->any())
            ->method('dispatch')
            ->will($this->returnValue($response));

        $httpClient->expects($this->any())
            ->method('getResponse')
            ->will($this->returnValue($response));

        /** @var $httpClient \Zend\Http\Client */
        $client = new RestClient('test', $httpClient);
        $profiler = $this->getMock('Matryoshka\Service\Api\Profiler\ProfilerInterface');

        $client->setRequestFormat($typeResponse);
        /** @var $profiler \Matryoshka\Service\Api\Profiler\ProfilerInterface */
        $client->setProfiler($profiler);

        call_user_func_array([$client, $method], $params);

        $this->assertInternalType('array', call_user_func_array([$client, $method], $params));
        $this->assertInstanceof('\Zend\Http\Request', $client->getLastRequest());
        $this->assertSame($response, $client->getLastResponse());
        $this->assertSame($client->getResponseDecoder()->getLastPayload(), $client->getLastResponseData());

        // Test query params
        if (
            (in_array($method, ['delete', 'get', 'head', 'post']) && isset($params[1]) && $query = $params[1])
            ||
            (in_array($method, ['options']) && isset($params[0]) && $query = $params[0])
            ||
            (in_array($method, ['patch', 'put']) && isset($params[2]) && $query = $params[2])
        ) {
            $request = $client->getLastRequest();
            foreach ($query as $key => $value) {
                $this->assertEquals($value, $request->getQuery($key));
            }
        }
    }

    /**
     * @param string $method
     * @param array $params
     * @param string $responseContent
     * @param mixed $responseContentType
     * @param mixed $responseStatusCode
     * @param string $format
     * @param string $exceptionType
     * @dataProvider providerServiceRequestResponseException
     */
    public function testHttpMethodRequestResponseException(
        $method,
        array $params,
        $responseContent,
        $responseContentType,
        $responseStatusCode,
        $format,
        $exceptionType = '\Matryoshka\Service\Api\Exception\InvalidResponseException'
    ) {
        $httpClient = $this->getMockBuilder('Zend\Http\Client')
            ->disableOriginalConstructor()
            ->setMethods(['dispatch', 'getResponse'])
            ->getMock();

        $response = new Response();
        $response->setContent($responseContent);
        if ($responseContentType) {
            $response->getHeaders()->addHeaderLine('Content-Type: ' . $responseContentType);
        }
        $response->setStatusCode($responseStatusCode);

        $httpClient->expects($this->any())
            ->method('dispatch')
            ->will($this->returnValue($response));

        $httpClient->expects($this->any())
            ->method('getResponse')
            ->will($this->returnValue($response));

        /** @var $httpClient \Zend\Http\Client */
        $client = new RestClient('test', $httpClient);
        $client->setRequestFormat($format);

        $this->setExpectedException($exceptionType);
        call_user_func_array([$client, $method], $params);
    }

    public function testPrepareRequestShouldThrowExceptionOnInvalidFormat()
    {
        $this->restClient->setRequestFormat('invalid format');

        $this->setExpectedException('\Matryoshka\Service\Api\Exception\InvalidFormatException');
        $this->restClient->prepareRequest('post', null, ['foo' => 'baz']);
    }
}


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

import java.math.*;
import java.nio.ByteBuffer;
import javax.annotation.Generated;

import com.amazonaws.services.qldb.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * GetDigestResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetDigestResultJsonUnmarshaller implements Unmarshaller<GetDigestResult, JsonUnmarshallerContext> {

    public GetDigestResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        GetDigestResult getDigestResult = new GetDigestResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return getDigestResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Digest", targetDepth)) {
                    context.nextToken();
                    getDigestResult.setDigest(context.getUnmarshaller(java.nio.ByteBuffer.class).unmarshall(context));
                }
                if (context.testExpression("DigestTipAddress", targetDepth)) {
                    context.nextToken();
                    getDigestResult.setDigestTipAddress(ValueHolderJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return getDigestResult;
    }

    private static GetDigestResultJsonUnmarshaller instance;

    public static GetDigestResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new GetDigestResultJsonUnmarshaller();
        return instance;
    }
}


text:
package com.netflix.spinnaker.kork.sql.test;

import static org.jooq.SQLDialect.H2;
import static org.jooq.conf.RenderNameStyle.AS_IS;
import static org.jooq.impl.DSL.currentSchema;
import static org.jooq.impl.DSL.query;
import static org.jooq.impl.DSL.truncateTable;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.Closeable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import liquibase.ContextExpression;
import liquibase.LabelExpression;
import liquibase.Liquibase;
import liquibase.changelog.ChangeLogParameters;
import liquibase.changelog.DatabaseChangeLog;
import liquibase.configuration.GlobalConfiguration;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.SetupException;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.jooq.DSLContext;
import org.jooq.Query;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.testcontainers.containers.JdbcDatabaseContainer;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.containers.PostgreSQLContainer;

public class SqlTestUtil {

  // See
  // https://www.testcontainers.org/modules/databases/jdbc/#database-containers-launched-via-jdbc-url-scheme
  // for background.  Providing this as a jdbc URL makes testcontainers
  // automatically start a mysql container.
  public static String tcJdbcUrl = "jdbc:tc:mysql:5.7.22:///somedb";

  public static String tcPgJdbcUrl = "jdbc:tc:postgres:10.13:///test";

  /** @deprecated Please use the TestContainers db initializers where possible, instead of H2 */
  @Deprecated
  public static TestDatabase initDatabase() {
    return initDatabase("jdbc:h2:mem:test;MODE=MYSQL");
  }

  /** @deprecated Please use the TestContainers db initializers where possible, instead of H2 */
  @Deprecated
  public static TestDatabase initPreviousDatabase() {
    return initDatabase("jdbc:h2:mem:test_previous;MODE=MYSQL");
  }

  public static TestDatabase initTcMysqlDatabase() {
    // host, port, and db name are ignored with the jdbcUrl method of TC initialization and
    // overridden to "test" by the driver.
    return initDatabase(tcJdbcUrl, SQLDialect.MYSQL);
  }

  public static TestDatabase initTcPostgresDatabase() {
    // The container defaults to a DB named "postgres", and Hikari explodes on purpose if it sees
    // that name
    // So, we need to manually start a container here, since Testcontainers does not honor the db
    // name in the JDBC url
    // when implicitly starting a container from a testcontainers-driver-prefixed JDBC URL
    PostgreSQLContainer container =
        new PostgreSQLContainer<>("postgres:10.13")
            .withDatabaseName("test")
            .withUsername("test")
            .withPassword("test");

    container.start();

    String fullJDBCUrl =
        container.getJdbcUrl()
            + String.format(
                "&user=%s&password=%s", container.getUsername(), container.getPassword());
    return initDatabase(fullJDBCUrl, SQLDialect.POSTGRES, container.getDatabaseName());
  }

  @Deprecated
  public static TestDatabase initPreviousTcMysqlDatabase() {
    MySQLContainer container =
        new MySQLContainer("mysql:5.7.22")
            .withDatabaseName("previous")
            .withUsername("test")
            .withPassword("test");

    container.start();

    String jdbcUrl =
        String.format(
            "%s?user=%s&password=%s",
            container.getJdbcUrl(), container.getUsername(), container.getPassword());

    return initDatabase(jdbcUrl, SQLDialect.MYSQL, "previous");
  }

  public static TestDatabase initDualTcMysqlDatabases() {
    return initDualTcDatabases("mysql:5.7.34", SQLDialect.MYSQL);
  }

  public static TestDatabase initDualTcPostgresDatabases() {
    return initDualTcDatabases("postgres:10.13", SQLDialect.POSTGRES);
  }

  private static TestDatabase initDualTcDatabases(String imageName, SQLDialect dialect) {
    JdbcDatabaseContainer container;
    String rootUser;
    String grantCommand;

    switch (dialect) {
      case MYSQL:
        container = new MySQLContainer(imageName);
        rootUser = "root";
        grantCommand = "grant all privileges on previous.* to 'test'@'%'";
        break;
      case POSTGRES:
        container = new PostgreSQLContainer(imageName);
        // Testcontainers sets the PG superuser credentials to the container user/pass
        // Since we're always superuser, we also don't need grants
        rootUser = "test";
        grantCommand = null;
        break;
      default:
        throw new RuntimeException("Unsupported SQL dialect: " + dialect.getName());
    }

    container = container.withDatabaseName("current").withUsername("test").withPassword("test");
    container.start();

    // PostgreSQLContainer has a default query param already added to the JDBC URL
    String queryStart = container.getJdbcUrl().contains("?") ? "&" : "?";

    String rootJdbcUrl =
        String.format(
            "%s%suser=%s&password=%s",
            container.getJdbcUrl(), queryStart, rootUser, container.getPassword());

    try {
      Connection rootCon = DriverManager.getConnection(rootJdbcUrl);
      rootCon.createStatement().executeUpdate("create database previous");
      if (grantCommand != null) {
        rootCon.createStatement().executeUpdate(grantCommand);
      }
      rootCon.close();
    } catch (SQLException e) {
      throw new RuntimeException("Error setting up testcontainer database", e);
    }

    String currentJdbcUrl =
        String.format(
            "%s%suser=%s&password=%s",
            container.getJdbcUrl(), queryStart, container.getUsername(), container.getPassword());

    String previousJdbcUrl = currentJdbcUrl.replace("/current", "/previous");

    TestDatabase currentTDB = initDatabase(currentJdbcUrl, dialect, "current");
    TestDatabase previousTDB = initDatabase(previousJdbcUrl, dialect, "previous");

    return new TestDatabase(
        currentTDB.dataSource,
        currentTDB.context,
        currentTDB.liquibase,
        previousTDB.dataSource,
        previousTDB.context,
        previousTDB.liquibase);
  }

  public static TestDatabase initDatabase(String jdbcUrl) {
    return initDatabase(jdbcUrl, H2);
  }

  public static TestDatabase initDatabase(String jdbcUrl, SQLDialect dialect) {
    return initDatabase(jdbcUrl, dialect, "test");
  }

  public static TestDatabase initDatabase(String jdbcUrl, SQLDialect dialect, String dbName) {
    HikariConfig cpConfig = new HikariConfig();
    cpConfig.setJdbcUrl(jdbcUrl);
    cpConfig.setMaximumPoolSize(5);
    HikariDataSource dataSource = new HikariDataSource(cpConfig);

    DefaultConfiguration config = new DefaultConfiguration();
    config.set(new DataSourceConnectionProvider(dataSource));
    config.setSQLDialect(dialect);

    if (dialect == H2) {
      config.settings().withRenderNameStyle(AS_IS);
    }

    DSLContext context = new DefaultDSLContext(config);

    Liquibase migrate;
    try {
      DatabaseChangeLog changeLog = new DatabaseChangeLog();

      changeLog.setChangeLogParameters(
          new ChangeLogParameters(
              DatabaseFactory.getInstance()
                  .findCorrectDatabaseImplementation(
                      new JdbcConnection(dataSource.getConnection()))));

      changeLog.includeAll(
          "db/changelog/",
          false,
          null,
          false,
          Comparator.comparing(String::toString),
          new ClassLoaderResourceAccessor(),
          new ContextExpression(),
          new LabelExpression(),
          false);

      migrate =
          new Liquibase(
              changeLog,
              new ClassLoaderResourceAccessor(),
              DatabaseFactory.getInstance()
                  .findCorrectDatabaseImplementation(
                      new JdbcConnection(dataSource.getConnection())));
    } catch (DatabaseException | SQLException | SetupException e) {
      throw new DatabaseInitializationFailed(e);
    }

    try {
      migrate.update(dbName);
    } catch (LiquibaseException e) {
      throw new DatabaseInitializationFailed(e);
    }

    return new TestDatabase(dataSource, context, migrate);
  }

  public static void cleanupDb(DSLContext context) {
    String schema = context.select(currentSchema()).fetch().getValue(0, 0).toString();

    GlobalConfiguration configuration =
        LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class);

    List<Query> commands = new ArrayList<>();
    if (context.dialect() == SQLDialect.MYSQL) {
      commands.add(query("set foreign_key_checks=0"));
    }
    context.meta().getTables().stream()
        .filter(
            table ->
                table.getType().isTable()
                    && table.getSchema().getName().equals(schema)
                    && !table.getName().equals(configuration.getDatabaseChangeLogTableName())
                    && !table.getName().equals(configuration.getDatabaseChangeLogLockTableName()))
        .forEach(
            table -> {
              switch (context.dialect()) {
                case POSTGRES:
                  commands.add(truncateTable(table).cascade());
                  break;
                default:
                  commands.add(truncateTable(table));
                  break;
              }
            });
    if (context.dialect() == SQLDialect.MYSQL) {
      commands.add(query("set foreign_key_checks=1"));
    }
    context.batch(commands).execute();
  }

  public static class TestDatabase implements Closeable {
    public final HikariDataSource dataSource;
    public final HikariDataSource previousDataSource;
    public final DSLContext context;
    public final DSLContext previousContext;
    public final Liquibase liquibase;
    public final Liquibase previousLiquibase;

    TestDatabase(HikariDataSource dataSource, DSLContext context, Liquibase liquibase) {
      this.dataSource = dataSource;
      this.context = context;
      this.liquibase = liquibase;
      this.previousDataSource = null;
      this.previousContext = null;
      this.previousLiquibase = null;
    }

    TestDatabase(
        HikariDataSource dataSource,
        DSLContext context,
        Liquibase liquibase,
        HikariDataSource previousDataSource,
        DSLContext previousContext,
        Liquibase previousLiquibase) {
      this.dataSource = dataSource;
      this.context = context;
      this.liquibase = liquibase;
      this.previousDataSource = previousDataSource;
      this.previousContext = previousContext;
      this.previousLiquibase = previousLiquibase;
    }

    @Override
    public void close() {
      dataSource.close();

      if (previousDataSource != null) {
        previousDataSource.close();
      }
    }
  }

  private static class DatabaseInitializationFailed extends RuntimeException {
    DatabaseInitializationFailed(Throwable cause) {
      super(cause);
    }
  }
}


text:
/**
 * Created by garima.kaila on 2017-04-16.
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    TouchableHighlight
} from 'react-native';

import {FBLogin, FBLoginManager} from 'react-native-facebook-login';

import Store from '../../store/Store';
var {
    loginSuccess
} = require('../../actions/login-actions');
import Button from './Button';
import Icon from 'react-native-vector-icons/FontAwesome';

class FacebookSignInButton extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userDetails: {}
        };
    }

    componentDidMount() {
        Store.subscribe(() => {
            this.setState({
                userDetails: Store.getState().login.userDetails
            });

            //   alert("hello " + JSON.stringify(Store.getState().login.userDetails, null, '  '));
        });
    }

    render() {
        var _this = this;
        if (this.state.userDetails.id && this.state.userDetails.id.length > 0) {
            let image = this.state.userDetails.image;
            let name = this.state.userDetails.name + " (" + this.state.userDetails.email + ")";
            return (<View>
                <Text>
                    Welcome!!
                </Text>
                {/* <Image
                 style={{width: 50, height: 50}}
                 source={{uri: image}}
                 />*/}
                <Text>
                    {name}
                </Text>
            </View>);
        } else {
            let button = (
                <View style={styles.inline}>
                    <Icon name="facebook-official" size={30} color="#3B5699"/>
                    <Text style={[styles.buttonBlueText, styles.buttonBigText]}> Connect </Text>
                    <Text style={styles.buttonBlueText}>with Facebook</Text>
                </View>
            )
            return (
                <FBLogin
                    buttonView={button }
                    onClickColor="#ccc"
                    containerStyle={styles.transparentButton}
                    ref={(fbLogin) => { this.fbLogin = fbLogin }}
                    loginBehavior={FBLoginManager.LoginBehaviors.Native}
                    permissions={["email","user_friends"]}
                    onLogin={function(user){
                    console.log(user);
                     setTimeout(() => {
                            let userInfo = {provider:"facebook",id:user.credentials.userId,email:user.profile.email,name:user.profile.name,image:user.profile.picture.data.url}
                            Store.dispatch(loginSuccess(userInfo));
                    },1500);
                 //   alert(JSON.stringify(userInfo, null, '  '));
                }}
                    onLoginFound={function(e){console.log(e)}}
                    onError={function(e){console.log(e)}}
                    onLoginNotFound={function(e){console.log(e)}}
                    onLogout={function(e){console.log(e)}}
                    onCancel={function(e){console.log(e)}}
                    onPermissionsMissing={function(e){console.log(e)}}
                />
            );
        }
    }
}

const styles = StyleSheet.create({
    transparentButton: {
        marginTop: 10,
        borderColor: '#3B5699',
        borderWidth: 2,
        alignItems: 'center',
        justifyContent: 'center',
        padding: 5
    },
    buttonBlueText: {
        fontSize: 20,
        color: '#3B5699'
    },
    buttonBigText: {
        fontSize: 20,
        fontWeight: 'bold'
    },
    inline: {
        flexDirection: 'row'
    }
});

module.exports = FacebookSignInButton;


text:
package infoserver

import (
	"encoding/json"
	"net/http"

	"github.com/concourse/concourse/atc"
)

func (s *Server) Info(w http.ResponseWriter, r *http.Request) {
	logger := s.logger.Session("info")

	w.Header().Set("Content-Type", "application/json")
	err := json.NewEncoder(w).Encode(atc.Info{Version: s.version,
		WorkerVersion: s.workerVersion,
		ExternalURL:   s.externalURL,
		ClusterName:   s.clusterName,
		FeatureFlags:  atc.FeatureFlags(),
	})
	if err != nil {
		logger.Error("failed-to-encode-info", err)
		w.WriteHeader(http.StatusInternalServerError)
	}
}


text:
<!DOCTYPE html>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.ParametersColon'))
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.UserNameEquals'))$Encoder.bodyEscape($USERNAME)
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.PasswordEquals'))********
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.URLEquals'))$Encoder.bodyEscape($URL)
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.HostEquals'))$Encoder.bodyEscape($HOST)
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.PortEquals'))$Encoder.bodyEscape($PORT)
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.DBEquals'))$Encoder.bodyEscape($DB)
      </nobr>

      <nobr>
        $Encoder.bodyEscape($ResourceBundle.getString('GridFSConnector.BucketEquals'))$Encoder.bodyEscape($BUCKET)
      </nobr>


text:
package com.pearson.statsagg.webui;

import com.pearson.statsagg.globals.GlobalVariables;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pearson.statsagg.utilities.StackTrace;
import com.pearson.statsagg.utilities.StringUtilities;
import static com.pearson.statsagg.webui.CreateMetricGroup.getMetricGroupNewlineDelimitedParameterValues;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jeffrey Schmidt
 */
@WebServlet(name = "MergedRegexMetricsPreview", urlPatterns = {"/MergedRegexMetricsPreview"})
public class MergedRegexMetricsPreview extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(MergedRegexMetricsPreview.class.getName());

    public static final String PAGE_NAME = "Merged Regex - Metrics Preview";

    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        processGetRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        processGetRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return PAGE_NAME;
    }

    protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) {

        if ((request == null) || (response == null)) {
            return;
        }

        response.setContentType("text/html");
        PrintWriter out = null;

        TreeSet<String> matchRegexes = getMetricGroupNewlineDelimitedParameterValues(request, "MatchRegexes");
        TreeSet<String> blacklistRegexes = getMetricGroupNewlineDelimitedParameterValues(request, "BlacklistRegexes");

        List matchRegexes_List = null, blacklistRegexes_List = null;
        if ((matchRegexes != null) && !matchRegexes.isEmpty()) matchRegexes_List = new ArrayList<>(matchRegexes);
        if ((blacklistRegexes != null) && !blacklistRegexes.isEmpty()) blacklistRegexes_List = new ArrayList<>(blacklistRegexes);

        String mergedMatchRegex = StringUtilities.createMergedRegex(matchRegexes_List);
        String mergedBlacklistRegex = StringUtilities.createMergedRegex(blacklistRegexes_List);

        Set<String> matchMetricKeys = RegexTester.getRegexMatches(GlobalVariables.metricKeysLastSeenTimestamp_UpdateOnResend.keySet(), mergedMatchRegex, mergedBlacklistRegex, 1001);
        String regexMatchesHtml = RegexTester.getRegexMatchesHtml(matchMetricKeys, 1000);

        try {
            StringBuilder htmlBuilder = new StringBuilder();

            StatsAggHtmlFramework statsAggHtmlFramework = new StatsAggHtmlFramework();
            String htmlHeader = statsAggHtmlFramework.createHtmlHeader("StatsAgg - " + PAGE_NAME, "");

            String htmlBody =
            "" +
            "
\n" +
            "    \n" +
            "
\n" +
            "
" +
            regexMatchesHtml +
            "
\n" +
            "
\n" +
            "
\n" +
            "";

            htmlBuilder.append("<!DOCTYPE html>\n\n").append(htmlHeader).append(htmlBody).append("");

            Document htmlDocument = Jsoup.parse(htmlBuilder.toString());
            String htmlFormatted  = htmlDocument.toString();
            out = response.getWriter();
            out.println(htmlFormatted);
        }
        catch (Exception e) {
            logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        }
        finally {
            if (out != null) {
                out.close();
            }
        }
    }

}


text:
<?php namespace AdammBalogh\Box\Command\View\Document;

use AdammBalogh\Box\Command\AbstractCommand;
use AdammBalogh\Box\GuzzleHttp\Message\PostRequest;
use GuzzleHttp\Post\PostBody;
use GuzzleHttp\Post\PostFile;
use AdammBalogh\Box\Request\ExtendedRequest;

class MultipartDocumentUpload extends AbstractCommand
{
    /**
     * @param string $content
     * @param string $fileName
     * @param ExtendedRequest $extendedRequest
     */
    public function __construct($content, $fileName, ExtendedRequest $extendedRequest = null)
    {
        $postBody = new PostBody();
        $this->request = new PostRequest('documents');

        if (!is_null($extendedRequest)) {
            $postBody = $extendedRequest->getPostBody();
        }

        $postBody->addFile(new PostFile('file', $content, $fileName));
        $this->request->setBody($postBody);
    }
}


text:
                Der VfU

Der VfU ist ein 1995 gegründetes Netzwerk von Sustainable Finance Professionals aus aktuell 49 Finanz-Unternehmen (Banken, Versicherungen, Kapitalanlage-Gesellschaften und entsprechende Verbände).

Das zentrale Anliegen des VfU besteht in der Förderung und Verbreitung von "Sustainable Finance", verstanden -  in Übereinstimmung mit der Definition des UN Environment Programm (UNEP) - als "ein umfassender Ansatz zum Management der ökonomischen, sozialen und umweltbezogenen Dimensionen des Finanzgeschäfts, um einen substantiellen Fortschritt in Richtung einer nachhaltigen Entwicklung zu ermöglichen" (UNEP, 2017).

Dafür bietet der VfU Finanzdienstleistern eine Plattform, auf der sie in verschiedenen Formaten Sustainable Finance Wissen und Know-How erwerben, austauschen, generieren und vertiefen können.


text:
package org.apache.camel.component.pdf;

public final class PdfPageSizeConstant {

    public static final String PAGE_SIZE_A0 = "PAGE_SIZE_A0";
    public static final String PAGE_SIZE_A1 = "PAGE_SIZE_A1";
    public static final String PAGE_SIZE_A2 = "PAGE_SIZE_A2";
    public static final String PAGE_SIZE_A3 = "PAGE_SIZE_A3";
    public static final String PAGE_SIZE_A4 = "PAGE_SIZE_A4";
    public static final String PAGE_SIZE_A5 = "PAGE_SIZE_A5";
    public static final String PAGE_SIZE_A6 = "PAGE_SIZE_A6";
    public static final String PAGE_SIZE_LETTER = "PAGE_SIZE_LETTER";

    private PdfPageSizeConstant() {
    }
}


text:
import subprocess

def run():
  cmd = "sudo halt"
  subprocess.call( cmd, shell=True  )


text:
<?php

namespace LiveTest\Connection\Request;

use Base\Security\Credentials;

use Base\Http\Request\Request as BaseRequest;
use Base\Www\Uri;

interface Request extends BaseRequest
{
    public function getIdentifier();

    public function getHttpBasicAuthenticationCredentials();

    public function removeParameter($key);

    public function addParameter($key, $value);
}