text:
using System;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Avalonia.VisualTree;
using Xunit;

namespace Avalonia.Markup.Xaml.UnitTests.MarkupExtensions
{
    public class StaticResourceExtensionTests : XamlTestBase
    {
        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
    </UserControl.Resources>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Attached_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <x:Int32 x:Key='col'>5</x:Int32>
    </UserControl.Resources>

    <Border Name='border' Grid.Column='{StaticResource col}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            Assert.Equal(5, Grid.GetColumn(border));
        }

        [Fact]
        public void StaticResource_From_Style_Can_Be_Assigned_To_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Styles>
        <Style>
            <Style.Resources>
                <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
            </Style.Resources>
        </Style>
    </UserControl.Styles>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_From_Application_Can_Be_Assigned_To_Property_In_Window()
        {
            using (StyledWindow())
            {
                Application.Current.Resources.Add("brush", new SolidColorBrush(0xff506070));

                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Border Name='border' Background='{StaticResource brush}'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var border = window.FindControl<Border>("border");

                var brush = (SolidColorBrush)border.Background;
                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_From_MergedDictionary_Can_Be_Assigned_To_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary>
                    <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_From_MergedDictionary_In_Style_Can_Be_Assigned_To_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Styles>
        <Style>
            <Style.Resources>
                <ResourceDictionary>
                    <ResourceDictionary.MergedDictionaries>
                        <ResourceDictionary>
                            <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
                        </ResourceDictionary>
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
            </Style.Resources>
        </Style>
    </UserControl.Styles>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_From_Application_Can_Be_Assigned_To_Property_In_UserControl()
        {
            using (UnitTestApplication.Start(TestServices.StyledWindow))
            {
                Application.Current.Resources.Add("brush", new SolidColorBrush(0xff506070));

                var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

                var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
                var border = userControl.FindControl<Border>("border");

                // We don't actually know where the global styles are until we attach the control
                // to a window, as Window has StylingParent set to Application.
                var window = new Window { Content = userControl };
                window.Show();

                var brush = (SolidColorBrush)border.Background;
                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Setter()
        {
            using (StyledWindow())
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Window.Resources>
        <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
    </Window.Resources>
    <Window.Styles>
        <Style Selector='Button'>
            <Setter Property='Background' Value='{StaticResource brush}'/>
        </Style>
    </Window.Styles>
    <Button Name='button'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var button = window.FindControl<Button>("button");
                var brush = (SolidColorBrush)button.Background;

                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_From_Style_Can_Be_Assigned_To_Setter()
        {
            using (StyledWindow())
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Window.Styles>
        <Style>
            <Style.Resources>
                <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
            </Style.Resources>
        </Style>
        <Style Selector='Button'>
            <Setter Property='Background' Value='{StaticResource brush}'/>
        </Style>
    </Window.Styles>
    <Button Name='button'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var button = window.FindControl<Button>("button");
                var brush = (SolidColorBrush)button.Background;

                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Setter_In_Styles_File()
        {
            var styleXaml = @"
<Styles xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Styles.Resources>
        <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
    </Styles.Resources>

    <Style Selector='Border'>
        <Setter Property='Background' Value='{StaticResource brush}'/>
    </Style>
</Styles>";

            using (StyledWindow(assets: ("test:style.xaml", styleXaml)))
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Window.Styles>
        <StyleInclude Source='test:style.xaml'/>
    </Window.Styles>
    <Border Name='border'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var border = window.FindControl<Border>("border");
                var brush = (SolidColorBrush)border.Background;

                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Resource_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <Color x:Key='color'>#ff506070</Color>
        <SolidColorBrush x:Key='brush' Color='{StaticResource color}'/>
    </UserControl.Resources>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Resource_Property_In_Styles_File()
        {
            var xaml = @"
<Styles xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Styles.Resources>
        <Color x:Key='color'>#ff506070</Color>
        <SolidColorBrush x:Key='brush' Color='{StaticResource color}'/>
    </Styles.Resources>
</Styles>";

            var styles = (Styles)AvaloniaRuntimeXamlLoader.Load(xaml);
            var brush = (SolidColorBrush)styles.Resources["brush"];

            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Property_In_ControlTemplate_In_Styles_File()
        {
            var styleXaml = @"
<Styles xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Styles.Resources>
        <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
    </Styles.Resources>

    <Style Selector='Button'>
        <Setter Property='Template'>
            <ControlTemplate>
                <Border Name='border' Background='{StaticResource brush}'/>
            </ControlTemplate>
        </Setter>
    </Style>
</Styles>";

            using (StyledWindow(assets: ("test:style.xaml", styleXaml)))
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <Window.Styles>
        <StyleInclude Source='test:style.xaml'/>
    </Window.Styles>
    <Button Name='button'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var button = window.FindControl<Button>("button");

                window.Show();

                var border = (Border)button.GetVisualChildren().Single();
                var brush = (SolidColorBrush)border.Background;

                Assert.Equal(0xff506070, brush.Color.ToUint32());
            }
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_ItemTemplate_Property()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <DataTemplate x:Key='PurpleData'>
          <TextBlock Text='{Binding Name}' Background='Purple'/>
        </DataTemplate>
    </UserControl.Resources>

    <ListBox Name='listBox' ItemTemplate='{StaticResource PurpleData}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var listBox = userControl.FindControl<ListBox>("listBox");

            Assert.NotNull(listBox.ItemTemplate);
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Converter()
        {
            using (StyledWindow())
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
             xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.MarkupExtensions;assembly=Avalonia.Markup.Xaml.UnitTests'>
    <Window.Resources>
        <local:TestValueConverter x:Key='converter' Append='bar'/>
    </Window.Resources>

    <TextBlock Name='textBlock' Text='{Binding Converter={StaticResource converter}}'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
                var textBlock = window.FindControl<TextBlock>("textBlock");

                window.DataContext = "foo";
                window.ApplyTemplate();

                Assert.Equal("foobar", textBlock.Text);
            }
        }

        [Fact]
        public void StaticResource_Can_Be_Assigned_To_Binding_Converter_In_DataTemplate()
        {
            using (StyledWindow())
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
             xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.MarkupExtensions;assembly=Avalonia.Markup.Xaml.UnitTests'>
    <Window.Resources>
        <local:TestValueConverter x:Key='converter' Append='bar'/>
        <DataTemplate x:Key='PurpleData'>
          <TextBlock Name='textBlock' Text='{Binding Converter={StaticResource converter}}'/>
        </DataTemplate>
    </Window.Resources>

    <ContentPresenter Name='presenter' Content='foo' ContentTemplate='{StaticResource PurpleData}'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);

                window.DataContext = "foo";
                var presenter = window.FindControl<ContentPresenter>("presenter");

                window.Show();

                var textBlock = (TextBlock)presenter.GetVisualChildren().Single();

                Assert.NotNull(textBlock);
                Assert.Equal("foobar", textBlock.Text);
            }
        }

        [Fact]
        public void StaticResource_Is_Correctly_Chosen_From_Within_DataTemplate()
        {
            // this tests if IAmbientProviders in DataTemplate contexts are in correct order
            // if they wouldn't be, Purple brush would be bound to
            using (StyledWindow())
            {
                var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
             xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.MarkupExtensions;assembly=Avalonia.Markup.Xaml.UnitTests'>
    <Window.Resources>
        <local:TestValueConverter x:Key='converter' Append='-bar'/>
        <SolidColorBrush x:Key='brush' Color='Purple'/>
        <DataTemplate x:Key='WhiteData'>
          <Border>
            <Border.Resources>
              <SolidColorBrush x:Key='brush' Color='White'/>
            </Border.Resources>
            <TextBlock Name='textBlock' Text='{Binding Color, Source={StaticResource brush}, Converter={StaticResource converter}}' Foreground='{StaticResource brush}' />
          </Border>
        </DataTemplate>
    </Window.Resources>

    <ContentPresenter Content='foo' ContentTemplate='{StaticResource WhiteData}'/>
</Window>";

                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);

                window.Show();

                var textBlock = window.GetVisualDescendants().OfType<TextBlock>().Single();

                Assert.NotNull(textBlock);
                Assert.Equal("White-bar", textBlock.Text);
            }
        }

        [Fact]
        public void Control_Property_Is_Not_Updated_When_Parent_Is_Changed()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
    </UserControl.Resources>

    <Border Name='border' Background='{StaticResource brush}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());

            userControl.Content = null;

            brush = (SolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        [Fact]
        public void Automatically_Converts_Color_To_SolidColorBrush()
        {
            var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
             xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
    <UserControl.Resources>
        <Color x:Key='color'>#ff506070</Color>
    </UserControl.Resources>

    <Border Name='border' Background='{StaticResource color}'/>
</UserControl>";

            var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
            var border = userControl.FindControl<Border>("border");

            var brush = (ISolidColorBrush)border.Background;
            Assert.Equal(0xff506070, brush.Color.ToUint32());
        }

        private IDisposable StyledWindow(params (string, string)[] assets)
        {
            var services = TestServices.StyledWindow.With(
                assetLoader: new MockAssetLoader(assets),
                theme: () => new Styles
                {
                    WindowStyle(),
                });

            return UnitTestApplication.Start(services);
        }

        private Style WindowStyle()
        {
            return new Style(x => x.OfType<Window>())
            {
                Setters =
                {
                    new Setter(
                        Window.TemplateProperty,
                        new FuncControlTemplate<Window>((x, scope) =>
                            new ContentPresenter
                            {
                                Name = "PART_ContentPresenter",
                                [!ContentPresenter.ContentProperty] = x[!Window.ContentProperty],
                            }.RegisterInNameScope(scope)))
                }
            };
        }
    }
}


text:
from __future__ import absolute_import, print_function

import inspect

from .index.reader import Reader
from ._patch_helpers import inspect_restored
from ._types import CInspectObject, PythonObject, get_cinspect_object

def getfile(obj, index_path=None):
    if not isinstance(obj, CInspectObject):
        obj = get_cinspect_object(obj)

    if isinstance(obj, PythonObject):
        with inspect_restored():
            path = inspect.getfile(obj.obj)

    else:
        path = Reader(index_path).get_file(obj)

    return path

def getsource(obj, index_path=None):
    if not isinstance(obj, CInspectObject):
        obj = get_cinspect_object(obj)

    if isinstance(obj, PythonObject):
        with inspect_restored():
            source = inspect.getsource(obj.obj)

    else:
        source = Reader(index_path).get_source(obj)

    return source

redpajama_set_name: RedPajamaGithub


text:
class PostsController < ApplicationController
	def new
		@post = Post.new
	end

	def edit
  	@post = Post.find(params[:id])
	end

	def update
	  @post = Post.find(params[:id])

	  if @post.update(post_params)
	    redirect_to @post
	  else
	    render 'edit'
	  end
	end

	def create
	  @post = Post.new(post_params)

	  @post.save

	  if @post.save
	    redirect_to @post
	  else
	    render 'new'
	  end
	end

	def show
	  @post = Post.find(params[:id])
	end

	def index
		@posts = Post.all
		@posts = @posts.paginate(:per_page => 5, :page => params[:page])
	end

	def destroy
	  @post = Post.find(params[:id])
	  @post.destroy

	  redirect_to posts_path
	end

	private
	  def post_params
	    params.require(:post).permit(:title, :text)
	  end

end


text:
require 'backports/tools/make_block_optional'

Backports.make_block_optional Array, :each_index, :test_on => [42]


text:
package com.yozio.cordova;

import android.content.Intent;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.yozio.android.Yozio;

import java.util.HashMap;

public final class YozioPlugin extends CordovaPlugin {

    private static boolean isNewInstall = false;

    public static void setIsNewInstall(boolean value) {
        isNewInstall = value;
    }

    private static boolean wasOpenedViaDeepLink = false;

    @Override
    protected void pluginInitialize() {

        // Set the flag so we know that the most recent launch was via a deep link.
        HashMap<String, Object> deepLinkMetadata = Yozio.getMetaData(cordova.getActivity().getIntent());
        wasOpenedViaDeepLink = deepLinkMetadata != null && deepLinkMetadata.size() > 0;

        Yozio.YOZIO_ENABLE_LOGGING = true;
        Yozio.YOZIO_READ_TIMEOUT = 7000;

        Yozio.initialize(cordova.getActivity());
    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // Set the flag so we know that the most recent launch was via a deep link.
        HashMap<String, Object> deepLinkMetadata = Yozio.getMetaData(intent);
        wasOpenedViaDeepLink = deepLinkMetadata != null && deepLinkMetadata.size() > 0;

        // We re-initialize here after explicitly setting the intent because Yozio's SDK is looking
        // for deep link metadata on the intent in the initialize call (see handleYozioDeeplink).
        // This allows a deep link launch into a backgrounded app to persist and track the metadata.
        cordova.getActivity().setIntent(intent);
        Yozio.initialize(cordova.getActivity());
    }

    @Override
    public void onPause(boolean multitasking) {
        wasOpenedViaDeepLink = false;
    }

    @Override
    public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {

        if (action == null) {
            return false;
        }

        if (action.equals("getIsNewInstall")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.getIsNewInstall(callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("getWasOpenedViaDeepLink")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.getWasOpenedViaDeepLink(callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("getInstallMetadata")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.getInstallMetadata(callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("getLastDeeplinkMetadata")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.getLastDeeplinkMetadata(callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("trackSignup")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.trackSignup(callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("trackPayment")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.trackPayment(args, callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else if (action.equals("trackEvent")) {

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        YozioPlugin.this.trackEvent(args, callbackContext);
                    }
                    catch (Exception exception) {
                        callbackContext.error("YozioPlugin uncaught exception: " + exception.getMessage());
                    }
                }
            });

            return true;
        }
        else {
            // The given action was not handled above.
            return false;
        }
    }

    private void getIsNewInstall(final CallbackContext callbackContext) throws JSONException {
        callbackContext.success(Boolean.toString(isNewInstall));
    }

    private void getWasOpenedViaDeepLink(final CallbackContext callbackContext) throws JSONException {
        callbackContext.success(Boolean.toString(wasOpenedViaDeepLink));
    }

    private void getInstallMetadata(final CallbackContext callbackContext) throws JSONException {

        // Delegate to the Yozio SDK.
        HashMap<String, Object> metadata = Yozio.getInstallMetaDataAsHash(cordova.getActivity().getApplicationContext());

        // Add a "isNewInstall" flag to the metadata for convenience so only one call has to
        // be made to get both the metadata and this flag.
        metadata.put("isNewInstall", isNewInstall);

        callbackContext.success(new JSONObject(metadata));
    }

    private void getLastDeeplinkMetadata(final CallbackContext callbackContext) throws JSONException {

        // Delegate to the Yozio SDK.
        HashMap<String, Object> metadata = Yozio.getLastDeeplinkMetaDataAsHash(cordova.getActivity().getApplicationContext());

        callbackContext.success(new JSONObject(metadata));
    }

    private void trackSignup(final CallbackContext callbackContext) throws JSONException {

        // Delegate to the Yozio API.
        Yozio.trackSignUp(cordova.getActivity().getApplicationContext());

        callbackContext.success();
    }

    private void trackPayment(JSONArray args, final CallbackContext callbackContext) throws JSONException {

        // Ensure we have the correct number of arguments.
        if (args.length() != 1) {
            callbackContext.error("An amount is required.");
            return;
        }

        // Obtain the arguments.
        double amount = args.getDouble(0);

        // Delegate to the Yozio API.
        Yozio.trackPayment(cordova.getActivity().getApplicationContext(), amount);

        callbackContext.success();
    }

    private void trackEvent(JSONArray args, final CallbackContext callbackContext) throws JSONException {

        // Ensure we have the correct number of arguments.
        if (args.length() != 2) {
            callbackContext.error("An event name and amount are required.");
            return;
        }

        // Obtain the arguments.
        String eventName = args.getString(0);
        double value = args.getDouble(1);

        // Validate the arguments.

        if (eventName == null || eventName.equals("")) {
            callbackContext.error("An event name is required.");
        }

        // Delegate to the Yozio API.
        Yozio.trackCustomEvent(cordova.getActivity().getApplicationContext(), eventName, value);

        callbackContext.success();
    }
}


text:
package com.linkedin.metadata.builders.search;

import com.linkedin.common.DatasetUrnArray;
import com.linkedin.common.FabricType;
import com.linkedin.common.urn.DataPlatformUrn;
import com.linkedin.common.urn.DataProcessUrn;
import com.linkedin.common.urn.DatasetUrn;
import com.linkedin.dataprocess.DataProcessInfo;
import com.linkedin.metadata.aspect.DataProcessAspect;
import com.linkedin.metadata.aspect.DataProcessAspectArray;
import com.linkedin.metadata.search.DataProcessDocument;
import com.linkedin.metadata.snapshot.DataProcessSnapshot;
import java.util.List;
import org.testng.annotations.Test;

import static org.testng.Assert.*;

public class DataProcessIndexBuilderTest {

  @Test
  public void testGetDocumentsToUpdateFromDataProcessSnapshot() {
    DataProcessUrn dataProcessUrn = new DataProcessUrn("Azure Data Factory", "ADFJob1", FabricType.PROD);
    DataProcessInfo dataProcessInfo = new DataProcessInfo();

    DatasetUrn inputDatasetUrn = new DatasetUrn(new DataPlatformUrn("HIVE"), "SampleInputDataset", FabricType.DEV);
    DatasetUrnArray inputs = new DatasetUrnArray();
    inputs.add(inputDatasetUrn);
    dataProcessInfo.setInputs(inputs);
    DatasetUrn outputDatasetUrn = new DatasetUrn(new DataPlatformUrn("HIVE"), "SampleOutputDataset", FabricType.DEV);
    DatasetUrnArray outputs = new DatasetUrnArray();
    outputs.add(outputDatasetUrn);
    dataProcessInfo.setOutputs(outputs);

    DataProcessAspect dataProcessAspect = new DataProcessAspect();
    dataProcessAspect.setDataProcessInfo(dataProcessInfo);
    DataProcessAspectArray dataProcessAspectArray = new DataProcessAspectArray();
    dataProcessAspectArray.add(dataProcessAspect);
    DataProcessSnapshot dataProcessSnapshot =
        new DataProcessSnapshot().setUrn(dataProcessUrn).setAspects(dataProcessAspectArray);

    List<DataProcessDocument> actualDocs = new DataProcessIndexBuilder().getDocumentsToUpdate(dataProcessSnapshot);
    assertEquals(actualDocs.size(), 2);
    assertEquals(actualDocs.get(0).getInputs().get(0), inputDatasetUrn);
    assertEquals(actualDocs.get(0).getOutputs().get(0), outputDatasetUrn);
    assertEquals(actualDocs.get(0).getUrn(), dataProcessUrn);
    assertEquals(actualDocs.get(1).getUrn(), dataProcessUrn);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/desc_tv"
        android:layout_width="fill_parent"
        android:layout_height="120dp"
        android:padding="5dp"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/set_vertical"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="5dp"
        android:text="设置单屏壁纸"/>

    <Button
        android:id="@+id/set_horizontal"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_marginTop="5dp"
        android:text="设置滚屏壁纸"/>
</LinearLayout>


text:
import * as React from 'react';
import { DashboardSection, DashboardSectionProps } from '../dashboard';
import { SpotifyCurrentlyPlaying } from './spotify-currently-playing';
import { SpotifyTopTrackItem } from './spotify-top-track-item';
import { useSpotifyTopTracks } from './use-spotify-top-tracks';

export type SpotifyDashboardProps = Omit<DashboardSectionProps, 'title'>;

export const SpotifyDashboard: React.FC<SpotifyDashboardProps> = ({ ...rest }) => {
  const { data } = useSpotifyTopTracks();

  const renderTracks = () => {
    if (data) {
      return data.tracks.map((item, i) => (
        <SpotifyTopTrackItem key={item.id} index={i + 1} track={item} />
      ));
    }

    return Array.from({ length: 10 }).map((_, i) => (
      <SpotifyTopTrackItem key={i} index={i + 1} isSkeleton />
    ));
  };

  return (
    <DashboardSection title="Music" {...rest}>
      <SpotifyCurrentlyPlaying />

Top tracks

{renderTracks()}

    </DashboardSection>
  );
};


text:
using namespace std;

template<class mytype>
class BOOK              		//template type BOOK class
{
private:
        static int count;       		//declaration of static variable to set ID for books
public:
        BOOK<mytype> *next, *prev;      //BOOK type pointers; 'next' to store address of next BOOK & 'prev' to store address of previous BOOK
        int ID;                 		//variable to store ID of a book
        string bookName;				//string to store name of a book
        string author;  				//string to store name of author of book
        string book_type;				//string to store type of a book
        long copies;    				//variable to store no. of copies a book
        long price;             		//variable to store price of a book
        string status;  				//to store status of a book, either its in stock or not
        dynamicQueue<string> book_queue;        //created an object of queueClass as data member of each Book

        BOOK()  //Constructor 0 argument to initialize everything
        {
                count++;        	//increment counter
                ID=count;       	//assign counter to ID to be ID of newly added book

                next = prev = 0;	//Initializing both pointers to 0

                bookName = "\0";
                author = "\0";
                book_type = "\0";
                copies = price = 0;
                status= "InStock";
        }

        BOOK(BOOK *n =  0, BOOK *p = 0, string book = "\0", string athr = "\0", string buk_type = "\0", long cp=0, long pr=0) //Constructor multiple arguments, to store information about a book
        {
                next = n;               //store contents of user-given value n into next
                prev = p;               //store contents of user-given value p into previous

                bookName = book;		//store contents of user-given value book into bookName
                author = athr;  		//store contents of user-given value athr into author
                book_type = buk_type;	//store contents of user-given value buk_type into book_type
                copies = cp;    		//store contents of user-given value cp into copies
                price = pr;             //store contents of user-given value pr into price

                if(copies>0)
                        status= "InStock";
                else if (copies<1)
                {
                        status= "OutOfStock";
                }
                count++;                //increment counter
                ID=count;               //assign counter to ID to be ID of newly added book
        }
};

template <class mytype>    				// declaration of static variable to set ID for books
int BOOK<mytype>::count=0;

template <class mytype>
class BookStoreDataBase  				//Class of (Doubly Linked List based) Database of Book Store
{
private:
        BOOK<mytype> *head;             //BOOK type pointer head to store address of 1st BOOK of list
        BOOK<mytype> *tail;             //BOOK type pointer tail to store address of last BOOK of list
        BOOK<mytype> *find_BOOK(string book_name);      //Address returning Function to find a specific BOOK with a certain book name
public:

        BookStoreDataBase()             //Constructor to initialize head and tail pointer
        {
                head = tail = 0;
        }
        ~BookStoreDataBase();                           //Destructor to be defined outside class

        bool is_Empty();                                //Function to check if DataBase is empty

        void addBook(string book, string athr, string buk_type, long cp, long pr);      //Function to add a book to database with user given info of book
        void editBook(int signal, string book, string athr, string buk_type, long cp, long pr); //Function to edit a book's information

        bool deletefromDLLhead();               //Function to delete a BOOK from head of list
        bool deletefromDLLtail();               //Function to delete a BOOK from tail of list
        bool delete_book(string book_name);		//Function to delete a specific book from list

        bool buy_book(string book_name);        //Function to buy a specific BOOK & update its containing information (data members)
        bool search_book(int srh, string book, string athr, string buk_type);   //Function to search a specific book in database/link list
        void set_stock(BOOK<mytype> *temp);		//Function to manage stock of a book/status of a book

        void create_queue(string book_name, string person); //Function to create queue for a book
        void print_queue(string book_name);					//Function to print queue of a specific book
        void manage_pending_queues(BOOK<mytype> *temp);		//function to manage any pending queue of a book

        void printbook(BOOK<mytype> *temp);     //Function to print a single book's info
        void print_allbooks();                  //Function to print complete database of books
        int total_BOOKs();                      //Function to tell total number of books created

        bool save_data();                       //Function to save (append) all database to file
		bool write_data();                      //Function to re-write all database to file & delete previous data

        void load_all_data();                   //Function to load all database from file
        void read_fromfile();                   //Functionn to read a batch of books from file.

		void queue_saving(BOOK<mytype> *temp);	//Function to save a book's queue in file on disk
		void queue_reading(BOOK<mytype> *temp, string bookName);					//Function to load a book's queue if it exists
};

template <class mytype>
bool BookStoreDataBase<mytype>::is_Empty()
{
        if(head==0)     //if head = 0, then database is empty
                return true;
        else
                return false;
}

template <class mytype>
BOOK<mytype>* BookStoreDataBase<mytype>::find_BOOK(string book_name)
{
        BOOK<mytype> *temp = head;      		//created a new BOOK pointer to copy head
        if(!is_Empty())
                while(temp->next!=0 && temp->bookName!=book_name)       //until Link list ends or data is found (& is used because search stops if data is found in a BOOK)
                {
                        temp=temp->next;		//move temp BOOK to next BOOK
                }
                return temp;
}

template <class mytype>
void BookStoreDataBase<mytype>::addBook(string book, string athr, string buk_type, long cp, long pr)
{
        if(is_Empty())  //If link list is empty, (for creation of 1st BOOK)
        {
                head = tail = new BOOK<mytype>(0, 0, book, athr, buk_type, cp, pr);     //Created a new BOOK and pointed both head & tail to temp
        }
        else                    //If link list is not empty, then
        {
                BOOK<mytype> *temp = new BOOK<mytype>(0, 0, book, athr, buk_type, cp, pr);      //Created a new BOOK
                tail->next=temp;                //stored address of temp in tail's next
                temp->prev=tail;                //stored address of tail in temp's previous
                tail = temp;                    //moved tail 1 step forward
        }
}

template <class mytype>
void BookStoreDataBase<mytype>::editBook(int signal, string book, string athr, string buk_type, long cp, long pr)
{
        BOOK<mytype> *temp = find_BOOK(book);
        if(signal==1)
        {
                temp->author=athr;
        }
        else if (signal==2)
        {
                temp->book_type=buk_type;
        }
        else if (signal==3)
        {
                temp->copies=cp;
                set_stock(temp);
        }
        else if (signal==4)
        {
                temp->price=pr;
        }
}

template <class mytype>
bool BookStoreDataBase<mytype>::deletefromDLLhead()
{
        if(!is_Empty())         //If Link List is not empty, then
        {
                if(head==tail)  //if both point to same BOOK, hence list has only 1 BOOK, then
                {
                        head=tail=0;    //Initialize both to 0
                        delete head;    //delete head
                        return true;
                }
                else                    //if list has multiple BOOKs, then
                {
                        head = head->next;      //move head to next BOOK
                        delete head->prev;      //delete address of previous BOOK
                        head->prev=0;           //Nullify head's previous
                        return true;
                }
        }       //If list is empty
        else
        {
                return false;
        }
}

template <class mytype>
bool BookStoreDataBase<mytype>::deletefromDLLtail()
{
        if(is_Empty())  //If Link List is empty then display error
        {
                return false;
        }
        else                    //If Link List is not empty, then
        {
                BOOK<mytype> *temp = head;      //created a new BOOK pointer (to copy head)

                if(head==tail)  //if both point to same BOOK, hence list has only 1 BOOK, then
                {
                        head=tail=0;    //Initialize both to 0
                        delete head;    //head deleted
                        return true;
                }
                else                    //if link list has multiple BOOKs
                {
                        tail=tail->prev;        //Move back tail 1 BOOK
                        delete tail->next;      //Delete address of last BOOK stored in tail's next
                        tail->next=0;           //Nullify tail's next
                        return true;
                }
        }
}

template <class mytype>
bool BookStoreDataBase<mytype>::delete_book(string book_name)
{
        if(is_Empty())
        {
                return false;
        }
        else
        {
                int verify;     //variable to verify deletion
                if(head->bookName==book_name)
                {
                        verify = deletefromDLLhead();
                        if (verify==1)
                        {
                                return true;
                        }
                        else if (verify==0)
                        {
                                return false;
                        }
                }
                else if (tail->bookName==book_name)
                {
                        verify = deletefromDLLtail();
                        if (verify==1)
                        {
                                return true;
                        }
                        else if (verify==0)
                        {
                                return false;
                        }
                }
                else
                {
                        BOOK<mytype> *temp = find_BOOK(book_name);
                        if(temp->bookName==book_name)
                        {
                                temp->prev->next=temp->next;            //put address of temp's next into 'next' of temp's previous node
                                temp->next->prev=temp->prev;            //put address of temp's previous node into 'previous' part of temp's next node
                                delete temp;            //Delete node

                                return true;
                        }
                        else
                        {
                                return false;
                        }
                }
        }
		return false;
}

template <class mytype>
bool BookStoreDataBase<mytype>::buy_book(string book_name)
{
        if(!is_Empty())
        {
                if(head->bookName==book_name)           	//if required book is first book
                {
                        if(head->status=="InStock")         //if book is in stock then, perform buy process
                        {
                                        head->copies--; 	//decrease 1 copy of book &
                                        set_stock(head);	// manage stock
                                        return true;
                        }
                        else if (head->status=="OutofStock"|| head->copies<1)	//else if book is not in stock then
                        {
                                return false;
                        }
                }
                else if(tail->bookName==book_name)	//else if specified data item is in 1st BOOK
                {
                        if(tail->status=="InStock")	//if book is in stock then, perform buy process
                        {
							tail->copies--; 	//decrease 1 copy of book &
                            set_stock(tail);	// manage stock
                            return true;
                        }
                        else if (tail->status=="OutofStock"|| tail->copies<1)	//else if book is not in stock then
                        {
                                return false;
                        }
                }
                else	//else if data item is in any middle BOOK
                {
                        BOOK<mytype> *temp = find_BOOK(book_name); 	//created a new BOOK pointer to store specific BOOK temp

                        if(temp->bookName==book_name)
                        {
                                if(temp->status=="InStock")         //if book is in stock then, perform buy process
                                {
                                                temp->copies--; 	//decrease 1 copy of book &
                                                set_stock(temp);	// manage stock
                                                return true;
                                }
                                else if (temp->status=="OutofStock" || temp->copies<1)	//else if book is not in stock then
                                {
                                        return false;
                                }
                        }
                }
				return false;
        }
		else
			return false;
}

template <class mytype>
bool BookStoreDataBase<mytype>::search_book(int srh, string book, string athr, string buk_type)
{
      if(!is_Empty())            // If list not empty
        {
                BOOK<mytype> *temp = head;      //created a copy of head
                if(srh==1)      //if search is by book name
                {
                        if(head->bookName==book)        //if required book is in head
                        {
                                printbook(head);        //print 1st book
                                return true;
                        }
                        else if (tail->bookName==book)	//else if required book is in tail
                        {
                                printbook(tail);        //print last book
                                return true;
                        }
                        else
                        {
                                while(temp!=tail && temp->bookName!=book)       //until list ends or book is found
                                {
                                        temp = temp->next;      //advance temp to next node
                                }
                                if(temp->bookName==book)        //if book found
                                {
                                        printbook(temp);        //then call function to print that book
                                        return true;
                                }
                                else //if book not found then display error
                                {
                                       // cout<<"ERROR:: Book Not Found with Name |"<<book<<"|";
                                        return false;
                                }
                        }
                }
                else if (srh==2)        //if search is by author name
                {
                        int n, stat=0;
                        while (temp!=tail)      //until list ends
                        {
                                n = temp->author.find(athr);
                                if(n!=-1)//if book found
                                {
                                        cout<<"\t\t\tBook Found. Press ENTER to Show Information...";   _getch();        stat++;
                                        printbook(temp);//then call function to print that book
                                }
                                temp = temp->next;      //advance temp to next node
                        }
                        n = temp->author.find(athr);
                        if(n!=-1)//if book found in last node
                        {
                                cout<<"\t\t\tBook Found. Press ENTER to Show Information...";   _getch();
                                printbook(temp);//then call function to print that book
                                return true;
                        }
                        if (stat>0)
                        {
                                return true;
                        }
                        else
                        {
                                return false;
                        }
                }
                else if (srh==3)        	//if search is by book type
                {
                        while (temp!=tail)	//until list ends or book is found
                        {
                                if(temp->book_type==buk_type)//if book found
                                {
                                        cout<<"\t\t\tBook Found. Press ENTER to Show Information...";   _getch();
                                        printbook(temp);//then call function to print that book
                                }
                                temp = temp->next;//advance temp to next node
                        }
                        if(temp->book_type==buk_type)//if book found
                        {
                                cout<<"\t\t\tBook Found. Press ENTER to Show Information...";   _getch();
                                printbook(temp);	//then call function to print that book
                                return true;
                        }
                        else	//if book not found then display error
                        {
                                return false;
                        }
                }
                else
                {
                        return false;
                }
        }
	  else return false;
}

template <class mytype>
void BookStoreDataBase<mytype>::set_stock(BOOK<mytype> *temp)
{
        if ((temp->copies) < 1) //if copies of a book are less then 1,
        {
                temp->status = "OutofStock";    //then change status of book
        }
        else if ((temp->copies) > 0)
        {
                temp->status = "InStock";
        }
}

template <class mytype>
void BookStoreDataBase<mytype>::create_queue(string book_name, string person)
{
        BOOK<mytype> *temp = find_BOOK(book_name);
        temp->book_queue.enqueue(person);
}

template <class mytype>
void BookStoreDataBase<mytype>::print_queue(string book_name)
{
        BOOK<mytype> *temp = find_BOOK(book_name);
        temp->book_queue.print_queue();
}

template <class mytype>
void BookStoreDataBase<mytype>::manage_pending_queues(BOOK<mytype> * temp)
{
        char choice;    //to store choice
        int counter;    //to store number of copies to be delivered
        cout<<"\n\n\tBook "<<temp->bookName<<" is "<<temp->status<<" & has a pending Queue. \n\t\tWould you like to settle it? (y/n): ";        cin>>choice;
        if(choice=='y')
        {
                inputagain:
                cout<<"\n\tCopies Available = "<<temp->copies<<"\tPeople in Queue = "<<temp->book_queue.total_items()<<"\n\t\tHow Much do you want to deliver?: ";      cin>>counter;
                if (counter > (temp->book_queue.total_items()) ) //for preventing wrong input
                {
                        cout<<"\n\t\t\t\t>>BAD ENTRY.. Try Again!\n";
                        goto inputagain;
                }
				if(counter!=0)
				{
					cout<<"\n\tCopy of Book "<<temp->bookName<<" sent to:\n ";
					for (int i = 1; i <= counter; i++)
					{
							temp->book_queue.dequeue();
							temp->copies--;
					}
				}
				else
				{
					cout<<"\nBooks not delievered to anyone!\n";
				}
        }
}

template <class mytype>
void BookStoreDataBase<mytype>::printbook(BOOK<mytype> *temp)
{
        cout<<"\nBook ID: "<<temp->ID<<"\n\tBook Name = "<<temp->bookName<<"\n\tAuthor = "<<temp->author<<"\n\tBook Type = "<<temp->book_type<<"\n\tTotal Copies = "<<temp->copies<<"\n\tPrice = "<<temp->price<<" PKR\n\tStatus = "<<temp->status<<endl; //print BOOK's contents
}

template <class mytype>
void BookStoreDataBase<mytype>::print_allbooks()
{
        if(is_Empty())	//Checking if Link List is empty
        {
                cout<<"\tERROR:: DataBase Is Empty!";
        }
        else            //If link list not empty, then
        {
                BOOK<mytype> *temp = head;      //Created a new BOOK pointer to copy head
                while(temp->next!=0)            //until temp's next pointer has Null (until link list ends)
                {
                        cout<<"\nBook ID: "<<temp->ID<<"\n\tBook Name = "<<temp->bookName<<"\n\tAuthor = "<<temp->author<<"\n\tBook Type = "<<temp->book_type<<"\n\tTotal Copies = "<<temp->copies<<"\n\tPrice = "<<temp->price<<" PKR\n\tStatus = "<<temp->status; //print BOOK's contents
                        if( (temp->copies > 0) && ! (temp->book_queue.is_Empty() ) )
                        {
                                manage_pending_queues(temp);
                        }
                        cout<<"\n\t\t\t Continue Reading DataBase? [Press Enter]";
                        _getch();
                        temp=temp->next;                        //move temp BOOK to next BOOK
                }
                cout<<"\nBook ID: "<<temp->ID<<"\n\tBook Name = "<<temp->bookName<<"\n\tAuthor = "<<temp->author<<"\n\tBook Type = "<<temp->book_type<<"\n\tTotal Copies = "<<temp->copies<<"\n\tPrice = "<<temp->price<<" PKR\n\tStatus = "<<temp->status;     //print last BOOK
                if( (temp->copies > 0) && ! (temp->book_queue.is_Empty() ) )
                        {
                                manage_pending_queues(temp);
                        }
        }
}

template <class mytype>
int BookStoreDataBase<mytype>::total_BOOKs()
{
        if(!is_Empty())         //If link list is not empty
        {
                int counter=0;  //variable to store counts of BOOKs in link list
                BOOK<mytype> *temp = head;      //created a BOOK pointer to copy head
                if(head==tail)  //If link list has just 1 BOOK,
                {
                        return 1;
                }
                else
                {
                        while(temp->next!=0)    //Until Link List ends
                        {
                                counter++;              //Increment counter by 1
                                temp=temp->next;        //move temp to next BOOK
                        }
                        counter++;
                        return counter;
                }
        }
        else    //If link list is empty, then
        {
                return 0;       //return 0
        }
}

template <class mytype>
bool BookStoreDataBase<mytype>::save_data()
{
        if(!is_Empty()) 		//if list is not empty
        {
                BOOK<mytype> *temp = head;   //created a copy of head
                ofstream file("database.txt", ios_base::app); 	//created file, to write at the end (append)
                while(temp != tail) 		//while list ends
                {
                        file<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<'\n';  //write all info
						queue_saving(temp);
                        temp = temp->next; 	//move temp to next node
                }
                file<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<'\n'; //for last book's info
                queue_saving(temp);
				return true; 	//to confirm sucessfull writing
        }
        else 	//if list is empty
        {
                return false; 	//to confirm error in writing
        }
}

template <class mytype>
bool BookStoreDataBase<mytype>::write_data()
{       if(!is_Empty()) 	//if list is not empty
        {
                BOOK<mytype> *temp = head;   //created a copy of head
                ofstream file("database.txt"); 	//created file, to delete previous data & write
                while(temp != tail) 		//while list ends
                {
                        file<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<'\n';  //write all info
                         queue_saving(temp);
						temp = temp->next; 		//move to next node
                }
                file<<temp->bookName<<' '<<temp->author<<' '<<temp->book_type<<' '<<temp->copies<<' '<<temp->price<<'\n'; //for last book's info
                 queue_saving(temp);
				return true;
        }
        else 	//if list is empty
        {
                return false;
        }

}

template <class mytype>
void BookStoreDataBase<mytype>::load_all_data()
{
        string bookName;	//string to store name of a book
        string author;  	//string to store name of author of book
        string book_type;	//string to store type of a book
        long copies;    	//variable to store no. of copies a book
        long price;         //variable to store price of a book
        string status;  	//to store status of a book, either its in stock or not

        stringstream mystr;

        ifstream file("database.txt");
        while(file>>bookName>>author>>book_type>>copies>>price)
        {
                mystr>>bookName>>author>>book_type>>copies>>price;

                BOOK<mytype> *temp = new BOOK<mytype>(0, 0, bookName, author, book_type, copies, price);
				queue_reading(temp, bookName);
                if(is_Empty())
                {
                        head = tail = temp;
                }
                else
                {
                        tail->next = temp;
                        temp->prev = tail;
                        tail = temp;
                }
        }
}

template <class mytype>
void BookStoreDataBase<mytype>::read_fromfile()
{
        string bookName;	//string to store name of a book
        string author;  	//string to store name of author of book
        string book_type;	//string to store type of a book
        long copies;    	//variable to store no. of copies a book
        long price;         //variable to store price of a book
        string status;  	//to store status of a book, either its in stock or not

        stringstream mystr;

        ifstream file("test.txt");
        while(file>>bookName>>author>>book_type>>copies>>price)
        {
                mystr>>bookName>>author>>book_type>>copies>>price;

                BOOK<mytype> *temp = new BOOK<mytype>(0, 0, bookName, author, book_type, copies, price);

                if(is_Empty())
                {
                        head = tail = temp;
                }
                else
                {
                        tail->next = temp;
                        temp->prev = tail;
                        tail = temp;
                }
        }
}

template <class mytype>
void BookStoreDataBase<mytype>::queue_saving(BOOK<mytype> *temp)
{
	if(!(temp->book_queue.is_Empty()))
	{
		int members = temp->book_queue.total_items();
		ofstream infile("queuemanager.txt", ios_base::app);
		infile<<temp->bookName<<' '<<members<<' ';
		while(!(temp->book_queue.is_Empty()))
		{
			infile<<temp->book_queue.return_dequeue()<<' ';
		}
		infile<<'\n';
	}
}

template <class mytype>
void BookStoreDataBase<mytype>::queue_reading(BOOK<mytype> *temp, string bookName)
{
	int total;
	string buk, person_name;
	stringstream read;

	ifstream file("queuemanager.txt");
	while(file>>buk>>total>>person_name)
	{
		read>>buk>>total>>person_name;
		{
			if(buk==bookName)
			{
				for(int i=1; i<=total; i++)
				{
					temp->book_queue.enqueue(person_name);
					file>>person_name;
				}
			}
		}
	}
}

template <class mytype>
BookStoreDataBase<mytype>::~BookStoreDataBase() //Destructor
{
        if(!is_Empty())
        {
                while(head!=0)
                {
                        deletefromDLLhead();
                }
        }
}


text:
/*
 * Do not modify this file. This file is generated from the lambda-2014-11-11.normal.json service model.
 */

using System;

namespace Amazon.Lambda.Model
{
    /// <summary>
    /// Configuration for accessing Amazon GetEventSource service
    /// </summary>
    public partial class GetEventSourceResponse : GetEventSourceResult
    {
        /// <summary>
        /// Gets and sets the GetEventSourceResult property.
        /// Represents the output of a GetEventSource operation.
        /// </summary>
        [Obsolete(@"This property has been deprecated. All properties of the GetEventSourceResult class are now available on the GetEventSourceResponse class. You should use the properties on GetEventSourceResponse instead of accessing them through GetEventSourceResult.")]
        public GetEventSourceResult GetEventSourceResult
        {
            get
            {
                return this;
            }
        }
    }
}


text:
using System;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;

namespace UPnPValidator
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ExceptionSink);
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventSink);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        public static void ExceptionSink(object sender, System.Threading.ThreadExceptionEventArgs args)
        {
            OpenSource.UPnP.AutoUpdate.ReportCrash(Application.ProductName, args.Exception.ToString());
            OpenSource.Utilities.InstanceTracker.GenerateExceptionFile("Exceptions-Validator.txt", args.Exception.ToString(), OpenSource.Utilities.InstanceTracker.VersionString);
        }

        public static void UnhandledExceptionEventSink(object sender, UnhandledExceptionEventArgs args)
        {
            OpenSource.UPnP.AutoUpdate.ReportCrash(Application.ProductName, ((Exception)args.ExceptionObject).ToString());
            OpenSource.Utilities.InstanceTracker.GenerateExceptionFile("Exceptions-Validator.txt", ((Exception)args.ExceptionObject).ToString(), OpenSource.Utilities.InstanceTracker.VersionString);
        }
    }
}


text:
## 2. Variables and Basic Types

### 2.1 primitive built-in types

- arithmetic types and a special type named void

- integral types and floating-point types

- ![02tab01](https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/graphics/02tab01.jpg)

- `bool` represents the truth values `true` and `false`

- `char` is the same size as a single machine byte

- `char16_t` and `char32_t` are for Unicode

- `long long` is new

- the smallest chunk of addressable memory is referred to as a "byte."

- on most machines a byte contains 8 bits and a word is either 32 or 64 bits

- typically, `float`s are in one word 32 btis, `double`s are in two words 64 bits, and `long double` s are either 3 or 4 words

- integral types may be signed or unsigned, former could include negative/postive/zero while latter only represents zero or above

- `unsigned int` is equal to `unsigned`

- unsigned type use all bits to represent the value, 8-bit `unsigned char` can hold [0, 255]

- `signed char` is guaranteed to hold [-127, 127], most modern machines allow [-128, 127]

- do not use plain `char` and `bool` in arithmetic expressions

- use `double` over `float`

- ```
  bool b = 42;            // b is true
  int i = b;              // i has value 1
  i = 3.14;               // i has value 3
  double pi = i;          // pi has value 3.0
  unsigned char c = -1;   // assuming 8-bit chars, c has value 255
  signed char c2 = 256;   // assuming 8-bit chars, the value of c2 is undefined
  ```

- assign an out-of-range value to an object of signed type, the result is undefined

- a value is known as literal because its value self-evident

- `20 /* decimal */ 024 /* octal */ 0x14 /* hexadecimal */`

- by default, decimal literals are signed while octal and hexadecimal literals can be either signed or unsigned

- floating-point literals include either a decimal point or an exponent

- by default, floating-point literals have type `double`

- single quotes is a literal of type `char`, double quotation is a string literal

- a null character is appended to every string literal, "A" represents an array of two characters

- ```c++
  // multiline string literal
  std::cout << "a really, really long string literal "
               "that spans two lines" << std::endl;
  ```

- escape sequence to represent nonprintable characters

- `true` and `false` are literals of type `bool`

- `nullptr`  is a pointer literal

### 2.2 variables

- a simple variable definition consists of a type specifier followed by a list of one or more variable names

- initialization is different from assignment

- ```c++
  int units_sold = 0;
  int units_sold = {0};
  int units_sold{0};
  int units_sold(0);
  ```

- default initialization when variables are defined without an initializer

- variables of built-in type defined inside a function are uninitialized

- separate compilation lets us split our programs into several files

- initialize every object of built-in type

- declaration and definition

- ```c++
  extern int i;   // declares but does not define i
  int j;          // declares and defines j
  extern double pi = 3.1416; // definition
  ```

- To use the same variable in multiple files, we must define that variable in one—and only one—file. Other files that use that variable must declare—but not define—that variable.

- identifiers can be composed of letters, digits and underscore character

- C++ keywords

- ![02tab03](https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/graphics/02tab03.jpg)

- C++ alternative operator names

- ![02tab04](https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/graphics/02tab04.jpg)

- conventions

  - variable names are lowercase
  - classes beigin with an uppercase letter
  - visually distinguish each word in identifiers

- scope is a part of the program which a name has a particular meaning, most sopces are in curly braces

- `main` has global scope

- nested scopes have inner scope and outer scope

- `::` scope operator, global scope has no name

### 2.3 compound types

- a type that is defined in terms of another type, most used two are references and pointers

- a declaration is a base type followed by a list of declarators

- lvalue reference and rvalue reference

- a reference defines an alternative name for an object

- ```c++
  int ival = 1024;
  int &refVal = ival;  // refVal refers to (is another name for) ival
  int &refVal2  // error: a reference must be initialized
  ```

- reference can't be rebind, so it must be initialized

- no reference to a reference

- the type of reference must match exactly with the object it referred

- a pointer is an object in its own right

- pointers need not be initialized at the time it is defined

- ```c++
  int *ip1, *ip2;  // both ip1 and ip2 are pointers to int
  double dp, *dp2; // dp2 is a pointer to double; dp is a double
  ```

- a pointer holds the address of another object, use address-of operator `&`

- we may not define a pointer to a reference

- ```c++
  double dval;
  double *pd = &dval;  // ok: initializer is the address of a double
  double *pd2 = pd;    // ok: initializer is a pointer to double
  int *pi = pd;  // error: types of pi and pd differ
  pi = &dval;    // error: assigning the address of a double to a pointer to int
  ```

- pointer value

  - point to an object
  - point the the location past the end of an object
  - null pointer
  - invalid

- dereference operator `*`

- ```c++
  int ival = 42;
  int *p = &ival; // p holds the address of ival; p is a pointer to ival
  cout << *p;     // * yields the object to which p points; prints 42
  ```

- null pointer

- ```c++
  int *p1 = nullptr; // equivalent to int *p1 = 0; c++11 standard
  int *p2 = 0;       // directly initializes p2 from the literal constant 0
  // must #include cstdlib
  int *p3 = NULL;    // equivalent to int *p3 = 0;
  ```

- preprocessor runs before the compiler

- use `nullptr` instead of `NULL`

- ```c++
  int zero = 0;
  pi = zero;        // error: cannot assign an int to a pointer
  ```

- reference is not an object

- assignment changes its left-hand operand

- ```c++
  int i = 42;
  int *pi = 0;   // pi is initialized but addresses no object
  int *pi2 = &i; // pi2 initialized to hold the address of i
  int *pi3;      // if pi3 is defined inside a block, pi3 is uninitialized
  pi3 = pi2;        // pi3 and pi2 address the same object, e.g., i
  pi2 = 0;          // pi2 now addresses no object
  ```

- any nonzero pointer evaluates as `true`

- `void *` pointers can hold address of any object

- ```c++
  double obj = 3.14, *pd = &obj;
  // ok: void* can hold the address value of any data pointer type
  void *pv = &obj;  // obj can be an object of any type
  pv = pd;          // pv can hold a pointer to any type
  ```

- pointers to pointers

- ```c++
  int ival = 1024;
  int *pi = &ival;    // pi points to an int
  int **ppi = π    // ppi points to a pointer to an int
  ```

- ![058fig01](https://learning.oreilly.com/library/view/c-primer-fifth/9780133053043/graphics/058fig01.jpg)

- references to pointers

- ```c++
  int i = 42;
  int *p;        // p is a pointer to int
  int *&r = p;   // r is a reference to the pointer p
  r = &i; //  r refers to a pointer; assigning &i to r makes p point to i
  *r = 0; //  dereferencing r yields i, the object to which p points; changes i to 0
  ```

### 2.4 `CONST` qualifier

- make a variable unchangeable by defining the type as `const`

- a `const` variable must be initialized

- `const` only matters for operations that might change the variables

- to define a single instance of `const` variable, use `extern` on both its definition and declaration

- ```c++
  // file_1.cc defines and initializes a const that is accessible to other files
  extern const int bufSize = fcn();
  // file_1.h
  extern const int bufSize; // same bufSize as defined in file_1.cc
  ```

- reference to `const` cannot be used to change the object

- ```c++
  const int ci = 1024;
  const int &r1 = ci;   // ok: both reference and underlying object are const
  r1 = 42;              // error: r1 is a reference to const
  int &r2 = ci;         // error: non const reference to a const object
  ```

- a reference to `const` may refer to an object that is not `const`

- a pointer to `const`

- ```c++
  const double pi = 3.14;   // pi is const; its value may not be changed
  double *ptr = π        // error: ptr is a plain pointer
  const double *cptr = π // ok: cptr may point to a double that is const
  *cptr = 42;               // error: cannot assign to *cptr
  ```

- `const` pointers are objects

- ```c++
  int errNumb = 0;
  int *const curErr = &errNumb;  // curErr will always point to errNumb
  const double pi = 3.14159;
  const double *const pip = π // pip is a const pointer to a const object

  *pip = 2.72;     // error: pip is a pointer to const
  // if the object to which curErr points (i.e., errNumb) is nonzero
  if (*curErr) {
      errorHandler();
      *curErr = 0; // ok: reset the value of the object to which curErr is bound
  }
  ```

- top-level `const`: the pointer itself is a `const`

- low-level `const`: a pointer can point to a `const` object

- ```c++
  int i = 0;
  int *const p1 = &i;  // we can't change the value of p1; const is top-level
  const int ci = 42;   // we cannot change ci; const is top-level
  const int *p2 = &ci; // we can change p2; const is low-level
  const int *const p3 = p2; // right-most const is top-level, left-most is not
  const int &r = ci;  // const in reference types is always low-level

  i = ci;  // ok: copying the value of ci; top-level const in ci is ignored
  p2 = p3; // ok: pointed-to type matches; top-level const in p3 is ignored

  int *p = p3; // error: p3 has a low-level const but p doesn't
  p2 = p3;     // ok: p2 has the same low-level const qualification as p3
  p2 = &i;     // ok: we can convert int* to const int*
  int &r = ci; // error: can't bind an ordinary int& to a const int object
  const int &r2 = i; // ok: can bind const int& to plain int
  ```

- we can convert a non`const` to `const` but not the other way round

- a constant expression cannot change its value and can be evaluated at compile time

- a literal is a constant expression

- a `const` object that is initialized from a constant expression is also a constant expression

- ```c++
  const int max_files = 20;    // max_files is a constant expression
  const int limit = max_files + 1; // limit is a constant expression
  int staff_size = 27;       // staff_size is not a constant expression
  const int sz = get_size(); // sz is not a constant expression
  ```

- ```c++
  // c++ 11
  constexpr int mf = 20;        // 20 is a constant expression
  constexpr int limit = mf + 1; // mf + 1 is a constant expression
  constexpr int sz = size();    // ok only if size is a constexpr function
  ```

- types we can use in a `constexpr` are literal types

- arithmetic, reference and pointer types are literal types

- ```c++
  const int *p = nullptr;     // p is a pointer to a const int
  constexpr int *q = nullptr; // q is a const pointer to int

  constexpr int *np = nullptr; // np is a constant pointer to int that is null
  int j = 0;
  constexpr int i = 42;  // type of i is const int
  // i and j must be defined outside any function
  constexpr const int *p = &i; // p is a constant pointer to the const int i
  constexpr int *p1 = &j;      // p1 is a constant pointer to the int j
  ```

### 2.5 dealing with types

- type alias is a name that is a synonym for another type

- ```c++
  typedef double wages;   // wages is a synonym for double
  typedef wages base, *p; // base is a synonym for double, p for double*

  // c++ 11
  using SI = Sales_item; // SI is a synonym for Sales_item

  wages hourly, weekly;    // same as double hourly, weekly;
  SI item;                 // same as Sales_item item
  ```

- ```c++
  typedef char *pstring;
  const pstring cstr = 0; // cstr is a constant pointer to char
  const pstring *ps;      // ps is a pointer to a constant pointer to char

  const char *cstr = 0; // wrong interpretation of const pstring cstr
  char *const cstr = 0; // correct interpretation
  ```

- a variable that uses `auto` must have an initializer

- ```c++
  // c++ 11
  // the type of item is deduced from the type of the result of adding val1 and val2
  auto item = val1 + val2; // item initialized to the result of val1 + val2

  auto i = 0, *p = &i;      // ok: i is int and p is a pointer to int
  auto sz = 0, pi = 3.14;   // error: inconsistent types for sz and pi

  int i = 0, &r = i;
  auto a = r;  // a is an int (r is an alias for i, which has type int)

  const int ci = i, &cr = ci;
  auto b = ci;  // b is an int (top-level const in ci is dropped)
  auto c = cr;  // c is an int (cr is an alias for ci whose const is top-level)
  auto d = &i;  // d is an int*(& of an int object is int*)
  auto e = &ci; // e is const int*(& of a const object is low-level const)

  const auto f = ci; // deduced type of ci is int; f has type const int

  auto &g = ci;       // g is a const int& that is bound to ci
  auto &h = 42;       // error: we can't bind a plain reference to a literal
  const auto &j = 42; // ok: we can bind a const reference to a literal

  auto k = ci, &l = i;    // k is int; l is int&
  auto &m = ci, *p = &ci; // m is a const int&;p is a pointer to const int
  // error: type deduced from i is int; type deduced from &ci is const int
  auto &n = i, *p2 = &ci;
  ```

- `decltype` returns the type of expression's operand but does not evaluate the expression

- `decltype` returns the type of the variable, including top-level `const` references

- ```c++
  const int ci = 0, &cj = ci;
  decltype(ci) x = 0; // x has type const int
  decltype(cj) y = x; // y has type const int& and is bound to x
  decltype(cj) z;     // error: z is a reference and must be initialized
  ```

- `decltype` returns a reference type for expressions that yield objects taht can stand on the left-hand side of assignment

- ```c++
  // decltype of an expression can be a reference type
  int i = 42, *p = &i, &r = i;
  decltype(r + 0) b;  // ok: addition yields an int; b is an (uninitialized) int
  decltype(*p) c;     // error: c is int& and must be initialized

  // decltype of a parenthesized variable is always a reference
  decltype((i)) d;    // error: d is int& and must be initialized
  decltype(i) e;      // ok: e is an (uninitialized) int
  ```

### 2.6 defining our own data structures

- ```c++
  struct Sales_data {
      std::string bookNo;
      unsigned units_sold = 0;
      double revenue = 0.0;
  };

  struct Sales_data { /* ... */ } accum, trans, *salesptr;
  // equivalent, but better way to define these objects
  struct Sales_data { /* ... */ };
  Sales_data accum, trans, *salesptr;
  ```

- close curly must be followed by a semicolon

- this class only has data members

- in-class initializers are restricted

- typically, classes are stored in headers whose name derives from the name of the class

- preprocessor makes including a header multiple times safe

- preprocessor is originally from C

- preprocessor runs before the compiler

- preprocessor variables have two states, defined or undefined

  - `#define`
  - `#ifdef`
  - `ifndef`

- preprocessor variables and names of header guards must be unique throughout the program


text:
title: Use a custom CSS Variable
localeTitle: استخدم متغير CSS مخصص
---
## استخدم متغير CSS مخصص

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/responsive-web-design/basic-css/use-a-custom-css-variable/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
"use strict";

var value = require("value"),
    _ = require("underscore"),
    Base = require("../../shared/Base.class.js");

/**
 * Response
 * @extends Base
 * @type {Class}
 */
var Response = Base.extend("Response", {

    /**
     * @event
     * @name Response#end
     */

    _statusCode : null,
    _headers : null,
    _data : null,
    _status : "success",
    _errorMessage : "",
    _statusCodes : {
        success : 200,
        fail : 400,
        error : 500
    },

    /**
     *  @construct
     */
    constructor : function () {
        this._headers = {};
        this._data = {};
    },
    /**
     * setHeader with headerKey, headerValue and optional protocol, defaults to (http)
     * @param {!String} headerKey
     * @param {!String} headerValue
     */
    setHeader : function (headerKey, headerValue) {
        this._headers[headerKey] = headerValue;
        return this;
    },
    /**
     * set Http Status-Code
     * @param {!Number} statusCode
     */
    setStatusCode : function (statusCode) {
        this._statusCode = statusCode;
        return this;
    },
    /**
     * set the status of the response to fail, error or success
     * @param {!String} status (success, fail or error)
     */
    setStatus : function (status) {

        if (_(Object.keys(this._statusCodes)).contains(status)) {
            this._status = status;
            return this;
        }

        throw new Error("Invalid Status: " + status);
    },
    /**
     * set an error Message
     * @param {String} msg
     */
    setErrorMessage : function (msg) {
        this._errorMessage = msg;
    },
    /**
     * bind data to the response
     * @param {!Object|Array} data
     */
    setData : function (data) {

        if (value(data).notTypeOf(Object) && value(data).notTypeOf(Array)) {
            throw new TypeError("(alamid) Cannot set data: Data only accepts objects and arrays");
        }

        this._data = data;
        return this;
    },
    /**
     * retrieve the response-data as an Object
     * @return {Object}
     */
    getData : function () {
        return this._data;
    },
    /**
     * retrieve the response-data as a JSON-string
     * @return {*}
     */
    getJSONData : function () {
        return JSON.stringify(this._data);
    },
    /**
     * return the statusCode if set. if no statusCode was set, we derive it from the string-status
     * @return {Number}
     */
    getStatusCode : function () {

        if (this._statusCode) {
            return this._statusCode;
        }

        if (this._statusCodes[this._status] !== undefined) {
            return this._statusCodes[this._status];
        }

        //return 200 as a default
        return 200;
    },
    /**
     * return the status as a String
     * @return {String}
     */
    getStatus : function () {
        return this._status;
    },
    /**
     * returns the Error-Messages
     * @return {String}
     */
    getErrorMessage : function () {
        return this._errorMessage;
    },
    /**
     * returns all Headers as an object
     * @return {Object}
     */
    getHeaders : function () {
        return this._headers;
    },
    /**
     *
     * ends the response
     * @param {Object} resObj an optional JSend Response
     */
    end : function (resObj) {

        //could also be set via setter
        if (resObj) {
            //setting data
            this.setData(resObj.data || {});
            this.setStatus(resObj.status || "error");
            this.setErrorMessage(resObj.message || "");
        }

        this.emit("end", null);
    },
    /**
     * returns an object following the jSend-spec
     * http://labs.omniti.com/labs/jsend
     * @return {Object}
     */
    toJSendBody : function () {

        var resObj = {};

        //we set a status in any case
        resObj.status = this.getStatus();
        resObj.data = this.getData();

        //we append the error message for "fail" & "error"
        if (resObj.status === "fail" || resObj.status === "error") {
            resObj.message = this.getErrorMessage() || "";
        }

        return resObj;
    }
});

module.exports = Response;


text:
package com.zj.action.chapter05.synchronizer;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * FutureTask的实现描述了一个抽象的可携带计算结果的计算

 * FutureTask的计算是通过Callable来实现的,它相当于一个可携带计算结果的Runnable

 * 它有三个状态:等待、运行、完成.一旦进入完成状态就不会再改变.

 * 正常结束、取消和异常都会使其进入完成状态

 * Future.get依赖于任务的状态,只有任务已经完成了才会返回结果,不然会一直阻塞

 * FutureTask把计算的结果从运行计算的线程传送到需要结果的线程

 *

 * Created by LZJ on 2015/12/8.
 */
public class TestFutureTask {

    ProductInfo loadProductInfo() throws DataLoadException {
        return null;
    }

    //相当于runnable
    private final FutureTask<ProductInfo> future =
            new FutureTask<ProductInfo>(() -> loadProductInfo());

    private final Thread thread = new Thread(future);

    public void start() {
        thread.start();
    }

    //启动后需要计算结果的时候可以调用这个方法
    //get抛出异常的三种情况:编译器(受检查的异常)、非检测异常:运行时异常、Error
    public ProductInfo get()
            throws DataLoadException, InterruptedException {
        try {
            return future.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof DataLoadException)
                throw (DataLoadException) cause;
            else
                throw LaunderThrowable.launderThrowable(cause);
        }
    }

    interface ProductInfo {
    }
}

class DataLoadException extends Exception {
}


text:
{% extends 'salt/base.html' %}
{% load static %}
{% block about_active %}active{% endblock %}
{% block title %}About Us{% endblock %}
{% block body %}

Saltan

				Welcome to Saltan, an image board for you and the rest of the world.

				You can share photos and start discussions. This is called a salt.

				Alright, that's cool, how do I get started?

				Simple, register and start posting!

{% endblock %}


text:
using System;
using System.Collections.Generic;
using Ccr.Std.Core.Extensions;
using Ccr.Std.Introspective.Extensions;
using Ccr.Std.Introspective.Infrastructure;
using Ccr.Std.Introspective.Infrastructure.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;

namespace Ccr.Dnc.Data.EntityFramework.Infrastucture
{
	public class UnitOfWork<TContext>
		: IUnitOfWork
			where TContext
				: DbContext
	{
		#region Fields
		private IDbContextTransaction _transaction;
		private readonly Dictionary<Type, object> _repositories;
		private readonly TContext _context;

		#endregion

		#region Constructors
		public UnitOfWork()
			: this(
				Activator.CreateInstance<TContext>())
		{
			_repositories = new Dictionary<Type, object>();
		}

		public UnitOfWork(
			TContext context)
		{
			_context = context;
		}

		#endregion

		public TRepository GetCustomRepository<TRepository, TEntity>()
			where TRepository
				: IRepository<TEntity>
			where TEntity
				: class
		{
			//throw new NotImplementedException();
			if (_repositories.TryGetValue(typeof(TEntity), out var cachedRepository))
				return cachedRepository.As<TRepository>();

			var repository =
				new IntrospectiveStaticContext<TRepository>()
				.InvokeCtorGeneric(
					MemberDescriptor.Any,
					new[] { typeof(TContext) },
					new object[] { _context });

			_repositories.Add(typeof(TEntity), repository);
			return repository;
		}

		public IRepository<TEntity, TKey> GetRepository<TEntity, TKey>()
			where TEntity
				: class
			where TKey
				: IComparable
		{
			if (!_repositories.TryGetValue(typeof(TEntity), out var cachedRepository))
			{
				var repository = new Repository<TEntity, TKey, TContext>(
					_context);

				_repositories.Add(
					typeof(TEntity),
					repository);

				return repository;
			}
			else
			{
				if (!(cachedRepository is IRepository<TEntity, TKey> repository))
					throw new InvalidCastException(
						$"Cached repository must be a {typeof(IRepository<TEntity, TKey>).Name.SQuote()}.");

				return repository;
			}
		}

		public IRepository<TEntity> GetRepositoryBase<TEntity>()
			where TEntity
				: class
		{
			if (!_repositories.TryGetValue(typeof(TEntity), out var cachedRepository))
			{
				var repository = new Repository<TEntity, IComparable, TContext>(
					_context);

				_repositories.Add(
					typeof(TEntity),
					repository);

				return repository;
			}
			else
			{
				if (!(cachedRepository is IRepository<TEntity> repository))
					throw new InvalidCastException(
						$"Cached repository must be a {typeof(IRepository<TEntity>).Name.SQuote()}.");

				return repository;
			}
			//if (_repositories
			//	.Keys
			//	.Contains(
			//		typeof(TSet)))
			//	return _repositories[typeof(TSet)] as IRepository<TSet>;

			//var repository = new Repository<TSet, IComparable, TContext>(
			//	_context);

			//_repositories.Add(
			//	typeof(TSet),
			//	repository);

			//return repository;
		}

		/// <summary>
		///		Start Transaction
		/// </summary>
		/// <returns></returns>
		public IDbContextTransaction BeginTransaction()
		{
			if (null == _transaction)
			{
				//using (var connection = _context.GetSingularDbConnection())
				//{
				//}
				_transaction = _context
					.Database
					.BeginTransaction();
			}
			return _transaction;
		}

		public int Save()
		{
			return _context
				.SaveChanges();
		}

		#region IDisposable Members
		public void Dispose()
		{
			_transaction?.Dispose();
			_context?.Dispose();
		}

		#endregion
	}
}


text:
using Btk.CaaS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Results;

namespace Btk.CaaS.Controllers.Api
{
    public class FortuneController : ApiController
    {
        private IFortuneProvider _fortuneProvider;
        public FortuneController(IFortuneProvider fortuneProvider)
        {
            if (fortuneProvider == null)
                throw new ArgumentNullException("fortuneProvider");

            _fortuneProvider = fortuneProvider;
        }

        public IHttpActionResult Get()
        {
            try
            {
                var result = _fortuneProvider.GetFortune().Replace("\r\n", "<br>");
                return Ok(result);
            }
            catch(FortuneServiceUnavailableException ex)
            {
                return NotFound();
            }
        }

    }
}


text:
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;

namespace NotifyPropertyChangedExtensions
{
    public static class NotifyPropertyChangedExtensions
    {
        public static void HandleOnPropertyChanged<TNotifyPropertyChanged, TSourceProperty>(this TNotifyPropertyChanged source,
                Expression<Func<TNotifyPropertyChanged, TSourceProperty>> sourceProperty,
                Action<TNotifyPropertyChanged> eventHandler)

            where TNotifyPropertyChanged : INotifyPropertyChanged
        {
            if (sourceProperty == null)
                throw new ArgumentNullException("sourceProperty");
            if (eventHandler == null)
                throw new ArgumentNullException("eventHandler");

            var sourceMember = sourceProperty.Body as MemberExpression;
            if (sourceMember == null)
                throw new ArgumentException("Source property must be a member-access property");

            string sourcePropertyName = sourceMember.Member.Name;

            source.PropertyChanged += (sender, args) =>
            {
                if (String.Equals(args.PropertyName, sourcePropertyName, StringComparison.Ordinal))
                {
                    eventHandler(source);
                }
            };
        }

        public static void BindProperty<TNotifyPropertyChanged, TSourceProperty, TTarget, TTargetProperty>(this TNotifyPropertyChanged source,
            Expression<Func<TNotifyPropertyChanged, TSourceProperty>> sourceProperty,
            TTarget target,
            Expression<Func<TTarget, TTargetProperty>> targetProperty,
            BindPropertyOptions options = BindPropertyOptions.InitialiseTarget)

            where TNotifyPropertyChanged : INotifyPropertyChanged
        {
            if (sourceProperty == null)
                throw new ArgumentNullException("sourceProperty");
            if (targetProperty == null)
                throw new ArgumentNullException("targetProperty");

            Type sourceBaseType = Nullable.GetUnderlyingType(typeof(TSourceProperty)) ?? typeof(TSourceProperty);
            bool isSourceNullable = sourceBaseType != typeof(TSourceProperty);

            Type targetBaseType = Nullable.GetUnderlyingType(typeof(TTargetProperty)) ?? typeof(TTargetProperty);
            bool isTargetNullable = targetBaseType != typeof(TTargetProperty);

            if (sourceBaseType != targetBaseType)
                throw new ArgumentException("source and target property types must be the same or nullable of each other", "sourceProperty");

            var sourceMember = sourceProperty.Body as MemberExpression;
            if (sourceMember == null)
                throw new ArgumentException("Source property must be a member-access property");

            var targetMember = targetProperty.Body as MemberExpression;
            MemberExpression negatedTargetMember = null;

            if (targetMember == null)
            {
                bool bindingAccepted = sourceBaseType == typeof(bool) && targetProperty.IsNotOfMemberAccess(out negatedTargetMember);
                if (!bindingAccepted)
                    throw new ArgumentException("The target property must be either a member-access or a negated member-access for boolean source types.", "targetProperty");
            }

            string sourcePropertyName = sourceMember.Member.Name;
            string targetPropertyName = targetMember != null ? targetMember.Member.Name : negatedTargetMember.Member.Name;

            var sourcePropertyInfo = source.GetType().GetProperty(sourcePropertyName, BindingFlags.Instance | BindingFlags.Public);
            var targetPropertyInfo = target.GetType().GetProperty(targetPropertyName, BindingFlags.Instance | BindingFlags.Public);
            bool dontUpdateTargetWhenSourceIsNullAndTargetIsNotNullable = options.HasFlag(BindPropertyOptions.DontUpdateWhenSourceIsNullAndTargetIsNotNullable);

            var updateAction = new Action<object>(sender =>
            {
                object sourceValue = sourcePropertyInfo.GetValue(source, null);

                object targetValue = null;
                bool setTarget;

                if (typeof(TSourceProperty) == typeof(TTargetProperty) || sourceValue != null)
                {
                    targetValue = sourceValue;
                    setTarget = true;
                }
                else // if (sourceValue == null)
                {
                    if (isTargetNullable)
                    {
                        targetValue = null;
                        setTarget = true;
                    }
                    else if (!dontUpdateTargetWhenSourceIsNullAndTargetIsNotNullable)
                    {
                        targetValue = default(TTargetProperty);
                        setTarget = true;
                    }
                    else
                    {
                        setTarget = false;
                    }
                }

                if (setTarget)
                {
                    if (negatedTargetMember != null)
                        targetValue = !(bool)(targetValue ?? false);

                    targetPropertyInfo.SetValue(target, targetValue, null);
                }
            });

            if (options.HasFlag(BindPropertyOptions.InitialiseTarget))
                updateAction(source);

            source.PropertyChanged += (sender, args) =>
            {
                if (String.Equals(args.PropertyName, sourcePropertyName, StringComparison.Ordinal))
                {
                    updateAction(sender);
                }
            };
        }

        public static void RaisePropertyChanged<TNotifyPropertyChanged, TProperty>(
            this TNotifyPropertyChanged self,
            Expression<Func<TProperty>> property)

            where TNotifyPropertyChanged : INotifyPropertyChanged
        {
            if (property == null)
                throw new ArgumentNullException("property");

            var sourceMember = property.Body as MemberExpression;
            if (sourceMember == null)
                throw new ArgumentException("Property must be a member-access property");

            string propertyName = sourceMember.Member.Name;

            var eventArgs = new PropertyChangedEventArgs(propertyName);

            Raise(self, "PropertyChanged", eventArgs);
        }

        internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
        {
            var eventInfo = source.GetType().GetField(eventName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (eventInfo == null)
                return;

            var eventDelegate = eventInfo.GetValue(source) as MulticastDelegate;
            if (eventDelegate != null)
            {
                foreach (var handler in eventDelegate.GetInvocationList())
                {
                    handler.Method.Invoke(handler.Target, new object[] { source, eventArgs });
                }
            }
        }
    }
}