text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.view;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.opengl.Matrix;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowInsets;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import org.json.JSONException;
import org.json.JSONObject;

import org.chromium.base.JNINamespace;
import org.chromium.mojo.bindings.Interface.Binding;
import org.chromium.mojo.bindings.InterfaceRequest;
import org.chromium.mojo.system.Core;
import org.chromium.mojo.system.MessagePipeHandle;
import org.chromium.mojo.system.MojoException;
import org.chromium.mojo.system.Pair;
import org.chromium.mojo.system.impl.CoreImpl;
import org.chromium.mojom.editing.Keyboard;
import org.chromium.mojom.flutter.platform.ApplicationMessages;
import org.chromium.mojom.mojo.ServiceProvider;
import org.chromium.mojom.pointer.Pointer;
import org.chromium.mojom.pointer.PointerKind;
import org.chromium.mojom.pointer.PointerPacket;
import org.chromium.mojom.pointer.PointerType;
import org.chromium.mojom.raw_keyboard.RawKeyboardService;
import org.chromium.mojom.semantics.SemanticsServer;
import org.chromium.mojom.sky.AppLifecycleState;
import org.chromium.mojom.sky.ServicesData;
import org.chromium.mojom.sky.SkyEngine;
import org.chromium.mojom.sky.ViewportMetrics;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.domokit.common.ActivityLifecycleListener;
import org.domokit.activity.ActivityImpl;
import org.domokit.editing.KeyboardImpl;
import org.domokit.editing.KeyboardViewState;
import org.domokit.raw_keyboard.RawKeyboardServiceImpl;
import org.domokit.raw_keyboard.RawKeyboardServiceState;

/**
 * An Android view containing a Flutter app.
 */
@JNINamespace("sky::shell")
public class FlutterView extends SurfaceView
  implements AccessibilityManager.AccessibilityStateChangeListener,
             AccessibilityManager.TouchExplorationStateChangeListener {
    private static final String TAG = "FlutterView";

    private static final String ACTION_DISCOVER = "io.flutter.view.DISCOVER";

    private long mNativePlatformView;
    private SkyEngine.Proxy mSkyEngine;
    private ServiceProviderImpl mPlatformServiceProvider;
    private Binding mPlatformServiceProviderBinding;
    private ServiceProviderImpl mViewServiceProvider;
    private Binding mViewServiceProviderBinding;
    private ServiceProvider.Proxy mDartServiceProvider;
    private ApplicationMessages.Proxy mFlutterAppMessages;
    private HashMap<String, OnMessageListener> mOnMessageListeners;
    private HashMap<String, OnMessageListenerAsync> mAsyncOnMessageListeners;
    private final SurfaceHolder.Callback mSurfaceCallback;
    private final ViewportMetrics mMetrics;
    private final KeyboardViewState mKeyboardState;
    private final RawKeyboardServiceState mRawKeyboardState;
    private final AccessibilityManager mAccessibilityManager;
    private BroadcastReceiver discoveryReceiver;
    private List<ActivityLifecycleListener> mActivityLifecycleListeners;

    public FlutterView(Context context) {
        this(context, null);
    }

    public FlutterView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TODO(abarth): Remove this static and instead make everything that
        // depends on it into a view-associated service.
        ActivityImpl.setCurrentActivity((Activity) context);

        mMetrics = new ViewportMetrics();
        mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
        setFocusable(true);
        setFocusableInTouchMode(true);

        attach();
        assert mNativePlatformView != 0;

        mSurfaceCallback = new SurfaceHolder.Callback() {
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                assert mNativePlatformView != 0;
                nativeSurfaceCreated(mNativePlatformView, holder.getSurface());
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                assert mNativePlatformView != 0;
                nativeSurfaceDestroyed(mNativePlatformView);
            }
        };
        getHolder().addCallback(mSurfaceCallback);

        mKeyboardState = new KeyboardViewState(this);
        mRawKeyboardState = new RawKeyboardServiceState();

        Core core = CoreImpl.getInstance();

        mPlatformServiceProvider = new ServiceProviderImpl(core, this, ServiceRegistry.SHARED);

        ServiceRegistry localRegistry = new ServiceRegistry();
        configureLocalServices(localRegistry);
        mViewServiceProvider = new ServiceProviderImpl(core, this, localRegistry);

        mAccessibilityManager = (AccessibilityManager)getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);

        mOnMessageListeners = new HashMap<String, OnMessageListener>();
        mAsyncOnMessageListeners = new HashMap<String, OnMessageListenerAsync>();
        mActivityLifecycleListeners = new ArrayList<ActivityLifecycleListener>();

        setLocale(getResources().getConfiguration().locale);

        if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            discoveryReceiver = new DiscoveryReceiver();
            context.registerReceiver(discoveryReceiver, new IntentFilter(ACTION_DISCOVER));
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (mRawKeyboardState.onKey(this, keyCode, event))
            return true;
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mRawKeyboardState.onKey(this, keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }

    SkyEngine getEngine() {
        return mSkyEngine;
    }

    public void addActivityLifecycleListener(ActivityLifecycleListener listener) {
        mActivityLifecycleListeners.add(listener);
    }

    public void onPause() {
        mSkyEngine.onAppLifecycleStateChanged(AppLifecycleState.PAUSED);
    }

    public void onPostResume() {
        for (ActivityLifecycleListener listener : mActivityLifecycleListeners)
            listener.onPostResume();

        mSkyEngine.onAppLifecycleStateChanged(AppLifecycleState.RESUMED);
    }

    public void pushRoute(String route) {
        mSkyEngine.pushRoute(route);
    }

    public void popRoute() {
        mSkyEngine.popRoute();
    }

    private void setLocale(Locale locale) {
        mSkyEngine.onLocaleChanged(locale.getLanguage(), locale.getCountry());
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setLocale(newConfig.locale);
    }

    float getDevicePixelRatio() {
        return mMetrics.devicePixelRatio;
    }

    public void destroy() {
        if (discoveryReceiver != null) {
            getContext().unregisterReceiver(discoveryReceiver);
        }

        if (mPlatformServiceProviderBinding != null) {
            mPlatformServiceProviderBinding.unbind().close();
            mPlatformServiceProvider.unbindServices();
        }

        if (mViewServiceProviderBinding != null) {
            mViewServiceProviderBinding.unbind().close();
            mViewServiceProvider.unbindServices();
        }

        getHolder().removeCallback(mSurfaceCallback);
        nativeDetach(mNativePlatformView);
        mNativePlatformView = 0;

        mSkyEngine.close();
        mDartServiceProvider.close();
        mFlutterAppMessages.close();
    }

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return mKeyboardState.createInputConnection(outAttrs);
    }

    private Integer getPointerTypeForAction(int maskedAction) {
        // Primary pointer:
        if (maskedAction == MotionEvent.ACTION_DOWN) {
            return PointerType.DOWN;
        }
        if (maskedAction == MotionEvent.ACTION_UP) {
            return PointerType.UP;
        }
        // Secondary pointer:
        if (maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
            return PointerType.DOWN;
        }
        if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
            return PointerType.UP;
        }
        // All pointers:
        if (maskedAction == MotionEvent.ACTION_MOVE) {
            return PointerType.MOVE;
        }
        if (maskedAction == MotionEvent.ACTION_CANCEL) {
            return PointerType.CANCEL;
        }
        return null;
    }

    private void addPointerForIndex(MotionEvent event, int pointerIndex,
                                    List<Pointer> result) {
        Integer pointerType = getPointerTypeForAction(event.getActionMasked());
        if (pointerType == null) {
            return;
        }

        Pointer pointer = new Pointer();

        pointer.timeStamp = event.getEventTime() * 1000; // Convert from milliseconds to microseconds.
        pointer.pointer = event.getPointerId(pointerIndex);
        pointer.type = pointerType;
        pointer.kind = PointerKind.TOUCH;
        pointer.x = event.getX(pointerIndex);
        pointer.y = event.getY(pointerIndex);

        pointer.buttons = 0;
        pointer.down = false;
        pointer.primary = false;
        pointer.obscured = false;

        // TODO(eseidel): Could get the calibrated range if necessary:
        // event.getDevice().getMotionRange(MotionEvent.AXIS_PRESSURE)
        pointer.pressure = event.getPressure(pointerIndex);
        pointer.pressureMin = 0.0f;
        pointer.pressureMax = 1.0f;

        pointer.distance = 0.0f;
        pointer.distanceMin = 0.0f;
        pointer.distanceMax = 0.0f;

        pointer.radiusMajor = 0.0f;
        pointer.radiusMinor = 0.0f;
        pointer.radiusMin = 0.0f;
        pointer.radiusMax = 0.0f;

        pointer.orientation = 0.0f;
        pointer.tilt = 0.0f;

        result.add(pointer);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO(abarth): This version check might not be effective in some
        // versions of Android that statically compile code and will be upset
        // at the lack of |requestUnbufferedDispatch|. Instead, we should factor
        // version-dependent code into separate classes for each supported
        // version and dispatch dynamically.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            requestUnbufferedDispatch(event);
        }

        ArrayList<Pointer> pointers = new ArrayList<Pointer>();

        // TODO(abarth): Rather than unpacking these events here, we should
        // probably send them in one packet to the engine.
        int maskedAction = event.getActionMasked();
        // ACTION_UP, ACTION_POINTER_UP, ACTION_DOWN, and ACTION_POINTER_DOWN
        // only apply to a single pointer, other events apply to all pointers.
        if (maskedAction == MotionEvent.ACTION_UP
                || maskedAction == MotionEvent.ACTION_POINTER_UP
                || maskedAction == MotionEvent.ACTION_DOWN
                || maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
            addPointerForIndex(event, event.getActionIndex(), pointers);
        } else {
            // ACTION_MOVE may not actually mean all pointers have moved
            // but it's the responsibility of a later part of the system to
            // ignore 0-deltas if desired.
            for (int p = 0; p < event.getPointerCount(); p++) {
                addPointerForIndex(event, p, pointers);
            }
        }

        PointerPacket packet = new PointerPacket();
        packet.pointers = pointers.toArray(new Pointer[0]);
        mSkyEngine.onPointerPacket(packet);

        return true;
    }

    @Override
    public boolean onHoverEvent(MotionEvent event) {
        boolean handled = handleAccessibilityHoverEvent(event);
        if (!handled) {
            // TODO(ianh): Expose hover events to the platform,
            // implementing ADD, REMOVE, etc.
        }
        return handled;
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
        mMetrics.physicalWidth = width;
        mMetrics.physicalHeight = height;
        mSkyEngine.onViewportMetricsChanged(mMetrics);
        super.onSizeChanged(width, height, oldWidth, oldHeight);
    }

    @Override
    public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
        mMetrics.physicalPaddingTop = insets.getSystemWindowInsetTop();
        mMetrics.physicalPaddingRight = insets.getSystemWindowInsetRight();
        mMetrics.physicalPaddingBottom = insets.getSystemWindowInsetBottom();
        mMetrics.physicalPaddingLeft = insets.getSystemWindowInsetLeft();
        mSkyEngine.onViewportMetricsChanged(mMetrics);
        return super.onApplyWindowInsets(insets);
    }

    private void configureLocalServices(ServiceRegistry registry) {
        registry.register(Keyboard.MANAGER.getName(), new ServiceFactory() {
            @Override
            public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
                return Keyboard.MANAGER.bind(new KeyboardImpl(view.getContext(), mKeyboardState), pipe);
            }
        });

        registry.register(RawKeyboardService.MANAGER.getName(), new ServiceFactory() {
            @Override
            public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
                return RawKeyboardService.MANAGER.bind(new RawKeyboardServiceImpl(mRawKeyboardState), pipe);
            }
        });

        registry.register(ApplicationMessages.MANAGER.getName(), new ServiceFactory() {
            @Override
            public Binding connectToService(FlutterView view, Core core, MessagePipeHandle pipe) {
                return ApplicationMessages.MANAGER.bind(new ApplicationMessagesImpl(), pipe);
            }
        });
    }

    private void attach() {
        Core core = CoreImpl.getInstance();
        Pair<SkyEngine.Proxy, InterfaceRequest<SkyEngine>> engine =
                SkyEngine.MANAGER.getInterfaceRequest(core);
        mSkyEngine = engine.first;
        mNativePlatformView = nativeAttach(engine.second.passHandle().releaseNativeHandle());
    }

    private void preRun() {
        if (mPlatformServiceProviderBinding != null) {
            mPlatformServiceProviderBinding.unbind().close();
            mPlatformServiceProvider.unbindServices();
        }
        if (mViewServiceProviderBinding != null) {
            mViewServiceProviderBinding.unbind().close();
            mViewServiceProvider.unbindServices();
        }
        if (mDartServiceProvider != null) {
            mDartServiceProvider.close();
        }

        Core core = CoreImpl.getInstance();

        Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> dartServiceProvider =
                ServiceProvider.MANAGER.getInterfaceRequest(core);
        mDartServiceProvider = dartServiceProvider.first;

        Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> platformServiceProvider =
                ServiceProvider.MANAGER.getInterfaceRequest(core);
        mPlatformServiceProviderBinding = ServiceProvider.MANAGER.bind(
                mPlatformServiceProvider, platformServiceProvider.second);

        Pair<ServiceProvider.Proxy, InterfaceRequest<ServiceProvider>> viewServiceProvider =
                ServiceProvider.MANAGER.getInterfaceRequest(core);
        mViewServiceProviderBinding = ServiceProvider.MANAGER.bind(
                mViewServiceProvider, viewServiceProvider.second);

        ServicesData services = new ServicesData();
        services.incomingServices = platformServiceProvider.first;
        services.outgoingServices = dartServiceProvider.second;
        services.viewServices = viewServiceProvider.first;
        mSkyEngine.setServices(services);

        resetAccessibilityTree();
    }

    private void postRun() {
        Core core = CoreImpl.getInstance();
        // Connect to the ApplicationMessages service exported by the Flutter framework
        Pair<ApplicationMessages.Proxy, InterfaceRequest<ApplicationMessages>> appMessages =
                  ApplicationMessages.MANAGER.getInterfaceRequest(core);
        mDartServiceProvider.connectToService(ApplicationMessages.MANAGER.getName(),
                                              appMessages.second.passHandle());
        mFlutterAppMessages = appMessages.first;
    }

    public void runFromBundle(String bundlePath, String snapshotPath) {
        preRun();

        if (FlutterMain.isRunningPrecompiledCode()) {
            mSkyEngine.runFromPrecompiledSnapshot(bundlePath);
        } else {
            String scriptUri = "file://" + bundlePath;
            if (snapshotPath != null) {
                mSkyEngine.runFromBundleAndSnapshot(scriptUri, bundlePath, snapshotPath);
            } else {
                mSkyEngine.runFromBundle(scriptUri, bundlePath);
            }
        }

        postRun();
    }

    public void runFromFile(String main, String packageRoot) {
        preRun();
        mSkyEngine.runFromFile(main, packageRoot, "");
        postRun();
    }

    private static native long nativeAttach(int inputObserverHandle);
    private static native int nativeGetObservatoryPort();
    private static native void nativeDetach(long nativePlatformViewAndroid);
    private static native void nativeSurfaceCreated(long nativePlatformViewAndroid,
                                                    Surface surface);
    private static native void nativeSurfaceDestroyed(long nativePlatformViewAndroid);

    // ACCESSIBILITY

    private boolean mAccessibilityEnabled = false;
    private boolean mTouchExplorationEnabled = false;

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mAccessibilityEnabled = mAccessibilityManager.isEnabled();
        mTouchExplorationEnabled = mAccessibilityManager.isTouchExplorationEnabled();
        if (mAccessibilityEnabled || mTouchExplorationEnabled)
          ensureAccessibilityEnabled();
        resetWillNotDraw();
        mAccessibilityManager.addAccessibilityStateChangeListener(this);
        mAccessibilityManager.addTouchExplorationStateChangeListener(this);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mAccessibilityManager.removeAccessibilityStateChangeListener(this);
        mAccessibilityManager.removeTouchExplorationStateChangeListener(this);
    }

    private void resetWillNotDraw() {
        setWillNotDraw(!(mAccessibilityEnabled || mTouchExplorationEnabled));
    }

    @Override
    public void onAccessibilityStateChanged(boolean enabled) {
        if (enabled) {
            mAccessibilityEnabled = true;
            ensureAccessibilityEnabled();
        } else {
            mAccessibilityEnabled = false;
        }
        if (mAccessibilityNodeProvider != null) {
            mAccessibilityNodeProvider.setAccessibilityEnabled(mAccessibilityEnabled);
        }
        resetWillNotDraw();
    }

    @Override
    public void onTouchExplorationStateChanged(boolean enabled) {
        if (enabled) {
            mTouchExplorationEnabled = true;
            ensureAccessibilityEnabled();
        } else {
            mTouchExplorationEnabled = false;
            if (mAccessibilityNodeProvider != null) {
                mAccessibilityNodeProvider.handleTouchExplorationExit();
            }
        }
        resetWillNotDraw();
    }

    @Override
    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
        ensureAccessibilityEnabled();
        return mAccessibilityNodeProvider;
    }

    private AccessibilityBridge mAccessibilityNodeProvider;

    void ensureAccessibilityEnabled() {
        if (mAccessibilityNodeProvider == null) {
            mAccessibilityNodeProvider = new AccessibilityBridge(this, createSemanticsServer());
        }
    }

    private SemanticsServer.Proxy createSemanticsServer() {
        Core core = CoreImpl.getInstance();
        Pair<SemanticsServer.Proxy, InterfaceRequest<SemanticsServer>> server =
                  SemanticsServer.MANAGER.getInterfaceRequest(core);
        mDartServiceProvider.connectToService(SemanticsServer.MANAGER.getName(), server.second.passHandle());
        return server.first;
    }

    void resetAccessibilityTree() {
        if (mAccessibilityNodeProvider != null) {
            mAccessibilityNodeProvider.reset(createSemanticsServer());
        }
    }

    private boolean handleAccessibilityHoverEvent(MotionEvent event) {
        if (!mTouchExplorationEnabled)
            return false;
        if (event.getAction() == MotionEvent.ACTION_HOVER_ENTER ||
                   event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
            mAccessibilityNodeProvider.handleTouchExploration(event.getX(), event.getY());
        } else if (event.getAction() == MotionEvent.ACTION_HOVER_EXIT) {
            mAccessibilityNodeProvider.handleTouchExplorationExit();
        } else {
            Log.d("flutter", "unexpected accessibility hover event: " + event);
            return false;
        }
        return true;
    }

    /**
     * Send a message to the Flutter application.  The Flutter Dart code can register a
     * host message handler that will receive these messages.
     */
    public void sendToFlutter(String messageName, String message,
                              final MessageReplyCallback callback) {
        mFlutterAppMessages.sendString(messageName, message,
            new ApplicationMessages.SendStringResponse() {
                @Override
                public void call(String reply) {
                    if (callback != null) {
                        callback.onReply(reply);
                    }
                }
            });
    }

    public void sendToFlutter(String messageName, String message) {
        sendToFlutter(messageName, message, null);
    }

    /** Callback invoked when the app replies to a message sent with sendToFlutter. */
    public interface MessageReplyCallback {
        void onReply(String reply);
    }

    /**
     * Register a callback to be invoked when the Flutter application sends a message
     * to its host.
     */
    public void addOnMessageListener(String messageName, OnMessageListener listener) {
        mOnMessageListeners.put(messageName, listener);
    }

    /**
     * Register a callback to be invoked when the Flutter application sends a message
     * to its host.  The reply to the message can be provided asynchronously.
     */
    public void addOnMessageListenerAsync(String messageName, OnMessageListenerAsync listener) {
        mAsyncOnMessageListeners.put(messageName, listener);
    }

    public interface OnMessageListener {
        /**
         * Called when a message is received from the Flutter app.
         * @return the reply to the message (can be null)
         */
        String onMessage(FlutterView view, String message);
    };

    public interface OnMessageListenerAsync {
        /**
         * Called when a message is received from the Flutter app.
         * @param response Used to send a reply back to the app.
         */
        void onMessage(FlutterView view, String message, MessageResponse response);
    }

    public interface MessageResponse {
        void send(String reply);
    }

    private class ApplicationMessagesImpl implements ApplicationMessages {
        @Override
        public void close() {}

        @Override
        public void onConnectionError(MojoException e) {}

        @Override
        public void sendString(String messageName, String message, SendStringResponse callback) {
            OnMessageListener listener = mOnMessageListeners.get(messageName);
            if (listener != null) {
                callback.call(listener.onMessage(FlutterView.this, message));
                return;
            }

            OnMessageListenerAsync asyncListener = mAsyncOnMessageListeners.get(messageName);
            if (asyncListener != null) {
                asyncListener.onMessage(FlutterView.this, message, new MessageResponseAdapter(callback));
                return;
            }

            callback.call(null);
        }
    }

    /**
     * This class wraps the raw Mojo callback object in an interface that is owned
     * by Flutter and can be safely given to host apps.
     */
    private static class MessageResponseAdapter implements MessageResponse {
        private ApplicationMessages.SendStringResponse callback;

        MessageResponseAdapter(ApplicationMessages.SendStringResponse callback) {
            this.callback = callback;
        }

        @Override
        public void send(String reply) {
            callback.call(reply);
        }
    }

    /** Broadcast receiver used to discover active Flutter instances. */
    private class DiscoveryReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            JSONObject discover = new JSONObject();
            try {
                discover.put("id", getContext().getPackageName());
                discover.put("observatoryPort", nativeGetObservatoryPort());
                Log.i(TAG, "DISCOVER: " + discover);
            } catch (JSONException e) {}
        }
    }
}


text:
videojs.addLanguage('pl', {
  "Audio Player": "Odtwarzacz audio",
  "Video Player": "Odtwarzacz wideo",
  "Play": "Odtwarzaj",
  "Pause": "Pauza",
  "Replay": "Odtwórz ponownie",
  "Current Time": "Aktualny czas",
  "Duration": "Czas trwania",
  "Remaining Time": "Pozostały czas",
  "Stream Type": "Typ strumienia",
  "LIVE": "NA ŻYWO",
  "Loaded": "Załadowany",
  "Progress": "Status",
  "Progress Bar": "Pasek stanu",
  "Fullscreen": "Pełny ekran",
  "Exit Fullscreen": "Pełny ekran niedostępny",
  "Mute": "Wyłącz dźwięk",
  "Unmute": "Włącz dźwięk",
  "Playback Rate": "Szybkość odtwarzania",
  "Subtitles": "Napisy",
  "subtitles off": "Napisy wyłączone",
  "Captions": "Transkrypcja",
  "captions off": "Transkrypcja wyłączona",
  "Chapters": "Rozdziały",
  "Descriptions": "Opisy",
  "descriptions off": "Opisy wyłączone",
  "Audio Track": "Ścieżka audio",
  "Volume Level": "Poziom głośności",
  "You aborted the media playback": "Odtwarzanie zostało przerwane",
  "A network error caused the media download to fail part-way.": "Problemy z siecią spowodowały błąd przy pobieraniu materiału wideo.",
  "The media could not be loaded, either because the server or network failed or because the format is not supported.": "Materiał wideo nie może być załadowany, ponieważ wystąpił problem z siecią lub format nie jest obsługiwany",
  "The media playback was aborted due to a corruption problem or because the media used features your browser did not support.": "Odtwarzanie materiału wideo zostało przerwane z powodu uszkodzonego pliku wideo lub z powodu błędu funkcji, które nie są wspierane przez przeglądarkę.",
  "No compatible source was found for this media.": "Dla tego materiału wideo nie znaleziono kompatybilnego źródła.",
  "The media is encrypted and we do not have the keys to decrypt it.": "Źródło jest zaszyfrowane i nie mamy kluczy do jego odszyfrowania.",
  "Play Video": "Odtwarzaj wideo",
  "Close": "Zamknij",
  "Close Modal Dialog": "Zamknij okno modala",
  "Modal Window": "Okno modala",
  "This is a modal window": "To jest okno modala",
  "This modal can be closed by pressing the Escape key or activating the close button.": "Ten modal możesz zamknąć naciskając przycisk Escape albo wybierając przycisk Zamknij.",
  ", opens captions settings dialog": ", otwiera okno dialogowe ustawień transkrypcji",
  ", opens subtitles settings dialog": ", otwiera okno dialogowe napisów",
  ", opens descriptions settings dialog": ", otwiera okno dialogowe opisów",
  ", selected": ", zaznaczone",
  "captions settings": "ustawienia transkrypcji",
  "subtitles settings": "ustawienia napisów",
  "descriptions settings": "ustawienia opisów",
  "Text": "Tekst",
  "White": "Biały",
  "Black": "Czarny",
  "Red": "Czerwony",
  "Green": "Zielony",
  "Blue": "Niebieski",
  "Yellow": "Żółty",
  "Magenta": "Magenta",
  "Cyan": "Cyjan",
  "Background": "Tło",
  "Window": "Okno",
  "Transparent": "Przezroczysty",
  "Semi-Transparent": "Półprzezroczysty",
  "Opaque": "Nieprzezroczysty",
  "Font Size": "Rozmiar czcionki",
  "Text Edge Style": "Styl krawędzi tekstu",
  "None": "Brak",
  "Raised": "Podniesiony",
  "Depressed": "Obniżony",
  "Uniform": "Równomierny",
  "Dropshadow": "Cień",
  "Font Family": "Czcionka",
  "Reset": "Ustawienia domyślne",
  "restore all settings to the default values": "zresetuj wszystkie ustawienia do domyślnych wartości",
  "Done": "Gotowe",
  "Caption Settings Dialog": "Okno dialogowe ustawień transkrypcji",
  "Beginning of dialog window. Escape will cancel and close the window.": "Początek okna dialogowego. Escape anuluje i zamknie okno.",
  "End of dialog window.": "Koniec okna dialogowego.",
  "Exit Picture-in-Picture": "Wyjdź z trybu obraz w obrazie",
  "Picture-in-Picture": "Obraz w obrazie"
});

redpajama_set_name: RedPajamaGithub


text:
import WAVLCore.WAVLTree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Leon on 06/05/2017.
 */
public class Tester {

    public void testWAVLTreeClass() {}

    public static void main(String[] args) {

        WAVLTree tree = new WAVLTree();

        boolean testClass = true; // Should we test the class functionality or the asymptotic performance

        // WAVLTree Test:

        if (testClass) {

            WAVLClassTester tester = new WAVLClassTester();
            try {
                tester.run(true);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        else { // Tests to submit
            AsymptoticTests tester = new AsymptoticTests();
            tester.run();

        }

    }
}


text:
MCToysWithCUDA
==============

Project to use CUDA to throw Toys and Calculate NNL in GPU, Interface with MINUIT2 from ROOT


text:
NS_ASSUME_NONNULL_BEGIN

@interface NSUserDefaults (DefaultValues)

- (nullable id)objectForKey:(NSString *)defaultName defaultValue:(nullable NSString *)value;
- (nullable NSString *)stringForKey:(NSString *)defaultName defaultValue:(nullable NSString *)value;
- (nullable NSArray *)arrayForKey:(NSString *)defaultName defaultValue:(nullable NSArray *)value;
- (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName defaultValue:(nullable NSDictionary<NSString *, id> *)value;

- (nullable NSData *)dataForKey:(NSString *)defaultName defaultValue:(nullable NSData *)value;
- (nullable NSArray<NSString *> *)stringArrayForKey:(NSString *)defaultName defaultValue:(nullable NSArray<NSString *> *)value;
- (NSInteger)integerForKey:(NSString *)defaultName defaultValue:(NSInteger)value;
- (float)floatForKey:(NSString *)defaultName defaultValue:(float)value;;
- (double)doubleForKey:(NSString *)defaultName defaultValue:(double)value;;
- (BOOL)boolForKey:(NSString *)defaultName defaultValue:(BOOL)value;;
- (nullable NSURL *)URLForKey:(NSString *)defaultName defaultValue:(nullable NSURL *)value;

@end

NS_ASSUME_NONNULL_END


text:
Changelog (revision history) for node-ubjson,
the Universal Binary JSON packer/unpacker for Node.js.

## Version 0.0.8

  * Use `long` npm module for int64 values storing
  * Write safe 64-bit integers as INT64 UBJSON types
  * Add usage examples to readme
  * Few tests added

## Version 0.0.7

  * No-Op marker support
  * Add code coverage report via Coveralls
  * Add API docs to GH pages
  * Use JSHint for linting code
  * Fix TMP dir creation on OS X
  * Support latest Node.js versions

## Version 0.0.6

  * Parser should return error for malformed input
    * Now pass error to callback for `unpackBuffer()` and `packToBuffer()`
    * Call `unpackBuffer()` callback only once
    * `unpackBuffer()` callback error object should contain `remainingData`
    * Error object should contain `collectedData` for malformed arrays and objects
    * `Stream` now emit 'error' event on malformed input
  * Add global and per-stream send buffer length setting with 'rw' interface
  * Write stream should split long strings
  * Implement int64/L support

## Version 0.0.5

  * Implement stream reader/writer
  * Improve readme, add API docs generated from PDoc comments
  * Split module into separate files

## Version 0.0.4

  * Support for unknown length containers unpacking

## Version 0.0.3

  * Fix object/o type marker
  * Support for byte/B, int16/i and int32/I values
  * Support for float/d and double/D values
  * Partial support for huge/h and huge/H values
  * Add MediaContent.json test from universal-binary-json-java

## Version 0.0.2

  * Support for string/s and string/S values
  * Support for object/o and object/O containers

## Version 0.0.1

  * Packer/unpacker using node-strtok
  * Support for null/Z, true/T, false/F values
  * Support for array/a and array/A containers

[milestone v0.0.6]: https://github.com/Sannis/node-ubjson/issues?milestone=6&state=closed


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

var FONT_SIZE = '48px ';
var DEFAULT_TEXT = 'test';

var doc = document;
var textSamples = {};

var Fonts = window.Fonts = {
  FONT_SIZE: FONT_SIZE,
  USE_FONTS_API: true,

  getFontType: getFontType,
  Font: Font,
  load: load,
  setSample: function setSample(fontType, sample) {
    textSamples[fontType] = sample;
  }
};

function naitveLoadFont(font, fontType) {
  var fontFace = new FontFace(font.family, font.src, font);
  doc.fonts.add(fontFace);

  return doc.fonts.load(fontType, font.text);
}

function nativeLoadFonts(fonts, callback, errback) {
  var promises = [];
  var used = {};

  for (var i = 0, len = fonts.length; i < len; i++) {
    var font = fonts[i];
    var fontType = getFontType(font);

    if (used[fontType]) continue;
    used[fontType] = true;

    console.log('Fonts API: Loading font:', fontType);

    promises.push(naitveLoadFont(font, fontType));
  }

  Promise.all(promises).then(callback, errback);
}

function load(stylesheet, callback, errback) {
  var nativeAPI = Fonts.USE_FONTS_API && doc.fonts;

  var handleFonts = function handleFonts(fonts) {
    if (nativeAPI) {
      nativeLoadFonts(fonts, callback, errback);
    } else {
      Fonts.loadFonts(fonts, callback, errback);
    }
  };

  if (Array.isArray(stylesheet)) {
    if (nativeAPI || Fonts.loadFonts) {
      handleFonts(stylesheet);
    } else {
      loadFallback(handleFonts);
    }
  } else if (typeof stylesheet === 'string') {
    var handleContent = function handleContent(content) {
      handleFonts(parseStylesheet(content));
    };

    var isURL = /^([a-zA-Z]+:)?\/\//.test(stylesheet);

    if (nativeAPI || Fonts.loadFonts) {
      if (isURL) {
        loadFile(stylesheet, handleContent, errback);
      } else {
        handleContent(stylesheet);
      }
    } else {
      loadFallback(handleContent, isURL);
    }
  } else {
    setTimeout(errback);
  }

  function loadFallback(callback, isURL) {
    var count = isURL ? 2 : 1;
    var content = stylesheet;

    function onLoad() {
      if (--count === 0) callback(content);
    }

    if (isURL) {
      loadFile(stylesheet, function (_cont) {
        content = _cont;
        onLoad();
      }, errback);
    }

    var script = doc.createElement('script');
    script.src = Fonts.FALLBACK_FILE;
    script.onload = onLoad;
    script.onerror = errback;

    doc.querySelector('head').appendChild(script);
  }
}

function Font(source, family, weight, style, text) {
  if (!(this instanceof Font)) throw new Error('#3');

  if (typeof source === 'string') {
    this.src = source;
    this.family = family;
    this.weight = weight;
    this.style = style;
    this._text = text;
  }
}

function getFontType(font, family) {
  return ((font.style || '') + ' ' + (font.variant || '') + ' ' + (font.weight || '') + ' ' + (font.stretch || '') + ' ' + FONT_SIZE + ' ' + (family || font.family)).trim().replace(/ +/g, ' ');
}

Font.prototype = {
  get text() {
    if (!this._text) {
      this._text = (textSamples[getFontType(this).replace(FONT_SIZE, '')] || textSamples[this.family] || textSamples['*'] || DEFAULT_TEXT) + '@';
    }

    return this._text;
  },

  set text(val) {
    this._text = val;
  }
}; }());


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

#nullable enable

using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
    internal sealed class ArrayTypeSymbol : TypeSymbol, IArrayTypeSymbol
    {
        private readonly Symbols.ArrayTypeSymbol _underlying;
        private ITypeSymbol? _lazyElementType;

        public ArrayTypeSymbol(Symbols.ArrayTypeSymbol underlying, CodeAnalysis.NullableAnnotation nullableAnnotation)
            : base(nullableAnnotation)
        {
            RoslynDebug.Assert(underlying is object);
            _underlying = underlying;
        }

        protected override ITypeSymbol WithNullableAnnotation(CodeAnalysis.NullableAnnotation nullableAnnotation)
        {
            Debug.Assert(nullableAnnotation != _underlying.DefaultNullableAnnotation);
            Debug.Assert(nullableAnnotation != this.NullableAnnotation);
            return new ArrayTypeSymbol(_underlying, nullableAnnotation);
        }

        internal override CSharp.Symbol UnderlyingSymbol => _underlying;
        internal override Symbols.TypeSymbol UnderlyingTypeSymbol => _underlying;
        internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying;

        int IArrayTypeSymbol.Rank => _underlying.Rank;

        bool IArrayTypeSymbol.IsSZArray => _underlying.IsSZArray;

        ImmutableArray<int> IArrayTypeSymbol.LowerBounds => _underlying.LowerBounds;

        ImmutableArray<int> IArrayTypeSymbol.Sizes => _underlying.Sizes;

        ITypeSymbol IArrayTypeSymbol.ElementType
        {
            get
            {
                if (_lazyElementType is null)
                {
                    Interlocked.CompareExchange(ref _lazyElementType, _underlying.ElementTypeWithAnnotations.GetPublicSymbol(), null);
                }

                return _lazyElementType;
            }
        }

        CodeAnalysis.NullableAnnotation IArrayTypeSymbol.ElementNullableAnnotation
        {
            get
            {
                return _underlying.ElementTypeWithAnnotations.ToPublicAnnotation();
            }
        }

        ImmutableArray<CustomModifier> IArrayTypeSymbol.CustomModifiers => _underlying.ElementTypeWithAnnotations.CustomModifiers;

        bool IArrayTypeSymbol.Equals(IArrayTypeSymbol? other)
        {
            return this.Equals(other as ArrayTypeSymbol, CodeAnalysis.SymbolEqualityComparer.Default);
        }

        #region ISymbol Members

        protected override void Accept(SymbolVisitor visitor)
        {
            visitor.VisitArrayType(this);
        }

        protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor)
            where TResult : default
        {
            return visitor.VisitArrayType(this);
        }

        #endregion
    }
}


text:
Get - Plain

--SKIPIF--
<?php
include dirname(__FILE__)."/../../cbtestframework/cbtest-phpt-loader.inc";
couchbase_phpt_skipif("Get", "testPlain");

--FILE--
<?php
include dirname(__FILE__)."/../../cbtestframework/cbtest-phpt-loader.inc";
couchbase_phpt_runtest("Get", "testPlain");
--EXPECT--
PHP_COUCHBASE_OK


text:
CREATE PROCEDURE [dbo].[PSP_LogTimingEntry]
	@TimingLogID BIGINT,
	@Timing Nvarchar(max)
AS
	IF EXISTS (SELECT 1 from tbl_TimingLog where TimingLogId = @TimingLogId AND [UpdatedEntry] = 0)
	BEGIN
		BEGIN TRY
			--generate xml doc
			DECLARE @idoc int
			EXEC sp_xml_preparedocument @idoc OUTPUT, @Timing

			BEGIN TRANSACTION Trans_PSP_LogTimingEntry
			--Delete tbl_TimingEntry where TimingLogId = @TimingLogID

			-- Insert timing entry
			Insert INTO [tbl_TimingEntry](
				[TimingLogId],[EntryUrl],[EntryType],[InitiatorType],[StartTime],[Duration],[ConnectStart],[ConnectEnd],[DomainLookupEnd],[DomainLookupStart],[FetchStart],[RedirectEnd],[RedirectStart],[RequestStart],[ResponseEnd],[ResponseStart]
			)
			SELECT
				@TimingLogID,[EntryUrl],[EntryType],[InitiatorType]
				,ISNULL([StartTime],0),ISNULL([Duration],0),ISNULL([ConnectStart],0),ISNULL([ConnectEnd],0),ISNULL([DomainLookupEnd],0),ISNULL([DomainLookupStart],0),ISNULL([FetchStart],0),ISNULL([RedirectEnd],0),ISNULL([RedirectStart],0),ISNULL([RequestStart],0),ISNULL([ResponseEnd],0),ISNULL([ResponseStart],0)
			from
			 OpenXml(@idoc,'/Log/entryList/entry',3)
					WITH (
						[EntryUrl] Nvarchar(500) 'name',
						[EntryType] Nvarchar(500) 'entryType',
						[InitiatorType] Nvarchar(500) 'initiatorType',
						[StartTime] FLOAT 'startTime',
						[Duration] FLOAT 'duration',
						[ConnectStart] FLOAT 'connectStart',
						[ConnectEnd] FLOAT 'connectEnd',
						[DomainLookupEnd] FLOAT 'domainLookupEnd',
						[DomainLookupStart] FLOAT 'domainLookupStart',
						[FetchStart] FLOAT 'fetchStart',
						[RedirectEnd] FLOAT 'redirectEnd',
						[RedirectStart] FLOAT 'redirectStart',
						[RequestStart] FLOAT 'requestStart',
						[ResponseEnd] FLOAT 'responseEnd',
						[ResponseStart] FLOAT 'responseStart'
			) AS tmpTimingEntry

			-- Insert js error entry
			Insert INTO [tbl_JSError](
				[TimingLogId],[ErrorMsg],[StartTime],[File],[LineNumber],[ColumnNumber],[ErrorType]
			)
			SELECT @TimingLogID,tmpErrorEntry.*
			from
			OpenXml(@idoc,'/Log/ErrorList/Error',3)
								WITH (
									[ErrorMsg] Nvarchar(2000) 'ErrorMsg',
									[StartTime] FLOAT 'Time',
									[File] Nvarchar(200) 'File',
									[LineNumber] FLOAT 'LineNumber',
									[ColumnNumber] FLOAT 'ColumnNumber',
									[ErrorType] Nvarchar(50) 'Type'
			) AS tmpErrorEntry

		    DECLARE @UpdatedJSError int = @@ROWCOUNT
			--update [UpdatedEntry] = 1 make it can;t append again
			Update tbl_TimingLog SET [UpdatedEntry]=1,[JSErrorCount] = @UpdatedJSError WHERE TimingLogId = @TimingLogId

			COMMIT TRANSACTION Trans_PSP_LogTimingEntry
			-- remove xml doc
			EXEC sp_xml_removedocument @idoc
			SELECT @TimingLogID
		END TRY
		BEGIN CATCH
			ROLLBACK TRANSACTION Trans_PSP_LogTiming
			DECLARE @ErrMsg Nvarchar(4000), @ErrSeverity INT
			SELECT @ErrMsg = ERROR_MESSAGE(),@ErrSeverity = ERROR_SEVERITY()
			RAISERROR(@ErrMsg, 11, 1)
			-- remove xml doc
			EXEC sp_xml_removedocument @idoc
		END CATCH
	END
	ELSE
	BEGIN
		RAISERROR ('Specific timing log has already updated or does not exist',11, 1)
	END
RETURN 0


text:
package org.trustedanalytics.cloud.uaa;

import java.util.Collection;
import java.util.Optional;
import java.util.UUID;

import org.cloudfoundry.identity.uaa.rest.SearchResults;
import org.cloudfoundry.identity.uaa.scim.ScimUser;

public interface UaaOperations {

    ScimUser createUser(String username, String password);

    void deleteUser(UUID userGuid);

    SearchResults<ScimUser> getUsers();

    Collection<UserIdNamePair> findUserNames(Collection<UUID> users);

    void changePassword(UUID guid, ChangePasswordRequest request);

    Optional<UserIdNamePair> findUserIdByName(String userName);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cabinet_archive_viewer">Pemapar Arkib Cabinet</string>
    <string name="open_as">Buka sebagai…</string>
    <string name="bookmark">Penanda Halaman</string>
    <string name="copy">Salin</string>
    <string name="move">Alih</string>
    <string name="rename">Namakan Semula</string>
    <string name="delete">Padam</string>
    <string name="share">Kongsi</string>
    <string name="archive">Arkib</string>
    <string name="selectAll">Pilih Semua</string>
    <string name="details">Butiran</string>
    <string name="no_files">Tiada fail</string>
    <string name="storage">Storan</string>
    <string name="internal_storage">Storan Dalaman</string>
    <string name="root">Root</string>
    <string name="go_up">Maju Selangkah</string>
    <string name="one_file">1 fail</string>
    <string name="x_files">fail %1$d</string>
    <string name="x_dirs">direktori %1$d</string>
    <string name="done">Selesai</string>
    <string name="remove_bookmark">Buang Penanda Halaman</string>
    <string name="sort_modified">kali terakhir diubah suai</string>
    <string name="modified_x">Ubahsuai %1$s</string>
    <string name="navigation_drawer_open">Buka laman navigasi</string>
    <string name="navigation_drawer_close">Tutup laman navigasi</string>
    <string name="new_folder">Folder baru</string>
    <string name="untitled">Tiada Tajuk</string>
    <string name="renamed_to">Namakan semula ke %1$s</string>
    <string name="moved_to">Alihkan ke %1$s</string>
    <string name="copied_to">Salin ke %1$s</string>
    <string name="no">Tidak</string>
    <string name="yes">Ya</string>
    <string name="search">Cari</string>
    <string name="confirm_delete_xfiles">Adakah anda pasti anda mahu memadam fail %1$d?</string>
    <string name="sort_by">Sisih Mengikut</string>
    <string name="sort_name">Nama</string>
    <string name="sort_extension">Pemalam</string>
    <string name="sort_size_lowhigh">Saiz, kecil ke besar</string>
    <string name="sort_size_highlow">Saiz, besar ke kecil</string>
    <string name="deleting">Memadam…</string>
    <string name="extracting">Mengekstrak…</string>
    <string name="archiving">Mengarkib…</string>
    <string name="moving">Mengalih…</string>
    <string name="copying">Menyalin…</string>
    <string name="failed_delete_file">Gagal untuk memadam fail ini: %1$s</string>
    <string name="failed_make_directory">gagal untuk membuat folder baru: %1$s</string>
    <string name="failed_rename_file">gagal untuk mengalih/menamakan semula fail ini: %1$s</string>
    <string name="failed_extract_file">Gagal untuk ekstrak fail ini: %1$s</string>
    <string name="failed_archive_files">Gagal untuk mengarkib fail:%1$s</string>
    <string name="error">Kesilapan</string>
    <string name="activity_not_found">Tiada aplikasi ditemui untuk membuka fail ini</string>
    <string name="no_apps_for_sharing">Tiada aplikasi yang dapat digunakan untuk berkongsi fail ini</string>
    <string name="copy_x"><![CDATA[ Salin: nbsp;%1$s]]></string>
    <string name="move_x"><![CDATA[ Alih: nbsp;%1$s]]></string>
    <string name="search_files">Cari fail…</string>
    <string name="search_x"><![CDATA[ CAri: %1$s]]></string>
    <string name="support_dev">Pembangunan Sokongan</string>
    <string name="thank_you">Terima kasih banyak!</string>
    <string name="rate">Nilai</string>
    <string name="later">Nanti</string>
    <string name="rate_desc">Adakah anda mahu menilai Cabinet di Google Play? Penilaian baik amat dihargai!</string>
    <string name="sure">Pasti!</string>
    <string name="no_thanks">Tidak Berminat</string>
    <string name="file">Fail</string>
    <string name="folder">Folder</string>
    <string name="text">Teks</string>
    <string name="image">Imej</string>
    <string name="audio">Audio</string>
    <string name="video">Video</string>
    <string name="other">Lain-lain</string>
    <string name="hidden_files">Fail Tersembunyi</string>
    <string name="settings">Tetapan</string>
    <string name="new_file">Fail baru</string>
    <string name="pick_a_file">Memilih fail…</string>
    <string name="cabinet_text_editor">Editor Teks Cabinet</string>
    <string name="save">Simpan</string>
    <string name="unsaved_changes">Perubahan yang tidak disimpan</string>
    <string name="unsaved_changes_desc">Anda mempunyai perubahan yang belum disimpan, adakah anda ingin menyimpannya sebelum keluar?</string>
    <string name="loading">Memuatkan…</string>
    <string name="unsupported_extension">Pemalam yang tidak disokong</string>
    <string name="unsupported_extension_desc">Anda tidak boleh membuka fail jenis ini untuk meyunting teks.</string>
    <string name="extract_to">Ekstrak ke…</string>
    <string name="filter">Penapis</string>
    <string name="none">Tiada</string>
    <string name="archives">Arkib</string>
    <string name="extension">Pemalam</string>
    <string name="superuser_not_available">Superuser tidak tersedia</string>
    <string name="filter_active">Saring aktif: %1$s</string>
    <string name="base_theme">Tema Asas</string>
    <string-array name="base_themes">
        <item>Terang</item>
        <item>Gelap</item>
        <item>Hitam (AMOLED)</item>
    </string-array>
    <string name="owner">Pemilik</string>
    <string name="group">Kumpulan</string>
    <string name="applying_permissions">Memohon kebenaran…</string>
    <string name="find_and_replace">Cari dan Tukar</string>
    <string name="find">Cari</string>
    <string name="replace">Tukar</string>
    <string name="replace_all">Tukar Semua</string>
    <string name="match_case">Sepadan</string>
    <string name="no_occurences">Tiada kejadian</string>
    <string name="no_occurences_desc">Tiada kejadian carian pertanyaan anda tidak dijumpai.</string>
    <string name="slash_name_invalid">Anda tidak boleh menyertakan / di dalam nama.</string>
    <string name="directory">Direktori</string>
    <string name="behavior">Perilaku</string>
    <string name="changelog">Log Perubahan</string>
    <string name="folders_first">Utamakan Folder</string>
    <string name="grid_size">Saiz Grid</string>
    <string name="grid_size_one">1</string>
    <string name="grid_size_two">2</string>
    <string name="grid_size_three">3</string>
    <string name="grid_size_four">4</string>
    <string name="grid_size_five">5</string>
    <string name="grid_size_six">6</string>
    <string name="current_path">Laluan semasa</string>
    <string name="one_file_x_folders">1 fail, %1$d folder</string>
    <string name="x_files_one_folder">%1$d fail, 1 folder</string>
    <string name="one_file_one_folder">1 fail, 1 folder</string>
    <string name="x_files_x_folders">%1$d fail, %2$d folder</string>
    <string name="empty">Kosong</string>
    <string name="one_folder">1 Folder</string>
    <string name="x_folders">%1$d folder</string>
    <string name="nickname">Nama samaran</string>
    <string name="choose_destination">Pilih destinasi…</string>
    <string name="external_storage">Storan Luar</string>
    <string name="sdcard_write_warning">Amaran: nampaknya Cabinet tidak boleh mendapatkan akses menulis kepada kad SD anda, anda tidak akan dapat mengubah suai fail padanya melainkan telah di root.</string>
    <string name="dont_show_again">Jangan paparkan lagi</string>
    <string name="pick_ringtone">Pilih fail audio…</string>
    <string name="not_audio_file">Anda mesti memilih audio fail.</string>
    <string name="cabinet_audio_preview">Prebiu Audio Cabinet</string>
    <string name="add">Tambah</string>
    <string name="connecting">Menyambung…</string>

    <string name="remember_last_folder">Ingat Folder Sebelum Ini</string>
    <string name="directory_count_list">Kiraan Senarai Direktori</string>
    <string name="show_free_space">Tunjuk Ruang Kosong</string>
    <string name="colored_navbar">Bar Navigasi Berwarna</string>
    <string name="primary_color">Warna Utama</string>
    <string name="accent_color">Warna Menonjol</string>
    <string name="thumbnail_color">Warna Thumbnail</string>
</resources>


text:
package com.ptycore.lib;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import com.ptycore.Audit;
import com.ptycore.BrokenRule;
import com.ptycore.BusinessRulesException;
import com.ptycore.Config;
import com.ptycore.Entity;
import com.ptycore.IIdentity;
import com.ptycore.Identity;
import com.ptycore.SystemException;

public class Instructions extends Entity {

	// Member variables
	private String _Title = "";
	private String _Description = "";
	private boolean _IsDocument;
	private String _DocumentsNeeded = "";
	private String _Location = "";

	// Properties
	public String getTitle() {
		return _Title;
	}

	public void setTitle(String value) {
		if (this._Title == null || !this._Title.equals(value)) {
			PropertyHasChanged("Title", _Title, value);
			this._Title = value;
		}
	}

	public String getDescription() {
		return _Description;
	}

	public void setDescription(String value) {
		if (this._Description == null || !this._Description.equals(value)) {
			PropertyHasChanged("Description", _Description, value);
			this._Description = value;
		}
	}

	public boolean getIsDocument() {
		return _IsDocument;
	}

	public void setIsDocument(boolean value) {
		_IsDocument = value;
	}

	public String getDocumentsNeeded() {
		return _DocumentsNeeded;
	}

	public void setDocumentsNeeded(String value) {
		if (this._DocumentsNeeded == null || !this._DocumentsNeeded.equals(value)) {
			PropertyHasChanged("DocumentsNeeded", _DocumentsNeeded, value);
			this._DocumentsNeeded = value;
		}
	}

	public String getLocation() {
		return _Location;
	}

	public void setLocation(String value) {
		if (this._Location == null || !this._Location.equals(value)) {
			PropertyHasChanged("Location", _Location, value);
			this._Location = value;
		}
	}

	// Rules
	protected void addRules() {
		super.addRules();
		_brokenRules.add(BrokenRule.NewBrokenRule("Required Title", "Title is required"));
		_brokenRules.add(BrokenRule.NewBrokenRule("Required Description", "Description is required"));
	}

	protected void checkRules() {
		super.checkRules();
		if (this._Title.length() > 0)
			this._brokenRules.remove("Required Title");
		if (this._Description.length() > 0)
			this._brokenRules.remove("Required Description");
	}

	// Constructors
	private Instructions(IIdentity identity) {
		_CurrentIdentity = identity;
		setIdentity((Identity) _CurrentIdentity);

		// Instantiate Audit
		_audit = this.getAudit();
	}

	private Instructions(int InstructionsID, IIdentity identity) {
		this._ID = InstructionsID;
		_CurrentIdentity = identity;
		Fetch();
		setIdentity((Identity) _CurrentIdentity);

		// Instantiate Audit
		_audit = this.getAudit();
	}

	// Factory methods
	public static Instructions GetInstructions(int InstructionsID, IIdentity identity) {
		Instructions Instructions = new Instructions(InstructionsID, identity);

		// Audit get record
		Audit audit = Instructions.getAudit();
		audit.setEntityID(Instructions.getID());
		audit.setMethodName("GetInstructions(" + Instructions.getID() + ")");
		audit.setIdentity(Instructions.getIdentity());
		try {
			audit.SaveAudit();
		} catch (BusinessRulesException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Instructions;

	}

	public static Instructions NewInstructions(IIdentity identity) {
		Instructions Instructions = new Instructions(identity);
		Instructions.setIdentity((Identity) identity);
		return Instructions;
	}

	public Instructions SaveInstructions() throws BusinessRulesException {
		if (isSavable()) {
			Save();
			// Audit new record
			_audit = this.getAudit();
			_audit.setEntityID(this.getID());
			if (isNew())
				_audit.setMethodName("NewInstructions() - " + this.getID());
			else
				_audit.setMethodName("UpdateInstructions() - " + this.getID());
			_audit.setIdentity(this.getIdentity());
			try {
				_audit.SaveAudit();
			} catch (BusinessRulesException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			if (this.isDirty() && this._brokenRules.size() > 0) {
				// Print broken rules
				for (BrokenRule rule : this._brokenRules)
					System.out.println(rule.getRule());
				throw new BusinessRulesException("Business rules were broken.", this._brokenRules);
			}
		}
		return this;
	}

	// Data access
	private Instructions Save() {
		StringBuilder exceptionMessage = new StringBuilder();
		Connection sqlConnection = null;
		int result = 0;
		try {
			sqlConnection = Config.getPooledConnection();
			sqlConnection.setAutoCommit(false);

			CallableStatement callableStatement;
			if (this._IsNew) {
				String addInstructions = "{call addInstructions(?,?,?,?,?,?)}";
				callableStatement = sqlConnection.prepareCall(addInstructions);
				callableStatement.registerOutParameter(1, Types.INTEGER);
				callableStatement.setString(2, this.getTitle());
				callableStatement.setString(3, this.getDescription());
				callableStatement.setBoolean(4, this.getIsDocument());
				callableStatement.setString(5, this.getDocumentsNeeded());
				callableStatement.setString(6, this.getLocation());
				result = callableStatement.executeUpdate();
				this._ID = callableStatement.getInt("o_ID");

			} else {
				String updateInstructions = "{call updateInstructions(?,?,?,?,?,?,?)}";
				callableStatement = sqlConnection.prepareCall(updateInstructions);
				callableStatement.setInt(1, this.getID());
				callableStatement.setString(2, this.getTitle());
				callableStatement.setString(3, this.getDescription());
				callableStatement.setBoolean(4, this.getIsDocument());
				callableStatement.setString(5, this.getDocumentsNeeded());
				callableStatement.setString(6, this.getLocation());
				callableStatement.setBoolean(7, this.getInactive());

				result = callableStatement.executeUpdate();
			}
			sqlConnection.commit(); // Commit transaction
			System.out.println("Instructions record " + this._ID + " inserted. Execution result is " + result + "");

			sqlConnection.close();
		} catch (SQLException sqlException1) {
			sqlException1.printStackTrace();
			try {
				if (sqlConnection != null)
					sqlConnection.rollback(); // Rollback transaction
			} catch (SQLException sqlException2) {
				exceptionMessage.append(sqlException2.getLocalizedMessage());
				sqlException2.printStackTrace();
			}
			sqlException1.getLocalizedMessage();
			sqlException1.printStackTrace();

			// Report exception
			SystemException systemException = new SystemException();
			systemException.setExceptionType(sqlException1.getClass().toString());
			systemException.setExceptionMessage(sqlException1.getMessage());
			this.setSystemException(systemException);
		} catch (Exception exception) {
			exception.printStackTrace();
			exceptionMessage.append(exception.getLocalizedMessage());

			// Report exception
			SystemException systemException = new SystemException();
			systemException.setExceptionType(exception.getClass().toString());
			systemException.setExceptionMessage(exception.getMessage());
			this.setSystemException(systemException);
		} finally {
			try {
				if (sqlConnection != null)
					sqlConnection.close();
			} catch (SQLException sqlException3) {
				sqlException3.printStackTrace();
				exceptionMessage.append(sqlException3.getLocalizedMessage());
			}
		}
		if (exceptionMessage.length() > 0)
			System.out.println(exceptionMessage.toString());
		return this;

	}

	private void Fetch() {
		StringBuilder exceptionMessage = new StringBuilder();
		Connection sqlConnection = null;

		try {
			sqlConnection = Config.getPooledConnection();
			sqlConnection.setAutoCommit(false);

			CallableStatement callableStatement = null;
			ResultSet resultSet = null;
			String getInstructions = "{call getInstructions(?)}";
			callableStatement = sqlConnection.prepareCall(getInstructions);
			callableStatement.setInt(1, this._ID);

			boolean results = callableStatement.execute();

			if (results) {
				// Retrieve Audit
				resultSet = callableStatement.getResultSet();
				while (resultSet.next()) {
					this._ID = resultSet.getInt("ID");
					this._Title = resultSet.getString("Title");
					this._Description = resultSet.getString("Description");
					this._IsDocument = resultSet.getBoolean("IsDocument");
					this._DocumentsNeeded = resultSet.getString("DocumentsNeeded");
					this._Location = resultSet.getString("Location");
					this._Created = resultSet.getTimestamp("Created").toString();
					if (resultSet.getTimestamp("Modified") != null)
						this._Modified = resultSet.getTimestamp("Modified").toString();
					this._Inactive = resultSet.getBoolean("Inactive");
					this._IsNew = false;
					System.out.println("Instructions ID " + this.getID() + " retrieved.");
				}
			}
			resultSet.close();
			callableStatement.close();
			sqlConnection.commit();
		} catch (SQLException sqlException1) {
			try {
				if (sqlConnection != null)
					sqlConnection.rollback(); // Rollback transaction
			} catch (SQLException sqlException2) {
				exceptionMessage.append(sqlException2.getLocalizedMessage());
				sqlException2.printStackTrace();
			}
			exceptionMessage.append(sqlException1.getLocalizedMessage());
			sqlException1.printStackTrace();

			// Report exception
			SystemException systemException = new SystemException();
			systemException.setExceptionType(sqlException1.getClass().toString());
			systemException.setExceptionMessage(sqlException1.getMessage());
			this.setSystemException(systemException);
		} catch (Exception exception) {
			exception.printStackTrace();
			exceptionMessage.append(exception.getLocalizedMessage());

			// Report exception
			SystemException systemException = new SystemException();
			systemException.setExceptionType(exception.getClass().toString());
			systemException.setExceptionMessage(exception.getMessage());
			this.setSystemException(systemException);
		} finally {
			try {
				if (sqlConnection != null)
					sqlConnection.close();
			} catch (SQLException sqlException3) {
				sqlException3.printStackTrace();
				exceptionMessage.append(sqlException3.getLocalizedMessage());
			}
		}
		if (exceptionMessage.length() > 0)
			System.out.println(exceptionMessage.toString());
	}

}


text:
//
//  NetWorkingHTTP.h
//  NetWorkingHTTP
//
//  Created by mac on 15/6/2.
//  Copyright (c) 2015年 白仕云. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface BSYNetWorkingHTTP : NSObject
//检查网络是否可用
+ (BOOL)bsy_NetWorkIsNetWorking;
//post请求封装
+ (void)bsy_post:(NSString *)Url RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block;
//get获取数据
+(NSString *)bsy_getDataByURL:(NSString *) url;
/**
 *  get获取图片
 */
+(UIImage *)bsy_getImageByURL:(NSString *) url;
@end


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

#import "MOZUIndexedProperty.h"

@implementation MOZUIndexedProperty
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
	return YES;
}

@end


text:
import Cookie
import base64
import email.utils
import hashlib
import hmac
import logging

from rogerthat.consts import SESSION_TIMEOUT, DEBUG
from rogerthat.utils import now
from rogerthat.settings import get_server_settings

#### Copied from https://github.com/facebook/python-sdk/blob/master/examples/oauth/facebookoauth.py ####
def set_cookie(response, name, value, domain=None, path="/", expires=None):
    """Generates and signs a cookie for the give name/value"""
    if not isinstance(name, str):
        name = name.encode("utf8")
    timestamp = unicode(now())
    value = base64.b64encode(value)
    signature = cookie_signature(value, timestamp)
    cookie = Cookie.BaseCookie()
    cookie[name] = "|".join([value, timestamp, signature])
    cookie[name]["path"] = path
    if not DEBUG:
        cookie[name]["secure"] = True
    if domain: cookie[name]["domain"] = domain
    if expires:
        cookie[name]["expires"] = email.utils.formatdate(expires, localtime=False, usegmt=True)
    response.headers["Set-Cookie"] = cookie.output()[12:] + '; httponly'

def parse_cookie(value):
    """Parses and verifies a cookie value from set_cookie"""
    if not value: return None
    parts = value.split("|")
    if len(parts) != 3: return None
    if cookie_signature(parts[0], parts[1]) != parts[2]:
        logging.warning("Invalid cookie signature %r", value)
        return None
    timestamp = int(parts[1])
    if timestamp < now() - SESSION_TIMEOUT:
        logging.warning("Expired cookie %r", value)
        return None
    try:
        return base64.b64decode(parts[0]).strip()
    except:
        return None

def cookie_signature(*parts):
    server_settings = get_server_settings()
    """Generates a cookie signature."""
    the_hash = hmac.new(base64.b64decode(server_settings.cookieSecretKey.encode("utf8")), digestmod=hashlib.sha1)
    for part in parts: the_hash.update(part)
    return the_hash.hexdigest()

#### End copied ####


text:
/**
 * This code is for dealing with adding, editing and managing file databases
 */
YAHOO.namespace("ur.file.database");

// action to perform when submitting the file databases.
var myFileDatabaseAction = basePath + 'admin/getAllFileDatabase.action';

// actions for adding, editing and removing file databases
var updateFileDatabaseAction = basePath + 'admin/updateFileDatabase.action';
var newFileDatabaseAction = basePath + 'admin/createFileDatabase.action';
var deleteFileDatabaseAction = basePath + 'admin/deleteFileDatabase.action';
var getFileDatabaseAction = basePath + 'admin/getFileDatabase.action';

YAHOO.ur.file.database =
{
   /**
    *  Function that retrieves file databases
    */
    getFileDatabases : function ()
    {
        var callback =
        {
            success: function(o)
            {
                // check for the timeout - forward user to login page if timout
	            // occured
	            if( !urUtil.checkTimeOut(o.responseText) )
	            {
                    var divToUpdate = document.getElementById('fileDatabases');
                    divToUpdate.innerHTML = o.responseText;
                }
            },

	        failure: function(o)
	        {
	            alert('Get file databases Failure ' + o.status + ' status text ' + o.statusText );
	        }
        };

        var fileServerId = document.getElementById("fileServerId").value;
        var transaction = YAHOO.util.Connect.asyncRequest('GET',
            myFileDatabaseAction + '?fileServerId=' + fileServerId +'&bustcache='+new Date().getTime(),
            callback, null);
    },

    /**
     *  clear out the file database form data
     */
    clearFileDatabaseForm : function()
    {
        var errorDiv = document.getElementById('error_div');
        errorDiv.innerHTML = "";

	    document.getElementById('newFileDatabaseFormName').value = "";
	    document.getElementById('newFileDatabaseFormPath').value = "";
	    document.getElementById('newFileDatabaseFormDescription').value = "";
	    document.getElementById('newFileDatabaseFormId').value = "";
	    document.addFileDatabaseForm.newFileDatabaseVal.value = "true";
    },

    /**
     * Create a file database dialog box for editing a file database
     */
    createNewFileDatabaseDialog : function()
    {
        // Define various event handlers for Dialog
	    var handleSubmit = function()
	    {
	    	this.submit();
	    };

	    // handle a cancel of the adding FileDatabase dialog
	    var handleCancel = function()
	    {
	        YAHOO.ur.file.database.newFileDatabaseDialog.hide();
	        YAHOO.ur.file.database.clearFileDatabaseForm();
	    };

	    var handleSuccess = function(o)
	    {
	        // check for the timeout - forward user to login page if timout
	        // occured
	        if( !urUtil.checkTimeOut(o.responseText) )
	        {
                //get the response from adding a FileDatabase
	            var response = o.responseText;
	            var fileServerForm = document.getElementById('newFileDatabaseDialogFields');

	            // update the form FileDatabases with the response.  This updates
	            // the form, if there was an issue, update the form with
	            // the error messages.
	            fileServerForm.innerHTML = o.responseText;

	            // determine if the add/edit was a success
	            var success = document.getElementById("newFileDatabaseFormSuccess").value;

	            //if the FileDatabase was not added then show the user the error message.
	            // received from the server
	            if( success == "false" )
	            {
                    YAHOO.ur.file.database.newFileDatabaseDialog.showDialog();
	            }
	            else
	            {
	            	YAHOO.ur.file.database.getFileDatabases();
	                // we can clear the form if the FileDatabase was added
	                YAHOO.ur.file.database.newFileDatabaseDialog.hide();
	                YAHOO.ur.file.database.clearFileDatabaseForm();
	            }

	        }
	    };

	    // handle form sbumission failure
	    var handleFailure = function(o)
	    {
	        alert('file database submission failed ' + o.status + ' status text ' + o.statusText);
	    };

	    // Instantiate the Dialog
	    // make it modal -
	    // it should not start out as visible - it should not be shown until
	    // new FileDatabase button is clicked.
	    YAHOO.ur.file.database.newFileDatabaseDialog = new YAHOO.widget.Dialog('newFileDatabaseDialog',
            { width : "500px",
		      visible : false,
		      modal : true,
		      buttons : [ { text:'Submit', handler:handleSubmit, isDefault:true },
					     { text:'Cancel', handler:handleCancel } ]
		    } );

	    // show and center the FileDatabase dialog
        YAHOO.ur.file.database.newFileDatabaseDialog.showDialog = function()
        {
            YAHOO.ur.file.database.newFileDatabaseDialog.center();
            YAHOO.ur.file.database.newFileDatabaseDialog.show();
        };

        // override the submit function
        YAHOO.ur.file.database.newFileDatabaseDialog.submit = function()
        {
        	YAHOO.util.Connect.setForm('addFileDatabaseForm');
	        if( YAHOO.ur.file.database.newFileDatabaseDialog.validate() )
	        {
	            //based on what we need to do (update or create a
	            // new FileDatabase) based on the action.
               var action = newFileDatabaseAction;
	           if( document.addFileDatabaseForm.newFileDatabaseVal.value != 'true')
	           {

	               action = updateFileDatabaseAction;
	           }

                var cObj = YAHOO.util.Connect.asyncRequest('post',
                action, callback);
            }

        };

 	    // Validate the entries in the form to require that file database name is entered
	    YAHOO.ur.file.database.newFileDatabaseDialog.validate = function()
        {
	        var name = document.getElementById('newFileDatabaseFormName').value;
		    if (name == "" || name == null)
		    {
		        alert('A File Database name must be entered');
			    return false;
		    }
		    else
		    {
			    return true;
		    }
	    };

	    // Wire up the success and failure handlers
	    var callback = { success: handleSuccess,
	                 failure: handleFailure };

	    // Render the Dialog
	    YAHOO.ur.file.database.newFileDatabaseDialog.render();

        // listener for showing the dialog when clicked.
	    YAHOO.util.Event.addListener("showNewFileDatabase", "click",
	        YAHOO.ur.file.database.newFileDatabaseDialog.showDialog,
	        YAHOO.ur.file.database.newFileDatabaseDialog, true);
	},

    /**
     * function to edit File Server information
     */
    edit : function(fileServerId, fileDatabaseId)
    {
	    /*
         * This call back updates the html when a editing a FileDatabase
         */
        var callback =
        {
            success: function(o)
            {
            	// check for the timeout - forward user to login page if timout
	            // occured
	            if( !urUtil.checkTimeOut(o.responseText) )
	            {
                    var divToUpdate = document.getElementById('newFileDatabaseDialogFields');
                    divToUpdate.innerHTML = o.responseText;
                    document.addFileDatabaseForm.newFileDatabaseVal.value = "false";
	                YAHOO.ur.file.database.newFileDatabaseDialog.showDialog();
                }
            },

	        failure: function(o)
	        {
	            alert('Edit FileDatabase failed ' + o.status + ' status text ' + o.statusText );
	        }
        };

        var transaction = YAHOO.util.Connect.asyncRequest('GET',
            getFileDatabaseAction + '?fileServerId=' + fileServerId +  '&fileDatabaseId=' + fileDatabaseId+'&bustcache='+new Date().getTime(),
            callback, null);
     },

    /**
     * Clear the delete fine
     */
    clearDeleteFileDatabaseForm : function()
    {
        var fileServerError = document.getElementById('newDeleteFileDatabaseError');
        if( fileServerError != null)
        {
            fileServerError.innerHTML = "";
        }
    },

    /**
     * Create the delete dialog
     */
    createDeleteFileDatabaseDialog : function()
    {
    	// Define various event handlers for Dialog
	    var handleSubmit = function()
	    {
	    	this.submit();
	    };

	    // handle a cancel of deleting FileDatabase dialog
	    var handleCancel = function() {
	        YAHOO.ur.file.database.deleteFileDatabaseDialog.hide();
	    };

	    var handleSuccess = function(o)
	    {
	        // check for the timeout - forward user to login page if timout
	        // occured
	        if( !urUtil.checkTimeOut(o.responseText) )
	        {
	            //get the response from adding a FileDatabase
	            var response = eval("("+o.responseText+")");
	            //if the FileDatabase was not deleted then show the user the error message.
	            // received from the server
	            if( response.fileServerDeleted == "false" )
	            {
	                var deleteFileDatabaseError = document.getElementById('deleteFileDatabaseError');
                    deleteFileDatabaseError.innerHTML = '
'
                    + response.message + '
';
                    YAHOO.ur.file.database.deleteFileDatabaseDialog.showDialog();
	            }
	            else
	            {
	            	document.getElementById('deleteFileDatabaseId').value = "";
	            	YAHOO.ur.file.database.getFileDatabases();
	                // we can clear the form if the FileDatabases were deleted
	                YAHOO.ur.file.database.deleteFileDatabaseDialog.hide();
	                YAHOO.ur.file.database.clearDeleteFileDatabaseForm();
	            }

	        }
	    };

	    // handle form submission failure
	    var handleFailure = function(o)
	    {
	        alert('File database delete submission failed ' + o.status + ' status text ' + o.statusText);
	    };

	    // Instantiate the Dialog
	    // make it modal -
	    // it should not start out as visible - it should not be shown until
	    // new FileDatabase button is clicked.
	    YAHOO.ur.file.database.deleteFileDatabaseDialog = new YAHOO.widget.Dialog('deleteFileDatabaseDialog',
            { width : "500px",
		      visible : false,
		      modal : true,
		      buttons : [ { text:'Yes', handler:handleSubmit, isDefault:true },
					      { text:'No', handler:handleCancel } ]
		    } );

	    // Wire up the success and failure handlers
	    var callback = { success: handleSuccess,
	                 failure: handleFailure };

	    // show and center the dialog box
	    YAHOO.ur.file.database.deleteFileDatabaseDialog.showDialog = function()
	    {
	        YAHOO.ur.file.database.deleteFileDatabaseDialog.show();
	        YAHOO.ur.file.database.deleteFileDatabaseDialog.center();
	    };

        // override the submit function
	    YAHOO.ur.file.database.deleteFileDatabaseDialog.submit = function()
        {
        	YAHOO.util.Connect.setForm('deleteFileDatabase');
        	var cObj = YAHOO.util.Connect.asyncRequest('post',
            		deleteFileDatabaseAction, callback);

        };

	    // Render the Dialog
	    YAHOO.ur.file.database.deleteFileDatabaseDialog.render();
    },

   deleteFileDatabase : function(id)
   {
    	document.getElementById('deleteFileDatabaseId').value = id;
    	YAHOO.ur.file.database.deleteFileDatabaseDialog.showDialog();
   },

    init : function()
    {
        YAHOO.ur.file.database.createNewFileDatabaseDialog();
        YAHOO.ur.file.database.createDeleteFileDatabaseDialog();
    }
};

// initialize the code once the dom is ready
YAHOO.util.Event.onDOMReady(YAHOO.ur.file.database.init);


text:
package decorators

import (
	"bytes"
	"net/http"

	"github.com/tidwall/gjson"

	"github.com/antham/chyle/chyle/apih"
)

// jSONResponse extracts datas from a JSON api using defined keys
// and add it to final commitMap data structure
type jSONResponse struct {
	client  *http.Client
	request *http.Request
	pairs   map[string]struct {
		DESTKEY string
		FIELD   string
	}
}

func (j jSONResponse) Decorate(commitMap *map[string]interface{}) (*map[string]interface{}, error) {
	statusCode, body, err := apih.SendRequest(j.client, j.request)

	if statusCode == 404 {
		return commitMap, nil
	}

	if err != nil {
		return commitMap, err
	}

	buf := bytes.NewBuffer(body)

	for _, pair := range j.pairs {
		if gjson.Get(buf.String(), pair.FIELD).Exists() {
			(*commitMap)[pair.DESTKEY] = gjson.Get(buf.String(), pair.FIELD).Value()
		}
	}

	return commitMap, nil
}


text:
package ch.luklanis.esscan.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;

import ch.luklanis.esscan.PreferencesActivity;
import ch.luklanis.esscan.R;

public class OptionalOkDialog extends DialogFragment {
    private final int mMsgId;

    public OptionalOkDialog(int msgId) {
        this.mMsgId = msgId;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View checkboxLayout = inflater.inflate(R.layout.dont_show_again, null);
        final CheckBox dontShowAgainCheckBox = (CheckBox) checkboxLayout.findViewById(R.id.dont_show_again_checkbox);

        return new AlertDialog.Builder(getActivity()).setTitle(R.string.alert_title_information)
                .setMessage(mMsgId)
                .setView(checkboxLayout)
                .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (dontShowAgainCheckBox.isChecked()) {
                            PreferenceManager.getDefaultSharedPreferences(getActivity())
                                    .edit()
                                    .putInt(PreferencesActivity.KEY_NOT_SHOW_ALERT + String.valueOf(
                                            mMsgId), 1)
                                    .apply();
                        }
                    }
                })
                .create();
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Oo-ev3-scratch-extension by SHeimlich</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

Oo-ev3-scratch-extension

      View on GitHub
      Download .zip
      Download .tar.gz

Hello, world!

        Oo-ev3-scratch-extension is maintained by SHeimlich.

        This page was generated by GitHub Pages using the Cayman theme by Jason Long.


text:
package org.atnos.site.snippets.tutorial

trait UserInteractionSnippet {
// 8<---
import org.atnos.eff._, all._

sealed trait Interact[A]

case class Ask(prompt: String) extends Interact[String]
case class Tell(msg: String) extends Interact[Unit]

type _interact[R] = Interact |= R

def askUser[R :_interact](prompt: String): Eff[R, String] =
  send(Ask(prompt))

def tellUser[R :_interact](message: String): Eff[R, Unit] =
  send(Tell(message))

sealed trait DataOp[A]

type _dataOp[R] = DataOp |= R

case class AddCat(a: String) extends DataOp[Unit]
case class GetAllCats() extends DataOp[List[String]]

def addCat[R :_dataOp](a: String): Eff[R, Unit] =
  send(AddCat(a))

def getAllCats[R :_dataOp]: Eff[R, List[String]] =
  send(GetAllCats())

  // 8<---
}

object UserInteractionSnippet extends UserInteractionSnippet


text:
<?php

namespace User;

class Controller_Error extends Controller_Base {

	public function before()
	{
		parent::before();

	}

	/**
	 * The index action.
	 * @access  public
	 * @return  void
	 */
	public function action_index()
	{
		\Session::get_flash('error') or \Response::redirect("user/projects");
		$this->template->content = \View::forge('error/index.php');
	}
}

/* End of file error.php */


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- See fburl.com/140690840 for information about i18n on Android -->
<!-- @generated -->
<!-- FB Locale: qz_MM -->

<resources exclude-from-buck-resource-map="true">
</resources>


text:
/**
 * Created by long on 14-7-11.
 */
/**
 * var waves = [{types:["enemy1","enemy2"],count:5,interval:[3,5],gap:5},
 *             {types:["enemy1","enemy2"],count:5,interval:[3,5],gap:5},
 *             {types:["enemy1","enemy2"],count:5,interval:[3,5],gap:5}
 *             ...]
 * Set waves and waveAssetJson, if need, override the _doCreateEnemy function
 * */
flax.EnemyWaveModule = {
    waveAssetJson:null,
    waves:null,
    onWaveBegin:null,
    onEnemyIn:null,
    onWaveOver:null,
    batchCanvas:null,
    currentWave:-1,
    totalWaves:0,
    wavePaused:true,
    waveOver:false,
    _waveDefine:null,
    _enemyCount:0,
    _firstRun:true,
    onEnter:function()
    {
        this.totalWaves = this.waves.length;
        this.onWaveBegin = new signals.Signal();
        this.onEnemyIn = new signals.Signal();
        this.onWaveOver = new signals.Signal();
        if(!this.wavePaused){
            this.nextWave();
        }
    },
    onExit:function(){
        this.onWaveBegin.removeAll();
        this.onEnemyIn.removeAll();
        this.onWaveOver.removeAll();
    },
    startWave:function()
    {
        if(!this.wavePaused) return;
        this.wavePaused = false;
        if(this._firstRun) this.nextWave();
        else this._createWaveEnemy();
        this._firstRun = false;
    },
    stopWave:function()
    {
        if(this.wavePaused) return;
        this.wavePaused = true;
    },
    nextWave:function()
    {
        if(this.waveOver || this.wavePaused) return;
        this._enemyCount = 0;
        this.currentWave++;
        this._waveDefine = this.waves[this.currentWave];
        this._createWaveEnemy();
        this.onWaveBegin.dispatch();
    },
    _createWaveEnemy:function()
    {
        if(this.waveOver || this.wavePaused) return;
        var assetID = flax.getRandomInArray(this._waveDefine.types);
        var enemy = this._doCreateEnemy(assetID);
        this.onEnemyIn.dispatch(enemy);
        if(++this._enemyCount < this._waveDefine.count){
            var interval = flax.randInt(parseInt(this._waveDefine.interval[0]), parseInt(this._waveDefine.interval[1]));
            this.scheduleOnce(function(){
                this._createWaveEnemy();
            },interval);
        }else if(this.currentWave == this.totalWaves - 1){
            this.waveOver = true;
            this.onWaveOver.dispatch();
        }else{
            this.nextWave();
        }
    },
    _doCreateEnemy:function(assetID){
        if(this.waveAssetJson) flax.assetsManager.createDisplay(this.waveAssetJson, assetID, {parent: this.batchCanvas, x: this.x, y: this.y}, true);
        //override this function yourself
    }
};


text:
[![Build Status][BS img]][Build Status]
[![Dependency Status][DS img]][Dependency Status]

## Description

Jenkins box ready for in-house TravisCI emulation.

Helps you build a local VM for ruby development by using [Vagrant][] + [Chef-Solo][]

## Features

- [Jenkins][] with port forwarding to port 8080
- Build [Ruby][] projects using [RVM][]

## Installation

Ensure you meet the [requirements](#requirements) then automatically verify and install by using the bootstrap script:

    ./bootstrap.sh

Or avoid the bootstrap.sh and do it yourself manually:

```sh
# Ensure these commands doesn't fail
vagrant --version   #=> Vagrant 1.6.5
ruby --version      #=> Ruby 2.1.3
bundle --version    #=> Bundler version 1.7.3

# Install gems and cookboks
bundle install
bundle exec berks vendor cookbooks # Note `install --path` has been replaced with `vendor` as of berkshelf >= 3

# Optional if you already had on older version
vagrant plugin update vagrant-berkshelf
vagrant plugin update vagrant-omnibus

# Install necessary plugins. Ref on custom options: http://goo.gl/ce63lQ and http://goo.gl/gqMXbn
vagrant plugin install vagrant-berkshelf
#=> Installed the plugin 'vagrant-berkshelf (3.0.1)'
vagrant plugin install vagrant-omnibus
#=> Installed the plugin 'vagrant-omnibus   (1.4.1)'
```

After everything went fine start your VM:

    NODE_HOSTNAME=jenkins-master vagrant up
    #=> Thank you for installing Chef!
    #=> Machine booted and ready!

I settled Vagrant not to provision the VM so we can be flexible and start getting used to `knife solo` command.

To ssh into the VM

    NODE_HOSTNAME=jenkins-master vagrant ssh

Install chef on your target server or VM. Note `jenkins` is the hostname i'm giving to my VM for easy of use.

    bundle exec knife solo prepare jenkins --bootstrap-version 11.16.2-1

Now provision the target machine with the run_list within the node json file

    bundle exec knife solo cook jenkins nodes/jenkins.json

This final steps may take from minutes to a couple of hours. If you get a timeout error try executed the errored command by yourself on the target server. Default timeout is set to 10 minutes, if a command takes longer than that ssh into the server and run it yourself, e.g.

    # This was taking 15 minutes on a 512 DSL so had to `NODE_HOSTNAME=jenkins-master vagrant ssh` and:
    sudo apt-get -q -y install openjdk-7-jdk

Finally open your browser and visit Jenkins to verify is running:

    open http://localhost:8080

## Usage

TODO; WIP

## Requirements

- [Vagrant][] 1.4+
- [Ruby][] + [Bundler][]
- [Chef][] through [Chef-Solo][] + [Berkshelf][]
- *nix based Operating Systems (Linux, Ubuntu, Mac OSX, etc...)
- Not tested on Windows. You should at least ensure [GNU sed][] is installed.

Go [back to Installation](#installation)

## Testing

This suite uses [minitest-chef-handler][] for convergence integration testing for configuration management systems since it has a broader compatibility than [busser-bats][] through [test-kitchen][]. Why? because you can add launch the minitest [through a recipe][minitest-chef-handler#usage], thus making it compatible with [chef-solo][Chef-Solo], [chef-client][], [vagrant-chef][] and even [test-kitchen][].

So testing is performed once you add `"minitest-handler"` to your run_list. Note this is already added in the [Vagrantfile](Vagrantfile#L49) and [.kitchen.yml](.kitchen.yml#L36)

To run the test suite against multiple platforms check the [.kitchen.yml](.kitchen.yml) and enable the platforms there.
Then:

```bash
# Perform all tests automatically without destroying the VM afterwards
bundle exec kitchen test --destroy never --parallel

# Or do it step by step by yourself and one platform at a time
bundle exec kitchen create -l info
bundle exec kitchen converge -l info
bundle exec kitchen verify -l info

# Or one platform at a time
bundle exec kitchen create ubuntu-12 -l debug
bundle exec kitchen converge ubuntu-12 -l debug
bundle exec kitchen verify ubuntu-12 -l debug

# Login (ssh) into the VM called "common"
bundle exec kitchen login common

# To login manually (without kitchen magic)
ssh -p 2222 vagrant@localhost -i ~/.vagrant.d/insecure_private_key

# When you are all done, destroy the testing VM
bundle exec kitchen destroy
```

Sample ssh config `~/.ssh/config`

```bash
Host kitchen-test
  Hostname localhost
  HostKeyAlias common-ubuntu-1204-x86-64-jenkins-0
  Port 2222
  User vagrant
  IdentityFile ~/.vagrant.d/insecure_private_key
```

Then simply

```bash
ssh kitchen-test
```

The following is not necessary while using vagrant (without test-kitchen) since in your Vagrantfile this is already configured for you in this line:

```ruby
config.vm.network :forwarded_port, guest: 8080, host: 8080
```

But if playing with test-kitchen you can manually forward ports using ssh tunnels. For example to open jenkins at localhost:

```bash
# All manually
ssh -L localhost:8080:localhost:8080 -p 2222 vagrant@localhost -i ~/.vagrant.d/insecure_private_key

# Or if you have set up the suggested `~/.ssh/config` simplify the above line into this:
ssh -L localhost:8080:localhost:8080 kitchen-test
```

## Contributing

1. Fork it.
2. Make your feature addition or bug fix and create your feature branch.
3. Update the [Change Log][].
3. Add specs/tests for it. This is important so I don't break it in a future version unintentionally.
4. Commit, create a new Pull Request.
5. Check that your pull request passes the [build][travis pull requests].

## License

Released under the MIT License. See the [LICENSE][] file for further details.

[Jenkins]:    http://jenkins-ci.org/
[Vagrant]:    http://www.vagrantup.com/
[Bundler]:    http://bundler.io/
[Chef]:       http://www.opscode.com/chef/
[Chef-Solo]:  http://docs.vagrantup.com/v2/provisioning/chef_solo.html
[Berkshelf]:  http://berkshelf.com/
[Ruby]:       http://www.ruby-lang.org/
[RVM]:        http://rvm.io/
[GNU sed]:    http://gnuwin32.sourceforge.net/packages/sed.htm
[LICENSE]: LICENSE.md

[Change Log]: CHANGELOG.md

<!-- [RubyGems]: https://rubygems.org/gems/jenkins-box -->
<!-- [Documentation]: http://rubydoc.info/gems/jenkins-box -->
[Source]: https://github.com/elgalu/jenkins-box
[Bugtracker]: https://github.com/elgalu/jenkins-box/issues

[travis pull requests]: https://travis-ci.org/elgalu/jenkins-box/pull_requests

<!-- [Gem Version]: https://rubygems.org/gems/jenkins-box -->
[Build Status]: https://travis-ci.org/elgalu/jenkins-box
[Dependency Status]: https://gemnasium.com/elgalu/jenkins-box
[Code Climate]: https://codeclimate.com/github/elgalu/jenkins-box
<!-- [Coverage Status]: https://coveralls.io/r/elgalu/jenkins-box -->

<!-- [GV img]: https://badge.fury.io/rb/jenkins-box.png -->
[BS img]: https://travis-ci.org/elgalu/jenkins-box.png
[DS img]: https://gemnasium.com/elgalu/jenkins-box.png
[CC img]: https://codeclimate.com/github/elgalu/jenkins-box.png
<!-- [CS img]: https://coveralls.io/repos/elgalu/jenkins-box/badge.png?branch=master -->

[test-kitchen]: https://github.com/test-kitchen/test-kitchen
[minitest-chef-handler]: https://github.com/calavera/minitest-chef-handler
[busser-bats]: https://github.com/test-kitchen/busser-bats
[minitest-chef-handler#usage]: https://github.com/calavera/minitest-chef-handler#usage
[chef-client]: http://docs.opscode.com/chef_client.html
[vagrant-chef]: http://docs.vagrantup.com/v2/provisioning/chef_solo.html


text:
// Package app implements a server that runs a set of active
// components.  This includes replication controllers, service endpoints and
// nodes.
//
package app

import (
	"github.com/golang/glog"

	"k8s.io/apimachinery/pkg/runtime/schema"
	certcontroller "k8s.io/kubernetes/pkg/controller/certificates"
)

func startCSRController(ctx ControllerContext) (bool, error) {
	if !ctx.AvailableResources[schema.GroupVersionResource{Group: "certificates.k8s.io", Version: "v1beta1", Resource: "certificatesigningrequests"}] {
		return false, nil
	}
	c := ctx.ClientBuilder.ClientOrDie("certificate-controller")

	signer, err := certcontroller.NewCFSSLSigner(ctx.Options.ClusterSigningCertFile, ctx.Options.ClusterSigningKeyFile)
	if err != nil {
		glog.Errorf("Failed to start certificate controller: %v", err)
		return false, nil
	}

	certController, err := certcontroller.NewCertificateController(
		c,
		ctx.InformerFactory.Certificates().V1beta1().CertificateSigningRequests(),
		signer,
		certcontroller.NewGroupApprover(ctx.Options.ApproveAllKubeletCSRsForGroup),
	)
	if err != nil {
		// TODO this is failing consistently in test-cmd and local-up-cluster.sh.  Fix them and make it consistent with all others which
		// cause a crash loop
		glog.Errorf("Failed to start certificate controller: %v", err)
		return false, nil
	}
	go certController.Run(1, ctx.Stop)
	return true, nil
}


text:
#pragma once
#include <graphene/db/index.hpp>

namespace graphene { namespace db {

   /**
    *  @class simple_index
    *  @brief A simple index uses a vector<unique_ptr<T>> to store data
    *
    *  This index is preferred in situations where the data will never be
    *  removed from main memory and when access by ID is the only kind
    *  of access that is necessary.
    */
   template<typename T>
   class simple_index : public index
   {
      public:
         typedef T object_type;

         virtual const object&  create( const std::function<void(object&)>& constructor ) override
         {
             auto id = get_next_id();
             auto instance = id.instance();
             if( instance >= _objects.size() ) _objects.resize( instance + 1 );
             _objects[instance].reset(new T);
             _objects[instance]->id = id;
             constructor( *_objects[instance] );
             _objects[instance]->id = id; // just in case it changed
             use_next_id();
             return *_objects[instance];
         }

         virtual void modify( const object& obj, const std::function<void(object&)>& modify_callback ) override
         {
            assert( obj.id.instance() < _objects.size() );
            modify_callback( *_objects[obj.id.instance()] );
         }

         virtual const object& insert( object&& obj )override
         {
            auto instance = obj.id.instance();
            assert( nullptr != dynamic_cast<T*>(&obj) );
            if( _objects.size() <= instance ) _objects.resize( instance+1 );
            assert( !_objects[instance] );
            _objects[instance].reset( new T( std::move( static_cast<T&>(obj) ) ) );
            return *_objects[instance];
         }

         virtual void remove( const object& obj ) override
         {
            assert( nullptr != dynamic_cast<const T*>(&obj) );
            const auto instance = obj.id.instance();
            _objects[instance].reset();
            while( (_objects.size() > 0) && (_objects.back() == nullptr) )
               _objects.pop_back();
         }

         virtual const object* find( object_id_type id )const override
         {
            assert( id.space() == T::space_id );
            assert( id.type() == T::type_id );

            const auto instance = id.instance();
            if( instance >= _objects.size() ) return nullptr;
            return _objects[instance].get();
         }

         virtual void inspect_all_objects(std::function<void (const object&)> inspector)const override
         {
            try {
               for( const auto& ptr : _objects )
               {
                  if( ptr.get() )
                     inspector(*ptr);
               }
            } FC_CAPTURE_AND_RETHROW()
         }
         virtual fc::uint128 hash()const override {
            fc::uint128 result;
            for( const auto& ptr : _objects )
               result += ptr->hash();

            return result;
         }

         class const_iterator
         {
            public:
               const_iterator( const vector<unique_ptr<object>>& objects ):_objects(objects) {}
               const_iterator(
                  const vector<unique_ptr<object>>& objects,
                  const vector<unique_ptr<object>>::const_iterator& a ):_itr(a),_objects(objects){}
               friend bool operator==( const const_iterator& a, const const_iterator& b ) { return a._itr == b._itr; }
               friend bool operator!=( const const_iterator& a, const const_iterator& b ) { return a._itr != b._itr; }
               const T& operator*()const { return static_cast<const T&>(*_itr->get()); }
               const_iterator operator++(int)     // postfix
               {
                  const_iterator result( *this );
                  ++(*this);
                  return result;
               }
               const_iterator& operator++()       // prefix
               {
                  ++_itr;
                  while( (_itr != _objects.end()) && ( (*_itr) == nullptr ) )
                     ++_itr;
                  return *this;
               }
               typedef std::forward_iterator_tag iterator_category;
               typedef vector<unique_ptr<object> >::value_type value_type;
               typedef vector<unique_ptr<object> >::difference_type difference_type;
               typedef vector<unique_ptr<object> >::pointer pointer;
               typedef vector<unique_ptr<object> >::reference reference;
            private:
               vector<unique_ptr<object>>::const_iterator _itr;
               const vector<unique_ptr<object>>& _objects;
         };
         const_iterator begin()const { return const_iterator(_objects, _objects.begin()); }
         const_iterator end()const   { return const_iterator(_objects, _objects.end());   }

         size_t size()const { return _objects.size(); }
      private:
         vector< unique_ptr<object> > _objects;
   };

} } // graphene::db


text:
@extends('layouts.base')

@push('footer_scripts')

@endpush

@section('heading', 'Create Reservation')

@section('body')

    @include('reservation.create.partials.processingmodal')
    @include('reservation.create.partials.customer')

    @include('reservation.create.partials.reservation')
    <barnacle-warnings v-bind:warnings="warnings" v-on:dismiss="warnings.splice($event.index, 1)"></barnacle-warnings>

            <button type="button" class="btn btn-primary" v-on:click="submitReservation">Submit Reservation</button>

@endsection