text:
require File.dirname(__FILE__) + '/../../spec_helper'
require File.dirname(__FILE__) + '/fixtures/classes'

describe "Struct#select" do
  it "raises an ArgumentError if given any non-block arguments" do
    lambda { Struct::Car.new.select(1) { } }.should raise_error(ArgumentError)
  end

  it "returns a new array of elements for which block is true" do
    struct = Struct::Car.new("Toyota", "Tercel", "2000")
    struct.select { |i| i == "2000" }.should == [ "2000" ]
  end

  it "returns an instance of Array" do
    struct = Struct::Car.new("Ford", "Escort", "1995")
    struct.select { true }.should be_kind_of(Array)
  end
end


text:
@protocol SRConnectionInterface;

@interface SRHeartbeatMonitor : NSObject

@property (assign, nonatomic, readonly, getter = hasBeenWarned) BOOL beenWarned;
@property (assign, nonatomic, readonly) BOOL timedOut;

- (instancetype)initWithConnection:(id <SRConnectionInterface>)connection;
- (void)start;
- (void)stop;

@end

redpajama_set_name: RedPajamaGithub


text:
package com.github.fppt.jedismock.operations.sets;

import com.github.fppt.jedismock.datastructures.RMSet;
import com.github.fppt.jedismock.operations.AbstractRedisOperation;
import com.github.fppt.jedismock.operations.RedisCommand;
import com.github.fppt.jedismock.server.Response;
import com.github.fppt.jedismock.datastructures.Slice;
import com.github.fppt.jedismock.storage.RedisBase;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toList;

@RedisCommand("smembers")
class SMembers extends AbstractRedisOperation {
    SMembers(RedisBase base, List<Slice> params) {
        super(base, params);
    }

    protected Slice response() {
        final Slice key = params().get(0);
        final RMSet setDBObj = getSetFromBaseOrCreateEmpty(key);
        final Set<Slice> data = setDBObj.getStoredData();
        //Has to be a list because Jedis can only deserialize lists
        LinkedList<Slice> list;
        if (data != null) {
            list = new LinkedList<>(data);
        } else {
            list = new LinkedList<>();
        }

        return Response.array(list.stream().map(Response::bulkString).collect(toList()));
    }
}


text:
module.exports = function (grunt) {
  grunt.initConfig({
    patternpack: {
      options: {
        assets: "./src/assets"
        // Add a custom theme by specifying a theme package.
        // theme: "patternpack-example-theme"
        //
        // You may also point directly to a theme by path if you wish to make
        // the theme part of your pattern library itself.
        // theme: "./theme/"
      },
      run: {},
      build: {},
      release: {},
      "release-major": {},
      "release-minor": {},
      "release-patch": {}
    }
  });

  grunt.loadNpmTasks("patternpack");

  grunt.registerTask("run", ["patternpack:run"]);
  grunt.registerTask("build", ["patternpack:build"]);
  grunt.registerTask("release", ["patternpack:release"]);
  grunt.registerTask("release-major", ["patternpack:release-major"]);
  grunt.registerTask("release-minor", ["patternpack:release-minor"]);
  grunt.registerTask("release-patch", ["patternpack:release-patch"]);
  grunt.registerTask("default", ["run"]);
};


text:
// Miscellaneous tests with the PRED type that don't fit anywhere else.
#include <memory>

#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/cpu_compiler_flags.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/platform/test.h"

namespace xla {
namespace {

class PredTest : public ClientLibraryTestBase {
 protected:
  void TestCompare(bool lhs, bool rhs, bool expected,
                   ComputationDataHandle (ComputationBuilder::*op)(
                       const ComputationDataHandle&,
                       const ComputationDataHandle&,
                       tensorflow::gtl::ArraySlice<int64>)) {
    ComputationBuilder builder(client_, TestName());
    ComputationDataHandle lhs_op = builder.ConstantR0<bool>(lhs);
    ComputationDataHandle rhs_op = builder.ConstantR0<bool>(rhs);
    ComputationDataHandle result = (builder.*op)(lhs_op, rhs_op, {});
    ComputeAndCompareR0<bool>(&builder, expected, {});
  }
};

TEST_F(PredTest, ConstantR0PredTrue) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR0<bool>(true);
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, ConstantR0PredFalse) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR0<bool>(false);
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, ConstantR0PredCompareEq) {
  TestCompare(true, false, false, &ComputationBuilder::Eq);
}

TEST_F(PredTest, ConstantR0PredCompareNe) {
  TestCompare(true, false, true, &ComputationBuilder::Ne);
}

TEST_F(PredTest, ConstantR0PredCompareLe) {
  TestCompare(true, false, false, &ComputationBuilder::Le);
}

TEST_F(PredTest, ConstantR0PredCompareLt) {
  TestCompare(true, false, false, &ComputationBuilder::Lt);
}

TEST_F(PredTest, ConstantR0PredCompareGe) {
  TestCompare(true, false, true, &ComputationBuilder::Ge);
}

TEST_F(PredTest, ConstantR0PredCompareGt) {
  TestCompare(true, false, true, &ComputationBuilder::Gt);
}

TEST_F(PredTest, ConstantR1Pred) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<bool>({true, false, false, true});
  ComputeAndCompareR1<bool>(&builder, {true, false, false, true}, {});
}

TEST_F(PredTest, ConstantR2Pred) {
  ComputationBuilder builder(client_, TestName());
  auto a =
      builder.ConstantR2<bool>({{false, true, true}, {true, false, false}});
  const string expected = R"(pred[2,3] {
  { 011 },
  { 100 },
})";
  EXPECT_EQ(expected, ExecuteToString(&builder, {}));
}

TEST_F(PredTest, AnyR1True) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<bool>({true, false});
  TF_ASSERT_OK(Any(a, &builder).status());
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, AnyR1False) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<bool>({false, false});
  TF_ASSERT_OK(Any(a, &builder).status());
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, AnyR1VacuouslyFalse) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<bool>({});
  TF_ASSERT_OK(Any(a, &builder).status());
  ComputeAndCompareR0<bool>(&builder, false, {});
}

TEST_F(PredTest, AnyR2True) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<bool>({
      {false, false, false}, {false, false, false}, {false, false, true},
  });
  TF_ASSERT_OK(Any(a, &builder).status());
  ComputeAndCompareR0<bool>(&builder, true, {});
}

TEST_F(PredTest, AnyR2False) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<bool>({
      {false, false, false}, {false, false, false}, {false, false, false},
  });
  TF_ASSERT_OK(Any(a, &builder).status());
  ComputeAndCompareR0<bool>(&builder, false, {});
}

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendCpuCompilerFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}


text:
@interface CardsTests : XCTestCase

@end

@implementation CardsTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testDeckOutput {
    JJCDeck *deck = [[JJCDeck alloc] init];
    XCTAssertNotNil(deck);
    NSLog(@"%@", deck);
    [deck shuffle];
    NSLog(@"%@", deck);
}

- (void)testCardEquality {
    JJCCard *aceOfSpades = [[JJCCard alloc] initWithSuit:JJCSuitSpade rank:JJCRankAce];
    JJCCard *otherAce = [[JJCCard alloc] initWithSuit:JJCSuitSpade rank:JJCRankAce];
    XCTAssertEqualObjects(aceOfSpades, otherAce);
}

- (void)testCardEqualityWrongSuit {
    JJCCard *aceOfSpades = [[JJCCard alloc] initWithSuit:JJCSuitSpade rank:JJCRankAce];
    JJCCard *otherAce = [[JJCCard alloc] initWithSuit:JJCSuitHeart rank:JJCRankAce];
    XCTAssertNotEqualObjects(aceOfSpades, otherAce);
}

- (void)testCardEqualityWrongRank {
    JJCCard *aceOfSpades = [[JJCCard alloc] initWithSuit:JJCSuitSpade rank:JJCRankAce];
    JJCCard *threeSpade = [[JJCCard alloc] initWithSuit:JJCSuitSpade rank:JJCRankThree];
    XCTAssertNotEqualObjects(aceOfSpades, threeSpade);
}

- (void)testDeckEquality {
    JJCDeck *deck1 = [[JJCDeck alloc] init];
    JJCDeck *deck2 = [[JJCDeck alloc] init];
    XCTAssertEqualObjects(deck1, deck2);
}

// The chance of this test failing is 1 in 8.07e67
- (void)testShuffleNonEqual {
    JJCDeck *deck1 = [[JJCDeck alloc] init];
    JJCDeck *deck2 = [[JJCDeck alloc] init];
    [deck2 shuffle];
    XCTAssertNotEqualObjects(deck1, deck2);
}

- (void)testDeckPerformance {
    __block JJCDeck *deck;
    [self measureBlock:^{
        deck = [[JJCDeck alloc] init];
    }];
}

- (void)testShufflePerformance {
    JJCDeck *deck = [[JJCDeck alloc] init];
    [self measureBlock:^{
        [deck shuffle];
    }];
}

@end


text:
package com.piticlistudio.playednext.game;

import com.piticlistudio.playednext.APIKeys;
import com.piticlistudio.playednext.collection.model.entity.CollectionMapper;
import com.piticlistudio.playednext.collection.model.entity.RealmCollectionMapper;
import com.piticlistudio.playednext.collection.model.repository.ICollectionRepository;
import com.piticlistudio.playednext.company.model.entity.CompanyMapper;
import com.piticlistudio.playednext.company.model.entity.RealmCompanyMapper;
import com.piticlistudio.playednext.company.model.repository.ICompanyRepository;
import com.piticlistudio.playednext.game.model.entity.GameMapper;
import com.piticlistudio.playednext.game.model.entity.RealmGameMapper;
import com.piticlistudio.playednext.game.model.entity.datasource.IGDBGame;
import com.piticlistudio.playednext.game.model.repository.GameRepository;
import com.piticlistudio.playednext.game.model.repository.IGameRepository;
import com.piticlistudio.playednext.game.model.repository.datasource.GamedataRepository;
import com.piticlistudio.playednext.game.model.repository.datasource.IGDBGameRepositoryImpl;
import com.piticlistudio.playednext.game.model.repository.datasource.IGamedataRepository;
import com.piticlistudio.playednext.game.model.repository.datasource.IGamedatasourceRepository;
import com.piticlistudio.playednext.game.model.repository.datasource.RealmGameRepositoryImpl;
import com.piticlistudio.playednext.gamerelease.model.entity.GameReleaseMapper;
import com.piticlistudio.playednext.gamerelease.model.entity.RealmGameReleaseMapper;
import com.piticlistudio.playednext.genre.model.entity.GenreMapper;
import com.piticlistudio.playednext.genre.model.entity.RealmGenreMapper;
import com.piticlistudio.playednext.genre.model.repository.IGenreRepository;
import com.piticlistudio.playednext.image.model.entity.ImageDataMapper;
import com.piticlistudio.playednext.image.model.entity.RealmImageDataMapper;
import com.piticlistudio.playednext.platform.model.entity.PlatformMapper;
import com.piticlistudio.playednext.platform.model.entity.RealmPlatformMapper;
import com.piticlistudio.playednext.platform.model.repository.IPlatformRepository;
import com.piticlistudio.playednext.releasedate.model.entity.ReleaseDateMapper;

import java.util.List;

import javax.inject.Named;

import dagger.Module;
import dagger.Provides;
import io.reactivex.Observable;
import retrofit2.Retrofit;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;

/**
 * A module that provides Game classes
 * Created by jorge.garcia on 10/02/2017.
 */
@Module
public class GameModule {

    @Provides
    public NetService service(Retrofit retrofit) {
        return retrofit.create(NetService.class);
    }

    @Provides
    @Named("net")
    public IGamedatasourceRepository provideNetRepository(NetService service) {
        return new IGDBGameRepositoryImpl(service);
    }

    @Provides
    @Named("db")
    public IGamedatasourceRepository provideDBRepository() {
        return new RealmGameRepositoryImpl();
    }

    @Provides
    public IGamedataRepository provideDataRepository(@Named("db") IGamedatasourceRepository dbImpl,
                                                     @Named("net") IGamedatasourceRepository netImpl) {
        return new GamedataRepository(dbImpl, netImpl);
    }

    @Provides
    public GameMapper mapper(CollectionMapper cm, ImageDataMapper im, CompanyMapper com, GenreMapper gm, GameReleaseMapper grm,
                             PlatformMapper pm) {
        return new GameMapper(cm, im, com, gm, grm, pm);
    }

    @Provides
    public RealmGameMapper realmMapper(RealmCollectionMapper cm, RealmImageDataMapper im, RealmCompanyMapper com, RealmGenreMapper gm,
                                       RealmGameReleaseMapper grm, RealmPlatformMapper pm) {
        return new RealmGameMapper(im, cm, com, gm, grm, pm);
    }

    @Provides
    public IGameRepository provideRepository(IGamedataRepository iGamedataRepository, GameMapper gm, RealmGameMapper rm,
                                             ICollectionRepository cr, ICompanyRepository comr, IGenreRepository gr, IPlatformRepository
                                                     pr, ReleaseDateMapper rdm) {
        return new GameRepository(iGamedataRepository, gm, rm, cr, comr, gr, pr, rdm);
    }

    public interface NetService {
        @Headers({
                "Accept: application/json",
                "X-Mashape-Key: " + APIKeys.IGDB_KEY
        })
        @GET("/games/")
        Observable<List<IGDBGame>> search(@Query("offset") int offset, @Query("search") String query, @Query("fields") String fields,
                                          @Query("limit") int limit);

        @Headers({
                "Accept: application/json",
                "X-Mashape-Key: " + APIKeys.IGDB_KEY
        })
        @GET("/games/{id}/")
        Observable<List<IGDBGame>> load(@Path("id") int id, @Query("fields") String fields);
    }
}


text:
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Embedding;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.Input.TextInput;
using Avalonia.Web.Blazor.Interop;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using SkiaSharp;

namespace Avalonia.Web.Blazor
{
    public partial class AvaloniaView : ITextInputMethodImpl
    {
        private readonly RazorViewTopLevelImpl _topLevelImpl;
        private EmbeddableControlRoot _topLevel;

        // Interop
        private SKHtmlCanvasInterop _interop = null!;
        private SizeWatcherInterop _sizeWatcher = null!;
        private DpiWatcherInterop _dpiWatcher = null!;
        private SKHtmlCanvasInterop.GLInfo? _jsGlInfo = null!;
        private InputHelperInterop _inputHelper = null!;
        private ElementReference _htmlCanvas;
        private ElementReference _inputElement;
        private double _dpi;
        private SKSize _canvasSize;

        private GRContext? _context;
        private GRGlInterface? _glInterface;
        private const SKColorType ColorType = SKColorType.Rgba8888;

        private bool _initialised;

        [Inject] private IJSRuntime Js { get; set; } = null!;

        public AvaloniaView()
        {
            _topLevelImpl = new RazorViewTopLevelImpl(this);

            _topLevel = new EmbeddableControlRoot(_topLevelImpl);

            if (Application.Current?.ApplicationLifetime is ISingleViewApplicationLifetime lifetime)
            {
                _topLevel.Content = lifetime.MainView;
            }
        }

        private void OnTouchStart(TouchEventArgs e)
        {
            foreach (var touch in e.ChangedTouches)
            {
                _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchBegin, new Point(touch.ClientX, touch.ClientY),
                    GetModifiers(e), touch.Identifier);
            }
        }

        private void OnTouchEnd(TouchEventArgs e)
        {
            foreach (var touch in e.ChangedTouches)
            {
                _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchEnd, new Point(touch.ClientX, touch.ClientY),
                    GetModifiers(e), touch.Identifier);
            }
        }

        private void OnTouchCancel(TouchEventArgs e)
        {
            foreach (var touch in e.ChangedTouches)
            {
                _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchCancel, new Point(touch.ClientX, touch.ClientY),
                    GetModifiers(e), touch.Identifier);
            }
        }

        private void OnTouchMove(TouchEventArgs e)
        {
            foreach (var touch in e.ChangedTouches)
            {
                _topLevelImpl.RawTouchEvent(RawPointerEventType.TouchUpdate, new Point(touch.ClientX, touch.ClientY),
                    GetModifiers(e), touch.Identifier);
            }
        }

        private void OnMouseMove(MouseEventArgs e)
        {
            _topLevelImpl.RawMouseEvent(RawPointerEventType.Move, new Point(e.ClientX, e.ClientY), GetModifiers(e));
        }

        private void OnMouseUp(MouseEventArgs e)
        {
            RawPointerEventType type = default;

            switch (e.Button)
            {
                case 0:
                    type = RawPointerEventType.LeftButtonUp;
                    break;

                case 1:
                    type = RawPointerEventType.MiddleButtonUp;
                    break;

                case 2:
                    type = RawPointerEventType.RightButtonUp;
                    break;
            }

            _topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e));
        }

        private void OnMouseDown(MouseEventArgs e)
        {
            RawPointerEventType type = default;

            switch (e.Button)
            {
                case 0:
                    type = RawPointerEventType.LeftButtonDown;
                    break;

                case 1:
                    type = RawPointerEventType.MiddleButtonDown;
                    break;

                case 2:
                    type = RawPointerEventType.RightButtonDown;
                    break;
            }

            _topLevelImpl.RawMouseEvent(type, new Point(e.ClientX, e.ClientY), GetModifiers(e));
        }

        private void OnWheel(WheelEventArgs e)
        {
            _topLevelImpl.RawMouseWheelEvent(new Point(e.ClientX, e.ClientY),
                new Vector(-(e.DeltaX / 50), -(e.DeltaY / 50)), GetModifiers(e));
        }

        private static RawInputModifiers GetModifiers(WheelEventArgs e)
        {
            var modifiers = RawInputModifiers.None;

            if (e.CtrlKey)
                modifiers |= RawInputModifiers.Control;
            if (e.AltKey)
                modifiers |= RawInputModifiers.Alt;
            if (e.ShiftKey)
                modifiers |= RawInputModifiers.Shift;
            if (e.MetaKey)
                modifiers |= RawInputModifiers.Meta;

            if ((e.Buttons & 1L) == 1)
                modifiers |= RawInputModifiers.LeftMouseButton;

            if ((e.Buttons & 2L) == 2)
                modifiers |= RawInputModifiers.RightMouseButton;

            if ((e.Buttons & 4L) == 4)
                modifiers |= RawInputModifiers.MiddleMouseButton;

            return modifiers;
        }

        private static RawInputModifiers GetModifiers(TouchEventArgs e)
        {
            var modifiers = RawInputModifiers.None;

            if (e.CtrlKey)
                modifiers |= RawInputModifiers.Control;
            if (e.AltKey)
                modifiers |= RawInputModifiers.Alt;
            if (e.ShiftKey)
                modifiers |= RawInputModifiers.Shift;
            if (e.MetaKey)
                modifiers |= RawInputModifiers.Meta;

            return modifiers;
        }

        private static RawInputModifiers GetModifiers(MouseEventArgs e)
        {
            var modifiers = RawInputModifiers.None;

            if (e.CtrlKey)
                modifiers |= RawInputModifiers.Control;
            if (e.AltKey)
                modifiers |= RawInputModifiers.Alt;
            if (e.ShiftKey)
                modifiers |= RawInputModifiers.Shift;
            if (e.MetaKey)
                modifiers |= RawInputModifiers.Meta;

            if ((e.Buttons & 1L) == 1)
                modifiers |= RawInputModifiers.LeftMouseButton;

            if ((e.Buttons & 2L) == 2)
                modifiers |= RawInputModifiers.RightMouseButton;

            if ((e.Buttons & 4L) == 4)
                modifiers |= RawInputModifiers.MiddleMouseButton;

            return modifiers;
        }

        private static RawInputModifiers GetModifiers(KeyboardEventArgs e)
        {
            var modifiers = RawInputModifiers.None;

            if (e.CtrlKey)
                modifiers |= RawInputModifiers.Control;
            if (e.AltKey)
                modifiers |= RawInputModifiers.Alt;
            if (e.ShiftKey)
                modifiers |= RawInputModifiers.Shift;
            if (e.MetaKey)
                modifiers |= RawInputModifiers.Meta;

            return modifiers;
        }

        private void OnKeyDown(KeyboardEventArgs e)
        {
            _topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyDown, e.Key, GetModifiers(e));
        }

        private void OnKeyUp(KeyboardEventArgs e)
        {
            _topLevelImpl.RawKeyboardEvent(RawKeyEventType.KeyUp, e.Code, GetModifiers(e));
        }

        private void OnInput(ChangeEventArgs e)
        {
            if (e.Value != null)
            {
                var inputData = e.Value.ToString();
                if (inputData != null)
                {
                    _topLevelImpl.RawTextEvent(inputData);
                }
            }

            _inputHelper.Clear();
        }

        [Parameter(CaptureUnmatchedValues = true)]
        public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; }

        protected override void OnAfterRender(bool firstRender)
        {
            if (firstRender)
            {
                Threading.Dispatcher.UIThread.Post(async () =>
                {
                    _inputHelper = await InputHelperInterop.ImportAsync(Js, _inputElement);

                    _inputHelper.Hide();
                    _inputHelper.SetCursor("default");

                    Console.WriteLine("starting html canvas setup");
                    _interop = await SKHtmlCanvasInterop.ImportAsync(Js, _htmlCanvas, OnRenderFrame);

                    Console.WriteLine("Interop created");
                    _jsGlInfo = _interop.InitGL();

                    Console.WriteLine("jsglinfo created - init gl");

                    _sizeWatcher = await SizeWatcherInterop.ImportAsync(Js, _htmlCanvas, OnSizeChanged);
                    _dpiWatcher = await DpiWatcherInterop.ImportAsync(Js, OnDpiChanged);

                    Console.WriteLine("watchers created.");

                    // create the SkiaSharp context
                    if (_context == null)
                    {
                        Console.WriteLine("create glcontext");
                        _glInterface = GRGlInterface.Create();
                        _context = GRContext.CreateGl(_glInterface);

                        var options = AvaloniaLocator.Current.GetService<SkiaOptions>();
                        // bump the default resource cache limit
                        _context.SetResourceCacheLimit(options?.MaxGpuResourceSizeBytes ?? 32 * 1024 * 1024);
                        Console.WriteLine("glcontext created and resource limit set");
                    }

                    _topLevelImpl.SetSurface(_context, _jsGlInfo, ColorType,
                        new PixelSize((int)_canvasSize.Width, (int)_canvasSize.Height), _dpi);

                    _initialised = true;

                    _topLevel.Prepare();

                    _topLevel.Renderer.Start();
                    Invalidate();
                });
            }
        }

        private void OnRenderFrame()
        {
            if (_canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null)
            {
                Console.WriteLine("nothing to render");
                return;
            }

            ManualTriggerRenderTimer.Instance.RaiseTick();
        }

        public void Dispose()
        {
            _dpiWatcher.Unsubscribe(OnDpiChanged);
            _sizeWatcher.Dispose();
            _interop.Dispose();
        }

        private void OnDpiChanged(double newDpi)
        {
            _dpi = newDpi;

            _topLevelImpl.SetClientSize(_canvasSize, _dpi);

            Invalidate();
        }

        private void OnSizeChanged(SKSize newSize)
        {
            _canvasSize = newSize;

            _topLevelImpl.SetClientSize(_canvasSize, _dpi);

            Invalidate();
        }

        public void Invalidate()
        {
            if (!_initialised || _canvasSize.Width <= 0 || _canvasSize.Height <= 0 || _dpi <= 0 || _jsGlInfo == null)
            {
                Console.WriteLine("invalidate ignored");
                return;
            }

            _interop.RequestAnimationFrame(true, (int)(_canvasSize.Width * _dpi), (int)(_canvasSize.Height * _dpi));
        }

        public void SetActive(bool active)
        {
            _inputHelper.Clear();

            if (active)
            {
                _inputHelper.Show();
                _inputHelper.Focus();
            }
            else
            {
                _inputHelper.Hide();
            }
        }

        public void SetCursorRect(Rect rect)
        {
        }

        public void SetOptions(TextInputOptionsQueryEventArgs options)
        {
        }

        public void Reset()
        {
            _inputHelper.Clear();
        }
    }
}


text:
var path = require('path');
var kpio = require('keepass.io');
var moment = require('moment');
var util = require('util');
var Promise = require('bluebird');
var read = Promise.promisify(require('read'));

function objectLog(myObject) {
  return util.inspect(myObject, false, null);
}

Promise.promisifyAll(kpio.Database.prototype);

var indent = 0;

function EntryTitle(Entry) {
  if(Entry.Name) {
    return Entry.Name;
  }

  var processedEntry = Entry.String.filter(function(Entry) {
    return Entry.Key === 'Title';
  })[0];
  return processedEntry.Value;
}

function updateEntryInGroup(Group, UpdatedEntry) {

  var entries = (Group.Entry instanceof Array) ? Group.Entry : [Group.Entry];

  for(var i = 0;i < entries.length;++i) {
    if(entries[i].UUID == UpdatedEntry.UUID) {
      //console.log('FOUND ENTRY!!', 'index', i);
      entries[i] = UpdatedEntry;
      return;
    }
  }
  if (!Group.Entry) {
    Group.Entry = UpdatedEntry;
  } else if( ! (Group.Entry instanceof Array) ) {
    Group.Entry = [Group.Entry, UpdatedEntry];
  } else {
    Group.Entry.push(UpdatedEntry);
  }
}

function processRawDb(rawDatabase, onEntry) {
  var groupPath = [];
  var groups = [];
  showGroup(rawDatabase.KeePassFile.Root.Group);

  function showGroup(Group) {
    onEntry({
      UUID: Group.UUID,
      path: groupPath.join('/') + '/' + Group.Name,
      Group: Group,
      ParentGroup: groups[groups.length - 1]
    });
    groups.push(Group);
    groupPath.push(Group.Name);
    if(Group.Group instanceof Array) {
      Group.Group.forEach(function(Group) {
        showGroup(Group);
      });
    } else if(Group.Group) {
      showGroup(Group.Group);
    }

    function processEntry(Entry) {
      onEntry({
        UUID: Entry.UUID,
        path: groupPath.join('/') + '/' + EntryTitle(Entry),
        Entry: Entry,
        ParentGroup: groups[groups.length - 1]
      });
    }

    if(Group.Entry) {
      if(Group.Entry instanceof Array) {
        Group.Entry.forEach(processEntry);
      } else {
        processEntry(Group.Entry);
      }
    }
    groupPath.pop();
    groups.pop();
  }
}

function rawDatabaseToHash(rawDatabase) {
  var entryDb = {};
  processRawDb(rawDatabase, function(entryForDb) {
    entryDb[entryForDb.UUID] = entryForDb;
  });
  return entryDb;
}

function loadDatabase(filename, credentials) {
  var db = new kpio.Database();
  credentials.forEach(function(credential) {
    db.addCredential(credential);
  });
  return db.loadFileAsync(filename).then(function() {
    var rawDatabase = db.getRawApi().get();

    return {
      db: db,
      entryDb: rawDatabaseToHash(rawDatabase),
      rawDatabase: rawDatabase
    };
  });
}

function mergeKdbx(kdbxFrom, kdbxFromCredentials, kdbxTo, kdbxToCredentials) {
  return Promise.all([
    loadDatabase(kdbxFrom, kdbxFromCredentials),
    loadDatabase(kdbxTo, kdbxToCredentials)
  ]).spread(function(db1, db2) {
    var entryDbFrom = db1.entryDb;
    var entryDbTo = db2.entryDb;

    Object.keys(entryDbFrom).forEach(function(key) {
      if(!entryDbTo[key]) {
        console.log(kdbxFrom + ' has entry : ', entryDbFrom[key].path, 'which does not exist in ', kdbxTo );

        updateEntryInGroup(entryDbTo[entryDbFrom[key].ParentGroup.UUID].Group , entryDbFrom[key].Entry);
      } else if(entryDbTo[key].Entry) {

        var m1 = moment(entryDbFrom[key].Entry.Times.LastModificationTime).toDate();
        var m2 = moment(entryDbTo[key].Entry.Times.LastModificationTime).toDate();

        if(m1 > m2) {
          console.log(kdbxFrom + ' is newer  : ', entryDbFrom[key].path);

          updateEntryInGroup(entryDbTo[key].ParentGroup, entryDbFrom[key].Entry);
        } else if(m2 > m1) {
          console.log(kdbxTo + ' is newer  : ', entryDbTo[key].path);
        }
      }
    });
    Object.keys(entryDbTo).forEach(function(key) {
      if(!entryDbFrom[key]) {
        console.log(kdbxTo + ' has entry : ', entryDbTo[key].path, 'which does not exist in ', kdbxFrom );
      }
    });

    db2.db.getRawApi().set(db2.rawDatabase);
    return db2.db.saveFileAsync(process.argv[4]);
  });
}

if(process.argv.length < 5) {
  return console.error('Usage: keepass-sync from.kdbx to.kdbx merged.kdbx');
}

console.log('Note: password should match both databases');
read({ prompt: 'Password: ', silent: true }).then(function(password) {
  var passwordCredential = new kpio.Credentials.Password(password[0]);
  return mergeKdbx(process.argv[2], [passwordCredential],
                  process.argv[3], [passwordCredential]);
}).catch(function(err) {
  console.error(err);
});


text:
<?php

$installer = $this;
/* @var $installer Mage_Sales_Model_Mysql4_Setup */

$tableOrder       = $this->getTable('sales_order');
$tableOrderEntity = $this->getTable('sales_order_entity');

$cleanTables = array(
    $tableOrder . '_datetime',
    $tableOrder . '_decimal',
    $tableOrder . '_int',
    $tableOrder . '_text',
    $tableOrder . '_varchar',
    $tableOrderEntity . '_decimal',
    $tableOrderEntity . '_datetime',
    $tableOrderEntity . '_int',
    $tableOrderEntity . '_text',
    $tableOrderEntity . '_varchar'
);
foreach ($cleanTables as $tableName) {
    $select = $installer->getConnection()->select()
        ->from($tableName, array(
            'entity_id'         => 'entity_id',
            'attribute_id'      => 'attribute_id',
            'entity_type_id'    => 'entity_type_id',
            'rows_count'        => 'COUNT(*)'))
        ->group(array('entity_id', 'attribute_id', 'entity_type_id'))
        ->having('rows_count > 1');
    $query = $installer->getConnection()->query($select);

    while ($row = $query->fetch()) {
        $sql = 'DELETE FROM `' . $tableName . '`'
            . ' WHERE entity_id=? AND attribute_id=? AND entity_type_id=?'
            . ' LIMIT ' . ($row['rows_count'] - 1);
        $installer->getConnection()->query($sql, array(
            $row['entity_id'],
            $row['attribute_id'],
            $row['entity_type_id']
        ));
    }
}

$installer->getConnection()->addKey("{$tableOrder}_datetime", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrder}_decimal", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrder}_int", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrder}_text", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrder}_varchar", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');

$installer->getConnection()->addKey("{$tableOrderEntity}_datetime", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrderEntity}_decimal", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrderEntity}_int", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrderEntity}_text", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');
$installer->getConnection()->addKey("{$tableOrderEntity}_varchar", 'UNQ_ENTITY_ATTRIBUTE_TYPE', array('entity_id', 'attribute_id', 'entity_type_id'), 'unique');

$installer->getConnection()->addKey($tableOrderEntity, 'IDX_SALES_ORDER_ENTITY_PARENT', 'parent_id');


text:
package reactor.pipe.key;

import java.util.Arrays;
import java.util.UUID;

public class Key {

  private final Object[] parts;
  private final boolean isDerived;
  private volatile Object metadata;

  public Key(Object[] parts) {
    this(parts, false, null);
  }

  protected Key(Object[] parts, boolean isDerived, Object metadata) {
    this.parts = parts;
    this.isDerived = isDerived;
    this.metadata = metadata;
  }

  @SuppressWarnings("unchecked")
  public <T> void setMetadata(T metadata) {
    this.metadata = metadata;
  }

  @SuppressWarnings("unchecked")
  public <T> T getMetadata() {
    return (T) metadata;
  }

  public Key derive() {
    Object[] newKey = new Object[parts.length + 1];
    System.arraycopy(parts, 0, newKey, 0, parts.length);
    newKey[parts.length] = UUID.randomUUID();
    return new Key(newKey, true, metadata);
  }

  @SuppressWarnings("unchecked")
  public <T> T getPart(int index) {
    if (index > parts.length - 1) {
      throw new RuntimeException(String.format("Can't get a part with index %d from %d long key",
                                               index,
                                               parts.length));
    } else {
      return (T) parts[index];
    }
  }

  public Key clone(Key metadataSource) {
    Key k = Key.wrap(parts);
    k.setMetadata(metadataSource.getMetadata());
    return k;
  }

  @Override
  public Key clone() {
    return Key.wrap(parts);
  }

  public boolean isDerivedFrom(Key other) {
    if (!isDerived || (this.parts.length <= other.parts.length)) {
      return false;
    }

    for(int i = 0; i < other.parts.length; i++) {
      if (!(other.parts[i].equals(this.parts[i]))) {
        return false;
      }
    }
    return true;
  }

  public boolean isDerived() {
    return isDerived;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;

    Key key = (Key) o;

    // Probably incorrect - comparing Object[] arrays with Arrays.equals
    if (!Arrays.equals(parts, key.parts))
      return false;

    return true;
  }

  @Override
  public int hashCode() {
    return parts != null ? Arrays.hashCode(parts) : 0;
  }

  public static Key wrap(Object k) {
    return new Key(new Object[] { k } );
  }

  public static Key wrap(Object... k) {
    return new Key(k);
  }

  @Override
  public String toString() {
    return "Key{" +
           "parts=" + Arrays.toString(parts) +
           '}';
  }

  public Object[] getObjects() {
    return Arrays.copyOf(parts, parts.length);
  }
}


text:
package org.devel.synfx.beads;

import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.Bead;
import net.beadsproject.beads.data.Buffer;
import net.beadsproject.beads.events.KillTrigger;
import net.beadsproject.beads.ugens.Envelope;
import net.beadsproject.beads.ugens.Gain;
import net.beadsproject.beads.ugens.WavePlayer;

public class Lesson06_Trigger {

	public static void main(String[] args) {

		AudioContext ac;

		ac = new AudioContext();
		 /*
		  * How do you trigger events to happen in the future?
		  *
		  * Here's one example where an Envelope is used to trigger
		  * the event. The event itself is a special class that
		  * kills another object, in this case a master gain object.
		  */

		  /*
		   * Here is the master gain object.
		   */
		  Gain masterGain = new Gain(ac, 1, 1);

		  /*
		   * Now two things. Firstly, a WavePlayer with an Envelope controlling
		   * its frequency, connected to a Gain.
		   */
		  Envelope freqEnv = new Envelope(ac, 250);
		  WavePlayer wp = new WavePlayer(ac, freqEnv, Buffer.SINE);
		  Gain g1 = new Gain(ac, 1, 0.3f);
		  g1.addInput(wp);

		  /*
		   * Secondly, just another WavePlayer connected to a Gain (no Envelope).
		   */
		  WavePlayer wp2 = new WavePlayer(ac, 255, Buffer.SQUARE);
		  Gain g2 = new Gain(ac, 1, 0.1f);
		  g2.addInput(wp2);

		  /*
		   * Connect them both to the master gain.
		   */
		  masterGain.addInput(g1);
		  masterGain.addInput(g2);

		  /*
		   * In this line we make the Gain envelope do something (fade to
		   * zero over 5 seconds), and then fire an event to a listener.
		   *
		   * All we have to do is tell the Envelope what listener to trigger.
		   * In this case, this will stop the second sound by killing g2.
		   *
		   * Note that "killing" any UGen causes it to be removed from the signal
		   * chain, and causes all of the things "upstream" from it to be
		   * removed as well.
		   */
		  freqEnv.addSegment(500, 5000, new KillTrigger(g2));

		  /*
		   * Now play
		   */
		  ac.out.addInput(masterGain);
		  ac.start();

		  /*
		   * Some other objects that can trigger events:
		   * Clock, DelayTrigger, PeakDetector.
		   *
		   * Some other objects that can respond to events:
		   * AudioContextStopTrigger, Pattern, PauseTrigger.
		   *
		   * It is easy to make your own trigger, by subclassing Bead.
		   * The following event gets added an extra 1s after the previous one.
		   */

		   Bead myTrigger = new Bead() {
		     public void messageReceived(Bead message) {
		        System.out.println("I've been triggered!");
		     }
		   };
		   freqEnv.addSegment(0, 1000, myTrigger);

	}
}


text:
module Memphis
  class Artist < Client

    ARTIST_URI = File.join(::Memphis::Configuration.base_uri, '/artist/profile?')

    def initialize
      super
    end

    def search id
      client_search ARTIST_URI, id
    end
  end
end


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

namespace Skills
{
    public static class Searching
    {
        /// <summary>
        /// Returns a step map (shows the best path to go from one point to another)
        /// </summary>
        /// <param name="map">a map to search the path. 1 is the starting point, 2 is the end point, 3 are obstacles and the rest should be 0's</param>
        /// <returns>If a map has a startpoint and endpoint, returns the path map, otherwise returns null</returns>
        public static int[,] AStarSearch(int[,] map)
        {
            List<Tuple<int, int>> openNodes = new List<Tuple<int, int>>();
            List<Tuple<int, int>> closedNodes = new List<Tuple<int, int>>();
            Tuple<int, int> startPoint = null;
            Tuple<int, int> endPoint = null;

            for (int i = 0; i < map.GetLength(0); i++)
            {
                for (int y = 0; y < map.GetLength(1); y++)
                {
                    if (map[i, y] == 1)
                    {
                        startPoint = new Tuple<int, int>(i, y);
                    }
                    else if (map[i, y] == 2)
                    {
                        endPoint = new Tuple<int, int>(i, y);
                    }
                }
            }

            if (startPoint == null || endPoint == null)
            {

                return null;
            }

            var validatePoint = new Func<Tuple<int, int>, bool>((currentPoint) => {
                if(currentPoint.Item1 < 0 || currentPoint.Item1 >= map.GetLength(0)
                || currentPoint.Item2 < 0 || currentPoint.Item2 >= map.GetLength(1))
                {
                    return false;
                }

                return true;
            });
            var analizeCurrentPoint = new Func<Tuple<int, int>, List<Tuple<int, int>>>((currentPoint) =>
            {
                int diffX = endPoint.Item1 - currentPoint.Item1;
                int diffY = endPoint.Item2 - currentPoint.Item2;
                if (Math.Abs(diffX) >= Math.Abs(diffY))
                {

                }
                else
                {

                }

                return null;
            });
            openNodes.Add(startPoint);
            int[,] pathMap = new int[map.GetLength(0), map.GetLength(1)];

            while (openNodes.Count > 0)
            {

            }

            return pathMap;
        }
    }
}


text:
<?php use_helper('recaptcha') ?>

<form action="<?php echo url_for('recaptcha/index') ?>" method="POST">
  <?php echo recaptcha_get_html(sfConfig::get('app_recaptcha_publickey'),
    $form['response']->getError()); ?>

  <input type="submit" />
</form>


text:
from distutils.command.config import config
from scipy import ndimage
from collections import Counter
from showattendtell.core.vggnet import Vgg19
from showattendtell.core.utils import *
from showattendtell.core import utils

import tensorflow as tf
import numpy as np
import pandas as pd
import hickle
import os
import json

def _process_caption_data(caption_file, image_dir, max_length):
    with open(caption_file) as f:
        caption_data = json.load(f)

    # id_to_filename is a dictionary such as {image_id: filename]}
    id_to_filename = {image['id']: image['file_name'] for image in caption_data['images']}

    # data is a list of dictionary which contains 'captions', 'file_name' and 'image_id' as key.
    data = []
    for annotation in caption_data['annotations']:
        image_id = annotation['image_id']
        annotation['file_name'] = os.path.join(image_dir, id_to_filename[image_id])
        data += [annotation]

    # convert to pandas dataframe (for later visualization or debugging)
    caption_data = pd.DataFrame.from_dict(data)
    del caption_data['id']
    caption_data.sort_values(by='image_id', inplace=True)
    caption_data = caption_data.reset_index(drop=True)

    del_idx = []
    for i, caption in enumerate(caption_data['caption']):
        caption = caption.replace('.','').replace(',','').replace("'","").replace('"','')
        caption = caption.replace('&','and').replace('(','').replace(")","").replace('-',' ')
        caption = " ".join(caption.split())  # replace multiple spaces

        caption_data.set_value(i, 'caption', caption.lower())
        if len(caption.split(" ")) > max_length:
            del_idx.append(i)

    # delete captions if size is larger than max_length
    print "The number of captions before deletion: %d" %len(caption_data)
    caption_data = caption_data.drop(caption_data.index[del_idx])
    caption_data = caption_data.reset_index(drop=True)
    print "The number of captions after deletion: %d" %len(caption_data)
    return caption_data

def _build_vocab(annotations, threshold=1):
    counter = Counter()
    max_len = 0
    for i, caption in enumerate(annotations['caption']):
        words = caption.split(' ') # caption contrains only lower-case words
        for w in words:
            counter[w] +=1

        if len(caption.split(" ")) > max_len:
            max_len = len(caption.split(" "))

    vocab = [word for word in counter if counter[word] >= threshold]
    print ('Filtered %d words to %d words with word count threshold %d.' % (len(counter), len(vocab), threshold))

    word_to_idx = {u'<NULL>': 0, u'<START>': 1, u'<END>': 2}
    idx = 3
    for word in vocab:
        word_to_idx[word] = idx
        idx += 1
    print "Max length of caption: ", max_len
    return word_to_idx

def _build_caption_vector(annotations, word_to_idx, max_length=15):
    n_examples = len(annotations)
    captions = np.ndarray((n_examples,max_length+2)).astype(np.int32)

    for i, caption in enumerate(annotations['caption']):
        words = caption.split(" ") # caption contrains only lower-case words
        cap_vec = []
        cap_vec.append(word_to_idx['<START>'])
        for word in words:
            if word in word_to_idx:
                cap_vec.append(word_to_idx[word])
        cap_vec.append(word_to_idx['<END>'])

        # pad short caption with the special null token '<NULL>' to make it fixed-size vector
        if len(cap_vec) < (max_length + 2):
            for j in range(max_length + 2 - len(cap_vec)):
                cap_vec.append(word_to_idx['<NULL>'])

        captions[i, :] = np.asarray(cap_vec)
    print "Finished building caption vectors"
    return captions

def _build_file_names(annotations):
    image_file_names = []
    id_to_idx = {}
    idx = 0
    image_ids = annotations['image_id']
    file_names = annotations['file_name']
    for image_id, file_name in zip(image_ids, file_names):
        if not image_id in id_to_idx:
            id_to_idx[image_id] = idx
            image_file_names.append(file_name)
            idx += 1

    file_names = np.asarray(image_file_names)
    return file_names, id_to_idx

def _build_image_idxs(annotations, id_to_idx):
    image_idxs = np.ndarray(len(annotations), dtype=np.int32)
    image_ids = annotations['image_id']
    for i, image_id in enumerate(image_ids):
        image_idxs[i] = id_to_idx[image_id]
    return image_idxs

def main():
    # batch size for extracting feature vectors from vggnet.
    batch_size = 100
    # maximum length of caption(number of word). if caption is longer than max_length, deleted.
    max_length = 15
    # if word occurs less than word_count_threshold in training dataset, the word index is special unknown token.
    word_count_threshold = 1
    # vgg model path
    vgg_model_path = './data/imagenet-vgg-verydeep-19.mat'

    caption_file = 'data/annotations/captions_train2014.json'
    image_dir = 'image/%2014_resized/'

    # about 80000 images and 400000 captions for train dataset
    train_dataset = _process_caption_data(caption_file='data/annotations/captions_train2014.json',
                                          image_dir='image/train2014_resized/',
                                          max_length=max_length)

    # about 40000 images and 200000 captions
    val_dataset = _process_caption_data(caption_file='data/annotations/captions_val2014.json',
                                        image_dir='image/val2014_resized/',
                                        max_length=max_length)

    # about 4000 images and 20000 captions for val / test dataset
    val_cutoff = int(0.1 * len(val_dataset))
    test_cutoff = int(0.2 * len(val_dataset))
    print 'Finished processing caption data'

    save_pickle(train_dataset, 'data/train/train.annotations.pkl')
    save_pickle(val_dataset[:val_cutoff], 'data/val/val.annotations.pkl')
    save_pickle(val_dataset[val_cutoff:test_cutoff].reset_index(drop=True), 'data/test/test.annotations.pkl')

    for split in ['train', 'val', 'test']:
        annotations = load_pickle('./data/%s/%s.annotations.pkl' % (split, split))

        if split == 'train':
            word_to_idx = _build_vocab(annotations=annotations, threshold=word_count_threshold)
            save_pickle(word_to_idx, './data/%s/word_to_idx.pkl' % split)

        captions = _build_caption_vector(annotations=annotations, word_to_idx=word_to_idx, max_length=max_length)
        save_pickle(captions, './data/%s/%s.captions.pkl' % (split, split))

        file_names, id_to_idx = _build_file_names(annotations)
        save_pickle(file_names, './data/%s/%s.file.names.pkl' % (split, split))

        image_idxs = _build_image_idxs(annotations, id_to_idx)
        save_pickle(image_idxs, './data/%s/%s.image.idxs.pkl' % (split, split))

        # prepare reference captions to compute bleu scores later
        image_ids = {}
        feature_to_captions = {}
        i = -1
        for caption, image_id in zip(annotations['caption'], annotations['image_id']):
            if not image_id in image_ids:
                image_ids[image_id] = 0
                i += 1
                feature_to_captions[i] = []
            feature_to_captions[i].append(caption.lower() + ' .')
        save_pickle(feature_to_captions, './data/%s/%s.references.pkl' % (split, split))
        print "Finished building %s caption dataset" %split

    # extract conv5_3 feature vectors
    vggnet = Vgg19(vgg_model_path)
    vggnet.build()
    with tf.Session(config=utils.config) as sess:
        tf.initialize_all_variables().run()
        for split in ['train', 'val', 'test']:
            anno_path = './data/%s/%s.annotations.pkl' % (split, split)
            save_path = './data/%s/%s.features.hkl' % (split, split)
            annotations = load_pickle(anno_path)
            image_path = list(annotations['file_name'].unique())
            n_examples = len(image_path)

            all_feats = np.ndarray([n_examples, 196, 512], dtype=np.float32)

            for start, end in zip(range(0, n_examples, batch_size),
                                  range(batch_size, n_examples + batch_size, batch_size)):
                image_batch_file = image_path[start:end]
                image_batch = np.array(map(lambda x: ndimage.imread(x, mode='RGB'), image_batch_file)).astype(
                    np.float32)
                feats = sess.run(vggnet.features, feed_dict={vggnet.images: image_batch})
                all_feats[start:end, :] = feats
                print ("Processed %d %s features.." % (end, split))

            # use hickle to save huge feature vectors
            hickle.dump(all_feats, save_path)
            print ("Saved %s.." % (save_path))

if __name__ == "__main__":
    main()


text:
/**
 * Several configuration validation functions.
 *
 * @module lignin/validation
 */

import path from 'path';
import _ from 'lodash';

import lignin from './index';

/**
 * NPM-style verbosity levels, with extra names to enable and disable all
 * levels.
 *
 * @type {Object.<string, number>}
 */
export const NPM_LEVELS = {
  // tslint:disable:object-literal-sort-keys
  off: -Infinity,
  error: 0,
  warn: 100,
  info: 200,
  verbose: 300,
  log: 300, // compatibility with built-in console
  debug: 400,
  silly: 500,
  all: Infinity
  // tslint:enable:object-literal-sort-keys
};

/**
 * What this tool considers a valid JavaScript identifier. Since there is
 * little support for unicode property classes, this regular expression will
 * not support all valid identifiers.
 *
 * @type {RegExp}
 */
const RE_IDENTIFIER = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;

/**
 * Validates another lignin module for configuration. That instance must be
 * an instance of lignin and be able to resolve a configuration state (by not
 * resolving to this instance).
 *
 * @memberof module:lignin/validation
 * @param {module:lignin} self - This instance of lignin.
 * @param {module:lignin} other - Another instance of lignin.
 * @returns {boolean} Whether the given instance can be used as a source of
 * configuration state.
 */
export function validateModule(self, other) {
  // Please note that classes cannot be used here, since each instance would
  // define its own class instance, always failing prototype chain tests.
  // Instead, use duck typing for this validation.

  if (!_.isFunction(_.get(other, 'configure'))) {
    return false;
  } else if (!_.isFunction(_.get(other, 'logger'))) {
    return false;
  } else if (!_.isObject(_.get(other, 'settings'))) {
    return false;
  } else if (self.settings === other.settings) {
    // Prevent cycles, which would cause infinite recursion
    return false;
  } else {
    return true;
  }
}

/**
 * Validates a full options object.
 *
 * @memberof module:lignin/validation
 *
 * @param {Object} options - The full configuration options.
 * @param {Object.<string, number>}
 * [options.levels={@link module:lignin/validation~NPM_LEVELS}] - Names must
 * be valid JavaScript identifiers, and values must be numeric.
 * @param {Object} [options.filters=empty] - Configured filters.
 * @param {string|Plugin} options.filters[]._ - Must be a valid plugin or
 * refer to an installed plugin.
 * @param {Object} [options.appenders=console] - Configured appenders.
 * @param {string|Plugin} options.appenders[]._ - Must be a valid plugin or
 * refer to an installed plugin.
 * @param {Object} [options.loggers=/] - Configured loggers.
 * @param {string} [options.loggers[].parent=/] - May refer to implicit
 * loggers, but must not result in cycles.
 * @param {string} [options.loggers[].level] - May refer to non-existing level
 * names, or the reserved names "off" and "all".
 * @param {string[]} [options.loggers[].filters=empty] - Must refer to
 * configured filters.
 * @param {string[]} [options.loggers[].appenders=empty] - Must refer to
 * configured appenders. The root logger will default to having all
 * configured appenders.
 * @param {boolean} [options.loggers[].swallow=true] - Must be boolean.
 * @param {module:lignin/settings} settings - The settings module instance
 * that will resolve plug-in references.
 *
 * @returns {Object} The sanitzed and validated options object.
 * @see module:lignin/settings#configure
 */
export function validateOptions(options, settings) {

  // set default values

  const r = _.defaults(options, {
    levels: NPM_LEVELS,

    loggers: _.defaultsDeep(options.loggers, {
      '/': {
        level: 'info'
      }
    }),

    filters: {},

    appenders: {
      'console': {
        _: 'console',
        level: 'all'
      }
    }
  });

  _.defaults(r.loggers['/'], {
    appenders: _.keys(r.appenders)
  });

  r.loggers = _.mapValues(r.loggers, (v, k) => _.defaultsDeep(v, {
    appenders: [],
    filters: [],
    level: undefined,
    parent: (path.posix.dirname(k) === '.') ? '/' : path.posix.dirname(k),
    swallow: true
  }));

  _.assign(r.loggers['/'], {
    parent: null,
    swallow: true
  });

  // validate configuration

  _.mapValues(r.levels, (v, k) => validateLevel(k, v));
  _.forEach(r.filters, (v, k) => validateFilter(k, v, settings));
  _.forEach(r.appenders, (v, k) => validateAppender(k, v, settings));
  _.forEach(r.loggers, (v, k) => validateLogger(k, v, r));

  return r;
}

/**
 * Validates a custom level. The numeric value must be numeric or null, and
 * the level name must be a valid JavaScript identifier.
 *
 * @param {string} name - The level name.
 * @param {number} value - The numeric value.
 */
export function validateLevel(name, value) {
  // The value might originate from an old-standard JSON, which did not define
  // numeric literals. Parsing that with the current standard should yield a
  // numeric string instead of a proper number.

  if (!RE_IDENTIFIER.test(name)
        || !(value === null || _.isString(value) || _.isNumber(value))) {
    throw new lignin.errors.ValidationError(
        'Invalid level configuration:', name);
  } else if (value === null) {
    // In some contexts, null is used to indicate that the configured value
    // should be removed, so that the default value can be used.
    return null;
  }

  const level = Number(value);
  if (_.isNaN(level)) {
    throw new lignin.errors.ValidationError(
        'Level value must be numeric:', name);
  }
  return level;
}

/**
 * Validates a filter configuration. The filter plug-in will not be
 * instantiated yet, so specific configuration will not be validated. It only
 * checks that the reference can be resolved and that the resolved plug-in
 * constructor responds to required filter methods.
 *
 * @memberof module:lignin/validation
 * @param {string} key - The filter instance identifier.
 * @param {Object} options - The filter configuration to be validated.
 * @param {module:lignin/settings} settings - The settings module that will
 * resolve plug-in references.
 */
export function validateFilter(key, options, settings) {
  if (!_.has(options, '_')) {
    throw new lignin.errors.ValidationError('Missing plugin type', key);
  }

  const plugin = _.isString(options._)
      ? settings.plugin(options._) : options._;

  if (!_.isFunction(plugin)
      || !_.isFunction(plugin.prototype.filter)) {
    throw new lignin.errors.ValidationError(
        'Invalid filter configuration:', key);
  }

  options._ = plugin;
}

/**
 * Validates an appender configuration. The appender plug-in will not be
 * instantiated yet, so specific configuration will not be validated. It only
 * checks that the reference can be resolved and that the resolved plug-in
 * constructor responds to required appender methods.
 *
 * @memberof module:lignin/validation
 * @param {string} key - The appender instance identifier.
 * @param {Object} options - The appender configuration to be validated.
 * @param {module:lignin/settings} settings - The settings module that will
 * resolve plug-in references.
 */
export function validateAppender(key, options, settings) {
  if (!_.has(options, '_')) {
    throw new lignin.errors.ValidationError('Missing plugin type', key);
  }

  const plugin = _.isString(options._)
      ? settings.plugin(options._) : options._;

  if (!_.isFunction(plugin)
      || !_.isFunction(plugin.prototype.append)) {
    throw new lignin.errors.ValidationError(
        'Invalid appender configuration:', key);
  }

  options._ = plugin;
}

/**
 * Validates a logger configuration. All filter and appender references must
 * resolve, and parent chains must not be circular.
 *
 * @memberof module:lignin/validation
 * @param {string} key - The logger name.
 * @param {Object} options - The logger options to validate.
 * @param {Object} context - The full configuration object to resolve
 * references from.
 */
export function validateLogger(key, options, context) {
  options.name = key;

  if (options.level !== undefined && !_.isString(options.level)) {
    throw new lignin.errors.ValidationError('Invalid logger level:', key);
  }

  if (options.filters.some(e => !_.has(context.filters, e))) {
    throw new lignin.errors.ValidationError(
        'Invalid filter in logger:', key);
  }

  if (options.appenders.some(e => !_.has(context.appenders, e))) {
    throw new lignin.errors.ValidationError(
        'Invalid appender in logger:', key);
  }

  if (key === '/') {
    return;
  }

  let p = _.get(options, 'parent', '/');
  const visited = new Set();
  visited.add(key);

  while (p !== '/') {
    if (visited.has(p)) {
      throw new lignin.errors.ValidationError(
          'Invalid logger parent:', key);
    }

    let logger = context.loggers[p];
    while (logger === undefined) {
      // implicit logger

      visited.add(p);
      p = path.posix.dirname(p);
      if (p === '.') {
        // reached root logger
        return;
      }

      logger = context.loggers[p];
    }

    visited.add(p);
    p = logger.parent;
  }
}


text:
package com.ev3.item;

import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.UUID;

public class ItemId {
    private static final int UUID_BYTE_LENGTH = 16;

    public static String generate() {
        UUID uuid = UUID.randomUUID();

        ByteBuffer uuidByteBuffer = ByteBuffer.wrap(new byte[UUID_BYTE_LENGTH]);
        uuidByteBuffer.putLong(uuid.getMostSignificantBits());
        uuidByteBuffer.putLong(uuid.getLeastSignificantBits());

        return Base64.getUrlEncoder().encodeToString(uuidByteBuffer.array());
    }
}


text:
class Browser;
class SkBitmap;

namespace content {
class RenderViewHost;
}

namespace extensions {
class ExtensionHost;
}

// This class represents extension views. An extension view internally contains
// a bridge to an extension process, which draws to the extension view's
// native view object through IPC.
class ExtensionViewMac : public extensions::ExtensionView {
 public:
  class Container {
   public:
    virtual ~Container() {}
    virtual void OnExtensionSizeChanged(ExtensionViewMac* view,
                                        const gfx::Size& new_size) {}
    virtual void OnExtensionViewDidShow(ExtensionViewMac* view) {};
  };

  // The minimum/maximum dimensions of the popup.
  // The minimum is just a little larger than the size of the button itself.
  // The maximum is an arbitrary number that should be smaller than most
  // screens.
  static const CGFloat kMinWidth;
  static const CGFloat kMinHeight;
  static const CGFloat kMaxWidth;
  static const CGFloat kMaxHeight;

  ExtensionViewMac(extensions::ExtensionHost* extension_host, Browser* browser);
  ~ExtensionViewMac() override;

  // Sets the container for this view.
  void set_container(Container* container) { container_ = container; }

  // Informs the view that its containing window's frame changed.
  void WindowFrameChanged();

  // Create the host view, adding it as a subview of |superview|.
  void CreateWidgetHostViewIn(gfx::NativeView superview);

  // extensions::ExtensionView:
  Browser* GetBrowser() override;
  gfx::NativeView GetNativeView() override;
  void ResizeDueToAutoResize(content::WebContents* web_contents,
                             const gfx::Size& new_size) override;
  void RenderViewCreated(content::RenderViewHost* render_view_host) override;
  void HandleKeyboardEvent(
      content::WebContents* source,
      const content::NativeWebKeyboardEvent& event) override;
  void DidStopLoading() override;

 private:
  content::RenderViewHost* render_view_host() const;

  // We wait to show the ExtensionView until several things have loaded.
  void ShowIfCompletelyLoaded();

  Browser* browser_;  // weak

  extensions::ExtensionHost* extension_host_;  // weak

  // What we should set the preferred width to once the ExtensionView has
  // loaded.
  gfx::Size pending_preferred_size_;

  Container* container_;

  DISALLOW_COPY_AND_ASSIGN(ExtensionViewMac);
};

#endif  // CHROME_BROWSER_UI_COCOA_EXTENSIONS_EXTENSION_VIEW_MAC_H_


text:
<?php session_start(); ?>
<meta name="author" content="Thomas Flucke">
<meta name="copyright" content=""><!-- TODO -->
<meta name="keywords" content="dominion randomizer card picker untility">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="expires" content="0">
<link type="text/css" href="styles/dominion.css" rel="stylesheet" />
<link type="text/css" href="/jquery/css/smoothness/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" />
<script type="text/javascript" src="/jquery/jquery.min.js"></script>
<script type="text/javascript" src="/jquery/jquery-ui.min.js"></script>
<script type="text/javascript" src="/jquery/jquery.cookie.js"></script>
<script type="text/javascript" src="/js-masonry/masonry.pkgd.min.js"></script>


text:
#include "CCUserDefault.h"
#include "platform/CCPlatformConfig.h"
#include "platform/CCCommon.h"
#include "support/base64.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"

// root name of xml
#define USERDEFAULT_ROOT_NAME    "userDefaultRoot"

#define KEEP_COMPATABILITY

#define XML_FILE_NAME "UserDefault.xml"

#ifdef KEEP_COMPATABILITY
#include "platform/CCFileUtils.h"
#include "../tinyxml2/tinyxml2.h"
#endif

using namespace std;

NS_CC_BEGIN

/**
 * implements of UserDefault
 */

UserDefault* UserDefault::_userDefault = 0;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;

#ifdef KEEP_COMPATABILITY
static tinyxml2::XMLElement* getXMLNodeForKey(const char* pKey, tinyxml2::XMLDocument **doc)
{
    tinyxml2::XMLElement* curNode = NULL;
    tinyxml2::XMLElement* rootNode = NULL;

    if (! UserDefault::isXMLFileExist())
    {
        return NULL;
    }

    // check the key value
    if (! pKey)
    {
        return NULL;
    }

    do
    {
        tinyxml2::XMLDocument* xmlDoc = new tinyxml2::XMLDocument();
        *doc = xmlDoc;
        unsigned long nSize;
        const char* pXmlBuffer = (const char*)FileUtils::getInstance()->getFileData(UserDefault::getInstance()->getXMLFilePath().c_str(), "rb", &nSize);
        //const char* pXmlBuffer = (const char*)data.getBuffer();
        if(NULL == pXmlBuffer)
        {
            CCLOG("can not read xml file");
            break;
        }
        xmlDoc->Parse(pXmlBuffer);
		delete[] pXmlBuffer;
        // get root node
        rootNode = xmlDoc->RootElement();
        if (NULL == rootNode)
        {
            CCLOG("read root node error");
            break;
        }
        // find the node
        curNode = rootNode->FirstChildElement();
        if (!curNode)
        {
            // There is not xml node, delete xml file.
            remove(UserDefault::getInstance()->getXMLFilePath().c_str());

            return NULL;
        }

        while (NULL != curNode)
        {
            const char* nodeName = curNode->Value();
            if (!strcmp(nodeName, pKey))
            {
                // delete the node
                break;
            }

            curNode = curNode->NextSiblingElement();
        }
    } while (0);

    return curNode;
}

static void deleteNode(tinyxml2::XMLDocument* doc, tinyxml2::XMLElement* node)
{
    if (node)
    {
        doc->DeleteNode(node);
        doc->SaveFile(UserDefault::getInstance()->getXMLFilePath().c_str());
        delete doc;
    }
}

static void deleteNodeByKey(const char *pKey)
{
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    deleteNode(doc, node);
}
#endif

/**
 * If the user invoke delete UserDefault::getInstance(), should set _userDefault
 * to null to avoid error when he invoke UserDefault::getInstance() later.
 */
UserDefault::~UserDefault()
{
	CC_SAFE_DELETE(_userDefault);
    _userDefault = NULL;
}

UserDefault::UserDefault()
{
	_userDefault = NULL;
}

// XXX: deprecated
void UserDefault::purgeSharedUserDefault()
{
    UserDefault::destroyInstance();
}

void UserDefault::destroyInstance()
{
    _userDefault = NULL;
}

bool UserDefault::getBoolForKey(const char* pKey)
{
    return getBoolForKey(pKey, false);
}

bool UserDefault::getBoolForKey(const char* pKey, bool defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            const char* value = (const char*)node->FirstChild()->Value();
            bool ret = (! strcmp(value, "true"));

            // set value in NSUserDefaults
            setBoolForKey(pKey, ret);
            flush();

            // delete xmle node
            deleteNode(doc, node);

            return ret;
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

    return getBoolForKeyJNI(pKey, defaultValue);
}

int UserDefault::getIntegerForKey(const char* pKey)
{
    return getIntegerForKey(pKey, 0);
}

int UserDefault::getIntegerForKey(const char* pKey, int defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            int ret = atoi((const char*)node->FirstChild()->Value());

            // set value in NSUserDefaults
            setIntegerForKey(pKey, ret);
            flush();

            // delete xmle node
            deleteNode(doc, node);

            return ret;
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

	return getIntegerForKeyJNI(pKey, defaultValue);
}

float UserDefault::getFloatForKey(const char* pKey)
{
    return getFloatForKey(pKey, 0.0f);
}

float UserDefault::getFloatForKey(const char* pKey, float defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            float ret = atof((const char*)node->FirstChild()->Value());

            // set value in NSUserDefaults
            setFloatForKey(pKey, ret);
            flush();

            // delete xmle node
            deleteNode(doc, node);

            return ret;
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

    return getFloatForKeyJNI(pKey, defaultValue);
}

double  UserDefault::getDoubleForKey(const char* pKey)
{
    return getDoubleForKey(pKey, 0.0);
}

double UserDefault::getDoubleForKey(const char* pKey, double defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            double ret = atof((const char*)node->FirstChild()->Value());

            // set value in NSUserDefaults
            setDoubleForKey(pKey, ret);
            flush();

            // delete xmle node
            deleteNode(doc, node);

            return ret;
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

	return getDoubleForKeyJNI(pKey, defaultValue);
}

std::string UserDefault::getStringForKey(const char* pKey)
{
    return getStringForKey(pKey, "");
}

string UserDefault::getStringForKey(const char* pKey, const std::string & defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            string ret = (const char*)node->FirstChild()->Value();

            // set value in NSUserDefaults
            setStringForKey(pKey, ret);
            flush();

            // delete xmle node
            deleteNode(doc, node);

            return ret;
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

    return getStringForKeyJNI(pKey, defaultValue.c_str());
}

Data* UserDefault::getDataForKey(const char* pKey)
{
    return getDataForKey(pKey, NULL);
}

Data* UserDefault::getDataForKey(const char* pKey, Data* defaultValue)
{
#ifdef KEEP_COMPATABILITY
    tinyxml2::XMLDocument* doc = NULL;
    tinyxml2::XMLElement* node = getXMLNodeForKey(pKey, &doc);
    if (node)
    {
        if (node->FirstChild())
        {
            const char * encodedData = node->FirstChild()->Value();

            unsigned char * decodedData;
            int decodedDataLen = base64Decode((unsigned char*)encodedData, (unsigned int)strlen(encodedData), &decodedData);

            if (decodedData) {
                Data *ret = Data::create(decodedData, decodedDataLen);

                // set value in NSUserDefaults
                setDataForKey(pKey, ret);

                CC_SAFE_DELETE_ARRAY(decodedData);

                delete decodedData;

                flush();

                // delete xmle node
                deleteNode(doc, node);

                return ret;
            }
        }
        else
        {
            // delete xmle node
            deleteNode(doc, node);
        }
    }
#endif

    char * encodedDefaultData = NULL;
    unsigned int encodedDefaultDataLen = defaultValue ? base64Encode(defaultValue->getBytes(), defaultValue->getSize(), &encodedDefaultData) : 0;

    string encodedStr = getStringForKeyJNI(pKey, encodedDefaultData);

    if (encodedDefaultData) {
        delete encodedDefaultData;
    }

    CCLOG("ENCODED STRING: --%s--%d", encodedStr.c_str(), encodedStr.length());

    Data *ret = defaultValue;

    unsigned char * decodedData = NULL;
    int decodedDataLen = base64Decode((unsigned char*)encodedStr.c_str(), (unsigned int)encodedStr.length(), &decodedData);

    CCLOG("AFTER DECoDE. ret %p defaultValue %p", ret, defaultValue);
    CCLOG("DECoDED DATA: %s %d", decodedData, decodedDataLen);

    if (decodedData && decodedDataLen) {
        ret = Data::create(decodedData, decodedDataLen);
    }

    CCLOG("RETURNED %p!", ret);

    return ret;
}

void UserDefault::setBoolForKey(const char* pKey, bool value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    return setBoolForKeyJNI(pKey, value);
}

void UserDefault::setIntegerForKey(const char* pKey, int value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    return setIntegerForKeyJNI(pKey, value);
}

void UserDefault::setFloatForKey(const char* pKey, float value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    return setFloatForKeyJNI(pKey, value);
}

void UserDefault::setDoubleForKey(const char* pKey, double value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    return setDoubleForKeyJNI(pKey, value);
}

void UserDefault::setStringForKey(const char* pKey, const std::string & value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    return setStringForKeyJNI(pKey, value.c_str());
}

void UserDefault::setDataForKey(const char* pKey, const Data& value)
{
#ifdef KEEP_COMPATABILITY
    deleteNodeByKey(pKey);
#endif

    CCLOG("SET DATA FOR KEY: --%s--%d", value.getBytes(), value.getSize());
    char * encodedData = NULL;
    unsigned int encodedDataLen = base64Encode(value.getBytes(), value.getSize(), &encodedData);

    CCLOG("SET DATA ENCODED: --%s", encodedData);

    return setStringForKeyJNI(pKey, encodedData);

    if (encodedData) {
        delete encodedData;
    }
}

// XXX: deprecated
UserDefault* UserDefault::sharedUserDefault()
{
    return UserDefault::getInstance();
}

UserDefault* UserDefault::getInstance()
{
#ifdef KEEP_COMPATABILITY
    initXMLFilePath();
#endif

    if (! _userDefault)
    {
        _userDefault = new UserDefault();
    }

    return _userDefault;
}

bool UserDefault::isXMLFileExist()
{
    FILE *fp = fopen(_filePath.c_str(), "r");
    bool bRet = false;

    if (fp)
    {
        bRet = true;
        fclose(fp);
    }

    return bRet;
}

void UserDefault::initXMLFilePath()
{
#ifdef KEEP_COMPATABILITY
    if (! _isFilePathInitialized)
    {
        // UserDefault.xml is stored in /data/data/<package-path>/ before v2.1.2
        _filePath += "/data/data/" + getPackageNameJNI() + "/" + XML_FILE_NAME;
        _isFilePathInitialized = true;
    }
#endif
}

// create new xml file
bool UserDefault::createXMLFile()
{
    return false;
}

const string& UserDefault::getXMLFilePath()
{
    return _filePath;
}

void UserDefault::flush()
{
}

NS_CC_END

#endif // (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)


text:
* [Basic configuration](basic_configuration.md)
* Configuring
    * [Configuring user registration strategy](configuring_user_registration_strategy.md)
    * [Configuring password change strategy](configuring_password_change_strategy.md)
    * [Disabling login/logout](configuring_disabling_login_logout.md)
    * [Disabling user removal](configuring_disabling_user_removal.md)
    * [Configuring default roles](configuring_default_roles.md)
    * [Configuring routes used](configuring_routes_used.md)
* Usage
    * [Using an existing use case](usage_existing_use_cases.md)
    * [Using an existing event subscriber](usage_events_subscribers.md)
    * [Using routes by default](usage_routes_by_default.md)
    * [Using an existing sign up type](usage_existing_sign_up_type.md)
    * [Using JWT authentication](usage_jwt_authentication.md)
    * [Using console commands](usage_console_commands.md)
    * [Multiple user entities](usage_multiple_users.md)
    * [MongoDB's Doctrine ODM](doctrine_odm_mongodb.md)
* Extending
    * [Create custom use case](extending_create_custom_use_case.md)
    * [Create custom subscriber](extending_create_custom_subscriber.md)
    * [Customize URLs](extending_customize_urls.md)
    * [Custom views](extending_custom_views.md)
* Reference
    * [Service reference](reference_services.md)
    * [Configuration reference](reference_configuration.md)
    * [Command reference](https://github.com/BenGorUser/User/blob/master/docs/command.md)
* Adapters
    * [Bus adapters](adapters_buses.md)
    * [Mailer adapters](adapters_mailers.md)
    * [Persistence adapters](adapters_persistence.md)
* [Frequently Asked Questions](faq.md)


text:
                            Very Short Call Out Message

                            Venis ea eosae occulpari odit volum. Quiati diorerc hiliquam, sernatquibus sent, que poriorem sustet aut voluptas cium re nait en dit is doleng at thist ud anta proa.


text:
    <?php include 'includes/header.php'; ?>

    <title>Replay Files</title>

    <link href="lib/bootstrap.min.css" rel="stylesheet">
    <link href="style/general.css" rel="stylesheet">
    <link href="style/learn.css" rel="stylesheet">

        <?php include 'includes/navbar.php'; ?>

            <?php include 'includes/learn_sidebar.php'; ?>

Replay Files

Overview

A Halite replay file is a JSON object which describes what occurred during the game. Halite replay files are easy to parse and reasonably compact (and extremely compact when compressed), making them ideal for both using machine learning on Halite as well as sharing interesting games. The extension .hlt is used to distinguish Halite replay files.

Detailed Specification

A Halite replay file contains only a single JSON object. This object has the following attributes:

version - Describes the version of the replay file. The present version is 11, which is expected to be stable for a while.

width - A positive integer representing the width of the map.

height - A positive integer representing the height of the map.

num_players - A positive integer of at least 2 representing the number of players taking part in the game.

num_frames - The number of frames encoded in this replay.

player_names - An array of strings which correspond to the names of the players, starting with the player with tag 1 and ending with the player with tag num_players.

productions - A 2D array of integers which represent the productions of the tiles on the map. These integers fill in the map from row 1 (i.e. the top) to row height and within a row from column 1 to column width and are all guaranteed to be positive and less than 255.

frames - A 4D arrays of integers. This is the most complex piece of the file specification, so here it is step by step:

The outermost array has length num_frames, and it contains individual frames.

The next array inwards has length height, and it contains individual rows of the frame. The first element is the first (top) row and the last is the bottom row.

The following array has length width, and it contains individual sites of the frame. The first element is the first (leftmost) column and the last is the rightmost row.

The innermost array has length 2 and contains integers. Its contents represent the attributes of a given site. The first element is always the owner of the site and the second element is the strength of the site.

moves - A 3D arrays of integers. The outermost array has length num_frames - 1 and contains the moves for an individual frame. Each element is a 2D array of integers which represent the directions chosen to move for every site on the map. As always, the outer layer of the 2D array fills in the rows from top to bottom and the inside layer fills in individual rows from left to right. The integer values for each site are: STILL = 0, NORTH = 1, EAST = 2, SOUTH = 3, and WEST = 4. Sites not owned by any player are assigned the value of 0.

                    <?php include 'includes/footer.php'; ?>


text:
export function register(user, token) {
    return {
        type: 'AUTH_REGISTER',
        user: user,
        token: token
    };
}

export function login(user, token, isAdmin) {
    return {
        type: 'AUTH_LOGIN',
        user: user,
        token: token,
        isAdmin: isAdmin
    };
}

export function logout() {
    return {
        type: 'AUTH_LOGOUT'
    };
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Resources;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("Peasouper")]
[assembly: AssemblyDescription("Portable .NET API for FogBugz bug tracking system")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright("Jason Duffett 2015")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("0.1.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]

[assembly: NeutralResourcesLanguageAttribute("en")]


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

namespace inin.Bridge.WebServices.Datadip.Lib
{
    [ServiceContract(Name= "RESTDemoServices")]
    public interface IWebServicesServer
    {
        [OperationContract]
        [WebInvoke(UriTemplate = "GetContactByPhoneNumber", BodyStyle = WebMessageBodyStyle.Bare, Method= "POST", ResponseFormat= WebMessageFormat.Json)]
        ResponseContact GetContactByPhoneNumber(PhoneNumberRequest req);

        [OperationContract]
        [WebInvoke(UriTemplate = "GetAccountByPhoneNumber", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        ResponseAccount GetAccountByPhoneNumber(PhoneNumberRequest req);

        [OperationContract]
        [WebInvoke(UriTemplate = "GetAccountByAccountNumber", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        ResponseAccount GetAccountByAccountNumber(AccountNumberRequest req);

        [OperationContract]
        [WebInvoke(UriTemplate = "GetAccountByContactId", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        ResponseAccount GetAccountByContactId(ContactIdRequest cidr);

        [OperationContract]
        [WebInvoke(UriTemplate = "GetMostRecentOpenCaseByContactId", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        ResponseCase GetMostRecentOpenCaseByContactId(ContactIdRequest cidr);
    }
}


text:
(function () {
    'use strict';

    angular.module('Fablab').controller('ReservationListController', function ($scope, $filter,
            $location, ngTableParams, ReservationService, NotificationService) {
        $scope.criteria = {
            dateFrom: moment().startOf('month').toDate(),
            dateTo: moment().endOf('month').toDate()
        };

        $scope.calendarEvents = [];

        $scope.tableParams = new ngTableParams(
                angular.extend({
                    page: 1, // show first page
                    count: 25, // count per page
                    sorting: {
                        dateStart: 'asc'
                    }
                }, $location.search()), {
            getData: function ($defer, params) {
                if ($scope.reservations) {
                    var filteredData = params.filter() ? $filter('filter')($scope.reservations, params.filter()) : $scope.reservations;
                    var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : filteredData;
                    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
            }
        });

        $scope.updateReservationList = function () {
            var criteria = {
                dateFrom: $filter('cropToDate')($scope.criteria.dateFrom),
                dateTo: $filter('cropToDate')($scope.criteria.dateTo)
            };
            ReservationService.search(criteria, function (data) {
                for (var i = 0; i < data.length; i++) {
                    data[i].machineName = ""; //initialization of new property
                    data[i].machineName = data[i].machine.name;  //set the data from nested obj into new property
                    data[i].userName = ""; //initialization of new property
                    data[i].userName = data[i].user === null ? "FabLab" : $filter('prettyUser')(data[i].user);  //set the data from nested obj into new property
                }
                $scope.reservations = data;
                $scope.tableParams.reload();
                updateCalendarEvent();
            });
        };

        var updateCalendarEvent = function () {
            $scope.calendarEvents.length = 0;
            for (var i = 0; i < $scope.reservations.length; i++) {
                var r = $scope.reservations[i];
                $scope.calendarEvents.push({
                    title: r.machine.name,
                    start: new Date(r.dateStart),
                    end: new Date(r.dateEnd)});
            }
        };

        $scope.remove = function (reservation) {
            ReservationService.remove(reservation.reservationId, function () {
                $scope.updateReservationList();
            });
        };

        $scope.softRemove = function (reservation) {
            ReservationService.softRemove(reservation.id, function () {
                NotificationService.notify("success", "reservation.notification.removed");
                $scope.updateReservationList();
            });
        };

        $scope.updateReservationList();

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();

        /* event source that pulls from google.com */
        $scope.dataSourceGoogleAgenda = {
            url: App.CONFIG.GOOGLE_CALENDAR_URL,
            className: 'gcal-event',
            currentTimezone: App.CONFIG.CALENDAR_TIME_ZONE,
            color: App.CONFIG.CALENDAR_AGENDA_COLOR,
            textColor: 'black'
        };

        $scope.dataSourceReservation = {
            events: $scope.calendarEvents,
            color: App.CONFIG.CALENDAR_RESERVATION_COLOR
        };

        /* config object */
        $scope.uiConfig = {
            calendar: {
                googleCalendarApiKey: App.CONFIG.GOOGLE_CALENDAR_API_KEY,
                height: 450,
                editable: false,
                firstDay: 1,
                header: {
                    left: 'title',
                    center: 'month,agendaWeek,agendaDay',
                    right: 'today prev,next'
                }
            }
        };

        /* event sources array*/
        $scope.eventSources = [$scope.dataSourceGoogleAgenda, $scope.dataSourceReservation];

        $scope.today = function () {
            $scope.dt = new Date();
        };
        $scope.today();

        $scope.clear = function () {
            $scope.dt = null;
        };

        $scope.open = function ($event) {
            $event.preventDefault();
            $event.stopPropagation();

            $scope.opened = true;
        };

        $scope.dateOptions = {
            formatYear: 'yy',
            startingDay: 1
        };

        $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy HH:mm', 'shortDate'];
        $scope.format = $scope.formats[2];

        var tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        var afterTomorrow = new Date();
        afterTomorrow.setDate(tomorrow.getDate() + 2);
        $scope.events =
                [
                    {
                        date: tomorrow,
                        status: 'full'
                    },
                    {
                        date: afterTomorrow,
                        status: 'partially'
                    }
                ];

        $scope.getDayClass = function (date, mode) {
            if (mode === 'day') {
                var dayToCheck = new Date(date).setHours(0, 0, 0, 0);

                for (var i = 0; i < $scope.events.length; i++) {
                    var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);

                    if (dayToCheck === currentDay) {
                        return $scope.events[i].status;
                    }
                }
            }

            return '';
        };
    });

}());


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The GNU C Library: Delivery of Signal</title>

<meta name="description" content="The GNU C Library: Delivery of Signal">
<meta name="keywords" content="The GNU C Library: Delivery of Signal">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Concepts-of-Signals.html#Concepts-of-Signals" rel="up" title="Concepts of Signals">
<link href="Standard-Signals.html#Standard-Signals" rel="next" title="Standard Signals">
<link href="Signal-Generation.html#Signal-Generation" rel="prev" title="Signal Generation">

Previous: Signal Generation, Up: Concepts of Signals   [Contents][Index]

24.1.3 How Signals Are Delivered

When a signal is generated, it becomes pending.  Normally it
remains pending for just a short period of time and then is
delivered to the process that was signaled.  However, if that kind
of signal is currently blocked, it may remain pending
indefinitely—until signals of that kind are unblocked.  Once
unblocked, it will be delivered immediately.  See Blocking Signals.

When the signal is delivered, whether right away or after a long delay,
the specified action for that signal is taken.  For certain
signals, such as SIGKILL and SIGSTOP, the action is fixed,
but for most signals, the program has a choice: ignore the signal,
specify a handler function, or accept the default action for
that kind of signal.  The program specifies its choice using functions
such as signal or sigaction (see Signal Actions).  We
sometimes say that a handler catches the signal.  While the
handler is running, that particular signal is normally blocked.

If the specified action for a kind of signal is to ignore it, then any
such signal which is generated is discarded immediately.  This happens
even if the signal is also blocked at the time.  A signal discarded in
this way will never be delivered, not even if the program subsequently
specifies a different action for that kind of signal and then unblocks
it.

If a signal arrives which the program has neither handled nor ignored,
its default action takes place.  Each kind of signal has its own
default action, documented below (see Standard Signals).  For most kinds
of signals, the default action is to terminate the process.  For certain
kinds of signals that represent “harmless” events, the default action
is to do nothing.

When a signal terminates a process, its parent process can determine the
cause of termination by examining the termination status code reported
by the wait or waitpid functions.  (This is discussed in
more detail in Process Completion.)  The information it can get
includes the fact that termination was due to a signal and the kind of
signal involved.  If a program you run from a shell is terminated by a
signal, the shell typically prints some kind of error message.

The signals that normally represent program errors have a special
property: when one of these signals terminates the process, it also
writes a core dump file which records the state of the process at
the time of termination.  You can examine the core dump with a debugger
to investigate what caused the error.

If you raise a “program error” signal by explicit request, and this
terminates the process, it makes a core dump file just as if the signal
had been due directly to an error.

Previous: Signal Generation, Up: Concepts of Signals   [Contents][Index]


text:
<?xml version='1.0' encoding='UTF-8'?>
<!--
Copyright 2014 satrapu.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <application id="churchmanagement">
        <locale-config>
            <default-locale>en_US</default-locale>
            <supported-locale>ro_RO</supported-locale>
        </locale-config>
        <resource-bundle>
            <base-name>ro.satrapu.churchmanagement.ui.messages</base-name>
            <var>msg</var>
        </resource-bundle>
        <!--
            The message-bundle XML node is needed in order to localize JSF converters and validators messages.
        -->
        <message-bundle>ro.satrapu.churchmanagement.ui.messages</message-bundle>
        <message-bundle>ValidationMessages</message-bundle>
    </application>
    <lifecycle>
        <!--
            The PageNavigationAwareFacesMessages phase listener needed to restore FacesMessage instances when navigating
            from a page to another.
        -->
        <phase-listener>ro.satrapu.churchmanagement.ui.messages.PageNavigationAwareFacesMessages</phase-listener>
    </lifecycle>
</faces-config>