text:
.class Landroid/bluetooth/BluetoothPbap$2;
.super Ljava/lang/Object;
.source "BluetoothPbap.java"

# interfaces
.implements Landroid/content/ServiceConnection;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/bluetooth/BluetoothPbap;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/bluetooth/BluetoothPbap;

# direct methods
.method constructor <init>(Landroid/bluetooth/BluetoothPbap;)V
    .locals 0
    .parameter

    .prologue
    .line 298
    iput-object p1, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V
    .locals 2
    .parameter "className"
    .parameter "service"

    .prologue
    .line 300
    const-string v0, "Proxy object connected"

    #calls: Landroid/bluetooth/BluetoothPbap;->log(Ljava/lang/String;)V
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$300(Ljava/lang/String;)V

    .line 301
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    invoke-static {p2}, Landroid/bluetooth/IBluetoothPbap$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothPbap;

    move-result-object v1

    #setter for: Landroid/bluetooth/BluetoothPbap;->mService:Landroid/bluetooth/IBluetoothPbap;
    invoke-static {v0, v1}, Landroid/bluetooth/BluetoothPbap;->access$102(Landroid/bluetooth/BluetoothPbap;Landroid/bluetooth/IBluetoothPbap;)Landroid/bluetooth/IBluetoothPbap;

    .line 302
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    #getter for: Landroid/bluetooth/BluetoothPbap;->mServiceListener:Landroid/bluetooth/BluetoothPbap$ServiceListener;
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$400(Landroid/bluetooth/BluetoothPbap;)Landroid/bluetooth/BluetoothPbap$ServiceListener;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 303
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    #getter for: Landroid/bluetooth/BluetoothPbap;->mServiceListener:Landroid/bluetooth/BluetoothPbap$ServiceListener;
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$400(Landroid/bluetooth/BluetoothPbap;)Landroid/bluetooth/BluetoothPbap$ServiceListener;

    move-result-object v0

    iget-object v1, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    invoke-interface {v0, v1}, Landroid/bluetooth/BluetoothPbap$ServiceListener;->onServiceConnected(Landroid/bluetooth/BluetoothPbap;)V

    .line 305
    :cond_0
    return-void
.end method

.method public onServiceDisconnected(Landroid/content/ComponentName;)V
    .locals 2
    .parameter "className"

    .prologue
    .line 307
    const-string v0, "Proxy object disconnected"

    #calls: Landroid/bluetooth/BluetoothPbap;->log(Ljava/lang/String;)V
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$300(Ljava/lang/String;)V

    .line 308
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    const/4 v1, 0x0

    #setter for: Landroid/bluetooth/BluetoothPbap;->mService:Landroid/bluetooth/IBluetoothPbap;
    invoke-static {v0, v1}, Landroid/bluetooth/BluetoothPbap;->access$102(Landroid/bluetooth/BluetoothPbap;Landroid/bluetooth/IBluetoothPbap;)Landroid/bluetooth/IBluetoothPbap;

    .line 309
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    #getter for: Landroid/bluetooth/BluetoothPbap;->mServiceListener:Landroid/bluetooth/BluetoothPbap$ServiceListener;
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$400(Landroid/bluetooth/BluetoothPbap;)Landroid/bluetooth/BluetoothPbap$ServiceListener;

    move-result-object v0

    if-eqz v0, :cond_0

    .line 310
    iget-object v0, p0, Landroid/bluetooth/BluetoothPbap$2;->this$0:Landroid/bluetooth/BluetoothPbap;

    #getter for: Landroid/bluetooth/BluetoothPbap;->mServiceListener:Landroid/bluetooth/BluetoothPbap$ServiceListener;
    invoke-static {v0}, Landroid/bluetooth/BluetoothPbap;->access$400(Landroid/bluetooth/BluetoothPbap;)Landroid/bluetooth/BluetoothPbap$ServiceListener;

    move-result-object v0

    invoke-interface {v0}, Landroid/bluetooth/BluetoothPbap$ServiceListener;->onServiceDisconnected()V

    .line 312
    :cond_0
    return-void
.end method


text:
#include "CodeUnit.h"

#include "Config.h"
#include "visitors/DeclarationVisitor.h"
#include "visitors/ExpressionVisitor.h"
#include "visitors/CppPrintContext.h"
#include "SpecialCases.h"
#include "ExportHelpers.h"

#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/MetaDefinition.h"
#include "OOModel/src/expressions/MetaCallExpression.h"
#include "OOModel/src/declarations/TypeAlias.h"
#include "OOModel/src/declarations/NameImport.h"
#include "OOModel/src/declarations/ExplicitTemplateInstantiation.h"

namespace CppExport {

CodeUnit::CodeUnit(QString name, Model::Node* node) : name_{name}, node_{node}
{
	Q_ASSERT(!name.isEmpty());
}

void CodeUnit::calculateSourceFragments()
{
	OOModel::Declaration* printContextDeclaration = ExportHelpers::firstValidAncestorPrintContext(node());

	if (auto classs = DCast<OOModel::Class>(node()))
	{
		if (SpecialCases::isTestClass(classs))
		{
			CppPrintContext headerPartPrintContext{classs, CppPrintContext::IsHeaderPart |
																			CppPrintContext::PrintMethodBodyInline |
																			(isTemplateImplementationSeparateFile() ?
																				CppPrintContext::IsTemplateImplementationSeparateFile :
																				CppPrintContext::None)};
			sourcePart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visitTopLevelClass(classs));
		}
		else
		{
			CppPrintContext headerPartPrintContext{classs, CppPrintContext::IsHeaderPart |
																			(isTemplateImplementationSeparateFile() ?
																				CppPrintContext::IsTemplateImplementationSeparateFile :
																				CppPrintContext::None)};
			headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visitTopLevelClass(classs));

			CppPrintContext sourcePartPrintContext{printContextDeclaration, CppPrintContext::PrintMethodBody |
																				(isTemplateImplementationSeparateFile() ?
																					CppPrintContext::IsTemplateImplementationSeparateFile :
																					CppPrintContext::None)};
			sourcePart()->setFragment(DeclarationVisitor{sourcePartPrintContext}.visitTopLevelClass(classs));
		}
	}
	else if (auto module = DCast<OOModel::Module>(node()))
	{
		CppPrintContext headerPartPrintContext{module, CppPrintContext::IsHeaderPart};
		auto fragment = new Export::CompositeFragment{node()};
		for (auto metaDefinition : Model::Node::childrenOfType<OOModel::MetaDefinition>(module))
			*fragment << DeclarationVisitor{headerPartPrintContext}.visit(metaDefinition);
		headerPart()->setFragment(fragment);
	}
	else if (auto method = DCast<OOModel::Method>(node()))
	{
		if (method->typeArguments()->isEmpty() && !method->modifiers()->isSet(OOModel::Modifier::Inline))
		{
			if (!printInCppOnly(method))
			{
				CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart};
				headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(method));
			}

			if (!method->modifiers()->isSet(OOModel::Modifier::Abstract) &&
				 !method->modifiers()->isSet(OOModel::Modifier::Deleted))
			{
				CppPrintContext::Options printContextOptions = CppPrintContext::PrintMethodBody;
				if (printInCppOnly(method)) printContextOptions |= CppPrintContext::PrintDeclarationCommentWithMethodBody;

				CppPrintContext printContext{printContextDeclaration, printContextOptions};
				sourcePart()->setFragment(DeclarationVisitor{printContext}.visit(method));
			}
		}
		else
		{
			CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart |
																									CppPrintContext::PrintMethodBody};
			headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(method));
		}
	}
	else if (auto variableDeclaration = DCast<OOModel::VariableDeclaration>(node()))
	{
		if (printInCppOnly(variableDeclaration))
			sourcePart()->setFragment(DeclarationVisitor{variableDeclaration}.visit(variableDeclaration));
		else
		{
			CppPrintContext headerPartPrintContext{variableDeclaration, CppPrintContext::IsHeaderPart};
			headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(variableDeclaration));
			sourcePart()->setFragment(DeclarationVisitor{printContextDeclaration}.visit(variableDeclaration));
		}
	}
	else if (auto typeAlias = DCast<OOModel::TypeAlias>(node()))
	{
		CppPrintContext headerPartPrintContext{typeAlias, CppPrintContext::IsHeaderPart};
		headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(typeAlias));
	}
	else if (auto metaCall = DCast<OOModel::MetaCallExpression>(node()))
	{
		auto ooReference = DCast<OOModel::ReferenceExpression>(metaCall->callee());
		if (ooReference->name().startsWith("BEGIN_"))
			headerPart()->setFragment(SpecialCases::printXMacroDataBlock(metaCall));
		else if (ooReference->name().startsWith("DEFINE_"))
			sourcePart()->setFragment(ExpressionVisitor{printContextDeclaration}.visit(metaCall));
		else
		{
			CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart};
			headerPart()->setFragment(ExpressionVisitor{headerPartPrintContext}.visit(metaCall));
		}
	}
	else if (auto metaDefinition = DCast<OOModel::MetaDefinition>(node()))
	{
		if (metaDefinition->name().startsWith("BEGIN_") && metaDefinition->metaBindings()->isEmpty())
		{
			headerPart()->setFragment(SpecialCases::printPartialBeginMacroSpecialization(metaDefinition, true));
			sourcePart()->setFragment(SpecialCases::printPartialBeginMacroSpecialization(metaDefinition, false));
		}
		else if (metaDefinition->name().startsWith("BEGIN_") && !metaDefinition->metaBindings()->isEmpty())
		{
			headerPart()->setFragment(SpecialCases::printPartialBeginMacroBase(metaDefinition, true));
			sourcePart()->setFragment(SpecialCases::printPartialBeginMacroBase(metaDefinition, false));
		}
		else if (metaDefinition->name().endsWith("_CPP"))
			sourcePart()->setFragment(DeclarationVisitor{printContextDeclaration}.visit(metaDefinition));
		else
		{
			CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart};
			headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(metaDefinition));
		}
	}
	else if (auto nameImport = DCast<OOModel::NameImport>(node()))
	{
		CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart};
		headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(nameImport));
		sourcePart()->setFragment(DeclarationVisitor{printContextDeclaration}.visit(nameImport));
	}
	else if (auto explicitTemplateInstantiation = DCast<OOModel::ExplicitTemplateInstantiation>(node()))
	{
		CppPrintContext headerPartPrintContext{printContextDeclaration, CppPrintContext::IsHeaderPart |
																								CppPrintContext::PrintExternKeyword};
		headerPart()->setFragment(DeclarationVisitor{headerPartPrintContext}.visit(explicitTemplateInstantiation));
		sourcePart()->setFragment(DeclarationVisitor{printContextDeclaration}.visit(explicitTemplateInstantiation));
	}
	else
		Q_ASSERT(false);
}

bool CodeUnit::printInCppOnly(OOModel::Declaration* declaration) const
{
	if (declaration->modifiers()->isSet(OOModel::Modifier::Static) &&
		 declaration->firstAncestorOfType<OOModel::Class>() == nullptr &&
		 (DCast<OOModel::Method>(declaration) || DCast<OOModel::Field>(declaration)))
	return true;

	return SpecialCases::printInCppOnly(declaration);
}

void CodeUnit::calculateDependencies(QList<CodeUnit*>& allUnits)
{
	headerPart()->calculateDependencies(allUnits);
	sourcePart()->calculateDependencies(allUnits);
}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />

<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Tab Icons | Android Developers</title>

<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../assets/css/default.css" rel="stylesheet" type="text/css">

          	Quicknav
			      Quicknav

                  Design

Develop

Distribute

Links

Google Play Developer Console

Android Developers Blog

About Android

Android Sites

Android.com

Android Developers

Android Open Source Project

      <form onsubmit="return submit_search()">
        <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../')"
onkeyup="return search_changed(event, false, '../../../')" />
      </form>

        close

Get Started

Style

Patterns

Building Blocks

Downloads

Videos

Training

API Guides

Reference

Tools

Get the SDK

Google Services

Google Play

Publishing

Promoting

App Quality

Spotlight

Open Distribution

Results

Loading...

Training

API Guides

Reference

Tools

Google Services

to top

        App Components

            App Fundamentals

            Activities

              Fragments

              Loaders

              Tasks and Back Stack

            Services

              Bound Services

              AIDL

            Content Providers

              Content Provider Basics

              Creating a Content Provider

              Calendar Provider

              Contacts Provider

              Storage Access Framework

          Intents and Intent Filters

          Processes and Threads

          Permissions

            App Widgets

              App Widget Host

          Android Manifest

<action>

<activity>

<activity-alias>

<application>

<category>

<compatible-screens>

<data>

<grant-uri-permission>

<instrumentation>

<intent-filter>

<manifest>

<meta-data>

<path-permission>

<permission>

<permission-group>

<permission-tree>

<provider>

<receiver>

<service>

<supports-gl-texture>

<supports-screens>

<uses-configuration>

<uses-feature>

<uses-library>

<uses-permission>

<uses-sdk>

        User Interface

          Overview

            Layouts

              Linear Layout

              Relative Layout

              List View

              Grid View

            Input Controls

              Buttons

              Text Fields

              Checkboxes

              Radio Buttons

              Toggle Buttons

              Spinners

              Pickers

          Input Events

          Menus

           Action Bar

            Settings

           Dialogs

          Notifications

          Toasts

            Search

Creating a Search Interface

Adding Recent Query Suggestions

Adding Custom Suggestions

Searchable Configuration

          Drag and Drop

            Accessibility

              Making Applications Accessible

              Accessibility Developer Checklist

              Building Accessibility Services

          Styles and Themes

          Custom Components

           App Resources

            Overview

            Providing Resources

            Accessing Resources

              Handling Runtime Changes

            Localization

              Resource Types

Animation

Color State List

Drawable

Layout

Menu

String

Style

More Types

          Animation and Graphics

            Overview

            Property Animation

            View Animation

            Drawable Animation

            Canvas and Drawables

            OpenGL ES

            Hardware Acceleration

              Computation

                    RenderScript

                    Advanced RenderScript

                    Runtime API Reference

            Media and Camera

                  Media Playback

                   Supported Media Formats

                  Audio Capture

                  JetPlayer

                  Camera

              Location and Sensors

               Location and Maps

               Location Strategies

              Sensors Overview

              Motion Sensors

              Position Sensors

              Environment Sensors

               Connectivity

          Bluetooth

Bluetooth Low Energy

          NFC

NFC Basics

Advanced NFC

Host-based Card Emulation

            Wi-Fi P2P

            USB

Accessory

Host

            SIP

            Text and Input

              Copy and Paste

              Creating an IME

              Spelling Checker

          Data Storage

            Storage Options

            Data Backup

            App Install Location

               Administration

                Device Policies

    Web Apps

            Overview

            Targeting Screens from Web Apps

            Building Web Apps in WebView

            Migrating to WebView in Android 4.4

            Debugging Web Apps

            Best Practices for Web Apps

      Best Practices
      Bewährte Verfahren
      Prácticas recomendadas
      Meilleures pratiques
      Best practice
      ベスト プラクティス
      最佳实践
      最佳實務

            Compatibility

          Supporting Multiple Screens

            Distributing to Specific Screens

            Screen Compatibility Mode

            Supporting Tablets and Handsets

Tab Icons

In this document

Providing Icons for Two Tab States

Android 2.0 through Android 2.3

Size

Style, colors, and effects

Do's and don'ts

Example icons

Android 1.6 and Earlier

See also

Supporting Multiple
Screens

New Guides for App Designers!

Check out the new documents for designers at Android Design, including more guidelines
for Iconography.

Tab icons are graphical elements used to represent individual tabs in a
multi-tab interface. Each tab icon has two states: unselected and selected.

As described in Providing
Density-Specific Icon Sets, you should create separate icon sets for low-,
medium-, and high-density screens. This ensures that your icons will display
properly across the range of devices on which your application can be installed.
See Tips for Designers
for suggestions on how to work with multiple sets of icons.

Final art must be exported as a transparent PNG file. Do not include
a background color.

Templates for creating icons in Adobe Photoshop are available in the Icon
Templates Pack.

Warning:

The style of tab icons has changed drastically in
Android 2.0 compared to previous versions. To
provide support for all Android versions, developers should:

1. Place tab icons for Android 2.0 and higher in the
drawable-hdpi-v5, drawable-mdpi-v5, and drawable-ldpi-v5 directories.

2. Place tab icons for previous versions in
drawable-hdpi, drawable-mdpi, and drawable-ldpi directories.

3. Set android:targetSdkVersion to 5 or higher in the
<uses-sdk>
in the application manifest.
This will inform the system that it should render tabs using the new tab style.

Providing Icons for Two Tab States

Tab icons should have two states: unselected and selected. To provide icons
with multiple states, developers must create a
state
list drawable for each an icon, which is an XML file that lists which image
to use for the different UI states.

For example, for a tab widget with tabs named 'Friends' and 'Coworkers',
you can use a directory structure similar to the one below:

res/...
    drawable/...
        ic_tab_friends.xml
        ic_tab_coworkers.xml
    drawable-ldpi/...
        ic_tab_friends_selected.png
        ic_tab_friends_unselected.png
        ic_tab_coworkers_selected.png
        ic_tab_coworkers_unselected.png
    drawable-mdpi/...
        ic_tab_friends_selected.png
        ic_tab_friends_unselected.png
        ic_tab_coworkers_selected.png
        ic_tab_coworkers_unselected.png
    drawable-hdpi/...
        ...
    drawable-ldpi-v5/...
        ...
    drawable-mdpi-v5/...
        ...
    drawable-hdpi-v5/...
        ...

The contents of the XML files listed above should reference the corresponding
selected and unselected icon drawables. For example, below is the code
for ic_tab_friends.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- selected state -->
    <item android:drawable="@drawable/ic_tab_friends_selected"
          android:state_selected="true"
          android:state_pressed="false" />
    <!-- unselected state (default) -->
    <item android:drawable="@drawable/ic_tab_friends_unselected" />
</selector>

Android 2.0 through Android 2.3

The following guidelines describe how to design tab icons for Android
2.0 through Android 2.3 (API Levels 5 through 10).

Size and positioning

Tab icons should use simple shapes and forms and those must be
scaled and positioned inside the final asset.

Figure 1 illustrates various ways of positioning the icon inside the
asset. You should size the icons smaller than the actual bounds of the
asset.

In order to indicate the recommended size for the icon, each example in
Figure 1 includes three different guide rectangles:

The red box is the bounding box for the full asset.

The blue box is the recommended bounding box for the actual icon.
The icon box is sized smaller than the full asset box to allow for
special icon treatments.

The orange box is the recommended bounding box for the actual icon when
the content is square. The box for square icons is smaller than that for other
icons to establish a consistent visual weight across the two types.

Tab icon dimensions for high-density (hdpi) screens:

Full Asset: 48 x 48 px

Icon: 42 x 42 px

Tab icon dimensions for medium-density (mdpi) screens:

Full Asset: 32 x 32 px

Icon: 28 x 28 px

Tab icon dimensions for low-density (ldpi) screens:

Full Asset: 24 x 24 px

Icon: 22 x 22 px

Figure 1.
 Tab icon sizing and positioning inside the bounds of the
 icon asset.

Style, colors, and effects

Tab icons are flat, matte, and pictured face-on.

Tab icons should have two states: selected and unselected.

Figure 2. Style and effects for unselected tab icons.

Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.

1.	Fill color:	#808080

2.	Inner content:	Inner content should subtract from the outer shape and consist purely of transparent pixels.

Figure 3. Style and effects for selected tab icons.

Note: all pixel dimensions are for medium density and should be scaled appropriately for other densities.

1.	Fill color:	#FFFFFF

2.	Inner content:	Inner content should subtract from the outer shape and consist purely of transparent pixels.

3.	Outer glow:	#000000, 25% opacity
size 3px

Do's and don'ts

Below are some "do and don't" examples to consider when creating tab icons for
your application.

Example icons

Shown below are standard high-density tab icons that are used in
the Android platform.

Warning:
Because these resources can change between platform versions, you
should not reference the system's copy of the resources. If you want to
use any icons or other internal drawable resources, you should store a
local copy of those icons or drawables in your application resources,
then reference the local copy from your application code. In that way, you can
maintain control over the appearance of your icons, even if the system's
copy changes. Note that the grid below is not intended to be complete.

Android 1.6 and Earlier

The following guidelines describe how to design tab icons for Android
1.6 (API Level 4) and earlier.

Structure

Unselected tab icons have the same fill gradient and effects as
menu icons,
but with no outer glow.

Selected tab icons look just like unselected tab icons, but with a fainter
inner shadow, and have the same front part gradient as
dialog icons.

Tab icons have a 1 px safeframe which should only be overlapped for the edge
of the anti-alias of a round shape.

All dimensions specified on this page are based on a 32x32 px artboard size.
Keep 1 px of padding around the bounding box inside the Photoshop template.

Figure 3. Safeframe and fill gradient for unselected tab
icons. Icon size is 32x32.

Figure 4. Safeframe and fill gradient for tab icons in
selected state. Icon size is 32x32.

Unselected tab icon

Light, effects, and shadows

Unselected tab icons look just like the selected tab icons, but with a
fainter inner shadow, and the same front part gradient as the dialog icons.

Figure 5. Light, effects, and shadows for unselected
tab icons.

1.	Front part:	gradient overlay | angle 90°
bottom color: r 223 | g 223 | b 223
top color: r 249 | g 249 | b 249
bottom color location: 0%
top color location: 75%

2.	Inner shadow:	black | 10 % opacity | angle 90° distance 2px | size 2px

3.	Inner bevel:	depth 1% | direction down | size 0px | angle 90° | altitude 10°
highlight white 70% opacity
shadow black 25% opacity

Step by step

Create the basic shapes using a tool like Adobe Illustrator.

Import the shape to a tool like Adobe Photoshop and scale to fit an image of
32x32 px on a transparent background.

Add the effects seen in Figure 5 for the unselected state filter.

Export the icon at 32x32 as a PNG file with transparency enabled.

Selected tab icon

The selected tab icons have the same fill gradient and effects as the menu
icon, but with no outer glow.

Figure 6. Light, effects, and shadows for selected tab
icons.

1.	Front part:	Use fill gradient from color palette.

2.	Inner shadow:	black | 20% opacity |
angle 90° | distance 2px |
size 2px

3.	Inner bevel:	depth 1% | direction down | size 0px | angle 90° |
altitude 10°
highlight white 70% opacity
shadow black 25% opacity

Color palette

Fill gradient
1:  r 163 | g 163 | b 163
2:  r 120 | g 120 | b 120
Used as color fill on unselected tab icons.

Step by step

Create the basic shape using a tool like Adobe Illustrator.

Import the shape into a tool like Adobe Photoshop and scale to fit a 32x32
px artboard with a transparent background.

Add the effects seen in Figure 6 for the selected state filter.

Export the icon at 32x32 as a PNG file with transparency enabled.

  Except as noted, this content is
  licensed under
  Creative Commons Attribution 2.5. For details and
  restrictions, see the Content
  License.

    About Android  |
    Legal  |
    Support


text:
layout: global
title: HDFS charts
---

# HDFS charts

Helm charts for launching HDFS daemons in a K8s cluster. The main entry-point
chart is `hdfs-k8s`, which is a uber-chart that specifies other charts as
dependency subcharts. This means you can launch all HDFS components using
`hdfs-k8s`.

Note that the HDFS charts are currently in pre-alpha quality. They are also
being heavily revised and are subject to change.

HDFS on K8s supports the following features:
  - namenode high availability (HA): HDFS namenode daemons are in charge of
    maintaining file system metadata concerning which directories have which
    files and where are the file data. Namenode crash will cause service outage.
    HDFS can run two namenodes in active/standby setup. HDFS on K8s supports HA.
  - K8s persistent volumes (PV) for metadata: Namenode crash will cause service
    outage. Losing namenode metadata can lead to loss of file system. HDFS on
    K8s can store the metadata in remote K8s persistent volumes so that metdata
    can remain intact even if both namenode daemons are lost or restarted.
  - K8s HostPath volumes for file data: HDFS datanodes daemons store actual
    file data. File data should also survive datanode crash or restart. HDFS on
    K8s stores the file data on the local disks of the K8s cluster nodes using
    K8s HostPath volumes. (We plan to switch to a better mechanism, K8s
    persistent local volumes)
  - Kerberos: Vanilla HDFS is not secure. Intruders can easily write custom
    client code, put a fake user name in requests and steal data. Production
    HDFS often secure itself using Kerberos. HDFS on K8s supports Kerberos.

Here is the list of all charts.

  - hdfs-k8s: main uber-chart. Launches other charts.
  - hdfs-namenode-k8s: a statefulset and other K8s components for launching HDFS
    namenode daemons, which maintains file system metadata. The chart supports
    namenode high availability (HA).
  - hdfs-datanode-k8s: a daemonset and other K8s components for launching HDFS
    datanode daemons, which are responsible for storing file data.
  - hdfs-config-k8s: a configmap containing Hadoop config files for HDFS.
  - zookeeper: This chart is NOT in this repo. But hdfs-k8s pulls the zookeeper
    chart in the incubator remote repo
    (https://kubernetes-charts-incubator.storage.googleapis.com/)
    as a dependency and launhces zookeeper daemons. Zookeeper makes sure
    only one namenode is active in the HA setup, while the other namenode
    becomes standby. By default, we will launch three zookeeper servers.
  - hdfs-journalnode-k8s: a statefulset and other K8s components for launching
    HDFS journalnode quorums, which ensures the file system metadata are
    properly shared among the two namenode daemons in the HA setup.
    By default, we will launch three journalnode servers.
  - hdfs-client-k8s: a pod that is configured to run Hadoop client commands
    for accessing HDFS.
  - hdfs-krb5-k8s: a size-1 statefulset and other K8s components for launching
    a Kerberos server, which can be used to secure HDFS. Disabled by default.
  - hdfs-simple-namenode-k8s: Disabled by default. A simpler setup of the
    namenode that launches only one namenode. i.e. This does not support HA. It
    does not support Kerberos nor persistent volumes either. As it does not
    support HA, we also don't need zookeeper nor journal nodes.  You may prefer
    this if you want the simplest possible setup.

# Prerequisite

Requires Kubernetes 1.6+ as the `namenode` and `datanodes` are using
`ClusterFirstWithHostNet`, which was introduced in Kubernetes 1.6

# Usage

## Basic

The HDFS daemons can be launched using the main `hdfs-k8s` chart. First, build
the main chart using:

```
  $ helm repo add incubator  \
      https://kubernetes-charts-incubator.storage.googleapis.com/
  $ helm dependency build charts/hdfs-k8s
```

Zookeeper, journalnodes and namenodes need persistent volumes for storing
metadata. By default, the helm charts do not set the storage class name for
dynamically provisioned volumes, nor does it use persistent volume selectors for
static persistent volumes.

This means it will rely on a provisioner for default storage volume class for
dynamic volumes. Or if your cluster has statically provisioned volumes, the
chart will match existing volumes entirely based on the size requirements. To
override this default behavior, you can specify storage volume classes for
dynamic volumes, or volume selectors for static volumes. See below for how to
set these options.

  - namenodes: Each of the two namenodes needs at least a 100 GB volume.  i.e.
    Yon need two 100 GB volumes. This can be overridden by the
    `hdfs-namenode-k8s.persistence.size` option.
    You can also override the storage class or the selector using
    `hdfs-namenode-k8s.persistence.storageClass`, or
    `hdfs-namenode-k8s.persistence.selector` respectively. For details, see the
    values.yaml file inside `hdfs-namenode-k8s` chart dir.
  - zookeeper: You need three > 5 GB volumes. i.e. Each of the two zookeeper
    servers will need at least 5 GB in the volume. Can be overridden by
    the `zookeeper.persistence.size` option. You can also override
    the storage class using `zookeeper.persistence.storageClass`.
  - journalnodes: Each of the three journalnodes will need at least 20 GB in
    the volume. The size can be overridden by the
    `hdfs-journalnode-k8s.persistence.size` option.
    You can also override the storage class or the selector using
    `hdfs-journalnode-k8s.persistence.storageClass`, or
    `hdfs-journalnode-k8s.persistence.selector` respectively. For details, see the
    values.yaml file inside `hdfs-journalnode-k8s` chart dir.
  - kerberos: The single Kerberos server will need at least 20 GB in the volume.
    The size can be overridden by the `hdfs-krb5-k8s.persistence.size` option.
    You can also override the storage class or the selector using
    `hdfs-krb5-k8s.persistence.storageClass`, or
    `hdfs-krb5-k8s.persistence.selector` respectively. For details, see the
    values.yaml file inside `hdfs-krb5-k8s` chart dir.

Then launch the main chart. Specify the chart release name say "my-hdfs",
which will be the prefix of the K8s resource names for the HDFS components.

```
  $ helm install -n my-hdfs charts/hdfs-k8s
```

Wait for all daemons to be ready. Note some daemons may restart themselves
a few times before they become ready.

```
  $ kubectl get pod -l release=my-hdfs

  NAME                             READY     STATUS    RESTARTS   AGE
  my-hdfs-client-c749d9f8f-d5pvk   1/1       Running   0          2m
  my-hdfs-datanode-o7jia           1/1       Running   3          2m
  my-hdfs-datanode-p5kch           1/1       Running   3          2m
  my-hdfs-datanode-r3kjo           1/1       Running   3          2m
  my-hdfs-journalnode-0            1/1       Running   0          2m
  my-hdfs-journalnode-1            1/1       Running   0          2m
  my-hdfs-journalnode-2            1/1       Running   0          1m
  my-hdfs-namenode-0               1/1       Running   3          2m
  my-hdfs-namenode-1               1/1       Running   3          2m
  my-hdfs-zookeeper-0              1/1       Running   0          2m
  my-hdfs-zookeeper-1              1/1       Running   0          2m
  my-hdfs-zookeeper-2              1/1       Running   0          2m
```

Namenodes and datanodes are currently using the K8s `hostNetwork` so they can
see physical IPs of each other. If they are not using `hostNetowrk`,
overlay K8s network providers such as weave-net may mask the physical IPs,
which will confuse the data locality later inside namenodes.

Finally, test with the client pod:

```
  $ _CLIENT=$(kubectl get pods -l app=hdfs-client,release=my-hdfs -o name |  \
      cut -d/ -f 2)
  $ kubectl exec $_CLIENT -- hdfs dfsadmin -report
  $ kubectl exec $_CLIENT -- hdfs haadmin -getServiceState nn0
  $ kubectl exec $_CLIENT -- hdfs haadmin -getServiceState nn1

  $ kubectl exec $_CLIENT -- hadoop fs -rm -r -f /tmp
  $ kubectl exec $_CLIENT -- hadoop fs -mkdir /tmp
  $ kubectl exec $_CLIENT -- sh -c  \
    "(head -c 100M < /dev/urandom > /tmp/random-100M)"
  $ kubectl exec $_CLIENT -- hadoop fs -copyFromLocal /tmp/random-100M /tmp
```

## Kerberos

Kerberos can be enabled by setting a few related options:

```
  $ helm install -n my-hdfs charts/hdfs-k8s  \
    --set global.kerberosEnabled=true  \
    --set global.kerberosRealm=MYCOMPANY.COM  \
    --set tags.kerberos=true
```

This will launch all charts including the Kerberos server, which will become
ready pretty soon. However, HDFS daemon charts will be blocked as the deamons
require Kerberos service principals to be available. So we need to unblock
them by creating those principals.

First, create a configmap containing the common Kerberos config file:

```
  _MY_DIR=~/krb5
  mkdir -p $_MY_DIR
  _KDC=$(kubectl get pod -l app=hdfs-krb5,release=my-hdfs --no-headers  \
      -o name | cut -d/ -f2)
  _run kubectl cp $_KDC:/etc/krb5.conf $_MY_DIR/tmp/krb5.conf
  _run kubectl create configmap my-hdfs-krb5-config  \
    --from-file=$_MY_DIR/tmp/krb5.conf
```

Second, create the service principals and passwords. Kerberos requires service
principals to be host specific. Some HDFS daemons are associated with your K8s
cluster nodes' physical host names say kube-n1.mycompany.com, while others are
associated with Kubernetes virtual service names, for instance
my-hdfs-namenode-0.my-hdfs-namenode.default.svc.cluster.local. You can get
the list of these host names like:

```
  $ _HOSTS=$(kubectl get nodes  \
    -o=jsonpath='{.items[*].status.addresses[?(@.type == "Hostname")].address}')

  $ _HOSTS+=$(kubectl describe configmap my-hdfs-config |  \
      grep -A 1 -e dfs.namenode.rpc-address.hdfs-k8s  \
          -e dfs.namenode.shared.edits.dir |
      grep "<value>" |
      sed -e "s/<value>//"  \
          -e "s/<\/value>//"  \
          -e "s/:8020//"  \
          -e "s/qjournal:\/\///"  \
          -e "s/:8485;/ /g"  \
          -e "s/:8485\/hdfs-k8s//")
```

Then generate per-host principal accounts and password keytab files.

```
  $ _SECRET_CMD="kubectl create secret generic my-hdfs-krb5-keytabs"
  $ for _HOST in $_HOSTS; do
      kubectl exec $_KDC -- kadmin.local -q  \
        "addprinc -randkey hdfs/$_HOST@MYCOMPANY.COM"
      kubectl exec $_KDC -- kadmin.local -q  \
        "addprinc -randkey HTTP/$_HOST@MYCOMPANY.COM"
      kubectl exec $_KDC -- kadmin.local -q  \
        "ktadd -norandkey -k /tmp/$_HOST.keytab hdfs/$_HOST@MYCOMPANY.COM HTTP/$_HOST@MYCOMPANY.COM"
      kubectl cp $_KDC:/tmp/$_HOST.keytab $_MY_DIR/tmp/$_HOST.keytab
      _SECRET_CMD+=" --from-file=$_MY_DIR/tmp/$_HOST.keytab"
    done
```

The above was building a command using a shell variable `SECRET_CMD` for
creating a K8s secret that contains all keytab files. Run the command to create
the secret.

```
  $ $_SECRET_CMD
```

This will unblock all HDFS daemon pods. Wait until they become ready.

Finally, test the setup using the following commands:

```
  $ _NN0=$(kubectl get pods -l app=hdfs-namenode,release=my-hdfs -o name |  \
      head -1 |  \
      cut -d/ -f2)
  $ kubectl exec $_NN0 -- sh -c "(apt install -y krb5-user > /dev/null)"  \
      || true
  $ kubectl exec $_NN0 --   \
      kinit -kt /etc/security/hdfs.keytab  \
      hdfs/my-hdfs-namenode-0.my-hdfs-namenode.default.svc.cluster.local@MYCOMPANY.COM
  $ kubectl exec $_NN0 -- hdfs dfsadmin -report
  $ kubectl exec $_NN0 -- hdfs haadmin -getServiceState nn0
  $ kubectl exec $_NN0 -- hdfs haadmin -getServiceState nn1
  $ kubectl exec $_NN0 -- hadoop fs -rm -r -f /tmp
  $ kubectl exec $_NN0 -- hadoop fs -mkdir /tmp
  $ kubectl exec $_NN0 -- hadoop fs -chmod 0777 /tmp
  $ kubectl exec $_KDC -- kadmin.local -q  \
      "addprinc -randkey user1@MYCOMPANY.COM"
  $ kubectl exec $_KDC -- kadmin.local -q  \
      "ktadd -norandkey -k /tmp/user1.keytab user1@MYCOMPANY.COM"
  $ kubectl cp $_KDC:/tmp/user1.keytab $_MY_DIR/tmp/user1.keytab
  $ kubectl cp $_MY_DIR/tmp/user1.keytab $_CLIENT:/tmp/user1.keytab

  $ kubectl exec $_CLIENT -- sh -c "(apt install -y krb5-user > /dev/null)"  \
      || true

  $ kubectl exec $_CLIENT -- kinit -kt /tmp/user1.keytab user1@MYCOMPANY.COM
  $ kubectl exec $_CLIENT -- sh -c  \
      "(head -c 100M < /dev/urandom > /tmp/random-100M)"
  $ kubectl exec $_CLIENT -- hadoop fs -ls /
  $ kubectl exec $_CLIENT -- hadoop fs -copyFromLocal /tmp/random-100M /tmp
```

## Advanced options

### Setting HostPath volume locations for datanodes

HDFS on K8s stores the file data on the local disks of the K8s cluster nodes
using K8s HostPath volumes. You may want to change the default locations. Set
global.dataNodeHostPath to override the default value. Note the option
takes a list in case you want to use multiple disks.

```
  $ helm install -n my-hdfs charts/hdfs-k8s  \
      --set "global.dataNodeHostPath={/mnt/sda1/hdfs-data0,/mnt/sda1/hdfs-data1}"
```

### Using an existing zookeeper quorum

By default, HDFS on K8s pulls in the zookeeper chart in the incubator remote
repo (https://kubernetes-charts-incubator.storage.googleapis.com/) as a
dependency and launhces zookeeper daemons. But your K8s cluster may already
have a zookeeper quorum.

It is possible to use the existing zookeeper. We just need set a few options
in the helm install command line. It should be something like:

```
  $helm install -n my-hdfs charts/hdfs-k8s  \
    --set condition.subchart.zookeeper=false  \
    --set global.zookeeperQuorumOverride=zk-0.zk-svc.default.svc.cluster.local:2181,zk-1.zk-svc.default.svc.cluster.local:2181,zk-2.zk-svc.default.svc.cluster.local:2181
```

Setting `condition.subchart.zookeeper` to false prevents the uber-chart from
bringing in zookeeper as sub-chart. And the `global.zookeeperQuorumOverride`
option specifies the custom address for a zookeeper quorum. Use your
zookeeper address here.

### Pinning namenodes to specific K8s cluster nodes

Optionally, you can attach labels to some of your k8s cluster nodes so that
namenodes will always run on those cluster nodes. This can allow your HDFS
client outside the Kubernetes cluster to expect stable IP addresses. When used
by those outside clients, Kerberos expects the namenode addresses to be stable.

```
  $ kubectl label nodes YOUR-HOST-1 hdfs-namenode-selector=hdfs-namenode
  $ kubectl label nodes YOUR-HOST-2 hdfs-namenode-selector=hdfs-namenode
```

You should add the nodeSelector option to the helm chart command:

```
  $ helm install -n my-hdfs charts/hdfs-k8s  \
     --set hdfs-namenode-k8s.nodeSelector.hdfs-namenode-selector=hdfs-namenode \
     ...
```

### Excluding datanodes from some K8s cluster nodes

You may want to exclude some K8s cluster nodes from datanodes launch target.
For instance, some K8s clusters may let the K8s cluster master node launch
a datanode. To prevent this, label the cluster nodes with
`hdfs-datanode-exclude`.

```
  $ kubectl label node YOUR-CLUSTER-NODE hdfs-datanode-exclude=yes
```

### Launching with a non-HA namenode

You may want non-HA namenode since it is the simplest possible setup.
Note this won't launch zookeepers nor journalnodes.

The single namenode is supposed to be pinned to a cluster host using a node
label.  Attach a label to one of your K8s cluster node.

```
  $ kubectl label nodes YOUR-CLUSTER-NODE hdfs-namenode-selector=hdfs-namenode-0
```

The non-HA setup does not even use persistent vlumes. So you don't even
need to prepare persistent volumes. Instead, it is using hostPath volume
of the pinned cluster node. So, just launch the chart while
setting options to turn off HA. You should add the nodeSelector option
so that the single namenode would find the hostPath volume of the same cluster
node when the pod restarts.

```
  $ helm install -n my-hdfs charts/hdfs-k8s  \
      --set tags.ha=false  \
      --set tags.simple=true  \
      --set global.namenodeHAEnabled=false  \
      --set hdfs-simple-namenode-k8s.nodeSelector.hdfs-namenode-selector=hdfs-namenode-0
```

# Security

## K8s secret containing Kerberos keytab files

The Kerberos setup creates a K8s secret containing all the keytab files of HDFS
daemon service princialps. This will be mounted onto HDFS daemon pods. You may
want to restrict access to this secret using k8s
[RBAC](https://kubernetes.io/docs/admin/authorization/rbac/), to minimize
exposure of the keytab files.

## HostPath volumes
`Datanode` daemons run on every cluster node. They also mount k8s `hostPath`
local disk volumes.  You may want to restrict access of `hostPath`
using `pod security policy`.
See [reference](https://github.com/kubernetes/examples/blob/master/staging/podsecuritypolicy/rbac/README.md))

## Credits

Many charts are using public Hadoop docker images hosted by
[uhopper](https://hub.docker.com/u/uhopper/).


text:
class QuestionsSurvey < ActiveRecord::Base
  belongs_to :question
  belongs_to :survey
end


text:
```
Hubot> sora_h++
Hubot> sora_h increment!! (total : 1)
Hubot> hogelog++
Hubot> hogelog increment!! (total : 1)
Hubot> sora_h++
Hubot> sora_h increment!! (total : 2)
Hubot> yoshiori--
Hubot> yoshiori decrement!! (total : -1)
Hubot> hubot scorekeeper
Hubot> 1 : sora_h
Hubot> 2 : hogelog
Hubot> 3 : yoshiori
```

## Installation

Add `hubot-scorekeeper` to your `package.json` dependencies.

```json
"dependencies": {
  "hubot-scorekeeper": ">= 0.0.7"
}
```

Run `npm install`

Add `hubot-scorekeeper` to `external-scripts.json`.

## Usage

* {name}++ - Increment {name}'s point
* {name}-- - Decrement {name}'s point
* scorekeeper - Show scoreboard
* show scoreboard - Show scoreboard
* scorekeeper {name} - Show current point of {name}
* what's the score of {name} - Show current point of {name}

### mention's prefix

if you need ignore hipchat's mention.

```
export HUBOT_SCOREKEEPER_MENTION_PREFIX="@"
```

```
Hubot> @con_mame++
Hubot> con_mame increment!! (total : 1)
Hubot> con_mame++
Hubot> con_mame increment!! (total : 2)
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
import traceback
from flask import render_template, redirect, url_for, abort, flash, request,\
    current_app, make_response
from flask_login import login_required, current_user
from flask_sqlalchemy import get_debug_queries
from .forms import EditProfileForm, EditProfileAdminForm, PostForm,\
    CommentForm
from flask import app
from app.models import Permission, Role, User, Post, Comment, HostPageTable, Pict,News
import urllib
import urllib2
from urllib import quote,unquote
import json
import urllib,urllib2
import random
from datetime import *
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_pagedown import PageDown
from config import Config
from config import config
from app import utils as ut
#from app import db
import time
import time
import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.csdn.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="cn.csdn.activity"></instrumentation>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".LoginActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegisterActivity"></activity>
        <uses-library android:name="android.test.runner"/>
    </application>

</manifest>


text:
package org.deeplearning4j.nn.conf.layers;

import lombok.*;
import org.deeplearning4j.nn.api.Layer;
import org.deeplearning4j.nn.api.ParamInitializer;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.params.GravesLSTMParamInitializer;
import org.deeplearning4j.optimize.api.IterationListener;
import org.deeplearning4j.util.LayerValidation;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.activations.impl.ActivationSigmoid;
import org.nd4j.linalg.api.ndarray.INDArray;

import java.util.Collection;
import java.util.Map;

/**
 * LSTM recurrent net, based on Graves: Supervised Sequence Labelling with Recurrent Neural Networks
 * http://www.cs.toronto.edu/~graves/phd.pdf
 */
@Data
@NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class GravesLSTM extends BaseRecurrentLayer {

    private double forgetGateBiasInit;
    private IActivation gateActivationFn = new ActivationSigmoid();

    private GravesLSTM(Builder builder) {
        super(builder);
        this.forgetGateBiasInit = builder.forgetGateBiasInit;
        this.gateActivationFn = builder.gateActivationFn;
    }

    @Override
    public Layer instantiate(NeuralNetConfiguration conf, Collection<IterationListener> iterationListeners,
                    int layerIndex, INDArray layerParamsView, boolean initializeParams) {
        LayerValidation.assertNInNOutSet("GravesLSTM", getLayerName(), layerIndex, getNIn(), getNOut());
        org.deeplearning4j.nn.layers.recurrent.GravesLSTM ret =
                        new org.deeplearning4j.nn.layers.recurrent.GravesLSTM(conf);
        ret.setListeners(iterationListeners);
        ret.setIndex(layerIndex);
        ret.setParamsViewArray(layerParamsView);
        Map<String, INDArray> paramTable = initializer().init(conf, layerParamsView, initializeParams);
        ret.setParamTable(paramTable);
        ret.setConf(conf);
        return ret;
    }

    @Override
    public ParamInitializer initializer() {
        return GravesLSTMParamInitializer.getInstance();
    }

    @Override
    public double getL1ByParam(String paramName) {
        switch (paramName) {
            case GravesLSTMParamInitializer.INPUT_WEIGHT_KEY:
            case GravesLSTMParamInitializer.RECURRENT_WEIGHT_KEY:
                return l1;
            case GravesLSTMParamInitializer.BIAS_KEY:
                return l1Bias;
            default:
                throw new IllegalArgumentException("Unknown parameter name: \"" + paramName + "\"");
        }
    }

    @Override
    public double getL2ByParam(String paramName) {
        switch (paramName) {
            case GravesLSTMParamInitializer.INPUT_WEIGHT_KEY:
            case GravesLSTMParamInitializer.RECURRENT_WEIGHT_KEY:
                return l2;
            case GravesLSTMParamInitializer.BIAS_KEY:
                return l2Bias;
            default:
                throw new IllegalArgumentException("Unknown parameter name: \"" + paramName + "\"");
        }
    }

    @Override
    public double getLearningRateByParam(String paramName) {
        switch (paramName) {
            case GravesLSTMParamInitializer.INPUT_WEIGHT_KEY:
            case GravesLSTMParamInitializer.RECURRENT_WEIGHT_KEY:
                return learningRate;
            case GravesLSTMParamInitializer.BIAS_KEY:
                if (!Double.isNaN(biasLearningRate)) {
                    //Bias learning rate has been explicitly set
                    return biasLearningRate;
                } else {
                    return learningRate;
                }
            default:
                throw new IllegalArgumentException("Unknown parameter name: \"" + paramName + "\"");
        }
    }

    @AllArgsConstructor
    @NoArgsConstructor
    public static class Builder extends BaseRecurrentLayer.Builder<Builder> {

        private double forgetGateBiasInit = 1.0;
        private IActivation gateActivationFn = new ActivationSigmoid();

        /** Set forget gate bias initalizations. Values in range 1-5 can potentially
         * help with learning or longer-term dependencies.
         */
        public Builder forgetGateBiasInit(double biasInit) {
            this.forgetGateBiasInit = biasInit;
            return this;
        }

        /**
         * Activation function for the LSTM gates.
         * Note: This should be bounded to range 0-1: sigmoid or hard sigmoid, for example
         *
         * @param gateActivationFn Activation function for the LSTM gates
         */
        public Builder gateActivationFunction(String gateActivationFn) {
            return gateActivationFunction(Activation.fromString(gateActivationFn));
        }

        /**
         * Activation function for the LSTM gates.
         * Note: This should be bounded to range 0-1: sigmoid or hard sigmoid, for example
         *
         * @param gateActivationFn Activation function for the LSTM gates
         */
        public Builder gateActivationFunction(Activation gateActivationFn) {
            return gateActivationFunction(gateActivationFn.getActivationFunction());
        }

        /**
         * Activation function for the LSTM gates.
         * Note: This should be bounded to range 0-1: sigmoid or hard sigmoid, for example
         *
         * @param gateActivationFn Activation function for the LSTM gates
         */
        public Builder gateActivationFunction(IActivation gateActivationFn) {
            this.gateActivationFn = gateActivationFn;
            return this;
        }

        @SuppressWarnings("unchecked")
        public GravesLSTM build() {
            return new GravesLSTM(this);
        }
    }

}


text:
package org.kaaproject.kaa.server.common;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.slf4j.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class EnvironmentTest {

  @Test
  public void logStateTest() throws Exception {
    Logger LOG = mock(Logger.class);
    Field logField = Environment.class.getDeclaredField("LOG");
    // set final static field
    setFinalStatic(logField, LOG);
    Environment.logState();
    verify(LOG, atLeastOnce()).info(any(String.class), any(Version.class), any(Version.class));
  }

  // sets final static field to an object
  private void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);
  }
}


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

namespace Hefezopf.Contracts.Comp
{
    public interface IStrategyExecutive
    {
        string GetStrategyName();
    }
}


text:
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/*
 * drivers/staging/android/uapi/ion.h
 *
 * Copyright (C) 2011 Google, Inc.
 */

#ifndef _UAPI_LINUX_ION_H
#define _UAPI_LINUX_ION_H

#include <linux/ioctl.h>
#include <linux/types.h>

/**
 * enum ion_heap_types - list of all possible types of heaps
 * @ION_HEAP_TYPE_SYSTEM:	 memory allocated via vmalloc
 * @ION_HEAP_TYPE_SYSTEM_CONTIG: memory allocated via kmalloc
 * @ION_HEAP_TYPE_CARVEOUT:	 memory allocated from a prereserved
 *				 carveout heap, allocations are physically
 *				 contiguous
 * @ION_HEAP_TYPE_DMA:		 memory allocated via DMA API
 * @ION_NUM_HEAPS:		 helper for iterating over heaps, a bit mask
 *				 is used to identify the heaps, so only 32
 *				 total heap types are supported
 */
enum ion_heap_type {
	ION_HEAP_TYPE_SYSTEM,
	ION_HEAP_TYPE_SYSTEM_CONTIG,
	ION_HEAP_TYPE_CARVEOUT,
	ION_HEAP_TYPE_CHUNK,
	ION_HEAP_TYPE_DMA,
	ION_HEAP_TYPE_CUSTOM, /*
			       * must be last so device specific heaps always
			       * are at the end of this enum
			       */
};

#define ION_NUM_HEAP_IDS		(sizeof(unsigned int) * 8)

/**
 * allocation flags - the lower 16 bits are used by core ion, the upper 16
 * bits are reserved for use by the heaps themselves.
 */

/*
 * mappings of this buffer should be cached, ion will do cache maintenance
 * when the buffer is mapped for dma
 */
#define ION_FLAG_CACHED 1

/**
 * DOC: Ion Userspace API
 *
 * create a client by opening /dev/ion
 * most operations handled via following ioctls
 *
 */

/**
 * struct ion_allocation_data - metadata passed from userspace for allocations
 * @len:		size of the allocation
 * @heap_id_mask:	mask of heap ids to allocate from
 * @flags:		flags passed to heap
 * @handle:		pointer that will be populated with a cookie to use to
 *			refer to this allocation
 *
 * Provided by userspace as an argument to the ioctl
 */
struct ion_allocation_data {
	__u64 len;
	__u32 heap_id_mask;
	__u32 flags;
	__u32 fd;
	__u32 unused;
};

#define MAX_HEAP_NAME			32

/**
 * struct ion_heap_data - data about a heap
 * @name - first 32 characters of the heap name
 * @type - heap type
 * @heap_id - heap id for the heap
 */
struct ion_heap_data {
	char name[MAX_HEAP_NAME];
	__u32 type;
	__u32 heap_id;
	__u32 reserved0;
	__u32 reserved1;
	__u32 reserved2;
};

/**
 * struct ion_heap_query - collection of data about all heaps
 * @cnt - total number of heaps to be copied
 * @heaps - buffer to copy heap data
 */
struct ion_heap_query {
	__u32 cnt; /* Total number of heaps to be copied */
	__u32 reserved0; /* align to 64bits */
	__u64 heaps; /* buffer to be populated */
	__u32 reserved1;
	__u32 reserved2;
};

#define ION_IOC_MAGIC		'I'

/**
 * DOC: ION_IOC_ALLOC - allocate memory
 *
 * Takes an ion_allocation_data struct and returns it with the handle field
 * populated with the opaque handle for the allocation.
 */
#define ION_IOC_ALLOC		_IOWR(ION_IOC_MAGIC, 0, \
				      struct ion_allocation_data)

/**
 * DOC: ION_IOC_HEAP_QUERY - information about available heaps
 *
 * Takes an ion_heap_query structure and populates information about
 * available Ion heaps.
 */
#define ION_IOC_HEAP_QUERY     _IOWR(ION_IOC_MAGIC, 8, \
					struct ion_heap_query)

#endif /* _UAPI_LINUX_ION_H */


text:
class DNS::Zone::RR::NSEC3 < DNS::Zone::RR::Record

  REGEX_NSEC3_RDATA = %r{
    (?<algorithm>\d+)\s*
    (?<flags>\d+)\s*
    (?<iterations>\d+)\s*
    (?<salt>\S+)\s*
    (?<next_hashed_owner_name>\S+)\s*
    (?<rrset_types>#{DNS::Zone::RR::REGEX_STRING})\s*
  }mx

  attr_accessor :algorithm, :flags, :iterations, :salt,
                :next_hashed_owner_name, :rrset_types

  def dump
    parts = general_prefix
    parts << algorithm
    parts << flags
    parts << iterations
    parts << salt
    parts << next_hashed_owner_name
    parts << rrset_types
    parts.join(' ')
  end

  def load(string, options = {})
    rdata = load_general_and_get_rdata(string, options)
    return nil unless rdata

    captures = rdata.match(REGEX_NSEC3_RDATA)
    return nil unless captures

    @algorithm = captures[:algorithm].to_i
    @flags = captures[:flags].to_i
    @iterations = captures[:iterations].to_i
    @salt = captures[:salt]
    @next_hashed_owner_name = captures[:next_hashed_owner_name]
    @rrset_types = captures[:rrset_types]
    self
  end

end


text:
import * as React from 'react';
import { MenuItem } from '../menuitem/MenuItem';

declare module 'primereact/megamenu' {

    type OrientationType = 'vertical' | 'horizontal';

    export interface MegaMenuProps {
        id?: string;
        model?: MenuItem[];
        style?: object;
        className?: string;
        orientation?: OrientationType;
    }

    export class MegaMenu extends React.Component<MegaMenuProps, any> { }
}


text:
import os
from unittest import mock

from django.conf import settings

def test_static_files(client):
    root = os.path.join(settings.BASE_DIR, 'utilities/tests/static')
    with mock.patch.object(settings, 'WHITENOISE_ROOT', root):
        # an API request
        response = client.get('/api/')
        assert 'workflows' in response.data

        # an unmatched file, goes to homepage
        response = client.get('/something')
        assert next(response.streaming_content) == b'index\n'

        # a real static file
        response = client.get('/static.txt')
        assert next(response.streaming_content) == b'static\n'


text:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';

import { Event } from '../../models';
import { GithubApiService } from '../../core/github-api.service';

@Component({
  templateUrl: './user-events.component.html',
  styleUrls: ['./user-events.component.scss']
})
export class UserEventsComponent implements OnInit {

  events: Event[] = [];
  page = 1;
  perPage = 20;
  loadButtonDisabled = false;

  constructor(
    private githubApiService: GithubApiService,
    private route: ActivatedRoute,
    private location: Location
  ) { }

  loadEvents() {
    this.route.parent.params
      .switchMap((params: Params) =>
        this.githubApiService.getUserEvents(params['login'], this.page, this.perPage))
      .subscribe(events => {
        if (0 < events.length) {
          this.events = this.events.concat(events);
        }
        else {
          this.loadButtonDisabled = true;
        }
      });
  }

  ngOnInit() {
    this.loadEvents();
  }

  loadMore() {
    this.page++;
    this.loadEvents();
  }

}


text:
class Beansplan {
    static get DISPLAY_THRESHOLD() {
        // show only percentage of last 30 minutes before show
        return 30 * 60 * 1000;
    }

    constructor() {
        this._interval = null;
        this._startTime = null;
        this._nextShow = null;
        var pattern = new RegExp("Um ([0-9:]+) folgt (.+)");
        var self = this;
        loadAndAddCssFile('next-show.css');

        YouTubeLive.onChatLoaded(function (youtube) {
			self._nextshowContainer = $("
", {"id": "brbtv-next-show"});
            self._circle = $("
", {"id": "brbtv-next-show-circle", "class": "c100 dark center green"});
            self._circle.append('▶

');
			self._nextshowContainer.prepend(self._circle);
			self._nextshowContainer.append("");

            $("#picker-buttons").after(self._nextshowContainer);

            youtube.registerChatMessageObserver(function(elem) {
                var jElem = $(elem);
                if (jElem.find("#author-name").text() == "Beansplan") {
                    var matches = pattern.exec(jElem.find("#message").text().trim());
                    if (matches && matches.length) {
                        var timeShowStarts = matches[1];
                        var showTitle = matches[2];
                        var hourMinutes = timeShowStarts.split(":")
                        hourMinutes[0] = parseInt(hourMinutes[0]);
                        hourMinutes[1] = parseInt(hourMinutes[1]);
                        var then = new Date();
                        var now = new Date();
                        then.setHours(hourMinutes[0]);
                        then.setMinutes(hourMinutes[1]);

                        // when will then be now?
                        var diffMilli = then - now;

                        // Did we already miss it?
                        if (diffMilli < 0) {
                            self.clearNextShowDisplay();

                        } else {
                            // remove unneccesary period
                            if (showTitle.endsWith('.')) {
                                showTitle = showTitle.substr(0, showTitle.length - 1);
                            }
                            self._nextShow = showTitle;
                            self._startTime = then;
                            self._nextshowContainer.find('.nextshow-time').text( timeShowStarts );

							self._nextshowContainer.attr('title', showTitle);
                            self._nextshowContainer.addClass('visible');
                            if (!self._interval) {
                                self._interval = youtube.setInterval(function() {self.timerFired();}, 2000);
                            }

                            // Update now
                            self.removePercent();
                            self.timerFired();
                        }
                    }
                }
            }, true);
        });
    }

    timerFired() {
        if (!this._startTime) {
            return;
        }

        var diffMilli =  this._startTime - (new Date());

        // update title
        var diffMinutes = Math.floor(diffMilli / 1000 / 60);
        this._nextshowContainer.attr('title', chrome.i18n.getMessage('nextShowIn',
        [diffMinutes.toString(), this._nextShow]));

        if (diffMilli < 0) {
            this.clearNextShowDisplay();
        } else if (diffMilli < Beansplan.DISPLAY_THRESHOLD) {
            this.removePercent();
            var percent = Math.floor(100.0 * (1.0 - (diffMilli / Beansplan.DISPLAY_THRESHOLD)));
            }

            this._circle.addClass('p'+percent);
        }

    removePercent() {
        // remove old percent class
        var classes = this._circle.attr('class').split(' ');
        if (classes) {
          for (let clazz of classes) {
              if (clazz.startsWith('p')) {
                  this._circle.removeClass(clazz);
              }
          }
       }
    }

    clearNextShowDisplay() {
        if (this._interval) {
            clearInterval(this._interval);
            this._interval = null;
        }
        this._nextShow = null;
        this._startTime = null;
        this._nextshowContainer.removeClass('visible');
    }
}


text:
package slackbot

import (
	"fmt"

	"github.com/nlopes/slack"

	"github.com/jguyomard/slackbot-links/src/config"
)

var (
	rtm *slack.RTM
)

// Listen connect to Slack through websocket
func Listen() {
	conf := config.Get()

	api := slack.New(conf.SlackToken)
	api.SetDebug(conf.DebugMode)

	// Open Websocket
	rtm = api.NewRTM()
	go rtm.ManageConnection()

	// Check Auth
	_, err := rtm.AuthTest()
	if err != nil {
		panic("Unable to connect to Slack ; invalid token?")
	}

	for {
		slackEvent := <-rtm.IncomingEvents

		switch eventData := slackEvent.Data.(type) {

		case *slack.MessageEvent:
			if conf.DebugMode {
				fmt.Printf("Incoming Message Event: %+v\n\n", eventData)
				fmt.Printf("Incoming SubMessage Event: %+v\n\n", eventData.SubMessage)
			}
			NewMessageFromEvent(eventData).Analyse()

		default:
			//fmt.Printf("Unknown Event Received: %+v\n", eventData)

		}
	}

}


text:
import marshmallow

from molecule import logger
from molecule.model import base

LOG = logger.get_logger(__name__)

class AnsibleSchema(base.Base):
    config_file = marshmallow.fields.Str()
    playbook = marshmallow.fields.Str()
    raw_env_vars = marshmallow.fields.Dict()
    extra_vars = marshmallow.fields.Str()
    verbose = marshmallow.fields.Bool()
    become = marshmallow.fields.Bool()
    tags = marshmallow.fields.Str()

class DriverSchema(base.Base):
    name = marshmallow.fields.Str()

class PlatformSchema(base.Base):
    name = marshmallow.fields.Str()
    box = marshmallow.fields.Str()
    box_version = marshmallow.fields.Str()
    box_url = marshmallow.fields.Str()

class ProviderOptionsSchema(base.Base):
    memory = marshmallow.fields.Int()
    cpus = marshmallow.fields.Int()

class ProviderSchema(base.Base):
    name = marshmallow.fields.Str()
    type = marshmallow.fields.Str()
    options = marshmallow.fields.Nested(ProviderOptionsSchema())

class InterfaceSchema(base.Base):
    network_name = marshmallow.fields.Str()
    type = marshmallow.fields.Str()
    auto_config = marshmallow.fields.Bool()
    ip = marshmallow.fields.Str()

class InstanceOptionsSchema(base.Base):
    append_platform_to_hostname = marshmallow.fields.Bool()

class InstanceSchema(base.Base):
    name = marshmallow.fields.Str()
    ansible_groups = marshmallow.fields.List(marshmallow.fields.Str())
    interfaces = marshmallow.fields.List(
        marshmallow.fields.Nested(InterfaceSchema()))
    raw_config_args = marshmallow.fields.List(marshmallow.fields.Str())
    options = marshmallow.fields.Nested(InstanceOptionsSchema())

class VagrantSchema(base.Base):
    platforms = marshmallow.fields.List(
        marshmallow.fields.Nested(PlatformSchema()))
    providers = marshmallow.fields.List(
        marshmallow.fields.Nested(ProviderSchema()))
    instances = marshmallow.fields.List(
        marshmallow.fields.Nested(InstanceSchema()))

class VerifierOptionsSchema(base.Base):
    sudo = marshmallow.fields.Bool()

class VerifierSchema(base.Base):
    name = marshmallow.fields.Str()
    options = marshmallow.fields.Nested(VerifierOptionsSchema())

class MoleculeSchema(marshmallow.Schema):
    ansible = marshmallow.fields.Nested(AnsibleSchema())
    vagrant = marshmallow.fields.Nested(VagrantSchema())
    driver = marshmallow.fields.Nested(DriverSchema())
    verifier = marshmallow.fields.Nested(VerifierSchema())

def validate(c):
    schema = MoleculeSchema(strict=True)

    return schema.load(c)


text:
<?php
namespace common\widgets;

use yii\helpers\Html;
use yii\widgets\InputWidget;

/**
 * Class JsCaptcha
 * Втджет JS капчи
 * @package common\widgets
 * @author Churkin Anton <webadmin87@gmail.com>
 */
class JsCaptcha extends InputWidget
{

    /**
     * @inheritdoc
     */

    public function init()
    {
        parent::init();
        $this->view->registerJs("
            $('#{$this->options['id']}').val('{$this->value}');
        ");
    }

    /**
     * @inheritdoc
     */

    public function run()
    {

        if ($this->hasModel()) {
            return Html::activeHiddenInput($this->model, $this->attribute, $this->options);
        } else {
            return Html::hiddenInput($this->name, '', $this->options);
        }

    }

}


text:
module Ajaxlibs::IncludesHelper
  # Returns an html script tag for each javascript library name provided.
  # By default, javascript files are loaded locally for development and test environment,
  # and through Google CDN on production environment. Basic dependencies are automatically handled.
  #
  # == Options
  # * <tt>version</tt> : specify the version to use for each library
  # * <tt>local</tt> : if true, always serve file locally, if false, use Google CDN
  # * <tt>:secure</tt> : specify if the generated link should be secured (https) or not. Default is <tt>false</tt>.
  # * <tt>:minified</tt> : <tt>true</tt> if you want a minified version of the javascript library, <tt>false</tt> otherwise. Default is <tt>true</tt>.
  #
  # == Exceptions
  # * <tt>Ajaxlibs::Exception::LibraryNotFound</tt> : raised if one or more of the given library is not available
  # * <tt>Ajaxlibs::Exception::VersionNotFound</tt> : raised if given version is not available for this/these library/libraries
  #
  # == Examples
  # * Simple library load, under the development environment
  #  ajaxlibs_include :jquery
  #    <script src="/javascripts/ajaxlibs/jquery/1.4.2/jquery.min.js?1267013480" type="text/javascript"></script>
  #
  #  ajaxlibs_include :jquery, :jqueryui
  #    <script src="/javascripts/ajaxlibs/jquery/1.4.2/jquery.min.js?1267013480" type="text/javascript"></script>
  #    <script src="/javascripts/ajaxlibs/jqueryui/1.7.2/jquery-ui.min.js?1267013480" type="text/javascript"></script>
  #
  # * Same examples as above, this time in production
  #  ajaxlibs_include :jquery
  #    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  #
  #  ajaxlibs_include :jquery, :jqueryui
  #    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
  #    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js" type="text/javascript"></script>
  #
  # * Specifying version
  #  ajaxlibs_include :prototype, :version => '1.6.0.3'
  #    <script src="/javascripts/ajaxlibs/prototype/1.6.0.3/prototype.js?1267013480" type="text/javascript"></script>
  #
  # * Ask for a non-minified version
  #  ajaxlibs_include :jquery, :minified => false
  #    <script src="/javascripts/ajaxlibs/jquery/1.4.2/jquery.js?1267013480" type="text/javascript"></script>
  #
  # * Automatic dependencies
  #  ajaxlibs_include :scriptaculous
  #    <script src="/javascripts/ajaxlibs/prototype/1.6.1.0/prototype.js?1267013480" type="text/javascript"></script>
  #    <script src="/javascripts/ajaxlibs/scriptaculous/1.8.3/scriptaculous.js?1267013481" type="text/javascript"></script>
  #
  def ajaxlibs_include(*args)
    options = (Hash === args.last) ? args.pop : {}

    includes = args.collect {|library| javascript_include_library library, options}.flatten.compact

    includes.collect {|ajaxlib| javascript_include_tag ajaxlib.include_path}.join("\n")
  end

  private
  def javascript_include_library(library, options)
    library = library.to_sym
    version = options.delete(:version)
    local   = options.delete(:local)
    options[:source] ||= (local === true or (local.nil? and not Ajaxlibs::ProductionEnvironments.include?(RAILS_ENV))) ? :local : :remote
    ajaxlib = Ajaxlibs::Library.by_name(library, options.merge({:version => version}))

    @included_javascript_libraries ||= []

    return if @included_javascript_libraries.include?(ajaxlib)
    @included_javascript_libraries << ajaxlib

    result = []

    ajaxlib.requires.each do |required_library, required_version|
      result << javascript_include_library(required_library, options.merge({:version => required_version}))
    end

    result << ajaxlib
  end
end


text:
<?php

namespace Drupal\Tests\block_content\Functional;

use Drupal\block_content\Entity\BlockContent;
use Drupal\block_content\Entity\BlockContentType;
use Drupal\Component\Utility\Unicode;
use Drupal\content_translation\Tests\ContentTranslationUITestBase;

/**
 * Tests the block content translation UI.
 *
 * @group block_content
 */
class BlockContentTranslationUITest extends ContentTranslationUITestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'language',
    'content_translation',
    'block',
    'field_ui',
    'block_content'
  ];

  /**
   * {@inheritdoc}
   */
  protected $defaultCacheContexts = [
    'languages:language_interface',
    'session',
    'theme',
    'url.path',
    'url.query_args',
    'user.permissions',
    'user.roles:authenticated',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->entityTypeId = 'block_content';
    $this->bundle = 'basic';
    $this->testLanguageSelector = FALSE;
    parent::setUp();

    $this->drupalPlaceBlock('page_title_block');
  }

  /**
   * {@inheritdoc}
   */
  protected function setupBundle() {
    // Create the basic bundle since it is provided by standard.
    $bundle = BlockContentType::create([
      'id' => $this->bundle,
      'label' => $this->bundle,
      'revision' => FALSE
    ]);
    $bundle->save();
  }

  /**
   * {@inheritdoc}
   */
  public function getTranslatorPermissions() {
    return array_merge(parent::getTranslatorPermissions(), [
      'translate any entity',
      'access administration pages',
      'administer blocks',
      'administer block_content fields'
    ]);
  }

  /**
   * Creates a custom block.
   *
   * @param bool|string $title
   *   (optional) Title of block. When no value is given uses a random name.
   *   Defaults to FALSE.
   * @param bool|string $bundle
   *   (optional) Bundle name. When no value is given, defaults to
   *   $this->bundle. Defaults to FALSE.
   *
   * @return \Drupal\block_content\Entity\BlockContent
   *   Created custom block.
   */
  protected function createBlockContent($title = FALSE, $bundle = FALSE) {
    $title = $title ?: $this->randomMachineName();
    $bundle = $bundle ?: $this->bundle;
    $block_content = BlockContent::create([
      'info' => $title,
      'type' => $bundle,
      'langcode' => 'en'
    ]);
    $block_content->save();
    return $block_content;
  }

  /**
   * {@inheritdoc}
   */
  protected function getNewEntityValues($langcode) {
    return ['info' => Unicode::strtolower($this->randomMachineName())] + parent::getNewEntityValues($langcode);
  }

  /**
   * Returns an edit array containing the values to be posted.
   */
  protected function getEditValues($values, $langcode, $new = FALSE) {
    $edit = parent::getEditValues($values, $langcode, $new);
    foreach ($edit as $property => $value) {
      if ($property == 'info') {
        $edit['info[0][value]'] = $value;
        unset($edit[$property]);
      }
    }
    return $edit;
  }

  /**
   * {@inheritdoc}
   */
  protected function doTestBasicTranslation() {
    parent::doTestBasicTranslation();

    // Ensure that a block translation can be created using the same description
    // as in the original language.
    $default_langcode = $this->langcodes[0];
    $values = $this->getNewEntityValues($default_langcode);
    $storage = \Drupal::entityManager()->getStorage($this->entityTypeId);
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $storage->create(['type' => 'basic'] + $values);
    $entity->save();
    $entity->addTranslation('it', $values);

    try {
      $message = 'Blocks can have translations with the same "info" value.';
      $entity->save();
      $this->pass($message);
    }
    catch (\Exception $e) {
      $this->fail($message);
    }

    // Check that the translate operation link is shown.
    $this->drupalGet('admin/structure/block/block-content');
    $this->assertLinkByHref('block/' . $entity->id() . '/translations');
  }

  /**
   * Test that no metadata is stored for a disabled bundle.
   */
  public function testDisabledBundle() {
    // Create a bundle that does not have translation enabled.
    $disabled_bundle = $this->randomMachineName();
    $bundle = BlockContentType::create([
      'id' => $disabled_bundle,
      'label' => $disabled_bundle,
      'revision' => FALSE
    ]);
    $bundle->save();

    // Create a block content for each bundle.
    $enabled_block_content = $this->createBlockContent();
    $disabled_block_content = $this->createBlockContent(FALSE, $bundle->id());

    // Make sure that only a single row was inserted into the block table.
    $rows = db_query('SELECT * FROM {block_content_field_data} WHERE id = :id', [':id' => $enabled_block_content->id()])->fetchAll();
    $this->assertEqual(1, count($rows));
  }

  /**
   * {@inheritdoc}
   */
  protected function doTestTranslationEdit() {
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    $languages = $this->container->get('language_manager')->getLanguages();

    foreach ($this->langcodes as $langcode) {
      // We only want to test the title for non-english translations.
      if ($langcode != 'en') {
        $options = ['language' => $languages[$langcode]];
        $url = $entity->urlInfo('edit-form', $options);
        $this->drupalGet($url);

        $title = t('Edit @type @title [%language translation]', [
          '@type' => $entity->bundle(),
          '@title' => $entity->getTranslation($langcode)->label(),
          '%language' => $languages[$langcode]->getName(),
        ]);
        $this->assertRaw($title);
      }
    }
  }

}


text:
using System;
using System.Linq;
using Lucene.Net.Store;

namespace Merchello.Examine.LocalStorage
{
    public class MultiIndexOutput : IndexOutput
    {
        private readonly IndexOutput[] _outputs;

        public MultiIndexOutput(params IndexOutput[] outputs)
        {
            if (outputs.Length < 1)
            {
                throw new InvalidOperationException("There must be at least one output specified");
            }
            _outputs = outputs;
        }

        public override void WriteByte(byte b)
        {
            foreach (var output in _outputs)
            {
                output.WriteByte(b);
            }
        }

        public override void WriteBytes(byte[] b, int offset, int length)
        {
            foreach (var output in _outputs)
            {
                output.WriteBytes(b, offset, length);
            }
        }

        public override void Flush()
        {
            foreach (var output in _outputs)
            {
                output.Flush();
            }
        }

        public override void Close()
        {
            foreach (var output in _outputs)
            {
                output.Close();
            }
        }

        public override long GetFilePointer()
        {
            //return the first
            return _outputs.First().GetFilePointer();
        }

        public override void Seek(long pos)
        {
            foreach (var output in _outputs)
            {
                output.Seek(pos);
            }
        }

        public override long Length()
        {
            //return the first
            return _outputs.First().GetFilePointer();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using MVCLibraryManagementSystem.Auth;
using MVCLibraryManagementSystem.Models;
using MVCLibraryManagementSystem.ViewModels;
using System.Threading.Tasks;

namespace MVCLibraryManagementSystem.Controllers
{
    // This attribute makes all action methods require
    // authorization in this controller, except the ones marked
    // AllowAnonymous
    [Authorize]
    public class AccountsController : Controller
    {
        // First we create the dependencies
        private LibrarySignInManager _signInManager;
        private LibraryUserManager _userManager;

        public AccountsController()
        {
        }

        public AccountsController(LibraryUserManager userManager, LibrarySignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }

        public LibrarySignInManager SignInManager
        {
            get
            {
                return _signInManager ?? HttpContext.GetOwinContext().Get<LibrarySignInManager>();
            }
            private set
            {
                _signInManager = value;
            }
        }

        public LibraryUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.GetOwinContext().GetUserManager<LibraryUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }

        // GET: Accounts
        public ActionResult Index()
        {
            return View();
        }

        // GET: Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, false, shouldLockout: true);

            switch(result)
            {
                case SignInStatus.Success:
                    return RedirectToAction("Index", "Home");
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }

    }
}


text:
exports.info = { FormatID: '1200',
  FormatName: 'Adobe Illustrator',
  FormatVersion: '3.0 / 3.2',
  FormatAliases: '',
  FormatFamilies: '',
  FormatTypes: 'Image (Vector)',
  FormatDisclosure: '',
  FormatDescription: 'The documents (files) created by Adobe Illustrator are PostScript language documents. A PostScript language document description that minimally conforms to the Document Structuring Conventions has two main parts: a prolog and a script. The prolog encapsulates information needed by other programs to interpret the file. The script describes the graphic elements on the page. Version 3 includes graph creation.',
  BinaryFileFormat: '',
  ByteOrders: '',
  ReleaseDate: '',
  WithdrawnDate: '',
  ProvenanceSourceID: '165',
  ProvenanceName: 'Georgia Tech Research Institute / Georgia Tech Research Institute',
  ProvenanceSourceDate: '11 Jun 2012',
  ProvenanceDescription: 'http://mercator.elte.hu/~saman/hu/okt/AI7FileFormat.pdf Adobe has classified Illustrator versions 3.0 and 3.2 as the same file format. Version 3 includes graph creation.',
  LastUpdatedDate: '19 Jul 2013',
  FormatNote: '',
  FormatRisk: '',
  TechnicalEnvironment: '',
  FileFormatIdentifier:
   [ { Identifier: 'com.adobe.illustrator-image',
       IdentifierType: 'Apple Uniform Type Identifier' },
     { Identifier: 'fmt/418', IdentifierType: 'PUID' } ],
  Developers:
   { DeveloperID: '7',
     DeveloperName: '',
     OrganisationName: 'Adobe Systems Incorporated',
     DeveloperCompoundName: 'Adobe Systems Incorporated' },
  Support:
   { SupportID: '7',
     SupportName: '',
     OrganisationName: 'Adobe Systems Incorporated',
     SupportCompoundName: 'Adobe Systems Incorporated' },
  ExternalSignature:
   { ExternalSignatureID: '1241',
     Signature: 'ai',
     SignatureType: 'File extension' },
  InternalSignature:
   [ { SignatureID: '885',
       SignatureName: 'Adobe Illustrator 3.x v1',
       SignatureNote: 'The first line of the file is a unique comment that declares the file contains a Postscript program and identifies the version of the Document Structuring Conventions to which the document conforms as 2.0 or 3.0. The first line may also specify that the file conforms to a version of the Encapsulated PostScript File format (EPSF). The prolog contains %%DocumentNeededResources: and the continuation %%+ procset Adobe_Illustrator_AI3 or %%+procset Adobe_IllustratorA_AI3',
       ByteSequence:
        { ByteSequenceID: '1109',
          PositionType: 'Absolute from BOF',
          Offset: '0',
          MaxOffset: '0',
          IndirectOffsetLocation: '',
          IndirectOffsetLength: '',
          Endianness: '',
          ByteSequenceValue: '252150532D41646F62652D322E30{16-512}2525446F63756D656E744E65656465645265736F75726365733A{1-512}25252B2070726F637365742041646F62655F496C6C7573747261746F72(5F414933|415F414933)' } },
     { SignatureID: '886',
       SignatureName: 'Adobe Illustrator 3.x v2',
       SignatureNote: 'The first line of the file is a unique comment that declares the file contains a Postscript program and identifies the version of the Document Structuring Conventions to which the document conforms as 2.0 or 3.0. The prolog did not contain %%DocumentNeededResources: but did contain %%DocumentSuppliedResources: and the continuation %%+ procset Adobe_Illustrator_AI3 or %%+procset Adobe_IllustratorA_AI3',
       ByteSequence:
        { ByteSequenceID: '1110',
          PositionType: 'Absolute from BOF',
          Offset: '0',
          MaxOffset: '0',
          IndirectOffsetLocation: '',
          IndirectOffsetLength: '',
          Endianness: '',
          ByteSequenceValue: '252150532D41646F62652D322E30{16-512}2525446F63756D656E74537570706C6965645265736F75726365733A{1-512}25252B2070726F637365742041646F62655F496C6C7573747261746F72(5F414933|415F414933)' } },
     { SignatureID: '900',
       SignatureName: 'Adobe Illustrator 3.x v3',
       SignatureNote: 'The first line of the file is a unique comment that declares the file contains a Postscript program and identifies the version of the Document Structuring Conventions to which the document conforms as 2.0 or 3.0. The first line may also specify that the file conforms to a version of the Encapsulated PostScript File format (EPSF). The prolog contains %%DocumentNeededResources: and the continuation %%+ procset Adobe_Illustrator_AI3 or %%+procset Adobe_IllustratorA_AI3',
       ByteSequence:
        { ByteSequenceID: '1124',
          PositionType: 'Absolute from BOF',
          Offset: '0',
          MaxOffset: '0',
          IndirectOffsetLocation: '',
          IndirectOffsetLength: '',
          Endianness: '',
          ByteSequenceValue: '252150532D41646F62652D332E30{16-512}2525446F63756D656E744E65656465645265736F75726365733A{1-512}25252B2070726F637365742041646F62655F496C6C7573747261746F72(5F414933|415F414933)' } },
     { SignatureID: '901',
       SignatureName: 'Adobe Illustrator 3.x v4',
       SignatureNote: 'The first line of the file is a unique comment that declares the file contains a Postscript program and identifies the version of the Document Structuring Conventions to which the document conforms as 2.0 or 3.0. The prolog did not contain %%DocumentNeededResources: but did contain %%DocumentSuppliedResources: and the continuation %%+ procset Adobe_Illustrator_AI3 or %%+procset Adobe_IllustratorA_AI3',
       ByteSequence:
        { ByteSequenceID: '1125',
          PositionType: 'Absolute from BOF',
          Offset: '0',
          MaxOffset: '0',
          IndirectOffsetLocation: '',
          IndirectOffsetLength: '',
          Endianness: '',
          ByteSequenceValue: '252150532D41646F62652D332E30{16-512}2525446F63756D656E74537570706C6965645265736F75726365733A{1-512}25252B2070726F637365742041646F62655F496C6C7573747261746F72(5F414933|415F414933)' } } ],
  RelatedFormat:
   [ { RelationshipType: 'Has lower priority than',
       RelatedFormatID: '1201',
       RelatedFormatName: 'Adobe Illustrator',
       RelatedFormatVersion: '4.0' },
     { RelationshipType: 'Has priority over',
       RelatedFormatID: '86',
       RelatedFormatName: 'Encapsulated PostScript File Format',
       RelatedFormatVersion: '1.2' },
     { RelationshipType: 'Has priority over',
       RelatedFormatID: '331',
       RelatedFormatName: 'Encapsulated PostScript File Format',
       RelatedFormatVersion: '3' },
     { RelationshipType: 'Has priority over',
       RelatedFormatID: '332',
       RelatedFormatName: 'Encapsulated PostScript File Format',
       RelatedFormatVersion: '2.0' },
     { RelationshipType: 'Has priority over',
       RelatedFormatID: '771',
       RelatedFormatName: 'PostScript',
       RelatedFormatVersion: '2.0' },
     { RelationshipType: 'Has priority over',
       RelatedFormatID: '773',
       RelatedFormatName: 'PostScript',
       RelatedFormatVersion: '3.0' } ] }


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

namespace Altavant.Fusion.Layouting
{
	using System.Collections.Generic;
	using Fusion.Core.Data;

	public class LayoutProvider : IRetainable
	{
		public delegate Layout OnCreateLayoutDelegate(int id);

		private Dictionary<int, LayoutCollection> _entries;
		private int _retainCounter;
		private OnCreateLayoutDelegate _onCreateLayout;

		public LayoutProvider()
		{
			_retainCounter = 1;
		}

		public OnCreateLayoutDelegate OnCreateLayout
		{
			get
			{
				return _onCreateLayout;
			}
			set
			{
				_onCreateLayout = value;
			}
		}

		public int RetainCounter
		{
			get
			{
				return _retainCounter;
			}
		}

		public void Retain()
		{
			if (_retainCounter > 0)
				_retainCounter++;
		}

		public Layout GetLayout(int id)
		{
			if (_entries == null)
				_entries = new Dictionary<int, LayoutCollection>();

			Layout layout = null;
			LayoutCollection layouts = null;

			if (_entries.ContainsKey(id))
			{
				layouts = _entries[id];
			}
			else
			{
				layouts = new LayoutCollection();

				_entries.Add(id, layouts);
			}

			if (layouts.Count > 0)
			{
				foreach (Layout l in layouts)
				{
					if (l.RetainCounter == 1)
					{
						layout = l;

						break;
					}
				}
			}

			if ((layout == null) && (_onCreateLayout != null))
			{
				layout = _onCreateLayout(id);

				if (layout != null)
					layouts.Add(layout);
			}

			if (layout != null)
				layout.Retain();

			return layout;
		}

		public void ReleaseLayout(Layout layout)
		{
			layout.Release();
		}

		public void Release()
		{
			if (_retainCounter > 0)
			{
				_retainCounter--;

				if (_retainCounter == 0)
				{
					if (_entries != null)
					{
						foreach (var entry in _entries)
						{
							LayoutCollection layouts = entry.Value;

							foreach (Layout layout in layouts)
							{
								layout.Release();
							}
						}

						_entries = null;
					}
				}
			}
		}
	}
}


text:
sigma.parsers.json
==================

Plugin developed by [Alexis Jacomy](https://github.com/jacomyal).

---

This plugin provides a single function, `sigma.parsers.json()`, that will load a JSON encoded file, parse it, eventually instanciate sigma and fill the graph with the `graph.read()` method. The main goal is to avoid using jQuery only to load an external JSON file.

The most basic way to use this helper is to call it with a path and a sigma configuration object. It will then instanciate sigma, but after having added the graph into the config object.

````javascript
sigma.parsers.json(
  'myGraph.json',
  { container: 'myContainer' }
);
````

It is also possible to update an existing instance's graph instead.

````javascript
sigma.parsers.json(
  'myGraph.json',
  myExistingInstance,
  function() {
    myExistingInstance.refresh();
  }
);
````


text:
using System;
using System.Collections.Generic;

namespace Flooder.CircuitBreaker
{
    public class CircuitBreakerStateStore : ICircuitBreakerStateStore
    {
        private IList<Exception> _exceptions;
        private Exception _exception;
        private DateTimeOffset _now;

        public CircuitBreakerStateStore()
        {
            _exceptions = new List<Exception>();
            _exception  = null;
            _now        = DateTimeOffset.Now;
            State       = CircuitBreakerState.Close;
        }

        public CircuitBreakerState State { get; private set; }

        public Exception LastException { get { return _exception; } }

        public DateTimeOffset LastStateChangedDate { get { return _now; } }

        public void Trip(Exception ex)
        {
            _exceptions.Add(ex);
            _exception = ex;
            _now       = DateTimeOffset.Now;
            State      = CircuitBreakerState.Open;
        }

        public void Reset()
        {
            _now  = DateTimeOffset.Now;
            State = CircuitBreakerState.Close;
        }

        public void HalfOpen()
        {
            _now  = DateTimeOffset.Now;
            State = CircuitBreakerState.HalfOpen;
        }

        public bool IsClosed { get { return State == CircuitBreakerState.Close; } }
    }
}