text:
package com.faforever.api.data;

import com.faforever.api.AbstractIntegrationTest;
import com.faforever.api.data.domain.GroupPermission;
import com.faforever.api.player.PlayerRepository;
import com.faforever.api.security.OAuthScope;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;

import static org.hamcrest.Matchers.hasKey;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/truncateTables.sql")
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepDefaultData.sql")
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepUniqueIDData.sql")
public class PlayerElideTest extends AbstractIntegrationTest {

  @Autowired
  PlayerRepository playerRepository;

  @Test
  public void restrictedResultWithoutScope() throws Exception {
    mockMvc.perform(get("/data/player")
      .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(5)))
      .andExpect(jsonPath("$.data[0].attributes.login", is("USER")))
      .andExpect(jsonPath("$.data[1].attributes.login", is("MODERATOR")))
      .andExpect(jsonPath("$.data[2].attributes.login", is("ADMIN")))
      .andExpect(jsonPath("$.data[3].attributes.login", is("BANNED")))
      .andExpect(jsonPath("$.data[4].attributes.login", is("ACTIVE_USER")))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[0].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[1].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[2].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[3].relationships", not(hasKey("uniqueIds"))))
      // you are allowed to see your own stuff
      .andExpect(jsonPath("$.data[4].attributes.email", is("active-user@faforever.com")))
      .andExpect(jsonPath("$.data[4].attributes.recentIpAddress", is("127.0.0.1")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("lastLogin")))
      // you cannot see your uuid
      .andExpect(jsonPath("$.data[4].relationships", not(hasKey("uniqueIds"))))
      // nobody can see passwords!
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[4].attributes", not(hasKey("password"))));

    mockMvc.perform(get("/data/player?filter=email==active-user@faforever.com")
      .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(1)));

    mockMvc.perform(get("/data/player?filter=email==user@faforever.com")
      .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(0)));
  }

  @Test
  public void restrictedResultWithoutRole() throws Exception {
    mockMvc.perform(get("/data/player")
      .with(getOAuthTokenWithActiveUser(OAuthScope._READ_SENSIBLE_USERDATA, NO_AUTHORITIES)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(5)))
      .andExpect(jsonPath("$.data[0].attributes.login", is("USER")))
      .andExpect(jsonPath("$.data[1].attributes.login", is("MODERATOR")))
      .andExpect(jsonPath("$.data[2].attributes.login", is("ADMIN")))
      .andExpect(jsonPath("$.data[3].attributes.login", is("BANNED")))
      .andExpect(jsonPath("$.data[4].attributes.login", is("ACTIVE_USER")))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("email"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("steamId"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("recentIpAddress"))))
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("lastLogin"))))
      .andExpect(jsonPath("$.data[0].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[1].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[2].relationships", not(hasKey("uniqueIds"))))
      .andExpect(jsonPath("$.data[3].relationships", not(hasKey("uniqueIds"))))
      // you are allowed to see your own stuff
      .andExpect(jsonPath("$.data[4].attributes.email", is("active-user@faforever.com")))
      .andExpect(jsonPath("$.data[4].attributes.recentIpAddress", is("127.0.0.1")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[4].relationships", hasKey("reporterOnModerationReports")))
      .andExpect(jsonPath("$.data[4].relationships", hasKey("userGroups")))
      // you cannot see your uuid
      .andExpect(jsonPath("$.data[4].relationships", not(hasKey("uniqueIds"))))
      // nobody can see passwords!
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[4].attributes", not(hasKey("password"))));

    mockMvc.perform(get("/data/player?filter=email==active-user@faforever.com")
      .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(1)));

    mockMvc.perform(get("/data/player?filter=email==user@faforever.com")
      .with(getOAuthTokenWithActiveUser(NO_SCOPE, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(0)));
  }

  @Test
  public void canSeePrivateDetailsWithScopeAndRole() throws Exception {
    mockMvc.perform(get("/data/player")
      .with(getOAuthTokenWithActiveUser(OAuthScope._READ_SENSIBLE_USERDATA, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(5)))
      .andExpect(jsonPath("$.data[0].attributes.login", is("USER")))
      .andExpect(jsonPath("$.data[1].attributes.login", is("MODERATOR")))
      .andExpect(jsonPath("$.data[2].attributes.login", is("ADMIN")))
      .andExpect(jsonPath("$.data[3].attributes.login", is("BANNED")))
      .andExpect(jsonPath("$.data[4].attributes.login", is("ACTIVE_USER")))
      .andExpect(jsonPath("$.data[0].attributes", hasKey("email")))
      .andExpect(jsonPath("$.data[1].attributes", hasKey("email")))
      .andExpect(jsonPath("$.data[2].attributes", hasKey("email")))
      .andExpect(jsonPath("$.data[3].attributes", hasKey("email")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("email")))
      .andExpect(jsonPath("$.data[0].attributes", hasKey("recentIpAddress")))
      .andExpect(jsonPath("$.data[1].attributes", hasKey("recentIpAddress")))
      .andExpect(jsonPath("$.data[2].attributes", hasKey("recentIpAddress")))
      .andExpect(jsonPath("$.data[3].attributes", hasKey("recentIpAddress")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("recentIpAddress")))
      .andExpect(jsonPath("$.data[0].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[1].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[2].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[3].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("lastLogin")))
      .andExpect(jsonPath("$.data[0].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[1].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[2].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[3].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[4].attributes", hasKey("steamId")))
      .andExpect(jsonPath("$.data[0].relationships", hasKey("uniqueIds")))
      .andExpect(jsonPath("$.data[1].relationships", hasKey("uniqueIds")))
      .andExpect(jsonPath("$.data[2].relationships", hasKey("uniqueIds")))
      .andExpect(jsonPath("$.data[3].relationships", hasKey("uniqueIds")))
      .andExpect(jsonPath("$.data[4].relationships", hasKey("uniqueIds")))
      // cannot see others reporterOnModerationReports
      .andExpect(jsonPath("$.data[0].relationships", not(hasKey("reporterOnModerationReports"))))
      .andExpect(jsonPath("$.data[1].relationships", not(hasKey("reporterOnModerationReports"))))
      .andExpect(jsonPath("$.data[2].relationships", not(hasKey("reporterOnModerationReports"))))
      .andExpect(jsonPath("$.data[3].relationships", not(hasKey("reporterOnModerationReports"))))
      // cannot see others userGroups
      .andExpect(jsonPath("$.data[0].relationships", not(hasKey("userGroups"))))
      .andExpect(jsonPath("$.data[1].relationships", not(hasKey("userGroups"))))
      .andExpect(jsonPath("$.data[2].relationships", not(hasKey("userGroups"))))
      .andExpect(jsonPath("$.data[3].relationships", not(hasKey("userGroups"))))
      // nobody can see passwords!
      .andExpect(jsonPath("$.data[0].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[1].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[2].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[3].attributes", not(hasKey("password"))))
      .andExpect(jsonPath("$.data[4].attributes", not(hasKey("password"))));

    mockMvc.perform(get("/data/player?filter=email==active-user@faforever.com")
      .with(getOAuthTokenWithActiveUser(OAuthScope._READ_SENSIBLE_USERDATA, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(1)));

    mockMvc.perform(get("/data/player?filter=email==user@faforever.com")
      .with(getOAuthTokenWithActiveUser(OAuthScope._READ_SENSIBLE_USERDATA, GroupPermission.ROLE_READ_ACCOUNT_PRIVATE_DETAILS)))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$.data", hasSize(1)));
  }
}


text:
//---------------------------------------------------------------------
// <copyright file="LockedAssemblyCache.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;

namespace System.Data.Metadata.Edm
{
    internal class LockedAssemblyCache : IDisposable
    {
        private object _lockObject;
        private Dictionary<Assembly, ImmutableAssemblyCacheEntry> _globalAssemblyCache;
        internal LockedAssemblyCache(object lockObject, Dictionary<Assembly, ImmutableAssemblyCacheEntry> globalAssemblyCache)
        {
            _lockObject = lockObject;
            _globalAssemblyCache = globalAssemblyCache;
#pragma warning disable 0618
            //@
            Monitor.Enter(_lockObject);
#pragma warning restore 0618
        }

        public void Dispose()
        {
            // Technically, calling GC.SuppressFinalize is not required because the class does not
            // have a finalizer, but it does no harm, protects against the case where a finalizer is added
            // in the future, and prevents an FxCop warning.
            GC.SuppressFinalize(this);
            Monitor.Exit(_lockObject);
            _lockObject = null;
            _globalAssemblyCache = null;
        }

        [Conditional("DEBUG")]
        private void AssertLockedByThisThread()
        {
            bool entered = false;
            Monitor.TryEnter(_lockObject, ref entered);
            if (entered)
            {
                Monitor.Exit(_lockObject);
            }

            Debug.Assert(entered, "The cache is being accessed by a thread that isn't holding the lock");
        }

        internal bool TryGetValue(Assembly assembly, out ImmutableAssemblyCacheEntry cacheEntry)
        {
            AssertLockedByThisThread();
            return _globalAssemblyCache.TryGetValue(assembly, out cacheEntry);
        }

        internal void Add(Assembly assembly, ImmutableAssemblyCacheEntry assemblyCacheEntry)
        {
            AssertLockedByThisThread();
            _globalAssemblyCache.Add(assembly, assemblyCacheEntry);
        }

        internal void Clear()
        {
            AssertLockedByThisThread();
            _globalAssemblyCache.Clear();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
``git diff —name-only —diff-filter=U```

[Source](http://stackoverflow.com/questions/3065650/whats-the-simplest-way-to-git-a-list-of-conflicted-files)


text:
package org.kie.workbench.common.screens.library.client.settings.sections.externaldataobjects;

import javax.inject.Inject;

import org.jboss.errai.ui.client.local.api.elemental2.IsElement;
import org.kie.soup.project.datamodel.imports.Import;
import org.kie.workbench.common.widgets.client.widget.ListItemPresenter;
import org.kie.workbench.common.widgets.client.widget.ListItemView;
import org.kie.workbench.common.widgets.configresource.client.widget.BuiltInTypeImportHelper;

public class ExternalDataObjectsItemPresenter extends ListItemPresenter<Import, ExternalDataObjectsPresenter, ExternalDataObjectsItemPresenter.View> {

    private Import import_;

    ExternalDataObjectsPresenter parentPresenter;

    public interface View extends ListItemView<ExternalDataObjectsItemPresenter>,
                                  IsElement {

        void setTypeName(final String typeName);

        void hideRemoveButton();

        void showRemoveButton();
    }

    @Inject
    public ExternalDataObjectsItemPresenter(final View view) {
        super(view);
    }

    @Override
    public ExternalDataObjectsItemPresenter setup(final Import import_,
                                                  final ExternalDataObjectsPresenter parentPresenter) {

        this.import_ = import_;
        this.parentPresenter = parentPresenter;

        view.init(this);
        view.setTypeName(import_.getType());

        final String typeName = import_.getType();
        setRemoveButtonVisibility(typeName);

        return this;
    }

    @Override
    public void remove() {
        super.remove();
        parentPresenter.fireChangeEvent();
    }

    public void onTypeNameChange(final String typeName) {
        import_.setType(typeName);
        parentPresenter.fireChangeEvent();
        setRemoveButtonVisibility(typeName);
    }

    @Override
    public Import getObject() {
        return import_;
    }

    public View getView() {
        return view;
    }

    private void setRemoveButtonVisibility(final String typeName) {
        if (BuiltInTypeImportHelper.isBuiltIn(typeName)) {
            view.hideRemoveButton();
        } else {
            view.showRemoveButton();
        }
    }
}


text:
[![CI Status](http://img.shields.io/travis/gph1991/FGSettingView.svg?style=flat)](https://travis-ci.org/gph1991/FGSettingView)
[![Version](https://img.shields.io/cocoapods/v/FGSettingView.svg?style=flat)](http://cocoapods.org/pods/FGSettingView)
[![License](https://img.shields.io/cocoapods/l/FGSettingView.svg?style=flat)](http://cocoapods.org/pods/FGSettingView)
[![Platform](https://img.shields.io/cocoapods/p/FGSettingView.svg?style=flat)](http://cocoapods.org/pods/FGSettingView)

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

FGSettingView is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "FGSettingView"
```

## Author

gph1991, guopenghao@haogw.com

## License

FGSettingView is available under the MIT license. See the LICENSE file for more info.


text:
/**
*============================================================================
*  Copyright The Ohio State University Research Foundation, The University of Chicago -
*	Argonne National Laboratory, Emory University, SemanticBits LLC, and
*	Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
/**
 *
 */
package org.cagrid.installer.tasks;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.installer.model.CaGridInstallerModel;
import org.cagrid.installer.steps.Constants;
import org.cagrid.installer.util.InstallerUtils;
import org.cagrid.installer.util.MD5Checksum;
import org.pietschy.wizard.InvalidStateException;

/**
 * @author Joshua Phillips
 */
public class DownloadFileTask extends BasicTask {

    private static final int BUFFER_SIZE = 1024;

    private static final int LOGAFTER_SIZE = BUFFER_SIZE * 1000;

    private static final int NUM_ATTEMPTS = 2;

    private static final Log logger = LogFactory.getLog(DownloadFileTask.class);

    private String fromUrlProp;

    private String toFileProp;

    private String checksumProp;

    // Max time to wait for connection
    private long connectTimeout;

    /**
     * @param name
     * @param description
     */
    public DownloadFileTask(String name, String description, String fromUrlProp, String toFileProp,
        String checksumProp, long timeout) {
        super(name, description);
        this.fromUrlProp = fromUrlProp;
        this.toFileProp = toFileProp;
        this.checksumProp = checksumProp;
        this.connectTimeout = timeout;
    }

    @Override
    protected Object internalExecute(CaGridInstallerModel model) throws Exception {

        String fromUrl = model.getProperty(this.fromUrlProp);

        URL url = null;
        try {
            url = new URL(fromUrl);
        } catch (MalformedURLException ex) {
            throw new RuntimeException("Bad URL: '" + fromUrl + "'", ex);
        }

        String toFile = model.getProperty(Constants.TEMP_DIR_PATH) + "/" + model.getProperty(this.toFileProp);

        boolean enforceChecksum = true;
        String expectedChecksum = model.getProperty(this.checksumProp);
        if (InstallerUtils.isEmpty(expectedChecksum)) {
            enforceChecksum = false;
            logger.warn("No checksum specified for '" + fromUrl + "'");
        }

        File toFileFile = new File(toFile);

        String checksum = null;
        boolean alreadyDownloaded = false;
        if (toFileFile.exists()) {
            if (enforceChecksum) {
                checksum = MD5Checksum.getChecksum(toFile);
                if (enforceChecksum && !expectedChecksum.equals(checksum)) {
                    logger.warn("Cached file does not match checksum, will attept to download");
                } else {
                    alreadyDownloaded = true;
                }
            }
        }

        if(!alreadyDownloaded){

            int i = 0;
            for (i = 0; i < NUM_ATTEMPTS; i++) {
                try {
                    download(url, new File(toFile), this.connectTimeout);
                    if (!enforceChecksum) {
                        break;
                    } else {
                        checksum = MD5Checksum.getChecksum(toFile);
                        if (expectedChecksum.equals(checksum)) {
                            break;
                        } else {
                            logger.warn("Downloaded file '" + toFile + "' is corrupted.  Expected checksum ("
                                + expectedChecksum + ") but recieved (" + checksum + ").");
                        }
                    }
                } catch (Exception ex) {
                    logger.warn("Failed attempt (" + (i + 1) + ") to download '" + fromUrl + "': " + ex.getMessage(),
                        ex);
                }
            }

            if (i == NUM_ATTEMPTS) {
                throw new InvalidStateException("Could not download '" + fromUrl + "'. See logs for details.");
            }

            if (enforceChecksum && !expectedChecksum.equals(checksum)) {
                throw new InvalidStateException("Could not download '" + fromUrl + "'. See logs for details.");
            }
        }

        return null;
    }

    private static void download(URL fromUrl, File toFile, long connectTimeout) throws Exception {

        ConnectThread t = new ConnectThread(fromUrl);
        t.start();
        try {
            t.join(connectTimeout);
        } catch (InterruptedException ex) {
            throw new RuntimeException("Thread interrupted", ex);
        }

        if (t.getEx() != null) {
            throw new RuntimeException("Error connecting to " + fromUrl + ": " + t.getEx().getMessage(), t.getEx());
        }
        if (!t.isFinished()) {
            throw new RuntimeException("Connection to " + fromUrl + " timed out.");
        }
        InputStream inputStream = t.getIn();

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(toFile));
        byte[] buffer = new byte[BUFFER_SIZE];
        int len = -1;
        int bytesRead = 0;
        int nextLog = -1;
        String lastMsg = null;
        while ((len = inputStream.read(buffer)) != -1) {
            out.write(buffer, 0, len);
            bytesRead += len;

            if (bytesRead > nextLog) {
                nextLog += LOGAFTER_SIZE;
                double percent = bytesRead / (double) t.getTotalBytes();
                String currMsg = "";
                if (percent > 0) {
                    currMsg = Math.round(percent * 100) + " % complete";
                } else {
                    currMsg = "Read " + bytesRead + " bytes of unknown total size.";
                }

                if (!currMsg.equals(lastMsg)) {
                    System.out.println(currMsg);
                }
                lastMsg = currMsg;
            }

        }
        out.flush();
        out.close();
        inputStream.close();
    }

    private static class ConnectThread extends Thread {
        private InputStream in;

        private Exception ex;

        private boolean finished;

        private URL url;

        int totalBytes;

        ConnectThread(URL url) {
            this.url = url;
            this.setDaemon(true);
        }

        @Override
        public void run() {
            try {
                URLConnection conn = this.url.openConnection();
                conn.connect();
                this.totalBytes = conn.getContentLength();
                this.in = conn.getInputStream();
                this.finished = true;
            } catch (Exception e) {
                this.ex = e;
            }
        }

        int getTotalBytes() {
            return this.totalBytes;
        }

        Exception getEx() {
            return this.ex;
        }

        boolean isFinished() {
            return this.finished;
        }

        InputStream getIn() {
            return this.in;
        }
    }
}


text:
local function BottomUpTree(item, depth)
  if depth > 0 then
    local i = item + item
    depth = depth - 1
    local left, right = BottomUpTree(i-1, depth), BottomUpTree(i, depth)
    return { item, left, right }
  else
    return { item }
  end
end

local function ItemCheck(tree)
  if tree[2] then
    return tree[1] + ItemCheck(tree[2]) - ItemCheck(tree[3])
  else
    return tree[1]
  end
end

local N = 10
local mindepth = 4
local maxdepth = mindepth + 2
if maxdepth < N then maxdepth = N end

do
  local stretchdepth = maxdepth + 1
  local stretchtree = BottomUpTree(0, stretchdepth)
  print(stretchdepth, ItemCheck(stretchtree))
end

local longlivedtree = BottomUpTree(0, maxdepth)

for depth = mindepth,maxdepth,2 do
  local iterations = 2 ^ (maxdepth - depth + mindepth)
  local check = 0
  for i=1,iterations do
    check = check + ItemCheck(BottomUpTree(1, depth)) +
            ItemCheck(BottomUpTree(-1, depth))
  end
  print(iterations*2, depth, check)
end

print("long lived tree of depth ", maxdepth, ItemCheck(longlivedtree))


text:
@implementation PMPeriod

@synthesize startDate = _startDate;
@synthesize endDate = _endDate;

+ (id) periodWithStartDate:(NSDate *) startDate endDate:(NSDate *) endDate
{
    PMPeriod *result = [[PMPeriod alloc] init];

    result.startDate = startDate;
    result.endDate = endDate;

    return result;
}

+ (PMPeriod*) oneDayPeriodWithDate:(NSDate *) date
{
    PMPeriod *result = [[PMPeriod alloc] init];

    result.startDate = [date dateWithoutTime];
    result.endDate = result.startDate;

    return result;
}

- (BOOL) isEqual:(id) object
{
    if (![object isKindOfClass:[PMPeriod class]])
    {
        return NO;
    }

    PMPeriod *period = object;
    return [self.startDate isEqualToDate:period.startDate]
            && [self.endDate isEqualToDate:period.endDate];
}

- (NSInteger) lengthInDays
{
    return [self.endDate daysSinceDate:self.startDate];
}

- (NSString *) description
{
    return [NSString stringWithFormat:@"startDate = %@; endDate = %@", _startDate, _endDate];
}

- (PMPeriod *) normalizedPeriod
{
    PMPeriod *result = [[PMPeriod alloc] init];

    if ([_startDate compare:_endDate] == NSOrderedAscending)
    {
        result.startDate = _startDate;
        result.endDate = _endDate;
    }
    else
    {
        result.startDate = _endDate;
        result.endDate = _startDate;
    }

    return result;
}

- (BOOL) containsDate:(NSDate *) date
{
    PMPeriod *normalizedPeriod = [self normalizedPeriod];

    if (([normalizedPeriod.startDate compare:date] != NSOrderedDescending)
        && ([normalizedPeriod.endDate compare:date] != NSOrderedAscending))
    {
        return YES;
    }

    return NO;
}

- (id) copyWithZone:(NSZone *) zone
{
    PMPeriod *copiedPeriod = [[PMPeriod alloc] init];
    copiedPeriod.startDate = [_startDate copyWithZone: zone];
    copiedPeriod.endDate = [_endDate copyWithZone: zone];

    return copiedPeriod;
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecanora allophana var. contigua Mereschk.

### Remarks
null


text:
using UnityEngine;
using System.Collections;

//
// アニメーション簡易プレビュースクリプト
// 2015/4/25 quad arrow
//

// Require these components when using this script
[RequireComponent(typeof(Animator))]

public class IdleChanger : MonoBehaviour
{

	private Animator anim;						// Animatorへの参照
	private AnimatorStateInfo currentState;		// 現在のステート状態を保存する参照
	private AnimatorStateInfo previousState;	// ひとつ前のステート状態を保存する参照

	// Use this for initialization
	void Start ()
	{
		// 各参照の初期化
		anim = GetComponent<Animator> ();
		currentState = anim.GetCurrentAnimatorStateInfo (0);
		previousState = currentState;

	}

	void OnGUI()
	{
		GUI.Box(new Rect(Screen.width - 200 , 45 ,120 , 350), "");
		if(GUI.Button(new Rect(Screen.width - 190 , 60 ,100, 20), "Jab"))
			anim.SetBool ("Jab", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 90 ,100, 20), "Hikick"))
			anim.SetBool ("Hikick", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 120 ,100, 20), "Spinkick"))
			anim.SetBool ("Spinkick", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 150 ,100, 20), "Rising_P"))
			anim.SetBool ("Rising_P", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 180 ,100, 20), "Headspring"))
			anim.SetBool ("Headspring", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 210 ,100, 20), "Land"))
			anim.SetBool ("Land", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 240 ,100, 20), "ScrewKick"))
			anim.SetBool ("ScrewK", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 270 ,100, 20), "DamageDown"))
			anim.SetBool ("DamageDown", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 300 ,100, 20), "SamK"))
			anim.SetBool ("SAMK", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 330 ,100, 20), "Run"))
			anim.SetBool ("Run", true);
		if(GUI.Button(new Rect(Screen.width - 190 , 360 ,100, 20), "Run_end"))
			anim.SetBool ("Run", false);

;
	}
}


text:
layout: structure/header
title: Digital Guides
title_badge: beta
mainmenu: /_shared/mainmenu.md
header_govau: header-govau.md


text:
Litepqxx is (planned to be) a wrapper library to access SQLite3 via API compatible with Libpqxx

## Usecases
* For quick prototyping with SQLite3 and smooth migration to Postgresql.
* To use SQLite3 as a stub db when you test your project with Postgresql.
* Just as a better, object-oriented API for SQLite3.

## Known gaps
* It does not (yet?) cover the whole API.
* Sqlite3 has "BLOB" instead of "BYTEA".
* affected_rows() works properly only in case of INSERT, UPDATE or DELETE. (In other cases, it returns value left by the last execution of such statements)
* It throws syntax_error instead of the subclasses, i.e
    * undefined_column
    * undefined_function
    * undefined_table.
* It throws integrity_constraint_violation instead of the subclasses, i.e.
    * check_violation
    * foreign_key_violation
    * not_null_violation
    * restrict_violation
    * unique_violation.


text:
<?php namespace Pantono\Products\Entity;

use Doctrine\ORM\Mapping as ORM;
use Pantono\Database\Entity\EntityAbstract;

/**
 * Class Product
 *
 * @package Pantono\Products\Entity
 * @ORM\Entity(repositoryClass="Pantono\Products\Entity\Repository\ProductRepository")
 * @ORM\Table(name="products")
 */
class Product extends EntityAbstract
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    protected $id;
    /**
     * @ORM\OneToOne(targetEntity="Pantono\Products\Entity\Draft")
     */
    protected $draft;
    /**
     * @ORM\OneToOne(targetEntity="Pantono\Products\Entity\Status")
     */
    protected $status;

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return Draft
     */
    public function getDraft()
    {
        return $this->draft;
    }

    /**
     * @param mixed Draft
     */
    public function setDraft($draft)
    {
        $this->draft = $draft;
    }

    /**
     * @return mixed
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * @param mixed $status
     */
    public function setStatus($status)
    {
        $this->status = $status;
    }
}


text:
<?xml version="1.0"?>
<!--

-->
<config>
    <menu>
        <catalog>
            <children>
<!--            <googlebase translate="title" module="googlebase">-->
<!--                <title>Google Base</title>-->
<!--                <children>-->
<!--                    <types translate="title" module="googlebase">-->
<!--                        <title>Manage Attributes</title>-->
<!--                        <action>adminhtml/googlebase_types</action>-->
<!--                    </types>-->
<!--                    <items translate="title" module="googlebase">-->
<!--                        <title>Manage Items</title>-->
<!--                        <action>adminhtml/googlebase_items</action>-->
<!--                    </items>-->
<!--                </children>-->
<!--                <sort_order>70</sort_order>-->
<!--            </googlebase>-->
             </children>
        </catalog>
    </menu>
    <acl>
        <resources>
            <admin>
                <children>
                    <catalog>
                        <children>
<!--                            <googlebase translate="title" module="googlebase">-->
<!--                                <title>Google Base</title>-->
<!--                                <sort_order>500</sort_order>-->
<!--                                <children>-->
<!--                                    <types translate="title">-->
<!--                                        <title>Manage Attributes</title>-->
<!--                                        <sort_order>0</sort_order>-->
<!--                                    </types>-->
<!--                                    <items translate="title">-->
<!--                                        <title>Manage Items</title>-->
<!--                                        <sort_order>5</sort_order>-->
<!--                                    </items>-->
<!--                                </children>-->
<!--                            </googlebase>-->
                        </children>
                    </catalog>
                </children>
            </admin>
        </resources>
    </acl>
</config>


text:
* Initial code

## 0.1.1 - Initial commit
* Settings page
* Read from file


text:
/*****************************************************************************
*
* expcss - ex_put_concat_side_sets
*
* entry conditions -
*   input parameters:
*       int     exoid                   exodus file id
*       int     *side_set_ids           array of side set ids
*       int     *num_elem_per_set       number of elements/sides/faces per set
*       int     *num_dist_per_set       number of distribution factors per set
* ----------pass in NULL for remaining args if just want to set params -------------
*       int     *side_sets_elem_index   index array of elements into elem list
*       int     *side_sets_dist_index   index array of df into df list
*       int     *side_sets_elem_list    array of elements
*       int     *side_sets_side_list    array of sides/faces
*       void    *side_sets_dist_fact    array of distribution factors
*
* exit conditions -
*
* revision history -
*
*  Id
*
*****************************************************************************/

#include <stdlib.h>
#include "exodusII.h"
#include "exodusII_int.h"

/*!
 * writes the side set ID's, side set element count array,
 * side set element pointers array, side set element list,
 * side set side list, and distribution factors list.
 * \param   exoid                   exodus file id
 * \param   side_set_ids           array of side set ids
 * \param   num_elem_per_set       number of elements/sides/faces per set
 * \param   num_dist_per_set       number of distribution factors per set
 * \param   side_sets_elem_index   index array of elements into elem list
 * \param   side_sets_dist_index   index array of df into df list
 * \param   side_sets_elem_list    array of elements
 * \param   side_sets_side_list    array of sides/faces
 * \param   side_sets_dist_fact    array of distribution factors
 * \deprecated Use ex_put_concat_sets()(exoid, EX_SIDE_SET, set_specs)
 */

int ex_put_concat_side_sets (int   exoid,
                             int  *side_set_ids,
                             int  *num_elem_per_set,
                             int  *num_dist_per_set,
                             int  *side_sets_elem_index,
                             int  *side_sets_dist_index,
                             int  *side_sets_elem_list,
                             int  *side_sets_side_list,
                             void *side_sets_dist_fact)
{
  struct ex_set_specs set_specs;

  set_specs.sets_ids = side_set_ids;
  set_specs.num_entries_per_set = num_elem_per_set;
  set_specs.num_dist_per_set = num_dist_per_set;
  set_specs.sets_entry_index = side_sets_elem_index;
  set_specs.sets_dist_index = side_sets_dist_index;
  set_specs.sets_entry_list = side_sets_elem_list;
  set_specs.sets_extra_list = side_sets_side_list;
  set_specs.sets_dist_fact = side_sets_dist_fact;

  return ex_put_concat_sets(exoid, EX_SIDE_SET, &set_specs);
}


text:
using NUnit.Framework;
using StoryGenerator.Domain.Story;
using System;
using System.Collections.Generic;
using System.Text;

namespace Tests.DomainTests.Story
{
    [TestFixture]
    class StoryPlotTests
    {
        [Test]
        public void Add_ShouldConcatenateTwoMessageListInTheCorrectOrder()
        {
            string[] storyEvents = { "Story Started", "Heros are summoned", "Saber wins the grail", "Story Ended" };

            var storyPlot = new StoryPlot();
            storyPlot.PlotEvents.Add(storyEvents[0]);
            storyPlot.PlotEvents.Add(storyEvents[1]);

            var newStoryEvents = new StoryPlot();
            newStoryEvents.PlotEvents.Add(storyEvents[2]);
            newStoryEvents.PlotEvents.Add(storyEvents[3]);

            storyPlot.Add(newStoryEvents);

            for (int i = 0; i < storyPlot.PlotEvents.Count; i++)
            {
                Assert.AreEqual(storyPlot.PlotEvents[i], storyEvents[i]);
            }

        }
    }
}


text: export default {'offset': 36000, 'dst': true, 'abbrev': 'KDT'};


text:
describe("@constant tag", function() {
    var docSet = jasmine.getDocSetFromFile('test/fixtures/constanttag.js'),
        FOO = docSet.getByLongname('FOO')[0],
        BAR = docSet.getByLongname('BAR')[0],
        BAZ = docSet.getByLongname('BAZ')[0];

    it("sets the doclet's 'kind' property to 'constant'", function() {
        expect(FOO.kind).toBe('constant');
        expect(BAR.kind).toBe('constant');
        expect(BAZ.kind).toBe('constant');
    });

    it("If used as a standalone, takes the name from the code", function() {
        expect(FOO.name).toBe('FOO');
    });

    it("If used with just a name, sets the doclet's name to that", function() {
        expect(BAR.name).toBe('BAR');
    });

    it("If used with a name and a type, sets the doclet's name and type appropriately", function() {
        expect(BAZ.name).toBe('BAZ');
        expect(typeof BAZ.type).toBe('object');
        expect(BAZ.type.names).toBeDefined();
        expect(BAZ.type.names.length).toBe(1);
        expect(BAZ.type.names[0]).toBe('string');
    });
});


text:
#ifndef ARROBOTPACKET_H
#define ARROBOTPACKET_H

#include "ariaTypedefs.h"
#include "ArBasePacket.h"
#include "ariaUtil.h"

/// Represents the packets sent to the robot as well as those received from it
/**
   This class reimplements some of the buf operations since the robot is
   opposeite endian from intel.  Also has the getID for convenience.

   You can just look at the documentation for the ArBasePacket except for
   the 4 new functions here, verifyCheckSum, getID, print, and calcCheckSum.
 */
class ArRobotPacket: public ArBasePacket
{
public:
  /// Constructor
  AREXPORT ArRobotPacket(unsigned char sync1 = 0xfa,
			 unsigned char sync2 = 0xfb);
  /// Destructor
  AREXPORT virtual ~ArRobotPacket();

  /// returns true if the checksum matches what it should be
  AREXPORT bool verifyCheckSum(void);

  /// returns the ID of the packet
  AREXPORT ArTypes::UByte getID(void);

  /// Sets the ID of the packet
  AREXPORT void setID(ArTypes::UByte id);

  /// returns the checksum, probably used only internally
  AREXPORT ArTypes::Byte2 calcCheckSum(void);

  // only call finalizePacket before a send
  AREXPORT virtual void finalizePacket(void);

  /// Gets the time the packet was received at
  AREXPORT ArTime getTimeReceived(void);
  /// Sets the time the packet was received at
  AREXPORT void setTimeReceived(ArTime timeReceived);

protected:
  unsigned char mySync1;
  unsigned char mySync2;
  ArTime myTimeReceived;
};

#endif // ARROBOTPACKET_H


text:
[![Build Status](https://travis-ci.org/Vilsepi/infinimonkey.svg?branch=master)](https://travis-ci.org/Vilsepi/infinimonkey)

According to the [infinite monkey theorem](https://en.wikipedia.org/wiki/Infinite_monkey_theorem), with enough monkeys and time, you will be able to randomly produce the works of William Shakespeare. I do not have the time for that, so let's lower the bar a little:

- Instead of monkeys and typewriters, we will have cyborg monkeys from [AWS](https://aws.amazon.com/)
- Instead of randomness, we will use [Markov chains](https://en.wikipedia.org/wiki/Markov_chain)
- Instead of Shakespeare, we will aim at level of ordinary shitty tweets

We will also find out how well Markov chains work with Finnish. Initial tests seem promising:

- *Nightwish ja Children of Bodom ja Stratovarius ovat julkaisseet albumeita, jotka ovat kuntien ja yksityisten säätiöiden omistamia.*
- *Presidentti Risto Ryti erosi ja hänen pelättiin jäävän maahan laittomaksi siirtolaiseksi.*
- *Heti perustamisensa jälkeen maakunnilla ei ollut kovin selvää roolia, ja niiden lujuus ja kantavuus heikkeni kuumuuden vuoksi huomattavasti.*
- *Vastavuoroisesti lastenpsykiatrian alku Suomessa on käytössä myös Viron kansallislaulussa.*
- *Toinen vaihtoehto olisi ollut vain pyllyjä ja heiluvia rintoja, joiden tarkoitus oli ratkoa opillisia riitoja.*
- *Tätä aiemmin läänejä oli Ahvenanmaa mukaan lukien Aamulehti, Iltalehti ja Kauppalehti.*
- *Uskonnoissa on se suojattava työasemakohtaisella palomuuriohjelmalla.*
- *Peruskallio on monin paikoin yhteiskunnallista tyytymättömyyttä.*

## Planned architecture

![Monkey architecture](doc/infinimonkey_architecture.jpg)


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

long_description = '''
An asynchronous high-level networking framework built on top of the Curio library.
'''

setup(name='Curionet',
      description='Curionet, curio based framework.',
      long_description=long_description,
      license='Apache 2.0',
      version='1.0.1',
      author='Caleb Marshall',
      author_email='anythingtechpro@gmail.com',
      maintainer='Caleb Marshall',
      maintainer_email='anythingtechpro@gmail.com',
      url='https://github.com/AnythingTechPro/Curionet',
      packages=['curionet'],
      classifiers=[
          'Programming Language :: Python :: 3',
      ])


text:
@implementation GTLRCloudSecurityToken_GoogleIamV1Binding
@dynamic condition, members, role;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"members" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1AccessBoundary
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1AccessBoundary
@dynamic accessBoundaryRules;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"accessBoundaryRules" : [GTLRCloudSecurityToken_GoogleIdentityStsV1AccessBoundaryRule class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1AccessBoundaryRule
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1AccessBoundaryRule
@dynamic availabilityCondition, availablePermissions, availableResource;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"availablePermissions" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1betaAccessBoundary
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1betaAccessBoundary
@dynamic accessBoundaryRules;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"accessBoundaryRules" : [GTLRCloudSecurityToken_GoogleIdentityStsV1betaAccessBoundaryRule class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1betaAccessBoundaryRule
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1betaAccessBoundaryRule
@dynamic availabilityCondition, availablePermissions, availableResource;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"availablePermissions" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1betaOptions
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1betaOptions
@dynamic accessBoundary, audiences, userProject;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"audiences" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1ExchangeTokenRequest
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1ExchangeTokenRequest
@dynamic audience, grantType, options, requestedTokenType, scope, subjectToken,
         subjectTokenType;
@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1ExchangeTokenResponse
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1ExchangeTokenResponse
@dynamic accessToken, expiresIn, issuedTokenType, tokenType;

+ (NSDictionary<NSString *, NSString *> *)propertyToJSONKeyMap {
  NSDictionary<NSString *, NSString *> *map = @{
    @"accessToken" : @"access_token",
    @"expiresIn" : @"expires_in",
    @"issuedTokenType" : @"issued_token_type",
    @"tokenType" : @"token_type"
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1IntrospectTokenRequest
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1IntrospectTokenRequest
@dynamic token, tokenTypeHint;
@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1IntrospectTokenResponse
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1IntrospectTokenResponse
@dynamic active, clientId, exp, iat, iss, scope, sub, username;

+ (NSDictionary<NSString *, NSString *> *)propertyToJSONKeyMap {
  return @{ @"clientId" : @"client_id" };
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleIdentityStsV1Options
//

@implementation GTLRCloudSecurityToken_GoogleIdentityStsV1Options
@dynamic accessBoundary, audiences, userProject;

+ (NSDictionary<NSString *, Class> *)arrayPropertyToClassMap {
  NSDictionary<NSString *, Class> *map = @{
    @"audiences" : [NSString class]
  };
  return map;
}

@end

// ----------------------------------------------------------------------------
//
//   GTLRCloudSecurityToken_GoogleTypeExpr
//

@implementation GTLRCloudSecurityToken_GoogleTypeExpr
@dynamic descriptionProperty, expression, location, title;

+ (NSDictionary<NSString *, NSString *> *)propertyToJSONKeyMap {
  return @{ @"descriptionProperty" : @"description" };
}

@end


text:
"""Helper tags and filters easing the handling of bidi in templates

"""
from django import template
from django.template.defaultfilters import stringfilter
from django.utils import translation

register = template.Library()

def add_direction(value, arg=u"rtl_only"):
    """Adds direction to the element

    :arguments:
        arg
            * rtl_only: Add the direction only in case of a
              right-to-left language (default)
            * both: add the direction in both case
            * ltr_only: Add the direction only in case of a
              left-to-right language

    {{image_name|add_direction}} when image_name is 'start_arrow.png'
    results in 'start_arrow_rtl.png' in case of RTL language, and
    'start_arrow.png' or 'start_arrow_ltr.png' depends on `arg` value.

    """

    if arg == u'rtl_only':
        directions = (u'', u'_rtl')
    elif arg == u'both':
        directions = (u'_ltr', u'_rtl')
    elif arg == u'ltr_only':
        directions = (u'_ltr', u'')
    else:
        raise template.TemplateSyntaxError('add_direction can use arg with one of ["rtl_only", "both", "ltr_only"]')

    parts = value.rsplit('.', 1)
    if not len(parts):
        return value
    elif len(parts) == 1:
        return value + directions[translation.get_language_bidi()]
    else:
        return '.'.join((parts[0]+directions[translation.get_language_bidi()],parts[1]))
add_direction.is_safe = True

register.filter(add_direction)


text:
import os
import logging

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__) + "../../")
SUPPORTED_NONLOCALES = ['media', 'admin', 'static']
LANGUAGE_CODE = 'en-us'
ROOT_URLCONF = '{{ project_name }}.urls'

INSTALLED_APPS = (
    # Django contrib apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.admin',
    'django.contrib.humanize',
    'django.contrib.syndication',
    'django.contrib.staticfiles',

    # Third-party apps, patches, fixes
    'djcelery',
    'django_jenkins',
    'rest_framework',
    'debug_toolbar',
    'compressor',
    'django_nose',
    'south',
    'base',
)

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = False
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()
USE_I18N = True
USE_L10N = True
USE_TZ = True
TIME_ZONE = 'America/Los_Angeles'

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

MIDDLEWARE_CLASSES = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]

TEMPLATE_CONTEXT_PROCESSORS = [
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.media',
    'django.core.context_processors.request',
    'django.core.context_processors.i18n',
    'django.core.context_processors.static',
    'django.core.context_processors.csrf',
    'django.core.context_processors.tz',
    'django.contrib.messages.context_processors.messages',
]

TEMPLATE_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates'),
)

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

def custom_show_toolbar(request):
    """ Only show the debug toolbar to users with the superuser flag. """
    return request.user.is_superuser

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False,
    'SHOW_TOOLBAR_CALLBACK': '{{ project_name }}.settings.custom_show_toolbar',
    'INSERT_BEFORE': 'body',
    'SHOW_TEMPLATE_CONTEXT': True,
    'ENABLE_STACKTRACES': True,
}

FILE_UPLOAD_PERMISSIONS = 0664
WSGI_APPLICATION = '{{ project_name }}.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db/development.sqlite3',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',

    },
}

ADMINS = ()
MANAGERS = ADMINS

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    }
}

DEBUG = TEMPLATE_DEBUG = bool(os.environ.get('DEBUG', 'False'))
DEV = True

ALLOWED_HOSTS = []

SECRET_KEY = os.environ.get('SECRET_KEY', '{{ secret_key }}')

INTERNAL_IPS = ('127.0.0.1')

# Uncomment these to activate and customize Celery:
# CELERY_ALWAYS_EAGER = False  # required to activate celeryd
# BROKER_HOST = 'localhost'
# BROKER_PORT = 5672
# BROKER_USER = 'django'
# BROKER_PASSWORD = 'django'
# BROKER_VHOST = 'django'
# CELERY_RESULT_BACKEND = 'amqp'

SERVER_EMAIL = "webmaster@example.com"
DEFAULT_FROM_EMAIL = "webmaster@example.com"
SYSTEM_EMAIL_PREFIX = "[{{ project_name }}]"

LOG_LEVEL = logging.INFO
HAS_SYSLOG = True
SYSLOG_TAG = "http_app_{{ project_name }}"  # Make this unique to your project.
LOGGING_CONFIG = None
LOGGING = {
    'version': 1,
    'loggers': {
        '{{ project_name }}': {
            'level': "DEBUG"
        }
    }
}


text:
+++
title = "Automate Docker Container Publishing Flow"
description = "Automate Docker Container Publishing Flow"

[menu]
  [menu.habitat]
    title = "Automate Docker Container Publishing Flow"
    identifier = "habitat/reference/diagrams/docker-automated-flow"
    parent = "habitat/reference/diagrams"
    weight = 20

+++

![Chef Habitat Automated Docker Container Publishing Flow Diagram](/images/infographics/habitat-automated-docker-container-publishing-flow.png)


text:
import inspect

import sys
import os

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
from django.utils.encoding import force_unicode
from django.utils.html import strip_tags

sys.path.insert(0, os.path.abspath('.'))

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.conf import settings

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.doctest',
    'sphinx.ext.todo',
    'sphinx.ext.coverage',
    'sphinx.ext.pngmath',
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# The suffix of source filenames.
source_suffix = '.rst'

# The encoding of source files.
#source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = u'Django apogee'
copyright = u'2014, Paul Guichon, Georges Ciobotaru'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
language = 'fr'

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []

# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'

# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'default'

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}

# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
#html_title = None

# A shorter title for the navigation bar.  Default is the same as html_title.
#html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}

# If false, no module index is generated.
#html_domain_indices = True

# If false, no index is generated.
#html_use_index = True

# If true, the index is split into individual pages for each letter.
#html_split_index = False

# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None

# Output file base name for HTML help builder.
htmlhelp_basename = 'Djangoapogeedoc'

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#'preamble': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
  ('index', 'Djangoapogee.tex', u'Django apogee Documentation',
   u'Paul Guichon, Georges Ciobotaru', 'manual'),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False

# If true, show page references after internal links.
#latex_show_pagerefs = False

# If true, show URL addresses after external links.
#latex_show_urls = False

# Documents to append as an appendix to all manuals.
#latex_appendices = []

# If false, no module index is generated.
#latex_domain_indices = True

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'djangoapogee', u'Django apogee Documentation',
     [u'Paul Guichon, Georges Ciobotaru'], 1)
]

# If true, show URL addresses after external links.
#man_show_urls = False

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
  ('index', 'Djangoapogee', u'Django apogee Documentation',
   u'Paul Guichon, Georges Ciobotaru', 'Djangoapogee', 'One line description of project.',
   'Miscellaneous'),
]

# Documents to append as an appendix to all manuals.
#texinfo_appendices = []

# If false, no module index is generated.
#texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

def process_docstring(app, what, name, obj, options, lines):
    # This causes import errors if left outside the function
    from django.db import models

    # Only look at objects that inherit from Django's base model class
    if inspect.isclass(obj) and issubclass(obj, models.Model):
        # Grab the field list from the meta class
        fields = obj._meta.fields

        for field in fields:
            # Decode and strip any html out of the field's help text
            help_text = strip_tags(field.help_text).encode('utf-8')

            # Decode and capitalize the verbose name, for use if there isn't
            # # any help text
            try:
                verbose_name = field.verbose_name.encode('utf-8').capitalize()
            except AttributeError:
                str(field.verbose_name).encode('utf-8').capitalize()
            if help_text:
                # Add the model field to the end of the docstring as a param
                # using the help text as the description
                lines.append(u':param %s: %s' % (field.attname, help_text))
            else:
                # Add the model field to the end of the docstring as a param
                # using the verbose name as the description
                lines.append(u':param %s: %s' % (field.attname, verbose_name.decode('utf-8')))

            # Add the field's type to the docstring
            lines.append(u':type %s: %s' % (field.attname, type(field).__name__))

    # Return the extended docstring
    return lines

def setup(app):
    # Register the docstring processor with sphinx
    app.connect('autodoc-process-docstring', process_docstring)


text:
package root.adt;

import java.util.Collection;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import root.annotation.Delegate;
import root.lang.Itemizer;
import root.util.Root;

/**
 *
 * @author Edward Smith
 * @version 0.5
 * @since 0.5
 *
 * @param <K>
 *            the {@link Map.Entry} key type
 * @param <V>
 *            the {@link Map.Entry} value type
 */
@Delegate
class MapEntrySet<K, V> implements Set<java.util.Map.Entry<K, V>> {

	// <><><><><><><><><><><><><>< Private Classes ><><><><><><><><><><><><><>

	/**
	 * A {@link java.util.Iterator} for the {@code MapEntrySet}. It is pointless to implement {@link Itemizer} here since we are implementing
	 * {@link java.util.Set}.
	 *
	 * @author Edward Smith
	 * @version 0.5
	 * @since 0.5
	 */
	private final class Iterator implements java.util.Iterator<java.util.Map.Entry<K, V>> {

		// <><><><><><><><><><><><><><> Attributes <><><><><><><><><><><><><><>

		final Itemizer<MapEntry<K, V>> itemizer = MapEntrySet.this.map.iterator();

		// <><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><>

		@Override
		public final boolean hasNext() {
			return this.itemizer.hasNext();
		}

		@Override
		public final MapEntry<K, V> next() {
			if (!this.itemizer.hasNext()) {
				throw new NoSuchElementException();
			}

			return this.itemizer.next();
		}

		@Override
		public final void remove() {
			throw new UnsupportedOperationException();
		}

	} // End Iterator

	// <><><><><><><><><><><><><><><> Attributes <><><><><><><><><><><><><><><>

	final RootMap<K, V> map;

	// <><><><><><><><><><><><><><>< Constructors ><><><><><><><><><><><><><><>

	MapEntrySet(final RootMap<K, V> map) {
		this.map = map;
	}

	// <><><><><><><><><><><><><><> Public Methods <><><><><><><><><><><><><><>

	@Override
	public final boolean add(final java.util.Map.Entry<K, V> mapEntry) {
		this.map.put(mapEntry.getKey(), mapEntry.getValue());

		return true;
	}

	@Override
	public final boolean addAll(final Collection<? extends java.util.Map.Entry<K, V>> collection) {
		for (final Map.Entry<K, V> mapEntry : collection) {
			this.map.put(mapEntry.getKey(), mapEntry.getValue());
		}

		return true;
	}

	@Override
	public final void clear() {
		this.map.clear();
	}

	@Override
	public final boolean contains(final Object obj) {
		if (obj instanceof Map.Entry) {
			final Map.Entry<?, ?> mapEntry = (Map.Entry<?, ?>) obj;

			return this.map.containsEntry(mapEntry.getKey(), mapEntry.getValue());
		}

		return false;
	}

	@Override
	public final boolean containsAll(final Collection<?> collection) {
		if (collection != null && collection.size() > 0) {
			final java.util.Iterator<?> itr = collection.iterator();
			final Object obj;
			Map.Entry<?, ?> mapEntry = null;

			obj = itr.next();

			if (obj instanceof Map.Entry) {
				mapEntry = (Map.Entry<?, ?>) obj;

				if (this.map.containsEntry(mapEntry.getKey(), mapEntry.getValue())) {
					while (itr.hasNext()) {
						mapEntry = (Map.Entry<?, ?>) itr.next();

						if (!this.map.containsEntry(mapEntry.getKey(), mapEntry.getValue())) {
							return false;
						}
					}

					return true;
				}
			}
		}

		return false;
	}

	@Override
	public final boolean isEmpty() {
		return this.map.isEmpty();
	}

	@Override
	public final java.util.Iterator<java.util.Map.Entry<K, V>> iterator() {
		return new Iterator();
	}

	@Override
	public final boolean remove(final Object obj) {
		if (obj instanceof Map.Entry) {
			final Map.Entry<?, ?> mapEntry = (Map.Entry<?, ?>) obj;

			return this.map.remove(mapEntry.getKey()) != null;
		}

		return false;
	}

	@Override
	public final boolean removeAll(final Collection<?> collection) {
		if (collection != null && collection.size() > 0) {
			final java.util.Iterator<?> itr = collection.iterator();
			final Object obj;
			Map.Entry<?, ?> mapEntry = null;

			obj = itr.next();

			if (obj instanceof Map.Entry) {
				mapEntry = (Map.Entry<?, ?>) obj;

				this.map.remove(mapEntry.getKey());

				while (itr.hasNext()) {
					mapEntry = (Map.Entry<?, ?>) itr.next();

					this.map.remove(mapEntry.getKey());
				}

				return true;
			}
		}

		return false;
	}

	@Override
	public final boolean retainAll(final Collection<?> collection) {
		if (collection != null && collection.size() > 0) {
			final int originalSize = this.map.size();

			for (final Itemizer<MapEntry<K, V>> itemizer = this.map.iterator(); itemizer.hasNext();) {
				if (!collection.contains(itemizer.next())) {
					itemizer.remove();
				}
			}

			return originalSize != this.map.size();
		}

		return false;
	}

	@Override
	public final int size() {
		return this.map.size();
	}

	@Override
	public final Object[] toArray() {
		final Object[] array = new Object[this.map.size()];
		int i = 0;

		for (final java.util.Map.Entry<K, V> mapEntry : this.map) {
			array[i++] = mapEntry;
		}

		return array;
	}

	@Override
	public final <T> T[] toArray(final T[] arrayVar) {
		final T[] array = Root.newArray(arrayVar, this.map.size());
		int i = 0;

		for (final java.util.Map.Entry<K, V> mapEntry : this.map) {
			array[i++] = Root.cast(mapEntry);
		}

		return array;
	}

} // End MapEntrySet


text:
package org.apache.hadoop.hbase.ipc;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HConstants;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;

/**
 * A scheduler that maintains isolated handler pools for general, high-priority and replication
 * requests.
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class SimpleRpcScheduler implements RpcScheduler {

  private int port;
  private final int handlerCount;
  private final int priorityHandlerCount;
  private final int replicationHandlerCount;
  private final PriorityFunction priority;
  final BlockingQueue<CallRunner> callQueue;
  final BlockingQueue<CallRunner> priorityCallQueue;
  final BlockingQueue<CallRunner> replicationQueue;
  private volatile boolean running = false;
  private final List<Thread> handlers = Lists.newArrayList();
  private AtomicInteger activeHandlerCount = new AtomicInteger(0);
  /** What level a high priority call is at. */
  private final int highPriorityLevel;

  /**
   * @param conf
   * @param handlerCount the number of handler threads that will be used to process calls
   * @param priorityHandlerCount How many threads for priority handling.
   * @param replicationHandlerCount How many threads for replication handling.
   * @param highPriorityLevel
   * @param priority Function to extract request priority.
   */
  public SimpleRpcScheduler(
      Configuration conf,
      int handlerCount,
      int priorityHandlerCount,
      int replicationHandlerCount,
      PriorityFunction priority,
      int highPriorityLevel) {
    int maxQueueLength = conf.getInt("ipc.server.max.callqueue.length",
        handlerCount * RpcServer.DEFAULT_MAX_CALLQUEUE_LENGTH_PER_HANDLER);
    this.handlerCount = handlerCount;
    this.priorityHandlerCount = priorityHandlerCount;
    this.replicationHandlerCount = replicationHandlerCount;
    this.priority = priority;
    this.highPriorityLevel = highPriorityLevel;
    this.callQueue = new LinkedBlockingQueue<CallRunner>(maxQueueLength);
    this.priorityCallQueue = priorityHandlerCount > 0
        ? new LinkedBlockingQueue<CallRunner>(maxQueueLength)
        : null;
    this.replicationQueue = replicationHandlerCount > 0
        ? new LinkedBlockingQueue<CallRunner>(maxQueueLength)
        : null;
  }

  @Override
  public void init(Context context) {
    this.port = context.getListenerAddress().getPort();
  }

  @Override
  public void start() {
    running = true;
    startHandlers(handlerCount, callQueue, null);
    if (priorityCallQueue != null) {
      startHandlers(priorityHandlerCount, priorityCallQueue, "Priority.");
    }
    if (replicationQueue != null) {
      startHandlers(replicationHandlerCount, replicationQueue, "Replication.");
    }
  }

  private void startHandlers(
      int handlerCount,
      final BlockingQueue<CallRunner> callQueue,
      String threadNamePrefix) {
    for (int i = 0; i < handlerCount; i++) {
      Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
          consumerLoop(callQueue);
        }
      });
      t.setDaemon(true);
      t.setName(Strings.nullToEmpty(threadNamePrefix) + "RpcServer.handler=" + i + ",port=" + port);
      t.start();
      handlers.add(t);
    }
  }

  @Override
  public void stop() {
    running = false;
    for (Thread handler : handlers) {
      handler.interrupt();
    }
  }

  @Override
  public void dispatch(CallRunner callTask) throws InterruptedException {
    RpcServer.Call call = callTask.getCall();
    int level = priority.getPriority(call.header, call.param);
    if (priorityCallQueue != null && level > highPriorityLevel) {
      priorityCallQueue.put(callTask);
    } else if (replicationQueue != null && level == HConstants.REPLICATION_QOS) {
      replicationQueue.put(callTask);
    } else {
      callQueue.put(callTask); // queue the call; maybe blocked here
    }
  }

  @Override
  public int getGeneralQueueLength() {
    return callQueue.size();
  }

  @Override
  public int getPriorityQueueLength() {
    return priorityCallQueue == null ? 0 : priorityCallQueue.size();
  }

  @Override
  public int getReplicationQueueLength() {
    return replicationQueue == null ? 0 : replicationQueue.size();
  }

  @Override
  public int getActiveRpcHandlerCount() {
    return activeHandlerCount.get();
  }

  private void consumerLoop(BlockingQueue<CallRunner> myQueue) {
    while (running) {
      try {
        CallRunner task = myQueue.take();
        try {
          activeHandlerCount.incrementAndGet();
          task.run();
        } finally {
          activeHandlerCount.decrementAndGet();
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
  }
}


text:
namespace Votyra.Core.TerrainMeshes
{
    public interface ITerrainMeshWithFixedCapacity : ITerrainMesh
    {
        int TriangleCapacity { get; }

        void Initialize(int triangleCapacity);
    }
}


text:
cherry-pick
===========

Scrapes IMDB ratings for an entire run of a television series and plots them with gRaphaël

This tool allows the best episodes to be skimmed from lightly-serialized shows while maintaining the overarching continuity.

A Python script runs with a title query and gathers episode information into a JSON structure that is consumed by the graph. The data can be served as static files or dynamically with a database - tweak the endpoints to your needs.

> Note: this is a web scaper and is subject to break at any point due to document restructuring on IMDB's part.

A connector for RethinkDB is provided to load results into a database.

Install
-------

The script is made for Python 3 and uses the Requests and Beautiful Soup packages, as saved in the requirements file:

	pip install -r requirements.txt

Install the `rethinkdb` package to use the database connector.

Usage
-----

	python cherrypick.py [-h] [--seasons SEASONS] [-o OUTFILE] query

The **query** should be precise enough to ensure that the target show is the first result in a title query on IMDB. The **seasons** parameter can be a comma-delimited list or a hyphen-delimited range or a combination of both.

	python cherrypick.py "red dwarf" --seasons 1,3,5-7 -o red_dwarf.json

To use the database connector, provide the connection string in the format `host:port/db`.

	python cherrypick.py "the it crowd" --db localhost:28015/cherry

You can also pipe the JSON through stdout with the `--pipe` option. Program messages are sent over stderr.


text:
The sample demonstrates how to make a Web Barcode Reader app with PHP, Nginx and Dynamsoft Barcode Reader SDK on Windows.

Prerequisites
-------------
* [Nginx][1]
* [PHP][2]
* [Dynamsoft Barcode Reader SDK][3]

How to Build PHP Custom Extension with Dynamsoft Barcode Reader SDK
-------------------------------------------------------------------
Please read [Making PHP Barcode Extension with Dynamsoft Barcode SDK][4] to learn how to build **php_dbr.dll**.

How to Configure PHP Environment
---------------------------------
1. Copy **php_dbr.dll** to **%php%\ext**.
2. Copy **DynamsoftBarcodeReaderx86.dll** to PHP root directory **%php%\**.
3. Open **%php%\php.ini** and add following line:

    ```
    extension=php_dbr.dll
    ```
    Change max file size if you want to upload big image files:

    ```
    upload_max_filesize=20M
    ```

How to Configure Nginx for PHP
-------------------------------------------------------
1. Open **%nginx%\conf\nginx.conf** and add PHP configuration:

    ```
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME <Your Web App Folder>/$fastcgi_script_name;
        include        fastcgi_params;
    }
    ```
    When uploading big files, you may see the error **nginx 413 Request Entity Too Large**. To fix it, change file size in configuration file:

    ```
    client_max_body_size 50M;
    ```

How to Run the PHP Barcode App
------------------------------
1. Run **php-cgi**:

    ```
    %php%\php-cgi.exe -b 127.0.0.1:9000 -c %php%\php.ini
    ```
2. Run **Nginx**:

    ```
    %nginx%\nginx.exe
    ```
3. Visit ``localhost:8080/index.php``
    ![load barcode image](http://www.codepool.biz/wp-content/uploads/2015/11/php_dbr_upload.png)

    ![read barcode](http://www.codepool.biz/wp-content/uploads/2015/11/php_dbr_result.png)

Reference
---------
* http://rfvallina.com/blog/2015/08/22/preview-tiff-and-pdf-files-using-html5-file-api/

Blog
------
[How to Create a Web Barcode Reader App with PHP and Nginx][5]

[1]:http://nginx.org/en/download.html
[2]:http://php.net/downloads.php
[3]:http://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx
[4]:http://www.codepool.biz/php-windows-barcode-reader-extension.html
[5]:http://www.codepool.biz/php-nginx-web-barcode-reader.html


text:
package version

import "runtime/debug"

func init() {
	fixBuild = buildInfoFixBuild
}

func buildInfoFixBuild(v *Version) {
	info, ok := debug.ReadBuildInfo()
	if !ok {
		return
	}
	for i := range info.Settings {
		if info.Settings[i].Key == "gitrevision" {
			v.Build = info.Settings[i].Value
			break
		}
	}
}


text:
<Record>
<Term>Berocca pn</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Ascorbic acid;biotin;cyanocobalamin;dexpanthenol;ergocalciferol;folic acid;niacinamide;pyridoxine hydrochloride;riboflavin phosphate sodium;thiamine hydrochloride;vitamin a palmitate;vitamin e</Synonym>
<Synonym>Ascorbic acid-biotin-cyanocobalamin-dexpanthenol-ergocalciferol-folic acid-niacinamide-pyridoxine-riboflavin phosphate-thiamine-vitamin a palmitate-vitamin e</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/app';
import TracksPage from './containers/tracks-page';
import SearchPage from './containers/search-page';
import AlbumsPage from './containers/albums-page';
import ArtistsPage from './containers/artists-page';
import Queue from './containers/queue';
import Artist from './containers/artist';
import Album from './containers/album';

export default (
  <Route path="/" component={App}>
    <IndexRoute component={TracksPage} />
    <Route path="/search" component={SearchPage} />
    <Route path="/albums" component={AlbumsPage} />
    <Route path="/artists" component={ArtistsPage} />
    <Route path="/queue" component={Queue} />
    <Route path="/artist/:id" component={Artist} />
    <Route path="/album/:id" component={Album} />
  </Route>
);


text:
=====
snote
=====
.. image:: https://travis-ci.org/tomokinakamaru/snote.svg?branch=master
    :target: https://travis-ci.org/tomokinakamaru/snote
    :alt: perth Build

About
=====

A tool for generating signed, time-limited & tagged tokens of python objects.

Example
=======

.. sourcecode:: python

    import snote

    # instanciate snote.Codec with your secret key
    sncodec = snote.Codec('secret-key')

    # the object to encode
    obj = {'user_id': 1}
    encoded_obj = sncodec.encode(obj)

    # retrieve the token to carry around
    token = encoded_obj.token
    print(encoded_obj.timestamp)  # timestamp of token generation
    print(encoded_obj.tag)  # use this tag to manage tokens' validity

    # decode from token
    decoded_obj = sncodec.decode(token)
    print(decoded_obj.obj)  # {'user_id': 1}
    print(decoded_obj.tag == encoded_obj.tag)  # True
    print(decoded_obj.is_expired(10))  # if the token age is less than 10 secs


text:
using CircuitSimulation.Library.Data;
using CircuitSimulation.Library.Elements;

namespace CircuitSimulation.Library.CircuitBuilders
{
    public class GeneratorBuilder : ElementBuilder<Generator, GeneratorData>
    {
        protected override Generator Build(GeneratorData data, Simulation simulation)
        {
            var generator = new Generator(data.Delay, simulation);
            generator.Id = data.Id;
            generator.Output.Id = data.Output.Id;
            generator.Output.SetInitialSocketSignal(Signal.FromSignalType(data.Output.Signal));
            return generator;
        }
    }

}


text:
package de.timedout.oc.browser;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.di.Persist;
import org.eclipse.e4.ui.model.application.ui.MDirtyable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.ObservableElementList;
import ca.odell.glazedlists.SortedList;
import ca.odell.glazedlists.matchers.Matcher;
import ca.odell.glazedlists.swt.DefaultEventTableViewer;
import ca.odell.glazedlists.swt.GlazedListsSWT;
import ca.odell.glazedlists.swt.TableComparatorChooser;
import de.timedout.oc.browser.cells.CustomTableItemConfigurer;
import de.timedout.oc.browser.columns.AdvancedFileTypeComparator;
import de.timedout.oc.browser.columns.BasenameColumn;
import de.timedout.oc.browser.columns.BrowserColumn;
import de.timedout.oc.browser.columns.ColumnTableFormat;
import de.timedout.oc.browser.columns.ExtensionColumn;
import de.timedout.oc.browser.columns.FilesizeColumn;
import de.timedout.oc.browser.model.Element;
import de.timedout.oc.browser.model.LocationMediator;
import de.timedout.oc.browser.model.LocationMediator.PopulateListener;
import de.timedout.oc.browser.model.ParentElement;
import de.timedout.oc.browser.model.PathElement;
import de.timedout.oc.browser.model.PathListManager;
import de.timedout.oc.browser.model.SystemElement;
import de.timedout.oc.browser.model.SystemListManager;

public class BrowserPart {

	@Inject
	private MDirtyable dirty;

	private Text label;

	private Table table;

	private Element location = null;

	private LocationMediator locationManager = null;

	private ObservableElementList<Element> observableList;

	private SortedList<Element> sortedList;

	private SortedList<Element> groupingList;

	private DefaultEventTableViewer<Element> tableViewer;

	private Composite parent;

	@PostConstruct
	public void createComposite(Composite parent) {
		this.parent = parent;

		GridLayout layout = new GridLayout(1, false);
		layout.marginHeight = 0;
		layout.marginWidth = 0;

		parent.setLayout(layout);

		label = new Text(parent, SWT.NONE);
		label.setText("Hallo");
		label.setEditable(false);
		label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		List<BrowserColumn<?>> columnList = new ArrayList<BrowserColumn<?>>();
		// columnList.add(new TypeColumn());
		columnList.add(new BasenameColumn());
		columnList.add(new ExtensionColumn());
		columnList.add(new FilesizeColumn());

		EventList<Element> eventList = GlazedLists.eventList(new ArrayList<Element>());

		ObservableElementList.Connector<Element> beanConnector = GlazedLists.beanConnector(Element.class);
		observableList = new ObservableElementList<Element>(eventList, beanConnector);

		FilterList<Element> filterList = new FilterList<Element>(observableList, new Matcher<Element>() {
			@Override
			public boolean matches(Element element) {
				return !element.isHidden() && element.isReadable();
			}
		});

		sortedList = new SortedList<Element>(filterList, new AdvancedFileTypeComparator());

		table = new Table(parent, SWT.NONE | SWT.V_SCROLL | SWT.H_SCROLL | SWT.VIRTUAL | SWT.FULL_SELECTION | SWT.SINGLE);
		table.setLayoutData(new GridData(GridData.FILL_BOTH));

		groupingList = new SortedList<Element>(sortedList, new AdvancedFileTypeComparator());

		tableViewer = GlazedListsSWT.eventTableViewerWithThreadProxyList(groupingList, table, new ColumnTableFormat(columnList));
		tableViewer.setTableItemConfigurer(new CustomTableItemConfigurer());

		TableComparatorChooser<Element> tcc = TableComparatorChooser.install(tableViewer, sortedList, false);

		table.setHeaderVisible(true);
		// table.setLinesVisible(true);

		table.addListener(SWT.Selection, new Listener() {
			@Override
			public void handleEvent(Event event) {

			}
		});

		/*
		 * table.addPaintListener(new PaintListener() {
		 *
		 * @Override public void paintControl(PaintEvent e) {
		 * e.gc.drawFocus(e.x, e.y, e.width, e.height);
		 *
		 * } });
		 */

		Path directory = Paths.get(System.getProperty("user.home"));
		setLocation(new PathElement(directory));

		/*
		 * Thread t = new Thread(){ public void run(){ try {
		 * Thread.sleep(50000); } catch (InterruptedException e) {
		 * e.printStackTrace(); } pathListManager.disconnect(); } }; t.start();
		 */

		/*
		 * table.addKeyListener(new KeyListener() {
		 *
		 * @Override public void keyReleased(org.eclipse.swt.events.KeyEvent e)
		 * { System.out.println("release "+e); }
		 *
		 * @Override public void keyPressed(org.eclipse.swt.events.KeyEvent e) {
		 * System.out.println("pressed "+e); } });
		 */

		/*
		 * EventList<Element> list = tableViewer.getSelected();
		 *
		 * list.addListEventListener(new ListEventListener<Element>() {
		 *
		 * @Override public void listChanged(ListEvent<Element> event) {
		 * if(!list.isEmpty()){ Element element = list.get(0);
		 * selectionCache.put(location, element); } } });
		 */

		for (Method method : table.getClass().getDeclaredMethods()) {
			if (method.toString().toLowerCase().contains("focus")) {
				System.out.println(method);
			}
		}

		try {
			setTableFocusMethod = table.getClass().getDeclaredMethod("setFocusIndex", Integer.TYPE);
			setTableFocusMethod.setAccessible(true);
		} catch (NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}

		tcc.addSortListener(new Listener() {
			@Override
			public void handleEvent(Event arg0) {
				System.out.println(arg0);
				observableList.getReadWriteLock().writeLock().lock();
				try {
					EventList<Element> list = tableViewer.getSelected();
					if(list.size()>0){
						Element e = list.iterator().next();
						System.out.println(groupingList.indexOf(e));
						setTableFocusMethod.invoke(table, groupingList.indexOf(e));
						table.showItem(table.getItem(groupingList.indexOf(e)));
						table.setFocus();
						table.redraw();
					}
				} catch (IllegalAccessException | InvocationTargetException e) {
					e.printStackTrace();
				}
				observableList.getReadWriteLock().writeLock().unlock();

			}
		});
	}

	Method setTableFocusMethod = null;

	Map<Element, Element> selectionCache = new HashMap<Element, Element>();

	public synchronized void setLocation(Element location) {
		if (location == null) {
			return;
		}

		if (this.location != null && location.equals(this.location.getParent())) { // parent
																					// navigation
			System.out.println(this.location + " " + location);
			selectionCache.put(location, this.location);
		}

		if (locationManager != null) {
			locationManager.disconnect();
		}

		if (location instanceof PathElement) {
			locationManager = new PathListManager();
		} else if (location instanceof SystemElement) {
			locationManager = new SystemListManager();
		} else if (location instanceof ParentElement) {
			setLocation(this.location.getParent());
			return;
		}

		this.location = location;

		label.setText(location.toString());

		locationManager.init(observableList, location);

		locationManager.addPopulateListener(new PopulateListener() {
			@Override
			public void finished() {
				Display.getDefault().asyncExec(new Runnable() {
					@Override
					public void run() {
						observableList.getReadWriteLock().writeLock().lock();
						// table.select(1);
						table.setFocus();

						EventList<Element> list = tableViewer.getTogglingSelected();

						Element selectionItem = selectionCache.get(location);
						try {
							if (selectionItem != null && observableList.contains(selectionItem)) {
								list.add(selectionItem);
								try {
									setTableFocusMethod.invoke(table, groupingList.indexOf(selectionItem));
									table.redraw();
								} catch (IllegalAccessException | InvocationTargetException e) {
									e.printStackTrace();
								}
							} else {
								list.add(sortedList.get(0));
							}
						} catch (IllegalArgumentException | IndexOutOfBoundsException e) {
						}

						/*
						 * System.out.println(table.getSelectionIndex()+" "+table
						 * .getItem(table.getSelectionIndex()));
						 * table.showItem(table
						 * .getItem(table.getSelectionIndex()));
						 *
						 * System.out.println(observableList.get(1));
						 */
						observableList.getReadWriteLock().writeLock().unlock();
					}
				});

			}
		});

		locationManager.connect();
	}

	public Element getLocation() {
		return location;
	}

	@Focus
	public void setFocus() {
		table.setFocus();
	}

	@Persist
	public void save() {
		dirty.setDirty(false);
	}

	public Element getCursorElement() {
		EventList<Element> selected = tableViewer.getSelected();

		if (selected.size() == 1) {
			return selected.get(0);
		}

		return null;
	}
}


text:
<?php

namespace PhpMigration\Changes\v5dot5;

use PhpMigration\Changes\AbstractIntroducedTest;

class IntroducedTest extends AbstractIntroducedTest
{
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar.string;

import org.elasticsearch.xpack.ql.expression.Expression;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
import org.elasticsearch.xpack.ql.tree.Source;
import org.elasticsearch.xpack.ql.type.DataType;
import org.elasticsearch.xpack.ql.type.DataTypes;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor.StringOperation;

/**
 * Returns the length (number of characters) in a string, excluding the trailing blanks.
 */
public class Length extends UnaryStringFunction {

    public Length(Source source, Expression field) {
        super(source, field);
    }

    @Override
    protected NodeInfo<Length> info() {
        return NodeInfo.create(this, Length::new, field());
    }

    @Override
    protected Length replaceChild(Expression newChild) {
        return new Length(source(), newChild);
    }

    @Override
    protected StringOperation operation() {
        return StringOperation.LENGTH;
    }

    @Override
    public DataType dataType() {
        return DataTypes.INTEGER;
    }

}


text:
(function () {
    var Bundle = new Class({
        "initialize": function (creator) {
            this.creator = creator;

            // Create DOM elements
            this.tab = new Element("div", {"class": "tab"});
            this.content = new Element("div", {"class": "tab-content"});

            // Create event handlers
            this.tab.addEvent("click", this.activate.bind(this));
        },

        "activate": function () {
            if (this.creator.activeBundle && this.creator.activeBundle !== this) {
                this.creator.activeBundle.deactivate();
            }
            this.tab.addClass("active");
            this.content.addClass("show");
            this.creator.activeBundle = this;
        },

        "deactivate": function () {
            this.tab.removeClass("active");
            this.content.removeClass("show");
            this.creator.activeBundle = null;
        }
    });

    this.Tab = new Class({
        "activeBundle": null,

        "initialize": function (tabContainer, tabContentContainer) {
            this.tabContainer = tabContainer;
            this.tabContentContainer = tabContentContainer;
        },

        "create": function () {
            var bundle = new Bundle(this);
            bundle.tab.inject(this.tabContainer);
            bundle.content.inject(this.tabContentContainer);
            if (!this.activeBundle) { bundle.activate(); }
            return bundle;
        }
    });
}());


text:
unsafe impl Sync for crate::syslog::State {}
unsafe impl Send for crate::syslog::State {}
pub use super::win::syslog::PlatformSyslog;


text:
require "google/cloud/video/stitcher/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::Video::Stitcher::V1::VideoStitcherService::Client#delete_cdn_key
#
def delete_cdn_key
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Video::Stitcher::V1::VideoStitcherService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Video::Stitcher::V1::DeleteCdnKeyRequest.new

  # Call the delete_cdn_key method.
  result = client.delete_cdn_key request

  # The returned object is of type Google::Protobuf::Empty.
  p result
end
# [END videostitcher_v1_generated_VideoStitcherService_DeleteCdnKey_sync]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sqrt
{
    class Program
    {
        static void Main(string[] args)
        {
            double num = Math.Sqrt(12345);
            Console.WriteLine(num);

        }
    }
}


text:
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using Steropes.UI.Components;
using Steropes.UI.Platform;

namespace Steropes.UI.Widgets
{
  /// <summary>
  ///   A clickable Button containing a Label and an optional Image icon
  /// </summary>
  public class Button : ButtonBase<IconLabel>
  {
    public Button(IUIStyle style, string text = "", IUITexture iconTex = null) : base(style)
    {
      Content = new IconLabel(style) { Texture = iconTex, Text = text, Enabled = false, Anchor = AnchoredRect.CreateHorizontallyStretched() };
    }
  }
}


text:
'use strict';

module.exports = function(app) {
	var users = require('../../app/controllers/users.server.controller');
	var enquires = require('../../app/controllers/enquires.server.controller');

	// Enquires Routes
	app.route('/enquires')
		.get(enquires.list)
		.post(users.requiresLogin, enquires.create);

	app.route('/enquires/:enquireId')
		.get(enquires.read)
		.put(users.requiresLogin, enquires.hasAuthorization, enquires.update)
		.delete(users.requiresLogin, enquires.hasAuthorization, enquires.delete);

	app.route('/enquires/addVisit/:enquireId')
		.get(enquires.increseVisitCounter);

	app.route('/enquires/search/:query')
		.get(enquires.search);

	// Finish by binding the Enquire middleware
	app.param('enquireId', enquires.enquireByID);
};