text:
@extends('layouts.app')
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
@section('nav')
@include('includes.nav')
@endsection

@section('body')

register

        <form id="register-form" method="post" class="text-left">

                        Email
                        <input type="text" class="form-control" id="reg_email" name="email" placeholder="email">

                        Email address
                        <input type="text" class="form-control" id="reg_username" name="username" placeholder="username">

                        Password
                        <input type="password" class="form-control" id="reg_password" name="password" placeholder="password">

                        Password Confirm
                        <input type="password" class="form-control" id="reg_password_confirm" name="password_confirmation" placeholder="confirm password">

                    <input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />

                <button type="submit" name="register" class="login-button"></button>

already have an account? login here

        </form>

                @if($errors->any())
                @include('includes.errors')

                @endif

@endsection

@section('footer')
@include('includes.footer')
@endsection


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Android Video Library</string>
    <string name="play">Play</string>
    <string name="pause">Pause</string>
    <string name="description">Media Controls</string>
    <string name="title_activity_video_player_activity">VideoPlayerActivity</string>
    <string name="title_main_activity">MainActivity</string>
    <string name="loading_video">Loading...</string>
    <string name="error_dialog_title">Error!</string>
    <string name="error_dialog_message">An error occurred while playing this video.</string>
    <string name="error_dialog_retry_button">Retry</string>
    <string name="error_dialog_cancel_button">Cancel</string>

</resources>

redpajama_set_name: RedPajamaGithub


text:
layout: step
title: Data Files
position: 6
---
Jekyll supports loading data from YAML, JSON, and CSV files located in a `_data`
directory. Data files are a great way to separate content from source code to
make the site easier to maintain.

In this step you'll store the contents of the navigation in a data file
and then iterate over it in the navigation include.

## Data file usage

[YAML](http://yaml.org/) is a format that's common in the Ruby ecosystem. You'll
use it to store an array of navigation items each with a name and link.

Create a data file for the navigation at `_data/navigation.yml` with the
following:

```yaml
- name: Home
  link: /
- name: About
  link: /about.html
```

Jekyll makes this data file available to you at `site.data.navigation`. Instead
of outputting each link in `_includes/navigation.html`, now you can iterate over
the data file instead:

{% raw %}
```liquid
<nav>
  {% for item in site.data.navigation %}
    <a href="{{ item.link }}" {% if page.url == item.link %}style="color: red;"{% endif %}>
      {{ item.name }}
    </a>
  {% endfor %}
</nav>
```
{% endraw %}

The output will be exactly the same. The difference is you've made it easier to
add new navigation items and change the HTML structure.

What good is a site without CSS, JS and images? Let's look at how to handle
assets in Jekyll.


text: mysql -u root <./schema/schema.sql


text:
#ifndef RUY_RUY_BLOCK_MAP_H_
#define RUY_RUY_BLOCK_MAP_H_

#include "ruy/cpu_cache_params.h"
#include "ruy/side_pair.h"

namespace ruy {

enum class BlockMapTraversalOrder {
  // Plain old row-by-row or column-by-column traversal.
  kLinear,
  // Fractal Z-order curve, https://en.wikipedia.org/wiki/Z-order_curve
  kFractalZ,
  // Variant of Z-order doing a U instead of a Z.
  kFractalU,
  // Hilbert curve, https://en.wikipedia.org/wiki/Hilbert_curve
  kFractalHilbert
};

// A BlockMap describes a tiling of a matrix, typically the destination matrix
// of a matrix multiplication computation. As is standard in matrix
// multiplication, a tile is called a "block".
//
// Ruy subdivides work by blocks of the destination matrix: each thread fully
// computes a block at once, then moves on to another block; each block is
// produced by a single thread.
//
// This ensures that the workloads for each block are mutually independent,
// which reduces synchronization requirements.
//
// Typically, a matrix multiplication will early on create a BlockMap by
// calling MakeBlockMap. It will then query the number of blocks in that
// BlockMap by calling NumBlocks. It will then create a single atomic integer
// counter indexing these blocks, called the 'index', and will distribute
// work to its N threads by ensuring that each thread works on disjoint sets
// of index values. For a given index value, the thread will call
// GetBlockByIndex to get the corresponding block, then GetBlockMatrixCoords
// to find the actual row and column numbers of this block.
//
// There are two nested levels of subdivision. On a local level, the matrix is
// tiled into a square NxN grid where N is a power of two, specifically:
//   N = 2^num_blocks_base_log2.
//
// At a larger scale, around these blocks, there may be one further
// level of subdivision, in only one dimension: either along rows or along
// columns. That is used to handle arbitrarily rectangular matrices. The
// aforementioned high-level block grid is square, so it does not readily fit
// well very rectangular matrices.
//
// Taking together these two nested levels of subdivision, the effective
// tiling is by
//   2^(num_blocks_base_log2 + rows_rectangularness_log2)
// blocks in the row dimension, and by
//   2^(num_blocks_base_log2 + cols_rectangularness_log2)
// blocks in the column dimension. See NumBlocksOfRows, NumBlocksOfCols.
//
// Either rows_rectangularness_log2 or cols_rectangularness_log2 must be zero.
//
// Finally, this BlockMap is designed to operate under alignment constraints:
// two fields, kernel_rows and kernel_cols, describe the requested alignment
// of the effective grid in both dimensions. The idea is to feed matrix
// multiplication kernels with tiles that fit their width as much as possible.
// Of course, if rows (resp. cols) is not a multiple of kernel_rows (resp.
// kernel_cols) then some tile will have to have unaligned size. BlockMap
// will only allow that to happen in the last position along each axis, so
// as to minimize the overhead incurred onto the matrix multiplication kernels.
struct BlockMap {
  // The number of threads to use (to distribute the blocks to).
  int thread_count;
  // The order in which to traverse the matrix of which this BlockMap represents
  // a tiling (hereafter "the matrix").
  BlockMapTraversalOrder traversal_order;
  // The dimensions of the block_map, that is, of the destination
  // matrix rounded up to next multiples of kernel_dims.
  SidePair<int> dims;
  // Log2 of the minimum number of subdivisions of the grid along either axis.
  int num_blocks_base_log2;
  // Log2 of the additional subdivision of the rows/columns axis.
  SidePair<int> rectangularness_log2;
  // Requested alignment of the subdivisions of the grid along the rows/columns
  // axis.
  SidePair<int> kernel_dims;
  // Internal helper. Minimum number of rows/columns in each block.
  SidePair<int> small_block_dims;
  // Internal helper. Number of blocks along each dimension that need to have
  // their size in that dimension be given by (small_block_dims + kernel_dims)
  // instead of just small_block_dims.
  SidePair<int> large_blocks;
};

// This function produces a coarse estimate of whether linear traversal will
// be used for this matmul. It offers a one-way guarantee: if this function
// returns true then linear traversal will be used.
//
// The purpose of this function is to allow TrMul to make a cheap, early
// decision to enter a "simple loop" code path for simple cases.
bool IsObviouslyLinearTraversal(int rows, int cols, int depth,
                                int lhs_scalar_size, int rhs_scalar_size,
                                const CpuCacheParams& cpu_cache_params);

// Create a BlockMap suitable for tiling the destination matrix in a
// matrix multiplication with the given parameters.
void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
                  int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
                  int tentative_thread_count,
                  const CpuCacheParams& cpu_cache_params, BlockMap* block_map);

// Maps an integer index to a block position in the grid.
void GetBlockByIndex(const BlockMap& block_map, int index,
                     SidePair<int>* block);

// Given a block position in the grid, returns its actual
// position in the matrix that the BlockMap refers to in the dimension
// referred to by `side`: along rows if side==kLhs, along columns if
// side==kRhs.
void GetBlockMatrixCoords(Side side, const BlockMap& block_map, int block,
                          int* start, int* end);

// Given a block position in the grid, returns its actual
// position in the matrix that the BlockMap refers to in terms of
// actual row/column indices.
void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
                          SidePair<int>* start, SidePair<int>* end);

// Returns the number of grid subdivisions along the rows dimension (if
// side == kLhs) or columns dimension (if side == kRhs).
inline int NumBlocksPerSide(Side side, const BlockMap& block_map) {
  return 1 << (block_map.num_blocks_base_log2 +
               block_map.rectangularness_log2[side]);
}

// Returns the overall number of blocks in
// the BlockMap. The valid index values to pass to GetBlockByIndex are the
// integers from 0 to N-1 where N is the value returned here.
//
// Note that it is always true that
//   NumBlocks == NumBlocksOfRows * NumBlocksOfCols
// because either rows_rectangularness_log2 or cols_rectangularness_log2 is 0.
inline int NumBlocks(const BlockMap& block_map) {
  return 1 << (2 * block_map.num_blocks_base_log2 +
               block_map.rectangularness_log2[Side::kLhs] +
               block_map.rectangularness_log2[Side::kRhs]);
}

}  // namespace ruy

#endif  // RUY_RUY_BLOCK_MAP_H_


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

package gaderian.test.services;

import java.util.EventListener;

/**
 * Test listener interface used to exercise {@link org.ops4j.gaderian.service.impl.BuilderFactory}'s
 * ability to register constructed services as listeners.
 *
 * @author Howard Lewis Ship
 */
public interface ZapListener extends EventListener
{
    public void zapDidWiggle(ZapEvent event);
}


text:
import numpy as np
import bct
from sklearn.externals import joblib
from my_settings import (bands, source_folder)

from sklearn.ensemble import AdaBoostClassifier
from sklearn.cross_validation import (StratifiedKFold, cross_val_score,
                                      permutation_test_score)
from sklearn.grid_search import GridSearchCV

subjects = [
    "0008", "0009", "0010", "0012", "0014", "0015", "0016", "0017", "0018",
    "0019", "0020", "0021", "0022"
]

cls_all = []
pln_all = []

scores_all = np.empty([4, 10])

results_all = {}

for subject in subjects:
    cls = np.load(source_folder + "graph_data/%s_classic_pow_pre.npy" %
                  subject).item()

    pln = np.load(source_folder + "graph_data/%s_plan_pow_pre.npy" %
                  subject).item()

    cls_all.append(cls)
    pln_all.append(pln)

for k, band in enumerate(bands.keys()):
    data_cls = []
    for j in range(len(cls_all)):
        tmp = cls_all[j][band]
        data_cls.append(
            np.asarray(
                [bct.centrality.pagerank_centrality(
                    g, d=0.85) for g in tmp]).mean(axis=0))
    data_pln = []
    for j in range(len(pln_all)):
        tmp = pln_all[j][band]
        data_pln.append(
            np.asarray(
                [bct.centrality.pagerank_centrality(
                    g, d=0.85) for g in tmp]).mean(axis=0))

    data_cls = np.asarray(data_cls)
    data_pln = np.asarray(data_pln)

    X = np.vstack([data_cls, data_pln])
    y = np.concatenate([np.zeros(len(data_cls)), np.ones(len(data_pln))])

    cv = StratifiedKFold(y, n_folds=6, shuffle=True)

    model = joblib.load(source_folder +
                        "graph_data/sk_models/pagerank_ada_pre_%s.plk" % band)

    score, perm_scores, pval = permutation_test_score(
        model, X, y, cv=cv, n_permutations=10000, n_jobs=1)

    result = {"score": score, "perm_scores": perm_scores, "pval": pval}
    results_all[band] = result

np.save(source_folder + "graph_data/perm_test_pagerank_pre.npy", results_all)


text:
export = number_is_nan;
declare function number_is_nan(p0: number): boolean;


text:
How to contribute
==================
Thank you for wanting to contribute to Spine. The following links will help you get started:
 * [Wiki home][wiki-home] — the home of the framework developer's documentation.
 * [Getting started with Spine in Java][quick-start] — this guide will walk you through
   a minimal client-server "Hello World!" application in Java.
 * [Introduction][docs-intro] — this section of the Spine Documentation will help you understand
   the foundation of the framework.

Pull requests
-------------
The work on an improvement starts with creating an issue that describes a bug or a feature. The issue will be used for communications on the proposed improvements.
If code changes are going to be introduced, the issue should also have a link to the corresponding Pull Request.

Code contributions should:
  * Be accompanied by tests.
  * Be licensed under the Apache v2.0 license with the appropriate copyright header for each file.
  * Formatted according to the code style. See [Wiki home][wiki-home] for the links to
    style guides of the programming languages used in the framework.

Contributor License Agreement
-----------------------------
Contributions to the code of Spine Event Engine framework and its libraries must be accompanied by
Contributor License Agreement (CLA).

 * If you are an individual writing original source code and you're sure you own
   the intellectual property, then you'll need to sign an individual CLA.

 * If you work for a company which wants you to contribute your work,
   then an authorized person from your company will need to sign a corporate CLA.

Please [contact us][legal-email] for arranging the paper formalities.

[wiki-home]: https://github.com/SpineEventEngine/SpineEventEngine.github.io/wiki
[quick-start]: https://spine.io/docs/quick-start
[docs-intro]: https://spine.io/docs/introduction
[legal-email]: mailto:legal@teamdev.com


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.trino.plugin.hive.HiveBucketProperty;
import io.trino.plugin.hive.HiveMetastoreClosure;
import io.trino.plugin.hive.HiveType;
import io.trino.plugin.hive.PartitionStatistics;
import io.trino.plugin.hive.acid.AcidTransaction;
import io.trino.plugin.hive.authentication.HiveIdentity;
import org.apache.hadoop.fs.Path;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.IntStream;

import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
import static io.trino.plugin.hive.HiveBasicStatistics.createEmptyStatistics;
import static io.trino.plugin.hive.HiveTestUtils.HDFS_ENVIRONMENT;
import static io.trino.plugin.hive.util.HiveBucketing.BucketingVersion.BUCKETING_V1;
import static io.trino.testing.TestingConnectorSession.SESSION;
import static java.util.concurrent.Executors.newFixedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static org.testng.Assert.assertTrue;

// countDownLatch field is shared between tests
@Test(singleThreaded = true)
public class TestSemiTransactionalHiveMetastore
{
    private static final Column TABLE_COLUMN = new Column(
            "column",
            HiveType.HIVE_INT,
            Optional.of("comment"));
    private static final Storage TABLE_STORAGE = new Storage(
            StorageFormat.create("serde", "input", "output"),
            Optional.of("location"),
            Optional.of(new HiveBucketProperty(ImmutableList.of("column"), BUCKETING_V1, 10, ImmutableList.of(new SortingColumn("column", SortingColumn.Order.ASCENDING)))),
            true,
            ImmutableMap.of("param", "value2"));

    private CountDownLatch countDownLatch;

    @Test
    public void testParallelPartitionDrops()
    {
        int partitionsToDrop = 5;
        IntStream dropThreadsConfig = IntStream.of(1, 2);
        dropThreadsConfig.forEach(dropThreads -> {
            countDownLatch = new CountDownLatch(dropThreads);
            SemiTransactionalHiveMetastore semiTransactionalHiveMetastore = getSemiTransactionalHiveMetastoreWithDropExecutor(newFixedThreadPool(dropThreads));
            IntStream.range(0, partitionsToDrop).forEach(i -> semiTransactionalHiveMetastore.dropPartition(SESSION,
                    "test",
                    "test",
                    ImmutableList.of(String.valueOf(i)),
                    true));
            semiTransactionalHiveMetastore.commit();
        });
    }

    private SemiTransactionalHiveMetastore getSemiTransactionalHiveMetastoreWithDropExecutor(Executor dropExecutor)
    {
        return new SemiTransactionalHiveMetastore(HDFS_ENVIRONMENT,
                new HiveMetastoreClosure(new TestingHiveMetastore()),
                directExecutor(),
                dropExecutor,
                directExecutor(),
                false,
                false,
                Optional.empty(),
                newScheduledThreadPool(1));
    }

    @Test
    public void testParallelUpdateStatisticsOperations()
    {
        int tablesToUpdate = 5;
        IntStream updateThreadsConfig = IntStream.of(1, 2);
        updateThreadsConfig.forEach(updateThreads -> {
            countDownLatch = new CountDownLatch(updateThreads);
            SemiTransactionalHiveMetastore semiTransactionalHiveMetastore;
            if (updateThreads == 1) {
                semiTransactionalHiveMetastore = getSemiTransactionalHiveMetastoreWithUpdateExecutor(directExecutor());
            }
            else {
                semiTransactionalHiveMetastore = getSemiTransactionalHiveMetastoreWithUpdateExecutor(newFixedThreadPool(updateThreads));
            }
            IntStream.range(0, tablesToUpdate).forEach(i -> semiTransactionalHiveMetastore.finishInsertIntoExistingTable(SESSION,
                    "database",
                    "table_" + i,
                    new Path("location"),
                    ImmutableList.of(),
                    PartitionStatistics.empty()));
            semiTransactionalHiveMetastore.commit();
        });
    }

    private SemiTransactionalHiveMetastore getSemiTransactionalHiveMetastoreWithUpdateExecutor(Executor updateExecutor)
    {
        return new SemiTransactionalHiveMetastore(HDFS_ENVIRONMENT,
                new HiveMetastoreClosure(new TestingHiveMetastore()),
                directExecutor(),
                directExecutor(),
                updateExecutor,
                false,
                false,
                Optional.empty(),
                newScheduledThreadPool(1));
    }

    private class TestingHiveMetastore
            extends UnimplementedHiveMetastore
    {
        @Override
        public Optional<Table> getTable(HiveIdentity identity, String databaseName, String tableName)
        {
            if (databaseName.equals("database")) {
                return Optional.of(new Table(
                        "database",
                        tableName,
                        "owner",
                        "table_type",
                        TABLE_STORAGE,
                        ImmutableList.of(TABLE_COLUMN),
                        ImmutableList.of(TABLE_COLUMN),
                        ImmutableMap.of("param", "value3"),
                        Optional.of("original_text"),
                        Optional.of("expanded_text"),
                        OptionalLong.empty()));
            }
            return Optional.empty();
        }

        @Override
        public PartitionStatistics getTableStatistics(HiveIdentity identity, Table table)
        {
            return new PartitionStatistics(createEmptyStatistics(), ImmutableMap.of());
        }

        @Override
        public void dropPartition(HiveIdentity identity, String databaseName, String tableName, List<String> parts, boolean deleteData)
        {
            assertCountDownLatch();
        }

        @Override
        public void updateTableStatistics(HiveIdentity identity, String databaseName, String tableName, AcidTransaction transaction, Function<PartitionStatistics, PartitionStatistics> update)
        {
            assertCountDownLatch();
        }

        private void assertCountDownLatch()
        {
            try {
                countDownLatch.countDown();
                assertTrue(countDownLatch.await(10, TimeUnit.SECONDS)); //all other threads launched should count down within 10 seconds
            }
            catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
    }
}


text:
package com.ibm.domino.das.resources;

import static com.ibm.domino.das.service.CoreService.PATH_SEGMENT_CORE;
import static com.ibm.domino.das.service.CoreService.PATH_SEGMENT_STATS;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.ibm.commons.util.io.json.JsonException;
import com.ibm.commons.util.io.json.JsonGenerator;
import com.ibm.commons.util.io.json.JsonGenerator.StringBuilderGenerator;
import com.ibm.commons.util.io.json.JsonJavaFactory;
import com.ibm.domino.commons.json.JsonSortedObject;
import com.ibm.domino.das.service.CoreService;
import com.ibm.domino.das.servlet.DasStats;
import com.ibm.domino.das.servlet.DasStats.MutableDouble;
import com.ibm.domino.das.servlet.DasStats.MutableInteger;

@Path(PATH_SEGMENT_CORE + "/" + PATH_SEGMENT_STATS)
public class StatsResource {

    @GET
    public Response getStats() {

        String jsonEntity = null;

        CoreService.verifyUserContext();

        try {
            JsonSortedObject stats = new JsonSortedObject();

            Set<Map.Entry<String, Object>> set = DasStats.get().getEntries();
            for ( Map.Entry<String, Object> entry : set ) {
                String name = null;
                StringTokenizer tokenizer = new StringTokenizer(entry.getKey(), ".");
                while ( tokenizer.hasMoreTokens() ) {
                    String segment = tokenizer.nextToken();
                    if ( name == null ) {
                        name = segment.toLowerCase();
                    }
                    else {
                        name += segment;
                    }
                }

                if ( entry.getValue() instanceof MutableInteger ) {
                    int value = ((MutableInteger)entry.getValue()).getValue();
                    stats.putInt(name, value);
                }
                else if ( entry.getValue() instanceof MutableDouble ) {
                    double value = ((MutableDouble)entry.getValue()).getValue();
                    stats.putDouble(name, value);
                }
            }

            // Serialize the JSON

            StringBuilder sb = new StringBuilder();
            JsonGenerator.Generator generator = new StringBuilderGenerator(JsonJavaFactory.instanceEx, sb, false);
            generator.toJson(stats);
            jsonEntity = sb.toString();
        }
        catch (JsonException e) {
            throw new WebApplicationException(CoreService.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        }
        catch (IOException e) {
            throw new WebApplicationException(CoreService.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        }
        finally {

        }

        ResponseBuilder builder = Response.ok();
        if ( jsonEntity != null ) {
            builder.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
        }

        Response response = builder.build();
        return response;
    }
}


text:
class PostContent
  include DataMapper::Resource

  property :id, Serial
  property :title, String
  property :body, String, :length => 10000
  property :language, String
  property :post_id, Integer

  belongs_to :post
end


text:
require 'yetis_node/version'
require 'yetis_node/cmd/base'
require 'yetis_node/cmd/show'
require 'yetis_node/cmd/set'
require 'yetis_node/cmd/request'
require 'yetis_node/error'
require 'yetis_node/base_transport'
require 'yetis_node/json_rpc_transport'
require 'yetis_node/client'

module YetisNode

end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DtoEntityEntry.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the client entity entry class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Data.Client.Capabilities
{
    using Kephas.Data.Capabilities;

    /// <summary>
    /// DTO holding information about the entity.
    /// </summary>
    public class DtoEntityEntry : IChangeStateTrackableEntityEntry
    {
        /// <summary>
        /// Gets or sets the change state of the entity.
        /// </summary>
        /// <value>
        /// The change state.
        /// </value>
        public ChangeState ChangeState { get; set; }

        /// <summary>
        /// Gets or sets the entity.
        /// </summary>
        /// <value>
        /// The entity.
        /// </value>
        public object Entity { get; set; }

        /// <summary>
        /// Gets or sets the original identifier of the entity.
        /// </summary>
        /// <remarks>
        /// In case of server generated IDs, the client sets a temporary ID
        /// which it needs to synchronize the internal cache after persisting.
        /// </remarks>
        /// <value>
        /// The original identifier of the entity.
        /// </value>
        public object OriginalEntityId { get; set; }

        /// <summary>
        /// Gets or sets the name of the entity type.
        /// </summary>
        /// <value>
        /// The name of the entity type.
        /// </value>
        public string EntityTypeName { get; set; }
    }
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Buellia mexicana J. Steiner

### Remarks
null


text:
package org.apache.camel.impl;

import java.util.Map;

import javax.naming.Context;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.PollingConsumer;
import org.apache.camel.Producer;
import org.apache.camel.TypeConverter;
import org.apache.camel.health.HealthCheckRegistry;
import org.apache.camel.impl.converter.DefaultTypeConverter;
import org.apache.camel.impl.engine.BeanProcessorFactoryResolver;
import org.apache.camel.impl.engine.BeanProxyFactoryResolver;
import org.apache.camel.impl.engine.DefaultAsyncProcessorAwaitManager;
import org.apache.camel.impl.engine.DefaultBeanIntrospection;
import org.apache.camel.impl.engine.DefaultCamelBeanPostProcessor;
import org.apache.camel.impl.engine.DefaultCamelContextNameStrategy;
import org.apache.camel.impl.engine.DefaultClassResolver;
import org.apache.camel.impl.engine.DefaultComponentResolver;
import org.apache.camel.impl.engine.DefaultDataFormatResolver;
import org.apache.camel.impl.engine.DefaultEndpointRegistry;
import org.apache.camel.impl.engine.DefaultFactoryFinderResolver;
import org.apache.camel.impl.engine.DefaultInflightRepository;
import org.apache.camel.impl.engine.DefaultInjector;
import org.apache.camel.impl.engine.DefaultLanguageResolver;
import org.apache.camel.impl.engine.DefaultManagementNameStrategy;
import org.apache.camel.impl.engine.DefaultMessageHistoryFactory;
import org.apache.camel.impl.engine.DefaultNodeIdFactory;
import org.apache.camel.impl.engine.DefaultPackageScanClassResolver;
import org.apache.camel.impl.engine.DefaultPackageScanResourceResolver;
import org.apache.camel.impl.engine.DefaultProcessorFactory;
import org.apache.camel.impl.engine.DefaultRouteController;
import org.apache.camel.impl.engine.DefaultShutdownStrategy;
import org.apache.camel.impl.engine.DefaultStreamCachingStrategy;
import org.apache.camel.impl.engine.DefaultTracer;
import org.apache.camel.impl.engine.DefaultUnitOfWorkFactory;
import org.apache.camel.impl.engine.DefaultUuidGenerator;
import org.apache.camel.impl.engine.EndpointKey;
import org.apache.camel.impl.engine.HeadersMapFactoryResolver;
import org.apache.camel.impl.engine.PropertiesComponentFactoryResolver;
import org.apache.camel.impl.engine.ReactiveExecutorResolver;
import org.apache.camel.impl.engine.RestRegistryFactoryResolver;
import org.apache.camel.impl.engine.ServicePool;
import org.apache.camel.impl.engine.WebSpherePackageScanClassResolver;
import org.apache.camel.impl.health.DefaultHealthCheckRegistry;
import org.apache.camel.runtimecatalog.RuntimeCamelCatalog;
import org.apache.camel.runtimecatalog.impl.DefaultRuntimeCamelCatalog;
import org.apache.camel.spi.AsyncProcessorAwaitManager;
import org.apache.camel.spi.BeanIntrospection;
import org.apache.camel.spi.BeanProcessorFactory;
import org.apache.camel.spi.BeanProxyFactory;
import org.apache.camel.spi.BeanRepository;
import org.apache.camel.spi.CamelBeanPostProcessor;
import org.apache.camel.spi.CamelContextNameStrategy;
import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.ComponentResolver;
import org.apache.camel.spi.DataFormatResolver;
import org.apache.camel.spi.EndpointRegistry;
import org.apache.camel.spi.ExecutorServiceManager;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.FactoryFinderResolver;
import org.apache.camel.spi.HeadersMapFactory;
import org.apache.camel.spi.InflightRepository;
import org.apache.camel.spi.Injector;
import org.apache.camel.spi.LanguageResolver;
import org.apache.camel.spi.ManagementNameStrategy;
import org.apache.camel.spi.MessageHistoryFactory;
import org.apache.camel.spi.ModelJAXBContextFactory;
import org.apache.camel.spi.NodeIdFactory;
import org.apache.camel.spi.PackageScanClassResolver;
import org.apache.camel.spi.PackageScanResourceResolver;
import org.apache.camel.spi.ProcessorFactory;
import org.apache.camel.spi.PropertiesComponent;
import org.apache.camel.spi.ReactiveExecutor;
import org.apache.camel.spi.Registry;
import org.apache.camel.spi.RestRegistryFactory;
import org.apache.camel.spi.RouteController;
import org.apache.camel.spi.ShutdownStrategy;
import org.apache.camel.spi.StreamCachingStrategy;
import org.apache.camel.spi.Tracer;
import org.apache.camel.spi.TypeConverterRegistry;
import org.apache.camel.spi.UnitOfWorkFactory;
import org.apache.camel.spi.UuidGenerator;
import org.apache.camel.support.DefaultRegistry;

/**
 * Represents the context used to configure routes and the policies to use.
 */
public class DefaultCamelContext extends AbstractModelCamelContext {

    /**
     * Creates the {@link CamelContext} using {@link DefaultRegistry} as
     * registry.
     *

     * Use one of the other constructors to force use an explicit registry.
     */
    public DefaultCamelContext() {
    }

    /**
     * Creates the {@link CamelContext} using the given {@link BeanRepository}
     * as first-choice repository, and the
     * {@link org.apache.camel.support.SimpleRegistry} as fallback, via the
     * {@link DefaultRegistry} implementation.
     *
     * @param repository the bean repository.
     */
    public DefaultCamelContext(BeanRepository repository) {
        super(new DefaultRegistry(repository));
    }

    /**
     * Creates the {@link CamelContext} using the given JNDI context as the
     * registry
     *
     * @param jndiContext the JNDI context
     * @deprecated create a new {@link JndiRegistry} and use the constructor
     *             that accepts this registry.
     */
    @Deprecated
    public DefaultCamelContext(Context jndiContext) {
        this(new JndiRegistry(jndiContext));
    }

    /**
     * Creates the {@link CamelContext} using the given registry
     *
     * @param registry the registry
     */
    public DefaultCamelContext(Registry registry) {
        super(registry);
    }

    /**
     * Creates the {@link CamelContext} and allows to control whether the
     * context should automatic initialize or not.
     *

     * This is used by some Camel components such as camel-cdi and
     * camel-blueprint, however this constructor is not intended for regular
     * Camel end users.
     *
     * @param init whether to automatic initialize.
     */
    public DefaultCamelContext(boolean init) {
        super(init);
    }

    @Override
    protected TypeConverter createTypeConverter() {
        return new DefaultTypeConverter(this, getPackageScanClassResolver(), getInjector(), getDefaultFactoryFinder(), isLoadTypeConverters());
    }

    @Override
    protected TypeConverterRegistry createTypeConverterRegistry() {
        TypeConverter typeConverter = getTypeConverter();
        if (typeConverter instanceof TypeConverterRegistry) {
            return (TypeConverterRegistry)typeConverter;
        }
        return null;
    }

    @Override
    protected Injector createInjector() {
        FactoryFinder finder = getDefaultFactoryFinder();
        return finder.newInstance("Injector", Injector.class).orElse(new DefaultInjector(this));
    }

    @Override
    protected PropertiesComponent createPropertiesComponent() {
        return new PropertiesComponentFactoryResolver().resolve(this);
    }

    @Override
    protected CamelBeanPostProcessor createBeanPostProcessor() {
        return new DefaultCamelBeanPostProcessor(this);
    }

    @Override
    protected ComponentResolver createComponentResolver() {
        return new DefaultComponentResolver();
    }

    @Override
    protected Registry createRegistry() {
        return new DefaultRegistry();
    }

    @Override
    protected UuidGenerator createUuidGenerator() {
        return new DefaultUuidGenerator();
    }

    @Override
    protected ModelJAXBContextFactory createModelJAXBContextFactory() {
        return new DefaultModelJAXBContextFactory();
    }

    @Override
    protected NodeIdFactory createNodeIdFactory() {
        return new DefaultNodeIdFactory();
    }

    @Override
    protected FactoryFinderResolver createFactoryFinderResolver() {
        return new DefaultFactoryFinderResolver();
    }

    @Override
    protected ClassResolver createClassResolver() {
        return new DefaultClassResolver(this);
    }

    @Override
    protected ProcessorFactory createProcessorFactory() {
        return new DefaultProcessorFactory();
    }

    @Override
    protected DataFormatResolver createDataFormatResolver() {
        return new DefaultDataFormatResolver();
    }

    @Override
    protected MessageHistoryFactory createMessageHistoryFactory() {
        return new DefaultMessageHistoryFactory();
    }

    @Override
    protected InflightRepository createInflightRepository() {
        return new DefaultInflightRepository();
    }

    @Override
    protected AsyncProcessorAwaitManager createAsyncProcessorAwaitManager() {
        return new DefaultAsyncProcessorAwaitManager();
    }

    @Override
    protected RouteController createRouteController() {
        return new DefaultRouteController(this);
    }

    @Override
    protected HealthCheckRegistry createHealthCheckRegistry() {
        return new DefaultHealthCheckRegistry(this);
    }

    @Override
    protected ShutdownStrategy createShutdownStrategy() {
        return new DefaultShutdownStrategy(this);
    }

    @Override
    protected PackageScanClassResolver createPackageScanClassResolver() {
        PackageScanClassResolver packageScanClassResolver;
        // use WebSphere specific resolver if running on WebSphere
        if (WebSpherePackageScanClassResolver.isWebSphereClassLoader(this.getClass().getClassLoader())) {
            log.info("Using WebSphere specific PackageScanClassResolver");
            packageScanClassResolver = new WebSpherePackageScanClassResolver("META-INF/services/org/apache/camel/TypeConverter");
        } else {
            packageScanClassResolver = new DefaultPackageScanClassResolver();
        }
        return packageScanClassResolver;
    }

    @Override
    protected PackageScanResourceResolver createPackageScanResourceResolver() {
        return new DefaultPackageScanResourceResolver();
    }

    @Override
    protected ExecutorServiceManager createExecutorServiceManager() {
        return new DefaultExecutorServiceManager(this);
    }

    @Override
    protected ServicePool<Producer> createProducerServicePool() {
        return new ServicePool<>(Endpoint::createProducer, Producer::getEndpoint, 100);
    }

    @Override
    protected ServicePool<PollingConsumer> createPollingConsumerServicePool() {
        return new ServicePool<>(Endpoint::createPollingConsumer, PollingConsumer::getEndpoint, 100);
    }

    @Override
    protected UnitOfWorkFactory createUnitOfWorkFactory() {
        return new DefaultUnitOfWorkFactory();
    }

    @Override
    protected RuntimeCamelCatalog createRuntimeCamelCatalog() {
        return new DefaultRuntimeCamelCatalog(this, true);
    }

    @Override
    protected CamelContextNameStrategy createCamelContextNameStrategy() {
        return new DefaultCamelContextNameStrategy();
    }

    @Override
    protected ManagementNameStrategy createManagementNameStrategy() {
        return new DefaultManagementNameStrategy(this);
    }

    @Override
    protected HeadersMapFactory createHeadersMapFactory() {
        return new HeadersMapFactoryResolver().resolve(this);
    }

    @Override
    protected BeanProxyFactory createBeanProxyFactory() {
        return new BeanProxyFactoryResolver().resolve(this);
    }

    @Override
    protected BeanProcessorFactory createBeanProcessorFactory() {
        return new BeanProcessorFactoryResolver().resolve(this);
    }

    @Override
    protected BeanIntrospection createBeanIntrospection() {
        return new DefaultBeanIntrospection();
    }

    @Override
    protected Tracer createTracer() {
        Tracer tracer = null;
        if (getRegistry() != null) {
            // lookup in registry
            Map<String, Tracer> map = getRegistry().findByTypeWithName(Tracer.class);
            if (map.size() == 1) {
                tracer = map.values().iterator().next();
            }
        }
        if (tracer == null) {
            tracer = getExtension(Tracer.class);
        }
        if (tracer == null) {
            tracer = new DefaultTracer();
            setExtension(Tracer.class, tracer);
        }
        return tracer;
    }

    @Override
    protected LanguageResolver createLanguageResolver() {
        return new DefaultLanguageResolver();
    }

    @Override
    protected RestRegistryFactory createRestRegistryFactory() {
        return new RestRegistryFactoryResolver().resolve(this);
    }

    @Override
    protected EndpointRegistry<EndpointKey> createEndpointRegistry(Map<EndpointKey, Endpoint> endpoints) {
        return new DefaultEndpointRegistry(this, endpoints);
    }

    @Override
    protected StreamCachingStrategy createStreamCachingStrategy() {
        return new DefaultStreamCachingStrategy();
    }

    @Override
    protected ReactiveExecutor createReactiveExecutor() {
        return new ReactiveExecutorResolver().resolve(this);
    }
}


text:
<fieldset class="module aligned">
    {% for line in fieldset %}

            {% for field in line %}

                    {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                    {% if field.is_checkbox %}
                        {{ field.field }}{{ field.label_tag }}
                    {% else %}
                        {{ field.label_tag }}
                        {% if field.is_readonly %}

{{ field.contents }}

                        {% else %}
                            {{ field.field }}
                        {% endif %}
                    {% endif %}
                    {% if field.field.help_text %}

{{ field.field.help_text|safe }}

                    {% endif %}

            {% endfor %}

    {% endfor %}
</fieldset>

    Username:
    <input autofocus="" class="vTextField" id="id_username" maxlength="254" name="username" type="text" value="adfadf">

Required. 254 characters or fewer. Letters, digits and @/./+/-/_ only.

    Username: <input autofocus="" id="id_username" maxlength="254" name="username" type="text" />
    Required. 254 characters or fewer. Letters, digits and @/./+/-/_ only.

<fieldset class="module aligned ">

                        Username:
                            <input class="vTextField" id="id_username" maxlength="254" name="username" type="text" value="user1">

Required. 254 characters or fewer. Letters, digits and @/./+/-/_ only.

                        Password:

algorithm: pbkdf2_sha256 iterations: 30000 salt: R7rcuz****** hash: h2Ohr1**************************************

Raw passwords are not stored, so there is no way to see this user's password, but you can change the password using this form.

</fieldset>


text:
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
  <ribbon>
    <tabs>
      <tab idMso="TabAddIns">
        <group id="MyGroup"
               label="Simple Pens">
          <labelControl id="SimplePensLabel" label="Enable SimplePens:"/>
          <checkBox id="ToggleCustomSlideShowForPresenter" label="when using Presenter view" getPressed="getSSPlusEnabledForPresenter" onAction="DisplayPresentationForPresenter"/>
          <checkBox id="ToggleCustomSlideShowForDefault" label="when not using Presenter view" getPressed="getSSPlusEnabledForDefault" onAction="DisplayPresentationForDefault"/>
        </group>
      </tab>
    </tabs>
  </ribbon>
</customUI>


text:
var PasswordMeter = (function(){
    'use strict';

    /**
     * attach password meter to DOM
     * @param $container       container for password meter, can be a p or div
     * @param id               optional id for meter element
     */
    function attach($container) {
        if (isIE()) return;
        var $meter = $('<meter></meter>', {id: 'password-meter', min: 0, max: 50, high: 20, low: 10, optimum: 50});
        $container
            .append($meter);
    }

    /**
     * Update password meter
     * @param $container        container for password meter, can be a p or div
     * @param newPW
     */
    function updateMeter($container, newPW) {
        var pwStrength = testPassword(newPW);
        var pwStrengthScore = pwStrength[0];

        $container.children('meter').val(pwStrengthScore);
    }

    return {
        attach: attach,
        updateMeter: updateMeter
    };
}());


text:
namespace SqlStreamStore.Infrastructure
{
    public static class InterlockedBooleanExtensions
    {
        public static bool EnsureCalledOnce(this InterlockedBoolean interlockedBoolean)
        {
            return interlockedBoolean.CompareExchange(true, false);
        }
    }
}


text:
namespace {

// The horizontal margein between workspaces in pixels.
const int kWorkspaceHorizontalMargin = 50;

// Minimum/maximum scale for overview mode.
const float kMaxOverviewScale = 0.9f;
const float kMinOverviewScale = 0.3f;

// Returns a list of all the windows with layers in |result|.
void BuildWindowList(const std::vector<aura::Window*>& windows,
                     std::vector<aura::Window*>* result) {
  for (size_t i = 0; i < windows.size(); ++i) {
    if (windows[i]->layer())
      result->push_back(windows[i]);
    BuildWindowList(windows[i]->transient_children(), result);
  }
}

gfx::Rect AlignRectToGrid(const gfx::Rect& rect, int grid_size) {
  if (grid_size <= 1)
    return rect;
  return gfx::Rect(ash::WindowResizer::AlignToGrid(rect.x(), grid_size),
                   ash::WindowResizer::AlignToGrid(rect.y(), grid_size),
                   ash::WindowResizer::AlignToGrid(rect.width(), grid_size),
                   ash::WindowResizer::AlignToGrid(rect.height(), grid_size));
}

}

namespace ash {
namespace internal {

////////////////////////////////////////////////////////////////////////////////
// WindowManager, public:

WorkspaceManager::WorkspaceManager(aura::Window* contents_view)
    : contents_view_(contents_view),
      active_workspace_(NULL),
      is_overview_(false),
      ignored_window_(NULL),
      grid_size_(0),
      shelf_(NULL) {
  DCHECK(contents_view);
}

WorkspaceManager::~WorkspaceManager() {
  std::vector<Workspace*> copy_to_delete(workspaces_);
  STLDeleteElements(&copy_to_delete);
}

bool WorkspaceManager::IsManagedWindow(aura::Window* window) const {
  return window->type() == aura::client::WINDOW_TYPE_NORMAL &&
         !window->transient_parent() && ash::GetTrackedByWorkspace(window);
}

bool WorkspaceManager::IsManagingWindow(aura::Window* window) const {
  return FindBy(window) != NULL;
}

void WorkspaceManager::AddWindow(aura::Window* window) {
  DCHECK(IsManagedWindow(window));

  Workspace* current_workspace = FindBy(window);
  if (current_workspace) {
    // Already know about this window. Make sure the workspace is active.
    if (active_workspace_ != current_workspace) {
      if (active_workspace_)
        window->layer()->GetAnimator()->StopAnimating();
      current_workspace->Activate();
    }
    window->Show();
    UpdateShelfVisibility();
    return;
  }

  if (wm::IsWindowNormal(window) && grid_size_ > 1)
    SetWindowBounds(window, AlignBoundsToGrid(window->GetTargetBounds()));

  Workspace* workspace = NULL;
  Workspace::Type type_for_window = Workspace::TypeForWindow(window);
  switch (type_for_window) {
    case Workspace::TYPE_MANAGED:
      // All normal windows go in the same workspace.
      workspace = GetManagedWorkspace();
      break;

    case Workspace::TYPE_MAXIMIZED:
      // All maximized windows go in their own workspace.
      break;
  }

  if (!workspace)
    workspace = CreateWorkspace(type_for_window);
  workspace->AddWindowAfter(window, NULL);
  workspace->Activate();
  UpdateShelfVisibility();
}

void WorkspaceManager::RemoveWindow(aura::Window* window) {
  Workspace* workspace = FindBy(window);
  if (!workspace)
    return;
  workspace->RemoveWindow(window);
  CleanupWorkspace(workspace);
  UpdateShelfVisibility();
}

void WorkspaceManager::SetActiveWorkspaceByWindow(aura::Window* window) {
  Workspace* workspace = FindBy(window);
  if (workspace)
    workspace->Activate();
}

void WorkspaceManager::SetOverview(bool overview) {
  if (is_overview_ == overview)
    return;
  NOTIMPLEMENTED();
}

gfx::Rect WorkspaceManager::AlignBoundsToGrid(const gfx::Rect& bounds) {
  if (grid_size_ <= 1)
    return bounds;
  return AlignRectToGrid(bounds, grid_size_);
}

void WorkspaceManager::UpdateShelfVisibility() {
  shelf_->UpdateVisibilityState();
}

WorkspaceManager::WindowState WorkspaceManager::GetWindowState() {
  if (!shelf_ || !active_workspace_)
    return WINDOW_STATE_DEFAULT;

  // TODO: this code needs to be made multi-monitor aware.
  gfx::Rect bounds(gfx::Screen::GetMonitorAreaNearestWindow(contents_view_));
  bounds.set_height(bounds.height() - shelf_->shelf_height());
  const aura::Window::Windows& windows(contents_view_->children());
  bool window_overlaps_launcher = false;
  for (aura::Window::Windows::const_iterator i = windows.begin();
       i != windows.end(); ++i) {
    if (!IsManagingWindow(*i))
      continue;
    ui::Layer* layer = (*i)->layer();
    if (!layer->GetTargetVisibility() || layer->GetTargetOpacity() == 0.0f)
      continue;
    if (wm::IsWindowMaximized(*i))
      return WINDOW_STATE_MAXIMIZED;
    if (wm::IsWindowFullscreen(*i))
      return WINDOW_STATE_FULL_SCREEN;
    if (!window_overlaps_launcher && (*i)->bounds().bottom() > bounds.bottom())
      window_overlaps_launcher = true;
  }

  return window_overlaps_launcher ? WINDOW_STATE_WINDOW_OVERLAPS_SHELF :
      WINDOW_STATE_DEFAULT;
}

void WorkspaceManager::ShowStateChanged(aura::Window* window) {
  if (!IsManagedWindow(window) || !FindBy(window))
    return;

  Workspace::Type old_type = FindBy(window)->type();
  Workspace::Type new_type = Workspace::TypeForWindow(window);
  if (new_type != old_type)
    OnTypeOfWorkspacedNeededChanged(window);
  UpdateShelfVisibility();
}

////////////////////////////////////////////////////////////////////////////////
// WorkspaceManager, private:

void WorkspaceManager::AddWorkspace(Workspace* workspace) {
  DCHECK(std::find(workspaces_.begin(), workspaces_.end(),
                   workspace) == workspaces_.end());
  if (active_workspace_) {
    // New workspaces go right after current workspace.
    Workspaces::iterator i = std::find(workspaces_.begin(), workspaces_.end(),
                                       active_workspace_);
    workspaces_.insert(++i, workspace);
  } else {
    workspaces_.push_back(workspace);
  }
}

void WorkspaceManager::RemoveWorkspace(Workspace* workspace) {
  Workspaces::iterator i = std::find(workspaces_.begin(),
                                     workspaces_.end(),
                                     workspace);
  DCHECK(i != workspaces_.end());
  i = workspaces_.erase(i);
  if (active_workspace_ == workspace) {
    // TODO: need mru order.
    if (i != workspaces_.end())
      SetActiveWorkspace(*i);
    else if (!workspaces_.empty())
      SetActiveWorkspace(workspaces_.back());
    else
      active_workspace_ = NULL;
  }
}

void WorkspaceManager::SetVisibilityOfWorkspaceWindows(
    ash::internal::Workspace* workspace,
    AnimateChangeType change_type,
    bool value) {
  std::vector<aura::Window*> children;
  BuildWindowList(workspace->windows(), &children);
  SetWindowLayerVisibility(children, change_type, value);
}

void WorkspaceManager::SetWindowLayerVisibility(
    const std::vector<aura::Window*>& windows,
    AnimateChangeType change_type,
    bool value) {
  for (size_t i = 0; i < windows.size(); ++i) {
    ui::Layer* layer = windows[i]->layer();
    // Only show the layer for windows that want to be visible.
    if (layer && (!value || windows[i]->TargetVisibility())) {
      windows[i]->SetProperty(aura::client::kAnimationsDisabledKey,
                              change_type == DONT_ANIMATE);
      bool update_layer = true;
      if (change_type == ANIMATE) {
        ash::SetWindowVisibilityAnimationType(
            windows[i],
            value ? ash::WINDOW_VISIBILITY_ANIMATION_TYPE_WORKSPACE_SHOW :
                    ash::WINDOW_VISIBILITY_ANIMATION_TYPE_WORKSPACE_HIDE);
        if (ash::internal::AnimateOnChildWindowVisibilityChanged(
                windows[i], value))
          update_layer = false;
      }
      if (update_layer)
        layer->SetVisible(value);
      // Reset the animation type so it isn't used in a future hide/show.
      ash::SetWindowVisibilityAnimationType(
          windows[i], ash::WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT);
      windows[i]->ClearProperty(aura::client::kAnimationsDisabledKey);
    }
  }
}

Workspace* WorkspaceManager::GetActiveWorkspace() const {
  return active_workspace_;
}

Workspace* WorkspaceManager::FindBy(aura::Window* window) const {
  int index = GetWorkspaceIndexContaining(window);
  return index < 0 ? NULL : workspaces_[index];
}

void WorkspaceManager::SetActiveWorkspace(Workspace* workspace) {
  if (active_workspace_ == workspace)
    return;
  DCHECK(std::find(workspaces_.begin(), workspaces_.end(),
                   workspace) != workspaces_.end());
  if (active_workspace_)
    SetVisibilityOfWorkspaceWindows(active_workspace_, ANIMATE, false);
  Workspace* last_active = active_workspace_;
  active_workspace_ = workspace;
  if (active_workspace_) {
    SetVisibilityOfWorkspaceWindows(active_workspace_,
                                    last_active ? ANIMATE : DONT_ANIMATE, true);
    UpdateShelfVisibility();
  }

  is_overview_ = false;
}

// Returns the index of the workspace that contains the |window|.
int WorkspaceManager::GetWorkspaceIndexContaining(aura::Window* window) const {
  for (Workspaces::const_iterator i = workspaces_.begin();
       i != workspaces_.end();
       ++i) {
    if ((*i)->Contains(window))
      return i - workspaces_.begin();
  }
  return -1;
}

void WorkspaceManager::SetWindowBounds(aura::Window* window,
                                       const gfx::Rect& bounds) {
  ignored_window_ = window;
  window->SetBounds(bounds);
  ignored_window_ = NULL;
}

void WorkspaceManager::OnTypeOfWorkspacedNeededChanged(aura::Window* window) {
  DCHECK(IsManagedWindow(window));
  Workspace* current_workspace = FindBy(window);
  DCHECK(current_workspace);
  Workspace* new_workspace = NULL;
  if (Workspace::TypeForWindow(window) == Workspace::TYPE_MAXIMIZED) {
    // Unmaximized -> maximized; create a new workspace.
    current_workspace->RemoveWindow(window);
    new_workspace = CreateWorkspace(Workspace::TYPE_MAXIMIZED);
    new_workspace->AddWindowAfter(window, NULL);
  } else {
    // Maximized -> unmaximized; move window to unmaximized workspace.
    wm::SetOpenWindowSplit(window, false);
    new_workspace = GetManagedWorkspace();
    current_workspace->RemoveWindow(window);
    if (!new_workspace)
      new_workspace = CreateWorkspace(Workspace::TYPE_MANAGED);
    new_workspace->AddWindowAfter(window, NULL);
  }
  SetActiveWorkspace(new_workspace);
  // Delete at the end so that we don't attempt to switch to another
  // workspace in RemoveWorkspace().
  CleanupWorkspace(current_workspace);
}

Workspace* WorkspaceManager::GetManagedWorkspace() {
  for (size_t i = 0; i < workspaces_.size(); ++i) {
    if (workspaces_[i]->type() == Workspace::TYPE_MANAGED)
      return workspaces_[i];
  }
  return NULL;
}

Workspace* WorkspaceManager::CreateWorkspace(Workspace::Type type) {
  Workspace* workspace = NULL;
  if (type == Workspace::TYPE_MAXIMIZED)
    workspace = new MaximizedWorkspace(this);
  else
    workspace = new ManagedWorkspace(this);
  AddWorkspace(workspace);
  return workspace;
}

void WorkspaceManager::CleanupWorkspace(Workspace* workspace) {
  if (workspace->type() != Workspace::TYPE_MANAGED && workspace->is_empty())
    delete workspace;
}

}  // namespace internal
}  // namespace ash


text:
(function ($) {

    //Notification handler
    abp.event.on('abp.notifications.received', function (userNotification) {
        abp.notifications.showUiNotifyForUserNotification(userNotification);
    });

    //serializeFormToObject plugin for jQuery
    $.fn.serializeFormToObject = function () {
        //serialize to array
        var data = $(this).serializeArray();

        //add also disabled items
        $(':disabled[name]', this).each(function () {
            data.push({ name: this.name, value: $(this).val() });
        });

        //map to object
        var obj = {};
        data.map(function (x) { obj[x.name] = x.value; });

        return obj;
    };

    //Configure blockUI
    if ($.blockUI) {
        $.blockUI.defaults.baseZ = 2000;
    }

})(jQuery);


text:
/** @file Common.h
 *
 * Defining the stuff that don't deserve headers of their own...
 */

#pragma once

#include <functional>

#include <jni.h>

#ifdef FBJNI_DEBUG_REFS
# ifdef __ANDROID__
#  include <android/log.h>
# else
#  include <cstdio>
# endif
#endif

// If a pending JNI Java exception is found, wraps it in a JniException object and throws it as
// a C++ exception.
#define FACEBOOK_JNI_THROW_PENDING_EXCEPTION() \
  ::facebook::jni::throwPendingJniExceptionAsCppException()

// If the condition is true, throws a JniException object, which wraps the pending JNI Java
// exception if any. If no pending exception is found, throws a JniException object that wraps a
// RuntimeException throwable.
#define FACEBOOK_JNI_THROW_EXCEPTION_IF(CONDITION) \
  ::facebook::jni::throwCppExceptionIf(CONDITION)

/// @cond INTERNAL

namespace facebook {
namespace jni {

void throwPendingJniExceptionAsCppException();
void throwCppExceptionIf(bool condition);

[[noreturn]] void throwNewJavaException(jthrowable);
[[noreturn]] void throwNewJavaException(const char* throwableName, const char* msg);
template<typename... Args>
[[noreturn]] void throwNewJavaException(const char* throwableName, const char* fmt, Args... args);

/**
 * This needs to be called at library load time, typically in your JNI_OnLoad method.
 *
 * The intended use is to return the result of initialize() directly
 * from JNI_OnLoad and to do nothing else there. Library specific
 * initialization code should go in the function passed to initialize
 * (which can be, and probably should be, a C++ lambda). This approach
 * provides correct error handling and translation errors during
 * initialization into Java exceptions when appropriate.
 *
 * Failure to call this will cause your code to crash in a remarkably
 * unhelpful way (typically a segfault) while trying to handle an exception
 * which occurs later.
 */
jint initialize(JavaVM*, std::function<void()>&&) noexcept;

namespace internal {

// Define to get extremely verbose logging of references and to enable reference stats
#ifdef FBJNI_DEBUG_REFS
template<typename... Args>
inline void dbglog(const char* msg, Args... args) {
# ifdef __ANDROID__
  __android_log_print(ANDROID_LOG_VERBOSE, "fbjni_dbg", msg, args...);
# else
  std::fprintf(stderr, msg, args...);
# endif
}

#else

template<typename... Args>
inline void dbglog(const char*, Args...) {
}

#endif

}}}

/// @endcond


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DotNetProgrammersToolbox.RegexPatterns {

    public partial class RegexMatch {

        /// <summary>
        /// SourceTextTextBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox SourceTextTextBox;

        /// <summary>
        /// RegularExpressionTextBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox RegularExpressionTextBox;

        /// <summary>
        /// OptionsCheckBoxList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBoxList OptionsCheckBoxList;

        /// <summary>
        /// OptionsDataSource control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ObjectDataSource OptionsDataSource;

        /// <summary>
        /// GoButton control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button GoButton;

        /// <summary>
        /// ErrorsHtmlTableRow control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableRow ErrorsHtmlTableRow;

        /// <summary>
        /// ErrorsBulletedList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.BulletedList ErrorsBulletedList;

        /// <summary>
        /// ResultsHtmlTableRow control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableRow ResultsHtmlTableRow;

        /// <summary>
        /// MatchResultsGridView control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView MatchResultsGridView;

        /// <summary>
        /// MatchResultsDataSource control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ObjectDataSource MatchResultsDataSource;
    }
}


text:
<?php
class testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy
    implements testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_interface
{

}

interface testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_interface
    extends testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parent
{

}

interface testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parent
    extends testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentA,
            testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentB
{

}

interface testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentA
    extends testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentC
{

}

interface testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentB
    extends testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parent {

}

interface testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_parentC
    extends testClassLevelAnalyzerNotRunsEndlessForDeepInterfaceHierarchy_interface {}


text:
package App::Wubot::Plugin::WebFetch;
use Moose;

our $VERSION = '0.3.4'; # VERSION

# todo: select with xpath in addition to regexp

use App::Wubot::Logger;
use App::Wubot::Util::WebFetcher;

with 'App::Wubot::Plugin::Roles::Cache';
with 'App::Wubot::Plugin::Roles::Plugin';

has 'fetcher' => ( is  => 'ro',
                   isa => 'App::Wubot::Util::WebFetcher',
                   lazy => 1,
                   default => sub {
                       return App::Wubot::Util::WebFetcher->new();
                   },
               );

sub check {
    my ( $self, $inputs ) = @_;

    my $config = $inputs->{config};
    my $cache  = $inputs->{cache};

    $self->logger->debug( "Fetching content from: $config->{url}" );

    my $content;
    eval {                          # try
        $content = $self->fetcher->fetch( $config->{url}, $config );
        1;
    } or do {                       # catch
        my $error = $@;
        my $subject = "Request failure: $error";
        $self->logger->error( $self->key . ": $subject" );
        return { react => { subject => $subject } };
    };

    my $field = $config->{field} || 'content';

    return { react => { $field => $content }, cache => $cache };
}

__PACKAGE__->meta->make_immutable;

1;

__END__

=head1 NAME

App::Wubot::Plugin::WebFetch - fetch content from a URL

=head1 VERSION

version 0.3.4

=head1 SYNOPSIS

  ~/wubot/config/plugins/WebFetch/mypage.yaml

  ---
  delay: 24h
  url: http://myweb.com/somepage.html
  field: content

=head1 DESCRIPTION

Fetch content from a web page at regular intervals.

The retrieved content will be stored in the 'field' specified in the
config.  If no field is specified, the default target field will be
'content'.

=head1 GITHUB TRAFFIC

I like to keep track of how many hits some of my projects have
received on github.  I haven't found any sort of a feed that will
provide that data.  The only place I have seen that is on the
'traffic' graph page.  So I use the following config to pull that page
once per day, grab the number of hits and send me a notification.

  ---
  delay: 24h
  url: https://github.com/wu/wubot/graphs/traffic

  react:

    - name: content
      condition: contains content
      rules:

        - name: get page views
          plugin: CaptureData
          config:
            source_field: content
            regexp: '^.*?Page Views \((\d+) over last 90 days\)'
            target_field: hits

        - name: build subject
          plugin: Template
          config:
            template: wubot: hits last 90 days: {$hits}
            target_field: subject

        - name: color
          plugin: SetField
          config:
            set:
              color: purple
              sticky: 1

=head1 GRAPHING ROUTER TRAFFIC

My DSL router does not provide any mechanism to graph the traffic sent
or received.  However it does provide a web page where it lists the
the total number of packets sent and received.  So I use the following
config which captures the sent and received packets every 5 minutes.

  ---
  delay: 5m
  url: http://192.168.1.98/cgi-bin/webcm?getpage=../html/lan_status.html

  react:

    - name: content
      condition: contains content
      rules:

        - name: get packets sent
          plugin: CaptureData
          config:
            source_field: content
            regexp: '^.*?Packets Sent:	.*?(\d+)'
            target_field: sent

        - name: get packets received
          plugin: CaptureData
          config:
            source_field: content
            regexp: '^.*?Packets Received:	.*?(\d+)'
            target_field: recv

Then I use the following rule in the reactor to graph the data using
RRD:

  - name: WebFetch RRD
    condition: key matches ^WebFetch-router
    plugin: RRD
    config:
      base_dir: /usr/home/wu/wubot/rrd
      fields:
        sent: COUNTER
        recv: COUNTER
      period:
        - day
        - week
        - month
      graph_options:
        lower_limit: 0
        right-axis: 1:0
        width: 375

=head1 SEE ALSO

This plugin uses L<App::Wubot::Util::WebFetcher>.

=head1 SUBROUTINES/METHODS

=over 8

=item check( $inputs )

The standard monitor check() method.

=back


text:
import inspect
import git
import os

__version__ = "0.1.0"
__author__ = "Broderick Carlin (beeedy)"
__email__= "broderick.carlin@gmail.com"
__license__= "MIT"

global_verbosity = False

def __print(verbose, msg):
	'''
	This is a simple utility function used to help assist in
	adding debug messages throughout the code. Print messages
	are formated as such:
	<name of calling function>:<line #> :: <msg>
	'''
	if not verbose and not global_verbosity:
		return

	stack = inspect.stack()
	calling_func = stack[1][3]
	line = stack[1][2]
	msg.replace("\n", "\n           ".format(calling_func, line))
	print("{}():{} :: {}".format(calling_func, line, msg))

def __get_calling_file(verbose=False):
	'''
	This function will go through the python call stack and find
	the script that originally called into this file. Returns a
	tuple where the first element is a string that is the folder
	containing the calling script, and the second element is the
	name of the file name of the calling script. If a file can not
	be found for some reason a LookupError is raised to indicate
	that an external script could not be found.
	'''
	stack = inspect.stack()
	this_file = stack[0][1]
	for i in range(1, len(stack)):
		if stack[i][1] != this_file:
			complete_path = os.path.normpath(os.getcwd() + "/" + stack[i][1])
			__print(verbose, "Module was called from: {}".format(complete_path))
			return os.path.split(complete_path)

	__print(verbose, "Module was not called by an external script.")
	raise LookupError("Module was not called by an external script.")

def __find_repo(verbose=False):
	'''
	This function will go figure out if the calling python script
	is inside a git repo, and if so, return a string that is the
	location of the base of the git repo. If the script is not, a
	LookupError is raised to indicate it could not find the repo
	'''
	file_path, file_name = __get_calling_file()
	# walk up the file tree looking for a valid git repo, stop when we hit the base
	while True:
		if os.path.samefile(os.path.normpath(file_path), os.path.normpath("/")):
			__print(verbose, "Calling script is not in a valid git repo")
			raise LookupError("Calling script is not in a valid git repo")

		try:
			git.Repo(file_path)
			__print(verbose, "Found root of repo located at: {}".format(os.path.normpath(file_path)))
			return os.path.normpath(file_path)
		except git.exc.InvalidGitRepositoryError:
			file_path = os.path.normpath(file_path + "/..")

def __find_current_branch(repo, verbose=False):
	'''
	Simple function that returns the name of the current branch.
	If for some reason the function fails to find the current branch
	an IOError is raised to indicate something has gone wrong.
	'''
	assert type(repo) is git.repo.base.Repo, "Passed in repo needs to be of type 'git.repo.base.Repo'"
	branches = str(repo.git.branch()).splitlines()
	for branch in branches:
		# asterix represents current branch, search for it
		if branch[0] == "*":
			__print(verbose, "Found current branch to be: {}".format(branch[2:]))
			return branch[2:]
	__print(verbose, "Failed to find current branch")
	raise  IOError("Failed to find current branch")

def __is_dev_env(directory, suppress_errors=False, verbose=False):
	'''
	This function will return 'True' if the git repo is setup to
	be a selfupdate development environment. This indicates that
	functions that perform destructive file manipulation will be
	limited in scope as to not cause the script to complicate
	development efforts when using the selfupdate library. A
	selfupdate development environment is configured by placeing
	an empty file in the root directory of the repo simply named
	'.devenv'. This file must also be included in the .gitignore
	or a EnvironmentError will be raised. This is to avoid the
	propogation of the development environment file to the main
	repo and any other local repositories that would then pull
	this file down and turn themselves into development
	environments. This error can be suppressed by setting the
	argument 'suppress_errors' to 'True' when calling is_dev_env().
	Suppressing this error can cause remote repos that rely on
	selfupdate to no longer update succesfully without direct
	user input. You have been warned!
	'''
	directory = os.path.normpath(directory)
	# see if the .devenv file even exists
	if os.path.isfile(directory + "/.devenv"):
		# it exists, so make sure a .gitignore exists and it includes .devenv
		if os.path.isfile(directory + "/.gitignore"):
			with open(directory + "/.gitignore", 'r') as gitignore:
				for line in gitignore.readlines():
					if ".devenv" in line:
						__print(verbose, "Found valid development environment")
						return True
		#raise error here
		__print(verbose, "'.devenv' found but not included in '.gitignore'.")
		if not suppress_errors:
			raise EnvironmentError("'.devenv' found but not included in '.gitignore'.")
	else:
		__print(verbose, "No '.devenv' file found in the root directory of the repo")

	return False

def __get_file_conflicts(repo, verbose=False):
	'''
	Simple function that takes in pointer to the repo
	and returns a list of files that have conflicts with
	the remote repo.
	'''
	assert type(repo) is git.repo.base.Repo, "Passed in repo needs to be of type 'git.repo.base.Repo'"
	diff = str(repo.git.diff("--name-only", "--diff-filter=U")).splitlines
	if len(diff) == 0:
		__print(verbose, "No diff conflicts found")
	else:
		msg = "Found {} conflicts in files:".format(len(diff))
		for conflict in diff:
			msg += "\n  {}".format(conflict)
		__print(verbose, msg)
	return diff

def __get_file_diffs(repo, verbose=False):
	'''
	Simple function that takes in a pointer to the repo
	and returns a list of files that contain changes
	between the remote and local repo.
	'''
	assert type(repo) is git.repo.base.Repo, "Passed in repo needs to be of type 'git.repo.base.Repo'"
	diff = str(repo.git.diff("--name-only")).splitlines
	if len(diff) == 0:
		__print(verbose, "No diff found")
	else:
		msg = "Found {} diffs in files:".format(len(diff))
		for conflict in diff:
			msg += "\n  {}".format(conflict)
		__print(verbose, msg)
	return diff

def pull(force=False, check_dev=True, verbose=False):
	'''
	This function will attempt to pull any remote changes down to
	the repository that the calling script is contained in. If
	there are any file conflicts the pull will fail and the function
	will return. This function is *safe* and does not perform
	destructive actions on the repo it is being called on. This
	function returns a tuple containing 2 fields. The first is a
	boolean value that indicates if the pull was successful or not.
	The second field contains a list of the files that were effected
	by the pull. If the pull was successful, this is the files that
	were updated by the pull action. If the pull was unsuccesful,
	this list contains the files that have conflicts and stopped the
	pull. All files listed in the case of a success or failure are
	referanced relative to the base of the repository. This function
	attempts to capture git errors but it is entirely possible that
	it does not handle a git error correctly in which case it will be
	raised again to be potentially handled higher up.
	'''
	repo_path = __find_repo()
	repo = git.Repo(repo_path)
	if not force:
		try:
			resp = str(repo.git.pull()).splitlines()
			if resp[0] == "Already up-to-date.":
				__print(verbose, "Repository is already up to date.")
				return (False, [])

			files = [a.split("|")[0][1:-1] for a in resp[2:-1]]
			__print(verbose, "Files that were updated:" + "\n  ".join(files))
			return (True, files)

		except git.exc.GitCommandError as err:
			err_list = str(err).splitlines()

			# this is a poor and rudamentary way to tell if there was a specific error TODO: fix
			if err_list[3] == "  stderr: 'error: Your local changes to the following files would be overwritten by merge:":
				files = [a[1:] for a in err_list[4:-2]]
				__print("Pull failed. Files with conflicts:" + "\n  ".join(files))
				return (False, files)
			# we got an error we didn't expect, pass it back up
			raise

		return (True, [])
	else:
		if check_dev and __is_dev_env(repo_path):
			__print(verbose, "Detected development environment. Aborting hard pull")
			return (False, [])
		repo_path = __find_repo()
		repo = git.Repo(repo_path)
		branch = __find_current_branch(repo)

		# record the diff, these will all replaced
		diffs = __get_file_diffs(repo)

		if len(diffs) == 0:
			return (False, [])

		# fetch all
		fetch_resp = str(repo.git.fetch("--all"))
		__print(verbose, "Fetched any and all changes with response: {}".format(fetch_resp))
		# reset
		reset_resp = str(repo.git.reset("--hard", "origin/{}".format(branch)))
		__print(verbose, "Completed hard pull with response: {}".format(reset_resp))
		# clean
		clean_resp = str(repo.git.clean("-f"))
		__print(verbose, "Completed clean with response: {}".format(clean_resp))
		return (True, diffs)

def push(force=False, check_dev=True, message="Pushing up changes with python selfupdate", username=None, password=None, verbose=False):
	'''
	This function will perform a push up of all local changes that have been
	made into a repo. However, if there is a file conflict this function will
	raise a SystemError flag if force is set to False. If force is True, it
	will force the push. The function will first run "git add -A", followed up by
	"git commit -m 'users message here'" and finally "git push" or possibly
	"git push <credentials>" if needed. If the function is called with the
	username and password populated it will attept to push using the provided
	credentials otherwise it will fall back to simply "git push". This method
	is currently unable to handle repositories that may need credentials and
	that are protected with 2-factor authentication. It is reccomended to
	clone the repo using SSH to avoid issues in this case.
	'''
	if check_dev and __is_dev_env(repo_path) and force:
		__print(verbose, "Detected development environment. Aborting hard pull")
		return

	conflicts = __get_file_conflicts(repo)
	if len(conflicts) != 0 and not force:
		__print(verbose, "Can not push, there are file conflicts")
		raise SystemError("Can not push up changes when there are file conflicts")

	# perform "git add -A"
	add_resp = str(repo.git.add("-A"))
	__print(verbose, "Added all local changes with response: {}".format(add_resp))

	# perform "git commit -m '<message>'"
	try:
		commit_resp = str(repo.git.commit("-m", "'{}'".format(message)))
		__print(verbose, "Commit all local changes with response: {}".format(commit_resp))
	except git.exc.GitCommandError:
		# TODO: handle errors that may occur when doing a commit
		pass

	# perform "git push" with credentials if provided
	try:
		if username is not None and password is not None:
			# user is attempting to send credentials with the push, fabricate URL
			repo_url = str(repo.git.remote("-v")).splitlines()[0][7:-8].split("//")[1]
			repo_url = "https://{}:{}@{}".format(username, password, repo_url)
			if force:
				push_resp = str(repo.git.push(repo_url, "-f"))
			else:
				push_resp = str(repo.git.push(repo_url))
		else:
			branch = __find_current_branch(repo)
			if force:
				push_resp = str(repo.git.push("origin", branch, "-f"))
			else:
				push_resp = str(repo.git.push("origin", branch))
		__print(verbose, "Push all local changes with response: {}".format(push_resp))
	except git.exc.GitCommandError as err:
		err = str(err).splitlines()
		# handle incorrect username/password
		if "remote: Invalid username or password." in err[-2]:
			__print(verbose, "Wrong login credentials, authentication failed")
			raise ValueError("Wrong login credentials, authentication failed")
		# correct credentials but something else went wrong, most likely 2-factor auth
		elif "remote: Anonymous access to " in err[-2]:
			__print(verbose, "Cannot gain access, authentication failed. This is often caused by 2-factor authentication")
			raise ValueError("Cannot gain access, authentication failed. This is often caused by 2-factor authentication")
		# we really goofed, pass the error along
		else:
			raise

def update(force=False, check_dev=True, message="Pushing up changes with python selfupdate", username=None, password=None, verbose=False):
	'''
	The single function that can be called to automagically
	update the repo in which the calling file is located.
	The 'force' paramter will cause the module to force do a
	pull and push. This is a destructive action that can
	cause loss of local data. 'check_dev' when set to True
	will not allow any destructive action to take place IFF
	the calling script is in a selfupdate dev environment.
	'message' is the commit message that will be used when
	changes are pushed up to the remote repo. If the remote
	repo is password protected you will need to provide the
	username and password so that the push does not fail.
	'''
	if force:
		push(force=force, check_dev=check_dev, message=message, username=username, password=password, verbose=verbose)
		__print(verbose, "Pushed any possible local changes")
		pull(force=force, check_dev=check_dev, verbose=verbose)
		__print(verbose, "Pulled any possible remote changes")
	else:
		pull(force=force, check_dev=check_dev, verbose=verbose)
		__print(verbose, "Pulled any possible remote changes")
		push(force=force, check_dev=check_dev, message=message, username=username, password=password, verbose=verbose)
		__print(verbose, "Pushed any possible local changes")


text:
layout: categories
title: Categorias
icon: fa-list
lang: pt
ref: categories
permalink: /categorias/
nav: 0
---


text:
#ifndef RUBY_UTIL_H
#define RUBY_UTIL_H 1

#if defined(__cplusplus)
extern "C" {
#if 0
} /* satisfy cc-mode */
#endif
#endif

#ifndef _
#ifdef __cplusplus
# ifndef  HAVE_PROTOTYPES
#  define HAVE_PROTOTYPES 1
# endif
# ifndef  HAVE_STDARG_PROTOTYPES
#  define HAVE_STDARG_PROTOTYPES 1
# endif
#endif
#ifdef HAVE_PROTOTYPES
# define _(args) args
#else
# define _(args) ()
#endif
#ifdef HAVE_STDARG_PROTOTYPES
# define __(args) args
#else
# define __(args) ()
#endif
#endif

#define scan_oct(s,l,e) (int)ruby_scan_oct(s,l,e)
unsigned long ruby_scan_oct(const char *, size_t, size_t *);
#define scan_hex(s,l,e) (int)ruby_scan_hex(s,l,e)
unsigned long ruby_scan_hex(const char *, size_t, size_t *);

#if defined(__CYGWIN32__) || defined(_WIN32)
void ruby_add_suffix(VALUE str, const char *suffix);
#endif

void ruby_qsort(void *, const size_t, const size_t,
		int (*)(const void *, const void *, void *), void *);

void ruby_setenv(const char *, const char *);
void ruby_unsetenv(const char *);
#undef setenv
#undef unsetenv
#define setenv(name,val) ruby_setenv(name,val)
#define unsetenv(name,val) ruby_unsetenv(name);

char *ruby_strdup(const char *);
#undef strdup
#define strdup(s) ruby_strdup(s)

char *ruby_getcwd(void);
#define my_getcwd() ruby_getcwd()

double ruby_strtod(const char *, char **);
#undef strtod
#define strtod(s,e) ruby_strtod(s,e)

#if defined _MSC_VER && _MSC_VER >= 1300
#pragma warning(push)
#pragma warning(disable:4723)
#endif
static inline double
ruby_div0(double x)
{
    double t = 0.0;
    return x / t;
}
#if defined _MSC_VER && _MSC_VER >= 1300
#pragma warning(pop)
#endif

void ruby_each_words(const char *, void (*)(const char*, int, void*), void *);

#if defined(__cplusplus)
#if 0
{ /* satisfy cc-mode */
#endif
}  /* extern "C" { */
#endif

#endif /* RUBY_UTIL_H */


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (C) 2008-2016 Ryo Suzuki
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include "Fwd.hpp"
# include "Array.hpp"
# include "String.hpp"
# include "Image.hpp"
# include "Wave.hpp"

namespace s3d
{
	namespace Threading
	{
		Array<Image> LoadImages(const Array<FilePath>& paths);

		bool SaveImages(const Array<Image>& images, const Array<FilePath>& paths);

		Array<Wave> LoadWaves(const Array<FilePath>& paths);

		bool SaveWaves(const Array<Wave>& waves, const Array<FilePath>& paths);
	}
}


text:
"use strict";
var path_graph_component_1 = require('./path-graph.component');
exports.PathGraphComponent = path_graph_component_1.PathGraphComponent;
//# sourceMappingURL=index.js.map


text:
package org.ihtsdo.otf.ts.rf2.jpa;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

import org.hibernate.envers.Audited;
import org.ihtsdo.otf.ts.rf2.SimpleRefSetMember;

/**
 * Concrete implementation of {@link SimpleRefSetMember}.
 */
@Entity
@Table(name = "simple_refset_members")
@Audited
@XmlRootElement(name = "simple")
public class SimpleRefSetMemberJpa extends AbstractConceptRefSetMember
    implements SimpleRefSetMember {

  /**
   * Instantiates an empty {@link SimpleRefSetMemberJpa}.
   */
  public SimpleRefSetMemberJpa() {
    // do nothing
  }

  /**
   * Instantiates a {@link SimpleRefSetMemberJpa} from the specified parameters.
   *
   * @param member the member
   */
  public SimpleRefSetMemberJpa(SimpleRefSetMember member) {
    super(member);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
    return super.toString()
        + (this.getConcept() == null ? null : this.getConcept()
            .getTerminologyId());
  }

}


text:
package com.jt;

public class StockPrices {
    /**
     * Find maximum profit given an array of stock prices sorted chronologically
     * @param stockPrices
     * @return
     */
    public static double findMaxProfit0(double[] stockPrices) {
        if (stockPrices == null || stockPrices.length == 0) {
            throw new IllegalArgumentException("stockPrices array cannot be null or empty");
        }

        double min = stockPrices[0];
        double maxProfit = 0;

        for (int i = 1; i < stockPrices.length; i++) {
            if (stockPrices[i] < min) {
                min = stockPrices[i];
            }
            else {
                double profit = stockPrices[i] - min;
                if (maxProfit < profit) {
                    maxProfit = profit;
                }
            }
        }

        return maxProfit;
    }

    public static double findMaxProfit(double[] stockPrices) {
        if (stockPrices == null || stockPrices.length < 2) {
            throw new IllegalArgumentException("stockPrices array cannot be null or has fewer than 2 items");
        }

        double min = stockPrices[1] < stockPrices[0] ? stockPrices[1] : stockPrices[0];
        double maxProfit = stockPrices[1] - stockPrices[0];

        for (int i=2; i<stockPrices.length; i++) {
            if (min > stockPrices[i]) {
                min = stockPrices[i];
            }
            else {
                double profit = stockPrices[i] - min;
                if (maxProfit < profit) {
                    maxProfit = profit;
                }
            }
        }

        return maxProfit;
    }

    public static double findMaxProfitBruteForce(double[] stockPrices) {
        double maxProfit = 0;

        for(int i=0; i<stockPrices.length - 1; i++) {
            for(int j=i+1; j<stockPrices.length; j++) {
                if (maxProfit < stockPrices[j] - stockPrices[i]) {
                    maxProfit = stockPrices[j] - stockPrices[i];
                }
            }
        }

        return maxProfit;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.synapse.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.synapse.fluent.models.ClusterPrincipalAssignmentInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** The list Kusto cluster principal assignments operation response. */
@Fluent
public final class ClusterPrincipalAssignmentListResult {
    /*
     * The list of Kusto cluster principal assignments.
     */
    @JsonProperty(value = "value")
    private List<ClusterPrincipalAssignmentInner> value;

    /**
     * Get the value property: The list of Kusto cluster principal assignments.
     *
     * @return the value value.
     */
    public List<ClusterPrincipalAssignmentInner> value() {
        return this.value;
    }

    /**
     * Set the value property: The list of Kusto cluster principal assignments.
     *
     * @param value the value value to set.
     * @return the ClusterPrincipalAssignmentListResult object itself.
     */
    public ClusterPrincipalAssignmentListResult withValue(List<ClusterPrincipalAssignmentInner> value) {
        this.value = value;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text:
require 'httparty'

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

  def present?
    !blank?
  end
end

class Angel
  def initialize
    @angel_url = "https://api.angel.co/1"
    @angel_token = ENV['ANGEL_TOKEN']
  end

  def get_similar startup_name
    startup = find_startup startup_name
    unless startup.present?
      puts "Couldn't find the #{startup_name} from search."
      return false
    end

    puts "Found #{startup_name} in AngelList. It's name is - '#{startup['name']}'' Getting more info."

    startup = fetch_info startup["id"].to_s
    if startup["hidden"]
      puts "#{startup_name} have it's details hidden in AngelList. Couldn't proceed."
      return false
    end

    if startup["markets"].present?
      puts "Got more Info about #{startup_name}. Fetching Market Tags and their children count."
      tags_hash = fetch_tag_children startup["markets"]
    elsif startup["locations"].present?
      puts "#{startup_name} has no Market tags. Fetching it's Location tags."
      tags_hash = fetch_tag_children startup["locations"]
    else
      puts "#{startup_name} has neither Location Tags nor Market tags. Couldn't proceed."
      return false
    end

    puts "Got Tag Information. Getting startups from the tag."
    similar = {}
    tags_hash.each do |k, v|
      similar = find_startup_by_tag k
      if similar.present?
        puts "Found a similar startup!"
        break
      end
    end
    return similar
  end

  def find_startup startup_name
    params_hash = {
          query: startup_name,
          type: "Startup",
          access_token: @angel_token
        }
    search_url = @angel_url + '/search?' + URI.encode_www_form(params_hash)
    results = get_data search_url

    return results.first
  end

  def fetch_info id
    fetch_url = @angel_url + '/startups/' + id + '?access_token=' + @angel_token
    return get_data fetch_url
  end

  def fetch_tag_children tags
    children = {}
    tags.each do |tag|
      tag_url = @angel_url + '/tags/' + tag["id"].to_s + '?access_token=' + @angel_token
      result = get_data tag_url

      children[tag["id"]] = result["total"]
    end
    Hash[children.sort]
  end

  def find_startup_by_tag tag
    params = {
      access_token: @angel_token,
      page: rand(1..1)
    }
    fetch_url = @angel_url + '/tags/' + tag.to_s + '/startups?' + URI.encode_www_form(params)
    results = get_data fetch_url
    unless results.present?
      return false
    end

    results["startups"].each do |startup|
      if startup["hidden"]
        next
      else
        return {
                :name => startup["name"],
                :summary =>startup["high_concept"]
                }
        break
      end
    end
  end

  def get_data url
    resp = HTTParty.get url
    JSON.parse(resp.body)
  end
end

startup = ARGV[0]
unless startup.present?
  puts 'Please provide a startup name..'
end

angel = Angel.new
similar = angel.get_similar startup
if similar.present?
  puts "Name: #{similar[:name]}"
  puts "Summary: #{similar[:summary]}"
else
  puts "Unable to find similar startup for #{startup}"
end


text:
context('Evo', () => {
  beforeEach(() => {
    cy.visit('http://localhost:5000/demo-server/evo');
    cy.wait(1000);
  });

  it('API should exist', () => {
    return cy.window().then(window => {
      expect(window).to.have.property('fresh8');
      expect(window.fresh8).to.have.property('remove');
      expect(window.fresh8).to.have.property('reloadAllAds');
      expect(window.fresh8).to.have.property('requestAd');
    });
  });

  it('Should allow you to request an ads', () => {
    return cy.window().then(window => {
      return window.fresh8.requestAd({ slotID: 'f8-5', appendPoint: 'body', view: 'football' });
    });
  });

  it('Should allow you to reload the ads', () => {
    return cy.window().then(window => {
      return window.fresh8.reloadAllAds();
    });
  });

  it('Should allow you to remove the ads', () => {
    return cy.window().then(window => {
      expect(function () {
        return window.fresh8.remove();
      }).to.not.throw();
    });
  });
});


text:
<?php

/**
 * Squiz_Sniffs_Objects_ObjectInstantiationSniff.
 *
 * Ensures objects are assigned to a variable when instantiated.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Greg Sherwood <gsherwood@squiz.net>
 * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
 * @version   Release: 1.5.2
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Squiz_Sniffs_Objects_ObjectMemberCommaSniff implements PHP_CodeSniffer_Sniff
{

    /**
     * A list of tokenizers this sniff supports.
     *
     * @var array
     */
    public $supportedTokenizers = array('JS');

    /**
     * Registers the token types that this sniff wishes to listen to.
     *
     * @return array
     */
    public function register()
    {
        return array(T_CLOSE_CURLY_BRACKET);

    }//end register()

    /**
     * Process the tokens that this sniff is listening for.
     *
     * @param PHP_CodeSniffer_File $phpcsFile The file where the token was found.
     * @param int                  $stackPtr  The position in the stack where
     *                                        the token was found.
     *
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        // Only interested in orphaned braces (which are objects)
        // and object definitions.
        if (isset($tokens[$stackPtr]['scope_condition']) === true) {
            $condition = $tokens[$stackPtr]['scope_condition'];
            if ($tokens[$condition]['code'] !== T_OBJECT) {
                return;
            }
        }

        $prev = $phpcsFile->findPrevious(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
        if ($tokens[$prev]['code'] === T_COMMA) {
            $error = 'Last member of object must not be followed by a comma';
            $phpcsFile->addError($error, $prev, 'Missing');
        }

    }//end process()

}//end class

?>


text:
public class SeguroDeVida implements Tributavel {
  public double calculaTributos() {
    return 42;
  }
}