text:
<?php

namespace Acacha\AdminLTETemplateLaravel\Providers;

use Acacha\AdminLTETemplateLaravel\Facades\AdminLTE;
use Illuminate\Console\AppNamespaceDetectorTrait;
use Illuminate\Support\ServiceProvider;

/**
 * Class AdminLTETemplateServiceProvider.
 */
class AdminLTETemplateServiceProvider extends ServiceProvider
{
    use AppNamespaceDetectorTrait;

    /**
     * Register the application services.
     */
    public function register()
    {
        if (!defined('ADMINLTETEMPLATE_PATH')) {
            define('ADMINLTETEMPLATE_PATH', realpath(__DIR__.'/../../'));
        }

        if ($this->app->runningInConsole()) {
            $this->commands([\Acacha\AdminLTETemplateLaravel\Console\AdminLTE::class]);
        }

        $this->app->bind('AdminLTE', function () {
            return new \Acacha\AdminLTETemplateLaravel\AdminLTE();
        });
    }

    /**
     * Bootstrap the application services.
     */
    public function boot()
    {
        $this->defineRoutes();
        $this->publishHomeController();
        $this->changeAuthController();
        $this->publishPublicAssets();
        $this->publishViews();
        $this->publishResourceAssets();
        $this->publishTests();
        $this->publishLanguages();
    }

    /**
     * Define the AdminLTETemplate routes.
     */
    protected function defineRoutes()
    {
        if (!$this->app->routesAreCached()) {
            $router = app('router');

            $router->group(['namespace' => $this->getAppNamespace().'Http\Controllers'], function () {
                require __DIR__.'/../Http/routes.php';
            });
        }
    }

    /**
     * Publish Home Controller.
     */
    private function publishHomeController()
    {
        $this->publishes(AdminLTE::homeController(), 'adminlte');
    }

    /**
     * Change default Laravel AuthController.
     */
    private function changeAuthController()
    {
        $this->publishes(AdminLTE::authController(), 'adminlte');
    }

    /**
     * Publish public resource assets to Laravel project.
     */
    private function publishPublicAssets()
    {
        $this->publishes(AdminLTE::publicAssets(), 'adminlte');
    }

    /**
     * Publish package views to Laravel project.
     */
    private function publishViews()
    {
        $this->loadViewsFrom(ADMINLTETEMPLATE_PATH.'/resources/views/', 'adminlte');

        $this->publishes(AdminLTE::views(), 'adminlte');
    }

    /**
     * Publish package resource assets to Laravel project.
     */
    private function publishResourceAssets()
    {
        $this->publishes(AdminLTE::resourceAssets(), 'adminlte');
    }

    /**
     * Publish package tests to Laravel project.
     */
    private function publishTests()
    {
        $this->publishes(AdminLTE::tests(), 'adminlte');
    }

    /**
     * Publish package language to Laravel project.
     */
    private function publishLanguages()
    {
        $this->loadTranslationsFrom(ADMINLTETEMPLATE_PATH.'/resources/lang/', 'adminlte_lang');

        $this->publishes([
            ADMINLTETEMPLATE_PATH.'/resources/lang/' => resource_path('lang/vendor/adminlte_lang'),
        ]);
    }
}


text:
import React from "react";
import { mount } from "enzyme";
import Inner from "../inner";
import withDebounce from "../../src/debounce";

jest.useFakeTimers();

// Alias the confusingly misnamed runTimersToTime to advanceTimersByTime
// Jest has done this in v22, so this can be removed if we upgrade
jest.advanceTimersByTime = jest.runTimersToTime;

describe("Debounce web test", () => {
  it("updates debounceProps once for many closely spaced props updates", () => {
    const Outer = withDebounce(Inner);
    const component = mount(<Outer debounceTimeMs={1000} foo="initialFoo" />);

    const numberOfDebouncedPropsUpdates = () =>
      component
        .update()
        .find("Inner")
        .instance().numberOfDebouncedPropsUpdates;

    expect(numberOfDebouncedPropsUpdates()).toEqual(0);

    component.setProps({ foo: "updatedFoo1" });
    jest.advanceTimersByTime(600);
    component.setProps({ foo: "updatedFoo2" });
    jest.advanceTimersByTime(600);
    component.setProps({ foo: "updatedFoo3" });
    jest.advanceTimersByTime(600);
    component.setProps({ foo: "updatedFoo4" });
    jest.advanceTimersByTime(1200);

    expect(numberOfDebouncedPropsUpdates()).toEqual(1);
  });
});

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

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

#### Published in
Annls Sci. Nat. , Bot. , sér. 3 5: 163 (1846)

#### Original name
Bovista paludosa Lév., 1846

### Remarks
null


text:
if(NOT WIN32)
  find_package(PkgConfig)
  if(PKG_CONFIG_FOUND)
    if(TinyXML_FIND_VERSION)
      if(TinyXML_FIND_VERSION_EXACT)
        pkg_check_modules(PC_TINYXML QUIET tinyxml2=${TinyXML_FIND_VERSION})
      else(TinyXML_FIND_VERSION_EXACT)
        pkg_check_modules(PC_TINYXML QUIET tinyxml2>=${TinyXML_FIND_VERSION})
      endif(TinyXML_FIND_VERSION_EXACT)
    else(TinyXML_FIND_VERSION)
      pkg_check_modules(PC_TINYXML QUIET tinyxml2)
    endif(TinyXML_FIND_VERSION)
  endif(PKG_CONFIG_FOUND)
endif(NOT WIN32)

set(TinyXML_INCLUDE_DIRS ${PC_TINYXML_INCLUDE_DIRS} CACHE PATH "TinyXML include directory" FORCE)
set(TinyXML_LIBRARY_DIRS ${PC_TINYXML_LIBRARY_DIRS} CACHE PATH "TinyXML library directory" FORCE)
set(TinyXML_LIBRARIES ${PC_TINYXML_LIBRARIES} CACHE STRING "TinyXML libraries" FORCE)
include(FindPackageHandleStandardArgs)

find_package_handle_standard_args(TinyXML
  DEFAULT_MSG
  TinyXML_LIBRARIES
  )

set(TinyXML_FOUND ${TINYXML_FOUND})
mark_as_advanced(TinyXML_INCLUDE_DIRS TinyXML_LIBRARY_DIRS TinyXML_LIBRARIES)


text:
0.2.9
-----
- Bug fix: exception on empty column

0.2.8
-----
- 1.8 compatibility

0.2.7
-----
- Customizable border
```ruby
  :hborder      => '─',
  :vborder      => '│',
  :iborder      => %w[┌ ┬ ┐ ├ ┼ ┤ └ ┴ ┘],
```
- `:border_color`
- Predefined border styles. `:border_style => :unicode`

0.2.5
-----
- Minor bug fixes

0.2.4
-----
- Improvment: Caching result of table generator
- Bug fix/feature: Handling rows of different number of cells

0.2.2
-----
- `screen_width` and `ellipsis` options to cut off trailing cells exceeding specified screen width

0.2.1
-----
- Multi-line support
- Vertical alignment

0.2.0
-----
- Tabularize::Table class for easy tabularization (doh!)
- Correctly handles ANSI codes

0.1.1
-----
- :unicode_display option added for CJK wide characters.

0.1.0
-----
- Initial release


text:
package cn.yoho.im.service;

import java.util.Map;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.server.BayeuxService;

/**
 * 持久数据处理服务
 *
 * @author Hbomb
 */
public class DataService extends BayeuxService {

    public DataService(Bayeux bayeux) {
        super(bayeux, "data");
        subscribe("/meta/handshake", "login");// 登录
        subscribe("/meta/connect", "update");// 更新用户状态
        subscribe("/service/*", "save");// 保存发送信息
        subscribe("/meta/unsubscribe", "logout");// 下线
    }

    /**
     * 获取登录信息
     *
     * @param source
     * @param channel
     * @param data
     * @param messageId
     */
    public void login(Client source, String channel, Map<String, Object> data,
            String messageId) {

    }

    /**
     * 更新用户状态,并获取最新好友列表(包含群列表)
     *
     * @param source
     * @param channel
     * @param data
     * @param messageId
     */
    public void update(Client source, String channel, Map<String, Object> data,
            String messageId) {

    }

    /**
     * 保存聊天信息
     *
     * @param source
     * @param channel
     * @param data
     * @param messageId
     */
    public void save(Client source, String channel, Map<String, Object> data,
            String messageId) {

    }

    /**
     * 登出(设置下线状态)
     *
     * @param source
     * @param channel
     * @param data
     * @param messageId
     */
    public void logout(Client source, String channel, Map<String, Object> data,
            String messageId) {

    }
}


text:
package org.springframework.messaging.converter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.ClassUtils;
import org.springframework.util.MimeType;

/**
 * Common base class for plain JSON converters, e.g. Gson and JSON-B.
 *
 * @author Juergen Hoeller
 * @since 5.3
 * @see GsonMessageConverter
 * @see JsonbMessageConverter
 * @see #fromJson(Reader, Type)
 * @see #fromJson(String, Type)
 * @see #toJson(Object, Type)
 * @see #toJson(Object, Type, Writer)
 */
public abstract class AbstractJsonMessageConverter extends AbstractMessageConverter {

	private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	protected AbstractJsonMessageConverter() {
		super(new MimeType("application", "json"));
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		return true;
	}

	@Override
	@Nullable
	protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
		try {
			Type resolvedType = getResolvedType(targetClass, conversionHint);
			Object payload = message.getPayload();
			if (ClassUtils.isAssignableValue(targetClass, payload)) {
				return payload;
			}
			else if (payload instanceof byte[]) {
				return fromJson(getReader((byte[]) payload, message.getHeaders()), resolvedType);
			}
			else {
				// Assuming a text-based source payload
				return fromJson(payload.toString(), resolvedType);
			}
		}
		catch (Exception ex) {
			throw new MessageConversionException(message, "Could not read JSON: " + ex.getMessage(), ex);
		}
	}

	@Override
	@Nullable
	protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers, @Nullable Object conversionHint) {
		try {
			Type resolvedType = getResolvedType(payload.getClass(), conversionHint);
			if (byte[].class == getSerializedPayloadClass()) {
				ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
				Writer writer = getWriter(out, headers);
				toJson(payload, resolvedType, writer);
				writer.flush();
				return out.toByteArray();
			}
			else {
				// Assuming a text-based target payload
				return toJson(payload, resolvedType);
			}
		}
		catch (Exception ex) {
			throw new MessageConversionException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}

	private Reader getReader(byte[] payload, @Nullable MessageHeaders headers) {
		InputStream in = new ByteArrayInputStream(payload);
		return new InputStreamReader(in, getCharsetToUse(headers));
	}

	private Writer getWriter(ByteArrayOutputStream out, @Nullable MessageHeaders headers) {
		return new OutputStreamWriter(out, getCharsetToUse(headers));
	}

	private Charset getCharsetToUse(@Nullable MessageHeaders headers) {
		MimeType mimeType = getMimeType(headers);
		return (mimeType != null && mimeType.getCharset() != null ? mimeType.getCharset() : DEFAULT_CHARSET);
	}

	protected abstract Object fromJson(Reader reader, Type resolvedType);

	protected abstract Object fromJson(String payload, Type resolvedType);

	protected abstract void toJson(Object payload, Type resolvedType, Writer writer);

	protected abstract String toJson(Object payload, Type resolvedType);

}


text:
package org.apache.druid.metadata.storage.sqlserver;

import com.google.common.base.Supplier;
import com.google.inject.Inject;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.metadata.MetadataStorageConnectorConfig;
import org.apache.druid.metadata.MetadataStorageTablesConfig;
import org.apache.druid.metadata.SQLMetadataConnector;
import org.skife.jdbi.v2.Binding;
import org.skife.jdbi.v2.ColonPrefixNamedParamStatementRewriter;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.HandleCallback;
import org.skife.jdbi.v2.tweak.RewrittenStatement;
import org.skife.jdbi.v2.tweak.StatementRewriter;
import org.skife.jdbi.v2.util.StringMapper;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;

@SuppressWarnings("nls")
public class SQLServerConnector extends SQLMetadataConnector
{
  private static final Logger log = new Logger(SQLServerConnector.class);

  /**
   *

   *

   *
   *

   *
   * Sql Server equivalent to the SERIAL_TYPE value in other SQLMetadataConnectors.
   *
   * SqlServer - PAYLOAD_TYPE = "VARBINARY(MAX)"
   *     Variable-length binary data
   *
   * PostgreSQL - PAYLOAD_TYPE = "BYTEA"
   *     variable-length binary string
   *
   * MySQL - PAYLOAD_TYPE = "LONGBLOB"
   *     a binary large object that can hold a variable amount of data
   *
   *

   *
   *

   *

   *
   * See also PostgreSQLConnector and MySQLConnector in corresponding modules in Druid.
   *
   * @see MS
   *      SQL Server Numeric Types
   */
  private static final String PAYLOAD_TYPE = "VARBINARY(MAX)";

  /**
   *
   *

   *

   *
   *

   * Sql Server equivalent to the SERIAL_TYPE value in other SQLMetadataConnectors.
   *
   * SqlServer - SERIAL_TYPE = "[bigint] IDENTITY (1, 1)"
   *     The bigint range is from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
   *
   * PostgreSQL - SERIAL_TYPE ="BIGSERIAL"
   *     The BIGSERIAL range is from 1 to 9223372036854775807
   *
   * MySQL - SERIAL_TYPE = "BIGINT(20) AUTO_INCREMENT"
   *     The BIGINT range is from -9223372036854775808 to 9223372036854775807
   *     Also note that "SERIAL" is an alias for "BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE"
   *
   *

   *
   *

   *

   *
   * See also PostgreSQLConnector and MySQLConnector in corresponding modules in Druid.
   *
   * @see MS SQL Server Numeric Types
   */
  private static final String SERIAL_TYPE = "[bigint] IDENTITY (1, 1)";

  private static final String QUOTE_STRING = "\\\"";
  public static final int DEFAULT_STREAMING_RESULT_SIZE = 100;

  private final DBI dbi;

  /**
   *

   *

   *
   *

   * Classify Transient Sql State Codes
   *

   *
   *

   *

   *
   * @see Spring Framework SQLStateSQLExceptionTranslator
   * @see SQLException#getSQLState()
   */
  private final Set<String> TRANSIENT_SQL_CLASS_CODES = new HashSet<>(Arrays.asList(
      "08", "53", "54", "57", "58", // Resource Failures
      "JW", "JZ", "S1", // Transient Failures
      "40" // Transaction Rollback
  ));

  @Inject
  public SQLServerConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables)
  {
    super(config, dbTables);

    final BasicDataSource datasource = getDatasource();
    datasource.setDriverClassLoader(getClass().getClassLoader());
    datasource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    this.dbi = new DBI(datasource);

    this.dbi.setStatementRewriter(new CustomStatementRewriter());

    log.info("Configured Sql Server as metadata storage");
  }

  public static class CustomStatementRewriter implements StatementRewriter
  {

    private static final Pattern REWRITE_PATTERN1 = Pattern.compile("(?i)BOOLEAN NOT NULL DEFAULT FALSE");
    private static final Pattern REWRITE_PATTERN2 = Pattern.compile("(?i)BOOLEAN NOT NULL DEFAULT TRUE");
    private static final Pattern REWRITE_PATTERN3 = Pattern.compile("(?i)BOOLEAN DEFAULT FALSE");
    private static final Pattern REWRITE_PATTERN4 = Pattern.compile("(?i)BOOLEAN DEFAULT TRUE");
    private static final Pattern REWRITE_PATTERN5 = Pattern.compile("(?i)BOOLEAN");
    private static final Pattern REWRITE_PATTERN6 = Pattern.compile("(?i)TRUE");
    private static final Pattern REWRITE_PATTERN7 = Pattern.compile("(?i)FALSE");

    private ColonPrefixNamedParamStatementRewriter colonPrefixNamedParamStatementRewriter = new ColonPrefixNamedParamStatementRewriter();

    @Override
    public RewrittenStatement rewrite(String sql, Binding params, StatementContext ctx)
    {

      String currentSql = sql;
      currentSql = REWRITE_PATTERN1.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)");
      currentSql = REWRITE_PATTERN2.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)");
      currentSql = REWRITE_PATTERN3.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (0)");
      currentSql = REWRITE_PATTERN4.matcher(currentSql).replaceAll("BIT NOT NULL DEFAULT (1)");
      currentSql = REWRITE_PATTERN5.matcher(currentSql).replaceAll("BIT");
      currentSql = REWRITE_PATTERN6.matcher(currentSql).replaceAll("1");
      currentSql = REWRITE_PATTERN7.matcher(currentSql).replaceAll("0");

      return (colonPrefixNamedParamStatementRewriter).rewrite(currentSql, params, ctx);

    }
  }

  @Override
  public String getPayloadType()
  {
    return PAYLOAD_TYPE;
  }

  @Override
  public String getSerialType()
  {
    return SERIAL_TYPE;
  }

  @Override
  public String getQuoteString()
  {
    return QUOTE_STRING;
  }

  @Override
  public int getStreamingFetchSize()
  {
    return DEFAULT_STREAMING_RESULT_SIZE;
  }

  @Override
  public boolean tableExists(final Handle handle, final String tableName)
  {
    return !handle.createQuery("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = :tableName")
        .bind("tableName", tableName)
        .map(StringMapper.FIRST)
        .list()
        .isEmpty();
  }

  @Override
  public String limitClause(int limit)
  {
    return String.format(Locale.ENGLISH, "FETCH NEXT %d ROWS ONLY", limit);
  }

  /**
   *
   * {@inheritDoc}
   *
   * @see http://stackoverflow.com/questions/1197733/does-sql-server-offer-anything-like-mysqls-on-duplicate-key-update
   *
   */
  @Override
  public Void insertOrUpdate(
      final String tableName,
      final String keyColumn,
      final String valueColumn,
      final String key,
      final byte[] value)
  {
    return getDBI().withHandle(
        new HandleCallback<Void>()
        {
          @Override
          public Void withHandle(Handle handle)
          {
            handle.createStatement(StringUtils.format(
                "MERGE INTO %1$s WITH (UPDLOCK, HOLDLOCK) as target"
                    + " USING "
                    + " (:key, :value) as source (%2$s, %3$s)"
                    + " ON"
                    + " (target.%2$s = source.%2$s)"
                    + " WHEN MATCHED THEN UPDATE SET %3$s = :value"
                    + " WHEN NOT MATCHED THEN INSERT (%2$s, %3$s) VALUES (:key, :value)",
                tableName,
                keyColumn,
                valueColumn))
                .bind("key", key)
                .bind("value", value)
                .execute();

            return null;
          }
        });
  }

  @Override
  public DBI getDBI()
  {
    return dbi;
  }

  /**
   *
   * {@inheritDoc}
   *
   * @see SQLException#getSQLState()
   *
   */
  @Override
  protected boolean connectorIsTransientException(Throwable e)
  {
    if (e instanceof SQLException) {
      final String sqlState = ((SQLException) e).getSQLState();
      if (sqlState == null) {
        return false;
      }

      final String sqlClassCode = sqlState.substring(0, 2);
      if (TRANSIENT_SQL_CLASS_CODES.contains(sqlClassCode)) {
        return true;
      }
    }
    return false;
  }
}


text:
using FluentMigrator;
using System;

namespace FMStudio.Lib.Test.Migrations.Migrations
{
    [Migration(4, "Alter table")]
    public class AlterTable : Migration
    {
        public override void Up()
        {
            Execute.Sql(@"
-- 0004_AlterTable.sql
");
        }

        public override void Down()
        {
            throw new NotImplementedException();
        }
    }
}


text:
package org.elasticsearch;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for Bosonnlp word segmenter.
 */
public class BosonNLPTest
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public BosonNLPTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( BosonNLPTest.class );
    }

    /**
     * Rigourous Test :-)
     */
    public void testApp()
    {
        assertTrue( true );
    }
}


text:
package com.stotem.lib.policy;

import com.stotem.lib.ConfigException;
import com.stotem.lib.RequestVersionException;
import com.stotem.lib.Tools;
import com.stotem.lib.Version;

/**
 * Created by JianjunWu on 16/4/12.
 */
public class TransferredVersionTypePolicy implements VersionTypePolicy {

    public void checkConfig(Version annotation) throws ConfigException {
        if (Tools.isEmpty(annotation.uri())) {
            throw new ConfigException("The uri is empty");
        }
        if (Tools.isEmpty(annotation.backupURI())) {
            throw new ConfigException("The backupURI is empty");
        }
    }

    public void checkRequestVersion(Version versionConfig, float requestV) throws RequestVersionException {
        throw new RequestVersionException(302, null, versionConfig.backupURI());
    }
}


text:
<?php

namespace Scribe\Arthur\DoctrineFixturesBundle\DataFixtures\Loader;

use Symfony\Component\Config\Loader\LoaderResolver;

/**
 * Class FixtureLoaderResolver.
 */
class FixtureLoaderResolver extends LoaderResolver implements FixtureLoaderResolverInterface
{
    /**
     * @param \Scribe\Arthur\DoctrineFixturesBundle\DataFixtures\Loader\FixtureLoaderInterface[] $loaders
     *
     * @return $this
     */
    public function assignLoaders(array $loaders = [])
    {
        foreach ($loaders as $l) {
            $this->addLoader($l);
        }

        return $this;
    }
}

/* EOF */


text:
aws-release-notes-rss
=====================

Scrape the AWS service release notes and spit out an RSS feed.

Point your newsreader here: https://dyn.tedder.me/rss/aws-release-notes.xml

```
pip3 install PyRSS2Gen requests boto3
```


text:
import '../amp-byside-content';
import {mockServiceForDoc} from '../../../../testing/test-helper';

describes.realWin(
  'amp-byside-content',
  {
    amp: {
      extensions: ['amp-byside-content'],
    },
    ampAdCss: true,
  },
  env => {
    let win, doc, urlMock;

    beforeEach(() => {
      win = env.win;
      doc = win.document;
      urlMock = mockServiceForDoc(sandbox, env.ampdoc, 'url-replace', [
        'expandUrlAsync',
      ]);
    });

    function getElement(attributes, opt_responsive, opt_beforeLayoutCallback) {
      const elem = doc.createElement('amp-byside-content');

      for (const key in attributes) {
        elem.setAttribute(key, attributes[key]);
      }

      elem.setAttribute('width', '640');
      elem.setAttribute('height', '360');
      if (opt_responsive) {
        elem.setAttribute('layout', 'responsive');
      }

      doc.body.appendChild(elem);
      return elem
        .build()
        .then(() => {
          urlMock.expandUrlAsync
            .returns(Promise.resolve(elem.implementation_.baseUrl_))
            .withArgs(sinon.match.any);
          if (opt_beforeLayoutCallback) {
            opt_beforeLayoutCallback(elem);
          }

          return elem.layoutCallback();
        })
        .then(() => elem);
    }

    function testIframe(elem) {
      const iframe = elem.querySelector('iframe');
      expect(iframe).to.not.be.null;
      expect(iframe.getAttribute('frameborder')).to.equal('0');
      expect(iframe.className).to.match(/i-amphtml-fill-content/);
      expect(iframe.fakeSrc).to.satisfy(src => {
        return src.startsWith(elem.implementation_.baseUrl_);
      });
    }

    it('renders', () => {
      return getElement({
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'amp-simple',
      }).then(elem => {
        testIframe(elem);
      });
    });

    it('requires data-label', () => {
      return allowConsoleError(() => {
        return getElement({
          'data-webcare-id': 'D6604AE5D0',
        }).should.eventually.be.rejectedWith(
          /The data-label attribute is required for/
        );
      });
    });

    it('requires data-webcare-id', () => {
      return allowConsoleError(() => {
        return getElement({
          'data-label': 'placeholder-label',
        }).should.eventually.be.rejectedWith(
          /The data-webcare-id attribute is required for/
        );
      });
    });

    it('generates correct default origin', () => {
      return getElement({
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
      }).then(elem => {
        expect(elem.implementation_.origin_).to.equal(
          'https://webcare.byside.com'
        );
      });
    });

    it('generates correct provided webcare zone', () => {
      const webcareZone = 'sa1';

      return getElement({
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
        'data-webcare-zone': webcareZone,
      }).then(elem => {
        expect(elem.implementation_.origin_).to.equal(
          'https://' + webcareZone + '.byside.com'
        );
      });
    });

    it('should create a loading animation', () => {
      return getElement({
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
      }).then(elem => {
        const loader = elem.querySelector(
          '.i-amphtml-byside-content-loading-animation'
        );
        expect(loader).to.not.be.null;
      });
    });

    it('builds a placeholder loading animation without inserting iframe', () => {
      const attributes = {
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
      };

      return getElement(attributes, true, elem => {
        const placeholder = elem.querySelector('[placeholder]');
        const iframe = elem.querySelector('iframe');
        expect(iframe).to.be.null;
        expect(placeholder).to.not.have.display('none');
      }).then(elem => {
        const placeholder = elem.querySelector('[placeholder]');
        elem.getVsync = () => {
          return {
            mutate: fn => fn(),
          };
        };

        // test iframe
        testIframe(elem);

        // test placeholder too
        elem.implementation_.iframePromise_.then(() => {
          expect(placeholder).to.have.display('none');
        });
      });
    });

    it('passes down sandbox attribute to iframe', () => {
      const sandbox = 'allow-scripts allow-same-origin allow-popups';
      const attributes = {
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
      };

      return getElement(attributes, false).then(elem => {
        const iframe = elem.querySelector('iframe');
        expect(iframe).to.not.be.null;
        expect(iframe.getAttribute('sandbox')).to.equal(sandbox);
      });
    });

    it('sets scrollable atribute in iframe', () => {
      const attributes = {
        'data-webcare-id': 'D6604AE5D0',
        'data-label': 'placeholder-label',
      };

      return getElement(attributes, false).then(elem => {
        const iframe = elem.querySelector('iframe');
        expect(iframe).to.not.be.null;
        expect(iframe.getAttribute('scrolling')).to.equal('no');
      });
    });
  }
);


text:
namespace fs = std::experimental::filesystem::v1;
namespace lt = libtorrent;
using Core::SessionLoader;

struct SessionLoadItem
{
    SessionLoadItem(const std::wstring &p)
        : path(p)
    {
    }

    std::wstring path;

    std::string resume_data;
    std::string magnet_save_path;
    std::string magnet_url;
};

SessionLoader::State SessionLoader::Load()
{
    // Paths
    fs::path data_path = Environment::GetDataPath();
    fs::path state_file = data_path / "Session.dat";
    fs::path torrents_dir = data_path / "Torrents";

    lt::settings_pack settings = SessionSettings::Get();

    State state;
    state.session = std::make_shared<lt::session>(settings);

    // Load state

    if (fs::exists(state_file))
    {
        std::ifstream state_input(state_file, std::ios::binary);
        std::stringstream ss;
        ss << state_input.rdbuf();
        std::string buf = ss.str();

        lt::bdecode_node node;
        lt::error_code ltec;
        lt::bdecode(&buf[0], &buf[0] + buf.size(), node, ltec);

        if (ltec)
        {
            LOG(Error) << "Could not bdecode session state file, error: " << ltec.message();
        }
        else
        {
            state.session->load_state(node);
        }
    }

    // Load torrents
    if (fs::exists(torrents_dir))
    {
        typedef std::pair<int64_t, SessionLoadItem> prio_item_t;
        auto comparer = [](const prio_item_t &lhs, const prio_item_t &rhs)
        {
            return lhs.first > rhs.first;
        };

        Configuration& cfg = Configuration::GetInstance();

        std::priority_queue<prio_item_t, std::vector<prio_item_t>, decltype(comparer)> queue(comparer);
        int64_t maxPosition = std::numeric_limits<int64_t>::max();

        for (auto& tmp : fs::directory_iterator(torrents_dir))
        {
            fs::path dat_file = tmp.path();

            if (dat_file.extension() != ".dat")
            {
                continue;
            }

            SessionLoadItem item(dat_file);

            std::ifstream dat_input(dat_file, std::ios::binary);
            std::stringstream ss;
            ss << dat_input.rdbuf();
            item.resume_data = ss.str();

            lt::error_code ltec;
            lt::bdecode_node node;
            lt::bdecode(
                &item.resume_data[0],
                &item.resume_data[0] + item.resume_data.size(),
                node,
                ltec);

            if (ltec)
            {
                LOG(Debug) << "Unable to decode bencoded file '" << dat_file << ", error: " << ltec;
                continue;
            }

            if (node.type() != lt::bdecode_node::type_t::dict_t)
            {
                LOG(Debug) << "File not a bencoded dictionary, '" << dat_file << "'";
                continue;
            }

            item.magnet_save_path = node.dict_find_string_value("pT-magnet-savePath").to_string();
            item.magnet_url = node.dict_find_string_value("pT-magnet-url").to_string();

            int64_t queuePosition = node.dict_find_int_value("pT-queuePosition", maxPosition);
            if (queuePosition < 0) { queuePosition = maxPosition; }

            queue.push({ queuePosition, item });
        }

        while (!queue.empty())
        {
            SessionLoadItem item = queue.top().second;
            queue.pop();

            fs::path torrent_file = fs::path(item.path).replace_extension(".torrent");

            if (!fs::exists(torrent_file)
                && item.magnet_url.empty())
            {
                LOG(Warning) << "Dat file did not have a corresponding torrent file, deleting.";
                fs::remove(torrent_file);
                continue;
            }

            lt::add_torrent_params params;

            if (!item.resume_data.empty())
            {
                lt::error_code ltec;
                params = lt::read_resume_data(
                    &item.resume_data[0],
                    static_cast<int>(item.resume_data.size()),
                    ltec);

                if (ltec)
                {
                    LOG(Debug) << "Could not decode resume data.";
                }
            }

            if (fs::exists(torrent_file))
            {

                std::ifstream torrent_input(torrent_file, std::ios::binary);
                std::stringstream ss;
                ss << torrent_input.rdbuf();
                std::string torrent_buf = ss.str();

                lt::bdecode_node node;
                lt::error_code ltec;
                lt::bdecode(
                    &torrent_buf[0],
                    &torrent_buf[0] + torrent_buf.size(),
                    node,
                    ltec);

                if (ltec)
                {
                    LOG(Info) << "Could not decode torrent file '" << torrent_file << "'";
                    continue;
                }

                params.ti = std::make_shared<lt::torrent_info>(node);
                state.muted_hashes.push_back(params.ti->info_hash());
            }

            if (!item.magnet_url.empty())
            {
                lt::error_code ec;
                lt::parse_magnet_uri(item.magnet_url, params, ec);
                params.save_path = item.magnet_save_path;
            }

            state.session->async_add_torrent(params);
            state.loaded_torrents += 1;
        }
    }

    return state;
}


text:
import 'leaflet';

L.Filter = (null != L.Filter) ? L.Filter : {};

L.Filter.SimpleShape = L.Filter.Feature.extend({
	options: {
	},

	initialize: function (map, options) {
		this._endLabelText = L.filterLocal.filter.handlers.simpleshape.tooltip.end;
		L.Filter.Feature.prototype.initialize.call(this, map, options);
	},

	addHooks: function () {
		L.Filter.Feature.prototype.addHooks.call(this);
		if (this._map) {
			this._mapDraggable = this._map.dragging.enabled();

			if (this._mapDraggable) {
				this._map.dragging.disable();
			}

			//TODO refactor: move cursor to styles
			this._container.style.cursor = 'crosshair';

			this._map
				.on('mousedown', this._onMouseDown, this)
				.on('mousemove', this._onMouseMove, this)
				.on('touchstart', this._onMouseDown, this)
				.on('touchmove', this._onMouseMove, this);
		}
	},

	removeHooks: function () {
		L.Filter.Feature.prototype.removeHooks.call(this);
		this._isDrawing = false;

		if (this._map) {
			if (this._mapDraggable) {
				this._map.dragging.enable();
			}

			//TODO refactor: move cursor to styles
			this._container.style.cursor = '';

			this._map
				.off('mousedown', this._onMouseDown, this)
				.off('mousemove', this._onMouseMove, this)
				.off('touchstart', this._onMouseDown, this)
				.off('touchmove', this._onMouseMove, this);

			L.DomEvent.off(document, 'mouseup', this._onMouseUp, this);
			L.DomEvent.off(document, 'touchend', this._onMouseUp, this);

			// If the box element doesn't exist they must not have moved the mouse, so don't need to destroy/return
			if (this._shape) {
				try {
					this._map.removeLayer(this._shape);
				}
				catch (err) {
					// Suppress the error on removing circle
				}

				delete this._shape;
			}
		}

	},

	_getTooltipText: function () {
		return {
			text: this._endLabelText
		};
	},

	_onMouseDown: function (e) {
		this._isDrawing = true;
		this._startLatLng = e.latlng;

		L.DomEvent
			.on(document, 'mouseup', this._onMouseUp, this)
			.on(document, 'touchend', this._onMouseUp, this)
			.preventDefault(e.originalEvent);
	},

	_onMouseMove: function (e) {
		var latlng = e.latlng;

		this._tooltip.updatePosition(latlng);
		if (this._isDrawing) {
			this._drawShape(latlng);
			this._tooltip.updateContent(this._getTooltipText());
		}
		else {
			this._tooltip.updateContent({ text: this._initialLabelText });
		}
	},

	_onMouseUp: function () {
		if (this._shape) {
			this._fireCreatedEvent();
		}

		this.disable();
	}
});


text:
/* @flow */

import { addAttr } from 'compiler/helpers'

function genText (node: ASTNode) {
  const value = node.type === 3
    ? node.text
    : node.type === 2
      ? node.tokens.length === 1
        ? node.tokens[0]
        : node.tokens
      : ''
  return JSON.stringify(value)
}

export function postTransformText (el: ASTElement, options: WeexCompilerOptions) {
  // weex <text> can only contain text, so the parser
  // always generates a single child.
  if (el.children.length) {
    addAttr(el, 'value', genText(el.children[0]))
    el.children = []
  }
}


text:
package com.faforever.client.game;

import com.faforever.client.builders.GamePlayerStatsBeanBuilder;
import com.faforever.client.builders.PlayerBeanBuilder;
import com.faforever.client.domain.GamePlayerStatsBean;
import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.test.UITest;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.RatingUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableMap;
import javafx.scene.control.Label;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class TeamCardControllerTest extends UITest {
  @InjectMocks
  private TeamCardController instance;

  @Mock
  private I18n i18n;
  @Mock
  private UiService uiService;
  @Mock
  private PlayerCardController playerCardController;
  @Mock
  private RatingChangeLabelController ratingChangeLabelController;

  private PlayerBean player;
  private ArrayList<PlayerBean> playerList;
  private ObservableMap<String, List<GamePlayerStatsBean>> teams;
  private GamePlayerStatsBean playerStats;

  @BeforeEach
  public void setUp() throws Exception {
    player = PlayerBeanBuilder.create().defaultValues().id(1).get();
    playerList = new ArrayList<>();
    playerList.add(player);
    teams = FXCollections.observableHashMap();

    when(uiService.loadFxml("theme/player_card.fxml")).thenReturn(playerCardController);
    when(uiService.loadFxml("theme/rating_change_label.fxml")).thenReturn(ratingChangeLabelController);
    when(playerCardController.getRoot()).thenReturn(new Label());
    when(ratingChangeLabelController.getRoot()).thenReturn(new Label());
    playerStats = GamePlayerStatsBeanBuilder.create()
        .defaultValues()
        .player(PlayerBeanBuilder.create().defaultValues().get())
        .get();

    teams.put("2", Collections.singletonList(playerStats));

    loadFxml("theme/team_card.fxml", param -> instance);
  }

  @Test
  public void setPlayersInTeam() {
    instance.setPlayersInTeam(2, playerList, player -> RatingUtil.getRating(1000, 0), null, RatingPrecision.ROUNDED);
    verify(i18n).get("game.tooltip.teamTitle", 1, 1000);
  }

  @Test
  public void showRatingChange() {
    instance.setPlayersInTeam(2, playerList, player -> RatingUtil.getRating(1000, 0), null, RatingPrecision.EXACT);
    instance.showRatingChange(teams);
    verify(ratingChangeLabelController).setRatingChange(playerStats);
  }

}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Core\Model;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Model\ShopBillingDataInterface;

final class ShopBillingDataSpec extends ObjectBehavior
{
    function it_implements_shop_billing_data_interface(): void
    {
        $this->shouldImplement(ShopBillingDataInterface::class);
    }

    function its_company_is_mutable(): void
    {
        $this->setCompany('Ragnarok');
        $this->getCompany()->shouldReturn('Ragnarok');
    }

    function its_tax_id_is_mutable(): void
    {
        $this->setTaxId('1100110011');
        $this->getTaxId()->shouldReturn('1100110011');
    }

    function its_country_code_is_mutable(): void
    {
        $this->setCountryCode('US');
        $this->getCountryCode()->shouldReturn('US');
    }

    function its_street_is_mutable(): void
    {
        $this->setStreet('Blue Street');
        $this->getStreet()->shouldReturn('Blue Street');
    }

    function its_city_is_mutable(): void
    {
        $this->setCity('New York');
        $this->getCity()->shouldReturn('New York');
    }

    function its_postcode_is_mutable(): void
    {
        $this->setPostcode('94111');
        $this->getPostcode()->shouldReturn('94111');
    }
}


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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.firebase.inappmessaging">

    <uses-sdk
        android:targetSdkVersion="23"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <application>
        <uses-library android:name="android.test.runner"/>
    </application>

    <instrumentation
        android:name="com.google.android.apps.common.testing.testrunner.Google3InstrumentationTestRunner"
        android:targetPackage="com.google.firebase.remoteconfig"/>
</manifest>


text:
<!DOCType html>

		<meta chartset='UTF-8'>
		<title>JWT Testing</title>

 Login

			<form ng-submit='vm.login(vm.userId, vm.password)'>
				User Id: <input type='text' ng-model='vm.userId'/>

				Password: <input type='password' ng-model='vm.password'/>

				<button type='submit'>Login</button>

			</form>

 Welcome {{vm.user.userId}}

			<button ng-click='vm.getRandomUser()'>Get User</button>
			<button ng-click='vm.logout()'>Logout</button>


text:
package com.bStone.engine.resource.timer;

import com.bStone.engine.resource.registry.RegistryMap;

public class TimerRegistry extends RegistryMap<String, Timer>
{
	public static final TimerRegistry INSTANCE = new TimerRegistry();

	@Override
	public void load() {}

	@Override
	public void unload() {}

	@Override
	public void reload() {}

	@Override
	public void update()
	{
		for(String id : this.toMap().keySet())
		{
			this.get(id).update();
		}
	}
}


text:
#ifndef __AddressBook__
#define __AddressBook__

#include <AddressBook/ABAddressBook.h>
#include <AddressBook/ABRecord.h>
#include <AddressBook/ABPerson.h>
#include <AddressBook/ABGroup.h>
#include <AddressBook/ABMultiValue.h>

#endif


text:
<!DOCTYPE HTML>

<meta charset="utf-8">
<title>jQuery File Upload Demo - AngularJS version</title>
<meta name="description" content="File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for AngularJS. Supports cross-domain, chunked and resumable file uploads and client-side image resizing. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="css/style.css">

<link rel="stylesheet" href="https://blueimp.github.io/Gallery/css/blueimp-gallery.min.css">

<link rel="stylesheet" href="css/jquery.fileupload.css">
<link rel="stylesheet" href="css/jquery.fileupload-ui.css">

<link rel="stylesheet" href="css/jquery.fileupload-noscript.css">
<link rel="stylesheet" href="css/jquery.fileupload-ui-noscript.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-fixed-top .navbar-collapse">

            </button>
            jQuery File Upload

Download

Source Code

Documentation

© Sebastian Tschan

jQuery File Upload Demo

AngularJS version

Basic

Basic Plus

Basic Plus UI

AngularJS

jQuery UI

File Upload widget with multiple file selection, drag&drop support, progress bars, validation and preview images, audio and video for AngularJS.

        Supports cross-domain, chunked and resumable file uploads and client-side image resizing.

        Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.

    <form id="fileupload" action="https://jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data" data-ng-app="demo" data-ng-controller="DemoFileUploadController" data-file-upload="options" data-ng-class="{'fileupload-processing': processing() || loadingFiles}">

        <input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/">

                    Add files...
                    <input type="file" name="files[]" multiple ng-disabled="disabled">

                <button type="button" class="btn btn-primary start" data-ng-click="submit()">

                    Start upload
                </button>
                <button type="button" class="btn btn-warning cancel" data-ng-click="cancel()">

                    Cancel upload
                </button>

                            {{file.name}}
                            {{file.name}}

                        {{file.name}}

                    {{file.error}}

{{file.size | formatFileSize}}

                    <button type="button" class="btn btn-primary start" data-ng-click="file.$submit()" data-ng-hide="!file.$submit || options.autoUpload" data-ng-disabled="file.$state() == 'pending' || file.$state() == 'rejected'">

                        Start
                    </button>
                    <button type="button" class="btn btn-warning cancel" data-ng-click="file.$cancel()" data-ng-hide="!file.$cancel">

                        Cancel
                    </button>
                    <button data-ng-controller="FileDestroyController" type="button" class="btn btn-danger destroy" data-ng-click="file.$destroy()" data-ng-hide="!file.$destroy">

                        Delete
                    </button>

    </form>

Demo Notes

The maximum file size for uploads in this demo is 999 KB (default file size is unlimited).

Only image files (JPG, GIF, PNG) are allowed in this demo (by default there is no file type restriction).

Uploaded files will be deleted automatically after 5 minutes or less (demo files are stored in memory).

You can drag & drop files from your desktop on this webpage (see Browser support).

Please refer to the project website and documentation for more information.

Built with the Bootstrap CSS framework and Icons from Glyphicons.

    ‹
    ›
    ×


text:
package com.bean.simplenews.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;

import java.lang.reflect.Type;

public class JsonUtils {

    private static Gson mGson = new Gson();

    /**
     * 将对象准换为json字符串
     * @param object
     * @param <T>
     * @return
     */
    public static <T> String serialize(T object) {
        return mGson.toJson(object);
    }

    /**
     * 将json字符串转换为对象
     * @param json
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Class<T> clz) throws JsonSyntaxException {
        return mGson.fromJson(json, clz);
    }

    /**
     * 将json对象转换为实体对象
     * @param json
     * @param clz
     * @param <T>
     * @return
     * @throws JsonSyntaxException
     */
    public static <T> T deserialize(JsonObject json, Class<T> clz) throws JsonSyntaxException {
        return mGson.fromJson(json, clz);
    }

    /**
     * 将json字符串转换为对象
     * @param json
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T deserialize(String json, Type type) throws JsonSyntaxException {
        return mGson.fromJson(json, type);
    }

}


text:
layout: post
title: "Angular Off Canvas Menu"
description: "Story of an off canvas menu module for Angular JS."
category:
tags: [angular, off, canvas, menu, ui, bootstrap, modal]
---
{% include JB/setup %}

Angular UI is a huge project providing many easy to use components with very much comfort. I personally use these modules nearly all of my Angular JS & Bootstrap projects.

One thing I suppose I needed with these super cool components was a good off-canvas side menu. There are a few solutions for that. Some of them like Snap or Sidr requires JQuery which is not cool in an Angular JS application. [Angular-Strap](http://mgcrea.github.io/angular-strap/) provides a very good aside, however you should depend on things in angular-strap to use this and I personally want to go with angular-ui instead of angular-strap.

So there were no choices left other than delivering an off-canvas menu module totally usable with angular-ui. An off-canvas menu is actually pretty same with a modal in practice. Only differences between a modal and an off-canvas menu would be the placement and the animation. So I decided to extend the modal of ui-bootstrap.

Off canvas menu should be created in controllers and should support both string contents and an html templates just like the modal. So the modal's provider is also very suitable for this purpose.

A little css hacking on modal gives us the off-canvas menu we always wanted. And modal has the windowClass option, awesome!

{% highlight js %}
...
var modalInstance = $modal.open({
  windowClass: 'ng-aside'
});
{% endhighlight%}

This creates a modal window with class `ng-aside`. All to be done is hacking the modal with some css to make it look like a menu. However if we want a menu we would want it to be configurable like place it left or right. So I have released this [angular-aside](https://github.com/dbtek/angular-aside) module which basically does it by extending `$modal` provider with a factory named `$aside` (thanks to angular-strap for the name) supporting all the configuration that modal provides. Additionally there is the `placement` configuration to set menu location left or right. It also includes animations provided by the awesome [animate.css](http://daneden.github.io/animate.css/).

Here is an example usage:

{% highlight js %}
angular.module('myApp', ['ui.bootstrap', 'ngAside'])
  .controller('MyController', function($scope, $aside) {
    var asideInstance = $aside.open({
      templateUrl: 'aside.html',
      controller: 'AsideCtrl',
      placement: 'left',
      size: 'lg'
    });
  });
{% endhighlight %}

###Live Demo

<iframe style="border: 0; width: 100%; height: 300px" allowfullscreen="allowfullscreen" src="http://embed.plnkr.co/w8Clzab6jJf6fPMHEXpP/preview">
  Loading plunk...
</iframe>

Easy, right? Angular-aside lives right [here](https://github.com/dbtek/angular-aside) at Github!


text:
ACCEPTED

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

#### Published in
null

#### Original name
Rhynchelytrum reynaudioides C.E.Hubb.

### Remarks
null


text: default_app_config = 'cms.content.apps.ContentConfig'


text:
module Azure::Network::Mgmt::V2018_06_01
  module Models
    #
    # Describes the destination of connection monitor.
    #
    class ConnectionMonitorDestination

      include MsRestAzure

      # @return [String] The ID of the resource used as the destination by
      # connection monitor.
      attr_accessor :resource_id

      # @return [String] Address of the connection monitor destination (IP or
      # domain name).
      attr_accessor :address

      # @return [Integer] The destination port used by connection monitor.
      attr_accessor :port

      #
      # Mapper for ConnectionMonitorDestination class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ConnectionMonitorDestination',
          type: {
            name: 'Composite',
            class_name: 'ConnectionMonitorDestination',
            model_properties: {
              resource_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'resourceId',
                type: {
                  name: 'String'
                }
              },
              address: {
                client_side_validation: true,
                required: false,
                serialized_name: 'address',
                type: {
                  name: 'String'
                }
              },
              port: {
                client_side_validation: true,
                required: false,
                serialized_name: 'port',
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
angular.module('myApp')
  .controller('HelloCtrl', function ($scope) {
 	$scope.name="Nicolas";
 	$scope.textColor = "#FF00000";

  $scope.reset = function(){
    $scope.name="";
    $scope.textColor = "#000000";
    $scope.bold = false;
  }
 })


text:
<!DOCTYPE html>

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

    <link href="css/bootstrap.min.css" rel="stylesheet">

Hello

  <button type="button" class="close" data-dismiss="alert">×</button>

Warning!

Best check yo self, you're not looking too good. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.


text:
using Azure.Core;

namespace Azure.ResourceManager.EventGrid.Models
{
    /// <summary> Information about the storage queue destination for an event subscription. </summary>
    public partial class StorageQueueEventSubscriptionDestination : EventSubscriptionDestination
    {
        /// <summary> Initializes a new instance of StorageQueueEventSubscriptionDestination. </summary>
        public StorageQueueEventSubscriptionDestination()
        {
            EndpointType = EndpointType.StorageQueue;
        }

        /// <summary> Initializes a new instance of StorageQueueEventSubscriptionDestination. </summary>
        /// <param name="endpointType"> Type of the endpoint for the event subscription destination. </param>
        /// <param name="resourceId"> The Azure Resource ID of the storage account that contains the queue that is the destination of an event subscription. </param>
        /// <param name="queueName"> The name of the Storage queue under a storage account that is the destination of an event subscription. </param>
        /// <param name="queueMessageTimeToLiveInSeconds"> Storage queue message time to live in seconds. </param>
        internal StorageQueueEventSubscriptionDestination(EndpointType endpointType, ResourceIdentifier resourceId, string queueName, long? queueMessageTimeToLiveInSeconds) : base(endpointType)
        {
            ResourceId = resourceId;
            QueueName = queueName;
            QueueMessageTimeToLiveInSeconds = queueMessageTimeToLiveInSeconds;
            EndpointType = endpointType;
        }

        /// <summary> The Azure Resource ID of the storage account that contains the queue that is the destination of an event subscription. </summary>
        public ResourceIdentifier ResourceId { get; set; }
        /// <summary> The name of the Storage queue under a storage account that is the destination of an event subscription. </summary>
        public string QueueName { get; set; }
        /// <summary> Storage queue message time to live in seconds. </summary>
        public long? QueueMessageTimeToLiveInSeconds { get; set; }
    }
}


text:
package de.jioc3;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import de.jreflect4.SuperToken;

public class SetupTest {

	Setup testee;

	@Before
	public void setUp() throws Exception {
		testee = new Setup("testee") {

			@Override
			protected void setup() {
				register(ITest.class, OneTest.class);
				register(SomeTest.class, SomeTest.class);
			}
		};
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test1() {
		testee.provide(SomeTest.class);
	}

	@Test
	public void test2() {
		testee.provide(SuperTest.class);
	}

}

class SuperTest{
	@Inject
	public SuperTest(SomeTest t, ITest t2){
	}
}

class SomeTest{
	ITest test;
	ITest test2;

	@Inject
	public SomeTest(IReadableContainer ioc, ITest test2){
		test = ioc.request(new SuperToken<ITest>(){});
	}
}


text:
import './header.scss';

class Header {

}

export default Header;


text:
using De.Osthus.Ambeth.Log;
using System;
using De.Osthus.Ambeth.Util;
using De.Osthus.Ambeth.Config;

namespace De.Osthus.Ambeth.Ioc.Config
{
    public class PropertyEmbeddedRefConfiguration : AbstractPropertyConfiguration
    {
        protected String propertyName;

        protected IBeanConfiguration embeddedBean;

        public PropertyEmbeddedRefConfiguration(IBeanConfiguration parentBeanConfiguration, String propertyName, IBeanConfiguration embeddedBean,
            IProperties props) : base(parentBeanConfiguration, props)
        {
            ParamChecker.AssertParamNotNull(propertyName, "propertyName");
            ParamChecker.AssertParamNotNull(embeddedBean, "embeddedBean");
            this.propertyName = propertyName;
            this.embeddedBean = embeddedBean;
        }

        public PropertyEmbeddedRefConfiguration(IBeanConfiguration parentBeanConfiguration, IBeanConfiguration embeddedBean, IProperties props)
            : base(parentBeanConfiguration, props)
        {
            ParamChecker.AssertParamNotNull(embeddedBean, "embeddedBean");
            this.embeddedBean = embeddedBean;
        }

        public override String GetPropertyName()
        {
            return propertyName;
        }

        public override String GetBeanName()
        {
            return embeddedBean.GetName();
        }

        public override bool IsOptional()
        {
            return false;
        }

        public override Object GetValue()
        {
            return embeddedBean;
        }
    }
}


text:
using AutoSoft.Domain.CoreBC.Telefones.Commands;
using FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoSoft.Domain.CoreBC.Telefones.Validations
{
    public class CriarTelefoneValidation : AbstractValidator<CriarTelefoneCommand>
    {
        public CriarTelefoneValidation()
        {
            RuleFor(x => x.DDD).NotEmpty();
            RuleFor(x => x.Number).NotEmpty();
        }
    }
}


text:
vault auth disable GloboAppRole/

# Let's confirm that we were successful

vault auth list


text:
package com.github.dcapwell.netty

import io.netty.channel.{ChannelFuture, ChannelFutureListener}

import scala.language.implicitConversions

package object examples {

  implicit def FunctionToChannelFutureListener(fn: ChannelFuture => Any): ChannelFutureListener =
    new ChannelFutureListener {
      override def operationComplete(future: ChannelFuture): Unit = fn(future)
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<project
    xmlns="http://maven.apache.org/DECORATION/1.7.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/DECORATION/1.7.0
                        http://maven.apache.org/xsd/decoration-1.7.0.xsd"
    name="${project.name}"
    combine.self="merge">
  <bannerRight>
    <name>µb ${project.artifactId}</name>
    <src>https://avatars0.githubusercontent.com/u/25515632?s=60</src>
    <href>${project.url}</href>
  </bannerRight>
  <version position="right"/>
  <skin>
    <groupId>org.apache.maven.skins</groupId>
    <artifactId>maven-fluido-skin</artifactId>
    <version>1.6</version>
  </skin>

  <body>
    <menu name="Documentation">
      <item name="Overview" href="index.html"/>
      <item name="JavaDocs" href="apidocs/index.html"/>
      <item name="Github Repository" href="${project.scm.url}"/>
      <item name="Examples" href="examples.html"/>
    </menu>
    <menu ref="reports"/>
  </body>

  <custom>
    <fluidoSkin>
      <topBarEnabled>false</topBarEnabled>
      <sideBarEnabled>true</sideBarEnabled>
    </fluidoSkin>
  </custom>

</project>


text:
function DogConstructor(name) {
    this.name = name;
}

var spot = new DogConstructor('Spot');
assert('Spot', spot.name);

function DogConstructor2(name) {
    this.name = name;
    this.respondTo = function(name) {
        if(this.name == name) {
            return 'Woof';
        }
    };
}

var spot = new DogConstructor2('Spot');
assert(undefined, spot.respondTo('Rover'));
assert('Woof', spot.respondTo('Spot')); // yeah!

assert(DogConstructor2, spot.constructor);


text:
NSString * const baseURL = @"https://api.uber.com/v1";
NSString * const sandBoxURL = @"https://sandbox-api.uber.com/v1";
NSString * const mobile_safari_string = @"com.apple.mobilesafari";

@interface UberKit()

@property (strong, nonatomic) NSString *accessToken;

@end

@interface UberKit (Private)

- (void) performNetworkOperationWithURL: (NSString *) url
                      completionHandler: (void (^)(NSDictionary *, NSURLResponse *, NSError *)) completion;
- (void) performNetworkOperationWithRequest:(NSURLRequest *)request
                      completionHandler:(void (^)(NSDictionary *, NSURLResponse *, NSError *))completion;

@end

@implementation UberKit

#pragma mark - Initialization

+ (UberKit *) sharedInstance
{
    static UberKit *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });

    return _sharedInstance;
}

- (instancetype) initWithServerToken:(NSString *)serverToken
{
    self = [super init];
    if(self)
    {
        _serverToken = serverToken;
    }

    return self;
}

- (instancetype) initWithClientID:(NSString *)clientId ClientSecret:(NSString *)clientSecret RedirectURL:(NSString *)redirectURL ApplicationName:(NSString *)applicationName
{
    self = [super init];
    if(self)
    {
        _clientID = clientId;
        _clientSecret = clientSecret;
        _redirectURL = redirectURL;
        _applicationName = applicationName;
    }

    return self;
}

#pragma mark - Login

- (void) startLogin
{
    [self setupOAuth2AccountStore];
    [self requestOAuth2Access];
}

- (NSString *) getStoredAuthToken
{
    return _accessToken;
}

- (void) setAuthTokenWith:(NSString *)token

{
    _accessToken = token;
}

#pragma mark - Product Types

- (void) getProductsForLocation:(CLLocation *)location withCompletionHandler:(CompletionHandler)completion
{
    // GET/v1/products

    NSString *url = [NSString stringWithFormat:@"%@/products?server_token=%@&latitude=%f&longitude=%f", baseURL, _serverToken, location.coordinate.latitude, location.coordinate.longitude];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *results, NSURLResponse *response, NSError *error)
     {
         if(!error)
         {
             NSArray *products = [results objectForKey:@"products"];
             NSMutableArray *availableProducts = [[NSMutableArray alloc] init];
             for(int i=0; i<products.count; i++)
             {
                 UberProduct *product = [[UberProduct alloc] initWithDictionary:[products objectAtIndex:i]];
                 [availableProducts addObject:product];
             }
             completion(availableProducts, response, error);
         }
         else
         {
             NSLog(@"Error %@", error);
             completion(nil, response, error);
         }
     }];
}

#pragma mark - Price Estimates

- (void) getPriceForTripWithStartLocation:(CLLocation *)startLocation endLocation:(CLLocation *)endLocation withCompletionHandler:(CompletionHandler)completion
{
    // GET /v1/estimates/price

    NSString *url = [NSString stringWithFormat:@"%@/estimates/price?server_token=%@&start_latitude=%f&start_longitude=%f&end_latitude=%f&end_longitude=%f", baseURL, _serverToken, startLocation.coordinate.latitude, startLocation.coordinate.longitude, endLocation.coordinate.latitude, endLocation.coordinate.longitude];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *results, NSURLResponse *response, NSError *error)
     {
         if(!error)
         {
             NSArray *prices = [results objectForKey:@"prices"];
             NSMutableArray *availablePrices = [[NSMutableArray alloc] init];
             for(int i=0; i<prices.count; i++)
             {
                 UberPrice *price = [[UberPrice alloc] initWithDictionary:[prices objectAtIndex:i]];
                 if(price.lowEstimate > -1)
                 {
                     [availablePrices addObject:price];
                 }
             }
             completion(availablePrices, response, error);
         }
         else
         {
             NSLog(@"Error %@", error);
             completion(nil, response, error);
         }
     }];
}

#pragma mark - Time Estimates

- (void) getTimeForProductArrivalWithLocation:(CLLocation *)location withCompletionHandler:(CompletionHandler)completion
{
    //GET /v1/estimates/time

    NSString *url = [NSString stringWithFormat:@"%@/estimates/time?server_token=%@&start_latitude=%f&start_longitude=%f", baseURL, _serverToken, location.coordinate.latitude, location.coordinate.longitude];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *results, NSURLResponse *response, NSError *error)
     {
         if(!error)
         {
             NSArray *times = [results objectForKey:@"times"];
             NSMutableArray *availableTimes = [[NSMutableArray alloc] init];
             for(int i=0; i<times.count; i++)
             {
                 UberTime *time = [[UberTime alloc] initWithDictionary:[times objectAtIndex:i]];
                 [availableTimes addObject:time];
             }
             completion(availableTimes, response, error);
         }
         else
         {
             NSLog(@"Error %@", error);
             completion(nil, response, error);
         }
     }];
}

#pragma mark - Promotion Estimates

- (void) getPromotionForLocation:(CLLocation *)startLocation endLocation:(CLLocation *)endLocation withCompletionHandler:(PromotionHandler)handler
{
    NSString *url = [NSString stringWithFormat:@"%@/promotions?server_token=%@&start_latitude=%f&start_longitude=%f&end_latitude=%f&end_longitude=%f", baseURL, _serverToken, startLocation.coordinate.latitude, startLocation.coordinate.longitude, endLocation.coordinate.latitude, endLocation.coordinate.longitude];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *promotionDictionary, NSURLResponse *response, NSError *error)
     {
         if(!error)
         {
             UberPromotion *promotion = [[UberPromotion alloc] initWithDictionary:promotionDictionary];
             handler(promotion, response, error);
         }
         else
         {
             handler(nil, response, error);
         }
     }];
}

#pragma mark - User History

- (void) getUserActivityWithCompletionHandler:(CompletionHandler)completion
{
    //GET /v1.1/history

    NSString *url = [NSString stringWithFormat:@"https://api.uber.com/v1.1/history?access_token=%@", _accessToken];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *activity, NSURLResponse *response, NSError *error)
     {
         if(!error)
         {
             int offset = [[activity objectForKey:@"offset"] intValue];
             int limit = [[activity objectForKey:@"limit"] intValue];
             int count = [[activity objectForKey:@"count"] intValue];
             NSArray *history = [activity objectForKey:@"history"];
             NSMutableArray *availableActivity = [[NSMutableArray alloc] init];
             for(int i=0; i<history.count; i++)
             {
                 UberActivity *activity = [[UberActivity alloc] initWithDictionary:[history objectAtIndex:i]];
                 [activity setLimit:limit];
                 [activity setOffset:offset];
                 [activity setCount:count];
                 [availableActivity addObject:activity];
             }
             completion(availableActivity, response, error);
         }
         else
         {
             completion(nil, response, error);
         }
     }];
}

#pragma mark - User Profile

- (void) getUserProfileWithCompletionHandler:(ProfileHandler)handler
{
    //GET /v1/me

    NSString *url = [NSString stringWithFormat:@"%@/me?access_token=%@", baseURL, _accessToken];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *profileDictionary, NSURLResponse *response, NSError *error)
     {
         if(profileDictionary)
         {
             UberProfile *profile = [[UberProfile alloc] initWithDictionary:profileDictionary];
             handler(profile, response, error);
         }
         else
         {
             handler(nil, response, error);
         }
     }];
}

#pragma mark - Request

- (void) getResponseForRequestWithParameters:(NSDictionary *)params withCompletionHandler:(RequestHandler)handler
{
    //POST /v1/requests
    NSString *url = [NSString stringWithFormat:@"%@/requests", sandBoxURL];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"Bearer %@", _accessToken] forHTTPHeaderField:@"Authorization"];

    NSError *error = nil;
    request.HTTPMethod = @"POST";
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

    [self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) { //OK
            UberRequest *requestResult = [[UberRequest alloc] initWithDictionary:requestDictionary];
            handler(requestResult, nil, response, error);
        }
        if (409 == httpResponse.statusCode) { //needs surge confirmation
            UberSurgeErrorResponse *surgeErrorResponse = [[UberSurgeErrorResponse alloc] initWithDictionary:requestDictionary];
            handler(nil, surgeErrorResponse, response, error);
        }
        else
        {
            handler(nil, nil, response, error);
        }
    }];
}

#pragma mark - Request - Estimate

- (void) getRequestEstimateWithProductId:(NSString *)productId andStartLocation:(CLLocation *)start endLocation:(CLLocation *)end withCompletionHandler:(EstimateHandler)handler
{
    //POST /v1/requests/estimate
    NSString *url = [NSString stringWithFormat:@"%@/requests/estimate", sandBoxURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"Bearer %@", _accessToken] forHTTPHeaderField:@"Authorization"];

    NSDictionary *params = @{@"product_id": productId, @"start_latitude": @(start.coordinate.latitude), @"start_longitude": @(start.coordinate.longitude), @"end_latitude": @(end.coordinate.latitude), @"end_longitude": @(end.coordinate.longitude)};

    NSError *error = nil;
    request.HTTPMethod = @"POST";
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];

    [self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) { //OK
            UberEstimate *estimateResult = [[UberEstimate alloc] initWithDictionary:requestDictionary];
            handler(estimateResult, response, error);
        } else {
            handler(nil, response, error);
        }
    }];
}

#pragma mark - Request - Cancel

- (void) cancelRequestForId:(NSString *)requestId withCompletionHandler:(CancelHandler)handler
{
    //DELETE /v1/requests/{request_id}
    NSString *url = [NSString stringWithFormat:@"%@/requests/%@", sandBoxURL, requestId];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"Bearer %@", _accessToken] forHTTPHeaderField:@"Authorization"];

    request.HTTPMethod = @"DELETE";

    [self performNetworkOperationWithRequest:request completionHandler:^(NSDictionary *requestDictionary, NSURLResponse *response, NSError *error) {
        handler(response, error);
    }];
}

#pragma mark - Request - Details

- (void) getDetailsForRequestId:(NSString *)requestId withCompletionHandler:(RequestHandler)handler
{
    //GET /v1/requests/{request_id}
    NSString *url = [NSString stringWithFormat:@"%@/requests/%@?access_token=%@", sandBoxURL, requestId, _accessToken];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *detailDictionary, NSURLResponse *response, NSError *error) {
        if(detailDictionary)
        {
            UberRequest *requestDetail = [[UberRequest alloc] initWithDictionary:detailDictionary];
            handler(requestDetail, response, error);
        }
        else
        {
            handler(requestResult, nil, response, error);
        }
        if (409 == httpResponse.statusCode) { //needs surge confirmation
            UberSurgeErrorResponse *surgeErrorResponse = [[UberSurgeErrorResponse alloc] initWithDictionary:requestDictionary];
            handler(nil, surgeErrorResponse, response, error);
        }
        else
        {
            handler(nil, nil, response, error);
    }];
}

#pragma mark - Request - Map

- (void) getMapForRequestId:(NSString *)requestId withCompletionHandler:(MapHandler)handler
{
    //GET /v1/requests/{request_id}/map
    NSString *url = [NSString stringWithFormat:@"%@/requests/%@/map?access_token=%@", sandBoxURL, requestId, _accessToken];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *mapDictionary, NSURLResponse *response, NSError *error) {
        if (mapDictionary) {
            UberMap *mapResult = [[UberMap alloc] initWithDictionary:mapDictionary];
            handler(mapResult, response, error);
        }
        else
        {
            handler(nil, response, error);
        }
    }];
}

#pragma mark - Request - Receipt

- (void) getReceiptForRequestId:(NSString *)requestId withCompletionHandler:(ReceiptHandler)handler
{
    //GET /v1/requests/{request)id}/receipt
    NSString *url = [NSString stringWithFormat:@"%@/requests/%@/receipt?access_token=%@", baseURL, requestId, _accessToken];
    [self performNetworkOperationWithURL:url completionHandler:^(NSDictionary *receiptDictionary, NSURLResponse *response, NSError *error) {
        if (receiptDictionary) {
            UberReceipt *receipt = [[UberReceipt alloc] initWithDictionary:receiptDictionary];
            handler(receipt, response, error);
        }
        else
        {
            handler(nil, response, error);
        }
    }];
}

#pragma mark - Login flow

- (BOOL) handleLoginRedirectFromUrl:(NSURL *)url sourceApplication:(NSString *)sourceApplication
{
    NSLog(@"url.absoluteURL.host is %@", url.absoluteURL.host);
    if ([sourceApplication isEqualToString:mobile_safari_string] && [url.absoluteString hasPrefix:_redirectURL])
    {
        NSString *code = nil;
        NSArray *urlParams = [[url query] componentsSeparatedByString:@"&"];
        for (NSString *param in urlParams) {
            NSArray *keyValue = [param componentsSeparatedByString:@"="];
            NSString *key = [keyValue objectAtIndex:0];
            if ([key isEqualToString:@"code"])
            {
                code = [keyValue objectAtIndex:1]; //retrieving the code
                NSLog(@"%@", code);
            }
            if (code)
            {
                //Got the code, now retrieving the auth token
                [self getAuthTokenForCode:code];
            }
            else
            {
                NSLog(@"There was an error returning from mobile safari");
            }
            return NO;
        }
    }
    return YES;
}

- (void) getAuthTokenForCode: (NSString *) code
{
    NSString *data = [NSString stringWithFormat:@"code=%@&client_id=%@&client_secret=%@&redirect_uri=%@&grant_type=authorization_code", code, _clientID, _clientSecret, _redirectURL];
    NSString *url = [NSString stringWithFormat:@"https://login.uber.com/oauth/token"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *authData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if(!error)
    {
        NSError *jsonError = nil;
        NSDictionary *authDictionary = [NSJSONSerialization JSONObjectWithData:authData options:0 error:&jsonError];
        if(!jsonError)
        {
            _accessToken = [authDictionary objectForKey:@"access_token"];
            if(_accessToken)
            {
                if([self.delegate respondsToSelector:@selector(uberKit:didReceiveAccessToken:)])
                {
                    [self.delegate uberKit:self didReceiveAccessToken:_accessToken];
                }
            }
        }
        else
        {
            NSLog(@"Error retrieving access token %@", jsonError);
        }
    }
    else
    {
        NSLog(@"Error in sending request for access token %@", error);
    }
}

#pragma mark - OAuth

- (void)setupOAuth2AccountStore
{
    [[NXOAuth2AccountStore sharedStore] setClientID:_clientID
                                             secret:_clientSecret
                                              scope:[NSSet setWithObjects:@"request", @"history_lite", @"profile", @"request_receipt", nil]
                                   authorizationURL:[NSURL URLWithString:@"https://login.uber.com/oauth/authorize"]
                                           tokenURL:[NSURL URLWithString:@"https://login.uber.com/oauth/token"]
                                        redirectURL:[NSURL URLWithString:_redirectURL]
                                      keyChainGroup:nil
                                     forAccountType:_applicationName];

    [[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreAccountsDidChangeNotification
                                                      object:[NXOAuth2AccountStore sharedStore]
                                                       queue:nil
                                                  usingBlock:^(NSNotification *aNotification){

                                                      if (aNotification.userInfo){
                                                          NSLog(@"Success! Received access token");
                                                      }
                                                      else{
                                                          NSLog(@"Account removed, lost access");
                                                      }
                                                  }];

    [[NSNotificationCenter defaultCenter] addObserverForName:NXOAuth2AccountStoreDidFailToRequestAccessNotification
                                                      object:[NXOAuth2AccountStore sharedStore]
                                                       queue:nil
                                                  usingBlock:^(NSNotification *aNotification){

                                                      NSError *error = [aNotification.userInfo objectForKey:NXOAuth2AccountStoreErrorKey];
                                                      NSLog(@"Error! %@", error.localizedDescription);

                                                  }];
}

-(void)requestOAuth2Access
{
    [[NXOAuth2AccountStore sharedStore] requestAccessToAccountWithType:_applicationName
                                   withPreparedAuthorizationURLHandler:^(NSURL *preparedURL){

                                       [[UIApplication sharedApplication] openURL:preparedURL];
                                       [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
                                   }];
}

#pragma mark - Deep Linking

- (void) openUberApp
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"uber://"]])
    {
        //Uber is installed
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"uber://"]];
    }
    else
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://uber.com"]];
    }
}

@end

@implementation UberKit (Private)

- (void) performNetworkOperationWithURL:(NSString *)url completionHandler:(void (^)(NSDictionary *, NSURLResponse *, NSError *))completion
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

    [[session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {

            NSError *jsonError = nil;
            NSDictionary *serializedResults = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];

            if (jsonError == nil) {
                completion(serializedResults, response, jsonError);
            } else {
                NSHTTPURLResponse *convertedResponse = (NSHTTPURLResponse *)response;
                completion(nil, convertedResponse, jsonError);
            }
        }
        else
        {
            NSHTTPURLResponse *convertedResponse = (NSHTTPURLResponse *)response;
            completion(nil, convertedResponse, error);
        }
    }] resume];
}

- (void) performNetworkOperationWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSDictionary *, NSURLResponse *, NSError *))completion
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

    [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {

            NSError *jsonError = nil;
            NSDictionary *serializedResults = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];

            if (jsonError == nil) {
                completion(serializedResults, response, jsonError);
            } else {
                NSHTTPURLResponse *convertedResponse = (NSHTTPURLResponse *)response;
                completion(nil, convertedResponse, error);
            }

        } else {
            NSHTTPURLResponse *convertedResponse = (NSHTTPURLResponse *)response;
            completion(nil, convertedResponse, error);
        }
    }] resume];
}

@end


text:
module Message where
import           Query
import           RoutingData
import           Utils

import           Data.Aeson
import qualified Data.List as L
import qualified Data.Maybe as M
import           Data.Text
import           Data.Time.Clock
import           GHC.Generics

-- let's assume network is reliable right? we don't need an ack...
-- https://www.youtube.com/watch?v=JG2ESDGwHHY

-- | These messages are sent between nodes.
data Message
  = Store
  { src :: ID                    -- ^ Who sent it?
  , srcInfo :: IPInfo
  , key :: ID                    -- ^ Under what key are we storing the value?
  , value :: Text                -- ^ What value are we storing?
  , dest :: ID                   -- ^ Who is it destined for?
  , sent :: UTCTime              -- ^ When was it sent?
  , mID :: Text                  -- ^ Unique UUID for this message
  }
  | FindNode
  { src :: ID                    -- ^ Who sent it?
  , srcInfo :: IPInfo
  , dest :: ID                   -- ^ Who is it destined for?
  , target :: ID                 -- ^ Who are we trying to find?
  , sent :: UTCTime              -- ^ When was it sent?
  , mRound :: Int                -- ^ Which find-Round does it belong to?
  , mID :: Text                  -- ^ Unique UUID for this message
  , qID :: QueryID               -- ^ Unique UUID for query it belongs to
  }
  | FindNodeR
  { src :: ID                    -- ^ Who sent it?
  , srcInfo :: IPInfo
  , dest :: ID                   -- ^ Who is it destined for?
  , results :: [NodeInfo]        -- ^ Who is close to the target?
  , sent :: UTCTime              -- ^ When was it sent?
  , mRound :: Int                -- ^ Which find-Round does it belong to?
  , mID :: Text                  -- ^ Unique UUID for this message
  , qID :: QueryID               -- ^ Unique UUID for query it belongs to
  }
  | FindValue
  { src :: ID                    -- ^ Who sent it?
  , srcInfo :: IPInfo
  , dest :: ID                   -- ^ Who is it destined for
  , key :: ID                    -- ^ Under which key is the value we're trying to obtain?
  , sent :: UTCTime              -- ^ When was it sent?
  , mID :: Text                  -- ^ Unique UUID for this message
  , qID :: QueryID               -- ^ Unique UUID for query it belongs to
  }
  | FindValueR
  { src :: ID                    -- ^ Who sent it?
  , srcInfo :: IPInfo
  , dest :: ID                   -- ^ Who is it destined for?
  , key :: ID                    -- ^ What keyw as the value under?
  , value :: Text                -- ^ What value did we have under that key?
  , sent :: UTCTime              -- ^ When was it sent?
  , mID :: Text                  -- ^ Unique UUID for this message
  , qID :: QueryID               -- ^ Unique UUID for query it belongs to
  }
  deriving (Show)

isFindValueR :: Message -> Bool
isFindValueR FindValueR{..} = True
isFindValueR _ = False

getNodeInfos :: Message -> [NodeInfo]
getNodeInfos FindNodeR{..} = results
getNodeInfos _ = []

cleanFindValueR :: Message -> Maybe (QueryID, ID, Text)
cleanFindValueR FindValueR{..} = Just (qID, key, value)
cleanFindValueR _ = Nothing

toQueryMessageResponse :: Message -> Maybe (QueryID, QueryMessageResponse)
toQueryMessageResponse FindNodeR{..} =
  Just (qID, QMR src mRound $ fmap fst results)
toQueryMessageResponse _ = Nothing

bulkToQueryMessageResponse :: [Message] -> [(QueryID, QueryMessageResponse)]
bulkToQueryMessageResponse = M.catMaybes . fmap toQueryMessageResponse

store :: ID -> IPInfo -> UTCTime -> Text -> ID -> Text -> ID -> Message
store src srcInfo now mID key value dest =
  Store src srcInfo key value dest now mID

-- TODO: This currently uses the same message ID for a batch of stores
bulkStores :: ID
           -> IPInfo
           -> UTCTime
           -> Text
           -> [(ID, Text, [ID])]
           -> [Message]
bulkStores src srcInfo now mID =
  L.concat . fmap (\(k, v, locs) -> fmap (store src srcInfo now mID k v) locs)

findNodeFromQM :: ID
               -> IPInfo
               -> UTCTime
               -> QueryID
               -> Text
               -> QueryMessage
               -> Message
findNodeFromQM myID ip now qID messageID QM{..} =
  FindNode myID ip qmDest qmTarget now qmRound messageID qID

findValueFromQM :: ID
                -> IPInfo
                -> UTCTime
                -> QueryID
                -> Text
                -> QueryMessage
                -> Message
findValueFromQM myID ip now qID messageID QM{..} =
  FindValue myID ip qmDest qmTarget now messageID qID

serialize :: Message -> String
serialize = undefined

deserialize :: String -> Message
deserialize = undefined


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace pserv4
{
    public abstract class BackgroundAction
    {
        public delegate void SetOutputTextDelegate(string message);
        protected SetOutputTextDelegate SetOutputText;
        protected BackgroundWorker Worker;

        public BackgroundAction()
        {
        }

        public void Bind(BackgroundWorker worker)
        {
            Worker = worker;
        }

        public void Setup(SetOutputTextDelegate setOutputText)
        {
            SetOutputText = setOutputText;
        }

        public abstract void DoWork();
    }
}


text:
<?php

namespace NetSuite\Classes;

class InitializeListResponse {
    public $readResponseList;
    static $paramtypesmap = array(
        "readResponseList" => "ReadResponseList",
    );
}


text:
NG_DOCS={
  "sections": {
    "api": "API Documentation"
  },
  "pages": [
    {
      "section": "api",
      "id": "earthquakersApp",
      "shortName": "earthquakersApp",
      "type": "overview",
      "moduleName": "earthquakersApp",
      "shortDescription": "earthquakersApp",
      "keywords": "api application earthquakersapp main module overview"
    },
    {
      "section": "api",
      "id": "earthquakersApp.controller:AboutCtrl",
      "shortName": "AboutCtrl",
      "type": "function",
      "moduleName": "earthquakersApp",
      "shortDescription": "AboutCtrl",
      "keywords": "aboutctrl api controller earthquakersapp function"
    },
    {
      "section": "api",
      "id": "earthquakersApp.controller:ContactCtrl",
      "shortName": "ContactCtrl",
      "type": "function",
      "moduleName": "earthquakersApp",
      "shortDescription": "ContactCtrl",
      "keywords": "api contact contactctrl controller earthquakersapp function"
    },
    {
      "section": "api",
      "id": "earthquakersApp.controller:MainCtrl",
      "shortName": "MainCtrl",
      "type": "function",
      "moduleName": "earthquakersApp",
      "shortDescription": "MainCtrl",
      "keywords": "api controller earthquakersapp function mainctrl"
    },
    {
      "section": "api",
      "id": "earthquakersApp.controller:QuakeTableCtrl",
      "shortName": "QuakeTableCtrl",
      "type": "function",
      "moduleName": "earthquakersApp",
      "shortDescription": "QuakeTableCtrl",
      "keywords": "api controller earthquakersapp function quaketable quaketablectrl"
    }
  ],
  "apis": {
    "api": true
  },
  "html5Mode": false,
  "editExample": true,
  "startPage": "/api",
  "scripts": [
    "angular.min.js"
  ]
};


text:
module Visualization
  UnknownType = Class.new(StandardError)

  def self.build(dataset, attributes)
    case attributes[:type]
      when 'frequency' then Visualization::Frequency
      when 'histogram' then Visualization::Histogram
      when 'heatmap' then Visualization::Heatmap
      when 'timeseries' then Visualization::Timeseries
      when 'boxplot' then Visualization::Boxplot
      else raise UnknownType, "Unknown visualization: #{attributes[:type]}"
    end.new(dataset, attributes)
  end

  class Base
    include CurrentUser

    def row_sql
      @dataset.query_setup_sql + build_row_sql
    end

    def min_max_sql
      @dataset.query_setup_sql + build_min_max_sql
    end

    def relation
      @relation ||= Arel::Table.new(@dataset.scoped_name)
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<com.meetme.android.multistateview.MultiStateView app:id="0x7f1100da" app:layout_width="-1" app:layout_height="-1">
    <com.myyearbook.m.ui.SwipeRefreshLayout app:id="0x7f11019c" app:layout_width="-1" app:layout_height="-1" app:scrollingDescendant="0x102000a">
        <ListView app:scrollbarStyle="2000000" app:id="0x102000a" app:layout_width="-1" app:layout_height="-1" app:divider="@mybapplication/SYNC_IS_NOT_SYNCABLE" app:dividerHeight="0dp" />
    </com.myyearbook.m.ui.SwipeRefreshLayout>
</com.meetme.android.multistateview.MultiStateView>


text:
This guide covers how you can quickly get started using Helm.

## Prerequisites

The following prerequisites are required for a successful and properly secured use of Helm.

1. A Kubernetes cluster
2. Deciding what security configurations to apply to your installation, if any
3. Installing and configuring Helm and Tiller, the cluster-side service.

### Install Kubernetes or have access to a cluster
- You must have Kubernetes installed. For the latest release of Helm, we recommend the latest stable release of Kubernetes, which in most cases is the second-latest minor release.
- You should also have a local configured copy of `kubectl`.

NOTE: Kubernetes versions prior to 1.6 have limited or no support for role-based access controls (RBAC).

Helm will figure out where to install Tiller by reading your Kubernetes
configuration file (usually `$HOME/.kube/config`). This is the same file
that `kubectl` uses.

To find out which cluster Tiller would install to, you can run
`kubectl config current-context` or `kubectl cluster-info`.

```console
$ kubectl config current-context
my-cluster
```

### Understand your Security Context

As with all powerful tools, ensure you are installing it correctly for your scenario.

If you're using Helm on a cluster that you completely control, like minikube or a cluster on a private network in which sharing is not a concern, the default installation -- which applies no security configuration -- is fine, and it's definitely the easiest. To install Helm without additional security steps, [install Helm](#Install-Helm) and then [initialize Helm](#initialize-helm-and-install-tiller).

However, if your cluster is exposed to a larger network or if you share your cluster with others -- production clusters fall into this category -- you must take extra steps to secure your installation to prevent careless or malicious actors from damaging the cluster or its data. To apply configurations that secure Helm for use in production environments and other multi-tenant scenarios, see [Securing a Helm installation](securing_installation.md)

If your cluster has Role-Based Access Control (RBAC) enabled, you may want
to [configure a service account and rules](rbac.md) before proceeding.

## Install Helm

Download a binary release of the Helm client. You can use tools like
`homebrew`, or look at [the official releases page](https://github.com/kubernetes/helm/releases).

For more details, or for other options, see [the installation
guide](install.md).

## Initialize Helm and Install Tiller

Once you have Helm ready, you can initialize the local CLI and also
install Tiller into your Kubernetes cluster in one step:

```console
$ helm init
```

This will install Tiller into the Kubernetes cluster you saw with
`kubectl config current-context`.

**TIP:** Want to install into a different cluster? Use the
`--kube-context` flag.

**TIP:** When you want to upgrade Tiller, just run `helm init --upgrade`.

By default, when Tiller is installed, it does not have authentication enabled.
To learn more about configuring strong TLS authentication for Tiller, consult
[the Tiller TLS guide](tiller_ssl.md).

## Install an Example Chart

To install a chart, you can run the `helm install` command. Helm has
several ways to find and install a chart, but the easiest is to use one
of the official `stable` charts.

```console
$ helm repo update              # Make sure we get the latest list of charts
$ helm install stable/mysql
Released smiling-penguin
```

In the example above, the `stable/mysql` chart was released, and the name of
our new release is `smiling-penguin`. You get a simple idea of the
features of this MySQL chart by running `helm inspect stable/mysql`.

Whenever you install a chart, a new release is created. So one chart can
be installed multiple times into the same cluster. And each can be
independently managed and upgraded.

The `helm install` command is a very powerful command with many
capabilities. To learn more about it, check out the [Using Helm
Guide](using_helm.md)

## Learn About Releases

It's easy to see what has been released using Helm:

```console
$ helm ls
NAME             VERSION   UPDATED                   STATUS    CHART
smiling-penguin  1         Wed Sep 28 12:59:46 2016  DEPLOYED  mysql-0.1.0
```

The `helm list` function will show you a list of all deployed releases.

## Uninstall a Release

To uninstall a release, use the `helm delete` command:

```console
$ helm delete smiling-penguin
Removed smiling-penguin
```

This will uninstall `smiling-penguin` from Kubernetes, but you will
still be able to request information about that release:

```console
$ helm status smiling-penguin
Status: DELETED
...
```

Because Helm tracks your releases even after you've deleted them, you
can audit a cluster's history, and even undelete a release (with `helm
rollback`).

## Reading the Help Text

To learn more about the available Helm commands, use `helm help` or type
a command followed by the `-h` flag:

```console
$ helm get -h
```