text:
/* Originally based on Roman Nurik's SwipeDismissListViewTouchListener (https://gist.github.com/romannurik/2980593). */
package com.nhaarman.listviewanimations.itemmanipulation.swipedismiss;

import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.nhaarman.listviewanimations.itemmanipulation.TouchEventHandler;
import com.nhaarman.listviewanimations.util.AdapterViewUtil;
import com.nhaarman.listviewanimations.util.ListViewWrapper;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;

/**
 * An {@link android.view.View.OnTouchListener} that makes the list items in a {@link android.widget.AbsListView} swipeable.
 * Implementations of this class should implement {@link #afterViewFling(android.view.View, int)} to specify what to do after an item has been swiped.
 */
public abstract class SwipeTouchListener implements View.OnTouchListener, TouchEventHandler {

    /**
     * TranslationX View property.
     */
    private static final String TRANSLATION_X = "translationX";

    /**
     * Alpha View property.
     */
    private static final String ALPHA = "alpha";

    private static final int MIN_FLING_VELOCITY_FACTOR = 16;

    /**
     * The minimum distance in pixels that should be moved before starting horizontal item movement.
     */
    private final int mSlop;

    /**
     * The minimum velocity to initiate a fling, as measured in pixels per second.
     */
    private final int mMinFlingVelocity;

    /**
     * The maximum velocity to initiate a fling, as measured in pixels per second.
     */
    private final int mMaxFlingVelocity;

    /**
     * The duration of the fling animation.
     */
    private final long mAnimationTime;

    @NonNull
    private final ListViewWrapper mListViewWrapper;

    /**
     * The minimum alpha value of swiped Views.
     */
    private float mMinimumAlpha;

    /**
     * The width of the {@link android.widget.AbsListView} in pixels.
     */
    private int mViewWidth = 1;

    /**
     * The raw X coordinate of the down event.
     */
    private float mDownX;

    /**
     * The raw Y coordinate of the down event.
     */
    private float mDownY;

    /**
     * Indicates whether the user is swiping an item.
     */
    private boolean mSwiping;

    /**
     * Indicates whether the user can dismiss the current item.
     */
    private boolean mCanDismissCurrent;

    /**
     * The {@code VelocityTracker} used in the swipe movement.
     */
    @Nullable
    private VelocityTracker mVelocityTracker;

    /**
     * The parent {@link android.view.View} being swiped.
     */
    @Nullable
    private View mCurrentView;

    /**
     * The {@link android.view.View} that is actually being swiped.
     */
    @Nullable
    private View mSwipingView;

    /**
     * The current position being swiped.
     */
    private int mCurrentPosition = AdapterView.INVALID_POSITION;

    /**
     * The number of items in the {@code AbsListView}, minus the pending dismissed items.
     */
    private int mVirtualListCount = -1;

    /**
     * Indicates whether the {@link android.widget.AbsListView} is in a horizontal scroll container.
     * If so, this class will prevent the horizontal scroller from receiving any touch events.
     */
    private boolean mParentIsHorizontalScrollContainer;

    /**
     * The resource id of the {@link android.view.View} that may steal touch events from their parents. Useful for example
     * when the {@link android.widget.AbsListView} is in a horizontal scroll container, but not the whole {@code AbsListView} should
     * steal the touch events.
     */
    private int mTouchChildResId;

    /**
     * The {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.DismissableManager} which decides
     * whether or not a list item can be swiped.
     */
    @Nullable
    private DismissableManager mDismissableManager;

    /**
     * The number of active swipe animations.
     */
    private int mActiveSwipeCount;

    /**
     * Indicates whether swipe is enabled.
     */
    private boolean mSwipeEnabled = true;

    /**
     * Constructs a new {@code SwipeTouchListener} for the given {@link android.widget.AbsListView}.
     */
    @SuppressWarnings("UnnecessaryFullyQualifiedName")
    protected SwipeTouchListener(@NonNull final ListViewWrapper listViewWrapper) {
        ViewConfiguration vc = ViewConfiguration.get(listViewWrapper.getListView().getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * MIN_FLING_VELOCITY_FACTOR;
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = listViewWrapper.getListView().getContext().getResources().getInteger(android.R.integer.config_shortAnimTime);
        mListViewWrapper = listViewWrapper;
    }

    /**
     * Sets the {@link com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.DismissableManager} to specify which views can or cannot be swiped.
     *
     * @param dismissableManager {@code null} for no restrictions.
     */
    public void setDismissableManager(@Nullable final DismissableManager dismissableManager) {
        mDismissableManager = dismissableManager;
    }

    /**
     * Set the minimum value of the alpha property swiping Views should have.
     *
     * @param minimumAlpha the alpha value between 0.0f and 1.0f.
     */
    public void setMinimumAlpha(final float minimumAlpha) {
        mMinimumAlpha = minimumAlpha;
    }

    /**
     * If the {@link android.widget.AbsListView} is hosted inside a parent(/grand-parent/etc) that can scroll horizontally, horizontal swipes won't
     * work, because the parent will prevent touch-events from reaching the {@code AbsListView}.
     * <p/>
     * Call this method to fix this behavior.
     * Note that this will prevent the parent from scrolling horizontally when the user touches anywhere in a list item.
     */
    public void setParentIsHorizontalScrollContainer() {
        mParentIsHorizontalScrollContainer = true;
        mTouchChildResId = 0;
    }

    /**
     * Sets the resource id of a child view that should be touched to engage swipe.
     * When the user touches a region outside of that view, no swiping will occur.
     *
     * @param childResId The resource id of the list items' child that the user should touch to be able to swipe the list items.
     */
    public void setTouchChild(final int childResId) {
        mTouchChildResId = childResId;
        mParentIsHorizontalScrollContainer = false;
    }

    /**
     * Notifies this {@code SwipeTouchListener} that the adapter contents have changed.
     */
    public void notifyDataSetChanged() {
        if (mListViewWrapper.getAdapter() != null) {
            mVirtualListCount = mListViewWrapper.getCount() - mListViewWrapper.getHeaderViewsCount();
        }
    }

    /**
     * Returns whether the user is currently swiping an item.
     *
     * @return {@code true} if the user is swiping an item.
     */
    public boolean isSwiping() {
        return mSwiping;
    }

    @NonNull
    public ListViewWrapper getListViewWrapper() {
        return mListViewWrapper;
    }

    /**
     * Enables the swipe behavior.
     */
    public void enableSwipe() {
        mSwipeEnabled = true;
    }

    /**
     * Disables the swipe behavior.
     */
    public void disableSwipe() {
        mSwipeEnabled = false;
    }

    /**
     * Flings the {@link android.view.View} corresponding to given position out of sight.
     * Calling this method has the same effect as manually swiping an item off the screen.
     *
     * @param position the position of the item in the {@link android.widget.ListAdapter}. Must be visible.
     */
    public void fling(final int position) {
        int firstVisiblePosition = mListViewWrapper.getFirstVisiblePosition();
        int lastVisiblePosition = mListViewWrapper.getLastVisiblePosition();
        if (position < firstVisiblePosition || position > lastVisiblePosition) {
            throw new IllegalArgumentException("View for position " + position + " not visible!");
        }

        View downView = AdapterViewUtil.getViewForPosition(mListViewWrapper, position);
        if (downView == null) {
            throw new IllegalStateException("No view found for position " + position);
        }
        flingView(downView, position, true);

        mActiveSwipeCount++;
        mVirtualListCount--;
    }

    @Override
    public boolean isInteracting() {
        return mSwiping;
    }

    @Override
    public boolean onTouchEvent(@NonNull final MotionEvent event) {
        return onTouch(null, event);
    }

    @Override
    public boolean onTouch(@Nullable final View view, @NonNull final MotionEvent event) {
        if (mListViewWrapper.getAdapter() == null) {
            return false;
        }

        if (mVirtualListCount == -1 || mActiveSwipeCount == 0) {
            mVirtualListCount = mListViewWrapper.getCount() - mListViewWrapper.getHeaderViewsCount();
        }

        if (mViewWidth < 2) {
            mViewWidth = mListViewWrapper.getListView().getWidth();
        }

        boolean result;
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                result = handleDownEvent(view, event);
                break;
            case MotionEvent.ACTION_MOVE:
                result = handleMoveEvent(view, event);
                break;
            case MotionEvent.ACTION_CANCEL:
                result = handleCancelEvent();
                break;
            case MotionEvent.ACTION_UP:
                result = handleUpEvent(event);
                break;
            default:
                result = false;
        }

        return result;
    }

    private boolean handleDownEvent(@Nullable final View view, @NonNull final MotionEvent motionEvent) {
        if (!mSwipeEnabled) {
            return false;
        }

        View downView = findDownView(motionEvent);
        if (downView == null) {
            return false;
        }

        int downPosition = AdapterViewUtil.getPositionForView(mListViewWrapper, downView);
        mCanDismissCurrent = isDismissable(downPosition);

        /* Check if we are processing the item at this position */
        if (mCurrentPosition == downPosition || downPosition >= mVirtualListCount) {
            return false;
        }

        if (view != null) {
            view.onTouchEvent(motionEvent);
        }

        disableHorizontalScrollContainerIfNecessary(motionEvent, downView);

        mDownX = motionEvent.getX();
        mDownY = motionEvent.getY();

        mCurrentView = downView;
        mSwipingView = getSwipeView(downView);
        mCurrentPosition = downPosition;

        mVelocityTracker = VelocityTracker.obtain();
        mVelocityTracker.addMovement(motionEvent);
        return true;
    }

    /**
     * Returns the child {@link android.view.View} that was touched, by performing a hit test.
     *
     * @param motionEvent the {@link android.view.MotionEvent} to find the {@code View} for.
     *
     * @return the touched {@code View}, or {@code null} if none found.
     */
    @Nullable
    private View findDownView(@NonNull final MotionEvent motionEvent) {
        Rect rect = new Rect();
        int childCount = mListViewWrapper.getChildCount();
        int x = (int) motionEvent.getX();
        int y = (int) motionEvent.getY();
        View downView = null;
        for (int i = 0; i < childCount && downView == null; i++) {
            View child = mListViewWrapper.getChildAt(i);
            if (child != null) {
                child.getHitRect(rect);
                if (rect.contains(x, y)) {
                    downView = child;
                }
            }
        }
        return downView;
    }

    /**
     * Finds out whether the item represented by given position is dismissable.
     *
     * @param position the position of the item.
     *
     * @return {@code true} if the item is dismissable, false otherwise.
     */
    private boolean isDismissable(final int position) {
        if (mListViewWrapper.getAdapter() == null) {
            return false;
        }

        if (mDismissableManager != null) {
            long downId = mListViewWrapper.getAdapter().getItemId(position);
            return mDismissableManager.isDismissable(downId, position);
        }
        return true;
    }

    private void disableHorizontalScrollContainerIfNecessary(@NonNull final MotionEvent motionEvent, @NonNull final View view) {
        if (mParentIsHorizontalScrollContainer) {
            mListViewWrapper.getListView().requestDisallowInterceptTouchEvent(true);
        } else if (mTouchChildResId != 0) {
            mParentIsHorizontalScrollContainer = false;

            final View childView = view.findViewById(mTouchChildResId);
            if (childView != null) {
                final Rect childRect = getChildViewRect(mListViewWrapper.getListView(), childView);
                if (childRect.contains((int) motionEvent.getX(), (int) motionEvent.getY())) {
                    mListViewWrapper.getListView().requestDisallowInterceptTouchEvent(true);
                }
            }
        }
    }

    private boolean handleMoveEvent(@Nullable final View view, @NonNull final MotionEvent motionEvent) {
        if (mVelocityTracker == null || mCurrentView == null) {
            return false;
        }

        mVelocityTracker.addMovement(motionEvent);

        float deltaX = motionEvent.getX() - mDownX;
        float deltaY = motionEvent.getY() - mDownY;

        if (Math.abs(deltaX) > mSlop && Math.abs(deltaX) > Math.abs(deltaY)) {
            if (!mSwiping) {
                mActiveSwipeCount++;
                onStartSwipe(mCurrentView, mCurrentPosition);
            }
            mSwiping = true;
            mListViewWrapper.getListView().requestDisallowInterceptTouchEvent(true);

            /* Cancel ListView's touch (un-highlighting the item) */
            if (view != null) {
                MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                cancelEvent.setAction(MotionEvent.ACTION_CANCEL | motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT);
                view.onTouchEvent(cancelEvent);
                cancelEvent.recycle();
            }
        }

        if (mSwiping) {
            if (mCanDismissCurrent) {
                ViewHelper.setTranslationX(mSwipingView, deltaX);
                ViewHelper.setAlpha(mSwipingView, Math.max(mMinimumAlpha, Math.min(1, 1 - 2 * Math.abs(deltaX) / mViewWidth)));
            } else {
                ViewHelper.setTranslationX(mSwipingView, deltaX * 0.1f);
            }
            return true;
        }
        return false;
    }

    private boolean handleCancelEvent() {
        if (mVelocityTracker == null || mCurrentView == null) {
            return false;
        }

        if (mCurrentPosition != AdapterView.INVALID_POSITION && mSwiping) {
            onCancelSwipe(mCurrentView, mCurrentPosition);
            restoreCurrentViewTranslation();
        }

        reset();
        return false;
    }

    private boolean handleUpEvent(@NonNull final MotionEvent motionEvent) {
        if (mVelocityTracker == null || mCurrentView == null) {
            return false;
        }

        if (mSwiping) {
            boolean shouldDismiss = false;
            boolean dismissToRight = false;

            if (mCanDismissCurrent) {
                float deltaX = motionEvent.getX() - mDownX;

                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(1000);

                float velocityX = Math.abs(mVelocityTracker.getXVelocity());
                float velocityY = Math.abs(mVelocityTracker.getYVelocity());

                if (Math.abs(deltaX) > mViewWidth / 2) {
                    shouldDismiss = true;
                    dismissToRight = deltaX > 0;
                } else if (mMinFlingVelocity <= velocityX && velocityX <= mMaxFlingVelocity && velocityY < velocityX) {
                    shouldDismiss = true;
                    dismissToRight = mVelocityTracker.getXVelocity() > 0;
                }
            }

            if (shouldDismiss) {
                beforeViewFling(mCurrentView, mCurrentPosition);
                if (willLeaveDataSetOnFling(mCurrentView, mCurrentPosition)) {
                    mVirtualListCount--;
                }
                flingCurrentView(dismissToRight);
            } else {
                onCancelSwipe(mCurrentView, mCurrentPosition);
                restoreCurrentViewTranslation();
            }
        }

        reset();
        return false;
    }

    /**
     * Flings the pending {@link android.view.View} out of sight.
     *
     * @param flingToRight {@code true} if the {@code View} should be flinged to the right, {@code false} if it should be flinged to the left.
     */
    private void flingCurrentView(final boolean flingToRight) {
        if (mCurrentView != null) {
            flingView(mCurrentView, mCurrentPosition, flingToRight);
        }
    }

    /**
     * Flings given {@link android.view.View} out of sight.
     *
     * @param view         the parent {@link android.view.View}.
     * @param position     the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     * @param flingToRight {@code true} if the {@code View} should be flinged to the right, {@code false} if it should be flinged to the left.
     */
    private void flingView(@NonNull final View view, final int position, final boolean flingToRight) {
        if (mViewWidth < 2) {
            mViewWidth = mListViewWrapper.getListView().getWidth();
        }

        View swipeView = getSwipeView(view);
        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(swipeView, TRANSLATION_X, flingToRight ? mViewWidth : -mViewWidth);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(swipeView, ALPHA, 0);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(xAnimator, alphaAnimator);
        animatorSet.setDuration(mAnimationTime);
        animatorSet.addListener(new FlingAnimatorListener(view, position));
        animatorSet.start();
    }

    /**
     * Animates the pending {@link android.view.View} back to its original position.
     */
    private void restoreCurrentViewTranslation() {
        if (mCurrentView == null) {
            return;
        }

        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(mSwipingView, TRANSLATION_X, 0);
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mSwipingView, ALPHA, 1);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(xAnimator, alphaAnimator);
        animatorSet.setDuration(mAnimationTime);
        animatorSet.addListener(new RestoreAnimatorListener(mCurrentView, mCurrentPosition));
        animatorSet.start();
    }

    /**
     * Resets the fields to the initial values, ready to start over.
     */
    private void reset() {
        if (mVelocityTracker != null) {
            mVelocityTracker.recycle();
        }

        mVelocityTracker = null;
        mDownX = 0;
        mDownY = 0;
        mCurrentView = null;
        mSwipingView = null;
        mCurrentPosition = AdapterView.INVALID_POSITION;
        mSwiping = false;
        mCanDismissCurrent = false;
    }

    /**
     * Called when the user starts swiping a {@link android.view.View}.
     *
     * @param view     the {@code View} that is being swiped.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     */
    protected void onStartSwipe(@NonNull final View view, final int position) {
    }

    /**
     * Called when the swipe movement is canceled. A restore animation starts at this point.
     *
     * @param view     the {@code View} that was swiped.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     */
    protected void onCancelSwipe(@NonNull final View view, final int position) {
    }

    /**
     * Called after the restore animation of a canceled swipe movement ends.
     *
     * @param view     the {@code View} that is being swiped.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     */
    protected void afterCancelSwipe(@NonNull final View view, final int position) {
    }

    /**
     * Called when the user lifted their finger off the screen, and the {@link android.view.View} should be swiped away. A fling animation starts at this point.
     *
     * @param view     the {@code View} that is being flinged.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     */
    protected void beforeViewFling(@NonNull final View view, final int position) {
    }

    /**
     * Returns whether flinging the item at given position in the current state
     * would cause it to be removed from the data set.
     *
     * @param view the {@code View} that would be flinged.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     *
     * @return {@code true} if the item would leave the data set, {@code false} otherwise.
     */
    protected abstract boolean willLeaveDataSetOnFling(@NonNull View view, int position);

    /**
     * Called after the fling animation of a succesful swipe ends.
     * Users of this class should implement any finalizing behavior at this point, such as notifying the adapter.
     *
     * @param view     the {@code View} that is being swiped.
     * @param position the position of the item in the {@link android.widget.ListAdapter} corresponding to the {@code View}.
     */
    protected abstract void afterViewFling(@NonNull View view, int position);

    /**
     * Restores the {@link android.view.View}'s {@code alpha} and {@code translationX} values.
     * Users of this class should call this method when recycling {@code View}s.
     *
     * @param view the {@code View} whose presentation should be restored.
     */
    protected void restoreViewPresentation(@NonNull final View view) {
        View swipedView = getSwipeView(view);
        ViewHelper.setAlpha(swipedView, 1);
        ViewHelper.setTranslationX(swipedView, 0);
    }

    /**
     * Returns the number of active swipe animations.
     */
    protected int getActiveSwipeCount() {
        return mActiveSwipeCount;
    }

    /**
     * Returns the {@link android.view.View} that should be swiped away. Must be a child of given {@code View}, or the {@code View} itself.
     *
     * @param view the parent {@link android.view.View}.
     */
    @NonNull
    protected View getSwipeView(@NonNull final View view) {
        return view;
    }

    private static Rect getChildViewRect(final View parentView, final View childView) {
        Rect childRect = new Rect(childView.getLeft(), childView.getTop(), childView.getRight(), childView.getBottom());
        if (!parentView.equals(childView)) {
            View workingChildView = childView;
            ViewGroup parent;
            while (!(parent = (ViewGroup) workingChildView.getParent()).equals(parentView)) {
                childRect.offset(parent.getLeft(), parent.getTop());
                workingChildView = parent;
            }
        }
        return childRect;
    }

    /**
     * An {@link com.nineoldandroids.animation.Animator.AnimatorListener} that notifies when the fling animation has ended.
     */
    private class FlingAnimatorListener extends AnimatorListenerAdapter {

        @NonNull
        private final View mView;

        private final int mPosition;

        private FlingAnimatorListener(@NonNull final View view, final int position) {
            mView = view;
            mPosition = position;
        }

        @Override
        public void onAnimationEnd(@NonNull final Animator animation) {
            mActiveSwipeCount--;
            afterViewFling(mView, mPosition);
        }
    }

    /**
     * An {@link com.nineoldandroids.animation.Animator.AnimatorListener} that performs the dismissal animation when the current animation has ended.
     */
    private class RestoreAnimatorListener extends AnimatorListenerAdapter {

        @NonNull
        private final View mView;

        private final int mPosition;

        private RestoreAnimatorListener(@NonNull final View view, final int position) {
            mView = view;
            mPosition = position;
        }

        @Override
        public void onAnimationEnd(@NonNull final Animator animation) {
            mActiveSwipeCount--;
            afterCancelSwipe(mView, mPosition);
        }
    }
}


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.

#include "remoting/host/it2me/it2me_native_messaging_host.h"

#include <memory>
#include <string>
#include <utility>

#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringize_macros.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/policy/policy_constants.h"
#include "net/base/url_util.h"
#include "net/socket/client_socket_factory.h"
#include "net/url_request/url_request_context_getter.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/host_exit_codes.h"
#include "remoting/host/policy_watcher.h"
#include "remoting/host/service_urls.h"
#include "remoting/protocol/name_value_map.h"
#include "remoting/signaling/delegating_signal_strategy.h"

#if defined(OS_WIN)
#include "base/command_line.h"
#include "base/files/file_path.h"

#include "remoting/host/win/elevated_native_messaging_host.h"
#endif  // defined(OS_WIN)

namespace remoting {

namespace {

const remoting::protocol::NameMapElement<It2MeHostState> kIt2MeHostStates[] = {
    {kDisconnected, "DISCONNECTED"},
    {kStarting, "STARTING"},
    {kRequestedAccessCode, "REQUESTED_ACCESS_CODE"},
    {kReceivedAccessCode, "RECEIVED_ACCESS_CODE"},
    {kConnected, "CONNECTED"},
    {kError, "ERROR"},
    {kInvalidDomainError, "INVALID_DOMAIN_ERROR"},
    {kConnecting, "CONNECTING"},
};

#if defined(OS_WIN)
const base::FilePath::CharType kBaseHostBinaryName[] =
    FILE_PATH_LITERAL("remote_assistance_host.exe");
const base::FilePath::CharType kElevatedHostBinaryName[] =
    FILE_PATH_LITERAL("remote_assistance_host_uiaccess.exe");
#endif  // defined(OS_WIN)

// Helper function to run |callback| on the correct thread using |task_runner|.
void PolicyUpdateCallback(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner,
    remoting::PolicyWatcher::PolicyUpdatedCallback callback,
    std::unique_ptr<base::DictionaryValue> policies) {
  DCHECK(!callback.is_null());

  // Always post the task so the execution is consistent (always asynchronous).
  task_runner->PostTask(FROM_HERE,
                        base::Bind(callback, base::Passed(&policies)));
}

// Called when malformed policies are detected.
void OnPolicyError() {
  // TODO(joedow): Report the policy error to the user.  crbug.com/433009
  NOTIMPLEMENTED();
}

}  // namespace

It2MeNativeMessagingHost::It2MeNativeMessagingHost(
    bool needs_elevation,
    policy::PolicyService* policy_service,
    std::unique_ptr<ChromotingHostContext> context,
    std::unique_ptr<It2MeHostFactory> factory)
    : needs_elevation_(needs_elevation),
      host_context_(std::move(context)),
      factory_(std::move(factory)),
      policy_service_(policy_service),
      policy_watcher_(PolicyWatcher::Create(policy_service_,
                                            host_context_->file_task_runner())),
      weak_factory_(this) {
  weak_ptr_ = weak_factory_.GetWeakPtr();

  // The policy watcher runs on the |file_task_runner| but we want to run the
  // update code on |task_runner| so we use a shim to post the callback to the
  // preferred task runner.
  PolicyWatcher::PolicyUpdatedCallback update_callback =
      base::Bind(&It2MeNativeMessagingHost::OnPolicyUpdate, weak_ptr_);
  policy_watcher_->StartWatching(
      base::Bind(&PolicyUpdateCallback, task_runner(), update_callback),
      base::Bind(&OnPolicyError));
}

It2MeNativeMessagingHost::~It2MeNativeMessagingHost() {
  DCHECK(task_runner()->BelongsToCurrentThread());

  if (it2me_host_.get()) {
    it2me_host_->Disconnect();
    it2me_host_ = nullptr;
  }
}

void It2MeNativeMessagingHost::OnMessage(const std::string& message) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  std::unique_ptr<base::DictionaryValue> response(new base::DictionaryValue());
  std::unique_ptr<base::Value> message_value = base::JSONReader::Read(message);
  if (!message_value->IsType(base::Value::Type::DICTIONARY)) {
    LOG(ERROR) << "Received a message that's not a dictionary.";
    client_->CloseChannel(std::string());
    return;
  }

  std::unique_ptr<base::DictionaryValue> message_dict(
      static_cast<base::DictionaryValue*>(message_value.release()));

  // If the client supplies an ID, it will expect it in the response. This
  // might be a string or a number, so cope with both.
  const base::Value* id;
  if (message_dict->Get("id", &id))
    response->Set("id", id->CreateDeepCopy());

  std::string type;
  if (!message_dict->GetString("type", &type)) {
    SendErrorAndExit(std::move(response), "'type' not found in request.");
    return;
  }

  response->SetString("type", type + "Response");

  if (type == "hello") {
    ProcessHello(std::move(message_dict), std::move(response));
  } else if (type == "connect") {
    ProcessConnect(std::move(message_dict), std::move(response));
  } else if (type == "disconnect") {
    ProcessDisconnect(std::move(message_dict), std::move(response));
  } else if (type == "incomingIq") {
    ProcessIncomingIq(std::move(message_dict), std::move(response));
  } else {
    SendErrorAndExit(std::move(response), "Unsupported request type: " + type);
  }
}

void It2MeNativeMessagingHost::Start(Client* client) {
  DCHECK(task_runner()->BelongsToCurrentThread());
  client_ = client;
#if !defined(OS_CHROMEOS)
  log_message_handler_.reset(
      new LogMessageHandler(
          base::Bind(&It2MeNativeMessagingHost::SendMessageToClient,
                     base::Unretained(this))));
#endif  // !defined(OS_CHROMEOS)
}

void It2MeNativeMessagingHost::SendMessageToClient(
    std::unique_ptr<base::Value> message) const {
  DCHECK(task_runner()->BelongsToCurrentThread());
  std::string message_json;
  base::JSONWriter::Write(*message, &message_json);
  client_->PostMessageFromNativeHost(message_json);
}

void It2MeNativeMessagingHost::ProcessHello(
    std::unique_ptr<base::DictionaryValue> message,
    std::unique_ptr<base::DictionaryValue> response) const {
  DCHECK(task_runner()->BelongsToCurrentThread());

  response->SetString("version", STRINGIZE(VERSION));

  // This list will be populated when new features are added.
  std::unique_ptr<base::ListValue> supported_features_list(
      new base::ListValue());
  response->Set("supportedFeatures", supported_features_list.release());

  SendMessageToClient(std::move(response));
}

void It2MeNativeMessagingHost::ProcessConnect(
    std::unique_ptr<base::DictionaryValue> message,
    std::unique_ptr<base::DictionaryValue> response) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  if (!policy_received_) {
    DCHECK(pending_connect_.is_null());
    pending_connect_ =
        base::Bind(&It2MeNativeMessagingHost::ProcessConnect, weak_ptr_,
                   base::Passed(&message), base::Passed(&response));
    return;
  }

  if (needs_elevation_) {
    // Attempt to pass the current message to the elevated process.  This method
    // will spin up the elevated process if it is not already running.  On
    // success, the elevated process will process the message and respond.
    // If the process cannot be started or message passing fails, then return an
    // error to the message sender.
    if (!DelegateToElevatedHost(std::move(message))) {
      SendErrorAndExit(std::move(response),
                       "Failed to send message to elevated host.");
    }
    return;
  }

  if (it2me_host_.get()) {
    SendErrorAndExit(std::move(response),
                     "Connect can be called only when disconnected.");
    return;
  }

  std::string username;
  if (!message->GetString("userName", &username)) {
    SendErrorAndExit(std::move(response), "'userName' not found in request.");
    return;
  }

  bool use_signaling_proxy = false;
  message->GetBoolean("useSignalingProxy", &use_signaling_proxy);

  const ServiceUrls* service_urls = ServiceUrls::GetInstance();
  std::unique_ptr<SignalStrategy> signal_strategy;

  if (!use_signaling_proxy) {
    XmppSignalStrategy::XmppServerConfig xmpp_config;
    xmpp_config.username = username;

    const bool xmpp_server_valid =
        net::ParseHostAndPort(service_urls->xmpp_server_address(),
                              &xmpp_config.host, &xmpp_config.port);
    DCHECK(xmpp_server_valid);
    xmpp_config.use_tls = service_urls->xmpp_server_use_tls();

    std::string auth_service_with_token;
    if (!message->GetString("authServiceWithToken", &auth_service_with_token)) {
      SendErrorAndExit(std::move(response),
                       "'authServiceWithToken' not found in request.");
      return;
    }

    // For backward compatibility the webapp still passes OAuth service as part
    // of the authServiceWithToken field. But auth service part is always
    // expected to be set to oauth2.
    const char kOAuth2ServicePrefix[] = "oauth2:";
    if (!base::StartsWith(auth_service_with_token, kOAuth2ServicePrefix,
                          base::CompareCase::SENSITIVE)) {
      SendErrorAndExit(std::move(response), "Invalid 'authServiceWithToken': " +
                                                auth_service_with_token);
      return;
    }

    xmpp_config.auth_token =
        auth_service_with_token.substr(strlen(kOAuth2ServicePrefix));

#if !defined(NDEBUG)
    std::string address;
    if (!message->GetString("xmppServerAddress", &address)) {
      SendErrorAndExit(std::move(response),
                       "'xmppServerAddress' not found in request.");
      return;
    }

    if (!net::ParseHostAndPort(address, &xmpp_config.host, &xmpp_config.port)) {
      SendErrorAndExit(std::move(response),
                       "Invalid 'xmppServerAddress': " + address);
      return;
    }

    if (!message->GetBoolean("xmppServerUseTls", &xmpp_config.use_tls)) {
      SendErrorAndExit(std::move(response),
                       "'xmppServerUseTls' not found in request.");
      return;
    }
#endif  // !defined(NDEBUG)

    signal_strategy.reset(new XmppSignalStrategy(
        net::ClientSocketFactory::GetDefaultFactory(),
        host_context_->url_request_context_getter(), xmpp_config));
  } else {
    std::string local_jid;

    if (!message->GetString("localJid", &local_jid)) {
      SendErrorAndExit(std::move(response), "'localJid' not found in request.");
      return;
    }

    delegating_signal_strategy_ = new DelegatingSignalStrategy(
        local_jid, host_context_->network_task_runner(),
        base::Bind(&It2MeNativeMessagingHost::SendOutgoingIq,
                   weak_factory_.GetWeakPtr()));
    signal_strategy.reset(delegating_signal_strategy_);
  }

  std::string directory_bot_jid = service_urls->directory_bot_jid();

#if !defined(NDEBUG)
  if (!message->GetString("directoryBotJid", &directory_bot_jid)) {
    SendErrorAndExit(std::move(response),
                     "'directoryBotJid' not found in request.");
    return;
  }
#endif  // !defined(NDEBUG)

  // Create the It2Me host and start connecting.
  it2me_host_ = factory_->CreateIt2MeHost(
      host_context_->Copy(), policy_service_, weak_ptr_,
      std::move(signal_strategy), username, directory_bot_jid);
  it2me_host_->Connect();

  SendMessageToClient(std::move(response));
}

void It2MeNativeMessagingHost::ProcessDisconnect(
    std::unique_ptr<base::DictionaryValue> message,
    std::unique_ptr<base::DictionaryValue> response) {
  DCHECK(task_runner()->BelongsToCurrentThread());
  DCHECK(policy_received_);

  if (needs_elevation_) {
    // Attempt to pass the current message to the elevated process.  This method
    // will spin up the elevated process if it is not already running.  On
    // success, the elevated process will process the message and respond.
    // If the process cannot be started or message passing fails, then return an
    // error to the message sender.
    if (!DelegateToElevatedHost(std::move(message))) {
      SendErrorAndExit(std::move(response),
                       "Failed to send message to elevated host.");
    }
    return;
  }

  if (it2me_host_.get()) {
    it2me_host_->Disconnect();
    it2me_host_ = nullptr;
  }
  SendMessageToClient(std::move(response));
}

void It2MeNativeMessagingHost::ProcessIncomingIq(
    std::unique_ptr<base::DictionaryValue> message,
    std::unique_ptr<base::DictionaryValue> response) {
  std::string iq;
  if (!message->GetString("iq", &iq)) {
    LOG(ERROR) << "Invalid incomingIq() data.";
    return;
  }

  if (delegating_signal_strategy_)
    delegating_signal_strategy_->OnIncomingMessage(iq);
  SendMessageToClient(std::move(response));
};

void It2MeNativeMessagingHost::SendOutgoingIq(const std::string& iq) {
  std::unique_ptr<base::DictionaryValue> message(new base::DictionaryValue());
  message->SetString("iq", iq);
  message->SetString("type", "sendOutgoingIq");
  SendMessageToClient(std::move(message));
}

void It2MeNativeMessagingHost::SendErrorAndExit(
    std::unique_ptr<base::DictionaryValue> response,
    const std::string& description) const {
  DCHECK(task_runner()->BelongsToCurrentThread());

  LOG(ERROR) << description;

  response->SetString("type", "error");
  response->SetString("description", description);
  SendMessageToClient(std::move(response));

  // Trigger a host shutdown by sending an empty message.
  client_->CloseChannel(std::string());
}

void It2MeNativeMessagingHost::OnStateChanged(
    It2MeHostState state,
    const std::string& error_message) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  state_ = state;

  std::unique_ptr<base::DictionaryValue> message(new base::DictionaryValue());

  message->SetString("type", "hostStateChanged");
  message->SetString("state", HostStateToString(state));

  switch (state_) {
    case kReceivedAccessCode:
      message->SetString("accessCode", access_code_);
      message->SetInteger("accessCodeLifetime",
                          access_code_lifetime_.InSeconds());
      break;

    case kConnected:
      message->SetString("client", client_username_);
      break;

    case kDisconnected:
      client_username_.clear();
      break;

    case kError:
      // kError is an internal-only state, sent to the web-app by a separate
      // "error" message so that errors that occur before the "connect" message
      // is sent can be communicated.
      message->SetString("type", "error");
      message->SetString("description", error_message);
      break;

    default:
      break;
  }

  SendMessageToClient(std::move(message));
}

void It2MeNativeMessagingHost::OnNatPolicyChanged(bool nat_traversal_enabled) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  std::unique_ptr<base::DictionaryValue> message(new base::DictionaryValue());

  message->SetString("type", "natPolicyChanged");
  message->SetBoolean("natTraversalEnabled", nat_traversal_enabled);
  SendMessageToClient(std::move(message));
}

// Stores the Access Code for the web-app to query.
void It2MeNativeMessagingHost::OnStoreAccessCode(
    const std::string& access_code,
    base::TimeDelta access_code_lifetime) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  access_code_ = access_code;
  access_code_lifetime_ = access_code_lifetime;
}

// Stores the client user's name for the web-app to query.
void It2MeNativeMessagingHost::OnClientAuthenticated(
    const std::string& client_username) {
  DCHECK(task_runner()->BelongsToCurrentThread());

  client_username_ = client_username;
}

scoped_refptr<base::SingleThreadTaskRunner>
It2MeNativeMessagingHost::task_runner() const {
  return host_context_->ui_task_runner();
}

/* static */
std::string It2MeNativeMessagingHost::HostStateToString(
    It2MeHostState host_state) {
  return ValueToName(kIt2MeHostStates, host_state);
}

void It2MeNativeMessagingHost::OnPolicyUpdate(
    std::unique_ptr<base::DictionaryValue> policies) {
  if (policy_received_) {
    // Don't dynamically change how the host operates since we don't have a good
    // way to communicate changes to the user.
    return;
  }

  bool allow_elevated_host = false;
  if (!policies->GetBoolean(
          policy::key::kRemoteAccessHostAllowUiAccessForRemoteAssistance,
          &allow_elevated_host)) {
    LOG(WARNING) << "Failed to retrieve elevated host policy value.";
  }
#if defined(OS_WIN)
  LOG(INFO) << "Allow UiAccess for Remote Assistance: " << allow_elevated_host;
#endif  // defined(OS_WIN)

  policy_received_ = true;

  // If |allow_elevated_host| is false, then we will fall back to using a host
  // running in the current context regardless of the elevation request.  This
  // may not be ideal, but is still functional.
  needs_elevation_ = needs_elevation_ && allow_elevated_host;
  if (!pending_connect_.is_null()) {
    base::ResetAndReturn(&pending_connect_).Run();
  }
}

#if defined(OS_WIN)

bool It2MeNativeMessagingHost::DelegateToElevatedHost(
    std::unique_ptr<base::DictionaryValue> message) {
  DCHECK(task_runner()->BelongsToCurrentThread());
  DCHECK(needs_elevation_);

  if (!elevated_host_) {
    base::FilePath binary_path =
        base::CommandLine::ForCurrentProcess()->GetProgram();
    CHECK(binary_path.BaseName() == base::FilePath(kBaseHostBinaryName));

    // The new process runs at an elevated level due to being granted uiAccess.
    // |parent_window_handle| can be used to position dialog windows but is not
    // currently used.
    elevated_host_.reset(new ElevatedNativeMessagingHost(
        binary_path.DirName().Append(kElevatedHostBinaryName),
        /*parent_window_handle=*/0,
        /*elevate_process=*/false,
        /*host_timeout=*/base::TimeDelta(), client_));
  }

  if (elevated_host_->EnsureElevatedHostCreated()) {
    elevated_host_->SendMessage(std::move(message));
    return true;
  }

  return false;
}

#else  // !defined(OS_WIN)

bool It2MeNativeMessagingHost::DelegateToElevatedHost(
    std::unique_ptr<base::DictionaryValue> message) {
  NOTREACHED();
  return false;
}

#endif  // !defined(OS_WIN)

}  // namespace remoting

redpajama_set_name: RedPajamaGithub


text:
{% extends "base.html" %}

{% block title %}{{ title }}{% endblock %}
{% block content %}
{% include "paste/paste-meta.html" %}
{{ highlighted|safe }}
{% endblock %}


text:
layout: relation
title:  'nsubj:pass'
shortdef : 'passive nominal subject'
udver: '2'
---

A passive nominal subject is a noun phrase which is the syntactic
subject of a passive clause.

~~~ sdparse
ב אוסטרליה , הועלה חשש בנוגע ל מיסחור של זכויות להט"ב על ידי תאגידים גדולים
nsubj:pass(הועלה, חשש)
~~~

<!-- Interlanguage links updated Po lis 14 15:35:35 CET 2022 -->


text:
require 'spec_helper'

describe Article do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
from django.conf import settings

# @@@ TODO: recurse through available content apps and dynamically set this
CONTENT_MODELS = getattr(settings,
                         'VIEWS_CONTENT_MODELS',
                         ['post', 'page', 'widget', ])


text:
/**
 * @internal
 */
export type SkyConfirmButtonAction = 'ok' | 'yes' | 'no' | 'cancel';


text:
using Xunit;
using static LanguageExt.Prelude;

namespace LanguageExt.Tests.Transformer.Traverse.Identity.Sync
{
    public class Option
    {
        [Fact]
        public void SomeIdentityIsIdentitySome()
        {
            var ma = Some(Id(42));

            var mb = ma.Traverse(identity);

            var mc = Id(Some(42));

            Assert.Equal(mc, mb);
        }

        [Fact]
        public void NoneIdentityIsIdentityNone()
        {
            var ma = Option<Identity<int>>.None;

            var mb = ma.Traverse(identity);

            var mc = Id(Option<int>.None);

            Assert.Equal(mc, mb);
        }
    }
}


text:
<!--
  Copyright 2019 Google LLC

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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
{% extends "layout.html" %}
{% block import_element %}
  {% raw %}
    <script src="/private/bower_components/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="/private/bower_components/polymer/polymer.html">
    <link rel="import" href="/private/bower_components/iron-icons/iron-icons.html">
    <link rel="import" href="/private/bower_components/iron-icon/iron-icon.html">
    <link rel="import" href="/private/bower_components/paper-icon-button/paper-icon-button.html">
    <link rel="import" href="/private/bower_components/paper-item/paper-item.html">
    <link rel="import" href="/private/bower_components/paper-listbox/paper-listbox.html">
    <link rel="import" href="/private/bower_components/app-layout/app-layout.html">

    <link rel="import" href="/private/components/testcase-list/testcase-list.html">

    <link rel="import" href="/private/components/technology/technology.html">
    <link rel="stylesheet" type="text/css" href="/private/stylesheets/main.css">
  {% endraw %}
{% endblock %}
{% block page_title %}
  Testcases
{% endblock %}
{% block content %}
  <dom-bind id="page">
    <template>
      <template is="dom-if" if="[[data]]">
        <testcase-list
            field-values="[[data.fieldValues]]"
            params="[[data.params]]"
            result="[[data.result]]"></testcase-list>
      </template>
    </template>
  </dom-bind>
  <script>
    document.querySelector('#page').data = {
      result: JSON.parse(atob('{{result|json}}')),
      fieldValues: JSON.parse(atob('{{fieldValues|json}}')),
      params: JSON.parse(atob('{{params|json}}'))
    };
  </script>
{% endblock %}


text:
"""
Django settings for _project410 project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import dj_database_url

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
#PROJECT_ROOT = os.path.normpath(os.path.join(BASE_DIR, '..'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+ei^7v4d_$7vf+$&cdsrr4zl0$$+c7hxn*ay02vnx+#^snfrp6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = [".herokuapp.com", "localhost", "127.0.0.1",
                 "compute-1.amazonaws.com"]

# Application definition
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #'rest_framework',
    'main',
    'friends',
    'friendrequest',
)

# Remote Authentication Modifications for Basic HTTP Auth
# https://docs.djangoproject.com/en/dev/howto/auth-remote-user/
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.RemoteUserMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATE_CONTEXT_PROCESSOR = (
    "django.contrib.auth.context_processors.auth",
    "django.template.context_processors.debug",
    "django.template.context_processors.i18n",
    "django.template.context_processors.media",
    "django.template.context_processors.static",
    "django.template.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

#AUTHENTICATION_BACKENDS = [
#    'django.contrib.auth.backends.RemoteUserBackend',
#]

ROOT_URLCONF = '_project410.urls'

WSGI_APPLICATION = '_project410.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

#DATABASES = {
#      'default': {
#          'ENGINE': 'django.db.backends.sqlite3',
#          'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
          #'NAME': os.path.join(PROJECT_ROOT, 'db.sqlite3'),
#      }
#  }

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Edmonton'

USE_I18N = True
USE_L10N = True
USE_TZ = True

STATIC_URL = '/static/'

#if ON_HEROKU:
#   DATABASE_URL = 'postgresql:///postgresql'
#else:
#   DATABASE_URL = 'sqlite://' + os.path.join(BASE_DIR, 'db.sqlite3')
#DATABASES = {'default': dj_database_url.config(default=DATABASE_URL)}

#ADDEDEDD THE FOLLLOWWINGGG TO DEAAALLLL WITHTHTHT DB ERRORS WHEN LOCAL

# if DEBUG:
#DATABASES = {
#   'default': {
#   'ENGINE': 'django.db.backends.sqlite3',
#   'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#   'USER': '',
#   'PASSWORD': '',
#   'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
#   'PORT': '',
# }
# }
# else:
#     DATABASES = {
#         'default': {
#         'ENGINE': 'django.db.backends.postgresql_psycopg2',
#         'NAME': 'deglt3tqs5mjfa',
#         'HOST': 'ec2-23-21-187-45.compute-1.amazonaws.com',
#         'USER': 'mwmqqmbieymuyq',
#         'PASSWORD' : '3D8Ruktp2PaYUFFvDE-2jKRhaD',
#         'PORT' : '5432',

#     }
# }

# DATABASES = {
#        'default': {
#        'ENGINE': 'django.db.backends.postgresql_psycopg2',
#        'NAME': 'deglt3tqs5mjfa',
#        'HOST': 'ec2-23-21-187-45.compute-1.amazonaws.com',
#        'USER': 'mwmqqmbieymuyq',
#        'PASSWORD' : '3D8Ruktp2PaYUFFvDE-2jKRhaD',
#        'PORT' : '5432',

#    }
# }

# new one

DATABASES = {
      'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': 'deqvblu3a2v0u9',
      'HOST': 'ec2-107-22-173-230.compute-1.amazonaws.com',
      'USER': 'shijubeknomhcq',
      'PASSWORD' : 'pKlULpGCjvOibbrlt0qNHOtkr4',
      'PORT' : '5432',
  }

}

# Parse database configuration from $DATABASE_URL
#COMMMENTEED OUT THIIIISSS LINNENENENENE
#DATABASES['default'] =  dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
TEMPLATE_DIRS = (os.path.join(PROJECT_PATH, '/author/templates'), )

# trying to fix loading static files when debug false. Save for last?
if DEBUG:
  STATIC_ROOT = "/static/images"
else:
  STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
    '/author/static/images',
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = os.path.join(PROJECT_PATH,'/static/')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media') # Absolute path to the media directory


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    ' and ' => ' et ',
    '{delta, plural, =1{1 day} other{# days}}' => '{delta, plural, =1{1 jour} other{# jours}}',
    '{delta, plural, =1{1 hour} other{# hours}}' => '{delta, plural, =1{1 heure} other{# heures}}',
    '{delta, plural, =1{1 minute} other{# minutes}}' => '{delta, plural, =1{1 minute} other{# minutes}}',
    '{delta, plural, =1{1 month} other{# months}}' => 'mois',
    '{delta, plural, =1{1 second} other{# seconds}}' => '{delta, plural, =1{1 seconde} other{# secondes}}',
    '{delta, plural, =1{1 year} other{# years}}' => '{delta, plural, =1{1 année} other{# années}}',
    '(not set)' => '(non défini)',
    'An internal server error occurred.' => 'Une erreur de serveur interne s\'est produite.',
    'Are you sure you want to delete this item?' => 'Êtes-vous sûr de vouloir supprimer cet élément ?',
    'Delete' => 'Supprimer',
    'Error' => 'Erreur',
    'File upload failed.' => 'Le téléchargement du fichier a échoué.',
    'Home' => 'Accueil',
    'Invalid data received for parameter "{param}".' => 'Données non valides reçues pour le paramètre « {param} ».',
    'Login Required' => 'Identifiant requis',
    'Missing required arguments: {params}' => 'Arguments manquants requis : {params}',
    'Missing required parameters: {params}' => 'Paramètres manquants requis : {params}',
    'No' => 'Non',
    'No results found.' => 'Aucun résultat trouvé.',
    'Only files with these MIME types are allowed: {mimeTypes}.' => 'Seulement les fichiers ayant ces types MIME sont autorisés : {mimeTypes}.',
    'Only files with these extensions are allowed: {extensions}.' => 'Les extensions de fichiers autorisées sont : {extensions}.',
    'Page not found.' => 'Page non trouvée.',
    'Please fix the following errors:' => 'Veuillez vérifier les erreurs suivantes :',
    'Please upload a file.' => 'Veuillez télécharger un fichier.',
    'Showing {begin, number}-{end, number} of {totalCount, number} {totalCount, plural, one{item} other{items}}.' => 'Affichage de {begin, number}-{end, number} sur {totalCount, number} {totalCount, plural, one{élément} other{éléments}}.',
    'The combination {values} of {attributes} has already been taken.' => 'La combinaison {values} de {attributes} est déjà utilisée.',
    'The file "{file}" is not an image.' => 'Le fichier « {file} » n\'est pas une image.',
    'The file "{file}" is too big. Its size cannot exceed {formattedLimit}.' => 'Le fichier « {file} » est trop gros. Sa taille ne peut dépasser {formattedLimit}.',
    'The file "{file}" is too small. Its size cannot be smaller than {formattedLimit}.' => 'Le fichier « {file} » est trop petit. Sa taille ne peut être inférieure à {formattedLimit}.',
    'The format of {attribute} is invalid.' => 'Le format de {attribute} est invalide',
    'The image "{file}" is too large. The height cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'L\'image « {file} » est trop grande. La hauteur ne peut être supérieure à {limit, number} {limit, plural, one{pixel} other{pixels}}.',
    'The image "{file}" is too large. The width cannot be larger than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'L\'image « {file} » est trop large. La largeur ne peut être supérieure à {limit, number} {limit, plural, one{pixel} other{pixels}}.',
    'The image "{file}" is too small. The height cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'L\'image « {file} » est trop petite. La hauteur ne peut être inférieure à {limit, number} {limit, plural, one{pixel} other{pixels}}.',
    'The image "{file}" is too small. The width cannot be smaller than {limit, number} {limit, plural, one{pixel} other{pixels}}.' => 'L\'image « {file} » est trop petite. La largeur ne peut être inférieure à {limit, number} {limit, plural, one{pixel} other{pixels}}.',
    'The requested view "{name}" was not found.' => 'La vue demandée « {name} » n\'a pas été trouvée.',
    'The verification code is incorrect.' => 'Le code de vérification est incorrect.',
    'Total {count, number} {count, plural, one{item} other{items}}.' => 'Total {count, number} {count, plural, one{élément} other{éléments}}.',
    'Unable to verify your data submission.' => 'Impossible de vérifier votre envoi de données.',
    'Unknown option: --{name}' => 'Option inconnue : --{name}',
    'Update' => 'Modifier',
    'View' => 'Voir',
    'Yes' => 'Oui',
    'You are not allowed to perform this action.' => 'Vous n\'êtes pas autorisé à effectuer cette action.',
    'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'Vous pouvez télécharger au maximum {limit, number} {limit, plural, one{fichier} other{fichiers}}.',
    'in {delta, plural, =1{a day} other{# days}}' => 'dans {delta, plural, =1{un jour} other{# jours}}',
    'in {delta, plural, =1{a minute} other{# minutes}}' => 'dans {delta, plural, =1{une minute} other{# minutes}}',
    'in {delta, plural, =1{a month} other{# months}}' => 'dans {delta, plural, =1{un mois} other{# mois}}',
    'in {delta, plural, =1{a second} other{# seconds}}' => 'dans {delta, plural, =1{une seconde} other{# secondes}}',
    'in {delta, plural, =1{a year} other{# years}}' => 'dans {delta, plural, =1{un an} other{# ans}}',
    'in {delta, plural, =1{an hour} other{# hours}}' => 'dans {delta, plural, =1{une heure} other{# heures}}',
    'just now' => 'à l\'instant',
    'the input value' => 'la valeur d\'entrée',
    '{attribute} "{value}" has already been taken.' => '{attribute} « {value} » a déjà été pris.',
    '{attribute} cannot be blank.' => '{attribute} ne peut être vide.',
    '{attribute} contains wrong subnet mask.' => '{attribute} contient un masque de sous-réseau non valide.',
    '{attribute} is invalid.' => '{attribute} est invalide.',
    '{attribute} is not a valid URL.' => '{attribute} n\'est pas une URL valide.',
    '{attribute} is not a valid email address.' => '{attribute} n\'est pas une adresse email valide.',
    '{attribute} is not in the allowed range.' => '{attribute} n\'est pas dans la plage autorisée.',
    '{attribute} must be "{requiredValue}".' => '{attribute} doit êre « {requiredValue} ».',
    '{attribute} must be a number.' => '{attribute} doit être un nombre.',
    '{attribute} must be a string.' => '{attribute} doit être au format texte.',
    '{attribute} must be a valid IP address.' => '{attribute} doit être une adresse IP valide.',
    '{attribute} must be an IP address with specified subnet.' => '{attribute} doit être une adresse IP avec un sous-réseau.',
    '{attribute} must be an integer.' => '{attribute} doit être un entier.',
    '{attribute} must be either "{true}" or "{false}".' => '{attribute} doit être soit « {true} » soit « {false} ».',
    '{attribute} must be equal to "{compareValueOrAttribute}".' => '{attribute} doit être égal à "{compareValueOrAttribute}".',
    '{attribute} must be greater than "{compareValueOrAttribute}".' => '{attribute} doit être supérieur à « {compareValueOrAttribute} ».',
    '{attribute} must be greater than or equal to "{compareValueOrAttribute}".' => '{attribute} doit être supérieur ou égal à « {compareValueOrAttribute} ».',
    '{attribute} must be less than "{compareValueOrAttribute}".' => '{attribute} doit être inférieur à « {compareValueOrAttribute} ».',
    '{attribute} must be less than or equal to "{compareValueOrAttribute}".' => '{attribute} doit être inférieur ou égal à « {compareValueOrAttribute} ».',
    '{attribute} must be no greater than {max}.' => '{attribute} ne doit pas être supérieur à {max}.',
    '{attribute} must be no less than {min}.' => '{attribute} ne doit pas être inférieur à {min}.',
    '{attribute} must be repeated exactly.' => '{attribute} doit être identique.',
    '{attribute} must not be a subnet.' => '{attribute} ne doit pas être un sous-réseau.',
    '{attribute} must not be an IPv4 address.' => '{attribute} ne doit pas être une adresse IPv4.',
    '{attribute} must not be an IPv6 address.' => '{attribute} ne doit pas être une adresse IPv6.',
    '{attribute} must not be equal to "{compareValueOrAttribute}".' => '{attribute} ne doit pas être égal à « {compareValueOrAttribute} ».',
    '{attribute} should contain at least {min, number} {min, plural, one{character} other{characters}}.' => '{attribute} doit comporter au moins {min, number} {min, plural, one{caractère} other{caractères}}.',
    '{attribute} should contain at most {max, number} {max, plural, one{character} other{characters}}.' => '{attribute} doit comporter au plus {max, number} {max, plural, one{caractère} other{caractères}}.',
    '{attribute} should contain {length, number} {length, plural, one{character} other{characters}}.' => '{attribute} doit comporter {length, number} {length, plural, one{caractère} other{caractères}}.',
    '{delta, plural, =1{a day} other{# days}} ago' => 'il y a {delta, plural, =1{un jour} other{# jours}}',
    '{delta, plural, =1{a minute} other{# minutes}} ago' => 'il y a {delta, plural, =1{une minute} other{# minutes}}',
    '{delta, plural, =1{a month} other{# months}} ago' => 'il y a {delta, plural, =1{un mois} other{# mois}}',
    '{delta, plural, =1{a second} other{# seconds}} ago' => 'il y a {delta, plural, =1{une seconde} other{# secondes}}',
    '{delta, plural, =1{a year} other{# years}} ago' => 'il y a {delta, plural, =1{un an} other{# ans}}',
    '{delta, plural, =1{an hour} other{# hours}} ago' => 'il y a {delta, plural, =1{une heure} other{# heures}}',
    '{nFormatted} B' => '{nFormatted} o',
    '{nFormatted} GB' => '{nFormatted} Go',
    '{nFormatted} GiB' => '{nFormatted} Gio',
    '{nFormatted} KB' => '{nFormatted} Ko',
    '{nFormatted} KiB' => '{nFormatted} Kio',
    '{nFormatted} MB' => '{nFormatted} Mo',
    '{nFormatted} MiB' => '{nFormatted} Mio',
    '{nFormatted} PB' => '{nFormatted} Po',
    '{nFormatted} PiB' => '{nFormatted} Pio',
    '{nFormatted} TB' => '{nFormatted} To',
    '{nFormatted} TiB' => '{nFormatted} Tio',
    '{nFormatted} {n, plural, =1{byte} other{bytes}}' => '{nFormatted} {n, plural, =1{octet} other{octets}}',
    '{nFormatted} {n, plural, =1{gibibyte} other{gibibytes}}' => '{nFormatted} {n, plural, =1{# gigaoctet} other{# gigaoctets}}',
    '{nFormatted} {n, plural, =1{gigabyte} other{gigabytes}}' => '{nFormatted} {n, plural, =1{gibioctet} other{gibioctets}}',
    '{nFormatted} {n, plural, =1{kibibyte} other{kibibytes}}' => '{nFormatted} {n, plural, =1{kibioctet} other{kibioctets}}',
    '{nFormatted} {n, plural, =1{kilobyte} other{kilobytes}}' => '{nFormatted} {n, plural, =1{# kilooctet} other{# kilooctets}}',
    '{nFormatted} {n, plural, =1{mebibyte} other{mebibytes}}' => '{nFormatted} {n, plural, =1{mebioctet} other{mebioctets}}',
    '{nFormatted} {n, plural, =1{megabyte} other{megabytes}}' => '{nFormatted} {n, plural, =1{# megaoctet} other{# megaoctets}}',
    '{nFormatted} {n, plural, =1{pebibyte} other{pebibytes}}' => '{nFormatted} {n, plural, =1{pebioctet} other{pebioctets}}',
    '{nFormatted} {n, plural, =1{petabyte} other{petabytes}}' => '{nFormatted} {n, plural, =1{# petaoctet} other{# petaoctets}}',
    '{nFormatted} {n, plural, =1{tebibyte} other{tebibytes}}' => '{nFormatted} {n, plural, =1{# teraoctet} other{# teraoctets}}',
    '{nFormatted} {n, plural, =1{terabyte} other{terabytes}}' => '{nFormatted} {n, plural, =1{# teraoctet} other{# teraoctets}}',
];


text:
'use strict'

const routes = require('./routes')

exports.register = (server, options, next) => {
  server.route(routes)

  next()
}

exports.register.attributes = {
  pkg: require('./package.json')
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../libc/fn.realloc.html">

Redirecting to ../../libc/fn.realloc.html...


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.4</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>io.pratik.i18n</groupId>
	<artifactId>productapp</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>productapp</name>
	<description>Demo project for Spring Boot Internationalization</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using MvcMusicStore.Application;
using MvcMusicStore.Application.Interfaces;
using MvcMusicStore.CrossCutting.Identity.Configuration;
using MvcMusicStore.CrossCutting.Identity.Context;
using MvcMusicStore.CrossCutting.Identity.Model;
using MvcMusicStore.Data.Context;
using MvcMusicStore.Data.Context.Interfaces;
using MvcMusicStore.Data.Repository.Dapper;
using MvcMusicStore.Data.Repository.EntityFramework;
using MvcMusicStore.Domain.Entities;
using MvcMusicStore.Domain.Interfaces.Repository;
using MvcMusicStore.Domain.Interfaces.Repository.Common;
using MvcMusicStore.Domain.Interfaces.Repository.ReadOnly;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using MvcMusicStore.Domain.Interfaces.Service;
using MvcMusicStore.Domain.Interfaces.Service.Common;
using MvcMusicStore.Domain.Services;
using MvcMusicStore.Domain.Services.Common;

namespace MvcMusicStore.CrossCutting.IoCSimpleInjector
{
    public class IoC
    {
        public static void RegisterServices(Container container)
        {
            #region Service Module

            container.Register(typeof(IService<>), typeof(Service<>), new WebRequestLifestyle());

            container.RegisterPerWebRequest<IGenreService, GenreService>();
            container.RegisterPerWebRequest<IArtistService, ArtistService>();
            container.RegisterPerWebRequest<IAlbumService, AlbumService>();
            container.RegisterPerWebRequest<ICartService, CartService>();
            container.RegisterPerWebRequest<IOrderService, OrderService>();
            container.RegisterPerWebRequest<IOrderDetailService, OrderDetailService>();
            container.RegisterPerWebRequest<IClientService, ClientService>();
            container.RegisterPerWebRequest<IUserService, UserService>();

            #endregion

            #region Infrastructure Module

            container.Register(typeof(IContextManager<MusicStoreContext>), (typeof(ContextManager<MusicStoreContext>)));
            container.Register(typeof(IUnitOfWork<MusicStoreContext>), (typeof(UnitOfWork<MusicStoreContext>)));

            container.Register(typeof(IContextManager<StoreContext>), (typeof(ContextManager<StoreContext>)));
            container.Register(typeof(IUnitOfWork<StoreContext>), (typeof(UnitOfWork<StoreContext>)));

            container.Register(typeof(IContextManager<IdentityContext>), (typeof(ContextManager<IdentityContext>)));
            container.Register(typeof(IUnitOfWork<IdentityContext>), (typeof(UnitOfWork<IdentityContext>)));

            container.RegisterPerWebRequest<ApplicationDbContext>();
            container.RegisterPerWebRequest<IUserStore<ApplicationUser>>(() => new UserStore<ApplicationUser>(new ApplicationDbContext()));
            container.RegisterPerWebRequest<IRoleStore<IdentityRole, string>>(() => new RoleStore<IdentityRole>());
            container.RegisterPerWebRequest<ApplicationRoleManager>();
            container.RegisterPerWebRequest<ApplicationUserManager>();
            container.RegisterPerWebRequest<ApplicationSignInManager>();

            #endregion

            #region Repository Module

            container.RegisterPerWebRequest<IGenreRepository, GenreRepository>();
            container.RegisterPerWebRequest<IRepository<Genre>, GenreRepository>();
            container.RegisterPerWebRequest<IGenreReadOnlyRepository, GenreDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Genre>, GenreDapperRepository>();

            container.RegisterPerWebRequest<IArtistRepository, ArtistRepository>();
            container.RegisterPerWebRequest<IRepository<Artist>, ArtistRepository>();
            container.RegisterPerWebRequest<IArtistReadOnlyRepository, ArtistDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Artist>, ArtistDapperRepository>();

            container.RegisterPerWebRequest<IAlbumRepository, AlbumRepository>();
            container.RegisterPerWebRequest<IRepository<Album>, AlbumRepository>();
            container.RegisterPerWebRequest<IAlbumReadOnlyRepository, AlbumDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Album>, AlbumDapperRepository>();

            container.RegisterPerWebRequest<ICartRepository, CartRepository>();
            container.RegisterPerWebRequest<IRepository<Cart>, CartRepository>();
            container.RegisterPerWebRequest<ICartReadOnlyRepository, CartDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Cart>, CartDapperRepository>();

            container.RegisterPerWebRequest<IOrderRepository, OrderRepository>();
            container.RegisterPerWebRequest<IRepository<Order>, OrderRepository>();
            container.RegisterPerWebRequest<IOrderReadOnlyRepository, OrderDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Order>, OrderDapperRepository>();

            container.RegisterPerWebRequest<IOrderDetailRepository, OrderDetailRepository>();
            container.RegisterPerWebRequest<IRepository<OrderDetail>, OrderDetailRepository>();
            container.RegisterPerWebRequest<IOrderDetailReadOnlyRepository, OrderDetailDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<OrderDetail>, OrderDetailDapperRepository>();

            container.RegisterPerWebRequest<IClientRepository, ClientRepository>();
            container.RegisterPerWebRequest<IRepository<Client>, ClientRepository>();
            container.RegisterPerWebRequest<IClientReadOnlyRepository, ClientDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<Client>, ClientDapperRepository>();

            container.RegisterPerWebRequest<IUserRepository, UserRepository>();
            container.RegisterPerWebRequest<IRepository<User>, UserRepository>();
            container.RegisterPerWebRequest<IUserReadOnlyRepository, UserDapperRepository>();
            container.RegisterPerWebRequest<IReadOnlyRepository<User>, UserDapperRepository>();

            #endregion

            #region Application Module

            container.RegisterPerWebRequest<IGenreAppService, GenreAppService>();
            container.RegisterPerWebRequest<IArtistAppService, ArtistAppService>();
            container.RegisterPerWebRequest<IAlbumAppService, AlbumAppService>();
            container.RegisterPerWebRequest<ICartAppService, CartAppService>();
            container.RegisterPerWebRequest<IOrderAppService, OrderAppService>();
            container.RegisterPerWebRequest<IOrderDetailAppService, OrderDetailAppService>();
            container.RegisterPerWebRequest<IClientAppService, ClientAppService>();
            container.RegisterPerWebRequest<IUserAppService, UserAppService>();

            #endregion
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IEMHR_ASP_App
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
package org.sakaiproject.nakamura.solr;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

public class Utils {

	private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class);

	public static String getParentPath(String path) {
		if ("/".equals(path)) {
			return "/";
		}
		int i = path.lastIndexOf('/');
		if (i == path.length() - 1) {
			i = path.substring(0, i).lastIndexOf('/');
		}
		String res = path;
		if (i > 0) {
			res = path.substring(0, i);
		} else if (i == 0) {
			return "/";
		}
		return res;
	}

	public static String getSolrHome(BundleContext bundleContext)
			throws IOException {
		String slingHomePath = bundleContext.getProperty("sling.home");
		File solrHome = new File(slingHomePath, "solr");
		if (!solrHome.isDirectory() && !solrHome.mkdirs()) {
      LOGGER.info(
          "verifyConfiguration: Cannot create Solr home {}, failed creating default configuration ",
          solrHome.getAbsolutePath());
      return null;
		}
		return solrHome.getAbsolutePath();
	}

	public static String toString(Object property, String defaultValue) {
		if (property == null) {
			return defaultValue;
		}
		return String.valueOf(property);
	}

	public static int toInt(Object property, int defaultValue) {
		if (property == null) {
			return defaultValue;
		}
		return Integer.parseInt(String.valueOf(property));
	}

	public static long toLong(Object property, long defaultValue) {
		if (property == null) {
			return defaultValue;
		}
		return Long.parseLong(String.valueOf(property));
	}

	public static boolean toBoolean(Object property, boolean defaultValue) {
		if (property == null) {
			return defaultValue;
		}
		return Boolean.parseBoolean(String.valueOf(property));
	}

    public static String[] toStringArray(Object property, String[] defaultArray) {
        if (property == null) {
            return defaultArray;

        } else if (property instanceof String && !((String)property).isEmpty()) {
            return ((String) property).split("\\|");

        } else if (property instanceof String[]) {
            // String[]
            return (String[]) property;

        } else if (property.getClass().isArray()) {
            // other array
            Object[] valueArray = (Object[]) property;
            List<String> values = Lists.newArrayListWithExpectedSize(valueArray.length);
            for (Object value : valueArray) {
                if (value != null) {
                    values.add(value.toString());
                }
            }
            return values.toArray(new String[values.size()]);

        } else if (property instanceof Collection<?>) {
            // collection
            Collection<?> valueCollection = (Collection<?>) property;
            List<String> valueList = Lists.newArrayListWithExpectedSize(valueCollection.size());
            for (Object value : valueCollection) {
                if (value != null) {
                    valueList.add(value.toString());
                }
            }
            return valueList.toArray(new String[valueList.size()]);
        }

        return defaultArray;
    }

	public static int defaultMax(int ttl) {
		if (ttl <= 0) {
			return Integer.MAX_VALUE;
		}
		return ttl;
	}

}


text:
category: Components
type: Data Display
title: Popover
cover: https://gw.alipayobjects.com/zos/alicdn/1PNL1p_cO/Popover.svg
---

The floating card popped by clicking or hovering.

## When To Use

A simple popup menu to provide extra information or operations.

Comparing with `Tooltip`, besides information `Popover` card can also provide action elements like links and buttons.

## API

| Param | Description | Type | Default value | Version |
| --- | --- | --- | --- | --- |
| content | Content of the card | ReactNode \| () => ReactNode | - |  |
| title | Title of the card | ReactNode \| () => ReactNode | - |  |

Consult [Tooltip's documentation](/components/tooltip/#API) to find more APIs.

## Note

Please ensure that the child node of `Popover` accepts `onMouseEnter`, `onMouseLeave`, `onFocus`, `onClick` events.


text:
lgsm_version="271215"

echo "applying WebAdmin ut2003.css fix."
echo "http://forums.tripwireinteractive.com/showpost.php?p=585435&postcount=13"
sed -i 's/none}/none;/g' "${filesdir}/Web/ServerAdmin/ut2003.css"
sed -i 's/underline}/underline;/g' "${filesdir}/Web/ServerAdmin/ut2003.css"
sleep 1
echo "applying WebAdmin CharSet fix."
echo "http://forums.tripwireinteractive.com/showpost.php?p=442340&postcount=1"
sed -i 's/CharSet="iso-8859-1"/CharSet="utf-8"/g' "${systemdir}/UWeb.int"
sleep 1
echo ""
echo -en "forcing server restart.\r"
sleep 0.5
echo -en "forcing server restart..\r"
sleep 0.5
echo -en "forcing server restart...\r"
sleep 0.5
echo -en "\n"
sleep 0.5
command_start.sh
sleep 5
command_stop.sh
command_start.sh
sleep 5
command_stop.sh


text:
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource
from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response
from nssrc.com.citrix.netscaler.nitro.service.options import options
from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception

from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util

class nd6ravariables(base_resource) :
	""" Configuration for nd6 Router Advertisment configuration variables resource. """
	def __init__(self) :
		self._vlan = 0
		self._ceaserouteradv = ""
		self._sendrouteradv = ""
		self._srclinklayeraddroption = ""
		self._onlyunicastrtadvresponse = ""
		self._managedaddrconfig = ""
		self._otheraddrconfig = ""
		self._currhoplimit = 0
		self._maxrtadvinterval = 0
		self._minrtadvinterval = 0
		self._linkmtu = 0
		self._reachabletime = 0
		self._retranstime = 0
		self._defaultlifetime = 0
		self._lastrtadvtime = 0
		self._nextrtadvdelay = 0
		self.___count = 0

	@property
	def vlan(self) :
		ur"""The VLAN number.
Maximum length =  4094.
		"""
		try :
			return self._vlan
		except Exception as e:
			raise e

	@vlan.setter
	def vlan(self, vlan) :
		ur"""The VLAN number.
Maximum length =  4094
		"""
		try :
			self._vlan = vlan
		except Exception as e:
			raise e

	@property
	def ceaserouteradv(self) :
		ur"""Cease router advertisements on this vlan.
Default value: NO
Possible values = YES, NO.
		"""
		try :
			return self._ceaserouteradv
		except Exception as e:
			raise e

	@ceaserouteradv.setter
	def ceaserouteradv(self, ceaserouteradv) :
		ur"""Cease router advertisements on this vlan.
Default value: NO
Possible values = YES, NO
		"""
		try :
			self._ceaserouteradv = ceaserouteradv
		except Exception as e:
			raise e

	@property
	def sendrouteradv(self) :
		ur"""whether the router sends periodic RAs and responds to Router Solicitations.
Default value: NO
Possible values = YES, NO.
		"""
		try :
			return self._sendrouteradv
		except Exception as e:
			raise e

	@sendrouteradv.setter
	def sendrouteradv(self, sendrouteradv) :
		ur"""whether the router sends periodic RAs and responds to Router Solicitations.
Default value: NO
Possible values = YES, NO
		"""
		try :
			self._sendrouteradv = sendrouteradv
		except Exception as e:
			raise e

	@property
	def srclinklayeraddroption(self) :
		ur"""Include source link layer address option in RA messages.
Default value: YES
Possible values = YES, NO.
		"""
		try :
			return self._srclinklayeraddroption
		except Exception as e:
			raise e

	@srclinklayeraddroption.setter
	def srclinklayeraddroption(self, srclinklayeraddroption) :
		ur"""Include source link layer address option in RA messages.
Default value: YES
Possible values = YES, NO
		"""
		try :
			self._srclinklayeraddroption = srclinklayeraddroption
		except Exception as e:
			raise e

	@property
	def onlyunicastrtadvresponse(self) :
		ur"""Send only Unicast Router Advertisements in respond to Router Solicitations.
Default value: NO
Possible values = YES, NO.
		"""
		try :
			return self._onlyunicastrtadvresponse
		except Exception as e:
			raise e

	@onlyunicastrtadvresponse.setter
	def onlyunicastrtadvresponse(self, onlyunicastrtadvresponse) :
		ur"""Send only Unicast Router Advertisements in respond to Router Solicitations.
Default value: NO
Possible values = YES, NO
		"""
		try :
			self._onlyunicastrtadvresponse = onlyunicastrtadvresponse
		except Exception as e:
			raise e

	@property
	def managedaddrconfig(self) :
		ur"""Value to be placed in the Managed address configuration flag field.
Default value: NO
Possible values = YES, NO.
		"""
		try :
			return self._managedaddrconfig
		except Exception as e:
			raise e

	@managedaddrconfig.setter
	def managedaddrconfig(self, managedaddrconfig) :
		ur"""Value to be placed in the Managed address configuration flag field.
Default value: NO
Possible values = YES, NO
		"""
		try :
			self._managedaddrconfig = managedaddrconfig
		except Exception as e:
			raise e

	@property
	def otheraddrconfig(self) :
		ur"""Value to be placed in the Other configuration flag field.
Default value: NO
Possible values = YES, NO.
		"""
		try :
			return self._otheraddrconfig
		except Exception as e:
			raise e

	@otheraddrconfig.setter
	def otheraddrconfig(self, otheraddrconfig) :
		ur"""Value to be placed in the Other configuration flag field.
Default value: NO
Possible values = YES, NO
		"""
		try :
			self._otheraddrconfig = otheraddrconfig
		except Exception as e:
			raise e

	@property
	def currhoplimit(self) :
		ur"""Current Hop limit.
Default value: 64
Maximum length =  255.
		"""
		try :
			return self._currhoplimit
		except Exception as e:
			raise e

	@currhoplimit.setter
	def currhoplimit(self, currhoplimit) :
		ur"""Current Hop limit.
Default value: 64
Maximum length =  255
		"""
		try :
			self._currhoplimit = currhoplimit
		except Exception as e:
			raise e

	@property
	def maxrtadvinterval(self) :
		ur"""Maximum time allowed between unsolicited multicast RAs, in seconds.
Default value: 600
Minimum length =  4
Maximum length =  1800.
		"""
		try :
			return self._maxrtadvinterval
		except Exception as e:
			raise e

	@maxrtadvinterval.setter
	def maxrtadvinterval(self, maxrtadvinterval) :
		ur"""Maximum time allowed between unsolicited multicast RAs, in seconds.
Default value: 600
Minimum length =  4
Maximum length =  1800
		"""
		try :
			self._maxrtadvinterval = maxrtadvinterval
		except Exception as e:
			raise e

	@property
	def minrtadvinterval(self) :
		ur"""Minimum time interval between RA messages, in seconds.
Default value: 198
Minimum length =  3
Maximum length =  1350.
		"""
		try :
			return self._minrtadvinterval
		except Exception as e:
			raise e

	@minrtadvinterval.setter
	def minrtadvinterval(self, minrtadvinterval) :
		ur"""Minimum time interval between RA messages, in seconds.
Default value: 198
Minimum length =  3
Maximum length =  1350
		"""
		try :
			self._minrtadvinterval = minrtadvinterval
		except Exception as e:
			raise e

	@property
	def linkmtu(self) :
		ur"""The Link MTU.
Default value: 0
Maximum length =  1500.
		"""
		try :
			return self._linkmtu
		except Exception as e:
			raise e

	@linkmtu.setter
	def linkmtu(self, linkmtu) :
		ur"""The Link MTU.
Default value: 0
Maximum length =  1500
		"""
		try :
			self._linkmtu = linkmtu
		except Exception as e:
			raise e

	@property
	def reachabletime(self) :
		ur"""Reachable time, in milliseconds.
Default value: 0
Maximum length =  3600000.
		"""
		try :
			return self._reachabletime
		except Exception as e:
			raise e

	@reachabletime.setter
	def reachabletime(self, reachabletime) :
		ur"""Reachable time, in milliseconds.
Default value: 0
Maximum length =  3600000
		"""
		try :
			self._reachabletime = reachabletime
		except Exception as e:
			raise e

	@property
	def retranstime(self) :
		ur"""Retransmission time, in milliseconds.
Default value: 0.
		"""
		try :
			return self._retranstime
		except Exception as e:
			raise e

	@retranstime.setter
	def retranstime(self, retranstime) :
		ur"""Retransmission time, in milliseconds.
Default value: 0
		"""
		try :
			self._retranstime = retranstime
		except Exception as e:
			raise e

	@property
	def defaultlifetime(self) :
		ur"""Default life time, in seconds.
Default value: 1800
Maximum length =  9000.
		"""
		try :
			return self._defaultlifetime
		except Exception as e:
			raise e

	@defaultlifetime.setter
	def defaultlifetime(self, defaultlifetime) :
		ur"""Default life time, in seconds.
Default value: 1800
Maximum length =  9000
		"""
		try :
			self._defaultlifetime = defaultlifetime
		except Exception as e:
			raise e

	@property
	def lastrtadvtime(self) :
		ur"""Last RA sent timestamp.
		"""
		try :
			return self._lastrtadvtime
		except Exception as e:
			raise e

	@property
	def nextrtadvdelay(self) :
		ur"""Next RA delay.
		"""
		try :
			return self._nextrtadvdelay
		except Exception as e:
			raise e

	def _get_nitro_response(self, service, response) :
		ur""" converts nitro response into object and returns the object array in case of get request.
		"""
		try :
			result = service.payload_formatter.string_to_resource(nd6ravariables_response, response, self.__class__.__name__)
			if(result.errorcode != 0) :
				if (result.errorcode == 444) :
					service.clear_session(self)
				if result.severity :
					if (result.severity == "ERROR") :
						raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
				else :
					raise nitro_exception(result.errorcode, str(result.message), str(result.severity))
			return result.nd6ravariables
		except Exception as e :
			raise e

	def _get_object_name(self) :
		ur""" Returns the value of object identifier argument
		"""
		try :
			if self.vlan is not None :
				return str(self.vlan)
			return None
		except Exception as e :
			raise e

	@classmethod
	def update(cls, client, resource) :
		ur""" Use this API to update nd6ravariables.
		"""
		try :
			if type(resource) is not list :
				updateresource = nd6ravariables()
				updateresource.vlan = resource.vlan
				updateresource.ceaserouteradv = resource.ceaserouteradv
				updateresource.sendrouteradv = resource.sendrouteradv
				updateresource.srclinklayeraddroption = resource.srclinklayeraddroption
				updateresource.onlyunicastrtadvresponse = resource.onlyunicastrtadvresponse
				updateresource.managedaddrconfig = resource.managedaddrconfig
				updateresource.otheraddrconfig = resource.otheraddrconfig
				updateresource.currhoplimit = resource.currhoplimit
				updateresource.maxrtadvinterval = resource.maxrtadvinterval
				updateresource.minrtadvinterval = resource.minrtadvinterval
				updateresource.linkmtu = resource.linkmtu
				updateresource.reachabletime = resource.reachabletime
				updateresource.retranstime = resource.retranstime
				updateresource.defaultlifetime = resource.defaultlifetime
				return updateresource.update_resource(client)
			else :
				if (resource and len(resource) > 0) :
					updateresources = [ nd6ravariables() for _ in range(len(resource))]
					for i in range(len(resource)) :
						updateresources[i].vlan = resource[i].vlan
						updateresources[i].ceaserouteradv = resource[i].ceaserouteradv
						updateresources[i].sendrouteradv = resource[i].sendrouteradv
						updateresources[i].srclinklayeraddroption = resource[i].srclinklayeraddroption
						updateresources[i].onlyunicastrtadvresponse = resource[i].onlyunicastrtadvresponse
						updateresources[i].managedaddrconfig = resource[i].managedaddrconfig
						updateresources[i].otheraddrconfig = resource[i].otheraddrconfig
						updateresources[i].currhoplimit = resource[i].currhoplimit
						updateresources[i].maxrtadvinterval = resource[i].maxrtadvinterval
						updateresources[i].minrtadvinterval = resource[i].minrtadvinterval
						updateresources[i].linkmtu = resource[i].linkmtu
						updateresources[i].reachabletime = resource[i].reachabletime
						updateresources[i].retranstime = resource[i].retranstime
						updateresources[i].defaultlifetime = resource[i].defaultlifetime
				result = cls.update_bulk_request(client, updateresources)
			return result
		except Exception as e :
			raise e

	@classmethod
	def unset(cls, client, resource, args) :
		ur""" Use this API to unset the properties of nd6ravariables resource.
		Properties that need to be unset are specified in args array.
		"""
		try :
			if type(resource) is not list :
				unsetresource = nd6ravariables()
				if type(resource) !=  type(unsetresource):
					unsetresource.vlan = resource
				else :
					unsetresource.vlan = resource.vlan
				return unsetresource.unset_resource(client, args)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						unsetresources = [ nd6ravariables() for _ in range(len(resource))]
						for i in range(len(resource)) :
							unsetresources[i].vlan = resource[i]
				else :
					if (resource and len(resource) > 0) :
						unsetresources = [ nd6ravariables() for _ in range(len(resource))]
						for i in range(len(resource)) :
							unsetresources[i].vlan = resource[i].vlan
				result = cls.unset_bulk_request(client, unsetresources, args)
			return result
		except Exception as e :
			raise e

	@classmethod
	def get(cls, client, name="", option_="") :
		ur""" Use this API to fetch all the nd6ravariables resources that are configured on netscaler.
		"""
		try :
			if not name :
				obj = nd6ravariables()
				response = obj.get_resources(client, option_)
			else :
				if type(name) != cls :
					if type(name) is not list :
						obj = nd6ravariables()
						obj.vlan = name
						response = obj.get_resource(client, option_)
					else :
						if name and len(name) > 0 :
							response = [nd6ravariables() for _ in range(len(name))]
							obj = [nd6ravariables() for _ in range(len(name))]
							for i in range(len(name)) :
								obj[i] = nd6ravariables()
								obj[i].vlan = name[i]
								response[i] = obj[i].get_resource(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def get_filtered(cls, client, filter_) :
		ur""" Use this API to fetch filtered set of nd6ravariables resources.
		filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = nd6ravariables()
			option_ = options()
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			return response
		except Exception as e :
			raise e

	@classmethod
	def count(cls, client) :
		ur""" Use this API to count the nd6ravariables resources configured on NetScaler.
		"""
		try :
			obj = nd6ravariables()
			option_ = options()
			option_.count = True
			response = obj.get_resources(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	@classmethod
	def count_filtered(cls, client, filter_) :
		ur""" Use this API to count filtered the set of nd6ravariables resources.
		Filter string should be in JSON format.eg: "port:80,servicetype:HTTP".
		"""
		try :
			obj = nd6ravariables()
			option_ = options()
			option_.count = True
			option_.filter = filter_
			response = obj.getfiltered(client, option_)
			if response :
				return response[0].__dict__['___count']
			return 0
		except Exception as e :
			raise e

	class Managedaddrconfig:
		YES = "YES"
		NO = "NO"

	class Onlyunicastrtadvresponse:
		YES = "YES"
		NO = "NO"

	class Sendrouteradv:
		YES = "YES"
		NO = "NO"

	class Otheraddrconfig:
		YES = "YES"
		NO = "NO"

	class Srclinklayeraddroption:
		YES = "YES"
		NO = "NO"

	class Ceaserouteradv:
		YES = "YES"
		NO = "NO"

class nd6ravariables_response(base_response) :
	def __init__(self, length=1) :
		self.nd6ravariables = []
		self.errorcode = 0
		self.message = ""
		self.severity = ""
		self.sessionid = ""
		self.nd6ravariables = [nd6ravariables() for _ in range(length)]