text:
The previous examples have always been very convenient; `Result`s interact
with other `Result`s and `Option`s interact with other `Option`s.

Sometimes an `Option` needs to interact with a `Result`, or a
`Result<T, Error1>` needs to interact with a `Result<T, Error2>`. In those
cases, we want to manage our different error types in a way that makes them
composable and easy to interact with.

In the following code, two instances of `unwrap` generate different error
types. `Vec::first` returns an `Option`, while `parse::<i32>` returns a
`Result<i32, ParseIntError>`:

```rust,editable,ignore,mdbook-runnable
fn double_first(vec: Vec<&str>) -> i32 {
    let first = vec.first().unwrap(); // Generate error 1
    2 * first.parse::<i32>().unwrap() // Generate error 2
}

fn main() {
    let numbers = vec!["42", "93", "18"];
    let empty = vec![];
    let strings = vec!["tofu", "93", "18"];

    println!("The first doubled is {}", double_first(numbers));

    println!("The first doubled is {}", double_first(empty));
    // Error 1: the input vector is empty

    println!("The first doubled is {}", double_first(strings));
    // Error 2: the element doesn't parse to a number
}
```

Over the next sections, we'll see several strategies for handling these kind of problems.

redpajama_set_name: RedPajamaGithub


text:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "C:/Program Files/glslang")
endif()
string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")

# Set the install configuration name.
if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME)
  if(BUILD_TYPE)
    string(REGEX REPLACE "^[^A-Za-z0-9_]+" ""
           CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}")
  else()
    set(CMAKE_INSTALL_CONFIG_NAME "Release")
  endif()
  message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"")
endif()

# Set the component getting installed.
if(NOT CMAKE_INSTALL_COMPONENT)
  if(COMPONENT)
    message(STATUS "Install component: \"${COMPONENT}\"")
    set(CMAKE_INSTALL_COMPONENT "${COMPONENT}")
  else()
    set(CMAKE_INSTALL_COMPONENT)
  endif()
endif()

if(NOT CMAKE_INSTALL_LOCAL_ONLY)
  # Include the install script for each subdirectory.
  include("D:/Vulkan/1.0.65.1/glslang/Build/External/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/glslang/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/OGLCompilersDLL/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/StandAlone/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/SPIRV/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/hlsl/cmake_install.cmake")
  include("D:/Vulkan/1.0.65.1/glslang/Build/gtests/cmake_install.cmake")

endif()

if(CMAKE_INSTALL_COMPONENT)
  set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt")
else()
  set(CMAKE_INSTALL_MANIFEST "install_manifest.txt")
endif()

string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT
       "${CMAKE_INSTALL_MANIFEST_FILES}")
file(WRITE "D:/Vulkan/1.0.65.1/glslang/Build/${CMAKE_INSTALL_MANIFEST}"
     "${CMAKE_INSTALL_MANIFEST_CONTENT}")


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/*
 * nsConsoleService class declaration.
 */

#ifndef __nsconsoleservice_h__
#define __nsconsoleservice_h__

#include "nsCOMPtr.h"
#include "nsHashtable.h"
#include "nsAutoLock.h"

#include "nsIConsoleService.h"

class nsConsoleService : public nsIConsoleService
{
public:
    nsConsoleService();

    NS_DECL_ISUPPORTS
    NS_DECL_NSICONSOLESERVICE

private:
    ~nsConsoleService();

    // build (or find) a proxy for the listener
    nsresult GetProxyForListener(nsIConsoleListener* aListener,
                                 nsIConsoleListener** aProxy);

    // Circular buffer of saved messages
    nsIConsoleMessage **mMessages;

    // How big?
    PRUint32 mBufferSize;

    // Index of slot in mMessages that'll be filled by *next* log message
    PRUint32 mCurrent;

    // Is the buffer full? (Has mCurrent wrapped around at least once?)
    PRBool mFull;

    // Listeners to notify whenever a new message is logged.
    nsSupportsHashtable mListeners;

    // Current listener being notified of a logged error - to prevent
    // stack overflows.
    PRBool mListening;

    // To serialize interesting methods.
    PRLock *mLock;
};

#endif /* __nsconsoleservice_h__ */


text:
#pragma once

#include "CoreMinimal.h"
#include "VoxelFastNoiseBase.h"

template<typename T>
class TVoxelFastNoise_PerlinNoise : public T
{
public:
	DEFINE_VOXEL_NOISE_CLASS()
	GENERATED_VOXEL_NOISE_FUNCTION_2D(Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_2D_DERIV(Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_3D(Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_3D_DERIV(Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_FRACTAL_2D(Perlin, Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_FRACTAL_2D_DERIV(Perlin, Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_FRACTAL_3D(Perlin, Perlin)
	GENERATED_VOXEL_NOISE_FUNCTION_FRACTAL_3D_DERIV(Perlin, Perlin)

protected:
	v_flt SinglePerlin_2D(uint8 offset, v_flt x, v_flt y) const;
	v_flt SinglePerlin_2D_Deriv(uint8 offset, v_flt x, v_flt y, v_flt& outDx, v_flt& outDy) const;

	v_flt SinglePerlin_3D(uint8 offset, v_flt x, v_flt y, v_flt z) const;
	v_flt SinglePerlin_3D_Deriv(uint8 offset, v_flt x, v_flt y, v_flt z, v_flt& outDx, v_flt& outDy, v_flt& outDz) const;
};


text:
package org.apache.flink.runtime.dispatcher.runner;

import org.apache.flink.runtime.dispatcher.DispatcherFactory;
import org.apache.flink.runtime.dispatcher.PartialDispatcherServices;
import org.apache.flink.runtime.entrypoint.component.JobGraphRetriever;
import org.apache.flink.runtime.jobmanager.JobGraphStoreFactory;
import org.apache.flink.runtime.leaderelection.LeaderElectionService;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;

import java.util.concurrent.Executor;

/**
 * {@link DispatcherRunnerFactory} implementation which creates {@link DefaultDispatcherRunner}
 * instances.
 */
public class DefaultDispatcherRunnerFactory implements DispatcherRunnerFactory {
    private final DispatcherLeaderProcessFactoryFactory dispatcherLeaderProcessFactoryFactory;

    public DefaultDispatcherRunnerFactory(
            DispatcherLeaderProcessFactoryFactory dispatcherLeaderProcessFactoryFactory) {
        this.dispatcherLeaderProcessFactoryFactory = dispatcherLeaderProcessFactoryFactory;
    }

    @Override
    public DispatcherRunner createDispatcherRunner(
            LeaderElectionService leaderElectionService,
            FatalErrorHandler fatalErrorHandler,
            JobGraphStoreFactory jobGraphStoreFactory,
            Executor ioExecutor,
            RpcService rpcService,
            PartialDispatcherServices partialDispatcherServices)
            throws Exception {

        final DispatcherLeaderProcessFactory dispatcherLeaderProcessFactory =
                dispatcherLeaderProcessFactoryFactory.createFactory(
                        jobGraphStoreFactory,
                        ioExecutor,
                        rpcService,
                        partialDispatcherServices,
                        fatalErrorHandler);

        return DefaultDispatcherRunner.create(
                leaderElectionService, fatalErrorHandler, dispatcherLeaderProcessFactory);
    }

    public static DefaultDispatcherRunnerFactory createSessionRunner(
            DispatcherFactory dispatcherFactory) {
        return new DefaultDispatcherRunnerFactory(
                SessionDispatcherLeaderProcessFactoryFactory.create(dispatcherFactory));
    }

    public static DefaultDispatcherRunnerFactory createJobRunner(
            JobGraphRetriever jobGraphRetriever) {
        return new DefaultDispatcherRunnerFactory(
                JobDispatcherLeaderProcessFactoryFactory.create(jobGraphRetriever));
    }
}


text:
package util

import "sort"

// SortedKeys returns a sorted slice of keys of a map.
func SortedKeys(m map[string]interface{}) []string {
	i, sorted := 0, make([]string, len(m))
	for k := range m {
		sorted[i] = k
		i++
	}
	sort.Strings(sorted)
	return sorted
}
//Added a line for testing
//Adding another line for Git event testing part 2
//Adding another line for Git event testing part 2.1
//Adding another line for Git event testing part 2.2


text:
package com.mapswithme.maps.editor;

import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.mapswithme.maps.MwmApplication;
import com.mapswithme.maps.R;
import com.mapswithme.maps.dialog.EditTextDialogFragment;
import com.mapswithme.maps.editor.data.LocalizedStreet;
import com.mapswithme.util.UiUtils;

public class StreetAdapter extends RecyclerView.Adapter<StreetAdapter.BaseViewHolder>
{
  private static final int TYPE_ADD_STREET = 0;
  private static final int TYPE_STREET = 1;

  private final LocalizedStreet[] mStreets;
  private final StreetFragment mFragment;
  private LocalizedStreet mSelectedStreet;

  public StreetAdapter(@NonNull StreetFragment host, @NonNull LocalizedStreet[] streets, @NonNull LocalizedStreet selected)
  {
    mFragment = host;
    mStreets = streets;
    mSelectedStreet = selected;
  }

  @Override
  public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
  {
    return viewType == TYPE_STREET ? new StreetViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_street, parent, false))
                                   : new AddViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_add_street, parent, false));
  }

  @Override
  public void onBindViewHolder(BaseViewHolder holder, int position)
  {
    holder.bind(position);
  }

  @Override
  public int getItemCount()
  {
    return mStreets.length + 1;
  }

  @Override
  public int getItemViewType(int position)
  {
    return position == getItemCount() - 1 ? TYPE_ADD_STREET : TYPE_STREET;
  }

  public LocalizedStreet getSelectedStreet()
  {
    return mSelectedStreet;
  }

  private void addStreet()
  {
    final Resources resources = MwmApplication.get().getResources();
    EditTextDialogFragment.show(resources.getString(R.string.street), null,
                                resources.getString(R.string.ok),
                                resources.getString(R.string.cancel), mFragment);
  }

  protected abstract class BaseViewHolder extends RecyclerView.ViewHolder
  {
    public BaseViewHolder(View itemView)
    {
      super(itemView);
    }

    public void bind(int position) {}
  }

  protected class StreetViewHolder extends BaseViewHolder implements View.OnClickListener
  {
    final TextView streetDef;
    final TextView streetLoc;
    final CompoundButton selected;

    public StreetViewHolder(View itemView)
    {
      super(itemView);
      streetDef = (TextView) itemView.findViewById(R.id.street_default);
      streetLoc = (TextView) itemView.findViewById(R.id.street_localized);
      selected = (CompoundButton) itemView.findViewById(R.id.selected);
      itemView.setOnClickListener(this);
      selected.setOnClickListener(new View.OnClickListener()
      {
        @Override
        public void onClick(View v)
        {
          selected.toggle();
          StreetViewHolder.this.onClick(selected);
        }
      });
    }

    @Override
    public void bind(int position)
    {
      selected.setChecked(mSelectedStreet.defaultName.equals(mStreets[position].defaultName));
      streetDef.setText(mStreets[position].defaultName);
      UiUtils.setTextAndHideIfEmpty(streetLoc, mStreets[position].localizedName);
    }

    @Override
    public void onClick(View v)
    {
      mSelectedStreet = mStreets[getAdapterPosition()];
      notifyDataSetChanged();
      mFragment.saveStreet(mSelectedStreet);
    }
  }

  protected class AddViewHolder extends BaseViewHolder
  {
    public AddViewHolder(View itemView)
    {
      super(itemView);
      itemView.setOnClickListener(new View.OnClickListener()
      {
        @Override
        public void onClick(View v)
        {
          addStreet();
        }
      });
    }
  }
}


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using OpenPriceConfig.Models;

namespace OpenPriceConfig.Data.Migrations
{
    public partial class optionInputType : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<int>(
                name: "InputType",
                table: "Option",
                nullable: false,
                defaultValue: Option.InputTypes.Checkbox);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "InputType",
                table: "Option");
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using TOutput = System.ValueTuple<System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.GeneratedSourceText>, System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic>>;

namespace Microsoft.CodeAnalysis
{
    internal sealed class SourceOutputNode<TInput> : IIncrementalGeneratorOutputNode, IIncrementalGeneratorNode<TOutput>
    {
        private readonly IIncrementalGeneratorNode<TInput> _source;

        private readonly Action<SourceProductionContext, TInput> _action;

        public SourceOutputNode(IIncrementalGeneratorNode<TInput> source, Action<SourceProductionContext, TInput> action)
        {
            _source = source;
            _action = action;
        }

        public IncrementalGeneratorOutputKind Kind => IncrementalGeneratorOutputKind.Source;

        public NodeStateTable<TOutput> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<TOutput> previousTable, CancellationToken cancellationToken)
        {
            var sourceTable = graphState.GetLatestStateTableForNode(_source);
            if (sourceTable.IsCached)
            {
                return previousTable;
            }

            var nodeTable = previousTable.ToBuilder();
            foreach (var entry in sourceTable)
            {
                if (entry.state == EntryState.Removed)
                {
                    nodeTable.RemoveEntries();
                }
                else if (entry.state != EntryState.Cached || !nodeTable.TryUseCachedEntries())
                {
                    // we don't currently handle modified any differently than added at the output
                    // we just run the action and mark the new source as added. In theory we could compare
                    // the diagnostics and sources produced and compare them, to see if they are any different
                    // than before.

                    var sourcesBuilder = ArrayBuilder<GeneratedSourceText>.GetInstance();
                    var diagnostics = DiagnosticBag.GetInstance();

                    SourceProductionContext context = new SourceProductionContext(sourcesBuilder, diagnostics, cancellationToken);
                    try
                    {
                        _action(context, entry.item);
                        nodeTable.AddEntry((sourcesBuilder.ToImmutable(), diagnostics.ToReadOnly()), EntryState.Added);
                    }
                    finally
                    {
                        sourcesBuilder.Free();
                        diagnostics.Free();
                    }

                }
            }

            return nodeTable.ToImmutableAndFree();
        }

        IIncrementalGeneratorNode<TOutput> IIncrementalGeneratorNode<TOutput>.WithComparer(IEqualityComparer<TOutput> comparer) => throw ExceptionUtilities.Unreachable;

        void IIncrementalGeneratorNode<TOutput>.RegisterOutput(IIncrementalGeneratorOutputNode output) => throw ExceptionUtilities.Unreachable;

        public void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken)
        {
            // get our own state table
            Debug.Assert(context.TableBuilder is object);
            var table = context.TableBuilder.GetLatestStateTableForNode(this);

            // add each non-removed entry to the context
            foreach (var ((sources, diagnostics), state) in table)
            {
                if (state != EntryState.Removed)
                {
                    foreach (var text in sources)
                    {
                        try
                        {
                            context.Sources.Add(text.HintName, text.Text);
                        }
                        catch (ArgumentException e)
                        {
                            throw new UserFunctionException(e);
                        }
                    }
                    context.Diagnostics.AddRange(diagnostics);
                }
            }
        }
    }
}


text:
package org.springframework.data.solr.repository;

/**
 * @author Francisco Spaeth
 * @since 1.2
 */
public @interface Pivot {

	/**
	 * {@code facet.pivot} definition of a pivot field.
	 *
	 * @return
	 */
	String[] value() default {};

}


text:
import React from 'react';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';

export default function FontSize() {
  return (
    <Typography component="div">
      <Box fontSize="fontSize" m={1}>
        Default
      </Box>
      <Box fontSize="h6.fontSize" m={1}>
        h6.fontSize
      </Box>
      <Box fontSize={16} m={1}>
        16px
      </Box>
    </Typography>
  );
}


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.dfareporting.model;

/**
 * Placement List Response
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Campaign Manager 360 API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class PlacementsListResponse extends com.google.api.client.json.GenericJson {

  /**
   * Identifies what kind of resource this is. Value: the fixed string
   * "dfareporting#placementsListResponse".
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String kind;

  /**
   * Pagination token to be used for the next list operation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String nextPageToken;

  /**
   * Placement collection.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<Placement> placements;

  static {
    // hack to force ProGuard to consider Placement used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(Placement.class);
  }

  /**
   * Identifies what kind of resource this is. Value: the fixed string
   * "dfareporting#placementsListResponse".
   * @return value or {@code null} for none
   */
  public java.lang.String getKind() {
    return kind;
  }

  /**
   * Identifies what kind of resource this is. Value: the fixed string
   * "dfareporting#placementsListResponse".
   * @param kind kind or {@code null} for none
   */
  public PlacementsListResponse setKind(java.lang.String kind) {
    this.kind = kind;
    return this;
  }

  /**
   * Pagination token to be used for the next list operation.
   * @return value or {@code null} for none
   */
  public java.lang.String getNextPageToken() {
    return nextPageToken;
  }

  /**
   * Pagination token to be used for the next list operation.
   * @param nextPageToken nextPageToken or {@code null} for none
   */
  public PlacementsListResponse setNextPageToken(java.lang.String nextPageToken) {
    this.nextPageToken = nextPageToken;
    return this;
  }

  /**
   * Placement collection.
   * @return value or {@code null} for none
   */
  public java.util.List<Placement> getPlacements() {
    return placements;
  }

  /**
   * Placement collection.
   * @param placements placements or {@code null} for none
   */
  public PlacementsListResponse setPlacements(java.util.List<Placement> placements) {
    this.placements = placements;
    return this;
  }

  @Override
  public PlacementsListResponse set(String fieldName, Object value) {
    return (PlacementsListResponse) super.set(fieldName, value);
  }

  @Override
  public PlacementsListResponse clone() {
    return (PlacementsListResponse) super.clone();
  }

}


text:
package com.jexunit.core.commands;

import com.jexunit.core.JExUnit;
import com.jexunit.core.JExUnitConfig;
import com.jexunit.core.commands.Command.Type;
import com.jexunit.core.commands.annotation.TestCommand;
import com.jexunit.core.commands.annotation.TestCommand.TestCommands;
import eu.infomas.annotation.AnnotationDetector.MethodReporter;
import eu.infomas.annotation.AnnotationDetector.TypeReporter;
import org.junit.runner.RunWith;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

/**
 * MethodReporter-Implementation for "storing" the annotated methods found. The "Annotation-Scan" will run once, so we
 * can hold the methods found in the static methods-Map.
 *

 * TODO: "override" command-methods (what about different parameter-types?)
 *
 * @author fabian
 */
public class TestCommandScanner implements TypeReporter, MethodReporter {

    private static final Map<String, Map<Class<?>, Command>> commands = new HashMap<>();

    @SuppressWarnings("unchecked")
    @Override
    public Class<? extends Annotation>[] annotations() {
        return new Class[]{TestCommand.class, TestCommands.class};
    }

    @Override
    public void reportMethodAnnotation(final Class<? extends Annotation> annotation, final String className, final String methodName) {
        try {
            final Class<?> clazz = getClass().getClassLoader().loadClass(className);
            Class<?> type = null;
            if (clazz.isAnnotationPresent(RunWith.class)) {
                final RunWith rwa = clazz.getAnnotation(RunWith.class);
                if (rwa.value() == JExUnit.class) {
                    type = clazz;
                }
            }

            if (annotation.isAnnotation() && (annotation == TestCommand.class || annotation == TestCommands.class)) {
                for (final Method m : clazz.getDeclaredMethods()) {
                    final TestCommand[] testCommands = m.getDeclaredAnnotationsByType(TestCommand.class);
                    registerCommands(testCommands, type, m);
                }
            }
        } catch (final ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void reportTypeAnnotation(final Class<? extends Annotation> annotation, final String className) {
        try {
            final Class<?> clazz = getClass().getClassLoader().loadClass(className);

            if (annotation.isAnnotation() && (annotation == TestCommand.class || annotation == TestCommands.class)) {
                if (!checkTestCommandClass(clazz)) {
                    throw new IllegalArgumentException(
                            "Test-Command implementation not valid. A class defined as test-command has to provide one single public method!");
                }

                final TestCommand[] testCommands = clazz.getDeclaredAnnotationsByType(TestCommand.class);
                registerCommands(testCommands, clazz, null);
            }
        } catch (final ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Calculate the command names for the given Annotations and "register" the test-commands.
     *
     * @param testCommands TestCommand-Annotations found
     * @param type         the type the annotations were found in
     * @param method       the method the annotations were found for
     */
    private void registerCommands(final TestCommand[] testCommands, final Class<?> type, final Method method) {
        for (final TestCommand tc : testCommands) {
            if (tc != null) {
                String[] commandNames = tc.value();
                if (commandNames.length == 0) {
                    // calculate command-name out of the method-name/class-name
                    if (method == null) {
                        commandNames = new String[]{calculateCommandName(type)};
                    } else {
                        commandNames = new String[]{calculateCommandName(method)};
                    }
                }
                for (String command : commandNames) {
                    command = command.toLowerCase();
                    if (!commands.containsKey(command)) {
                        commands.put(command, new HashMap<>());
                    }
                    if (method == null) {
                        // test-command is implemented in a class
                        commands.get(command).put(null, new Command(command, type, tc.fastFail()));
                    } else {
                        // test-command is a method
                        commands.get(command).put(type, new Command(command, type, method, tc.fastFail()));
                    }
                }
            }
        }
    }

    /**
     * Calculate the name for the test-command out of the simple name of the given class. If there is a prefix and/or
     * postfix configured, this will be removed from the name.
     *
     * @param type Class to calculate the name for the test-command from
     * @return the calculated name for the test-command
     */
    private String calculateCommandName(final Class<?> type) {
        String name = type.getSimpleName();
        final String prefix = JExUnitConfig.getStringProperty(JExUnitConfig.ConfigKey.COMMAND_CLASS_PREFIX);
        final String postfix = JExUnitConfig.getStringProperty(JExUnitConfig.ConfigKey.COMMAND_CLASS_POSTFIX);
        if (prefix != null && name.toLowerCase().startsWith(prefix.toLowerCase())) {
            name = name.substring(prefix.length());
        }
        if (postfix != null && name.toLowerCase().endsWith(postfix.toLowerCase())) {
            name = name.substring(0, name.length() - postfix.length());
        }

        return name;
    }

    /**
     * Calculate the name for the test-command out of the name of the given method. If there is a prefix and/or postfix
     * configured, this will be removed from the name.
     *
     * @param m Method to calculate the name for the test-command from
     * @return the calculated name for the test-command
     */
    private String calculateCommandName(final Method m) {
        String name = m.getName();
        final String prefix = JExUnitConfig.getStringProperty(JExUnitConfig.ConfigKey.COMMAND_METHOD_PREFIX);
        final String postfix = JExUnitConfig.getStringProperty(JExUnitConfig.ConfigKey.COMMAND_METHOD_POSTFIX);
        if (prefix != null && name.toLowerCase().startsWith(prefix.toLowerCase())) {
            name = name.substring(prefix.length());
        }
        if (postfix != null && name.toLowerCase().endsWith(postfix.toLowerCase())) {
            name = name.substring(0, name.length() - postfix.length());
        }

        return name;
    }

    /**
     * Check, if the given class is a valid test-command implementation. A class is a valid test-command implementation,
     * if there is only a single public method (functional interface!).
     *
     * @param clazz Class to check
     * @return true, if the class defines exactly one single public method, else false
     */
    private boolean checkTestCommandClass(final Class<?> clazz) {
        // check number of public methods
        final Method[] methods = clazz.getDeclaredMethods();
        int numberOfPublicMethods = 0;
        for (final Method m : methods) {
            if (Modifier.isPublic(m.getModifiers())) {
                numberOfPublicMethods++;
            }
        }

        return numberOfPublicMethods == 1;
    }

    /**
     * Get the Command for the given command-name and type.
     *
     * @param command the excel-command
     * @param clazz   the type of the test-class
     * @return the command for the given class, if found, else null
     */
    static Command getTestCommand(final String command, final Class<?> clazz) {
        if (commands.containsKey(command)) {
            final Map<Class<?>, Command> cmds = commands.get(command);

            if (cmds != null && !cmds.isEmpty()) {
                if (clazz == null) {
                    if (cmds.containsKey(null)) {
                        return cmds.get(null);
                    }
                } else {
                    // not found? check superclass
                    Class<?> cls = clazz;
                    do {
                        if (cmds.containsKey(cls)) {
                            final Command c = cmds.get(cls);
                            if (c.getType() == Type.CLASS || c.getImplementation() == cls) {
                                return c;
                            }
                        }
                    } while ((cls = cls.getSuperclass()) != Object.class);
                }
                return cmds.get(null);
            }
        }
        return null;
    }

    /**
     * Checks if the passed command exists.
     *
     * @param s command name to check
     * @return true if there is a command-implementation for the given string, else false
     */
    public static boolean isTestCommandValid(final String s) {
        if (commands.containsKey(s)) {
            return true;
        }

        boolean isDefaultCommand = false;
        for (final DefaultCommands defaultCommands : DefaultCommands.values()) {
            isDefaultCommand = defaultCommands.getDefaultValue().equals(s);
            if (isDefaultCommand) {
                break;
            }
        }
        return isDefaultCommand;
    }

}


text:
<?php

/**
 * @package redaxo\install
 */
class rex_install_packages
{
    private static $updatePackages;
    private static $addPackages;
    private static $myPackages;

    public static function getUpdatePackages()
    {
        if (is_array(self::$updatePackages)) {
            return self::$updatePackages;
        }

        self::$updatePackages = self::getPackages();

        foreach (self::$updatePackages as $key => $addon) {
            if (is_dir(rex_path::addon($key)) && isset($addon['files'])) {
                self::unsetOlderVersions($key, OOAddon::getVersion($key));
            } else {
                unset(self::$updatePackages[$key]);
            }
        }
        return self::$updatePackages;
    }

    public static function updatedPackage($package, $fileId)
    {
        self::unsetOlderVersions($package, self::$updatePackages[$package]['files'][$fileId]['version']);
    }

    private static function unsetOlderVersions($package, $version)
    {
        foreach (self::$updatePackages[$package]['files'] as $fileId => $file) {
            if (empty($version) || empty($file['version']) || rex_string::versionCompare($file['version'], $version, '<=')) {
                unset(self::$updatePackages[$package]['files'][$fileId]);
            }
        }
        if (empty(self::$updatePackages[$package]['files'])) {
            unset(self::$updatePackages[$package]);
        }
    }

    public static function getAddPackages()
    {
        if (is_array(self::$addPackages)) {
            return self::$addPackages;
        }

        self::$addPackages = self::getPackages();
        /*foreach (self::$addPackages as $key => $addon) {
            if (is_dir(rex_path::addon($key))) {
                unset(self::$addPackages[$key]);
            }
        }*/
        return self::$addPackages;
    }

    public static function addedPackage($package)
    {
        //unset(self::$addPackages[$package]);
        self::$myPackages = null;
    }

    public static function getMyPackages()
    {
        if (is_array(self::$myPackages)) {
            return self::$myPackages;
        }

        self::$myPackages = self::getPackages('?only_my=1');
        foreach (self::$myPackages as $key => $addon) {
            if (!is_dir(rex_path::addon($key))) {
                unset(self::$myPackages[$key]);
            }
        }
        return self::$myPackages;
    }

    public static function getPath($path = '')
    {
        return 'packages/' . $path;
    }

    private static function getPackages($path = '')
    {
        return rex_install_webservice::getJson(self::getPath($path));
    }

    public static function deleteCache()
    {
        self::$updatePackages = null;
        self::$addPackages = null;
        self::$myPackages = null;
        rex_install_webservice::deleteCache('packages/');
    }
}


text:
package robocode.robotinterfaces.peer;

/**
 * The junior robot peer for junior robot types like {@link robocode.JuniorRobot}.
 *

 * A robot peer is the object that deals with game mechanics and rules, and
 * makes sure your robot abides by them.
 *
 * @see IBasicRobotPeer
 * @see IStandardRobotPeer
 * @see IAdvancedRobotPeer
 * @see ITeamRobotPeer
 *
 * @author Pavel Savara (original)
 * @author Flemming N. Larsen (contributor)
 *
 * @since 1.6
 */
public interface IJuniorRobotPeer extends IBasicRobotPeer {

	/**
	 * Moves this robot forward or backwards by pixels and turns this robot
	 * right or left by degrees at the same time. The robot will move in a curve
	 * that follows a perfect circle, and the moving and turning will end at
	 * exactly the same time.
	 *

	 * Note that the max. velocity and max. turn rate is automatically adjusted,
	 * which means that the robot will move slower the sharper the turn is
	 * compared to the distance.
	 *

	 * Note that both positive and negative values can be given as input:
	 *

	 *
If the {@code distance} parameter is set to a positive value, it
	 * means that the robot is set to move forward, and a negative value means
	 * that the robot is set to move backward. If set to 0, the robot will not
	 * move, but will be able to turn.
	 *
If the {@code radians} parameter is set to a positive value, it means
	 * that the robot is set to turn to the right, and a negative value means
	 * that the robot is set to turn to the left. If set to 0, the robot will
	 * not turn, but will be able to move.
	 *

	 *
	 * @param distance the distance to move measured in pixels.
	 *                 If {@code distance} > 0 the robot is set to move forward.
	 *                 If {@code distance} < 0 the robot is set to move backward.
	 *                 If {@code distance} = 0 the robot will not move anywhere, but just
	 *                 finish its turn.
	 * @param radians  the amount of radians to turn the robot's body.
	 *                 If {@code radians} > 0 the robot's body is set to turn right.
	 *                 If {@code radians} < 0 the robot's body is set to turn left.
	 *                 If {@code radians} = 0 the robot's body is set to stop turning.
	 * @see IBasicRobotPeer#move(double) move(double)
	 * @see IBasicRobotPeer#turnBody(double) turnBody(double)
	 * @see IBasicRobotPeer#getBodyHeading() getBodyHeading()
	 * @see IBasicRobotPeer#getX() getX()
	 * @see IBasicRobotPeer#getY() getY()
	 */
	void turnAndMove(double distance, double radians);
}


text:
class AddReasonToCryptoPayOut < ActiveRecord::Migration[5.1]
  def change
    add_column :crypto_pay_outs, :reason, :string
  end
end


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

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValueUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceStability;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.protobuf.generated.QuotaProtos.Quotas;
import org.apache.hadoop.hbase.regionserver.BloomType;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;

/**
 * Helper class to interact with the quota table
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving
public class QuotaUtil extends QuotaTableUtil {
  private static final Log LOG = LogFactory.getLog(QuotaUtil.class);

  public static final String QUOTA_CONF_KEY = "hbase.quota.enabled";
  private static final boolean QUOTA_ENABLED_DEFAULT = false;

  /** Table descriptor for Quota internal table */
  public static final HTableDescriptor QUOTA_TABLE_DESC = new HTableDescriptor(QUOTA_TABLE_NAME);
  static {
    QUOTA_TABLE_DESC.addFamily(new HColumnDescriptor(QUOTA_FAMILY_INFO)
        .setScope(HConstants.REPLICATION_SCOPE_LOCAL).setBloomFilterType(BloomType.ROW)
        .setMaxVersions(1));
    QUOTA_TABLE_DESC.addFamily(new HColumnDescriptor(QUOTA_FAMILY_USAGE)
        .setScope(HConstants.REPLICATION_SCOPE_LOCAL).setBloomFilterType(BloomType.ROW)
        .setMaxVersions(1));
  }

  /** Returns true if the support for quota is enabled */
  public static boolean isQuotaEnabled(final Configuration conf) {
    return conf.getBoolean(QUOTA_CONF_KEY, QUOTA_ENABLED_DEFAULT);
  }

  /*
   * ========================================================================= Quota "settings"
   * helpers
   */
  public static void addTableQuota(final Connection connection, final TableName table,
      final Quotas data) throws IOException {
    addQuotas(connection, getTableRowKey(table), data);
  }

  public static void deleteTableQuota(final Connection connection, final TableName table)
      throws IOException {
    deleteQuotas(connection, getTableRowKey(table));
  }

  public static void addNamespaceQuota(final Connection connection, final String namespace,
      final Quotas data) throws IOException {
    addQuotas(connection, getNamespaceRowKey(namespace), data);
  }

  public static void deleteNamespaceQuota(final Connection connection, final String namespace)
      throws IOException {
    deleteQuotas(connection, getNamespaceRowKey(namespace));
  }

  public static void
      addUserQuota(final Connection connection, final String user, final Quotas data)
          throws IOException {
    addQuotas(connection, getUserRowKey(user), data);
  }

  public static void addUserQuota(final Connection connection, final String user,
      final TableName table, final Quotas data) throws IOException {
    addQuotas(connection, getUserRowKey(user), getSettingsQualifierForUserTable(table), data);
  }

  public static void addUserQuota(final Connection connection, final String user,
      final String namespace, final Quotas data) throws IOException {
    addQuotas(connection, getUserRowKey(user), getSettingsQualifierForUserNamespace(namespace),
      data);
  }

  public static void deleteUserQuota(final Connection connection, final String user)
      throws IOException {
    deleteQuotas(connection, getUserRowKey(user));
  }

  public static void deleteUserQuota(final Connection connection, final String user,
      final TableName table) throws IOException {
    deleteQuotas(connection, getUserRowKey(user), getSettingsQualifierForUserTable(table));
  }

  public static void deleteUserQuota(final Connection connection, final String user,
      final String namespace) throws IOException {
    deleteQuotas(connection, getUserRowKey(user), getSettingsQualifierForUserNamespace(namespace));
  }

  private static void
      addQuotas(final Connection connection, final byte[] rowKey, final Quotas data)
          throws IOException {
    addQuotas(connection, rowKey, QUOTA_QUALIFIER_SETTINGS, data);
  }

  private static void addQuotas(final Connection connection, final byte[] rowKey,
      final byte[] qualifier, final Quotas data) throws IOException {
    Put put = new Put(rowKey);
    put.addColumn(QUOTA_FAMILY_INFO, qualifier, quotasToData(data));
    doPut(connection, put);
  }

  private static void deleteQuotas(final Connection connection, final byte[] rowKey)
      throws IOException {
    deleteQuotas(connection, rowKey, null);
  }

  private static void deleteQuotas(final Connection connection, final byte[] rowKey,
      final byte[] qualifier) throws IOException {
    Delete delete = new Delete(rowKey);
    if (qualifier != null) {
      delete.addColumns(QUOTA_FAMILY_INFO, qualifier);
    }
    doDelete(connection, delete);
  }

  public static Map<String, UserQuotaState> fetchUserQuotas(final Connection connection,
      final List<Get> gets) throws IOException {
    long nowTs = EnvironmentEdgeManager.currentTime();
    Result[] results = doGet(connection, gets);

    Map<String, UserQuotaState> userQuotas = new HashMap<String, UserQuotaState>(results.length);
    for (int i = 0; i < results.length; ++i) {
      byte[] key = gets.get(i).getRow();
      assert isUserRowKey(key);
      String user = getUserFromRowKey(key);

      final UserQuotaState quotaInfo = new UserQuotaState(nowTs);
      userQuotas.put(user, quotaInfo);

      if (results[i].isEmpty()) continue;
      assert Bytes.equals(key, results[i].getRow());

      try {
        parseUserResult(user, results[i], new UserQuotasVisitor() {
          @Override
          public void visitUserQuotas(String userName, String namespace, Quotas quotas) {
            quotaInfo.setQuotas(namespace, quotas);
          }

          @Override
          public void visitUserQuotas(String userName, TableName table, Quotas quotas) {
            quotaInfo.setQuotas(table, quotas);
          }

          @Override
          public void visitUserQuotas(String userName, Quotas quotas) {
            quotaInfo.setQuotas(quotas);
          }
        });
      } catch (IOException e) {
        LOG.error("Unable to parse user '" + user + "' quotas", e);
        userQuotas.remove(user);
      }
    }
    return userQuotas;
  }

  public static Map<TableName, QuotaState> fetchTableQuotas(final Connection connection,
      final List<Get> gets) throws IOException {
    return fetchGlobalQuotas("table", connection, gets, new KeyFromRow<TableName>() {
      @Override
      public TableName getKeyFromRow(final byte[] row) {
        assert isTableRowKey(row);
        return getTableFromRowKey(row);
      }
    });
  }

  public static Map<String, QuotaState> fetchNamespaceQuotas(final Connection connection,
      final List<Get> gets) throws IOException {
    return fetchGlobalQuotas("namespace", connection, gets, new KeyFromRow<String>() {
      @Override
      public String getKeyFromRow(final byte[] row) {
        assert isNamespaceRowKey(row);
        return getNamespaceFromRowKey(row);
      }
    });
  }

  public static <K> Map<K, QuotaState> fetchGlobalQuotas(final String type,
      final Connection connection, final List<Get> gets, final KeyFromRow<K> kfr)
      throws IOException {
    long nowTs = EnvironmentEdgeManager.currentTime();
    Result[] results = doGet(connection, gets);

    Map<K, QuotaState> globalQuotas = new HashMap<K, QuotaState>(results.length);
    for (int i = 0; i < results.length; ++i) {
      byte[] row = gets.get(i).getRow();
      K key = kfr.getKeyFromRow(row);

      QuotaState quotaInfo = new QuotaState(nowTs);
      globalQuotas.put(key, quotaInfo);

      if (results[i].isEmpty()) continue;
      assert Bytes.equals(row, results[i].getRow());

      byte[] data = results[i].getValue(QUOTA_FAMILY_INFO, QUOTA_QUALIFIER_SETTINGS);
      if (data == null) continue;

      try {
        Quotas quotas = quotasFromData(data);
        quotaInfo.setQuotas(quotas);
      } catch (IOException e) {
        LOG.error("Unable to parse " + type + " '" + key + "' quotas", e);
        globalQuotas.remove(key);
      }
    }
    return globalQuotas;
  }

  private static interface KeyFromRow<T> {
    T getKeyFromRow(final byte[] row);
  }

  /*
   * ========================================================================= HTable helpers
   */
  private static void doPut(final Connection connection, final Put put) throws IOException {
    try (Table table = connection.getTable(QuotaUtil.QUOTA_TABLE_NAME)) {
      table.put(put);
    }
  }

  private static void doDelete(final Connection connection, final Delete delete)
      throws IOException {
    try (Table table = connection.getTable(QuotaUtil.QUOTA_TABLE_NAME)) {
      table.delete(delete);
    }
  }

  /*
   * ========================================================================= Data Size Helpers
   */
  public static long calculateMutationSize(final Mutation mutation) {
    long size = 0;
    for (Map.Entry<byte[], List<Cell>> entry : mutation.getFamilyCellMap().entrySet()) {
      for (Cell cell : entry.getValue()) {
        size += KeyValueUtil.length(cell);
      }
    }
    return size;
  }

  public static long calculateResultSize(final Result result) {
    long size = 0;
    for (Cell cell : result.rawCells()) {
      size += KeyValueUtil.length(cell);
    }
    return size;
  }

  public static long calculateResultSize(final List<Result> results) {
    long size = 0;
    for (Result result : results) {
      for (Cell cell : result.rawCells()) {
        size += KeyValueUtil.length(cell);
      }
    }
    return size;
  }
}


text:
<?php

/**
 * BaseCollectionStorageLocation
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @property integer $collection_id
 * @property integer $storage_location_id
 * @property Collection $Collection
 * @property StorageLocation $StorageLocation
 *
 * @method integer                   getCollectionId()        Returns the current record's "collection_id" value
 * @method integer                   getStorageLocationId()   Returns the current record's "storage_location_id" value
 * @method Collection                getCollection()          Returns the current record's "Collection" value
 * @method StorageLocation           getStorageLocation()     Returns the current record's "StorageLocation" value
 * @method CollectionStorageLocation setCollectionId()        Sets the current record's "collection_id" value
 * @method CollectionStorageLocation setStorageLocationId()   Sets the current record's "storage_location_id" value
 * @method CollectionStorageLocation setCollection()          Sets the current record's "Collection" value
 * @method CollectionStorageLocation setStorageLocation()     Sets the current record's "StorageLocation" value
 *
 * @package    mediaSCORE
 * @subpackage model
 * @author     Nouman Tayyab
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class BaseCollectionStorageLocation extends sfDoctrineRecord
{
    public function setTableDefinition()
    {
        $this->setTableName('collection_storage_location');
        $this->hasColumn('collection_id', 'integer', null, array(
             'type' => 'integer',
             'primary' => true,
             ));
        $this->hasColumn('storage_location_id', 'integer', null, array(
             'type' => 'integer',
             'primary' => true,
             ));
    }

    public function setUp()
    {
        parent::setUp();
        $this->hasOne('Collection', array(
         'local' => 'collection_id',
             'foreign' => 'id',
             'onDelete' => 'CASCADE',
             'onUpdate' => 'CASCADE'));

        $this->hasOne('StorageLocation', array(
             'local' => 'storage_location_id',
             'foreign' => 'id',
             'onDelete' => 'CASCADE',
             'onUpdate' => 'CASCADE'));
    }
}


text: require File.dirname(__FILE__) + '/lib/fixed_point_math'


text:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@id/print_menu_item_search" android:title="@string/print_menu_item_search" android:imeOptions="actionSearch" android:showAsAction="collapseActionView" android:actionViewClass="android.widget.SearchView" />
    <item android:id="@id/print_menu_item_add_printer" android:title="@string/print_menu_item_add_printer" android:showAsAction="never" />
    <item android:id="@id/print_menu_item_settings" android:title="@string/print_menu_item_settings" android:showAsAction="never" />
</menu>


text:
<?php

namespace Hubzero\Auth;

use Hubzero\Container\Container;

/**
 * Authentication manager
 *
 * Login/logout initially based on Joomla
 * JApplication::login/logout methods.
 */
class Manager
{
	/**
	 * The application implementation.
	 *
	 * @var  object
	 */
	protected $app;

	/**
	 * Constructor
	 *
	 * @param   object  $app
	 * @return  void
	 */
	public function __construct(Container $app)
	{
		$this->app = $app;
	}

	/**
	 * Login authentication function.
	 *
	 * Username and encoded password are passed the onUserLogin event which
	 * is responsible for the user validation. A successful validation updates
	 * the current session record with the user's details.
	 *
	 * Username and encoded password are sent as credentials (along with other
	 * possibilities) to each observer (authentication plugin) for user
	 * validation.  Successful validation will update the current session with
	 * the user details.
	 *
	 * @param   array    $credentials  Array('username' => string, 'password' => string)
	 * @param   array    $options      Array('remember' => boolean)
	 * @return  boolean  True on success.
	 */
	public function login($credentials, $options = array())
	{
		$guard = new Guard($this->app);

		$response = $guard->authenticate($credentials, $options);

		if ($response->status === Status::SUCCESS)
		{
			// validate that the user should be able to login (different to being authenticated)
			// this permits authentication plugins blocking the user
			$authorisations = $guard->authorise($response, $options);

			$denied_states = array(
				Status::EXPIRED,
				Status::DENIED
			);

			foreach ($authorisations as $authorisation)
			{
				if (in_array($authorisation->status, $denied_states))
				{
					// Trigger onUserAuthorisationFailure Event.
					$this->app['dispatcher']->trigger('user.onUserAuthorisationFailure', array((array) $authorisation));

					// If silent is set, just return false.
					if (isset($options['silent']) && $options['silent'])
					{
						return false;
					}

					// Return the error.
					switch ($authorisation->status)
					{
						case Status::EXPIRED:
							return new Exception($this->app['language']->txt('JLIB_LOGIN_EXPIRED'), 102002, E_WARNING);
							break;
						case Status::DENIED:
							return new Exception($this->app['language']->txt('JLIB_LOGIN_DENIED'), 102003, E_WARNING);
							break;
						default:
							return new Exception($this->app['language']->txt('JLIB_LOGIN_AUTHORISATION'), 102004, E_WARNING);
							break;
					}
				}
			}

			// OK, the credentials are authenticated and user is authorised.  Lets fire the onLogin event.
			$results = $this->app['dispatcher']->trigger('user.onUserLogin', array((array) $response, $options));

			// If any of the user plugins did not successfully complete the login routine
			// then the whole method fails.
			//
			// Any errors raised should be done in the plugin as this provides the ability
			// to provide much more information about why the routine may have failed.
			if (!in_array(false, $results, true))
			{
				// Set the remember me cookie if enabled.
				if (isset($options['remember']) && $options['remember'])
				{
					// Create the encryption key, apply extra hardening using the user agent string.
					$privateKey = $this->app->hash(@$_SERVER['HTTP_USER_AGENT']);
					$crypt = new \Hubzero\Encryption\Encrypter(
						new \Hubzero\Encryption\Cipher\Simple,
						new \Hubzero\Encryption\Key('simple', $privateKey, $privateKey)
					);
					$rcookie = $crypt->encrypt(json_encode($credentials));
					$lifetime = time() + 365 * 24 * 60 * 60;

					// Use domain and path set in config for cookie if it exists.
					$cookie_domain = $this->app['config']->get('cookie_domain', '');
					$cookie_path   = $this->app['config']->get('cookie_path', '/');

					// Check for SSL connection
					$secure = ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) || getenv('SSL_PROTOCOL_VERSION'));

					setcookie($this->app->hash('JLOGIN_REMEMBER'), $rcookie, $lifetime, $cookie_path, $cookie_domain, $secure, true);
				}

				return true;
			}
		}

		// Trigger onUserLoginFailure Event.
		$this->app['dispatcher']->trigger('user.onUserLoginFailure', array((array) $response));

		// If silent is set, just return false.
		if (isset($options['silent']) && $options['silent'])
		{
			return false;
		}

		// If status is success, any error will have been raised by the user plugin
		if ($response->status !== Status::SUCCESS)
		{
			return new Exception($response->error_message, 102001, E_WARNING);
		}

		return false;
	}

	/**
	 * Logout a user
	 *
	 * @param   integer  $userid
	 * @param   array    $options
	 * @return  boolean
	 */
	public function logout($userid = null, $options = array())
	{
		// Get a user object
		$user = ($userid ? \User::getInstance($userid) : \User::getInstance());

		// Build the credentials array.
		$parameters['username'] = $user->get('username');
		$parameters['id']       = $user->get('id');

		// Set clientid in the options array if it hasn't been set already.
		if (!isset($options['clientid']))
		{
			$options['clientid'] = $this->app['client']->id;
		}

		// OK, the credentials are built. Lets fire the onLogout event.
		$results = $this->app['dispatcher']->trigger('user.onUserLogout', array($parameters, $options));

		// Check if any of the plugins failed. If none did, success.
		if (!in_array(false, $results, true))
		{
			// Use domain and path set in config for cookie if it exists.
			$cookie_domain = $this->app['config']->get('cookie_domain', '');
			$cookie_path   = $this->app['config']->get('cookie_path', '/');

			setcookie($this->app->hash('JLOGIN_REMEMBER'), false, time() - 86400, $cookie_path, $cookie_domain);

			return true;
		}

		// Trigger onUserLoginFailure Event.
		$this->app['dispatcher']->trigger('user.onUserLogoutFailure', array($parameters));

		return false;
	}
}


text:
<?php
namespace mychaelstyle\fops;

use \mychaelstyle\fops\Ops;

class OpsShow implements Ops {
  public function __construct(){
  }
  public function canDo($path){
    return true;
  }
  public function ooops($filePath,Printers $printers){
    echo $filePath."\n";
  }
}


text:
Based on [shower](https://github.com/shower/shower) engine and [ribbon](https://github.com/shower/ribbon) theme.

To see Shower in action:

- Open [shwr.me](http://shwr.me/)
- Click any slide to enter presentation mode
- Use arrow keys to navigate
- Press `Esc` to exit presentation mode

See more details in Shower [readme](https://github.com/shower/shower#readme). Follow [@shower_me](http://twitter.com/shower_me/) for support and updates. Use [Issues](https://github.com/shower/shower/issues) for sharing your ideas, bugs and feature requests.

## Using template

To get Shower template run following command:

``` bash
git clone --recursive git://github.com/shower/template.git
```

Or you can just download [latest version](http://shwr.me/template.zip) as ZIP file.

---
Licensed under [MIT License](http://en.wikipedia.org/wiki/MIT_License), see [license page](https://github.com/shower/shower/wiki/MIT-License) for details.


text:
.include <bsd.own.mk>

LIB=	llvmanalysis

SRCDIR=	lib/Analysis
SRCS=	AliasAnalysis.cpp \
	AliasAnalysisCounter.cpp \
	AliasAnalysisEvaluator.cpp \
	AliasDebugger.cpp \
	AliasSetTracker.cpp \
	Analysis.cpp \
	BasicAliasAnalysis.cpp \
	BranchProbabilityInfo.cpp \
	CFGPrinter.cpp \
	CaptureTracking.cpp \
	CodeMetrics.cpp \
	ConstantFolding.cpp \
	CostModel.cpp \
	DependenceAnalysis.cpp \
	DomPrinter.cpp \
	DominanceFrontier.cpp \
	IVUsers.cpp \
	InstCount.cpp \
	InstructionSimplify.cpp \
	Interval.cpp \
	IntervalPartition.cpp \
	LazyValueInfo.cpp \
	LibCallAliasAnalysis.cpp \
	LibCallSemantics.cpp \
	Lint.cpp \
	Loads.cpp \
	LoopInfo.cpp \
	LoopPass.cpp \
	MemDepPrinter.cpp \
	MemoryBuiltins.cpp \
	MemoryDependenceAnalysis.cpp \
	ModuleDebugInfoPrinter.cpp \
	NoAliasAnalysis.cpp \
	PHITransAddr.cpp \
	PathNumbering.cpp \
	PathProfileInfo.cpp \
	PathProfileVerifier.cpp \
	PostDominators.cpp \
	ProfileDataLoader.cpp \
	ProfileDataLoaderPass.cpp \
	ProfileEstimatorPass.cpp \
	ProfileInfo.cpp \
	ProfileInfoLoader.cpp \
	ProfileInfoLoaderPass.cpp \
	ProfileVerifierPass.cpp \
	PtrUseVisitor.cpp \
	RegionInfo.cpp \
	RegionPass.cpp \
	RegionPrinter.cpp \
	ScalarEvolution.cpp \
	ScalarEvolutionAliasAnalysis.cpp \
	ScalarEvolutionExpander.cpp \
	ScalarEvolutionNormalization.cpp \
	SparsePropagation.cpp \
	TargetTransformInfo.cpp \
	Trace.cpp \
	TypeBasedAliasAnalysis.cpp \
	ValueTracking.cpp

.if ${MK_CLANG_EXTRAS} != "no"
SRCS+=	BlockFrequencyInfo.cpp
.endif

TGHDRS=	Intrinsics

.include "../clang.lib.mk"


text:
@interface ATDeviceInfo : NSObject
@property (nonatomic, readonly) NSDictionary *dictionaryRepresentation;

+ (NSString *)carrier;

- (NSDictionary *)apiJSON;
@end


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid src: host-hostname-in-brackets</title>
<embed src="http://[www.google.com]/">


text:
    <form name="form" ng-submit="ctrl.onSubmit(form.$valid)" class="p-lg"  novalidate>

Send Message!

            <input ng-model="ctrl.twilio.phone_number" type="text" name="phone_number" placeholder="Your Mobile Number" class="form-control">

                {{ errorMessage('phone_number'); }}

            <textarea ng-model="ctrl.twilio.message_body" class="form-control" name="message_body" placeholder="Just say Hi!"></textarea>

                {{ errorMessage('message_body'); }}

        <button ng-click="ctrl.onSubmit(form.$valid)" class="btn btn-store btn-block" title="Send Message"
                ng-disabled="form.$invalid || form.$pristine"
                role="button" type="button">
            Send Message
        </button>
    </form>


text:
package org.apache.poi.hssf.record;

import java.util.Arrays;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.formula.Formula;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.util.LittleEndianOutput;

/**
 * Conditional Formatting Rule Record (0x01B1).
 *
 *
This is for the older-style Excel conditional formattings,
 *  new-style (Excel 2007+) also make use of {@link CFRule12Record}
 *  for their rules.

 */
public final class CFRuleRecord extends CFRuleBase implements Cloneable {
    public static final short sid = 0x01B1;

    /** Creates new CFRuleRecord */
    private CFRuleRecord(byte conditionType, byte comparisonOperation) {
        super(conditionType, comparisonOperation);
        setDefaults();
    }

    private CFRuleRecord(byte conditionType, byte comparisonOperation, Ptg[] formula1, Ptg[] formula2) {
        super(conditionType, comparisonOperation, formula1, formula2);
        setDefaults();
    }
    private void setDefaults() {
        // Set modification flags to 1: by default options are not modified
        formatting_options = modificationBits.setValue(formatting_options, -1);
        // Set formatting block flags to 0 (no formatting blocks)
        formatting_options = fmtBlockBits.setValue(formatting_options, 0);
        formatting_options = undocumented.clear(formatting_options);

        formatting_not_used = (short)0x8002; // Excel seems to write this value, but it doesn't seem to care what it reads
        _fontFormatting = null;
        _borderFormatting = null;
        _patternFormatting = null;
    }

    /**
     * Creates a new comparison operation rule
     *
     * @param sheet the sheet
     * @param formulaText the formula text
     *
     * @return a new comparison operation rule
     */
    public static CFRuleRecord create(HSSFSheet sheet, String formulaText) {
        Ptg[] formula1 = parseFormula(formulaText, sheet);
        return new CFRuleRecord(CONDITION_TYPE_FORMULA, ComparisonOperator.NO_COMPARISON,
                formula1, null);
    }
    /**
     * Creates a new comparison operation rule
     *
     * @param sheet the sheet
     * @param comparisonOperation the comparison operation
     * @param formulaText1 the first formula text
     * @param formulaText2 the second formula text
     *
     * @return a new comparison operation rule
     */
    public static CFRuleRecord create(HSSFSheet sheet, byte comparisonOperation,
            String formulaText1, String formulaText2) {
        Ptg[] formula1 = parseFormula(formulaText1, sheet);
        Ptg[] formula2 = parseFormula(formulaText2, sheet);
        return new CFRuleRecord(CONDITION_TYPE_CELL_VALUE_IS, comparisonOperation, formula1, formula2);
    }

    public CFRuleRecord(RecordInputStream in) {
        setConditionType(in.readByte());
        setComparisonOperation(in.readByte());
        int field_3_formula1_len = in.readUShort();
        int field_4_formula2_len = in.readUShort();
        readFormatOptions(in);

        // "You may not use unions, intersections or array constants in Conditional Formatting criteria"
        setFormula1(Formula.read(field_3_formula1_len, in));
        setFormula2(Formula.read(field_4_formula2_len, in));
    }

    @Override
    public short getSid() {
        return sid;
    }

    /**
     * called by the class that is responsible for writing this sucker.
     * Subclasses should implement this so that their data is passed back in a
     * byte array.
     *
     * @param out the stream to write to
     */
    @Override
    public void serialize(LittleEndianOutput out) {
        int formula1Len=getFormulaSize(getFormula1());
        int formula2Len=getFormulaSize(getFormula2());

        out.writeByte(getConditionType());
        out.writeByte(getComparisonOperation());
        out.writeShort(formula1Len);
        out.writeShort(formula2Len);

        serializeFormattingBlock(out);

        getFormula1().serializeTokens(out);
        getFormula2().serializeTokens(out);
    }

    @Override
    protected int getDataSize() {
        return 6 + getFormattingBlockSize() +
               getFormulaSize(getFormula1())+
               getFormulaSize(getFormula2());
    }

    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[CFRULE]\n");
        buffer.append("    .condition_type   =").append(getConditionType()).append("\n");
        buffer.append("    OPTION FLAGS=0x").append(Integer.toHexString(getOptions())).append("\n");
        if (containsFontFormattingBlock()) {
            buffer.append(_fontFormatting.toString()).append("\n");
        }
        if (containsBorderFormattingBlock()) {
            buffer.append(_borderFormatting.toString()).append("\n");
        }
        if (containsPatternFormattingBlock()) {
            buffer.append(_patternFormatting.toString()).append("\n");
        }
        buffer.append("    Formula 1 =").append(Arrays.toString(getFormula1().getTokens())).append("\n");
        buffer.append("    Formula 2 =").append(Arrays.toString(getFormula2().getTokens())).append("\n");
        buffer.append("[/CFRULE]\n");
        return buffer.toString();
    }

    @Override
    public CFRuleRecord clone() {
        CFRuleRecord rec = new CFRuleRecord(getConditionType(), getComparisonOperation());
        super.copyTo(rec);
        return rec;
    }
}


text:
<?php
namespace SD\Currency\DependencyInjection;

use SD\Currency\Repository;

trait CurrencyAwareTrait {
    protected $autoDeclareCurrency = 'currency';
    private $currency;

    public function setCurrency(Repository $currency) {
        $this->currency = $currency;
    }

    protected function getCurrency(): Repository {
        return $this->currency;
    }
}


text:
@implementation NSObject (JSON)

static const NSString *S_VALUE_TYPES = @"cislqCISLQfdB";

+ (id)objectWithJSONString:(NSString *)jsonString {
    id jsonObj = [[CommonHelper sharedSingleton] deserializeStringToObject:jsonString];
    id obj = [self objectWithJSONObject:jsonObj];
    return obj;
}

- (void)fillInJSONObject:(NSDictionary *)jsonObj {
    Class class = [self class];
    NSArray *allKeys = [jsonObj allKeys];

    for (NSString *key in allKeys) {
        objc_property_t property = class_getProperty(class, [key UTF8String]);
        if (property != nil) {
            NSString *typeName = [self getTypeNameByAttribute:property];

            id value = [jsonObj objectForKey:key];
            id newValue = nil;

            if ([typeName hasPrefix:TYPE_PREFIX]) {

                Class class = [self createObjectByTypeName:typeName];

                if ([class isSubclassOfClass:[NSDecimalNumber class]]) {
                    if ([value isKindOfClass:[NSDecimalNumber class]]) {
                        newValue = value;
                    } else if ([value isKindOfClass:[NSNumber class]]) {
                        newValue = [NSDecimalNumber decimalNumberWithDecimal:[value decimalValue]];
                    }
                } else if ([class isSubclassOfClass:[NSNumber class]]) {
                    if ([value isKindOfClass:[NSNumber class]]) {
                        newValue = value;
                    }
                } else if ([class isSubclassOfClass:[NSString class]]) {
                    if ([value isKindOfClass:[NSString class]]) {
                        newValue = value;
                    }
                } else if ([class isSubclassOfClass:[NSDictionary class]]) {
                    if ([value isKindOfClass:[NSDictionary class]]) {
                        newValue = value;
                    }
                } else if ([class isSubclassOfClass:[NSArray class]]) {
                    newValue = [self valueForKey:key];
                    if ([value isKindOfClass:[NSArray class]] && [newValue isKindOfClass:[ObjectArray class]]) {
                        [(ObjectArray *)newValue fillInJSONObject:value];
                    }
                } else {
                    if ([value isKindOfClass:[NSDictionary class]]) {
                        newValue = [[class alloc] init];
                        [newValue fillInJSONObject:value];
                    }
                }
            } else if ([S_VALUE_TYPES rangeOfString:typeName].location != NSNotFound) {
                newValue = value;
            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
                newValue = value;
            }
            [self setValue:newValue forKey:key];
        }
    }
}

- (NSString *)toJSONString {
    NSDictionary *jsonObjDic = [self toJSONObject];
    NSString     *jsonString = [[CommonHelper sharedSingleton] serializeObjectToString:jsonObjDic];

    return jsonString;
}
- (NSDictionary *)toJSONObject {
    NSMutableDictionary *jsonDictionary = [NSMutableDictionary dictionary];

    Class class = [self class];
    NSUInteger  counter;

    //To root classes.
    while (class != [NSObject class]) {
        objc_property_t *properties = class_copyPropertyList(class, &counter);

        //Copy properties.
        for (NSUInteger i = 0; i < counter; i++) {
            NSString *key = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding];
            id value = [self valueForKey:key];
            id newValue = nil;

            if ([value isKindOfClass:[NSString class]]) {
                newValue = value;
            } else if ([value isKindOfClass:[NSNumber class]]) {
                newValue = value;
            } else if ([value isKindOfClass:[NSNull class]]) {
                newValue = value;
            } else if ([value isKindOfClass:[NSArray class]]) {
                newValue = [(NSArray *)value toJSONObject];
            } else {
                newValue = [value toJSONObject];
            }
            if (newValue == nil) {
                newValue = [NSNull null];
            }

            [jsonDictionary setObject:newValue forKey:key];
        }
        class = class_getSuperclass(class);
    }
    return jsonDictionary;
}

#pragma mark - Private methods

+ (id)objectWithJSONObject:(id)jsonObj {
    id objsArray = nil;
    Class type = [self class];

    if ([jsonObj isKindOfClass:[NSArray class]]) {
        ObjectArray *array = [ObjectArray arrayWithObjectType:type];
        [array fillInJSONObject:jsonObj];
        objsArray = array;
    } else if([jsonObj isKindOfClass:[NSDictionary class]]) {
        NSObject *objItem = [[type alloc] init];
        [objItem fillInJSONObject:jsonObj];
        objsArray = objItem;
    }
    return objsArray;
}

- (NSString *)getTypeNameByAttribute:(objc_property_t) property {
    NSString *attribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding];
    NSRange range = NSMakeRange(1, [attribute rangeOfString:@","].location - 1);
    NSString *attrType = [attribute substringWithRange:range];
    return attrType;
}

- (Class)createObjectByTypeName:(NSString *)name {
    name = [name substringWithRange:NSMakeRange(2, [name length] - 3)];
    Class class = NSClassFromString(name);
    return class;
}

@end


text:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MonoGame.Extended.BitmapFonts;
using MonoGame.Extended.Shapes;
using MonoGame.Extended.TextureAtlases;

namespace MonoGame.Extended.Gui
{
    public interface IGuiRenderer
    {
        void Begin();
        void DrawRegion(TextureRegion2D textureRegion, Rectangle rectangle, Color color, Rectangle? clippingRectangle = null);
        void DrawRegion(TextureRegion2D textureRegion, Vector2 position, Color color, Rectangle? clippingRectangle = null);
        void DrawText(BitmapFont font, string text, Vector2 position, Color color, Rectangle? clippingRectangle = null);
        void DrawRectangle(Rectangle rectangle, Color color, float thickness = 1f);
        void End();
    }

    public class GuiSpriteBatchRenderer : IGuiRenderer
    {
        private readonly Func<Matrix> _getTransformMatrix;
        private readonly SpriteBatch _spriteBatch;

        public GuiSpriteBatchRenderer(GraphicsDevice graphicsDevice, BitmapFont defaultFont, Func<Matrix> getTransformMatrix)
        {
            _getTransformMatrix = getTransformMatrix;
            _spriteBatch = new SpriteBatch(graphicsDevice);
        }

        public SpriteSortMode SortMode { get; set; }
        public BlendState BlendState { get; set; } = BlendState.AlphaBlend;
        public SamplerState SamplerState { get; set; } = SamplerState.PointClamp;
        public DepthStencilState DepthStencilState { get; set; } = DepthStencilState.Default;
        public RasterizerState RasterizerState { get; set; } = RasterizerState.CullNone;
        public Effect Effect { get; set; }

        public void Begin()
        {
            _spriteBatch.Begin(SortMode, BlendState, SamplerState, DepthStencilState, RasterizerState, Effect, _getTransformMatrix());
        }

        public void End()
        {
            _spriteBatch.End();
        }

        public void DrawRegion(TextureRegion2D textureRegion, Rectangle rectangle, Color color, Rectangle? clippingRectangle = null)
        {
            if(textureRegion != null)
                _spriteBatch.Draw(textureRegion, rectangle, color, clippingRectangle);
        }

        public void DrawRegion(TextureRegion2D textureRegion, Vector2 position, Color color, Rectangle? clippingRectangle = null)
        {
            if (textureRegion != null)
                _spriteBatch.Draw(textureRegion, position, color, clippingRectangle);
        }

        public void DrawText(BitmapFont font, string text, Vector2 position, Color color, Rectangle? clippingRectangle = null)
        {
            _spriteBatch.DrawString(font, text, position, color, clippingRectangle);
        }

        public void DrawRectangle(Rectangle rectangle, Color color, float thickness = 1f)
        {
            _spriteBatch.DrawRectangle(rectangle, color, thickness);
        }
    }
}


text:
#include "ignite/impl/binary/binary_type_handler.h"

using namespace ignite::common::concurrent;

namespace ignite
{
    namespace impl
    {
        namespace binary
        {
            BinaryTypeHandler::BinaryTypeHandler(SPSnap snap) :
                origin(snap),
                updated()
            {
                // No-op.
            }

            void BinaryTypeHandler::OnFieldWritten(int32_t fieldId, std::string fieldName, int32_t fieldTypeId)
            {
                if (!origin.Get() || !origin.Get()->ContainsFieldId(fieldId))
                {
                    if (!updated.Get())
                        updated = SPSnap(new Snap(*origin.Get()));

                    updated.Get()->AddField(fieldId, fieldName, fieldTypeId);
                }
            }
        }
    }
}


text:
using namespace std;

class FlatMesh : public Model{
protected:
     vector< vector<shared_ptr<V3D>> > vertex;
     void paint(bool fill)const;
};

#endif // FLATMESH_H


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.apache</groupId>
  <artifactId>maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>maven</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
<build>
  <plugins>
  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.5.5.201112152213</version>
    <configuration>
    <destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
    <dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
    </configuration>
    <executions>
    <execution>
      <id>jacoco-initialize</id>
      <goals>
      <goal>prepare-agent</goal>
      </goals>
    </execution>
    <execution>
      <id>jacoco-site</id>
      <phase>package</phase>
      <goals>
      <goal>report</goal>
      </goals>
    </execution>
    </executions>
  </plugin>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
    <source>1.5</source>
    <target>1.5</target>
    </configuration>
  </plugin>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>cobertura-maven-plugin</artifactId>
    <version>2.7</version>
    <configuration>
        <format>xml</format>
        <maxmem>256m</maxmem>
        <!-- aggregated reports for multi-module projects -->
        <aggregate>true</aggregate>
    </configuration>
</plugin>
  </plugins>
</build>

</project>


text:
$(document).ready(function(){

var bgColor;
var effect = 'animated bounceInLeft'; /* bounceIn, bounceInUp, bounceInDown, bounceInLeft,
										 bounceInRight, rotateIn, rotateInUpLeft, rotateInDownLeft,
										 rotateInUpRight, rotateInDownRight  */

$('.all-content').hide();

/**
*
* Click list
*
**/
$('.a_content li').click(function(){

	/* Hide Card Front & Card Back from all lists */
	$('.card-front, .card-back').hide();

	/* Remove Class active, Hide and Adding border: none to the lists */
	$('.a_content li').removeClass('active').hide().css('border','none');
	$(this).addClass('active').show();

	/* Get Background Color */
	bgColor = $('.active .card-back').css('background-color');
	$('.content').css('background-color',bgColor);

	/* Show Close Element & Content of list */
	$('.close, .all-content').show();

	/* Append close element and Add CSS effect "bounceInLeft"*/
	$('.responsive').append('close').addClass(effect);

});

/**
*
* Close element
*
**/
$('.responsive').on('click', '.close', function(){

	/* Remove close button */
	$('.close').remove();

	/* Get Background Color */
	bgColor = $('.active .card-front').css('background-color');

	/* Remove animation effect from ul.content */
	$('.responsive').removeClass(effect);

	/* Hide Close Element & Content of list */
	$('.all-content').hide();

	/*  Remove "active" class from all lists and adding "bounceInLeft" */
	$('.a_content li').removeClass('active').show().css({ 'border-bottom':'1px solid #2c2c2c',
													    'border-left':'1px solid #2c2c2c' });

	$('.card-front, .card-back').show();
	$('.content').css('background-color',bgColor);

});

});


text:
template "#{node['apache']['windows']['extras_dir']}/httpd-ssl.conf" do
  source "httpd-ssl.conf.erb"
  action :create
  notifies :restart, "service[apache2]"
end


text:
/**
 * @fileoverview Date layer
 * @author NHN. FE Development Lab <dl_javascript@nhn.com>
 */

'use strict';

var defineClass = require('tui-code-snippet/defineClass/defineClass');

var dateUtil = require('../../dateUtil');
var bodyTmpl = require('./../../../template/calendar/dateLayer');
var LayerBase = require('./base');
var TYPE_DATE = require('../../constants').TYPE_DATE;
var WEEK_START_DAY_MAP = require('../../constants').WEEK_START_DAY_MAP;

var DATE_SELECTOR = '.tui-calendar-date';
var DAYS_OF_WEEK = 7;

/**
 * @ignore
 * @class
 * @extends LayerBase
 * @param {string} language - Initial language
 */
var DateLayer = defineClass(
  LayerBase,
  /** @lends DateLayer.prototype */ {
    init: function(language, weekStartDay) {
      LayerBase.call(this, language);

      this.weekStartDay = WEEK_START_DAY_MAP[String(weekStartDay).toLowerCase()] || 0;
    },

    /**
     * Layer type
     * @type {string}
     * @private
     */
    _type: TYPE_DATE,

    /**
     * @override
     * @private
     * @returns {object} Template context
     */
    _makeContext: function(date) {
      var daysShort = this._localeText.titles.D;
      var year, month, days, i;

      date = date || new Date();
      year = date.getFullYear();
      month = date.getMonth() + 1;

      if (this.weekStartDay) {
        days = daysShort.slice();
        for (i = 0; i < this.weekStartDay; i += 1) {
          days.push(days.shift());
        }
        daysShort = days;
      }

      return {
        Sun: daysShort[0],
        Mon: daysShort[1],
        Tue: daysShort[2],
        Wed: daysShort[3],
        Thu: daysShort[4],
        Fri: daysShort[5],
        Sat: daysShort[6],
        year: year,
        month: month,
        weeks: this._getWeeks(year, month)
      };
    },

    /**
     * weeks (templating) for date-calendar
     * @param {number} year - Year
     * @param {number} month - Month
     * @returns {Array.<Array.<Date>>}
     * @private
     */
    _getWeeks: function(year, month) {
      var weekNumber = 0;
      var weeksCount = 6; // Fix for no changing height
      var weeks = [];
      var week, dates, i;

      while (weekNumber < weeksCount) {
        dates = [];

        for (i = this.weekStartDay; i < DAYS_OF_WEEK + this.weekStartDay; i += 1) {
          dates.push(dateUtil.getDateOfWeek(year, month, weekNumber, i));
        }

        week = this._getWeek(year, month, dates);

        if (this.weekStartDay && !_isFirstWeek(weekNumber, week[0].dayInMonth)) {
          weeks.push(this._getFirstWeek(year, month));
          weeksCount -= 1; // Fix for no changing height
        }

        weeks.push(week);
        weekNumber += 1;
      }

      return weeks;
    },

    /**
     * week (templating) for date-calendar
     * @param {number} currentYear
     * @param {number} currentMonth
     * @param {Array.<Date>} dates
     * @private
     */
    _getWeek: function(currentYear, currentMonth, dates) {
      var firstDateOfCurrentMonth = new Date(currentYear, currentMonth - 1, 1);
      var lastDateOfCurrentMonth = new Date(currentYear, currentMonth, 0);
      var contexts = [];
      var i = 0;
      var length = dates.length;
      var date, className;

      for (; i < length; i += 1) {
        className = 'tui-calendar-date';
        date = dates[i];

        if (date < firstDateOfCurrentMonth) {
          className += ' tui-calendar-prev-month';
        }

        if (date > lastDateOfCurrentMonth) {
          className += ' tui-calendar-next-month';
        }

        if (date.getDay() === 0) {
          className += ' tui-calendar-sun';
        } else if (date.getDay() === 6) {
          className += ' tui-calendar-sat';
        }

        contexts.push({
          dayInMonth: date.getDate(),
          className: className,
          timestamp: date.getTime()
        });
      }

      return contexts;
    },

    /**
     * Render date-layer
     * @override
     * @param {Date} date Date to render
     * @param {HTMLElement} container A container element for the rendered element
     */
    render: function(date, container) {
      var context = this._makeContext(date);

      container.innerHTML = bodyTmpl(context);
      this._element = container.firstChild;
    },

    /**
     * Return date elements
     * @override
     * @returns {HTMLElement[]}
     */
    getDateElements: function() {
      return this._element.querySelectorAll(DATE_SELECTOR);
    },

    _getFirstWeek: function(year, month) {
      var firstWeekDates = [];
      var i;

      for (i = this.weekStartDay; i < DAYS_OF_WEEK + this.weekStartDay; i += 1) {
        firstWeekDates.push(dateUtil.getDateOfWeek(year, month, -1, i));
      }

      return this._getWeek(year, month, firstWeekDates);
    }
  }
);

function _isFirstWeek(weekIndex, dayInMonth) {
  return weekIndex || dayInMonth === 1 || dayInMonth > DAYS_OF_WEEK;
}

module.exports = DateLayer;


text:
using namespace std;
using namespace rail::interactive_world;

ObjectOnSurfaceModel::ObjectOnSurfaceModel(const string &object, const string &surface)
    : object_(object), surface_(surface)
{
  dirty_ = false;
  last_seen_ = 0;
  mu_ = 0;
}

const string &ObjectOnSurfaceModel::getObject() const
{
  return object_;
}

void ObjectOnSurfaceModel::setObject(const std::string &object)
{
  object_ = object;
}

const string &ObjectOnSurfaceModel::getSurface() const
{
  return surface_;
}

void ObjectOnSurfaceModel::setSurface(const std::string &surface)
{
  surface_ = surface;
}

time_t ObjectOnSurfaceModel::getLastSeen() const
{
  return last_seen_;
}

void ObjectOnSurfaceModel::addObservation(const time_t seen, const time_t removed)
{
  if (seen > last_seen_)
  {
    last_seen_ = seen;
  }
  struct observation cur;
  cur.seen = seen;
  cur.removed = removed;
  observations_.push_back(cur);
  dirty_ = true;
}

double ObjectOnSurfaceModel::getMu()
{
  if (dirty_)
  {
    // average
    mu_ = 0;
    ros::Time now = ros::Time::now();
    for (size_t i = 0; i < observations_.size(); i++)
    {
      // check if the observation is still current
      double duration;
      if (observations_[i].removed == 0)
      {
        duration = now.toSec() - observations_[i].seen;
      } else
      {
        duration = observations_[i].removed - observations_[i].seen;
      }
      // put into minutes
      duration /= 60.0;
      mu_ += duration;
    }
    mu_ /= (double) observations_.size();
    dirty_ = false;
  }

  return mu_;
}

double ObjectOnSurfaceModel::getLambda()
{
  return 1.0 / this->getMu();
}

double ObjectOnSurfaceModel::getCurrentProbability()
{
  ros::Time now = ros::Time::now();
  // x in minutes
  double x = (now.toSec() - this->getLastSeen()) / 60.0;
  double lambda = this->getLambda();
  return exp(-lambda * x);
}


text:
package monitor_test

import (
	"github.com/bbva-innotech/go-monitor"
	"time"
)

func Example() {
	monValueA := monitor.NewField("Value_A", false)
	monValueA.Set(1111)

	monitor.NewField("Value_B", true)

	monValueC := monitor.NewField("Value_C", true)
	monValueC.Add(2222)

	monitor.Start()
	time.Sleep(time.Millisecond * 2100)
	monitor.Stop()

	// // Output:
	// // Value_A  Value_B
	// //    1111     2222
	// //    1111        0
}


text:
Selenium GenericMasterFunctions::<BIG>GetGUIImage</BIG>

TID
SE
SE2

<short_desc xmlns="">
               Capture the screen shot of a GUI component and save it to a file
              </short_desc>

<detailed_desc xmlns="">
               Capture the screen shot of a GUI component and save it to a file.
               The available formats for the output file are BITMAP (*.bmp) and JPEG
               (*.jpg).
               For RJ and IBT engine, other formats like TIFF (*.tif), GIF (*.gif),
               PNG (*.png) and PNM (*.pnm) are also supported.
               Optionally the user can specify part of the component to capture.

               The specified GUI component/part must be in the viewing range of its
               containing window. If portion of the component is displayed in the
               window, only that portion will be captured; if the component falls
               completely out of the viewing range of the window, the command will
               fail. The command makes no attempt to bring the component into view.

Robot Classic (RC) Specific Notes:

               		1) This command may fail to execute if the user has turned off logging
              	 	to TestManager via the Robot tools setting.  You may have to enable
               		TestManager logging for the command to successfully execute.

               		2) This command requires that the TestManager Image Comparator tool is
               		installed on the test machine. Machines having only the Robot Test Agent
               		installed will not be able to use this command.

               		3) Due to a bug in Robot Classic, images captured using the Robot Classic
			engine may differ in image size and/or file size from those captured using
			other supported engines.  Depending on the comparator used, rebenching
               		your images may be necessary when migrating to another engine.

RobotJ (RJ) and IBT Specific Notes:

               		1)It requires that Java Advanced Imaging (JAI) be installed
               		on the test machine

               		2)It supports to save image in format TIFF (*.tif), GIF (*.gif), PNG (*.png)
               		and PNM (*.pnm)

Apple IOS specific Notes:

               UIAutomation captures all screenshots as PNG images, but SAFS copies and stores them
               into the image format desired (JPG, BMP, etc.). However, the rootname of the desired
               output image name must be unique to avoid UIAutomation generating indexed image names
               we will not be looking for.

               For example, specifying MyImage.JPG and later MyImage.BMP will cause UIAutomation to capture
               MyImage.PNG and MyImage1.PNG. When attempting to find MyImage.PNG captured for MyImage.BMP
               we will retrieve MyImage.PNG which is NOT the correct image capture for MyImage.BMP.

</detailed_desc>

Fields: [ ]=Optional with Default Value

OutputFile

<short_desc xmlns="">
             Path (with filename) to the output image file.
              </short_desc>

<detailed_desc xmlns="">
              Path/file name of the output image file.
              This can be a full path, a relative path or just a file name. If
              relative, it is appended to the Datapool directory; if only a
              file name without path, the file will be saved in Datapool\Test
              directory. The extension of the file must be either .bmp or
              .jpg. If not, .bmp is appended to this parameter to force a
              BITMAP export.
              </detailed_desc>

[ SubArea =  ]

<short_desc xmlns="">
             Optional app map subkey indicating partial image of the component to capture.
              </short_desc>

<detailed_desc xmlns="">
              Optional app map subkey indicating partial image of the component to capture.
              Value of this app map reference must be in the format of a
              top-left and bottom-right pair, and can be either absolute
              coordinates or percentages ("x1,y1,x2,y2" or "x1%,y1%,x2%,y2%").
              Coordinates are relative to the component, i.e. (0,0) and
              (0%,0%) are the minimum, and (COMPONENT_WIDTH, COMPONENT_HEIGHT)
              and (100%,100%) are the maximum. Values exceeding the minimun/
              maximum are forced to the nearest limiting value. Absolute and
              percent values can be mixed, so "0,0,50%,50%" is valid. If this
              parameter is omitted, full image of the component is captured
              (equivalent to "0,0,100%,100%").
              </detailed_desc>

[ FilteredAreas =  ]

<short_desc xmlns="">
              "Filter=one or multiple areas" to filter the GUI image (or sub image of GUI if the parameter "SubArea" is present)
             </short_desc>

<detailed_desc xmlns="">
              "Filter=one or multiple areas" to filter the GUI image (or sub image of GUI if the parameter "SubArea" is present)

              The area is in the same format described for the parameter "SubArea".

              Multiple areas are separated by a space character, such as "subarea1 subarea2 subarea3"

              The filtered-image will be covered by black color at filtered areas.

              Do NOT forget the prefix "Filter=", without it this parameter will be ignored.
             </detailed_desc>

Examples:

<usage xmlns="">T, WINDOW, COMPONENT, GetGUIImage, "C:\comp.bmp"</usage>

<short_desc xmlns="">
             Save the full component image to BITMAP file "C:\comp.bmp".
              </short_desc>

<usage xmlns="">T, WINDOW, COMPONENT, GetGUIImage, "Datapool\comp.jpg"</usage>

<short_desc xmlns="">
             Save the full component image to JPEG file "<project>\Datapool\comp.jpg".
              </short_desc>

<usage xmlns="">T, WINDOW, COMPONENT, GetGUIImage, "Datapool\Logs\comp.bmp", SUBAREA</usage>

<short_desc xmlns="">
             Save specified part of the component image.
              </short_desc>

<detailed_desc xmlns="">
              Save specified part of the component image.
              Depending on the definition of SUBAREA in the app map, the command captures:

              UNDER [COMPONENT] IN APP MAP    PART OF COMPONENT

              ----------------------------    ---------------------

              SUBAREA="0,0,10,10"             top-left 10x10 square

              SUBAREA="0,80%,100%,100%"       bottom fifth
</detailed_desc>

<usage xmlns="">T, WINDOW, COMPONENT, GetGUIImage, "Datapool\comp.jpg", "", "Filter=0;0;10;10"</usage>

<short_desc xmlns="">
             Get the component image and filter some parts and save it.
              </short_desc>

<detailed_desc xmlns="">
             Get the full component image and draw a "10*10 black quare" at the top-left,
             then save it to JPEG file "<project>\Datapool\comp.jpg".
              </detailed_desc>

<usage xmlns="">T, WINDOW, COMPONENT, GetGUIImage, "comp.jpg", "", "FilterMapKey"</usage>

<short_desc xmlns="">
             Get the component image and filter some parts and save it.
              </short_desc>

<detailed_desc xmlns="">
             Get the full component image, and draw "10x10 black square" at "top-left" and "10x15 black rectangle" at "60,60"
             to make a filtered image, and save the filtered image.

              ----------------------------        Map           ---------------------

              [COMPONENT]

              FilterMapKey="Filter=0,0,10,10 60,60,10,15"
</detailed_desc>

[How To Read This Reference]