text:
package me.framework.fragmentation.swipeback;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.IntDef;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentationHack;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.xin.framework.xinframwork.R;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import me.framework.fragmentation.ISupportFragment;
import me.framework.fragmentation.swipeback.core.ISwipeBackActivity;

/**
 * Thx https://github.com/ikew0ng/SwipeBackLayout.
 * <p>
 * Created by YoKey on 16/4/19.
 */
public class SwipeBackLayout extends FrameLayout {
    /**
     * Edge flag indicating that the left edge should be affected.
     */
    public static final int EDGE_LEFT = ViewDragHelper.EDGE_LEFT;

    /**
     * Edge flag indicating that the right edge should be affected.
     */
    public static final int EDGE_RIGHT = ViewDragHelper.EDGE_RIGHT;

    public static final int EDGE_ALL = EDGE_LEFT | EDGE_RIGHT;

    /**
     * A view is not currently being dragged or animating as a result of a
     * fling/snap.
     */
    public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;

    /**
     * A view is currently being dragged. The position is currently changing as
     * a result of user input or simulated user input.
     */
    public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;

    /**
     * A view is currently settling into place as a result of a fling or
     * predefined non-interactive motion.
     */
    public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;

    private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
    private static final float DEFAULT_PARALLAX = 0.33f;
    private static final int FULL_ALPHA = 255;
    private static final float DEFAULT_SCROLL_THRESHOLD = 0.4f;
    private static final int OVERSCROLL_DISTANCE = 10;

    private float mScrollFinishThreshold = DEFAULT_SCROLL_THRESHOLD;

    private ViewDragHelper mHelper;

    private float mScrollPercent;
    private float mScrimOpacity;

    private FragmentActivity mActivity;
    private View mContentView;
    private ISupportFragment mFragment;
    private Fragment mPreFragment;

    private Drawable mShadowLeft;
    private Drawable mShadowRight;
    private Rect mTmpRect = new Rect();

    private int mEdgeFlag;
    private boolean mEnable = true;
    private int mCurrentSwipeOrientation;
    private float mParallaxOffset = DEFAULT_PARALLAX;

    private boolean mCallOnDestroyView;

    private boolean mInLayout;

    private int mContentLeft;
    private int mContentTop;

    /**
     * The set of listeners to be sent events through.
     */
    private List<OnSwipeListener> mListeners;

    private Context mContext;

    public enum EdgeLevel {
        MAX, MIN, MED
    }

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

    public SwipeBackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init();
    }

    private void init() {
        mHelper = ViewDragHelper.create(this, new ViewDragCallback());
        setShadow( R.drawable.shadow_left, EDGE_LEFT);
        setEdgeOrientation(EDGE_LEFT);
    }

    /**
     * Set scroll threshold, we will close the activity, when scrollPercent over
     * this value
     *
     * @param threshold
     */
    public void setScrollThresHold(float threshold) {
        if (threshold >= 1.0f || threshold <= 0) {
            throw new IllegalArgumentException("Threshold value should be between 0 and 1.0");
        }
        mScrollFinishThreshold = threshold;
    }

    public void setParallaxOffset(float offset) {
        this.mParallaxOffset = offset;
    }

    /**
     * Enable edge tracking for the selected edges of the parent view.
     * The callback's {@link ViewDragHelper.Callback#onEdgeTouched(int, int)} and
     * {@link ViewDragHelper.Callback#onEdgeDragStarted(int, int)} methods will only be invoked
     * for edges for which edge tracking has been enabled.
     *
     * @param orientation Combination of edge flags describing the edges to watch
     * @see #EDGE_LEFT
     * @see #EDGE_RIGHT
     */
    public void setEdgeOrientation(@EdgeOrientation int orientation) {
        mEdgeFlag = orientation;
        mHelper.setEdgeTrackingEnabled(orientation);

        if (orientation == EDGE_RIGHT || orientation == EDGE_ALL) {
            setShadow( R.drawable.shadow_right, EDGE_RIGHT);
        }
    }

    @IntDef({EDGE_LEFT, EDGE_RIGHT, EDGE_ALL})
    @Retention(RetentionPolicy.SOURCE)
    public @interface EdgeOrientation {
    }

    /**
     * Set a drawable used for edge shadow.
     */
    public void setShadow(Drawable shadow, int edgeFlag) {
        if ((edgeFlag & EDGE_LEFT) != 0) {
            mShadowLeft = shadow;
        } else if ((edgeFlag & EDGE_RIGHT) != 0) {
            mShadowRight = shadow;
        }
        invalidate();
    }

    /**
     * Set a drawable used for edge shadow.
     */
    public void setShadow(int resId, int edgeFlag) {
        setShadow(getResources().getDrawable(resId), edgeFlag);
    }

    /**
     * Add a callback to be invoked when a swipe event is sent to this view.
     *
     * @param listener the swipe listener to attach to this view
     */
    public void addSwipeListener(OnSwipeListener listener) {
        if (mListeners == null) {
            mListeners = new ArrayList<>();
        }
        mListeners.add(listener);
    }

    /**
     * Removes a listener from the set of listeners
     *
     * @param listener
     */
    public void removeSwipeListener(OnSwipeListener listener) {
        if (mListeners == null) {
            return;
        }
        mListeners.remove(listener);
    }

    public interface OnSwipeListener {
        /**
         * Invoke when state change
         *
         * @param state flag to describe scroll state
         * @see #STATE_IDLE
         * @see #STATE_DRAGGING
         * @see #STATE_SETTLING
         */
        void onDragStateChange(int state);

        /**
         * Invoke when edge touched
         *
         * @param oritentationEdgeFlag edge flag describing the edge being touched
         * @see #EDGE_LEFT
         * @see #EDGE_RIGHT
         */
        void onEdgeTouch(int oritentationEdgeFlag);

        /**
         * Invoke when scroll percent over the threshold for the first time
         *
         * @param scrollPercent scroll percent of this view
         */
        void onDragScrolled(float scrollPercent);
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        boolean isDrawView = child == mContentView;
        boolean drawChild = super.drawChild(canvas, child, drawingTime);
        if (isDrawView && mScrimOpacity > 0 && mHelper.getViewDragState() != ViewDragHelper.STATE_IDLE) {
            drawShadow(canvas, child);
            drawScrim(canvas, child);
        }
        return drawChild;
    }

    private void drawShadow(Canvas canvas, View child) {
        final Rect childRect = mTmpRect;
        child.getHitRect(childRect);

        if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
            mShadowLeft.setBounds(childRect.left - mShadowLeft.getIntrinsicWidth(), childRect.top, childRect.left, childRect.bottom);
            mShadowLeft.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
            mShadowLeft.draw(canvas);
        } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
            mShadowRight.setBounds(childRect.right, childRect.top, childRect.right + mShadowRight.getIntrinsicWidth(), childRect.bottom);
            mShadowRight.setAlpha((int) (mScrimOpacity * FULL_ALPHA));
            mShadowRight.draw(canvas);
        }
    }

    private void drawScrim(Canvas canvas, View child) {
        final int baseAlpha = (DEFAULT_SCRIM_COLOR & 0xff000000) >>> 24;
        final int alpha = (int) (baseAlpha * mScrimOpacity);
        final int color = alpha << 24;

        if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
            canvas.clipRect(0, 0, child.getLeft(), getHeight());
        } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
            canvas.clipRect(child.getRight(), 0, getRight(), getHeight());
        }
        canvas.drawColor(color);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        mInLayout = true;
        if (mContentView != null) {
            mContentView.layout(mContentLeft, mContentTop,
                    mContentLeft + mContentView.getMeasuredWidth(),
                    mContentTop + mContentView.getMeasuredHeight());
        }
        mInLayout = false;
    }

    @Override
    public void requestLayout() {
        if (!mInLayout) {
            super.requestLayout();
        }
    }

    @Override
    public void computeScroll() {
        mScrimOpacity = 1 - mScrollPercent;
        if (mScrimOpacity >= 0) {
            if (mHelper.continueSettling(true)) {
                ViewCompat.postInvalidateOnAnimation(this);
            }

            if (mPreFragment != null && mPreFragment.getView() != null) {
                if (mCallOnDestroyView) {
                    mPreFragment.getView().setX(0);
                    return;
                }

                if (mHelper.getCapturedView() != null) {
                    int leftOffset = (int) ((mHelper.getCapturedView().getLeft() - getWidth()) * mParallaxOffset * mScrimOpacity);
                    mPreFragment.getView().setX(leftOffset > 0 ? 0 : leftOffset);
                }
            }
        }
    }

    /**
     * hide
     */
    public void internalCallOnDestroyView() {
        mCallOnDestroyView = true;
    }

    public void setFragment(final ISupportFragment fragment, View view) {
        this.mFragment = fragment;
        mContentView = view;
    }

    public void hiddenFragment() {
        if (mPreFragment != null && mPreFragment.getView() != null) {
            mPreFragment.getView().setVisibility(GONE);
        }
    }

    public void attachToActivity(FragmentActivity activity) {
        mActivity = activity;
        TypedArray a = activity.getTheme().obtainStyledAttributes(new int[]{
                android.R.attr.windowBackground
        });
        int background = a.getResourceId(0, 0);
        a.recycle();

        ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
        ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
        decorChild.setBackgroundResource(background);
        decor.removeView(decorChild);
        addView(decorChild);
        setContentView(decorChild);
        decor.addView(this);
    }

    public void attachToFragment(ISupportFragment fragment, View view) {
        addView(view);
        setFragment(fragment, view);
    }

    private void setContentView(View view) {
        mContentView = view;
    }

    public void setEnableGesture(boolean enable) {
        mEnable = enable;
    }

    public void setEdgeLevel(EdgeLevel edgeLevel) {
        validateEdgeLevel(-1, edgeLevel);
    }

    public void setEdgeLevel(int widthPixel) {
        validateEdgeLevel(widthPixel, null);
    }

    private void validateEdgeLevel(int widthPixel, EdgeLevel edgeLevel) {
        try {
            DisplayMetrics metrics = new DisplayMetrics();
            WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
            windowManager.getDefaultDisplay().getMetrics(metrics);
            Field mEdgeSize = mHelper.getClass().getDeclaredField("mEdgeSize");
            mEdgeSize.setAccessible(true);
            if (widthPixel >= 0) {
                mEdgeSize.setInt(mHelper, widthPixel);
            } else {
                if (edgeLevel == EdgeLevel.MAX) {
                    mEdgeSize.setInt(mHelper, metrics.widthPixels);
                } else if (edgeLevel == EdgeLevel.MED) {
                    mEdgeSize.setInt(mHelper, metrics.widthPixels / 2);
                } else {
                    mEdgeSize.setInt(mHelper, ((int) (20 * metrics.density + 0.5f)));
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private class ViewDragCallback extends ViewDragHelper.Callback {

        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            boolean dragEnable = mHelper.isEdgeTouched(mEdgeFlag, pointerId);
            if (dragEnable) {
                if (mHelper.isEdgeTouched(EDGE_LEFT, pointerId)) {
                    mCurrentSwipeOrientation = EDGE_LEFT;
                } else if (mHelper.isEdgeTouched(EDGE_RIGHT, pointerId)) {
                    mCurrentSwipeOrientation = EDGE_RIGHT;
                }

                if (mListeners != null && !mListeners.isEmpty()) {
                    for (OnSwipeListener listener : mListeners) {
                        listener.onEdgeTouch(mCurrentSwipeOrientation);
                    }
                }

                if (mPreFragment == null) {
                    if (mFragment != null) {
                        List<Fragment> fragmentList = FragmentationHack.getActiveFragments(((Fragment) mFragment).getFragmentManager());
                        if (fragmentList != null && fragmentList.size() > 1) {
                            int index = fragmentList.indexOf(mFragment);
                            for (int i = index - 1; i >= 0; i--) {
                                Fragment fragment = fragmentList.get(i);
                                if (fragment != null && fragment.getView() != null) {
                                    fragment.getView().setVisibility(VISIBLE);
                                    mPreFragment = fragment;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    View preView = mPreFragment.getView();
                    if (preView != null && preView.getVisibility() != VISIBLE) {
                        preView.setVisibility(VISIBLE);
                    }
                }
            }
            return dragEnable;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {
            int ret = 0;
            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                ret = Math.min(child.getWidth(), Math.max(left, 0));
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                ret = Math.min(0, Math.max(left, -child.getWidth()));
            }
            return ret;
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);

            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowLeft.getIntrinsicWidth()));
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                mScrollPercent = Math.abs((float) left / (mContentView.getWidth() + mShadowRight.getIntrinsicWidth()));
            }
            mContentLeft = left;
            mContentTop = top;
            invalidate();

            if (mListeners != null && !mListeners.isEmpty()
                    && mHelper.getViewDragState() == STATE_DRAGGING && mScrollPercent <= 1 && mScrollPercent > 0) {
                for (OnSwipeListener listener : mListeners) {
                    listener.onDragScrolled(mScrollPercent);
                }
            }

            if (mScrollPercent > 1) {
                if (mFragment != null) {
                    if (mCallOnDestroyView) return;

                    if (mPreFragment instanceof ISupportFragment) {
                        ((ISupportFragment) mPreFragment).getSupportDelegate().mLockAnim = true;
                    }
                    if (!((Fragment) mFragment).isDetached()) {
                        mFragment.getSupportDelegate().mLockAnim = true;
                        mFragment.getSupportDelegate().pop();
                        ((Fragment) mFragment).getFragmentManager().executePendingTransactions();
                        mFragment.getSupportDelegate().mLockAnim = false;
                    }
                    if (mPreFragment instanceof ISupportFragment) {
                        ((ISupportFragment) mPreFragment).getSupportDelegate().mLockAnim = false;
                    }
                } else {
                    if (!mActivity.isFinishing()) {
                        mActivity.finish();
                        mActivity.overridePendingTransition(0, 0);
                    }
                }
            }
        }

        @Override
        public int getViewHorizontalDragRange(View child) {
            if (mFragment != null) {
                return 1;
            }
            if (mActivity instanceof ISwipeBackActivity && ((ISwipeBackActivity) mActivity).swipeBackPriority()) {
                return 1;
            }
            return 0;
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            final int childWidth = releasedChild.getWidth();

            int left = 0, top = 0;
            if ((mCurrentSwipeOrientation & EDGE_LEFT) != 0) {
                left = xvel > 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? (childWidth
                        + mShadowLeft.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
            } else if ((mCurrentSwipeOrientation & EDGE_RIGHT) != 0) {
                left = xvel < 0 || xvel == 0 && mScrollPercent > mScrollFinishThreshold ? -(childWidth
                        + mShadowRight.getIntrinsicWidth() + OVERSCROLL_DISTANCE) : 0;
            }

            mHelper.settleCapturedViewAt(left, top);
            invalidate();
        }

        @Override
        public void onViewDragStateChanged(int state) {
            super.onViewDragStateChanged(state);
            if (mListeners != null && !mListeners.isEmpty()) {
                for (OnSwipeListener listener : mListeners) {
                    listener.onDragStateChange(state);
                }
            }
        }

        @Override
        public void onEdgeTouched(int edgeFlags, int pointerId) {
            super.onEdgeTouched(edgeFlags, pointerId);
            if ((mEdgeFlag & edgeFlags) != 0) {
                mCurrentSwipeOrientation = edgeFlags;
            }
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!mEnable) return super.onInterceptTouchEvent(ev);
        try {
            return mHelper.shouldInterceptTouchEvent(ev);
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mEnable) return super.onTouchEvent(event);
        try {
            mHelper.processTouchEvent(event);
            return true;
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return false;
    }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Localisation;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osuTK.Graphics;

namespace osu.Game.Overlays.Music
{
    public class PlaylistItem : OsuRearrangeableListItem<BeatmapSetInfo>, IFilterable
    {
        public readonly Bindable<BeatmapSetInfo> SelectedSet = new Bindable<BeatmapSetInfo>();

        public Action<BeatmapSetInfo> RequestSelection;

        private TextFlowContainer text;
        private ITextPart titlePart;

        [Resolved]
        private OsuColour colours { get; set; }

        public PlaylistItem(BeatmapSetInfo item)
            : base(item)
        {
            Padding = new MarginPadding { Left = 5 };

            FilterTerms = item.Metadata.GetSearchableTerms();
        }

        [BackgroundDependencyLoader]
        private void load()
        {
            HandleColour = colours.Gray5;
        }

        protected override void LoadComplete()
        {
            base.LoadComplete();

            SelectedSet.BindValueChanged(set =>
            {
                if (set.OldValue?.Equals(Model) != true && set.NewValue?.Equals(Model) != true)
                    return;

                updateSelectionState(false);
            }, true);
        }

        private void updateSelectionState(bool instant)
        {
            foreach (Drawable s in titlePart.Drawables)
                s.FadeColour(SelectedSet.Value?.Equals(Model) == true ? colours.Yellow : Color4.White, instant ? 0 : FADE_DURATION);
        }

        protected override Drawable CreateContent() => text = new OsuTextFlowContainer
        {
            RelativeSizeAxes = Axes.X,
            AutoSizeAxes = Axes.Y,
        };

        protected override void LoadAsyncComplete()
        {
            base.LoadAsyncComplete();

            var title = new RomanisableString(Model.Metadata.TitleUnicode, Model.Metadata.Title);
            var artist = new RomanisableString(Model.Metadata.ArtistUnicode, Model.Metadata.Artist);

            titlePart = text.AddText(title, sprite => sprite.Font = OsuFont.GetFont(weight: FontWeight.Regular));
            updateSelectionState(true);
            titlePart.DrawablePartsRecreated += _ => updateSelectionState(true);

            text.AddText(@"  "); // to separate the title from the artist.

            text.AddText(artist, sprite =>
            {
                sprite.Font = OsuFont.GetFont(size: 14, weight: FontWeight.Bold);
                sprite.Colour = colours.Gray9;
                sprite.Padding = new MarginPadding { Top = 1 };
            });
        }

        protected override bool OnClick(ClickEvent e)
        {
            RequestSelection?.Invoke(Model);
            return true;
        }

        private bool inSelectedCollection = true;

        public bool InSelectedCollection
        {
            get => inSelectedCollection;
            set
            {
                if (inSelectedCollection == value)
                    return;

                inSelectedCollection = value;
                updateFilter();
            }
        }

        public IEnumerable<string> FilterTerms { get; }

        private bool matchingFilter = true;

        public bool MatchingFilter
        {
            get => matchingFilter && inSelectedCollection;
            set
            {
                if (matchingFilter == value)
                    return;

                matchingFilter = value;
                updateFilter();
            }
        }

        private void updateFilter() => this.FadeTo(MatchingFilter ? 1 : 0, 200);

        public bool FilteringActive { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
include ../Makefile_cpp.in
PROG = memdb


text:
describe 'Connecting to remote host with SSH STDIN adapter',
         type: :integration do
  let(:context) do
    ::RemoteRuby::ExecutionContext.new(
      adapter: ::RemoteRuby::SSHStdinAdapter,
      server: ssh_host,
      user: ssh_user,
      key_file: ssh_key_file,
      working_dir: ssh_workdir
    )
  end

  context 'with do-blocks' do
    it 'succeeds and prints' do
      s = 'Something'

      expect do
        context.execute do
          puts s
        end
      end.to output(Regexp.new(s)).to_stdout
    end
  end

  context 'with {}-blocks' do
    it 'succeeds and prints' do
      s = 'Something'

      expect do
        context.execute { puts s }
      end.to output(Regexp.new(s)).to_stdout
    end
  end
end


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<meta name="description" content="Fallible can help protect your M&A and investments from cybersecurity risks."/>

    <title>Cybersecurity Due Diligence - Fallible</title>
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400" rel="stylesheet">

    <link rel="stylesheet" href="styles/main.css">

            <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar" aria-controls="exCollapsingNavbar" aria-expanded="false" aria-label="Toggle navigation">
                ☰
            </button>
            Fallible

                    PRODUCTS

                        Fallible Managed Security
                        Cybersecurity Due Diligence
                        Checksum Security Scanner
                        Portfolio Package

                    PRICING

                    BLOG

                    FAQ

                    Open dashboard

                <button class="navbar-toggler hidden-md-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar" aria-controls="exCollapsingNavbar" aria-expanded="false" aria-label="Toggle navigation">
                    ☰
                </button>

Pricing

Blog

FAQ

Due Diligence

Checksum Scanner

Managed Security

Portfolio Package

 Login

 Cybersecurity Due Diligence

We help you in assessing cyber risks for M&A, investments

Contact us

40% acquirers discovered cybersecurity issues post acquisition

Your acquisition target might have an ongoing breach you have not found out, have a history of cybersecurity issues or have compliance issues that might cost you heavily in the future. We help you discover all these issues before you go ahead with the acquisition.

How we work

We investigate and prepare reports for past security incidents, current security posture and any ongoing or undiscovered breaches in the target company.

We also investigate how resilient the target company is to certain types of attacks on their network and infrastructure including DDoS and data leaks.

                <form class="form-inline">
                    <input class="form-control form-control-lg" type="text" placeholder="Your primary domain">
                    Get Started
                </form>

                Privacy Policy
                Terms of Service
                Refund Policy
                Contact
                Join Us
                Blog

© 2016 Checksum Labs, Inc. All rights reserved.

    Questions? Feedback? powered by Olark live chat software


text:
[![Build Status](https://travis-ci.org/cangyan/redis-client-plus.svg?branch=master)](https://travis-ci.org/cangyan/redis-client-plus) [![Latest Stable Version](https://poser.pugx.org/cangyan/redis-client-plus/v/stable)](https://packagist.org/packages/cangyan/redis-client-plus) [![Total Downloads](https://poser.pugx.org/cangyan/redis-client-plus/downloads)](https://packagist.org/packages/cangyan/redis-client-plus) [![Latest Unstable Version](https://poser.pugx.org/cangyan/redis-client-plus/v/unstable)](https://packagist.org/packages/cangyan/redis-client-plus) [![License](https://poser.pugx.org/cangyan/redis-client-plus/license)](https://packagist.org/packages/cangyan/redis-client-plus)

# redis-client-plus
Redis增强客户端

# 功能列表
- 主从支持(操作走主,读取走从)

# 安装
- 待补充


text:
#include <iostream>
#include <regex>
#include <string>
#include <sstream>
#include <assert.h>
#include <memory>
#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
#include <utility>
#include "color_info.h"

static Color colorspec_to_color(std::string& colorSpec)
{
    assert(colorSpec.length() == 6);
    Color color;
    color.Red = stoi(colorSpec.substr(0, 2), NULL, /* hex */16);
    color.Blue = stoi(colorSpec.substr(2, 2), NULL, /* hex */16);
    color.Green = stoi(colorSpec.substr(4, 2), NULL, /* hex */16);
    return color;
}

std::string preprocess_xresources_file(const std::string &contents)
{
	std::istringstream iss(contents);

	// map with
	//   key is string containing identifier
	//   value is pair of compiled regex for matching the identifier and the replacement string
	// using a map instead of a vector of pairs allows for detection of collision among defines
	std::map<std::string, std::pair<std::regex, std::string>> replacements;
	const std::regex define_re(
		R"(^#define\s+([_a-zA-Z][_0-9a-zA-Z]*)\s+(.*))"
	);
	std::ostringstream oss;
	for (std::string line; std::getline(iss, line);)
	{
		std::smatch define_match;
		std::regex_match(line, define_match, define_re);
		if (define_match.size() == 3)
		{
			std::string identifier = define_match[1].str();
			if (replacements.find(identifier) == replacements.end())
			{
				replacements[identifier] = std::make_pair(std::regex(identifier), define_match[2].str());
			}
			else
			{
				std::cerr << "warning: multiple defines for " << identifier << std::endl;
			}
			oss << line << std::endl;
		}
		else
		{
			if (!line.empty())
			{
				// lazy replacement algorithm
				for (auto &p : replacements)
				{
					line = std::regex_replace(line, p.second.first, p.second.second);
				}
			}
			oss << line << std::endl;
		}
	}

	return oss.str();
}

ColorInfo parse_xresources_file(const std::string &contents)
{
    std::stringstream xres(contents, std::stringstream::ios_base::in);
    ColorInfo colorInfo = ColorInfo();
    for (std::string line; std::getline(xres, line);)
    {
        if (line.empty())
        {
            continue;
        }

        const std::regex colorLine(
            R"((?:rxvt|term|^\s*|^\s*\*))" // Optional term specifier
            R"((?:\*|\.)?)" // Separator
            R"((foreground|background|color\d{1,2})\s*:\s*)" // Color id
            R"(#([a-f0-9]{6}))", // Color specifier
            std::regex_constants::icase);

        std::smatch matchResult;
        if (!std::regex_search(line, matchResult, colorLine))
        {
            continue;
        }

        auto iter = matchResult.begin();
        iter++;
        auto colorId = iter->str();
        iter++;
        Color color = colorspec_to_color(iter->str());

        if (colorId == "foreground")
        {
            colorInfo.ForegroundColor = color;
        }
        else if (colorId == "background")
        {
            colorInfo.BackgroundColor = color;
        }
        else
        {
            const size_t colorlen = sizeof("color") - 1;
            auto colorNumber = stoi(colorId.substr(colorlen, colorId.length() - colorlen));

            switch (colorNumber)
            {
            case 0:
                colorInfo.Black = color;
                break;
            case 1:
                colorInfo.Red = color;
                break;
            case 2:
                colorInfo.Green = color;
                break;
            case 3:
                colorInfo.Yellow = color;
                break;
            case 4:
                colorInfo.Blue = color;
                break;
            case 5:
                colorInfo.Magenta = color;
                break;
            case 6:
                colorInfo.Cyan = color;
                break;
            case 7:
                colorInfo.White = color;
                break;
            case 8:
                colorInfo.BrightBlack = color;
                break;
            case 9:
                colorInfo.BrightRed = color;
                break;
            case 10:
                colorInfo.BrightGreen = color;
                break;
            case 11:
                colorInfo.BrightYellow = color;
                break;
            case 12:
                colorInfo.BrightBlue = color;
                break;
            case 13:
                colorInfo.BrightMagenta = color;
                break;
            case 14:
                colorInfo.BrightCyan = color;
                break;
            case 15:
                colorInfo.BrightWhite = color;
                break;
            default:
                std::cerr << "Color id specified in '" << line << "' is invalid. Skipping..." << std::endl;
                break;
            }
        }
    }

    return colorInfo;
}


text:
$(document).ready(function (e) {
    $('#voucher-btn').click(function(event)
    {
        event.preventDefault();
        reloadBillPersonData('#voucher-wrapper',0,false);
    });

    $('#bp-submit-modal').click(function(event)
    {
        event.preventDefault();
        reloadBillPersonData('#bill-grid-wrapper',1,true);
    });

    $('#cancel-bp-submit-modal').click(function(event)
    {
        event.preventDefault();
        $.pjax.reload({container:'#bill-grid-wrapper'});
    });

    $('#voucher-wrapper').on('pjax:success', function(data, status, xhr, options)
    {
        $('#modal-voucher').modal('show');
    });

    $('#bill-grid-wrapper').on('pjax:success', function(data, status, xhr, options)
    {
        $('#modal-voucher').modal('hide');
    });

    $('#voucher-wrapper, #bill-grid-wrapper').on('pjax:error', function(xhr, textStatus, error, options)
    {
        $('#error-modal .modal-body').html(textStatus + ", " + errorThrown);
        $('#error-modal').modal('show');
    });
});

function reloadBillPersonData(wrapper,mode,openAfter)
{
    var keys = $("#bill-grid").yiiGridView('getSelectedRows');

    $.pjax.reload({
        container:wrapper,
        type: 'POST',data:{selected:keys,mode: mode},
        replace: false
    });

    if(openAfter)
        window.open("print?p="+$('#person-id').val()+"&s="+keys);
}


text:
ScalaJS.impls.scala_Function1$mcJI$sp$class__$init$__Lscala_Function1$mcJI$sp__V = (function($$this) {
  /*<skip>*/
});
//@ sourceMappingURL=Function1$mcJI$sp$class.js.map


text:
var gulp = require('gulp');
var path = require('path');
var KarmaServer = require('karma').Server;

var karmaConf = path.join(__dirname, '../karma.conf.js'); // was getting confused with relative URLs

// runs a server, outputs a URL to visit.
// we want sourcemaps (modules:dev).
gulp.task('test', [ 'modules:dev', 'locale' ], function(done) {
	new KarmaServer({
		configFile: karmaConf,
		singleRun: false,
		autoWatch: true
	}, function(exitCode) { // plays best with developing from command line
		process.exit(exitCode);
	}).start();
});

// runs headlessly and continuously, watching files
gulp.task('test:headless', [ 'modules', 'locale' ], function(done) {
	new KarmaServer({
		configFile: karmaConf,
		browsers: [ 'PhantomJS_custom' ],
		singleRun: false,
		autoWatch: true
	}, function(exitCode) { // plays best with developing from command line
		process.exit(exitCode);
	}).start();
});

// runs headlessly once, then exits
gulp.task('test:single', [ 'modules', 'locale' ], function(done) {
	new KarmaServer({
		configFile: karmaConf,
		browsers: [ 'PhantomJS_custom' ],
		singleRun: true,
		autoWatch: false
	}).on('run_complete', function(browsers, results) { // plays best with CI and other tasks
		done(results.exitCode);
	}).start();
});


text:
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

import monsters from './monsters';
import filters from './filters';
import encounter from './encounter';
import ga from './ga';
import data from '../data/monsters';

const rootReducer = combineReducers({monsters, filters, encounter, data, ga, routing: routerReducer});

export default rootReducer;


text:
slice
=====

Doctrine2 ORM Search tool - get a slice of results by applying filters.

The primary usage of this library is to create pageable searchable front-facing interfaces, by combining it with a tool
to parse URLs into filters to apply to searches.

The initial problem that was solved by this library was very slow counting for InnoDB databases when using Doctrine's Pager class and complex joined filtering.

This library solves that problem by removing the DQL from the interface, which allows for managing the construction of multiple efficient queries.  This in turn allows for
reliable counting and paging for one-to-many and many-to-many joins.

Those searches can then be used to create aggregated reports.

Usage
-----

```php

	//Assume we have 2 classes
	namespace Acme\Demo\DemoBundle;

	class Contact {

		protected $id;

		protected $name;

		//one-to-many
		protected $addresses
	}

	class Address {

		protected $street;

		protected $zip;
	}

	$em = ...; \\Get entity manager

	use Slice\Search\Search;
	$search = new Search($em, 'AcmeDemoBundle:Contact'); //or 'Acme\Demo\DemoBundle' - full name

	//Only get contacts with addresses 00211 zip code.
	$search->addFilter(new EqualFilter('addresses.zip', '00211'));

	//order Contacts by their Address.street alphabetically ascending.
	$search->addFilter(new OrderByFilter('addresses.street', 'ASC'));

	//get first 10 results
	$search->addFilter(new PagingFilter(0, 10));

	$results = $search->getResults();

	$totalResults = $search->getTotalResultCount();

	echo "$totalResults records were found.\n";

	foreach($results as $contact) {
		$addresses = $contact->getAddresses();

		print $contact->getName() . "\n";
		foreach($addresses as $address) {
			print "\t" . $address->getStreet() ."\n";
		}
	}

	// output paging links to allow various paging filters to be applied.

```

Output would be something like this..
```
Joe Josephson
	111 Address Place.
James Jameson
	1234 Place St.
	555 Five St.

...
(10th result)
Dan Danson
	94 ABC St.

```

LogicalFilter (AndFilter, OrFilter) allow for grouping filters together into complex logic.

DistanceCriteriaFilter and DistanceSortFilter allow for distance searches against particular latitude/longitudes.

Multiple OrderByFilter instances can be added to a given search, but only 1 PagingFilter is used (the last given).

Finally - ResultSetBuilderInterface objects allow for a particular result to be built instead of the default Entity result set.

The FormulaFilter allows for complicated queries that aren't easily (or conveniently) expressed otherwise - however it is not safe to be exposed to the client via any web interface.
It can be used to limit the initial result set in interesting ways.

Example:
```php

//using search above.
$resultBuilder = new FlatResultBuilder();
$resultBuilder->addSelect('name', 'alias');

$results = $search->getResults($resultBuilder);
// returns array(0 => array('alias' => 'Joe Josephson'), 1 => array('alias' => 'James Jameson'), 2 => array('alias' => 'Dan Danson') )

```


text:
class Stack<T>
{
	public void Hello (int a, params T[] args)
	{ }
}

class X
{
	public static void Main ()
	{
		Stack<string> stack = new Stack<string> ();
		stack.Hello (1, "Hello", "World");
	}
}


text:
var menuState = {

    create: function(){
        var background = game.add.sprite(0, 0, 'floresta');
        background.width = 1300;
        background.height = 650;

        var logo = game.add.sprite(background.width-700, background.height-650, 'logoGame');
        logo.width = 628;
        logo.height = 511;

        //  Standard button (also used as our pointer tracker)
        botaoStart = game.add.button(250, 195, 'botaoStart', this.start, this, 2, 1, 0);
        botaoStart.name = 'start';
        botaoStart.width = 275;
        botaoStart.height = 55;
        var btnStartLabel = game.add.text(300, 205, 'Iniciar Jogo',
                                     {font: '30px Verdana', fill: '#ffffff'});

        //  Standard button (also used as our pointer tracker)
        botaoCadastrar = game.add.button(175, 295, 'botaoCadastrar', null, this, 2, 1, 0);
        botaoCadastrar.name = 'start';
        botaoCadastrar.width = 300;
        botaoCadastrar.height = 55;
        var btnCadastrarLabel = game.add.text(186, 305, 'Cadastrar Jogador',
                                     {font: '30px Verdana', fill: '#ffffff'});

       //  Standard button (also used as our pointer tracker)
        botaoAcompanhamento = game.add.button(250, 395, 'botaoAcompanhamento', null, this, 2, 1, 0);
        botaoAcompanhamento.name = 'start';
        botaoAcompanhamento.width = 300;
        botaoAcompanhamento.height = 55;
        var btnAcompanhamentoLabel = game.add.text(264, 405, 'Acompanhamento',
                                     {font: '30px Verdana', fill: '#ffffff'});
    },

    start: function(){
        game.state.start('play');
    },

};


text:
<?php
// This class was automatically generated by a giiant build task
// You should not change it manually as it will be overwritten on next build

namespace common\models\base;

use Yii;

/**
 * This is the base-model class for table "device_device_group".
 *
 * @property integer $id
 * @property integer $device_group_id
 * @property integer $device_id
 * @property string $created_at
 * @property string $updated_at
 * @property integer $created_by
 * @property integer $updated_by
 *
 * @property \common\models\DeviceGroup $deviceGroup
 * @property \common\models\Device $device
 */
abstract class DeviceDeviceGroup extends \yii\db\ActiveRecord
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'device_device_group';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['device_group_id', 'device_id'], 'required'],
            [['device_group_id', 'device_id', 'created_by', 'updated_by'], 'integer'],
            [['created_at', 'updated_at'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('gip', 'ID'),
            'device_group_id' => Yii::t('gip', 'Device Group'),
            'device_id' => Yii::t('gip', 'Device'),
            'created_at' => Yii::t('gip', 'Created At'),
            'updated_at' => Yii::t('gip', 'Updated At'),
            'created_by' => Yii::t('gip', 'Created By'),
            'updated_by' => Yii::t('gip', 'Updated By'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDeviceGroup()
    {
        return $this->hasOne(\common\models\DeviceGroup::className(), ['id' => 'device_group_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDevice()
    {
        return $this->hasOne(\common\models\Device::className(), ['id' => 'device_id']);
    }

}


text:
<?php

namespace Mobishop\Http\Controllers;

use Validator;
use Illuminate\Http\Request;
use Mobishop\Carts\Helper as CartHelper;
use Gloudemans\Shoppingcart\Facades\Cart;

class CartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('cart.index');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $search = Cart::search(function ($cartItem, $rowId) use ($request) {
            return $cartItem->id === $request->input('id') &&
                $cartItem->options->type === $request->get('attributes')['type'];
        });

        if ($search->count()) {
            return redirect('carts')->withSuccessMessage('Item is already in your cart!');
        }

        $attributes = $request->get('attributes');

        CartHelper::add($request->all());

        return redirect('carts')->withSuccessMessage('Item was added to your cart!');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Validation on max quantity
        $validator = Validator::make($request->all(), [
            'quantity' => 'required|numeric|between:1,5'
        ]);

        if ($validator->fails()) {
            session()->flash('error_message', 'Quantity must be between 1 and 5.');
            return response()->json(['success' => false]);
        }

        Cart::update($id, $request->quantity);
        session()->flash('success_message', 'Quantity was updated successfully!');

        return response()->json(['success' => true]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Cart::remove($id);
        return redirect('carts')->withSuccessMessage('Item has been removed!');
    }

    /**
     * Remove the resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function emptyCart()
    {
        Cart::destroy();
        return redirect('carts')->withSuccessMessage('Your cart his been cleared!');
    }
}


text:
var dir = __dirname+'/data'

var normalize = require('normalize-registry-metadata')
var ccf = require('concurrent-couch-follower')
var makeDiffer = require('./')
var differ = makeDiffer({dir:dir})

var fs = require('fs')
var ws = fs.createWriteStream(__dirname+'/example.log',{flags:'a+'})

ccf(function(change,done){
  change.doc = normalize(change.doc)
  if(!change.doc) {
    return done()
  }

  differ(change, function(err, report) {
    if(err) throw err;
    var oreport = {name:change.doc.name,sequence:change.sequence,diff:report}
    var report = JSON.stringify(oreport)

    console.log(JSON.stringify(oreport,null,'  '))
    ws.write(report+'\n')

    done()
  })

},{
  db:'https://skimdb.npmjs.com/registry',
  include_docs:true,
  sequence:'.example-sequence',
  include_docs:true,
  concurrency:5
})


text:
#include "source/common/common/fine_grain_logger.h"

#include <atomic>
#include <memory>
#include <tuple>

#include "source/common/common/logger.h"

#include "absl/strings/str_join.h"

using spdlog::level::level_enum;

namespace Envoy {

/**
 * Implements a lock from BasicLockable, to avoid dependency problem of thread.h.
 */
class FineGrainLogBasicLockable : public Thread::BasicLockable {
public:
  // BasicLockable
  void lock() ABSL_EXCLUSIVE_LOCK_FUNCTION() override { mutex_.Lock(); }
  bool tryLock() ABSL_EXCLUSIVE_TRYLOCK_FUNCTION(true) override { return mutex_.TryLock(); }
  void unlock() ABSL_UNLOCK_FUNCTION() override { mutex_.Unlock(); }

private:
  absl::Mutex mutex_;
};

SpdLoggerSharedPtr FineGrainLogContext::getFineGrainLogEntry(absl::string_view key)
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  auto it = fine_grain_log_map_->find(key);
  if (it != fine_grain_log_map_->end()) {
    return it->second;
  }
  return nullptr;
}

spdlog::level::level_enum FineGrainLogContext::getVerbosityDefaultLevel() const {
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  return verbosity_default_level_;
}

void FineGrainLogContext::initFineGrainLogger(const std::string& key,
                                              std::atomic<spdlog::logger*>& logger)
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  absl::WriterMutexLock l(&fine_grain_log_lock_);
  auto it = fine_grain_log_map_->find(key);
  spdlog::logger* target;
  if (it == fine_grain_log_map_->end()) {
    target = createLogger(key);
  } else {
    target = it->second.get();
  }
  logger.store(target);
}

bool FineGrainLogContext::setFineGrainLogger(absl::string_view key, level_enum log_level)
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  auto it = fine_grain_log_map_->find(key);
  if (it != fine_grain_log_map_->end()) {
    it->second->set_level(log_level);
    return true;
  }
  return false;
}

void FineGrainLogContext::setDefaultFineGrainLogLevelFormat(spdlog::level::level_enum level,
                                                            const std::string& format)
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  {
    absl::WriterMutexLock wl(&fine_grain_log_lock_);
    verbosity_default_level_ = level;
  }

  absl::ReaderMutexLock rl(&fine_grain_log_lock_);
  for (const auto& [key, logger] : *fine_grain_log_map_) {
    logger->set_level(getLogLevel(key));
    Logger::Utility::setLogFormatForLogger(*logger, format);
  }
}

std::string FineGrainLogContext::listFineGrainLoggers() ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  std::string info =
      absl::StrJoin(*fine_grain_log_map_, "\n", [](std::string* out, const auto& log_pair) {
        absl::StrAppend(out, "  ", log_pair.first, ": ", log_pair.second->level());
      });
  return info;
}

void FineGrainLogContext::setAllFineGrainLoggers(spdlog::level::level_enum level)
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  if (verbosity_update_info_.empty()) {
    for (const auto& it : *fine_grain_log_map_) {
      it.second->set_level(level);
    }
  } else {
    for (const auto& [key, logger] : *fine_grain_log_map_) {
      logger->set_level(getLogLevel(key));
    }
  }
}

FineGrainLogLevelMap FineGrainLogContext::getAllFineGrainLogLevelsForTest()
    ABSL_LOCKS_EXCLUDED(fine_grain_log_lock_) {
  FineGrainLogLevelMap log_levels;
  absl::ReaderMutexLock l(&fine_grain_log_lock_);
  for (const auto& it : *fine_grain_log_map_) {
    log_levels[it.first] = it.second->level();
  }
  return log_levels;
}

bool FineGrainLogContext::safeFileNameMatch(absl::string_view pattern, absl::string_view str) {
  while (true) {
    if (pattern.empty()) {
      // `pattern` is exhausted; succeed if all of `str` was consumed matching it.
      return str.empty();
    }
    if (str.empty()) {
      // `str` is exhausted; succeed if `pattern` is empty or all '*'s.
      return pattern.find_first_not_of('*') == pattern.npos;
    }
    if (pattern.front() == '*') {
      pattern.remove_prefix(1);
      if (pattern.empty()) {
        return true;
      }
      do {
        if (safeFileNameMatch(pattern, str)) {
          return true;
        }
        str.remove_prefix(1);
      } while (!str.empty());
      return false;
    }
    if (pattern.front() == '?' || pattern.front() == str.front()) {
      pattern.remove_prefix(1);
      str.remove_prefix(1);
      continue;
    }
    return false;
  }
}

void FineGrainLogContext::initSink() {
  spdlog::sink_ptr sink = Logger::Registry::getSink();
  Logger::DelegatingLogSinkSharedPtr sp = std::static_pointer_cast<Logger::DelegatingLogSink>(sink);
  if (!sp->hasLock()) {
    static FineGrainLogBasicLockable tlock;
    sp->setLock(tlock);
    sp->setShouldEscape(false);
  }
}

spdlog::logger* FineGrainLogContext::createLogger(const std::string& key)
    ABSL_EXCLUSIVE_LOCKS_REQUIRED(fine_grain_log_lock_) {
  SpdLoggerSharedPtr new_logger =
      std::make_shared<spdlog::logger>(key, Logger::Registry::getSink());
  if (!Logger::Registry::getSink()->hasLock()) { // occurs in benchmark test
    initSink();
  }

  new_logger->set_level(getLogLevel(key));
  Logger::Utility::setLogFormatForLogger(*new_logger, Logger::Context::getFineGrainLogFormat());
  new_logger->flush_on(level_enum::critical);
  fine_grain_log_map_->insert(std::make_pair(key, new_logger));
  return new_logger.get();
}

void FineGrainLogContext::updateVerbosityDefaultLevel(level_enum level) {
  {
    absl::WriterMutexLock wl(&fine_grain_log_lock_);
    if (level == verbosity_default_level_) {
      return;
    }
    verbosity_default_level_ = level;
  }

  setAllFineGrainLoggers(level);
}

void FineGrainLogContext::updateVerbositySetting(
    const std::vector<std::pair<absl::string_view, int>>& updates) {
  absl::WriterMutexLock ul(&fine_grain_log_lock_);
  verbosity_update_info_.clear();
  for (const auto& [glob, level] : updates) {
    if (level < kLogLevelMin || level > kLogLevelMax) {
      printf(
          "The log level: %d for glob: %s is out of scope, and it should be in [0, 6]. Skipping.",
          level, std::string(glob).c_str());
      continue;
    }
    appendVerbosityLogUpdate(glob, static_cast<level_enum>(level));
  }

  for (const auto& [key, logger] : *fine_grain_log_map_) {
    logger->set_level(getLogLevel(key));
  }
}

void FineGrainLogContext::appendVerbosityLogUpdate(absl::string_view update_pattern,
                                                   level_enum log_level) {
  for (const auto& info : verbosity_update_info_) {
    if (safeFileNameMatch(info.update_pattern, update_pattern)) {
      // This is a memory optimization to avoid storing patterns that will never
      // match due to exit early semantics.
      return;
    }
  }
  bool update_is_path = update_pattern.find('/') != update_pattern.npos;
  verbosity_update_info_.emplace_back(std::string(update_pattern), update_is_path, log_level);
}

level_enum FineGrainLogContext::getLogLevel(absl::string_view file) const {
  if (verbosity_update_info_.empty()) {
    return verbosity_default_level_;
  }

  // Get basename for file.
  absl::string_view basename = file;
  {
    const size_t sep = basename.rfind('/');
    if (sep != basename.npos) {
      basename.remove_prefix(sep + 1);
    }
  }

  absl::string_view stem = file, stem_basename = basename;
  {
    const size_t sep = stem_basename.find('.');
    if (sep != stem_basename.npos) {
      stem.remove_suffix(stem_basename.size() - sep);
      stem_basename.remove_suffix(stem_basename.size() - sep);
    }
  }
  for (const auto& info : verbosity_update_info_) {
    if (info.update_is_path) {
      // If there are any slashes in the pattern, try to match the full path name.
      if (safeFileNameMatch(info.update_pattern, stem)) {
        return info.log_level;
      }
    } else if (safeFileNameMatch(info.update_pattern, stem_basename)) {
      return info.log_level;
    }
  }

  return verbosity_default_level_;
}

FineGrainLogContext& getFineGrainLogContext() {
  MUTABLE_CONSTRUCT_ON_FIRST_USE(FineGrainLogContext);
}

} // namespace Envoy


text:
package eu.hyvar.feature.constraint.resource.hyconstraints.ui;

import org.eclipse.jface.action.IAction;

public class HyconstraintsOutlinePageAutoExpandAction extends eu.hyvar.feature.constraint.resource.hyconstraints.ui.AbstractHyconstraintsOutlinePageAction {

	public HyconstraintsOutlinePageAutoExpandAction(eu.hyvar.feature.constraint.resource.hyconstraints.ui.HyconstraintsOutlinePageTreeViewer treeViewer) {
		super(treeViewer, "Auto expand", IAction.AS_CHECK_BOX);
		initialize("icons/auto_expand_icon.gif");
	}

	public void runInternal(boolean on) {
		getTreeViewer().setAutoExpand(on);
		getTreeViewer().refresh();
	}

}


text:
(function (factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(["require", "exports", '@angular/core'], factory);
    }
})(function (require, exports) {
    "use strict";
    var core_1 = require('@angular/core');
    var Avatar = (function () {
        function Avatar() {
        }
        Avatar.decorators = [
            { type: core_1.Directive, args: [{
                        selector: 'ion-avatar'
                    },] },
        ];
        Avatar.ctorParameters = [];
        return Avatar;
    }());
    exports.Avatar = Avatar;
});
//# sourceMappingURL=avatar.js.map


text:
/**
 *
 */
package org.minnal.utils;

import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.LogChute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ganeshs
 *
 * FIXME: Replace this with org.apache.velocity.slf4j.Slf4jLogChute when velocity 2.0 is available
 */
public class Slf4jLogChute implements LogChute
{

    /** Property key for specifying the name for the log instance */
    public static final String LOGCHUTE_SLF4J_NAME =
        "runtime.log.logsystem.slf4j.name";

    /** Default name for the commons-logging instance */
    public static final String DEFAULT_LOG_NAME = "org.apache.velocity";

    /** the commons-logging Log instance */
    protected Logger log;

    /********** LogChute methods *************/

    public void init(RuntimeServices rs)
    {
        String name =
            (String)rs.getProperty(LOGCHUTE_SLF4J_NAME);

        if (name == null)
        {
            name = DEFAULT_LOG_NAME;
        }
        log = LoggerFactory.getLogger(name);
        log(LogChute.DEBUG_ID, "Slf4jLogChute name is '" + name + "'");
    }

    /**
     * Send a log message from Velocity.
     */
    public void log(int level, String message)
    {
        switch (level)
        {
            case LogChute.WARN_ID:
                log.warn(message);
                break;
            case LogChute.INFO_ID:
                log.info(message);
                break;
            case LogChute.TRACE_ID:
                log.trace(message);
                break;
            case LogChute.ERROR_ID:
                log.error(message);
                break;
            case LogChute.DEBUG_ID:
            default:
                log.debug(message);
                break;
        }
    }

    /**
     * Send a log message from Velocity with an error.
     */
    public void log(int level, String message, Throwable t)
    {
        switch (level)
        {
            case LogChute.WARN_ID:
                log.warn(message, t);
                break;
            case LogChute.INFO_ID:
                log.info(message, t);
                break;
            case LogChute.TRACE_ID:
                log.trace(message, t);
                break;
            case LogChute.ERROR_ID:
                log.error(message, t);
                break;
            case LogChute.DEBUG_ID:
            default:
                log.debug(message, t);
                break;
        }
    }

    /**
     * Checks whether the specified log level is enabled.
     */
    public boolean isLevelEnabled(int level)
    {
        switch (level)
        {
            case LogChute.DEBUG_ID:
                return log.isDebugEnabled();
            case LogChute.INFO_ID:
                return log.isInfoEnabled();
            case LogChute.TRACE_ID:
                return log.isTraceEnabled();
            case LogChute.WARN_ID:
                return log.isWarnEnabled();
            case LogChute.ERROR_ID:
                return log.isErrorEnabled();
            default:
                return true;
        }
    }
}


text:
/*************************************************************************************************/

#ifndef BOOST_GIL_EXTENSION_IO_TARGA_SUPPORTED_TYPES_HPP
#define BOOST_GIL_EXTENSION_IO_TARGA_SUPPORTED_TYPES_HPP

////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief
/// \author Kenneth Riddile \n
///
/// \date   2010 \n
///
////////////////////////////////////////////////////////////////////////////////////////

#include <boost/mpl/not.hpp>
#include <boost/type_traits/is_same.hpp>

#include <boost/gil/channel.hpp>
#include <boost/gil/color_base.hpp>

#include <boost/gil/extension/io/detail/base.hpp>

namespace boost { namespace gil { namespace detail {

// Read support

template< typename Channel
        , typename ColorSpace
        >
struct targa_read_support : read_support_false
{
    static const targa_depth::type bpp = 0;
};

template<>
struct targa_read_support< bits8
                         , rgb_t
                         > : read_support_true
{
    static const targa_depth::type bpp = 24;
};

template<>
struct targa_read_support< bits8
                         , rgba_t
                         > : read_support_true
{
    static const targa_depth::type bpp = 32;
};

// Write support

template< typename Channel
        , typename ColorSpace
        >
struct targa_write_support : write_support_false
{};

template<>
struct targa_write_support< bits8
                          , rgb_t
                          > : write_support_true {};

template<>
struct targa_write_support< bits8
                          , rgba_t
                          > : write_support_true {};

} // namespace detail

template< typename Pixel >
struct is_read_supported< Pixel
                        , targa_tag
                        >
    : mpl::bool_< detail::targa_read_support< typename channel_type< Pixel >::type
                                            , typename color_space_type< Pixel >::type
                                            >::is_supported
                >
{
    typedef detail::targa_read_support< typename channel_type< Pixel >::type
                                      , typename color_space_type< Pixel >::type
                                      > parent_t;

    static const typename targa_depth::type bpp = parent_t::bpp;
};

template< typename Pixel >
struct is_write_supported< Pixel
                         , targa_tag
                         >
    : mpl::bool_< detail::targa_write_support< typename channel_type< Pixel >::type
                                             , typename color_space_type< Pixel >::type
                                             >::is_supported
                > {};

} // namespace gil
} // namespace boost

#endif // BOOST_GIL_EXTENSION_IO_TARGA_SUPPORTED_TYPES_HPP


text:
#region Foreign-License
// .Net40 Polyfill
#endregion
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Reflection;
namespace System.Net
{
    [FriendAccessAllowed]
    internal class Logging
    {
        #region internal
        private static _MethodInfo _headerEncodingInfo = Type.GetType("System.Net.WebHeaderCollection+HeaderEncoding").GetMethod("GetString", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(byte[]), typeof(int), typeof(int) }, null);
        [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true, ExactSpelling = true)]
        internal static extern uint GetCurrentThreadId();
        #endregion
        private const string AttributeNameMaxSize = "maxdatasize";
        private const string AttributeNameTraceMode = "tracemode";
        private const string AttributeValueProtocolOnly = "protocolonly";
        private const int DefaultMaxDumpSize = 0x400;
        private const bool DefaultUseProtocolTextOnly = false;
        private static volatile bool s_AppDomainShutdown;
        private static TraceSource s_CacheTraceSource;
        private static TraceSource s_HttpListenerTraceSource;
        private static object s_InternalSyncObject;
        private static volatile bool s_LoggingEnabled = true;
        private static volatile bool s_LoggingInitialized;
        private static TraceSource s_SocketsTraceSource;
        private static TraceSource s_TraceSourceHttpName;
        private static TraceSource s_WebSocketsTraceSource;
        private static TraceSource s_WebTraceSource;
        private static readonly string[] SupportedAttributes = new string[] { "maxdatasize", "tracemode" };
        private const string TraceSourceCacheName = "System.Net.Cache";
        private const string TraceSourceHttpListenerName = "System.Net.HttpListener";
        private const string TraceSourceHttpName = "System.Net.Http";
        private const string TraceSourceSocketsName = "System.Net.Sockets";
        private const string TraceSourceWebName = "System.Net";
        private const string TraceSourceWebSocketsName = "System.Net.WebSockets";

        private Logging() { }

        private static void AppDomainUnloadEvent(object sender, EventArgs e)
        {
            Close();
            s_AppDomainShutdown = true;
        }

        [FriendAccessAllowed]
        internal static void Associate(TraceSource traceSource, object objA, object objB)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Information, 0, "Associating " + (GetObjectName(objA) + "#" + ValidationHelper.HashString(objA)) + " with " + (GetObjectName(objB) + "#" + ValidationHelper.HashString(objB)));
        }

        private static void Close()
        {
            if (s_WebTraceSource != null)
                s_WebTraceSource.Close();
            if (s_HttpListenerTraceSource != null)
                s_HttpListenerTraceSource.Close();
            if (s_SocketsTraceSource != null)
                s_SocketsTraceSource.Close();
            if (s_WebSocketsTraceSource != null)
                s_WebSocketsTraceSource.Close();
            if (s_CacheTraceSource != null)
                s_CacheTraceSource.Close();
            if (s_TraceSourceHttpName != null)
                s_TraceSourceHttpName.Close();
        }

        internal static void Dump(TraceSource traceSource, object obj, string method, IntPtr bufferPtr, int length)
        {
            if ((ValidateSettings(traceSource, TraceEventType.Verbose) && (bufferPtr != IntPtr.Zero)) && (length >= 0))
            {
                byte[] destination = new byte[length];
                Marshal.Copy(bufferPtr, destination, 0, length);
                Dump(traceSource, obj, method, destination, 0, length);
            }
        }

        internal static void Dump(TraceSource traceSource, object obj, string method, byte[] buffer, int offset, int length)
        {
            if (ValidateSettings(traceSource, TraceEventType.Verbose))
                if (buffer == null)
                    PrintLine(traceSource, TraceEventType.Verbose, 0, "(null)");
                else if (offset > buffer.Length)
                    PrintLine(traceSource, TraceEventType.Verbose, 0, "(offset out of range)");
                else
                {
                    PrintLine(traceSource, TraceEventType.Verbose, 0, "Data from " + GetObjectName(obj) + "#" + ValidationHelper.HashString(obj) + "::" + method);
                    var maxDumpSizeSetting = GetMaxDumpSizeSetting(traceSource);
                    if (length > maxDumpSizeSetting)
                    {
                        PrintLine(traceSource, TraceEventType.Verbose, 0, "(printing " + maxDumpSizeSetting.ToString(NumberFormatInfo.InvariantInfo) + " out of " + length.ToString(NumberFormatInfo.InvariantInfo) + ")");
                        length = maxDumpSizeSetting;
                    }
                    if (length < 0 || length > (buffer.Length - offset))
                        length = buffer.Length - offset;
                    if (GetUseProtocolTextSetting(traceSource))
                    {
                        var msg = "<<" + (string)_headerEncodingInfo.Invoke(null, new object[] { buffer, offset, length }) + ">>";
                        PrintLine(traceSource, TraceEventType.Verbose, 0, msg);
                    }
                    else
                    {
                        do
                        {
                            var num2 = Math.Min(length, 0x10);
                            var str2 = string.Format(CultureInfo.CurrentCulture, "{0:X8} : ", new object[] { offset });
                            for (int i = 0; i < num2; i++)
                                str2 = str2 + string.Format(CultureInfo.CurrentCulture, "{0:X2}", new object[] { buffer[offset + i] }) + ((i == 7) ? '-' : ' ');
                            for (int j = num2; j < 0x10; j++)
                                str2 = str2 + "   ";
                            str2 = str2 + ": ";
                            for (int k = 0; k < num2; k++)
                                str2 = str2 + ((buffer[offset + k] < 0x20 || buffer[offset + k] > 0x7e ? '.' : ((char)buffer[offset + k])));
                            PrintLine(traceSource, TraceEventType.Verbose, 0, str2);
                            offset += num2;
                            length -= num2;
                        }
                        while (length > 0);
                    }
                }
        }

        internal static void Enter(TraceSource traceSource, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Verbose, 0, msg);
        }

        internal static void Enter(TraceSource traceSource, string method, string parameters)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Enter(traceSource, method + "(" + parameters + ")");
        }

        [FriendAccessAllowed]
        internal static void Enter(TraceSource traceSource, object obj, string method, object paramObject)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Enter(traceSource, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj), method, paramObject);
        }

        [FriendAccessAllowed]
        internal static void Enter(TraceSource traceSource, object obj, string method, string param)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Enter(traceSource, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj), method, param);
        }

        internal static void Enter(TraceSource traceSource, string obj, string method, object paramObject)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
            {
                var str = string.Empty;
                if (paramObject != null)
                    str = GetObjectName(paramObject) + "#" + ValidationHelper.HashString(paramObject);
                Enter(traceSource, obj + "::" + method + "(" + str + ")");
            }
        }

        internal static void Enter(TraceSource traceSource, string obj, string method, string param)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Enter(traceSource, obj + "::" + method + "(" + param + ")");
        }

        [FriendAccessAllowed]
        internal static void Exception(TraceSource traceSource, object obj, string method, System.Exception e)
        {
            if (ValidateSettings(traceSource, TraceEventType.Error))
            {
                var msg = SR.GetString(SR.net_log_exception, GetObjectLogHash(obj), method, e.Message);
                if (!ValidationHelper.IsBlankString(e.StackTrace))
                    msg = msg + "\r\n" + e.StackTrace;
                PrintLine(traceSource, TraceEventType.Error, 0, msg);
            }
        }

        internal static void Exit(TraceSource traceSource, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Verbose, 0, "Exiting " + msg);
        }

        internal static void Exit(TraceSource traceSource, string method, string parameters)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Exit(traceSource, method + "() " + parameters);
        }

        [FriendAccessAllowed]
        internal static void Exit(TraceSource traceSource, object obj, string method, object retObject)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
            {
                var retValue = string.Empty;
                if (retObject != null)
                    retValue = GetObjectName(retObject) + "#" + ValidationHelper.HashString(retObject);
                Exit(traceSource, obj, method, retValue);
            }
        }

        [FriendAccessAllowed]
        internal static void Exit(TraceSource traceSource, object obj, string method, string retValue)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                Exit(traceSource, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj), method, retValue);
        }

        internal static void Exit(TraceSource traceSource, string obj, string method, object retObject)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
            {
                var retValue = string.Empty;
                if (retObject != null)
                    retValue = GetObjectName(retObject) + "#" + ValidationHelper.HashString(retObject);
                Exit(traceSource, obj, method, retValue);
            }
        }

        internal static void Exit(TraceSource traceSource, string obj, string method, string retValue)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
            {
                if (!ValidationHelper.IsBlankString(retValue))
                    retValue = "\t-> " + retValue;
                Exit(traceSource, obj + "::" + method + "() " + retValue);
            }
        }

        private static int GetMaxDumpSizeSetting(TraceSource traceSource)
        {
            var num = 0x400;
            if (traceSource.Attributes.ContainsKey("maxdatasize"))
                try { num = int.Parse(traceSource.Attributes["maxdatasize"], NumberFormatInfo.InvariantInfo); }
                catch (System.Exception exception)
                {
                    if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                        throw;
                    traceSource.Attributes["maxdatasize"] = num.ToString(NumberFormatInfo.InvariantInfo);
                }
            return num;
        }

        [FriendAccessAllowed]
        internal static string GetObjectLogHash(object obj)
        {
            return (GetObjectName(obj) + "#" + ValidationHelper.HashString(obj));
        }

        private static string GetObjectName(object obj)
        {
            if (obj is Uri || obj is IPAddress || obj is IPEndPoint)
                return obj.ToString();
            return obj.GetType().Name;
        }

        internal static uint GetThreadId()
        {
            var currentThreadId = GetCurrentThreadId();
            if (currentThreadId == 0)
                currentThreadId = (uint)Thread.CurrentThread.GetHashCode();
            return currentThreadId;
        }

        private static bool GetUseProtocolTextSetting(TraceSource traceSource)
        {
            var flag = false;
            if (traceSource.Attributes["tracemode"] == "protocolonly")
                flag = true;
            return flag;
        }

        private static void InitializeLogging()
        {
            lock (InternalSyncObject)
            {
                if (!s_LoggingInitialized)
                {
                    bool flag = false;
                    s_WebTraceSource = new NclTraceSource("System.Net");
                    s_HttpListenerTraceSource = new NclTraceSource("System.Net.HttpListener");
                    s_SocketsTraceSource = new NclTraceSource("System.Net.Sockets");
                    s_WebSocketsTraceSource = new NclTraceSource("System.Net.WebSockets");
                    s_CacheTraceSource = new NclTraceSource("System.Net.Cache");
                    s_TraceSourceHttpName = new NclTraceSource("System.Net.Http");
                    try
                    {
                        flag = (((s_WebTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_HttpListenerTraceSource.Switch.ShouldTrace(TraceEventType.Critical)) || (s_SocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical) || s_WebSocketsTraceSource.Switch.ShouldTrace(TraceEventType.Critical))) || s_CacheTraceSource.Switch.ShouldTrace(TraceEventType.Critical)) || s_TraceSourceHttpName.Switch.ShouldTrace(TraceEventType.Critical);
                    }
                    catch (SecurityException)
                    {
                        Close();
                        flag = false;
                    }
                    if (flag)
                    {
                        var currentDomain = AppDomain.CurrentDomain;
                        currentDomain.UnhandledException += new UnhandledExceptionEventHandler(Logging.UnhandledExceptionHandler);
                        currentDomain.DomainUnload += new EventHandler(Logging.AppDomainUnloadEvent);
                        currentDomain.ProcessExit += new EventHandler(Logging.ProcessExitEvent);
                    }
                    s_LoggingEnabled = flag;
                    s_LoggingInitialized = true;
                }
            }
        }

        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        internal static bool IsVerbose(TraceSource traceSource)
        {
            return ValidateSettings(traceSource, TraceEventType.Verbose);
        }

        [FriendAccessAllowed]
        internal static void PrintError(TraceSource traceSource, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Error))
                PrintLine(traceSource, TraceEventType.Error, 0, msg);
        }

        [FriendAccessAllowed]
        internal static void PrintError(TraceSource traceSource, object obj, string method, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Error))
                PrintLine(traceSource, TraceEventType.Error, 0, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj) + "::" + method + "() - " + msg);
        }

        internal static void PrintInfo(TraceSource traceSource, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Information, 0, msg);
        }

        [FriendAccessAllowed]
        internal static void PrintInfo(TraceSource traceSource, object obj, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj) + " - " + msg);
        }

        internal static void PrintInfo(TraceSource traceSource, object obj, string method, string param)
        {
            if (ValidateSettings(traceSource, TraceEventType.Information))
                PrintLine(traceSource, TraceEventType.Information, 0, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj) + "::" + method + "(" + param + ")");
        }

        internal static void PrintLine(TraceSource traceSource, TraceEventType eventType, int id, string msg)
        {
            traceSource.TraceEvent(eventType, id, ("[" + GetThreadId().ToString("d4", CultureInfo.InvariantCulture) + "] ") + msg);
        }

        [FriendAccessAllowed]
        internal static void PrintWarning(TraceSource traceSource, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Warning))
                PrintLine(traceSource, TraceEventType.Warning, 0, msg);
        }

        internal static void PrintWarning(TraceSource traceSource, object obj, string method, string msg)
        {
            if (ValidateSettings(traceSource, TraceEventType.Warning))
                PrintLine(traceSource, TraceEventType.Warning, 0, GetObjectName(obj) + "#" + ValidationHelper.HashString(obj) + "::" + method + "() - " + msg);
        }

        private static void ProcessExitEvent(object sender, EventArgs e)
        {
            Close();
            s_AppDomainShutdown = true;
        }

        private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
        {
            var exceptionObject = (Exception)args.ExceptionObject;
            Exception(Web, sender, "UnhandledExceptionHandler", exceptionObject);
        }

        private static bool ValidateSettings(TraceSource traceSource, TraceEventType traceLevel)
        {
            if (!s_LoggingEnabled)
                return false;
            if (!s_LoggingInitialized)
                InitializeLogging();
            if (traceSource == null || !traceSource.Switch.ShouldTrace(traceLevel))
                return false;
            if (s_AppDomainShutdown)
                return false;
            return true;
        }

        [FriendAccessAllowed]
        internal static TraceSource Http
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_TraceSourceHttpName;
            }
        }

        internal static TraceSource HttpListener
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_HttpListenerTraceSource;
            }
        }

        private static object InternalSyncObject
        {
            get
            {
                if (s_InternalSyncObject == null)
                {
                    object obj2 = new object();
                    Interlocked.CompareExchange(ref s_InternalSyncObject, obj2, null);
                }
                return s_InternalSyncObject;
            }
        }

        [FriendAccessAllowed]
        internal static bool On
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                return s_LoggingEnabled;
            }
        }

        internal static TraceSource RequestCache
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_CacheTraceSource;
            }
        }

        internal static TraceSource Sockets
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_SocketsTraceSource;
            }
        }

        internal static TraceSource Web
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_WebTraceSource;
            }
        }

        internal static TraceSource WebSockets
        {
            get
            {
                if (!s_LoggingInitialized)
                    InitializeLogging();
                if (!s_LoggingEnabled)
                    return null;
                return s_WebSocketsTraceSource;
            }
        }

        private class NclTraceSource : TraceSource
        {
            internal NclTraceSource(string name)
                : base(name) { }
            protected override string[] GetSupportedAttributes() { return Logging.SupportedAttributes; }
        }
    }
}


text:
/*jslint node: true, indent: 2, passfail: true */
/*global Chain, Slice, Filter, Map*/

module.exports = (function () {
  "use strict";

  var modelo = require('modelo'),
    Iterable = require('./core/iterable'),
    Iterator = require('./core/iterator'),
    callbackHelper = require('../helper/callback'),
    args = require('../helper/args'),
    forEachIter = require('./core/foreach'),
    ChainIterable = require('./iterables/chain'),
    CompressIterable = require('./iterables/compress'),
    CountIterable = require('./iterables/count'),
    CycleIterable = require('./iterables/cycle'),
    DropWhileIterable = require('./iterables/dropwhile'),
    FilterIterable = require('./iterables/filter'),
    FilterFalseIterable = require('./iterables/filterfalse'),
    MapIterable = require('./iterables/map'),
    RepeatIterable = require('./iterables/repeat'),
    SliceIterable = require('./iterables/slice'),
    StreamIterable = require('./iterables/stream'),
    TakeWhileIterable = require('./iterables/takewhile');

  function ExtendedIterable() {
    Iterable.apply(this, arguments);
  }
  modelo.inherits(ExtendedIterable, Iterable);

  ExtendedIterable.prototype.toArray = function toArray(callback) {

    var helper = callbackHelper.call(undefined, callback),
      response = [];

    forEachIter(this.iterator(), response.push.bind(response)).then(
      function () { helper.resolve(response); },
      helper.reject
    );

    return helper.response;

  };

  ExtendedIterable.prototype.concat = function concat() {

    var i = Object.create(Chain.prototype);
    Chain.apply(i, [this].concat(args.appl(undefined, arguments)));
    return i;

  };

  ExtendedIterable.prototype.join = function join(seperator, callback) {

    var helper = callbackHelper.call(undefined, callback);

    this.toArray().then(function (r, v) {
      r(v.join(seperator));
    }.bind(undefined, helper.resolve), helper.reject);

    return helper.response;

  };

  ExtendedIterable.prototype.slice = function slice(start, stop, step) {

    return new Slice(this.iterator(), start, stop, step);

  };

  ExtendedIterable.prototype.forEach = function forEach(fn, thisArg, callback) {

    var helper = callbackHelper.call(undefined, callback);

    forEachIter(this.iterator(), fn.bind(thisArg)).then(
      helper.resolve,
      helper.reject
    );

    return helper.response;

  };

  ExtendedIterable.prototype.every = function every(test, thisArg, callback) {

    var helper = callbackHelper.call(undefined, callback);

    this.toArray().then(
      function (arr) { return arr.every(test, thisArg); }
    ).then(
      helper.resolve,
      helper.reject
    );

    return helper.response;

  };

  ExtendedIterable.prototype.some = function some(test, thisArg, callback) {

    var helper = callbackHelper.call(undefined, callback);

    this.toArray().then(
      function (arr) { return arr.some(test, thisArg); }
    ).then(
      helper.resolve,
      helper.reject
    );

    return helper.response;

  };

  ExtendedIterable.prototype.filter = function filter(test, thisArg) {

    return new Filter(test.bind(thisArg), this.iterator());

  };

  ExtendedIterable.prototype.map = function map(fn, thisArg) {

    return new Map(fn.bind(thisArg), this.iterator());

  };

  function Chain() {
    ExtendedIterable.call(this);
    ChainIterable.apply(this, arguments);
  }
  modelo.inherits(Chain, ExtendedIterable, ChainIterable);

  function Compress() {
    ExtendedIterable.call(this);
    CompressIterable.apply(this, arguments);
  }
  modelo.inherits(Compress, ExtendedIterable, CompressIterable);

  function Count() {
    ExtendedIterable.call(this);
    CountIterable.apply(this, arguments);
  }
  modelo.inherits(Count, ExtendedIterable, CountIterable);

  function Cycle() {
    ExtendedIterable.call(this);
    CycleIterable.apply(this, arguments);
  }
  modelo.inherits(Cycle, ExtendedIterable, CycleIterable);

  function DropWhile() {
    ExtendedIterable.call(this);
    DropWhileIterable.apply(this, arguments);
  }
  modelo.inherits(DropWhile, ExtendedIterable, DropWhileIterable);

  function Filter() {
    ExtendedIterable.call(this);
    FilterIterable.apply(this, arguments);
  }
  modelo.inherits(Filter, ExtendedIterable, FilterIterable);

  function FilterFalse() {
    ExtendedIterable.call(this);
    FilterFalseIterable.apply(this, arguments);
  }
  modelo.inherits(FilterFalse, ExtendedIterable, FilterFalseIterable);

  function Map() {
    ExtendedIterable.call(this);
    MapIterable.apply(this, arguments);
  }
  modelo.inherits(Map, ExtendedIterable, MapIterable);

  function Repeat() {
    ExtendedIterable.call(this);
    RepeatIterable.apply(this, arguments);
  }
  modelo.inherits(Repeat, ExtendedIterable, RepeatIterable);

  function Slice() {
    ExtendedIterable.call(this);
    SliceIterable.apply(this, arguments);
  }
  modelo.inherits(Slice, ExtendedIterable, SliceIterable);

  function Stream() {
    ExtendedIterable.call(this);
    StreamIterable.apply(this, arguments);
  }
  modelo.inherits(Stream, ExtendedIterable, StreamIterable);

  function TakeWhile() {
    ExtendedIterable.call(this);
    TakeWhileIterable.apply(this, arguments);
  }
  modelo.inherits(TakeWhile, ExtendedIterable, TakeWhileIterable);

  return {
    "Chain": Chain,
    "Compress": Compress,
    "Count": Count,
    "Cycle": Cycle,
    "DropWhile": DropWhile,
    "Filter": Filter,
    "FilterFalse": FilterFalse,
    "Map": Map,
    "Repeat": Repeat,
    "Slice": Slice,
    "Stream": Stream,
    "TakeWhile": TakeWhile,
    "Iterable": ExtendedIterable,
    "Iterator": Iterator
  };

}());


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

<TITLE>
Deleter (Objectify-AppEngine Javadoc)
</TITLE>

<META NAME="date" CONTENT="2012-01-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.googlecode.objectify.cmd

Interface Deleter

public interface Deleter

The top element in the command chain for deleting entities from the datastore.

You can delete entities by either passing in the POJO or their keys.  Note that deletes do NOT cascade;
 you must delete each individual entity in an object graph.

The type() method allows you to construct keys fluently.

Note that all command objects are immutable.

Author:

Jeff Schnitzer <jeff@infohazard.org>

Method Summary

 Result<java.lang.Void>
entities(java.lang.Iterable<?> entities)

          Begin asynchronous deletion of specific entities.

 Result<java.lang.Void>
entities(java.lang.Object... entities)

          Convenient substitute for entities(Iterable)

 Result<java.lang.Void>
entity(java.lang.Object entity)

          Begin asynchronous deletion of a specific entity.

 Result<java.lang.Void>
key(Key<?> key)

          Begin asynchronous deletion of a specific entity.

 Result<java.lang.Void>
keys(java.lang.Iterable<Key<?>> keys)

          Begin asynchronous deletion of specific entities.

 Result<java.lang.Void>
keys(Key<?>... keys)

          Convenient substitute for keys(Iterable)

 DeleteType
type(java.lang.Class<?> type)

          Begin construction of a key or keys to delete by specifying a kind.

Method Detail

type

DeleteType type(java.lang.Class<?> type)

Begin construction of a key or keys to delete by specifying a kind.

Parameters:
type - is the kind of object to delete.

Returns:
the next step in the command chain where you specify a parent and/or ids.

key

Result<java.lang.Void> key(Key<?> key)

Begin asynchronous deletion of a specific entity.

To force synchronous delete, call now() on the returned Result.

Parameters:
key - defines which entity to delete

Returns:
an asynchronous Result.  Call now() to force synchronous deletion.

keys

Result<java.lang.Void> keys(java.lang.Iterable<Key<?>> keys)

Begin asynchronous deletion of specific entities.

To force synchronous delete, call now() on the returned Result.

Parameters:
keys - defines which entities to delete

Returns:
an asynchronous Result.  Call now() to force synchronous deletion.

keys

Result<java.lang.Void> keys(Key<?>... keys)

Convenient substitute for keys(Iterable)

entity

Result<java.lang.Void> entity(java.lang.Object entity)

Begin asynchronous deletion of a specific entity.

To force synchronous delete, call now() on the returned Result.

Parameters:
entity - can be an entity or any key-like structure; a Key<?>, a native datastore Key, or an entity object with valid id/parent fields.

Returns:
an asynchronous Result.  Call now() to force synchronous deletion.

entities

Result<java.lang.Void> entities(java.lang.Iterable<?> entities)

Begin asynchronous deletion of specific entities.

To force synchronous delete, call now() on the returned Result.

Parameters:
entities - can be entity instances or any key-like structure; a Key<?>, a native datastore Key, or an entity object with valid id/parent fields.

Returns:
an asynchronous Result.  Call now() to force synchronous deletion.

entities

Result<java.lang.Void> entities(java.lang.Object... entities)

Convenient substitute for entities(Iterable)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2012 Jeff Schnitzer and a gang of pirates. All Rights Reserved. Build version: 4.0a3


text:
function contentEncoding(acceptEncoding) {
  return contentEncoding_re.test(acceptEncoding) && RegExp.$1;
}

var contentEncoding_re = /\b(deflate|gzip)\b/;


text:
package org.spongepowered.common.data.value;

import org.spongepowered.api.data.Key;
import org.spongepowered.api.data.value.WeightedCollectionValue;
import org.spongepowered.api.util.weighted.TableEntry;
import org.spongepowered.api.util.weighted.WeightedTable;
import org.spongepowered.common.data.key.SpongeKey;

import java.util.List;
import java.util.Random;
import java.util.function.Consumer;

public class ImmutableSpongeWeightedCollectionValue<E> extends ImmutableSpongeCollectionValue<TableEntry<E>, WeightedTable<E>,
        WeightedCollectionValue.Immutable<E>, WeightedCollectionValue.Mutable<E>> implements WeightedCollectionValue.Immutable<E> {

    public ImmutableSpongeWeightedCollectionValue(
            Key<? extends WeightedCollectionValue<E>> key, WeightedTable<E> element) {
        super(key, element);
    }

    @Override
    @SuppressWarnings("unchecked")
    public SpongeKey<? extends WeightedCollectionValue<E>, WeightedTable<E>> key() {
        return (SpongeKey<? extends WeightedCollectionValue<E>, WeightedTable<E>>) super.key();
    }

    @Override
    public List<E> get(Random random) {
        return this.element.get(random);
    }

    @Override
    protected WeightedCollectionValue.Immutable<E> modifyCollection(Consumer<WeightedTable<E>> consumer) {
        final WeightedTable<E> table = new WeightedTable<>(this.element.rolls());
        table.addAll(this.element);
        consumer.accept(table);
        return this.key().getValueConstructor().getRawImmutable(table).asImmutable();
    }

    @Override
    public WeightedCollectionValue.Immutable<E> with(WeightedTable<E> value) {
        return this.key().getValueConstructor().getImmutable(value).asImmutable();
    }

    @Override
    public WeightedCollectionValue.Mutable<E> asMutable() {
        return new MutableSpongeWeightedCollectionValue<>(this.key(), this.get());
    }
}


text:
/**
 * rxSubscriber symbol is a symbol for retreiving an "Rx safe" Observer from an object
 * "Rx safety" can be defined as an object that has all of the traits of an Rx Subscriber,
 * including the ability to add and remove subscriptions to the subscription chain and
 * guarantees involving event triggering (can't "next" after unsubscription, etc).
 */
export declare const rxSubscriber: any;


text:
package eu.agilejava.batch.chunk;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.batch.api.chunk.AbstractItemWriter;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.inject.Named;

/**
 * Simple writer for batch chunk demo.
 *
 * @author Ivar Grimstad <ivar.grimstad@gmail.com>
 */
@Dependent
@Named("simpleWriter")
public class SimpleWriter extends AbstractItemWriter {

   @Inject
   private Logger logger;

   /**
    * Writes to log when item is written.
    *
    * @param items the items to write
    * @throws Exception
    */
   @Override
   public void writeItems(List<Object> items) throws Exception {

      for (Object o : items) {
         SimpleOutput output = (SimpleOutput) o;
         logger.log(Level.INFO, "writing {0}", output.getValue());
      }
   }
}


text:
"""
Contains common logger initialization to be used in job_manager internals
that are to be captured from playbook_helper.py sub-process
"""

import logging

DEFAULT_JOB_MGR_LOG_PATH = '/var/log/contrail/contrail-fabric-ansible.log'
DATE_FORMAT = "%m/%d/%Y %I:%M:%S %p"
LOGGING_FORMAT = '%(asctime)s [%(name)s] [%(levelname)s]:  %(message)s'

def job_mgr_logger(name, ctx=None):
    name = name
    ctx = ctx

    logger = logging.getLogger(name)
    handler = logging.FileHandler(DEFAULT_JOB_MGR_LOG_PATH)
    formatter = logging.Formatter(fmt=LOGGING_FORMAT, datefmt=DATE_FORMAT)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    return logger