text:
package automock

import (
	compute "google.golang.org/api/compute/v1"

	mock "github.com/stretchr/testify/mock"
)

// DiskAPI is an autogenerated mock type for the DiskAPI type
type DiskAPI struct {
	mock.Mock
}

// ListDisks provides a mock function with given fields: project, zone
func (_m *DiskAPI) ListDisks(project string, zone string) ([]*compute.Disk, error) {
	ret := _m.Called(project, zone)

	var r0 []*compute.Disk
	if rf, ok := ret.Get(0).(func(string, string) []*compute.Disk); ok {
		r0 = rf(project, zone)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]*compute.Disk)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, string) error); ok {
		r1 = rf(project, zone)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// RemoveDisk provides a mock function with given fields: name, project, zone
func (_m *DiskAPI) RemoveDisk(name string, project string, zone string) error {
	ret := _m.Called(name, project, zone)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
		r0 = rf(name, project, zone)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.vineey.rql.sort;

/**
 * @author vrustia - 4/10/16.
 */
public class SortContext<T, E extends SortParam> {
    private SortBuilder<T, E> sortBuilder;
    private E sortParam;

    public static <T, E extends SortParam> SortContext<T, E> withBuilderAndParam(SortBuilder<T, E> builder, E sortParam) {
        return new SortContext<T, E>()
                .setSortBuilder(builder)
                .setSortParam(sortParam);
    }

    public SortBuilder<T, E> getSortBuilder() {
        return sortBuilder;
    }

    public SortContext setSortBuilder(SortBuilder<T, E> sortBuilder) {
        this.sortBuilder = sortBuilder;
        return this;
    }

    public E getSortParam() {
        return sortParam;
    }

    public SortContext setSortParam(E sortParam) {
        this.sortParam = sortParam;
        return this;
    }
}


text:
using content::PasswordForm;
using sync_datatype_helper::test;

const std::string kFakeSignonRealm = "http://fake-signon-realm.google.com/";
const char* kIndexedFakeOrigin = "http://fake-signon-realm.google.com/%d";

namespace {

// We use a WaitableEvent to wait when logins are added, removed, or updated
// instead of running the UI message loop because of a restriction that
// prevents a DB thread from initiating a quit of the UI message loop.
void PasswordStoreCallback(base::WaitableEvent* wait_event) {
  // Wake up passwords_helper::AddLogin.
  wait_event->Signal();
}

class PasswordStoreConsumerHelper : public PasswordStoreConsumer {
 public:
  explicit PasswordStoreConsumerHelper(std::vector<PasswordForm>* result)
      : PasswordStoreConsumer(),
        result_(result) {}

  virtual void OnPasswordStoreRequestDone(
      CancelableRequestProvider::Handle handle,
      const std::vector<PasswordForm*>& result) OVERRIDE {
    // TODO(kaiwang): Remove this function.
    NOTREACHED();
  }

  virtual void OnGetPasswordStoreResults(
      const std::vector<PasswordForm*>& result) OVERRIDE {
    result_->clear();
    for (std::vector<PasswordForm*>::const_iterator it = result.begin();
         it != result.end();
         ++it) {
      result_->push_back(**it);
      delete *it;
    }

    // Quit the message loop to wake up passwords_helper::GetLogins.
    base::MessageLoopForUI::current()->Quit();
  }

 private:
  std::vector<PasswordForm>* result_;

  DISALLOW_COPY_AND_ASSIGN(PasswordStoreConsumerHelper);
};

}  // namespace

namespace passwords_helper {

void AddLogin(PasswordStore* store, const PasswordForm& form) {
  ASSERT_TRUE(store);
  base::WaitableEvent wait_event(true, false);
  store->AddLogin(form);
  store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event));
  wait_event.Wait();
}

void UpdateLogin(PasswordStore* store, const PasswordForm& form) {
  ASSERT_TRUE(store);
  base::WaitableEvent wait_event(true, false);
  store->UpdateLogin(form);
  store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event));
  wait_event.Wait();
}

void GetLogins(PasswordStore* store, std::vector<PasswordForm>& matches) {
  ASSERT_TRUE(store);
  PasswordForm matcher_form;
  matcher_form.signon_realm = kFakeSignonRealm;
  PasswordStoreConsumerHelper consumer(&matches);
  store->GetLogins(matcher_form, &consumer);
  content::RunMessageLoop();
}

void RemoveLogin(PasswordStore* store, const PasswordForm& form) {
  ASSERT_TRUE(store);
  base::WaitableEvent wait_event(true, false);
  store->RemoveLogin(form);
  store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event));
  wait_event.Wait();
}

void RemoveLogins(PasswordStore* store) {
  std::vector<PasswordForm> forms;
  GetLogins(store, forms);
  for (std::vector<PasswordForm>::iterator it = forms.begin();
       it != forms.end(); ++it) {
    RemoveLogin(store, *it);
  }
}

void SetEncryptionPassphrase(int index,
                             const std::string& passphrase,
                             ProfileSyncService::PassphraseType type) {
  ProfileSyncServiceFactory::GetForProfile(
      test()->GetProfile(index))->SetEncryptionPassphrase(passphrase, type);
}

bool SetDecryptionPassphrase(int index, const std::string& passphrase) {
  return ProfileSyncServiceFactory::GetForProfile(
      test()->GetProfile(index))->SetDecryptionPassphrase(passphrase);
}

PasswordStore* GetPasswordStore(int index) {
  return PasswordStoreFactory::GetForProfile(test()->GetProfile(index),
                                             Profile::IMPLICIT_ACCESS).get();
}

PasswordStore* GetVerifierPasswordStore() {
  return PasswordStoreFactory::GetForProfile(test()->verifier(),
                                             Profile::IMPLICIT_ACCESS).get();
}

bool ProfileContainsSamePasswordFormsAsVerifier(int index) {
  std::vector<PasswordForm> verifier_forms;
  std::vector<PasswordForm> forms;
  GetLogins(GetVerifierPasswordStore(), verifier_forms);
  GetLogins(GetPasswordStore(index), forms);
  bool result = ContainsSamePasswordForms(verifier_forms, forms);
  if (!result) {
    LOG(ERROR) << "Password forms in Verifier Profile:";
    for (std::vector<PasswordForm>::iterator it = verifier_forms.begin();
         it != verifier_forms.end(); ++it) {
      LOG(ERROR) << *it << std::endl;
    }
    LOG(ERROR) << "Password forms in Profile" << index << ":";
    for (std::vector<PasswordForm>::iterator it = forms.begin();
         it != forms.end(); ++it) {
      LOG(ERROR) << *it << std::endl;
    }
  }
  return result;
}

bool ProfilesContainSamePasswordForms(int index_a, int index_b) {
  std::vector<PasswordForm> forms_a;
  std::vector<PasswordForm> forms_b;
  GetLogins(GetPasswordStore(index_a), forms_a);
  GetLogins(GetPasswordStore(index_b), forms_b);
  bool result = ContainsSamePasswordForms(forms_a, forms_b);
  if (!result) {
    LOG(ERROR) << "Password forms in Profile" << index_a << ":";
    for (std::vector<PasswordForm>::iterator it = forms_a.begin();
         it != forms_a.end(); ++it) {
      LOG(ERROR) << *it << std::endl;
    }
    LOG(ERROR) << "Password forms in Profile" << index_b << ":";
    for (std::vector<PasswordForm>::iterator it = forms_b.begin();
         it != forms_b.end(); ++it) {
      LOG(ERROR) << *it << std::endl;
    }
  }
  return result;
}

bool AllProfilesContainSamePasswordFormsAsVerifier() {
  for (int i = 0; i < test()->num_clients(); ++i) {
    if (!ProfileContainsSamePasswordFormsAsVerifier(i)) {
      LOG(ERROR) << "Profile " << i << " does not contain the same password"
                                       " forms as the verifier.";
      return false;
    }
  }
  return true;
}

bool AllProfilesContainSamePasswordForms() {
  for (int i = 1; i < test()->num_clients(); ++i) {
    if (!ProfilesContainSamePasswordForms(0, i)) {
      LOG(ERROR) << "Profile " << i << " does not contain the same password"
                                       " forms as Profile 0.";
      return false;
    }
  }
  return true;
}

int GetPasswordCount(int index) {
  std::vector<PasswordForm> forms;
  GetLogins(GetPasswordStore(index), forms);
  return forms.size();
}

int GetVerifierPasswordCount() {
  std::vector<PasswordForm> verifier_forms;
  GetLogins(GetVerifierPasswordStore(), verifier_forms);
  return verifier_forms.size();
}

PasswordForm CreateTestPasswordForm(int index) {
  PasswordForm form;
  form.signon_realm = kFakeSignonRealm;
  form.origin = GURL(base::StringPrintf(kIndexedFakeOrigin, index));
  form.username_value = ASCIIToUTF16(base::StringPrintf("username%d", index));
  form.password_value = ASCIIToUTF16(base::StringPrintf("password%d", index));
  form.date_created = base::Time::Now();
  return form;
}

}  // namespace passwords_helper


text:
import { RouteRecordRaw } from 'vue-router';

export const routeAuthAuthorize: RouteRecordRaw = {
	name: 'auth.authorize',
	path: '/authorize/:userId/:code/:type',
	component: () => import('./authorize.vue'),
	meta: {
		hideCoverImage: true,
	},
};


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.modeshape.jcr.cache.document;

import java.util.concurrent.ConcurrentHashMap;
import javax.transaction.Transaction;
import org.modeshape.jcr.cache.RepositoryCache;
import org.modeshape.jcr.cache.change.ChangeSet;
import org.modeshape.jcr.txn.Transactions;

/**
 * A special WorkspaceCache implementation that should be used by sessions running within user transactions.
 *

 * Normally, each {@link RepositoryCache} instance has for each workspace a single WorkspaceCache instance shared by all sessions.
 * However, in the event that a session is running within a user transaction, it is possible for the session (or other sessions
 * that are also participating in the same user transaction) to persist node changes in the document store but to not commit the
 * transaction. This means that no other transactions should see these persisted-but-not-committed node representations. Thus,
 * these sessions running within a user transaction cannot share the common WorkspaceCache instance, lest any node representations
 * persisted-but-not-committed be loaded into the WorkspaceCache (leaking transaction-scoped data outside of the transaction) or
 * the shared WorkspaceCache instance has already-cached pre-modified representations of the persisted-but-not-committed nodes
 * (transaction-scoped changes are not visible to the transaction).
 *

 *

 * Therefore, such sessions running within user transactions need a transactionally-scoped WorkspaceCache instance. Because the
 * ModeShape infrastructure is not set up to handle lots of WorkspaceCache instances, we only want one instance that is actually
 * caching nodes. Therefore, the WorkspaceCache returned from this method will never cache any nodes and will always re-read the
 * nodes from the document store.
 *

 */
public class TransactionalWorkspaceCache extends WorkspaceCache {

    private final WorkspaceCache sharedWorkspaceCache;
    private final TransactionalWorkspaceCaches txWorkspaceCaches;
    private final Transaction txn;

    protected TransactionalWorkspaceCache( WorkspaceCache sharedWorkspaceCache,
                                           TransactionalWorkspaceCaches txWorkspaceCaches,
                                           Transaction txn) {
        // Use a new in-memory map for the transactional cache which is empty when first created...
        super(sharedWorkspaceCache, new ConcurrentHashMap<>());
        this.sharedWorkspaceCache = sharedWorkspaceCache;
        this.txn = txn;
        this.txWorkspaceCaches = txWorkspaceCaches;
    }

    @Override
    public void changed( ChangeSet changes ) {
        // Delegate to the shared ...
        sharedWorkspaceCache.changed(changes);
        // And then delegate so that all transactional workspace caches are notified ...
        changedWithinTransaction(changes);
    }

    /**
     * Signal that this transaction-specific workspace cache needs to reflect recent changes that have been persisted but not yet
     * committed. Generally, the transactional workspace cache will clear any cached nodes that were included in the change set
     *
     * @param changes the changes that were persisted but not yet committed
     * @see Transactions#updateCache(WorkspaceCache, ChangeSet, org.modeshape.jcr.txn.Transactions.Transaction)
     */
    public void changedWithinTransaction( final ChangeSet changes ) {
        txWorkspaceCaches.workspaceCachesFor(txn).forEach(cache -> cache.internalChangedWithinTransaction(changes));
    }

    @Override
    public void clear() {
        txWorkspaceCaches.workspaceCachesFor(txn).forEach(TransactionalWorkspaceCache::internalClear);
    }

   protected void internalClear() {
        super.clear();
    }

    protected void internalChangedWithinTransaction( ChangeSet changes ) {
        // Handle it ourselves ...
        super.changed(changes);
    }

    @Override
    protected void evictChangedNodes( ChangeSet changeSet ) {
        // Delegate to the shared ...
        sharedWorkspaceCache.evictChangedNodes(changeSet);
        // And then handle it ourselves ...
        super.evictChangedNodes(changeSet);
    }
}


text:
namespace Poco {
namespace RemotingNG {

template <>
class TypeSerializer<IoT::Modbus::ReadInputRegistersResponse>
{
public:
	static void serialize(const std::string& name, const IoT::Modbus::ReadInputRegistersResponse& value, Serializer& ser)
	{
		ser.serializeStructBegin(name);
		serializeImpl(value, ser);
		ser.serializeStructEnd(name);
	}

	static void serializeImpl(const IoT::Modbus::ReadInputRegistersResponse& value, Serializer& ser)
	{
		// IoT::Modbus::ModbusMessage
		{
		remoting__staticInitBegin(REMOTING__NAMES__IOT__MODBUS__MODBUSMESSAGE);
		static const std::string REMOTING__NAMES__IOT__MODBUS__MODBUSMESSAGE[] = {"functionCode","slaveOrUnitAddress",""};
		remoting__staticInitEnd(REMOTING__NAMES__IOT__MODBUS__MODBUSMESSAGE);
		TypeSerializer<Poco::UInt8 >::serialize(REMOTING__NAMES__IOT__MODBUS__MODBUSMESSAGE[0], value.functionCode, ser);
		TypeSerializer<Poco::UInt8 >::serialize(REMOTING__NAMES__IOT__MODBUS__MODBUSMESSAGE[1], value.slaveOrUnitAddress, ser);
		}

		remoting__staticInitBegin(REMOTING__NAMES);
		static const std::string REMOTING__NAMES[] = {"registerValues",""};
		remoting__staticInitEnd(REMOTING__NAMES);
		TypeSerializer<std::vector < Poco::UInt16 > >::serialize(REMOTING__NAMES[0], value.registerValues, ser);
	}

};

} // namespace RemotingNG
} // namespace Poco

#endif // TypeSerializer_IoT_Modbus_ReadInputRegistersResponse_INCLUDED


text:
package com.pushtechnology.diffusion.maven.plugin;

import java.io.File;
import java.util.List;
import java.util.Set;

import org.apache.maven.model.Build;
import org.apache.maven.project.MavenProject;

import static java.util.Collections.emptyList;
import static java.util.Collections.emptySet;

/**
 * @author Phil Aston
 * @author Andy Piper
 */
public class DiffusionProjectStub extends MavenProject {

    public DiffusionProjectStub(final File buildDirectory, final File pom)
            throws Exception {

        super(new DiffusionModelStub());

        setExecutionProject(this);

        setFile(pom);

        final Build build = new Build();
        build.setDirectory(buildDirectory.getAbsolutePath());
        setBuild(build);
        setDependencyArtifacts((Set)emptySet());
        setArtifacts((Set)emptySet());
        setPluginArtifacts((Set)emptySet());
        setReportArtifacts((Set)emptySet());
        setExtensionArtifacts((Set)emptySet());
        setRemoteArtifactRepositories((List)emptyList());
        setPluginArtifactRepositories((List)emptyList());
        setCollectedProjects((List)emptyList());
        setActiveProfiles((List)emptyList());
    }
}


text:
#ifndef VLC_IMAGE_H
#define VLC_IMAGE_H 1

/**
 * \file
 * This file defines functions and structures for image conversions in vlc
 */

#include <vlc_vout.h>

# ifdef __cplusplus
extern "C" {
# endif

struct image_handler_t
{
    picture_t * (*pf_read)      ( image_handler_t *, block_t *,
                                  video_format_t *, video_format_t * );
    picture_t * (*pf_read_url)  ( image_handler_t *, const char *,
                                  video_format_t *, video_format_t * );
    block_t * (*pf_write)       ( image_handler_t *, picture_t *,
                                  video_format_t *, video_format_t * );
    int (*pf_write_url)         ( image_handler_t *, picture_t *,
                                  video_format_t *, video_format_t *,
                                  const char * );

    picture_t * (*pf_convert)   ( image_handler_t *, picture_t *,
                                  video_format_t *, video_format_t * );
    picture_t * (*pf_filter)    ( image_handler_t *, picture_t *,
                                  video_format_t *, const char * );

    /* Private properties */
    vlc_object_t *p_parent;
    decoder_t *p_dec;
    encoder_t *p_enc;
    filter_t  *p_filter;
};

VLC_API image_handler_t * image_HandlerCreate( vlc_object_t * ) VLC_USED;
#define image_HandlerCreate( a ) image_HandlerCreate( VLC_OBJECT(a) )
VLC_API void image_HandlerDelete( image_handler_t * );

#define image_Read( a, b, c, d ) a->pf_read( a, b, c, d )
#define image_ReadUrl( a, b, c, d ) a->pf_read_url( a, b, c, d )
#define image_Write( a, b, c, d ) a->pf_write( a, b, c, d )
#define image_WriteUrl( a, b, c, d, e ) a->pf_write_url( a, b, c, d, e )
#define image_Convert( a, b, c, d ) a->pf_convert( a, b, c, d )
#define image_Filter( a, b, c, d ) a->pf_filter( a, b, c, d )

VLC_API vlc_fourcc_t image_Type2Fourcc( const char *psz_name );
VLC_API vlc_fourcc_t image_Ext2Fourcc( const char *psz_name );
VLC_API vlc_fourcc_t image_Mime2Fourcc( const char *psz_mime );

# ifdef __cplusplus
}
# endif

#endif /* _VLC_IMAGE_H */


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Interface IPagedList<T>
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Interface IPagedList<T>
   ">
    <meta name="generator" content="docfx 2.45.1.0">

    <link rel="shortcut icon" href="../images/logo.png">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Interface IPagedList<T>

A list which contains paged data from the API.

Namespace: Auth0.Core.Collections

Assembly: cs.temp.dll.dll

Syntax

public interface IPagedList<T> : IList<T>

Type Parameters

        Name
        Description

        T

Properties

Paging

Declaration

PagingInformation Paging { get; set; }

Property Value

        Type
        Description

        PagingInformation

              Back to top

            Generated by DocFX


text:
namespace EntityFrameworkHelper.Model
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("ExtChannelCity")]
    public partial class ExtChannelCity
    {
        [Key]
        [Column(Order = 0)]
        public Guid ExternalChannelId { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CityId { get; set; }

        public virtual ExtChannel ExtChannel { get; set; }
    }
}


text:
package com.db4o.ta;

import com.db4o.*;

/**
 * Interface defining rollback behavior when Transparent Persistence mode is on.
 * @see TransparentPersistenceSupport
 */
public interface RollbackStrategy {

	/**
	 * Method to be called per TP-enabled object when the transaction is rolled back.
	 * @param container current ObjectContainer
	 * @param obj TP-enabled object
	 */
	void rollback(ObjectContainer container, Object obj);

}


text:
/** Automatically generated file. DO NOT MODIFY */
package se.sics.phonesense;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


text:
package org.apache.geode.cache.execute;

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.examples.SimpleSecurityManager;
import org.apache.geode.security.ResourcePermission;
import org.apache.geode.test.junit.rules.ConnectionConfiguration;
import org.apache.geode.test.junit.rules.GfshCommandRule;
import org.apache.geode.test.junit.rules.ServerStarterRule;

public class FunctionDynamicByArgsSecurityTest {
  private static final String RESULT_HEADER = "Message";

  @ClassRule
  public static ServerStarterRule server =
      new ServerStarterRule().withJMXManager().withSecurityManager(SimpleSecurityManager.class)
          .withRegion(RegionShortcut.PARTITION, "testRegion1")
          .withRegion(RegionShortcut.PARTITION, "testRegion2")
          .withAutoStart();

  @Rule
  public GfshCommandRule gfsh =
      new GfshCommandRule(server::getJmxPort, GfshCommandRule.PortType.jmxManager);

  private static final DynamicSecurityFunction function = new DynamicSecurityFunction();

  @BeforeClass
  public static void setupClass() {
    FunctionService.registerFunction(function);
  }

  @Test
  @ConnectionConfiguration(user = "DATAREADtestRegion1", password = "DATAREADtestRegion1")
  public void functionDynamicRequireExpectedPermission() throws Exception {
    gfsh.executeAndAssertThat(
        "execute function --id=" + function.getId() + " --arguments=testRegion1")
        .tableHasRowCount(1)
        .tableHasRowWithValues(RESULT_HEADER, "[successfully invoked with argument:testRegion1]")
        .statusIsSuccess();
    gfsh.executeAndAssertThat(
        "execute function --id=" + function.getId() + " --arguments=testRegion1,testRegion2")
        .tableHasRowCount(1)
        .tableHasRowWithValues(RESULT_HEADER,
            "Exception: DATAREADtestRegion1 not authorized for DATA:READ:testRegion2")
        .statusIsError();
  }

  static class DynamicSecurityFunction implements Function {
    @Override
    public void execute(FunctionContext context) {
      Object args = context.getArguments();
      String[] regions = (String[]) args;
      context.getResultSender()
          .lastResult("successfully invoked with argument:" + String.join(",", regions));
    }

    @Override
    public Collection<ResourcePermission> getRequiredPermissions(String regionName, Object args) {
      String[] regions = (String[]) args;
      return Stream.of(regions).map(s -> new ResourcePermission(ResourcePermission.Resource.DATA,
          ResourcePermission.Operation.READ, s)).collect(Collectors.toSet());
    }
  }
}


text:
require([
  '$api/models',
  '$views/list#List'
], function(models, List) {
  'use strict';

  var doPlaylistForAlbum = function() {
    var album = models.Album.fromURI('spotify:album:5rCCCernTo6IwFwEZM4H53');
    var list = List.forAlbum(album);
    console.log(list);
    document.getElementById('playlistContainer').appendChild(list.node);
    list.init();
  };

  exports.doPlaylistForAlbum = doPlaylistForAlbum;
});


text:
describe('Email Validator', function() {
  var validator = new Validator(window.validations.email);

  it('exists', function() {
    expect(validator).toBeDefined();
  });

  it('fails for less than 1 character', function() {
    expect(validator.test('')).toBe(false);
  });

  it('fails for more than 48 characters', function() {
    var testString = 'srandddddddddddddddddddddddddddddd@mcdpartners.com';
    expect(validator.test(testString)).toBe(false);
  });

  it('passes for exactly 48 characters', function() {
    var testString = 'srandddddddddddddddddddddddddddd@mcdpartners.com';
    expect(validator.test(testString)).toBe(true);
  });

  it('fails for no @ symbol in string', function() {
    expect(validator.test('srandmcdpartners.com')).toBe(false);
  });

  it('fails for no . symbol in string', function() {
    expect(validator.test('srand@mcdpartnerscom')).toBe(false);
  });

  it('fails for / character in string after @ symbol', function() {
    expect(validator.test('srand@/mcdpartners.com')).toBe(false);
  });

  it('fails for @ symbol in beginning of string', function() {
    expect(validator.test('@srand@mcdpartners.com')).toBe(false);
  });

  it('fails for . symbol in beginning of string', function() {
    expect(validator.test('.srand@mcdpartners.com')).toBe(false);
  });

  it('fails for two @ symbols in string', function() {
    expect(validator.test('srand@@mcdpartners.com')).toBe(false);
  });

  it('fails for two . symbols in string', function() {
    expect(validator.test('srand@mcdpartners..com')).toBe(false);
  });

  it('fails for . symbol at end in string', function() {
    expect(validator.test('srand@mcdpartners.com.')).toBe(false);
  });

  it('fails for @ symbol at end in string', function() {
    expect(validator.test('srand@mcdpartners.com@')).toBe(false);
  });

  it('fails for . symbol next to @ in string', function() {
    expect(validator.test('srand@.mcdpartners.com')).toBe(false);
  });

  it('passes for good string', function() {
    expect(validator.test('srand@mcdpartners.com')).toBe(true);
  });

  it('passes for good string with number', function() {
    expect(validator.test('sr4and@mcdpartners.com')).toBe(true);
  });

  it('passes for good string with two dots not together', function() {
    expect(validator.test('srand@mcdpa.rtners.com')).toBe(true);
  });

  it('passes for good string with dash', function() {
    expect(validator.test('sra-nd@mcdpartners.com')).toBe(true);
  });
});


text:
FROM docker.dever.cc/office/libreoffice:latest

MAINTAINER Rabin "https://github.com/shemic"

ENV DEMETER_HOME=/usr/local/convert
ENV DEMETER_CONF=env
ENV PATH=$PATH:$DEMETER_HOME

RUN echo -e '@community http://mirrors.ustc.edu.cn/alpine/edge/community' >> /etc/apk/repositories

#rm -rf $DEMETER_HOME/runtime/mysql/* && \
# apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev && pip install pillow && pip install pdf2image

#git clone https://github.com/dawbarton/pdf2svg && cd pdf2svg && cp README.md README && ./configure && make && make install

RUN apk add --no-cache --update git curl nginx gcc g++ python-dev py-pip make cmake m4 openssl-dev libffi-dev imagemagick6@community imagemagick6-dev@community && \
	pip install --upgrade pip && \
	pip install gevent==1.2 && \
	pip install redis && \
	pip install wand && \
	pip install pdf2jpg && \
	pip install -U git+http://git.dever.cc:3000/python/demeter.git && \
	git clone http://git.dever.cc:3000/python/convert.git $DEMETER_HOME && \
	curl -O https://fossies.org/linux/misc/poppler-data-0.4.9.tar.gz && \
	tar -zxvf poppler-data-0.4.9.tar.gz && \
	cd poppler-data-0.4.9 && \
	make install datadir=/usr/share && \
	mkdir /run/nginx/ && \
	rm -rf /etc/nginx/conf.d/default.conf && \
	apk del curl m4 make cmake gcc g++ python-dev

EXPOSE 8087 8088 80 443

COPY convert.sh /entrypoint/convert.sh
COPY convert.conf /etc/nginx/conf.d/convert.conf


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Reis. Amur-Land. , Bot. 146. 1868

#### Original name
null

### Remarks
null


text:
package com.ginsberg.ginsberg;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class AlarmTask implements Runnable{
	// The date selected for the alarm
	private final Calendar date;
	// The android system alarm manager
	private final AlarmManager am;
	// Your context to retrieve the alarm manager from
	private final Context context;

	public AlarmTask(Context context, Calendar date)
    {
		this.context = context;
		this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		this.date = date;
	}

	@Override
	public void run()
    {
		// Request to start are service when the alarm date is upon us
		// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
		Intent intent = new Intent(context, NotifyService.class);
		intent.putExtra(NotifyService.INTENT_NOTIFY, true);
		PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

		// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
        am.cancel(pendingIntent);
		am.setRepeating(AlarmManager.RTC, date.getTimeInMillis(), 1000*60*60*24, pendingIntent);
    }

    public static void cancel(Context context)
    {
        Intent intent = new Intent(context, NotifyService.class);
        intent.putExtra(NotifyService.INTENT_NOTIFY, true);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(pendingIntent);
    }
}


text:
package integration

import (
	"encoding/base64"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

	"github.com/golang/glog"
	"github.com/gorilla/context"
)

type User struct {
	ID       string
	Password string
	Name     string
	Email    string
}

type BasicAuthChallenger struct {
	realm                string
	users                map[string]User
	authenticatedHandler http.Handler
}

// NewBasicAuthChallenger provides a simple basic auth server that is compatible with our basic auth password validator
func NewBasicAuthChallenger(realm string, users []User, authenticatedHandler http.Handler) BasicAuthChallenger {
	userMap := make(map[string]User, len(users))
	for _, user := range users {
		userMap[user.ID] = user
	}

	return BasicAuthChallenger{realm, userMap, authenticatedHandler}
}

func (challenger BasicAuthChallenger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	glog.Infof("--- %v\n", r.URL)

	authHeader := r.Header["Authorization"]
	if len(authHeader) == 0 {
		challenger.Challenge(w)
		return
	}

	auth := strings.SplitN(authHeader[0], " ", 2)
	if len(auth) != 2 || auth[0] != "Basic" {
		Error("bad syntax", http.StatusBadRequest, w)
		return
	}

	payload, err := base64.StdEncoding.DecodeString(auth[1])
	if err != nil {
		Error("bad syntax", http.StatusBadRequest, w)
		return
	}

	pair := strings.SplitN(string(payload), ":", 2)
	if len(pair) != 2 {
		Error("bad syntax", http.StatusBadRequest, w)
		return
	}

	if !challenger.Validate(pair[0], pair[1]) {
		challenger.Challenge(w)
		return
	}

	context.Set(r, "username", challenger.users[pair[0]])

	challenger.authenticatedHandler.ServeHTTP(w, r)
}

func (challenger *BasicAuthChallenger) Challenge(w http.ResponseWriter) {
	glog.Infof("Sending challenge\n")

	w.Header().Set("WWW-Authenticate", "Basic realm=\""+challenger.realm+"\"")
	Error("Authorization failed", http.StatusUnauthorized, w)
}

func Error(message string, status int, w http.ResponseWriter) {
	glog.Infof("Writing error: %s\n", message)

	data := map[string]string{"error": message}
	json, _ := json.Marshal(data)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	io.WriteString(w, string(json))
}

func (challenger *BasicAuthChallenger) Validate(username, password string) bool {
	knownUser, exists := challenger.users[username]
	if !exists {
		return false
	}

	if knownUser.Password == password {
		glog.Infof("Validated user: %s\n", username)
		return true
	}

	glog.Infof("Rejected user: %s\n", username)
	return false
}

type identifyingHandler struct {
}

func (handler *identifyingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user := context.Get(r, "username")
	if user == nil {
		Error("No user found", http.StatusBadRequest, w)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	result, _ := json.Marshal(user)
	io.WriteString(w, string(result))
}

func NewIdentifyingHandler() http.Handler {
	return &identifyingHandler{}
}

type xRemoteUserProxyingHandler struct {
	proxier *httputil.ReverseProxy
}

func (handler *xRemoteUserProxyingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	user := context.Get(r, "username")
	if user == nil {
		Error("No user found", http.StatusBadRequest, w)
		return
	}

	r.Header.Add("X-Remote-User", user.(User).ID)
	handler.proxier.ServeHTTP(w, r)
}

func NewXRemoteUserProxyingHandler(rawURL string) http.Handler {
	parsedURL, _ := url.Parse(rawURL)
	proxier := httputil.NewSingleHostReverseProxy(parsedURL)
	// proxier.Transport = NewBasicAuthRoundTripper(http.DefaultTransport)
	return &xRemoteUserProxyingHandler{proxier}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Arsan Irianto
 * Date: 16/12/2015
 * Time: 23:51
 */

$sp = "{:retval = CALL PCDR_AREA_TRIP (@BULAN=:bulan,@TAHUN=:tahun)}";
$result = $conn->prepare($sp);

$retval = null;
$bulan = isset($_GET['cbo_month']) ? $_GET['cbo_month'] : "";
$tahun = isset($_GET['cbo_year']) ? $_GET['cbo_year'] : "";

$result->bindParam('retval', $retval, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, 4);
$result->bindParam('bulan', $bulan, PDO::PARAM_INT);
$result->bindParam('tahun', $tahun, PDO::PARAM_INT);

$result->execute();

// If the query returns a valid response, prepare the JSON string
if ($result) {
    // The `$arrData` array holds the chart attributes and data
    $arrData = array(
        "chart" => array(
            "caption" => "Jumlah Gangguan Penyulang < 5 menit Per Area Dist",
            "bgColor" => "#ffffff",
            "borderAlpha"=> "20",
            "canvasBorderAlpha"=> "0",
            "usePlotGradientColor"=> "0",
            "plotBorderAlpha"=> "10",
            "showXAxisLine"=> "1",
            "xAxisLineColor" => "#999999",
            "showValues" => "0",
            "divlineColor" => "#999999",
            "divLineIsDashed" => "1",
            "showAlternateHGridColor" => "0"
        )
    );

    $arrData["data"] = array();

    // Push the data into the array
    while( $row = $result->fetch() ) {
        array_push($arrData["data"], array(
                "label" => $row["AREA"],
                "value" => $row["TEMPORER"],
				"link"  => "P-detailsWin,width=1100,height=500,toolbar=no,scrollbars=yes, resizable=no-modules/charts_details.php?modules=xttarea"."&areaid=".$row["AREAID"]."&giid=&bulan=".$bulan."&tahun=".$tahun."&kodefgtm=&lama=2&relay="
            )
        );
    }

    /*JSON Encode the data to retrieve the string containing the JSON representation of the data in the array. */

    $jsonEncodedData = json_encode($arrData);

    /*Create an object for the column chart using the FusionCharts PHP class constructor. Syntax for the constructor is ` FusionCharts("type of chart", "unique chart id", width of the chart, height of the chart, "div id to render the chart", "data format", "data source")`. Because we are using JSON data to render the chart, the data format will be `json`. The variable `$jsonEncodeData` holds all the JSON data for the chart, and will be passed as the value for the data source parameter of the constructor.*/

    $columnChart = new FusionCharts("column2D", "myFirstChart" , 700, 350, "chartContainer", "json", $jsonEncodedData);

    // Render the chart
    $columnChart->render();

    // Close the database connection
    $conn = null;
}
?>

<title> Kali Trip Temporer</title>

            Grafik Per Area
            Kali Trip Temporer

 Grafik Per Area

Kali Trip Temporer

Monthly Report

                                    <form name="period" id="period" method="get" >
                                        <input type="hidden" name="modules" id="modules" value="xtt_area">
                                        <?php
                                        echo combonamabln(1, 12, "cbo_month", "-Month-","form-control input-sm");
                                        ?>

                                    <?php
                                    echo combothn(2013, date("Y"), "cbo_year", "-Year-","form-control input-sm")
                                    ?>

                                </form>


text:
package org.apache.flink.table.planner.plan.nodes.physical.batch

import org.apache.flink.table.functions.UserDefinedFunction
import org.apache.flink.table.planner.expressions.PlannerNamedWindowProperty
import org.apache.flink.table.planner.plan.cost.{FlinkCost, FlinkCostFactory}
import org.apache.flink.table.planner.plan.logical.LogicalWindow

import org.apache.calcite.plan.{RelOptCluster, RelOptCost, RelOptPlanner, RelTraitSet}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rel.core.AggregateCall
import org.apache.calcite.rel.metadata.RelMetadataQuery

/** Batch physical RelNode for sort-based window aggregate. */
abstract class BatchPhysicalSortWindowAggregateBase(
    cluster: RelOptCluster,
    traitSet: RelTraitSet,
    inputRel: RelNode,
    outputRowType: RelDataType,
    grouping: Array[Int],
    auxGrouping: Array[Int],
    aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
    window: LogicalWindow,
    namedProperties: Seq[PlannerNamedWindowProperty],
    enableAssignPane: Boolean = false,
    isMerge: Boolean,
    isFinal: Boolean)
  extends BatchPhysicalWindowAggregateBase(
    cluster,
    traitSet,
    inputRel,
    outputRowType,
    grouping,
    auxGrouping,
    aggCallToAggFunction,
    window,
    namedProperties,
    enableAssignPane,
    isMerge,
    isFinal) {

  override def computeSelfCost(planner: RelOptPlanner, mq: RelMetadataQuery): RelOptCost = {
    val inputRowCnt = mq.getRowCount(getInput)
    if (inputRowCnt == null) {
      return null
    }
    // does not take pane optimization into consideration here
    // sort is not done here
    val cpu = FlinkCost.FUNC_CPU_COST * inputRowCnt * aggCallToAggFunction.size
    val averageRowSize: Double = mq.getAverageRowSize(this)
    val memCost = averageRowSize
    val costFactory = planner.getCostFactory.asInstanceOf[FlinkCostFactory]
    costFactory.makeCost(mq.getRowCount(this), cpu, 0, 0, memCost)
  }
}


text:
'use strict';

const file = require('../helpers/file');
var blueprintHelpers = require('ember-cli-blueprint-test-helpers/helpers');
var setupTestHooks = blueprintHelpers.setupTestHooks;
var emberNew = blueprintHelpers.emberNew;
var emberGenerateDestroy = blueprintHelpers.emberGenerateDestroy;

var chai = require('ember-cli-blueprint-test-helpers/chai');
var expect = chai.expect;

describe('Acceptance: ember generate and destroy helper-addon', function() {
  setupTestHooks(this);

  it('in-addon helper-addon foo/bar-baz', function() {
    var args = ['helper-addon', 'foo/bar-baz'];

    return emberNew({ target: 'addon' })
      .then(() => emberGenerateDestroy(args, _file => {
        expect(_file('app/helpers/foo/bar-baz.js'))
          .to.equal(file('helper-addon.js'));
      }));
  });
});


text:
using Xunit;

namespace System.Runtime.InteropServices
{
    public static class HandleCollectorTests
    {
        private const int LowLimitSize = 20;
        private const int HighLimitSize = 100000;

        [Fact]
        public static void NegativeInitialThresholdCtor()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new HandleCollector("NegativeInitial", -1));
        }

        [Fact]
        public static void NegateMaximumThresholdCtor()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => new HandleCollector("NegativeMax", 0, -1));
        }

        [Fact]
        public static void InitialGreaterThanMaxThresholdCtor()
        {
            Assert.Throws<ArgumentException>(() => new HandleCollector("InitialGreaterThanMax", 100, 1));
        }

        [Fact]
        public static void SimplePropertyValidation()
        {
            string name = "ExampleName";
            int initial = 10;
            int max = 20;

            HandleCollector collector = new HandleCollector(name, initial, max);

            Assert.Equal(0, collector.Count);
            Assert.Equal(name, collector.Name);
            Assert.Equal(initial, collector.InitialThreshold);
            Assert.Equal(max, collector.MaximumThreshold);
        }

        [Fact]
        public static void NullNameCtor()
        {
            HandleCollector collector = new HandleCollector(null, 0, 0);
            Assert.Equal(string.Empty, collector.Name);
        }

        [Fact]
        public static void EmptyRemoval()
        {
            HandleCollector collector = new HandleCollector("EmptyRemoval", 10);
            Assert.Throws<InvalidOperationException>(() => collector.Remove());
        }

        [Fact]
        [OuterLoop]
        public static void CountOverflow()
        {
            HandleCollector collector = new HandleCollector("CountOverflow", int.MaxValue);
            for (int i = 0; i < Int32.MaxValue; i++)
            {
                collector.Add();
            }

            Assert.Throws<InvalidOperationException>(() => collector.Add());
        }

        [Fact]
        public static void TestHandleCollector()
        {
            Tuple<int, int, int> intialGcState = new Tuple<int, int, int>(
                GC.CollectionCount(0),
                GC.CollectionCount(1),
                GC.CollectionCount(2));

            HandleCollector lowLimitCollector = new HandleCollector("LowLimit.Collector", LowLimitSize);
            for (int i = 0; i < LowLimitSize + 1; ++i)
            {
                HandleLimitTester hlt = new HandleLimitTester(lowLimitCollector);
            }

            Tuple<int, int, int> postLowLimitState = new Tuple<int, int, int>(
                GC.CollectionCount(0),
                GC.CollectionCount(1),
                GC.CollectionCount(2));

            Assert.True(intialGcState.Item1 + intialGcState.Item2 + intialGcState.Item3 < postLowLimitState.Item1 + postLowLimitState.Item2 + postLowLimitState.Item3, "Low limit handle did not trigger a GC");

            HandleCollector highLimitCollector = new HandleCollector("HighLimit.Collector", HighLimitSize);
            for (int i = 0; i < HighLimitSize + 10; ++i)
            {
                HandleLimitTester hlt = new HandleLimitTester(highLimitCollector);
            }

            Tuple<int, int, int> postHighLimitState = new Tuple<int, int, int>(
                GC.CollectionCount(0),
                GC.CollectionCount(1),
                GC.CollectionCount(2));

            Assert.True(postLowLimitState.Item1 + postLowLimitState.Item2 + postLowLimitState.Item3 < postHighLimitState.Item1 + postHighLimitState.Item2 + postHighLimitState.Item3, "High limit handle did not trigger a GC");
        }

        private sealed class HandleLimitTester
        {
            private HandleCollector _collector;

            internal HandleLimitTester(HandleCollector collector)
            {
                _collector = collector;
                _collector.Add();
                GC.KeepAlive(this);
            }

            ~HandleLimitTester()
            {
                _collector.Remove();
            }
        }
    }
}


text:
namespace SecureAuth.Admin.Sdk
{
    public class MultifactorRequest : BaseRequest
    {
        public Models.MultiFactor MultiFactor { get; set; }

        public MultifactorRequest()
        {
            MultiFactor = new Models.MultiFactor();
        }
    }
}


text:
//Using bitwise operators, write an expression for finding the value of the bit #3 of a given unsigned integer.
//The bits are counted from right to left, starting from bit #0.
//The result of the expression should be either 1 or 0.

using System;

class bitExtraktor
{
    static void Main()
    {
        int number = int.Parse(Console.ReadLine());

        number = number >> 3;
        number = number & 1;

        Console.WriteLine(number);
    }
}


text:
import boto3
import http.client
import json

from .api_auth import ApiAuth
from alexa.skills.smarthome import AlexaResponse
from botocore.exceptions import ClientError
from datetime import datetime, timedelta

dynamodb_aws = boto3.client('dynamodb')
iot_aws = boto3.client('iot')

class ApiHandlerEvent:
    def create(self, request):
        print("LOG event.create.request:", request)

        try:
            json_object = json.loads(request['body'])
            endpoint_user_id = json_object['event']['endpoint']['userId']  # Expect a Profile
            endpoint_name = json_object['event']['endpoint']['id']  # Expect a valid AWS IoT Thing Name
            endpoint_state = json_object['event']['endpoint']['state']  # Expect a state value, ex: ON or OFF
            sku = json_object['event']['endpoint']['sku']  # Expect a meaningful type, ex: SW00

            try:
                # Update the IoT Thing
                response = iot_aws.update_thing(
                    thingName=endpoint_name,
                    attributePayload={
                        'attributes': {
                            'state': endpoint_state,
                            'proactively_reported': 'True',
                            'user_id': endpoint_user_id
                        }
                    }
                )
                print('LOG event.create.iot_aws.update_thing.response:', str(response))

                # Update Alexa with a Proactive State Update
                if endpoint_user_id == 0:
                    print('LOG PSU: Not sent for user_id of 0')
                else:
                    response_psu = self.send_psu(endpoint_user_id, endpoint_name, endpoint_state)
                    print('LOG PSU response:', response_psu)

            except ClientError as e:
                alexa_response = AlexaResponse(name='ErrorResponse', message=e)
                alexa_response.set_payload(
                    {
                        'type': 'INTERNAL_ERROR',
                        'message': e
                    }
                )
                response = alexa_response.get()

            return response

        except KeyError as key_error:
            return "KeyError: " + str(key_error)

    def is_token_expired(self, expiration_utc):
        now = datetime.utcnow().replace(tzinfo=None)
        then = datetime.strptime(expiration_utc, "%Y-%m-%dT%H:%M:%S.00Z")
        is_expired = now > then
        if is_expired:
            return is_expired
        seconds = (now - then).seconds
        is_soon = seconds < 30  # Give a 30 second buffer for expiration
        return is_soon

    def send_psu(self, endpoint_user_id, endpoint_id, endpoint_state):

        # Get the User Information
        table = boto3.resource('dynamodb').Table('SampleUsers')
        result = table.get_item(
            Key={
                'UserId': endpoint_user_id
            },
            AttributesToGet=[
                'UserId',
                'AccessToken',
                'ClientId',
                'ClientSecret',
                'ExpirationUTC',
                'RedirectUri',
                'RefreshToken',
                'TokenType'
            ]
        )

        if result['ResponseMetadata']['HTTPStatusCode'] == 200:
            print('LOG event.create.send_psu.SampleUsers.get_item:', str(result))

            if 'Item' in result:
                expiration_utc = result['Item']['ExpirationUTC']
                token_is_expired = self.is_token_expired(expiration_utc)
                print('LOG event.create.send_psu.token_is_expired:', token_is_expired)
                if token_is_expired:
                    # The token has expired so get a new access token using the refresh token
                    refresh_token = result['Item']['RefreshToken']
                    client_id = result['Item']['ClientId']
                    client_secret = result['Item']['ClientSecret']
                    redirect_uri = result['Item']['RedirectUri']

                    api_auth = ApiAuth()
                    response_refresh_token = api_auth.refresh_access_token(refresh_token, client_id, client_secret,
                                                                           redirect_uri)
                    response_refresh_token_string = response_refresh_token.read().decode('utf-8')
                    response_refresh_token_object = json.loads(response_refresh_token_string)

                    # Store the new values from the refresh
                    access_token = response_refresh_token_object['access_token']
                    refresh_token = response_refresh_token_object['refresh_token']
                    token_type = response_refresh_token_object['token_type']
                    expires_in = response_refresh_token_object['expires_in']

                    # Calculate expiration
                    expiration_utc = datetime.utcnow() + timedelta(seconds=(int(expires_in) - 5))

                    print('access_token', access_token)
                    print('expiration_utc', expiration_utc)

                    result = table.update_item(
                        Key={
                            'UserId': endpoint_user_id
                        },
                        UpdateExpression="set AccessToken=:a, RefreshToken=:r, TokenType=:t, ExpirationUTC=:e",
                        ExpressionAttributeValues={
                            ':a': access_token,
                            ':r': refresh_token,
                            ':t': token_type,
                            ':e': expiration_utc.strftime("%Y-%m-%dT%H:%M:%S.00Z")
                        },
                        ReturnValues="UPDATED_NEW"
                    )
                    print('LOG event.create.send_psu.SampleUsers.update_item:', str(result))

                    # TODO Return an error here if the token could not be refreshed
                else:
                    # Use the stored access token
                    access_token = result['Item']['AccessToken']
                    print('LOG Using stored access_token:', access_token)

                alexa_changereport_response = AlexaResponse(name='ChangeReport', endpoint_id=endpoint_id, token=access_token)
                alexa_changereport_response.set_payload(
                    {
                        'change': {
                            'cause': {
                                'type': 'PHYSICAL_INTERACTION'
                            },
                            "properties": [
                                alexa_changereport_response.create_property(namespace='Alexa.PowerController', name='powerState', value='ON')
                            ]
                        }
                    }
                )
                payload = json.dumps(alexa_changereport_response.get())
                print('LOG AlexaChangeReport.get_response:', payload)

                # TODO Map to correct endpoint for Europe: https://api.eu.amazonalexa.com/v3/events
                # TODO Map to correct endpoint for Far East: https://api.fe.amazonalexa.com/v3/events
                alexa_event_gateway_uri = 'api.amazonalexa.com'
                connection = http.client.HTTPSConnection(alexa_event_gateway_uri)
                headers = {
                    'content-type': "application/json;charset=UTF-8",
                    'cache-control': "no-cache"
                }
                connection.request('POST', '/v3/events', payload, headers)
                code = connection.getresponse().getcode()
                return 'LOG PSU HTTP Status code: ' + str(code)


text:
namespace Nest {
    public interface IElasticPropertyAttribute
    {
        bool AddSortField { get; set; }

        bool OptOut { get; set; }
        string Name { get; set; }

        FieldType Type { get; }

        TermVectorOption TermVector { get; set; }
        FieldIndexOption Index { get; set; }

        double Boost { get; set; }

        string Analyzer { get; set; }
        string IndexAnalyzer { get; set; }
        string SearchAnalyzer { get; set; }
        string SortAnalyzer { get; set; }
        string NullValue { get; set; }

        bool OmitNorms { get; set; }
        bool OmitTermFrequencyAndPositions { get; set; }
        bool IncludeInAll { get; set; }
        bool Store { get; set; }

        string Similarity { get; set; }

        /// <summary>
        /// Defaults to float so be sure to set this correctly!
        /// </summary>
        NumericType NumericType { get; set; }
        int PrecisionStep { get; set; }

        /// <summary>
        /// http://www.elasticsearch.org/guide/reference/mapping/date-format.html
        /// </summary>
        string DateFormat { get; set; }

        void Accept(IElasticPropertyVisitor visitor);
    }
}


text:
require 'spec_helper'

describe Whois::Client do

  describe "#initialize" do
    it "accepts a zero parameters" do
      lambda { described_class.new }.should_not raise_error
    end

    it "accepts a settings parameter" do
      lambda { described_class.new({ :foo => "bar" }) }.should_not raise_error
    end

    it "accepts a timeout setting with a value in seconds" do
      client = described_class.new(:timeout => 100)
      client.timeout.should == 100
    end

    it "accepts a timeout setting with a nil value" do
      client = described_class.new(:timeout => nil)
      client.timeout.should be_nil
    end

    it "accepts a block" do
      described_class.new do |client|
        client.should be_instance_of(described_class)
      end
    end

    it "defaults timeout setting to DEFAULT_TIMEOUT" do
      client = described_class.new
      client.timeout.should == described_class::DEFAULT_TIMEOUT
    end

    it "sets settings to given argument, except timeout" do
      client = described_class.new(:timeout => nil, :foo => "bar")
      client.settings.should == { :foo => "bar" }
    end
  end

  describe "#lookup" do
    it "converts the argument to string" do
      query = ["example", ".", "test"]
      query.instance_eval do
        def to_s
          join
        end
      end

      server = Whois::Server::Adapters::Base.new(:tld, ".test", "whois.test")
      server.expects(:lookup).with("example.test")
      Whois::Server.expects(:guess).with("example.test").returns(server)

      described_class.new.lookup(query)
    end

    it "converts the argument to downcase" do
      server = Whois::Server::Adapters::Base.new(:tld, ".test", "whois.test")
      server.expects(:lookup).with("example.test")
      Whois::Server.expects(:guess).with("example.test").returns(server)

      described_class.new.lookup("Example.TEST")
    end

    it "detects email" do
      expect {
        described_class.new.lookup("weppos@weppos.net")
      }.to raise_error(Whois::ServerNotSupported)
    end

    it "works with domain with no whois" do
      Whois::Server.define(:tld, ".nowhois", nil, :adapter => Whois::Server::Adapters::None)

      expect {
        described_class.new.lookup("domain.nowhois")
      }.to raise_error(Whois::NoInterfaceError, /no whois server/)
    end

    it "works with domain with web whois" do
      Whois::Server.define(:tld, ".webwhois", nil, :adapter => Whois::Server::Adapters::Web, :url => "http://www.example.com/")

      expect {
        described_class.new.lookup("domain.webwhois")
      }.to raise_error(Whois::WebInterfaceError, /www\.example\.com/)
    end

    it "raises if timeout is exceeded" do
      adapter = Class.new(Whois::Server::Adapters::Base) do
        def lookup(*)
          sleep(2)
        end
      end
      Whois::Server.expects(:guess).returns(adapter.new(:tld, ".test", "whois.test"))

      client = described_class.new(:timeout => 1)
      expect {
        client.lookup("example.test")
      }.to raise_error(Timeout::Error)
    end

    it "does not raise if timeout is not exceeded" do
      adapter = Class.new(Whois::Server::Adapters::Base) do
        def lookup(*)
          sleep(1)
        end
      end
      Whois::Server.expects(:guess).returns(adapter.new(:tld, ".test", "whois.test"))

      client = described_class.new(:timeout => 5)
      expect {
        client.lookup("example.test")
      }.to_not raise_error
    end

    it "supports unlimited timeout" do
      adapter = Class.new(Whois::Server::Adapters::Base) do
        def lookup(*)
          sleep(1)
        end
      end
      Whois::Server.expects(:guess).returns(adapter.new(:tld, ".test", "whois.test"))

      client = described_class.new.tap { |c| c.timeout = nil }
      expect {
        client.lookup("example.test")
      }.to_not raise_error
    end

  end

  # FIXME: use RSpec metadata
  need_connectivity do
    describe "#query" do
      it "sends a query for given domain" do
        record = described_class.new.lookup("weppos.it")
        assert record.match?(/Domain:\s+weppos\.it/)
        assert record.match?(/Created:/)
      end
    end
  end

end


text:
package bits.hidpunk.osx;

import bits.hidpunk.HidException;

/**
 * This class has a weird referencing inversion thing going, so be careful.
 * ref() and deref() calls on this object are actually given to the member
 * CFLoopSource object, mSource. When mSource is freed, it will call deref() on
 * a special object, "SuperRef", which will actually dereference the
 * OsxNotificationPort. What this accomplishes is that, as long as anything owns
 * a reference to either the OsxNotificationPort or the CFLoopSource, they will
 * both be valid. However, the CFLoopSource is then guaranteed to be free itself
 * before the notification port, ensuring that a run loop thread is not
 * accessing the notification port while a different thread disposes the port.
 *
 * @author Philip DeCamp
 */
class CFNotificationSource extends CFLoopSource {

    public static CFNotificationSource create( long masterPort ) throws HidException {
        long portPtr = 0;
        long sourcePtr = 0;
        boolean aborted = true;

        try {
            portPtr = createPort( masterPort );
            if( portPtr == 0 ) {
                throw new IOKitException( "Failed to create notification port." );
            }

            sourcePtr = getLoopSource( portPtr );
            if( sourcePtr == 0 ) {
                throw new IOKitException( "Failed to retreive RunLoopSource for NotificationPort." );
            }

            CFNotificationSource port = new CFNotificationSource( portPtr, sourcePtr );
            aborted = false;
            return port;

        } finally {
            if( aborted ) {
                if( sourcePtr != 0 ) {
                    try {
                        new CFRef( sourcePtr ).deref();
                    } catch( Exception ex ) {
                        ex.printStackTrace();
                    }
                }

                if( portPtr != 0 ) {
                    try {
                        destroyPort( portPtr );
                    } catch( Exception ex ) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    private final long mPortPtr;

    private CFNotificationSource( long portPtr, long sourcePtr ) throws HidException {
        super( sourcePtr );
        mPortPtr = portPtr;
    }

    public long portPointer() {
        return mPortPtr;
    }

    @Override
    protected void freeObject() {
        try {
            super.freeObject();
        } catch( Exception ex ) {
            ex.printStackTrace();
        }

        try {
            destroyPort( mPortPtr );
        } catch( Exception ex ) {
            ex.printStackTrace();
        }
    }

    private static native long createPort( long masterPort ) throws HidException;

    private static native void destroyPort( long portPtr ) throws HidException;

    /**
     * Calls CFRetain on pointer before returning.
     */
    private static native long getLoopSource( long portPtr ) throws HidException;

}


text:
<BrowseNodeLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <RequestId>0CT7934ZQKSMBVDMDEZN</RequestId>
    <RequestProcessingTime>0.00394606590270996</RequestProcessingTime>
  </OperationRequest>
  <BrowseNodes>
    <Request>
      <IsValid>False</IsValid>
      <Errors>
        <Error>
          AWS.InvalidResponseGroup
          <Message>Your ResponseGroup parameter is invalid. Valid response groups for  requests include Request, BrowseNodeInfo, TopSellers, NewReleases, MostWishedFor, MostGifted.</Message>
        </Error>
        <Error>
          AWS.InvalidEnumeratedParameter
          <Message>The value you specified for ResponseGroup is invalid. Valid values include BrowseNodeInfo, MostGifted, MostWishedFor, NewReleases, Request, TopSellers.</Message>
        </Error>
      </Errors>
    </Request>
  </BrowseNodes>
</BrowseNodeLookupResponse>


text:
package io.crate.udc.service;

import io.crate.ClusterIdService;
import io.crate.udc.ping.PingTask;
import io.crate.udc.plugin.UDCPlugin;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.inject.Provider;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.node.service.NodeService;

import java.util.Timer;

public class UDCService extends AbstractLifecycleComponent<UDCService> {

    private final Timer timer;

    private final ClusterService clusterService;
    private final Provider<ClusterIdService> clusterIdServiceProvider;
    private final NodeService nodeService;

    @Inject
    public UDCService(Settings settings,
                      NodeService nodeService, ClusterService clusterService,
                      Provider<ClusterIdService> clusterIdServiceProvider) {
        super(settings);
        this.nodeService = nodeService;
        this.clusterService = clusterService;
        this.clusterIdServiceProvider = clusterIdServiceProvider;
        this.timer = new Timer("crate-udc");
    }

    @Override
    protected void doStart() throws ElasticsearchException {
        String url = settings.get(UDCPlugin.URL_SETTING_NAME, UDCPlugin.URL_DEFAULT_SETTING);
        TimeValue initialDelay = settings.getAsTime(UDCPlugin.INITIAL_DELAY_SETTING_NAME, UDCPlugin.INITIAL_DELAY_DEFAULT_SETTING);
        TimeValue interval = settings.getAsTime(UDCPlugin.INTERVAL_SETTING_NAME, UDCPlugin.INTERVAL_DEFAULT_SETTING);

        if (logger.isDebugEnabled()) {
            logger.debug("Starting with delay {} and period {}.", initialDelay.getSeconds(), interval.getSeconds());
        }
        PingTask pingTask = new PingTask(clusterService, clusterIdServiceProvider.get(), nodeService, url);
        timer.scheduleAtFixedRate(pingTask, initialDelay.millis(), interval.millis());
    }

    @Override
    protected void doStop() throws ElasticsearchException {
        timer.cancel();
    }

    @Override
    protected void doClose() throws ElasticsearchException {
        timer.cancel(); // safety net, in case of unlikely weirdness
    }
}


text:
import kivy
kivy.require('1.7.1')

from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout

class SayThis(BoxLayout):
    saywhat_text = ObjectProperty(None)

    def clear(self):
        self.saywhat_text.text = ""
        self.saywhat_text.focus = True

class SayThisApp(App):
    def build(self):
        return SayThis()

if __name__ == '__main__':
    SayThisApp().run()


text:
/****************************************************************************
 *
 *   MODULE:  rxXfer_api.h
 *
 *   PURPOSE: Rx Xfer module API.
 *
 ****************************************************************************/

#ifndef _RX_XFER_API_H
#define _RX_XFER_API_H

#include "TWDriverInternal.h"

/* Public Function Definitions */

TI_HANDLE			rxXfer_Create(TI_HANDLE hOs);

void				rxXfer_Destroy(TI_HANDLE hRxXfer);

void				rxXfer_Init( TI_HANDLE hRxXfer,
								 TI_HANDLE hFwEvent,
								 TI_HANDLE hReport,
                                 TI_HANDLE hTwIf,
                                 TI_HANDLE hRxQueue);

void                rxXfer_SetDefaults (TI_HANDLE hRxXfer, TTwdInitParams *pInitParams);

void                rxXfer_SetBusParams (TI_HANDLE hRxXfer, TI_UINT32 uDmaBufLen);

ETxnStatus           rxXfer_RxEvent (TI_HANDLE hRxXfer, FwStatus_t* pFwStatus);

void				rxXfer_Register_CB(TI_HANDLE hRxXfer,TI_UINT32 CallBackID,void *CBFunc,TI_HANDLE CBObj);

void                rxXfer_SetRxDirectAccessParams (TI_HANDLE hRxXfer, TDmaParams *pDmaParams);

void                rxXfer_RegisterErrCb (TI_HANDLE hRxXfer, void *fErrCb, TI_HANDLE hErrCb);

void                rxXfer_Restart (TI_HANDLE hRxXfer);

#ifdef TI_DBG

void rxXfer_ClearStats( TI_HANDLE hRxXfer );

void rxXfer_PrintStats( TI_HANDLE hRxXfer );

#endif /* TI_DBG */

#endif /* _RX_XFER_API_H */


text:
package com.mohammedsazid.android.browse;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.pressImeActionButton;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class WebsiteVisitTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void websiteVisitTest() {
        ViewInteraction appCompatAutoCompleteTextView = onView(
                allOf(withId(R.id.addressBar_et), isDisplayed()));
        appCompatAutoCompleteTextView.perform(replaceText("google.com"), closeSoftKeyboard());

        ViewInteraction appCompatAutoCompleteTextView2 = onView(
                allOf(withId(R.id.addressBar_et), withText("google.com"), isDisplayed()));
        appCompatAutoCompleteTextView2.perform(pressImeActionButton());

        ViewInteraction textView = onView(
                allOf(withId(R.id.title_tv), withText("Google"),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.bottom_bar),
                                        1),
                                1),
                        isDisplayed()));
        textView.check(matches(withText("Google")));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}


text:
package patio.infrastructure.email.services;

import patio.infrastructure.email.domain.Email;

/**
 * Represents the actions available in an email service
 *
 * @since 0.1.0
 */
public interface EmailService {

  /**
   * Sends the email passed as parameter
   *
   * @param email an instance of type {@link Email}
   * @since 0.1.0
   */
  void send(Email email);
}


text:
<?php

// ***************** Config entries below ***********************

// IPs are enterable as individual addresses TODO: add CIDR support
$allowedIPs = array("192.168.1.55", "12.2.2.2");

# format is "username" => "password"
# password is generated using sha1sum as shown below (don't forget the -n, KEVIN!)
# echo -n  Password1 | sha1sum
$users = array("kevin" => "b441ac06613fc8d63795be9ad0beaf55011936ac", "tim" => "a94a1fe5ccb19ba61c4c0873d391e987982fbbd3", "yomamma" => "a94a1fe5ccb19ba61c4c0873d391e987982fbbd3");

# *********** No editable content below this line **************

$allowed = 0;
foreach ($allowedIPs as $IP) {
    if ($_SERVER["REMOTE_ADDR"] == $IP)
        $allowed = 1;
}

if ($allowed == 0) {
    header("HTTP/1.0 404 Not Found");
    die();
}

/* This error handler will turn all notices, warnings, and errors into fatal
 * errors, unless they have been suppressed with the @-operator. */
function error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    /* The @-opertor (used with chdir() below) temporarely makes
     * error_reporting() return zero, and we don't want to die in that case.
     * We do note the error in the output, though. */
    if (error_reporting() == 0) {
        $_SESSION['output'] .= $errstr . "\n";
    } else {
        die('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

  <title>Laudanum PHP Shell Access</title>

Fatal Error!

' . $errstr . '

in ' . $errfile . ', line ' . $errline . '.

  <address>
  Copyright © 2012, Kevin Johnson and the Laudanum team.

  Get the latest version at laudanum.secureideas.net.
  </address>

');
    }
}

set_error_handler('error_handler');

function logout() {
    $_SESSION = array('authenticated' => false);
    if (isset($_COOKIE[session_name()]))
        setcookie(session_name(), '', time()-42000, '/');
    session_destroy();
}

function stripslashes_deep($value) {
    if (is_array($value))
        return array_map('stripslashes_deep', $value);
    else
        return stripslashes($value);
}

if (get_magic_quotes_gpc())
    $_POST = stripslashes_deep($_POST);

/* Initialize some variables we need again and again. */
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$nounce   = isset($_POST['nounce'])   ? $_POST['nounce']   : '';

$command  = isset($_POST['command'])  ? $_POST['command']  : '';
$rows     = isset($_POST['rows'])     ? $_POST['rows']     : 24;
$columns  = isset($_POST['columns'])  ? $_POST['columns']  : 80;

///* Default settings --- these settings should always be set to something. */
//$default_settings = array('home-directory'   => '.');

///* Merge settings. */
//$ini['settings'] = array_merge($default_settings, $ini['settings']);

session_start();

/* Delete the session data if the user requested a logout.  This leaves the
 * session cookie at the user, but this is not important since we
 * authenticates on $_SESSION['authenticated']. */
if (isset($_POST['logout']))
    logout();

///* Attempt authentication. */
//if (isset($_SESSION['nounce']) && $nounce == $_SESSION['nounce'] &&
//    isset($ini['users'][$username])) {
//    if (strchr($ini['users'][$username], ':') === false) {
//        // No seperator found, assume this is a password in clear text.
//        $_SESSION['authenticated'] = ($ini['users'][$username] == $password);
//    } else {
//        list($fkt, $salt, $hash) = explode(':', $ini['users'][$username]);
//        $_SESSION['authenticated'] = ($fkt($salt . $password) == $hash);
//    }
//}

/* Attempt authentication. */
if (isset($_SESSION['nounce']) && $nounce == $_SESSION['nounce'] && isset($users[$username]))
    $_SESSION['authenticated'] = ($users[$username] == hash("sha1", $password));

/* Enforce default non-authenticated state if the above code didn't set it
 * already. */
if (!isset($_SESSION['authenticated']))
    $_SESSION['authenticated'] = false;

if ($_SESSION['authenticated']) {
    /* Initialize the session variables. */
    if (empty($_SESSION['cwd'])) {
        $_SESSION['cwd'] = '.';
        $_SESSION['history'] = array();
        $_SESSION['output'] = '';
    }

    if (!empty($command)) {
        /* Save the command for late use in the JavaScript.  If the command is
         * already in the history, then the old entry is removed before the
         * new entry is put into the list at the front. */
        if (($i = array_search($command, $_SESSION['history'])) !== false)
            unset($_SESSION['history'][$i]);

        array_unshift($_SESSION['history'], $command);

        /* Now append the commmand to the output. */
        $_SESSION['output'] .= '$ ' . $command . "\n";

        /* Initialize the current working directory. */
        if (preg_match('/^[[:blank:]]*cd[[:blank:]]*$/', $command)) {
            $_SESSION['cwd'] = realpath($ini['settings']['home-directory']);
        } elseif (preg_match('/^[[:blank:]]*cd[[:blank:]]+([^;]+)$/', $command, $regs)) {
            /* The current command is a 'cd' command which we have to handle
             * as an internal shell command. */

            if ($regs[1]{0} == '/') {
                /* Absolute path, we use it unchanged. */
                $new_dir = $regs[1];
            } else {
                /* Relative path, we append it to the current working
                 * directory. */
                $new_dir = $_SESSION['cwd'] . '/' . $regs[1];
            }

            /* Transform '/./' into '/' */
            while (strpos($new_dir, '/./') !== false)
                $new_dir = str_replace('/./', '/', $new_dir);

            /* Transform '//' into '/' */
            while (strpos($new_dir, '//') !== false)
                $new_dir = str_replace('//', '/', $new_dir);

            /* Transform 'x/..' into '' */
            while (preg_match('|/\.\.(?!\.)|', $new_dir))
                $new_dir = preg_replace('|/?[^/]+/\.\.(?!\.)|', '', $new_dir);

            if ($new_dir == '') $new_dir = '/';

            /* Try to change directory. */
            if (@chdir($new_dir)) {
                $_SESSION['cwd'] = $new_dir;
            } else {
                $_SESSION['output'] .= "cd: could not change to: $new_dir\n";
            }

        } elseif (trim($command) == 'exit') {
            logout();
        } else {

            /* The command is not an internal command, so we execute it after
             * changing the directory and save the output. */
            chdir($_SESSION['cwd']);

            // We canot use putenv() in safe mode.
            if (!ini_get('safe_mode')) {
                // Advice programs (ls for example) of the terminal size.
                putenv('ROWS=' . $rows);
                putenv('COLUMNS=' . $columns);
            }

            /* Alias expansion. */
            $length = strcspn($command, " \t");
            $token = substr($command, 0, $length);
            if (isset($ini['aliases'][$token]))
                $command = $ini['aliases'][$token] . substr($command, $length);

            $io = array();
            $p = proc_open($command,
                           array(1 => array('pipe', 'w'),
                                 2 => array('pipe', 'w')),
                           $io);

            /* Read output sent to stdout. */
            while (!feof($io[1])) {
                $_SESSION['output'] .= htmlspecialchars(fgets($io[1]),
                                                        ENT_COMPAT, 'UTF-8');
            }
            /* Read output sent to stderr. */
            while (!feof($io[2])) {
                $_SESSION['output'] .= htmlspecialchars(fgets($io[2]),
                                                        ENT_COMPAT, 'UTF-8');
            }

            fclose($io[1]);
            fclose($io[2]);
            proc_close($p);
        }
    }

    /* Build the command history for use in the JavaScript */
    if (empty($_SESSION['history'])) {
        $js_command_hist = '""';
    } else {
        $escaped = array_map('addslashes', $_SESSION['history']);
        $js_command_hist = '"", "' . implode('", "', $escaped) . '"';
    }
}

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

  <title>Laudanum Shell</title>
  <link rel="stylesheet" href="style.css" type="text/css">

Laudanum Shell

<form name="shell" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">

<?php
if (!$_SESSION['authenticated']) {
    /* Genereate a new nounce every time we preent the login page.  This binds
     * each login to a unique hit on the server and prevents the simple replay
     * attack where one uses the back button in the browser to replay the POST
     * data from a login. */
    $_SESSION['nounce'] = mt_rand();

?>

<fieldset>
  <legend>Authentication</legend>

  <?php
  if (!empty($username))
      echo '
Login failed, please try again:
' . "\n";
  else
      echo "
Please login:
\n";
  ?>

Username: <input name="username" type="text" value="<?php echo $username
  ?>">

Password: <input name="password" type="password">

<input type="submit" value="Login">

  <input name="nounce" type="hidden" value="<?php echo $_SESSION['nounce']; ?>">

</fieldset>

<?php } else { /* Authenticated. */ ?>

<fieldset>
  <legend>Current Working Directory: <?php
     echo  htmlspecialchars($_SESSION['cwd'], ENT_COMPAT, 'UTF-8');
    ?></legend>

<textarea name="output" readonly="readonly" cols="<?php echo $columns ?>" rows="<?php echo $rows ?>">
<?php
$lines = substr_count($_SESSION['output'], "\n");
$padding = str_repeat("\n", max(0, $rows+1 - $lines));
echo rtrim($padding . $_SESSION['output']);
?>
</textarea>

  $ <input name="command" type="text"
                onkeyup="key(event)" size="<?php echo $columns-2 ?>" tabindex="1">

  Size: <input type="text" name="rows" size="2"
  maxlength="3" value="<?php echo $rows ?>"> × <input type="text"
  name="columns" size="2" maxlength="3" value="<?php echo $columns
  ?>">

<input type="submit" value="Execute Command">
  <input type="submit" name="logout" value="Logout">

</fieldset>

<?php } ?>

</form>

  <address>
  Copyright © 2012, Kevin Johnson and the Laudanum team.

  Updated by Tim Medin.

  Get the latest version at laudanum.secureideas.net.
  </address>


text:
package org.mifos.application.personnel.util.helpers;

import org.mifos.framework.business.View;

/**
 * This obect denotes instance of search result, that will be obtained after
 * user search.
 */
public class UserSearchResultsView extends View {

    short officeId;

    String officeName;

    short personnelId;

    String globalPersonnelNum;

    String personnelName;

    public String getGlobalPersonnelNum() {
        return globalPersonnelNum;
    }

    public void setGlobalPersonnelNum(String globalPersonnelNum) {
        this.globalPersonnelNum = globalPersonnelNum;
    }

    public short getOfficeId() {
        return officeId;
    }

    public void setOfficeId(short officeId) {
        this.officeId = officeId;
    }

    public String getOfficeName() {
        return officeName;
    }

    public void setOfficeName(String officeName) {
        this.officeName = officeName;
    }

    public short getPersonnelId() {
        return personnelId;
    }

    public void setPersonnelId(short personnelId) {
        this.personnelId = personnelId;
    }

    public String getPersonnelName() {
        return personnelName;
    }

    public void setPersonnelName(String personnelName) {
        this.personnelName = personnelName;
    }
}


text:
from django.contrib.auth.models import User
from django.test import Client, TestCase
try:
    from django.core.urlresolvers import reverse
except ImportError:
    from django.urls import reverse

from app.models import TestModel

class AbstractTestCase(TestCase):
    def setUp(self):
        User.objects.create_superuser('user', 'email@test.com', 'password')
        self.client = Client()
        self.client.login(username='user', password='password')

    def assertMessage(self, response, message):
        messages = [m.message for m in response.context['messages']]
        error_text = 'Message "{0}" not found. Messages: {1}'.format(message,
                                                                     messages)
        self.assertTrue(message in messages, error_text)

class NoObjectsTestCase(AbstractTestCase):

    def test_can_add_new_model(self):
        response = self.client.get(reverse('admin:app_testmodel_add'),
                                   follow=True)
        self.assertEqual(response.status_code, 200)

    def test_changelist_redirects_to_add(self):
        response = self.client.get(reverse('admin:app_testmodel_changelist'),
                                   follow=True)
        self.assertRedirects(response, reverse('admin:app_testmodel_add'))

    def test_renders_add_button(self):
        response = self.client.get(reverse('admin:app_list', args=['app']),
                                   follow=True)
        self.assertContains(
            response,
            'Add',
            html=True)

class SingleObjectTestCase(AbstractTestCase):

    def setUp(self):
        super(SingleObjectTestCase, self).setUp()
        TestModel.objects.create(field='value')

    def test_cannot_add_new_model(self):
        response = self.client.get(reverse('admin:app_testmodel_add'),
                                   follow=True)
        self.assertRedirects(response,
                             reverse('admin:app_testmodel_change', args=[1]))
        self.assertMessage(
            response,
            'Do not add additional instances of testmodel. Only one is needed.'
            )

    def test_cannot_see_changelist(self):
        response = self.client.get(reverse('admin:app_testmodel_changelist'),
                                   follow=True)
        self.assertRedirects(response,
                             reverse('admin:app_testmodel_change', args=[1]))

    def test_does_not_render_add_button(self):
        response = self.client.get(reverse('admin:app_list', args=['app']),
                                   follow=True)
        self.assertNotContains(
            response,
            'Add',
            html=True)

class MultipleObjectsTestCase(AbstractTestCase):

    def setUp(self):
        super(MultipleObjectsTestCase, self).setUp()
        TestModel.objects.create(field='value1')
        TestModel.objects.create(field='value2')
        TestModel.objects.create(field='value3')

    def test_cannot_add_new_model(self):
        response = self.client.get(reverse('admin:app_testmodel_add'),
                                   follow=True)
        self.assertRedirects(response,
                             reverse('admin:app_testmodel_changelist'))
        self.assertMessage(
            response,
            'Do not add additional instances of testmodel. Only one is needed.'
            )

    def test_can_see_changelist(self):
        response = self.client.get(reverse('admin:app_testmodel_changelist'),
                                   follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertMessage(
            response,
            ('There are multiple instances of testmodel. There should only be '
             'one.'))

    def test_does_not_render_add_button(self):
        response = self.client.get(reverse('admin:app_list', args=['app']),
                                   follow=True)
        self.assertNotContains(
            response,
            'Add',
            html=True)


text:
import { IPromise } from 'angular';

import { API } from 'core/api';

export class ManagedWriter {
  public static pauseApplicationManagement(applicationName: string): IPromise<void> {
    return API.one('managed')
      .one('application', applicationName)
      .one('pause')
      .post();
  }

  public static resumeApplicationManagement(applicationName: string): IPromise<void> {
    return API.one('managed')
      .one('application', applicationName)
      .one('pause')
      .remove();
  }

  public static pauseResourceManagement(resourceId: string): IPromise<void> {
    return API.one('managed')
      .one('resources', resourceId)
      .one('pause')
      .post();
  }

  public static resumeResourceManagement(resourceId: string): IPromise<void> {
    return API.one('managed')
      .one('resources', resourceId)
      .one('pause')
      .remove();
  }
}


text:
package io.netty.handler.codec.http2;

import io.netty.handler.codec.DefaultHeaders;
import io.netty.handler.codec.UnsupportedValueConverter;
import io.netty.handler.codec.ValueConverter;
import io.netty.util.internal.UnstableApi;

import static io.netty.util.AsciiString.CASE_INSENSITIVE_HASHER;
import static io.netty.util.AsciiString.CASE_SENSITIVE_HASHER;

/**
 * Internal use only!
 */
@UnstableApi
public final class CharSequenceMap<V> extends DefaultHeaders<CharSequence, V, CharSequenceMap<V>> {
    public CharSequenceMap() {
        this(true);
    }

    public CharSequenceMap(boolean caseSensitive) {
        this(caseSensitive, UnsupportedValueConverter.<V>instance());
    }

    public CharSequenceMap(boolean caseSensitive, ValueConverter<V> valueConverter) {
        super(caseSensitive ? CASE_SENSITIVE_HASHER : CASE_INSENSITIVE_HASHER, valueConverter);
    }

    @SuppressWarnings("unchecked")
    public CharSequenceMap(boolean caseSensitive, ValueConverter<V> valueConverter, int arraySizeHint) {
        super(caseSensitive ? CASE_SENSITIVE_HASHER : CASE_INSENSITIVE_HASHER, valueConverter,
                NameValidator.NOT_NULL, arraySizeHint);
    }
}


text:
<?php if($this->session->userdata('idperfil')!=3):?>
  <?php $this->load->view("trem/insert"); ?>
<?php endif; ?>

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

      </button>

            <?php if($this->session->has_userdata("idterminal")):?>
              Você está na <?= $this->session->userdata("nome_terminal")?>
            <?php else:?>
              Terminais
            <?php endif;?>

            <?php foreach($this->session->userdata("terminais") as $value):?>
              <li <?= $this->session->userdata("idterminal") == $value["idterminal"]?"class='active'":"" ?> ><a href="<?=base_url('home/terminal/'.$value['idterminal'])?>"> <?=$value['nome_terminal']?>

            <?php endforeach;?>

      <?php if($this->session->has_userdata("idterminal")):?>

           Trens

            <?php if($this->session->userdata('idperfil')!=3):?>

 Adicionar Trem

            <?php endif; ?>

<a href="<?= base_url('trens/em_transito')?>"> Em Trânsito

<a href="<?= base_url('trens/em_operacao')?>"> Em operação

<a href="<?= base_url('trens/operados')?>"> Operados

           Rodoviário

 Opção 1

        <?php if($this->session->userdata('ver_relatorios') == "sim"):?>

             Relatórios

<a href="<?= base_url('relatorios/rel_01')?>"> Painel Operações

<a href="<?= base_url('relatorios/rel_02')?>"> Painel Trens

<a href="<?= base_url('relatorios/rel_03')?>"> Painel Prev. Chegadas

        <?php endif;?>

      <?php endif; ?>

        <?php if($this->session->userdata('idperfil')==1):?>

             Configurações

<a href="<?= base_url('usuario/')?>"> Usuários

<a href="<?= base_url('terminal/')?>"> Terminais

<a href="<?= base_url('tipoparada/')?>"> Tipos de Paradas

        <?php endif; ?>

           <?=ucwords($this->session->userdata("nome"))?>

<a href="<?= base_url('auth/logout')?>"> Sair


text:
package org.kie.workbench.common.dmn.client.commands.expressions.types.invocation;

import java.util.stream.IntStream;

import org.kie.workbench.common.dmn.api.definition.model.Binding;
import org.kie.workbench.common.dmn.api.definition.model.InformationItem;
import org.kie.workbench.common.dmn.api.definition.model.Invocation;
import org.kie.workbench.common.dmn.client.commands.VetoExecutionCommand;
import org.kie.workbench.common.dmn.client.commands.VetoUndoCommand;
import org.kie.workbench.common.dmn.client.commands.util.CommandUtils;
import org.kie.workbench.common.dmn.client.editors.expressions.types.invocation.InvocationDefaultValueUtilities;
import org.kie.workbench.common.dmn.client.editors.expressions.types.invocation.InvocationUIModelMapper;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasCommand;
import org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasGraphCommand;
import org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder;
import org.kie.workbench.common.stunner.core.client.command.CanvasViolation;
import org.kie.workbench.common.stunner.core.command.Command;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandResultBuilder;
import org.kie.workbench.common.stunner.core.graph.command.impl.AbstractGraphCommand;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.GridRow;

public class AddParameterBindingCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand,
                                                                                VetoUndoCommand {

    private final Invocation invocation;
    private final Binding binding;
    private final GridData uiModel;
    private final GridRow uiModelRow;
    private final int uiRowIndex;
    private final InvocationUIModelMapper uiModelMapper;
    private final org.uberfire.mvp.Command canvasOperation;
    private final String name;

    public AddParameterBindingCommand(final Invocation invocation,
                                      final Binding binding,
                                      final GridData uiModel,
                                      final GridRow uiModelRow,
                                      final int uiRowIndex,
                                      final InvocationUIModelMapper uiModelMapper,
                                      final org.uberfire.mvp.Command canvasOperation) {
        this.invocation = invocation;
        this.binding = binding;
        this.uiModel = uiModel;
        this.uiModelRow = uiModelRow;
        this.uiRowIndex = uiRowIndex;
        this.uiModelMapper = uiModelMapper;
        this.canvasOperation = canvasOperation;
        this.name = InvocationDefaultValueUtilities.getNewParameterName(invocation);
    }

    @Override
    protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler handler) {
        return new AbstractGraphCommand() {
            @Override
            protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext gce) {
                return GraphCommandResultBuilder.SUCCESS;
            }

            @Override
            public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext gce) {
                invocation.getBinding().add(uiRowIndex, binding);
                final InformationItem informationItem = binding.getParameter();
                informationItem.getName().setValue(name);

                binding.setParent(invocation);
                binding.getParameter().setParent(binding);

                return GraphCommandResultBuilder.SUCCESS;
            }

            @Override
            public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext gce) {
                invocation.getBinding().remove(binding);

                return GraphCommandResultBuilder.SUCCESS;
            }
        };
    }

    @Override
    protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) {
        return new AbstractCanvasCommand() {
            @Override
            public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) {
                uiModel.insertRow(uiRowIndex,
                                  uiModelRow);
                uiModelMapper.fromDMNModel(uiRowIndex,
                                           InvocationUIModelMapper.ROW_NUMBER_COLUMN_INDEX);
                uiModelMapper.fromDMNModel(uiRowIndex,
                                           InvocationUIModelMapper.BINDING_PARAMETER_COLUMN_INDEX);
                uiModelMapper.fromDMNModel(uiRowIndex,
                                           InvocationUIModelMapper.BINDING_EXPRESSION_COLUMN_INDEX);

                updateRowNumbers();
                updateParentInformation();

                canvasOperation.execute();

                return CanvasCommandResultBuilder.SUCCESS;
            }

            @Override
            public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) {
                final int rowIndex = uiModel.getRows().indexOf(uiModelRow);
                uiModel.deleteRow(rowIndex);

                updateRowNumbers();
                updateParentInformation();

                canvasOperation.execute();

                return CanvasCommandResultBuilder.SUCCESS;
            }
        };
    }

    public void updateRowNumbers() {
        CommandUtils.updateRowNumbers(uiModel,
                                      IntStream.range(0,
                                                      uiModel.getRowCount()));
    }

    public void updateParentInformation() {
        CommandUtils.updateParentInformation(uiModel);
    }
}


text:
all: build

build:
	make -C ../../libgit2/git2go install
	go install .


text:
class AddInSearchToInstitutions < ActiveRecord::Migration
  def change
    add_column :institutions, :in_search, :boolean, default: true
  end
end


text:
{-# LANGUAGE BangPatterns #-}

module Numeric.MaxEnt.Train.Enumerator (toTrainCorpus) where

import Data.Enumerator hiding (isEOF, length, map)
import qualified Data.Map as M
import Numeric.MaxEnt (Context(..))

import Numeric.MaxEnt.Train.Internal

toTrainCorpus :: (Monad m, Ord a) =>
            Iteratee (Context a) m (TrainCorpus a)
toTrainCorpus = liftI $ step emptyMapping where
    step acc@(FeatureMapping !i !f !n, !corpus) chunk = case chunk of
                       Chunks [] -> Continue $ returnI . step acc
                       Chunks xs -> Continue $ returnI .
                                    (step $ ctxsToNum acc xs)
                       EOF -> Yield (TrainCorpus mapping normCtxs) EOF
                              where (mapping, ctxs) = acc
                                    normCtxs = normalizeTrainCorpus ctxs


text:
Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.

They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.

For example:

    [1,2,3] and {"a":2,"b":4} both have a sum of 6.
    [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
    {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
    [] and {} both have a sum of 0.

You will not encounter any strings containing numbers.

What is the sum of all numbers in the document?

--- Part Two ---

Uh oh - the Accounting-Elves have realized that they double-counted everything red.

Ignore any object (and all of its children) which has any property with the value "red". Do this only for objects ({...}), not arrays ([...]).

    [1,2,3] still has a sum of 6.
    [1,{"c":"red","b":2},3] now has a sum of 4, because the middle object is ignored.
    {"d":"red","e":[1,2,3,4],"f":5} now has a sum of 0, because the entire structure is ignored.
    [1,"red",5] has a sum of 6, because "red" in an array has no effect.


text:
import React, {useCallback} from 'react';
import {useIntl} from 'react-intl';

import OptionItem from '@components/option_item';
import Screens from '@constants/screens';
import {showModal} from '@screens/navigation';
import {preventDoubleTap} from '@utils/tap';

const Settings = () => {
    const intl = useIntl();

    const openSettings = useCallback(preventDoubleTap(() => {
        showModal(
            Screens.SETTINGS,
            intl.formatMessage({id: 'mobile.screen.settings', defaultMessage: 'Settings'}),
        );
    }), []);

    return (
        <OptionItem
            action={openSettings}
            icon='settings-outline'
            label={intl.formatMessage({id: 'account.settings', defaultMessage: 'Settings'})}
            testID='account.settings.option'
            type='default'
        />
    );
};

export default Settings;


text:
//
//  DLSFTPClient.h
//  DLSFTPClient
//
//  Created by Ryan on 12/17/16.
//  Copyright © 2016 Dan Leehr. All rights reserved.
//

#ifndef DLSFTPClient_h
#define DLSFTPClient_h

#import <Foundation/Foundation.h>
#import <fcntl.h>
#import <sys/socket.h>
#import <arpa/inet.h>
#import "libssh2.h"
#import "libssh2_publickey.h"
#import "libssh2_sftp.h"

#import "DLSFTPRequest.h"
#import "DLSFTPConnection.h"
#import "DLSFTPDownloadRequest.h"
#import "DLSFTPFile.h"
#import "DLSFTPListFilesRequest.h"
#import "DLSFTPMakeDirectoryRequest.h"
#import "DLSFTPMoveRenameRequest.h"
#import "DLSFTPRemoveDirectoryRequest.h"
#import "DLSFTPRemoveFileRequest.h"
#import "DLSFTPUploadRequest.h"
#import "NSDictionary+SFTPFileAttributes.h"

#endif /* DLSFTPClient_h */


text:
package org.apache.activemq.artemis.service.extensions.tests.xa;

import javax.transaction.xa.XAResource;
import java.util.Map;

import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapper;
import org.apache.activemq.artemis.service.extensions.xa.ActiveMQXAResourceWrapperFactory;

public class MockActiveMQResourceWrapperFactory implements ActiveMQXAResourceWrapperFactory
{
   @Override
   public ActiveMQXAResourceWrapper wrap(XAResource xaResource, Map<String, Object> properties)
   {
      return null;
   }
}