/*-
 *   BSD LICENSE
 *
 *   Copyright (c) Intel Corporation.
 *   All rights reserved.
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "env_internal.h"

#include <rte_config.h>
#include <rte_lcore.h>

uint32_t
spdk_env_get_core_count(void)
{
	return rte_lcore_count();
}

uint32_t
spdk_env_get_current_core(void)
{
	return rte_lcore_id();
}

uint32_t
spdk_env_get_first_core(void)
{
	return rte_get_next_lcore(-1, 0, 0);
}

uint32_t
spdk_env_get_last_core(void)
{
	uint32_t i;
	uint32_t last_core = UINT32_MAX;

	SPDK_ENV_FOREACH_CORE(i) {
		last_core = i;
	}

	assert(last_core != UINT32_MAX);

	return last_core;
}

uint32_t
spdk_env_get_next_core(uint32_t prev_core)
{
	unsigned lcore;

	lcore = rte_get_next_lcore(prev_core, 0, 0);
	if (lcore == RTE_MAX_LCORE) {
		return UINT32_MAX;
	}
	return lcore;
}

uint32_t
spdk_env_get_socket_id(uint32_t core)
{
	if (core >= RTE_MAX_LCORE) {
		return SPDK_ENV_SOCKET_ID_ANY;
	}

	return rte_lcore_to_socket_id(core);
}

int
spdk_env_thread_launch_pinned(uint32_t core, thread_start_fn fn, void *arg)
{
	int rc;

	rc = rte_eal_remote_launch(fn, arg, core);

	return rc;
}

void
spdk_env_thread_wait_all(void)
{
	rte_eal_mp_wait_lcore();
}

{'repo_name': 'spdk/spdk', 'stars': '1387', 'repo_language': 'C', 'file_name': 'Makefile', 'mime_type': 'text/x-makefile', 'hash': -6372320225103442002, 'source_dataset': 'data'}


package mage.cards.l;

import mage.abilities.Ability;
import mage.abilities.effects.OneShotEffect;
import mage.abilities.effects.common.DamageAllEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Outcome;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.permanent.AttackingPredicate;
import mage.filter.predicate.permanent.BlockingPredicate;
import mage.game.Game;
import mage.players.Player;

import java.util.UUID;

/**
 * @author TheElk801
 */
public final class LavaStorm extends CardImpl {

    public LavaStorm(UUID ownerId, CardSetInfo setInfo) {
        super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{3}{R}{R}");

        // Lava Storm deals 2 damage to each attacking creature or Lava Storm deals 2 damage to each blocking creature.
        this.getSpellAbility().addEffect(new LavaStormEffect());
    }

    private LavaStorm(final LavaStorm card) {
        super(card);
    }

    @Override
    public LavaStorm copy() {
        return new LavaStorm(this);
    }
}

class LavaStormEffect extends OneShotEffect {
    private static final FilterPermanent filter = new FilterCreaturePermanent();
    private static final FilterPermanent filter2 = new FilterCreaturePermanent();

    static {
        filter.add(AttackingPredicate.instance);
        filter2.add(BlockingPredicate.instance);
    }

    LavaStormEffect() {
        super(Outcome.Benefit);
        staticText = "{this} deals 2 damage to each attacking creature " +
                "or {this} deals 2 damage to each blocking creature.";
    }

    private LavaStormEffect(final LavaStormEffect effect) {
        super(effect);
    }

    @Override
    public LavaStormEffect copy() {
        return new LavaStormEffect(this);
    }

    @Override
    public boolean apply(Game game, Ability source) {
        Player player = game.getPlayer(source.getControllerId());
        if (player == null) {
            return false;
        }
        if (player.chooseUse(
                Outcome.Benefit, "Deal 2 damage to all attacking creatures or all blocking creatures?",
                null, "Attackers", "Blockers", source, game)
        ) {
            return new DamageAllEffect(2, filter).apply(game, source);
        }
        return new DamageAllEffect(2, filter2).apply(game, source);
    }
}

{'repo_name': 'magefree/mage', 'stars': '1076', 'repo_language': 'Java', 'file_name': 'Wildcall.java', 'mime_type': 'text/x-java', 'hash': 4674812147235420543, 'source_dataset': 'data'}


# Hardware

**node-wifi** has been tested on following hardwares.

## macOS

## Linux

To get the device info: `lspci | egrep -i --color 'network|ethernet'`.

- Dell XPS 13 2019 (9370): Qualcomm Atheros QCA6174 802.11ac Wireless Network Adapter (rev 32)

{'repo_name': 'friedrith/node-wifi', 'stars': '206', 'repo_language': 'JavaScript', 'file_name': 'test-connect.js', 'mime_type': 'text/plain', 'hash': -869224375941755395, 'source_dataset': 'data'}


using System;
using System.Threading;

namespace GitUI
{
    ///
    /// Supports sequences of actions where the commencement of an action cancels any
    /// prior action.
    ///
    /// <remarks>
    /// This sequence does not guarantee that prior operations stop executing before
    /// <see cref="Next"/> returns. It only guarantees that their <see cref="CancellationToken"/>
    /// will be cancelled. Operations need to use their tokens in an appropriate manner.
    /// You may still require additional concurrency protections.
    /// </remarks>
    /// <example>
    /// Define an instance of this type, usually as a private readonly field:
    ///
    /// private readonly CancellableSequence _sequence = new CancellableSequence();
    ///
    /// Then use it to generate <see cref="CancellationToken"/> objects for use in asynchronous
    /// operations.
    ///
    /// var token = _sequence.Next();
    /// // Do asynchronous operation using this token.
    /// // Subsequent calls to Next will cancel this token.
    ///
    /// </example>
    public sealed class CancellationTokenSequence : IDisposable
    {
        /// <remarks>
        /// If this field is <c>null</c>, the object has been disposed.
        /// </remarks>
        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        ///
        /// Issues the <see cref="CancellationToken"/> for use by the next asynchronous operation in the sequence,
        /// and cancels any prior token.
        ///
        /// <remarks>
        /// <para>This method does not guarantee that prior operations stop executing before
        /// it returns. It only guarantees that their <see cref="CancellationToken"/>
        /// will be cancelled. Operations need to use their tokens in an appropriate manner.
        /// You may still require additional concurrency protections.</para>
        ///
        /// <para>This method is thread-safe.</para>
        /// </remarks>
        /// <returns>A <see cref="CancellationToken"/> to be used by the commencing asynchronous operation.</returns>
        /// <exception cref="OperationCanceledException">This object is disposed.</exception>
        public CancellationToken Next()
        {
            var next = new CancellationTokenSource();

            // Make sure to obtain the CancellationToken for the next source before exposing the source,
            // or another thread could dispose of source before we get a chance to access this property.
            var nextToken = next.Token;

            // The following block is identical to Interlocked.Exchange, except no replacement is
            // made if the current field value is null (latch on null).
            var prior = Volatile.Read(ref _cancellationTokenSource);

            while (prior != null)
            {
                var candidate = Interlocked.CompareExchange(ref _cancellationTokenSource, next, prior);

                if (candidate == prior)
                {
                    break;
                }
                else
                {
                    prior = candidate;
                }
            }

            // Detect and handle the case where the sequence was already disposed
            if (prior is null)
            {
                next.Cancel();
                next.Dispose();
                nextToken.ThrowIfCancellationRequested();
            }

            prior.Cancel();
            prior.Dispose();

            return nextToken;
        }

        ///
        /// Cancels any current asynchronous operation.
        ///
        /// <remarks>
        /// It is safe to call this method multiple times, regardless of whether a
        /// new token has been issued or not.
        /// </remarks>
        /// <exception cref="ObjectDisposedException">This object is disposed.</exception>
        public void CancelCurrent()
        {
            // Calling Next() will cancel the current operation. Ignoring the return value means
            // an unnecessary CancellationTokenSource is allocated, but it will not be leaked or
            // otherwise interfere with the sequence.
            Next();
        }

        ///
        /// Cancels the current token and disposes this object.
        ///
        /// <remarks>
        /// Only the first call to this method per instance of this class has any effect.
        /// </remarks>
        public void Dispose()
        {
            var cancellationTokenSource = Interlocked.Exchange(ref _cancellationTokenSource, null);

            if (cancellationTokenSource is null)
            {
                return;
            }

            cancellationTokenSource.Cancel();
            cancellationTokenSource.Dispose();
        }
    }
}

{'repo_name': 'gitextensions/gitextensions', 'stars': '5043', 'repo_language': 'C#', 'file_name': 'AssemblyInfo.cs', 'mime_type': 'text/plain', 'hash': -8583930152465127363, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0-only
/*
 * Minimal BPF debugger
 *
 * Minimal BPF debugger that mimics the kernel's engine (w/o extensions)
 * and allows for single stepping through selected packets from a pcap
 * with a provided user filter in order to facilitate verification of a
 * BPF program. Besides others, this is useful to verify BPF programs
 * before attaching to a live system, and can be used in socket filters,
 * cls_bpf, xt_bpf, team driver and e.g. PTP code; in particular when a
 * single more complex BPF program is being used. Reasons for a more
 * complex BPF program are likely primarily to optimize execution time
 * for making a verdict when multiple simple BPF programs are combined
 * into one in order to prevent parsing same headers multiple times.
 *
 * More on how to debug BPF opcodes see Documentation/networking/filter.txt
 * which is the main document on BPF. Mini howto for getting started:
 *
 *  1) `./bpf_dbg` to enter the shell (shell cmds denoted with '>'):
 *  2) > load bpf 6,40 0 0 12,21 0 3 20... (output from `bpf_asm` or
 *     `tcpdump -iem1 -ddd port 22 | tr '\n' ','` to load as filter)
 *  3) > load pcap foo.pcap
 *  4) > run <n>/disassemble/dump/quit (self-explanatory)
 *  5) > breakpoint 2 (sets bp at loaded BPF insns 2, do `run` then;
 *       multiple bps can be set, of course, a call to `breakpoint`
 *       w/o args shows currently loaded bps, `breakpoint reset` for
 *       resetting all breakpoints)
 *  6) > select 3 (`run` etc will start from the 3rd packet in the pcap)
 *  7) > step [-<n>, +<n>] (performs single stepping through the BPF)
 *
 * Copyright 2013 Daniel Borkmann <borkmann@redhat.com>
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdarg.h>
#include <setjmp.h>
#include <linux/filter.h>
#include <linux/if_packet.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <arpa/inet.h>
#include <net/ethernet.h>

#define TCPDUMP_MAGIC	0xa1b2c3d4

#define BPF_LDX_B	(BPF_LDX | BPF_B)
#define BPF_LDX_W	(BPF_LDX | BPF_W)
#define BPF_JMP_JA	(BPF_JMP | BPF_JA)
#define BPF_JMP_JEQ	(BPF_JMP | BPF_JEQ)
#define BPF_JMP_JGT	(BPF_JMP | BPF_JGT)
#define BPF_JMP_JGE	(BPF_JMP | BPF_JGE)
#define BPF_JMP_JSET	(BPF_JMP | BPF_JSET)
#define BPF_ALU_ADD	(BPF_ALU | BPF_ADD)
#define BPF_ALU_SUB	(BPF_ALU | BPF_SUB)
#define BPF_ALU_MUL	(BPF_ALU | BPF_MUL)
#define BPF_ALU_DIV	(BPF_ALU | BPF_DIV)
#define BPF_ALU_MOD	(BPF_ALU | BPF_MOD)
#define BPF_ALU_NEG	(BPF_ALU | BPF_NEG)
#define BPF_ALU_AND	(BPF_ALU | BPF_AND)
#define BPF_ALU_OR	(BPF_ALU | BPF_OR)
#define BPF_ALU_XOR	(BPF_ALU | BPF_XOR)
#define BPF_ALU_LSH	(BPF_ALU | BPF_LSH)
#define BPF_ALU_RSH	(BPF_ALU | BPF_RSH)
#define BPF_MISC_TAX	(BPF_MISC | BPF_TAX)
#define BPF_MISC_TXA	(BPF_MISC | BPF_TXA)
#define BPF_LD_B	(BPF_LD | BPF_B)
#define BPF_LD_H	(BPF_LD | BPF_H)
#define BPF_LD_W	(BPF_LD | BPF_W)

#ifndef array_size
# define array_size(x)	(sizeof(x) / sizeof((x)[0]))
#endif

#ifndef __check_format_printf
# define __check_format_printf(pos_fmtstr, pos_fmtargs) \
	__attribute__ ((format (printf, (pos_fmtstr), (pos_fmtargs))))
#endif

enum {
	CMD_OK,
	CMD_ERR,
	CMD_EX,
};

struct shell_cmd {
	const char *name;
	int (*func)(char *args);
};

struct pcap_filehdr {
	uint32_t magic;
	uint16_t version_major;
	uint16_t version_minor;
	int32_t  thiszone;
	uint32_t sigfigs;
	uint32_t snaplen;
	uint32_t linktype;
};

struct pcap_timeval {
	int32_t tv_sec;
	int32_t tv_usec;
};

struct pcap_pkthdr {
	struct pcap_timeval ts;
	uint32_t caplen;
	uint32_t len;
};

struct bpf_regs {
	uint32_t A;
	uint32_t X;
	uint32_t M[BPF_MEMWORDS];
	uint32_t R;
	bool     Rs;
	uint16_t Pc;
};

static struct sock_filter bpf_image[BPF_MAXINSNS + 1];
static unsigned int bpf_prog_len;

static int bpf_breakpoints[64];
static struct bpf_regs bpf_regs[BPF_MAXINSNS + 1];
static struct bpf_regs bpf_curr;
static unsigned int bpf_regs_len;

static int pcap_fd = -1;
static unsigned int pcap_packet;
static size_t pcap_map_size;
static char *pcap_ptr_va_start, *pcap_ptr_va_curr;

static const char * const op_table[] = {
	[BPF_ST]	= "st",
	[BPF_STX]	= "stx",
	[BPF_LD_B]	= "ldb",
	[BPF_LD_H]	= "ldh",
	[BPF_LD_W]	= "ld",
	[BPF_LDX]	= "ldx",
	[BPF_LDX_B]	= "ldxb",
	[BPF_JMP_JA]	= "ja",
	[BPF_JMP_JEQ]	= "jeq",
	[BPF_JMP_JGT]	= "jgt",
	[BPF_JMP_JGE]	= "jge",
	[BPF_JMP_JSET]	= "jset",
	[BPF_ALU_ADD]	= "add",
	[BPF_ALU_SUB]	= "sub",
	[BPF_ALU_MUL]	= "mul",
	[BPF_ALU_DIV]	= "div",
	[BPF_ALU_MOD]	= "mod",
	[BPF_ALU_NEG]	= "neg",
	[BPF_ALU_AND]	= "and",
	[BPF_ALU_OR]	= "or",
	[BPF_ALU_XOR]	= "xor",
	[BPF_ALU_LSH]	= "lsh",
	[BPF_ALU_RSH]	= "rsh",
	[BPF_MISC_TAX]	= "tax",
	[BPF_MISC_TXA]	= "txa",
	[BPF_RET]	= "ret",
};

static __check_format_printf(1, 2) int rl_printf(const char *fmt, ...)
{
	int ret;
	va_list vl;

	va_start(vl, fmt);
	ret = vfprintf(rl_outstream, fmt, vl);
	va_end(vl);

	return ret;
}

static int matches(const char *cmd, const char *pattern)
{
	int len = strlen(cmd);

	if (len > strlen(pattern))
		return -1;

	return memcmp(pattern, cmd, len);
}

static void hex_dump(const uint8_t *buf, size_t len)
{
	int i;

	rl_printf("%3u: ", 0);
	for (i = 0; i < len; i++) {
		if (i && !(i % 16))
			rl_printf("\n%3u: ", i);
		rl_printf("%02x ", buf[i]);
	}
	rl_printf("\n");
}

static bool bpf_prog_loaded(void)
{
	if (bpf_prog_len == 0)
		rl_printf("no bpf program loaded!\n");

	return bpf_prog_len > 0;
}

static void bpf_disasm(const struct sock_filter f, unsigned int i)
{
	const char *op, *fmt;
	int val = f.k;
	char buf[256];

	switch (f.code) {
	case BPF_RET | BPF_K:
		op = op_table[BPF_RET];
		fmt = "#%#x";
		break;
	case BPF_RET | BPF_A:
		op = op_table[BPF_RET];
		fmt = "a";
		break;
	case BPF_RET | BPF_X:
		op = op_table[BPF_RET];
		fmt = "x";
		break;
	case BPF_MISC_TAX:
		op = op_table[BPF_MISC_TAX];
		fmt = "";
		break;
	case BPF_MISC_TXA:
		op = op_table[BPF_MISC_TXA];
		fmt = "";
		break;
	case BPF_ST:
		op = op_table[BPF_ST];
		fmt = "M[%d]";
		break;
	case BPF_STX:
		op = op_table[BPF_STX];
		fmt = "M[%d]";
		break;
	case BPF_LD_W | BPF_ABS:
		op = op_table[BPF_LD_W];
		fmt = "[%d]";
		break;
	case BPF_LD_H | BPF_ABS:
		op = op_table[BPF_LD_H];
		fmt = "[%d]";
		break;
	case BPF_LD_B | BPF_ABS:
		op = op_table[BPF_LD_B];
		fmt = "[%d]";
		break;
	case BPF_LD_W | BPF_LEN:
		op = op_table[BPF_LD_W];
		fmt = "#len";
		break;
	case BPF_LD_W | BPF_IND:
		op = op_table[BPF_LD_W];
		fmt = "[x+%d]";
		break;
	case BPF_LD_H | BPF_IND:
		op = op_table[BPF_LD_H];
		fmt = "[x+%d]";
		break;
	case BPF_LD_B | BPF_IND:
		op = op_table[BPF_LD_B];
		fmt = "[x+%d]";
		break;
	case BPF_LD | BPF_IMM:
		op = op_table[BPF_LD_W];
		fmt = "#%#x";
		break;
	case BPF_LDX | BPF_IMM:
		op = op_table[BPF_LDX];
		fmt = "#%#x";
		break;
	case BPF_LDX_B | BPF_MSH:
		op = op_table[BPF_LDX_B];
		fmt = "4*([%d]&0xf)";
		break;
	case BPF_LD | BPF_MEM:
		op = op_table[BPF_LD_W];
		fmt = "M[%d]";
		break;
	case BPF_LDX | BPF_MEM:
		op = op_table[BPF_LDX];
		fmt = "M[%d]";
		break;
	case BPF_JMP_JA:
		op = op_table[BPF_JMP_JA];
		fmt = "%d";
		val = i + 1 + f.k;
		break;
	case BPF_JMP_JGT | BPF_X:
		op = op_table[BPF_JMP_JGT];
		fmt = "x";
		break;
	case BPF_JMP_JGT | BPF_K:
		op = op_table[BPF_JMP_JGT];
		fmt = "#%#x";
		break;
	case BPF_JMP_JGE | BPF_X:
		op = op_table[BPF_JMP_JGE];
		fmt = "x";
		break;
	case BPF_JMP_JGE | BPF_K:
		op = op_table[BPF_JMP_JGE];
		fmt = "#%#x";
		break;
	case BPF_JMP_JEQ | BPF_X:
		op = op_table[BPF_JMP_JEQ];
		fmt = "x";
		break;
	case BPF_JMP_JEQ | BPF_K:
		op = op_table[BPF_JMP_JEQ];
		fmt = "#%#x";
		break;
	case BPF_JMP_JSET | BPF_X:
		op = op_table[BPF_JMP_JSET];
		fmt = "x";
		break;
	case BPF_JMP_JSET | BPF_K:
		op = op_table[BPF_JMP_JSET];
		fmt = "#%#x";
		break;
	case BPF_ALU_NEG:
		op = op_table[BPF_ALU_NEG];
		fmt = "";
		break;
	case BPF_ALU_LSH | BPF_X:
		op = op_table[BPF_ALU_LSH];
		fmt = "x";
		break;
	case BPF_ALU_LSH | BPF_K:
		op = op_table[BPF_ALU_LSH];
		fmt = "#%d";
		break;
	case BPF_ALU_RSH | BPF_X:
		op = op_table[BPF_ALU_RSH];
		fmt = "x";
		break;
	case BPF_ALU_RSH | BPF_K:
		op = op_table[BPF_ALU_RSH];
		fmt = "#%d";
		break;
	case BPF_ALU_ADD | BPF_X:
		op = op_table[BPF_ALU_ADD];
		fmt = "x";
		break;
	case BPF_ALU_ADD | BPF_K:
		op = op_table[BPF_ALU_ADD];
		fmt = "#%d";
		break;
	case BPF_ALU_SUB | BPF_X:
		op = op_table[BPF_ALU_SUB];
		fmt = "x";
		break;
	case BPF_ALU_SUB | BPF_K:
		op = op_table[BPF_ALU_SUB];
		fmt = "#%d";
		break;
	case BPF_ALU_MUL | BPF_X:
		op = op_table[BPF_ALU_MUL];
		fmt = "x";
		break;
	case BPF_ALU_MUL | BPF_K:
		op = op_table[BPF_ALU_MUL];
		fmt = "#%d";
		break;
	case BPF_ALU_DIV | BPF_X:
		op = op_table[BPF_ALU_DIV];
		fmt = "x";
		break;
	case BPF_ALU_DIV | BPF_K:
		op = op_table[BPF_ALU_DIV];
		fmt = "#%d";
		break;
	case BPF_ALU_MOD | BPF_X:
		op = op_table[BPF_ALU_MOD];
		fmt = "x";
		break;
	case BPF_ALU_MOD | BPF_K:
		op = op_table[BPF_ALU_MOD];
		fmt = "#%d";
		break;
	case BPF_ALU_AND | BPF_X:
		op = op_table[BPF_ALU_AND];
		fmt = "x";
		break;
	case BPF_ALU_AND | BPF_K:
		op = op_table[BPF_ALU_AND];
		fmt = "#%#x";
		break;
	case BPF_ALU_OR | BPF_X:
		op = op_table[BPF_ALU_OR];
		fmt = "x";
		break;
	case BPF_ALU_OR | BPF_K:
		op = op_table[BPF_ALU_OR];
		fmt = "#%#x";
		break;
	case BPF_ALU_XOR | BPF_X:
		op = op_table[BPF_ALU_XOR];
		fmt = "x";
		break;
	case BPF_ALU_XOR | BPF_K:
		op = op_table[BPF_ALU_XOR];
		fmt = "#%#x";
		break;
	default:
		op = "nosup";
		fmt = "%#x";
		val = f.code;
		break;
	}

	memset(buf, 0, sizeof(buf));
	snprintf(buf, sizeof(buf), fmt, val);
	buf[sizeof(buf) - 1] = 0;

	if ((BPF_CLASS(f.code) == BPF_JMP && BPF_OP(f.code) != BPF_JA))
		rl_printf("l%d:\t%s %s, l%d, l%d\n", i, op, buf,
			  i + 1 + f.jt, i + 1 + f.jf);
	else
		rl_printf("l%d:\t%s %s\n", i, op, buf);
}

static void bpf_dump_curr(struct bpf_regs *r, struct sock_filter *f)
{
	int i, m = 0;

	rl_printf("pc:       [%u]\n", r->Pc);
	rl_printf("code:     [%u] jt[%u] jf[%u] k[%u]\n",
		  f->code, f->jt, f->jf, f->k);
	rl_printf("curr:     ");
	bpf_disasm(*f, r->Pc);

	if (f->jt || f->jf) {
		rl_printf("jt:       ");
		bpf_disasm(*(f + f->jt + 1), r->Pc + f->jt + 1);
		rl_printf("jf:       ");
		bpf_disasm(*(f + f->jf + 1), r->Pc + f->jf + 1);
	}

	rl_printf("A:        [%#08x][%u]\n", r->A, r->A);
	rl_printf("X:        [%#08x][%u]\n", r->X, r->X);
	if (r->Rs)
		rl_printf("ret:      [%#08x][%u]!\n", r->R, r->R);

	for (i = 0; i < BPF_MEMWORDS; i++) {
		if (r->M[i]) {
			m++;
			rl_printf("M[%d]: [%#08x][%u]\n", i, r->M[i], r->M[i]);
		}
	}
	if (m == 0)
		rl_printf("M[0,%d]:  [%#08x][%u]\n", BPF_MEMWORDS - 1, 0, 0);
}

static void bpf_dump_pkt(uint8_t *pkt, uint32_t pkt_caplen, uint32_t pkt_len)
{
	if (pkt_caplen != pkt_len)
		rl_printf("cap: %u, len: %u\n", pkt_caplen, pkt_len);
	else
		rl_printf("len: %u\n", pkt_len);

	hex_dump(pkt, pkt_caplen);
}

static void bpf_disasm_all(const struct sock_filter *f, unsigned int len)
{
	unsigned int i;

	for (i = 0; i < len; i++)
		bpf_disasm(f[i], i);
}

static void bpf_dump_all(const struct sock_filter *f, unsigned int len)
{
	unsigned int i;

	rl_printf("/* { op, jt, jf, k }, */\n");
	for (i = 0; i < len; i++)
		rl_printf("{ %#04x, %2u, %2u, %#010x },\n",
			  f[i].code, f[i].jt, f[i].jf, f[i].k);
}

static bool bpf_runnable(struct sock_filter *f, unsigned int len)
{
	int sock, ret, i;
	struct sock_fprog bpf = {
		.filter = f,
		.len = len,
	};

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0) {
		rl_printf("cannot open socket!\n");
		return false;
	}
	ret = setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
	close(sock);
	if (ret < 0) {
		rl_printf("program not allowed to run by kernel!\n");
		return false;
	}
	for (i = 0; i < len; i++) {
		if (BPF_CLASS(f[i].code) == BPF_LD &&
		    f[i].k > SKF_AD_OFF) {
			rl_printf("extensions currently not supported!\n");
			return false;
		}
	}

	return true;
}

static void bpf_reset_breakpoints(void)
{
	int i;

	for (i = 0; i < array_size(bpf_breakpoints); i++)
		bpf_breakpoints[i] = -1;
}

static void bpf_set_breakpoints(unsigned int where)
{
	int i;
	bool set = false;

	for (i = 0; i < array_size(bpf_breakpoints); i++) {
		if (bpf_breakpoints[i] == (int) where) {
			rl_printf("breakpoint already set!\n");
			set = true;
			break;
		}

		if (bpf_breakpoints[i] == -1 && set == false) {
			bpf_breakpoints[i] = where;
			set = true;
		}
	}

	if (!set)
		rl_printf("too many breakpoints set, reset first!\n");
}

static void bpf_dump_breakpoints(void)
{
	int i;

	rl_printf("breakpoints: ");

	for (i = 0; i < array_size(bpf_breakpoints); i++) {
		if (bpf_breakpoints[i] < 0)
			continue;
		rl_printf("%d ", bpf_breakpoints[i]);
	}

	rl_printf("\n");
}

static void bpf_reset(void)
{
	bpf_regs_len = 0;

	memset(bpf_regs, 0, sizeof(bpf_regs));
	memset(&bpf_curr, 0, sizeof(bpf_curr));
}

static void bpf_safe_regs(void)
{
	memcpy(&bpf_regs[bpf_regs_len++], &bpf_curr, sizeof(bpf_curr));
}

static bool bpf_restore_regs(int off)
{
	unsigned int index = bpf_regs_len - 1 + off;

	if (index == 0) {
		bpf_reset();
		return true;
	} else if (index < bpf_regs_len) {
		memcpy(&bpf_curr, &bpf_regs[index], sizeof(bpf_curr));
		bpf_regs_len = index;
		return true;
	} else {
		rl_printf("reached bottom of register history stack!\n");
		return false;
	}
}

static uint32_t extract_u32(uint8_t *pkt, uint32_t off)
{
	uint32_t r;

	memcpy(&r, &pkt[off], sizeof(r));

	return ntohl(r);
}

static uint16_t extract_u16(uint8_t *pkt, uint32_t off)
{
	uint16_t r;

	memcpy(&r, &pkt[off], sizeof(r));

	return ntohs(r);
}

static uint8_t extract_u8(uint8_t *pkt, uint32_t off)
{
	return pkt[off];
}

static void set_return(struct bpf_regs *r)
{
	r->R = 0;
	r->Rs = true;
}

static void bpf_single_step(struct bpf_regs *r, struct sock_filter *f,
			    uint8_t *pkt, uint32_t pkt_caplen,
			    uint32_t pkt_len)
{
	uint32_t K = f->k;
	int d;

	switch (f->code) {
	case BPF_RET | BPF_K:
		r->R = K;
		r->Rs = true;
		break;
	case BPF_RET | BPF_A:
		r->R = r->A;
		r->Rs = true;
		break;
	case BPF_RET | BPF_X:
		r->R = r->X;
		r->Rs = true;
		break;
	case BPF_MISC_TAX:
		r->X = r->A;
		break;
	case BPF_MISC_TXA:
		r->A = r->X;
		break;
	case BPF_ST:
		r->M[K] = r->A;
		break;
	case BPF_STX:
		r->M[K] = r->X;
		break;
	case BPF_LD_W | BPF_ABS:
		d = pkt_caplen - K;
		if (d >= sizeof(uint32_t))
			r->A = extract_u32(pkt, K);
		else
			set_return(r);
		break;
	case BPF_LD_H | BPF_ABS:
		d = pkt_caplen - K;
		if (d >= sizeof(uint16_t))
			r->A = extract_u16(pkt, K);
		else
			set_return(r);
		break;
	case BPF_LD_B | BPF_ABS:
		d = pkt_caplen - K;
		if (d >= sizeof(uint8_t))
			r->A = extract_u8(pkt, K);
		else
			set_return(r);
		break;
	case BPF_LD_W | BPF_IND:
		d = pkt_caplen - (r->X + K);
		if (d >= sizeof(uint32_t))
			r->A = extract_u32(pkt, r->X + K);
		break;
	case BPF_LD_H | BPF_IND:
		d = pkt_caplen - (r->X + K);
		if (d >= sizeof(uint16_t))
			r->A = extract_u16(pkt, r->X + K);
		else
			set_return(r);
		break;
	case BPF_LD_B | BPF_IND:
		d = pkt_caplen - (r->X + K);
		if (d >= sizeof(uint8_t))
			r->A = extract_u8(pkt, r->X + K);
		else
			set_return(r);
		break;
	case BPF_LDX_B | BPF_MSH:
		d = pkt_caplen - K;
		if (d >= sizeof(uint8_t)) {
			r->X = extract_u8(pkt, K);
			r->X = (r->X & 0xf) << 2;
		} else
			set_return(r);
		break;
	case BPF_LD_W | BPF_LEN:
		r->A = pkt_len;
		break;
	case BPF_LDX_W | BPF_LEN:
		r->A = pkt_len;
		break;
	case BPF_LD | BPF_IMM:
		r->A = K;
		break;
	case BPF_LDX | BPF_IMM:
		r->X = K;
		break;
	case BPF_LD | BPF_MEM:
		r->A = r->M[K];
		break;
	case BPF_LDX | BPF_MEM:
		r->X = r->M[K];
		break;
	case BPF_JMP_JA:
		r->Pc += K;
		break;
	case BPF_JMP_JGT | BPF_X:
		r->Pc += r->A > r->X ? f->jt : f->jf;
		break;
	case BPF_JMP_JGT | BPF_K:
		r->Pc += r->A > K ? f->jt : f->jf;
		break;
	case BPF_JMP_JGE | BPF_X:
		r->Pc += r->A >= r->X ? f->jt : f->jf;
		break;
	case BPF_JMP_JGE | BPF_K:
		r->Pc += r->A >= K ? f->jt : f->jf;
		break;
	case BPF_JMP_JEQ | BPF_X:
		r->Pc += r->A == r->X ? f->jt : f->jf;
		break;
	case BPF_JMP_JEQ | BPF_K:
		r->Pc += r->A == K ? f->jt : f->jf;
		break;
	case BPF_JMP_JSET | BPF_X:
		r->Pc += r->A & r->X ? f->jt : f->jf;
		break;
	case BPF_JMP_JSET | BPF_K:
		r->Pc += r->A & K ? f->jt : f->jf;
		break;
	case BPF_ALU_NEG:
		r->A = -r->A;
		break;
	case BPF_ALU_LSH | BPF_X:
		r->A <<= r->X;
		break;
	case BPF_ALU_LSH | BPF_K:
		r->A <<= K;
		break;
	case BPF_ALU_RSH | BPF_X:
		r->A >>= r->X;
		break;
	case BPF_ALU_RSH | BPF_K:
		r->A >>= K;
		break;
	case BPF_ALU_ADD | BPF_X:
		r->A += r->X;
		break;
	case BPF_ALU_ADD | BPF_K:
		r->A += K;
		break;
	case BPF_ALU_SUB | BPF_X:
		r->A -= r->X;
		break;
	case BPF_ALU_SUB | BPF_K:
		r->A -= K;
		break;
	case BPF_ALU_MUL | BPF_X:
		r->A *= r->X;
		break;
	case BPF_ALU_MUL | BPF_K:
		r->A *= K;
		break;
	case BPF_ALU_DIV | BPF_X:
	case BPF_ALU_MOD | BPF_X:
		if (r->X == 0) {
			set_return(r);
			break;
		}
		goto do_div;
	case BPF_ALU_DIV | BPF_K:
	case BPF_ALU_MOD | BPF_K:
		if (K == 0) {
			set_return(r);
			break;
		}
do_div:
		switch (f->code) {
		case BPF_ALU_DIV | BPF_X:
			r->A /= r->X;
			break;
		case BPF_ALU_DIV | BPF_K:
			r->A /= K;
			break;
		case BPF_ALU_MOD | BPF_X:
			r->A %= r->X;
			break;
		case BPF_ALU_MOD | BPF_K:
			r->A %= K;
			break;
		}
		break;
	case BPF_ALU_AND | BPF_X:
		r->A &= r->X;
		break;
	case BPF_ALU_AND | BPF_K:
		r->A &= K;
		break;
	case BPF_ALU_OR | BPF_X:
		r->A |= r->X;
		break;
	case BPF_ALU_OR | BPF_K:
		r->A |= K;
		break;
	case BPF_ALU_XOR | BPF_X:
		r->A ^= r->X;
		break;
	case BPF_ALU_XOR | BPF_K:
		r->A ^= K;
		break;
	}
}

static bool bpf_pc_has_breakpoint(uint16_t pc)
{
	int i;

	for (i = 0; i < array_size(bpf_breakpoints); i++) {
		if (bpf_breakpoints[i] < 0)
			continue;
		if (bpf_breakpoints[i] == pc)
			return true;
	}

	return false;
}

static bool bpf_handle_breakpoint(struct bpf_regs *r, struct sock_filter *f,
				  uint8_t *pkt, uint32_t pkt_caplen,
				  uint32_t pkt_len)
{
	rl_printf("-- register dump --\n");
	bpf_dump_curr(r, &f[r->Pc]);
	rl_printf("-- packet dump --\n");
	bpf_dump_pkt(pkt, pkt_caplen, pkt_len);
	rl_printf("(breakpoint)\n");
	return true;
}

static int bpf_run_all(struct sock_filter *f, uint16_t bpf_len, uint8_t *pkt,
		       uint32_t pkt_caplen, uint32_t pkt_len)
{
	bool stop = false;

	while (bpf_curr.Rs == false && stop == false) {
		bpf_safe_regs();

		if (bpf_pc_has_breakpoint(bpf_curr.Pc))
			stop = bpf_handle_breakpoint(&bpf_curr, f, pkt,
						     pkt_caplen, pkt_len);

		bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen,
				pkt_len);
		bpf_curr.Pc++;
	}

	return stop ? -1 : bpf_curr.R;
}

static int bpf_run_stepping(struct sock_filter *f, uint16_t bpf_len,
			    uint8_t *pkt, uint32_t pkt_caplen,
			    uint32_t pkt_len, int next)
{
	bool stop = false;
	int i = 1;

	while (bpf_curr.Rs == false && stop == false) {
		bpf_safe_regs();

		if (i++ == next)
			stop = bpf_handle_breakpoint(&bpf_curr, f, pkt,
						     pkt_caplen, pkt_len);

		bpf_single_step(&bpf_curr, &f[bpf_curr.Pc], pkt, pkt_caplen,
				pkt_len);
		bpf_curr.Pc++;
	}

	return stop ? -1 : bpf_curr.R;
}

static bool pcap_loaded(void)
{
	if (pcap_fd < 0)
		rl_printf("no pcap file loaded!\n");

	return pcap_fd >= 0;
}

static struct pcap_pkthdr *pcap_curr_pkt(void)
{
	return (void *) pcap_ptr_va_curr;
}

static bool pcap_next_pkt(void)
{
	struct pcap_pkthdr *hdr = pcap_curr_pkt();

	if (pcap_ptr_va_curr + sizeof(*hdr) -
	    pcap_ptr_va_start >= pcap_map_size)
		return false;
	if (hdr->caplen == 0 || hdr->len == 0 || hdr->caplen > hdr->len)
		return false;
	if (pcap_ptr_va_curr + sizeof(*hdr) + hdr->caplen -
	    pcap_ptr_va_start >= pcap_map_size)
		return false;

	pcap_ptr_va_curr += (sizeof(*hdr) + hdr->caplen);
	return true;
}

static void pcap_reset_pkt(void)
{
	pcap_ptr_va_curr = pcap_ptr_va_start + sizeof(struct pcap_filehdr);
}

static int try_load_pcap(const char *file)
{
	struct pcap_filehdr *hdr;
	struct stat sb;
	int ret;

	pcap_fd = open(file, O_RDONLY);
	if (pcap_fd < 0) {
		rl_printf("cannot open pcap [%s]!\n", strerror(errno));
		return CMD_ERR;
	}

	ret = fstat(pcap_fd, &sb);
	if (ret < 0) {
		rl_printf("cannot fstat pcap file!\n");
		return CMD_ERR;
	}

	if (!S_ISREG(sb.st_mode)) {
		rl_printf("not a regular pcap file, duh!\n");
		return CMD_ERR;
	}

	pcap_map_size = sb.st_size;
	if (pcap_map_size <= sizeof(struct pcap_filehdr)) {
		rl_printf("pcap file too small!\n");
		return CMD_ERR;
	}

	pcap_ptr_va_start = mmap(NULL, pcap_map_size, PROT_READ,
				 MAP_SHARED | MAP_LOCKED, pcap_fd, 0);
	if (pcap_ptr_va_start == MAP_FAILED) {
		rl_printf("mmap of file failed!");
		return CMD_ERR;
	}

	hdr = (void *) pcap_ptr_va_start;
	if (hdr->magic != TCPDUMP_MAGIC) {
		rl_printf("wrong pcap magic!\n");
		return CMD_ERR;
	}

	pcap_reset_pkt();

	return CMD_OK;

}

static void try_close_pcap(void)
{
	if (pcap_fd >= 0) {
		munmap(pcap_ptr_va_start, pcap_map_size);
		close(pcap_fd);

		pcap_ptr_va_start = pcap_ptr_va_curr = NULL;
		pcap_map_size = 0;
		pcap_packet = 0;
		pcap_fd = -1;
	}
}

static int cmd_load_bpf(char *bpf_string)
{
	char sp, *token, separator = ',';
	unsigned short bpf_len, i = 0;
	struct sock_filter tmp;

	bpf_prog_len = 0;
	memset(bpf_image, 0, sizeof(bpf_image));

	if (sscanf(bpf_string, "%hu%c", &bpf_len, &sp) != 2 ||
	    sp != separator || bpf_len > BPF_MAXINSNS || bpf_len == 0) {
		rl_printf("syntax error in head length encoding!\n");
		return CMD_ERR;
	}

	token = bpf_string;
	while ((token = strchr(token, separator)) && (++token)[0]) {
		if (i >= bpf_len) {
			rl_printf("program exceeds encoded length!\n");
			return CMD_ERR;
		}

		if (sscanf(token, "%hu %hhu %hhu %u,",
			   &tmp.code, &tmp.jt, &tmp.jf, &tmp.k) != 4) {
			rl_printf("syntax error at instruction %d!\n", i);
			return CMD_ERR;
		}

		bpf_image[i].code = tmp.code;
		bpf_image[i].jt = tmp.jt;
		bpf_image[i].jf = tmp.jf;
		bpf_image[i].k = tmp.k;

		i++;
	}

	if (i != bpf_len) {
		rl_printf("syntax error exceeding encoded length!\n");
		return CMD_ERR;
	} else
		bpf_prog_len = bpf_len;
	if (!bpf_runnable(bpf_image, bpf_prog_len))
		bpf_prog_len = 0;

	return CMD_OK;
}

static int cmd_load_pcap(char *file)
{
	char *file_trim, *tmp;

	file_trim = strtok_r(file, " ", &tmp);
	if (file_trim == NULL)
		return CMD_ERR;

	try_close_pcap();

	return try_load_pcap(file_trim);
}

static int cmd_load(char *arg)
{
	char *subcmd, *cont = NULL, *tmp = strdup(arg);
	int ret = CMD_OK;

	subcmd = strtok_r(tmp, " ", &cont);
	if (subcmd == NULL)
		goto out;
	if (matches(subcmd, "bpf") == 0) {
		bpf_reset();
		bpf_reset_breakpoints();

		if (!cont)
			ret = CMD_ERR;
		else
			ret = cmd_load_bpf(cont);
	} else if (matches(subcmd, "pcap") == 0) {
		ret = cmd_load_pcap(cont);
	} else {
out:
		rl_printf("bpf <code>:  load bpf code\n");
		rl_printf("pcap <file>: load pcap file\n");
		ret = CMD_ERR;
	}

	free(tmp);
	return ret;
}

static int cmd_step(char *num)
{
	struct pcap_pkthdr *hdr;
	int steps, ret;

	if (!bpf_prog_loaded() || !pcap_loaded())
		return CMD_ERR;

	steps = strtol(num, NULL, 10);
	if (steps == 0 || strlen(num) == 0)
		steps = 1;
	if (steps < 0) {
		if (!bpf_restore_regs(steps))
			return CMD_ERR;
		steps = 1;
	}

	hdr = pcap_curr_pkt();
	ret = bpf_run_stepping(bpf_image, bpf_prog_len,
			       (uint8_t *) hdr + sizeof(*hdr),
			       hdr->caplen, hdr->len, steps);
	if (ret >= 0 || bpf_curr.Rs) {
		bpf_reset();
		if (!pcap_next_pkt()) {
			rl_printf("(going back to first packet)\n");
			pcap_reset_pkt();
		} else {
			rl_printf("(next packet)\n");
		}
	}

	return CMD_OK;
}

static int cmd_select(char *num)
{
	unsigned int which, i;
	bool have_next = true;

	if (!pcap_loaded() || strlen(num) == 0)
		return CMD_ERR;

	which = strtoul(num, NULL, 10);
	if (which == 0) {
		rl_printf("packet count starts with 1, clamping!\n");
		which = 1;
	}

	pcap_reset_pkt();
	bpf_reset();

	for (i = 0; i < which && (have_next = pcap_next_pkt()); i++)
		/* noop */;
	if (!have_next || pcap_curr_pkt() == NULL) {
		rl_printf("no packet #%u available!\n", which);
		pcap_reset_pkt();
		return CMD_ERR;
	}

	return CMD_OK;
}

static int cmd_breakpoint(char *subcmd)
{
	if (!bpf_prog_loaded())
		return CMD_ERR;
	if (strlen(subcmd) == 0)
		bpf_dump_breakpoints();
	else if (matches(subcmd, "reset") == 0)
		bpf_reset_breakpoints();
	else {
		unsigned int where = strtoul(subcmd, NULL, 10);

		if (where < bpf_prog_len) {
			bpf_set_breakpoints(where);
			rl_printf("breakpoint at: ");
			bpf_disasm(bpf_image[where], where);
		}
	}

	return CMD_OK;
}

static int cmd_run(char *num)
{
	static uint32_t pass, fail;
	bool has_limit = true;
	int pkts = 0, i = 0;

	if (!bpf_prog_loaded() || !pcap_loaded())
		return CMD_ERR;

	pkts = strtol(num, NULL, 10);
	if (pkts == 0 || strlen(num) == 0)
		has_limit = false;

	do {
		struct pcap_pkthdr *hdr = pcap_curr_pkt();
		int ret = bpf_run_all(bpf_image, bpf_prog_len,
				      (uint8_t *) hdr + sizeof(*hdr),
				      hdr->caplen, hdr->len);
		if (ret > 0)
			pass++;
		else if (ret == 0)
			fail++;
		else
			return CMD_OK;
		bpf_reset();
	} while (pcap_next_pkt() && (!has_limit || (has_limit && ++i < pkts)));

	rl_printf("bpf passes:%u fails:%u\n", pass, fail);

	pcap_reset_pkt();
	bpf_reset();

	pass = fail = 0;
	return CMD_OK;
}

static int cmd_disassemble(char *line_string)
{
	bool single_line = false;
	unsigned long line;

	if (!bpf_prog_loaded())
		return CMD_ERR;
	if (strlen(line_string) > 0 &&
	    (line = strtoul(line_string, NULL, 10)) < bpf_prog_len)
		single_line = true;
	if (single_line)
		bpf_disasm(bpf_image[line], line);
	else
		bpf_disasm_all(bpf_image, bpf_prog_len);

	return CMD_OK;
}

static int cmd_dump(char *dontcare)
{
	if (!bpf_prog_loaded())
		return CMD_ERR;

	bpf_dump_all(bpf_image, bpf_prog_len);

	return CMD_OK;
}

static int cmd_quit(char *dontcare)
{
	return CMD_EX;
}

static const struct shell_cmd cmds[] = {
	{ .name = "load", .func = cmd_load },
	{ .name = "select", .func = cmd_select },
	{ .name = "step", .func = cmd_step },
	{ .name = "run", .func = cmd_run },
	{ .name = "breakpoint", .func = cmd_breakpoint },
	{ .name = "disassemble", .func = cmd_disassemble },
	{ .name = "dump", .func = cmd_dump },
	{ .name = "quit", .func = cmd_quit },
};

static int execf(char *arg)
{
	char *cmd, *cont, *tmp = strdup(arg);
	int i, ret = 0, len;

	cmd = strtok_r(tmp, " ", &cont);
	if (cmd == NULL)
		goto out;
	len = strlen(cmd);
	for (i = 0; i < array_size(cmds); i++) {
		if (len != strlen(cmds[i].name))
			continue;
		if (strncmp(cmds[i].name, cmd, len) == 0) {
			ret = cmds[i].func(cont);
			break;
		}
	}
out:
	free(tmp);
	return ret;
}

static char *shell_comp_gen(const char *buf, int state)
{
	static int list_index, len;

	if (!state) {
		list_index = 0;
		len = strlen(buf);
	}

	for (; list_index < array_size(cmds); ) {
		const char *name = cmds[list_index].name;

		list_index++;
		if (strncmp(name, buf, len) == 0)
			return strdup(name);
	}

	return NULL;
}

static char **shell_completion(const char *buf, int start, int end)
{
	char **matches = NULL;

	if (start == 0)
		matches = rl_completion_matches(buf, shell_comp_gen);

	return matches;
}

static void intr_shell(int sig)
{
	if (rl_end)
		rl_kill_line(-1, 0);

	rl_crlf();
	rl_refresh_line(0, 0);
	rl_free_line_state();
}

static void init_shell(FILE *fin, FILE *fout)
{
	char file[128];

	snprintf(file, sizeof(file), "%s/.bpf_dbg_history", getenv("HOME"));
	read_history(file);

	rl_instream = fin;
	rl_outstream = fout;

	rl_readline_name = "bpf_dbg";
	rl_terminal_name = getenv("TERM");

	rl_catch_signals = 0;
	rl_catch_sigwinch = 1;

	rl_attempted_completion_function = shell_completion;

	rl_bind_key('\t', rl_complete);

	rl_bind_key_in_map('\t', rl_complete, emacs_meta_keymap);
	rl_bind_key_in_map('\033', rl_complete, emacs_meta_keymap);

	snprintf(file, sizeof(file), "%s/.bpf_dbg_init", getenv("HOME"));
	rl_read_init_file(file);

	rl_prep_terminal(0);
	rl_set_signals();

	signal(SIGINT, intr_shell);
}

static void exit_shell(FILE *fin, FILE *fout)
{
	char file[128];

	snprintf(file, sizeof(file), "%s/.bpf_dbg_history", getenv("HOME"));
	write_history(file);

	clear_history();
	rl_deprep_terminal();

	try_close_pcap();

	if (fin != stdin)
		fclose(fin);
	if (fout != stdout)
		fclose(fout);
}

static int run_shell_loop(FILE *fin, FILE *fout)
{
	char *buf;

	init_shell(fin, fout);

	while ((buf = readline("> ")) != NULL) {
		int ret = execf(buf);
		if (ret == CMD_EX)
			break;
		if (ret == CMD_OK && strlen(buf) > 0)
			add_history(buf);

		free(buf);
	}

	exit_shell(fin, fout);
	return 0;
}

int main(int argc, char **argv)
{
	FILE *fin = NULL, *fout = NULL;

	if (argc >= 2)
		fin = fopen(argv[1], "r");
	if (argc >= 3)
		fout = fopen(argv[2], "w");

	return run_shell_loop(fin ? : stdin, fout ? : stdout);
}

{'repo_name': 'google/ktsan', 'stars': '551', 'repo_language': 'C', 'file_name': 'irqsrcs_thm_9_0.h', 'mime_type': 'text/x-c', 'hash': -1713291155933897896, 'source_dataset': 'data'}


[general]
config_dir = "/share/conf"
id = <AUTOFILLED>

[log.console]
level = "debug"

[features]
allow_run_as_root = true

{'repo_name': 'scionproto/scion', 'stars': '178', 'repo_language': 'Go', 'file_name': 'daemon.proto', 'mime_type': 'text/x-java', 'hash': -7109738487831701099, 'source_dataset': 'data'}


[[compName]]
= --comp-name
:author: Artur Hefczyc <artur.hefczyc@tigase.net>
:version: v2.0, June 2014: Reformatted for AsciiDoc.
:date: 2013-02-09 21:54
:version: v2.1

:toc:
:numbered:
:website: http://tigase.net/

*Default value:* 'custom string.'

*Example:* +--comp-name-1 = muc+

*Possible values:* 'XMPP localnode string.'

*Description:* The --comp-name property is used to assign name 'name' to the non-standard component which is loaded by the server. It is normally used when you want to load components which are not loaded by the +config-type+ you use. Together with +--comp-class-1+ it allows you to load any extra component to your server configuration. Of course you can load more than just one component, just use +--comp-name-2+, +--comp-name-3+ and so on... Let's say you want to load the MUC component. You can then put give it a name: +muc+ and the setting would look like:

[source,bash]
-----
--comp-name-1 = muc
-----

*Available since:* 3.0.0

{'repo_name': 'YiChat/IM_Server_YiChat', 'stars': '165', 'repo_language': 'Java', 'file_name': 'tigase-server.postrm', 'mime_type': 'text/x-shellscript', 'hash': 6501462205060235783, 'source_dataset': 'data'}


import DataSet from '@antv/data-set';
import { Chart, registerShape, Util } from '@antv/g2';

function getTextAttrs(cfg) {
  return {
    ...cfg.defaultStyle,
    ...cfg.style,
    fontSize: cfg.data.size,
    text: cfg.data.text,
    textAlign: 'center',
    fontFamily: cfg.data.font,
    fill: cfg.color || cfg.defaultStyle.stroke,
    textBaseline: 'Alphabetic'
  };
}

// 给point注册一个词云的shape
registerShape('point', 'cloud', {
  draw(cfg, container) {
    const attrs = getTextAttrs(cfg);
    const textShape = container.addShape('text', {
      attrs: {
        ...attrs,
        x: cfg.x,
        y: cfg.y
      }
    });
    if (cfg.data.rotate) {
      Util.rotate(textShape, cfg.data.rotate * Math.PI / 180);
    }
    return textShape;
  }
});
fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/world-population.json')
  .then(res => res.json())
  .then(data => {
    const dv = new DataSet.View().source(data);
    const range = dv.range('value');
    const min = range[0];
    const max = range[1];
    dv.transform({
      type: 'tag-cloud',
      fields: ['x', 'value'],
      size: [600, 500],
      font: 'Verdana',
      padding: 0,
      timeInterval: 5000, // max execute time
      rotate() {
        let random = ~~(Math.random() * 4) % 4;
        if (random === 2) {
          random = 0;
        }
        return random * 90; // 0, 90, 270
      },
      fontSize(d) {
        if (d.value) {
          return ((d.value - min) / (max - min)) * (80 - 24) + 24;
        }
        return 0;
      }
    });
    const chart = new Chart({
      container: 'container',
      autoFit: false,
      width: 600,
      height: 500,
      padding: 0
    });
    chart.data(dv.rows);
    chart.scale({
      x: { nice: false },
      y: { nice: false }
    });
    chart.legend(false);
    chart.axis(false);
    chart.tooltip({
      showTitle: false,
      showMarkers: false
    });
    chart.coordinate().reflect();
    chart.point()
      .position('x*y')
      .color('CornflowerBlue')
      .shape('cloud')
      .tooltip('value*category');
    chart.interaction('element-active');
    chart.render();
  });

{'repo_name': 'antvis/G2', 'stars': '9859', 'repo_language': 'TypeScript', 'file_name': 'positive-negative.ts', 'mime_type': 'text/plain', 'hash': -6753025051266591835, 'source_dataset': 'data'}


/*
 * Copyright 2014 Treode, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.treode.async.io

import java.lang.{Integer => JavaInt}
import java.nio.ByteBuffer
import java.nio.channels._
import java.util.ArrayDeque
import java.util.concurrent.Future
import scala.collection.JavaConversions._
import scala.util.{Success, Failure}

import com.treode.async.Callback
import com.treode.async.implicits._
import com.treode.async.stubs.StubScheduler
import org.scalatest.Assertions._

/** ScalaMock refuses to mock AsynchronousFileChannel. */
class AsyncFileMock extends AsynchronousFileChannel {

  private class Expectation {
    def read (dst: ByteBuffer, position: Long) {
      Thread.dumpStack()
      assert (false, "Unexpected file read: " + AsyncFileMock.this)
    }
    def write (src: ByteBuffer, position: Long) {
      Thread.dumpStack()
      assert (false, "Unexpected file write: " + AsyncFileMock.this)
    }
    override def toString = "Expecting nothing."
  }

  private val expectations = new ArrayDeque [Expectation] ()
  private var completion: Callback [Int] = null

  def completeLast (v: Int) (implicit scheduler: StubScheduler) {
    completion.pass (v)
    scheduler.run()
  }

  def failLast (t: Throwable) (implicit scheduler: StubScheduler) {
    completion.fail (t)
    scheduler.run()
  }

  def expectRead (filePos: Long, bufPos: Int, bufLimit: Int) {
    expectations.add (new Expectation {
      override def read (dst: ByteBuffer, _filePos: Long) {
        assert (_filePos == filePos, s"Expected file position $filePos but got ${_filePos}")
        assert (dst.position == bufPos, s"Expected buffer position $bufPos but got ${dst.position}")
        assert (dst.limit == bufLimit, s"Expected buffer limit $bufLimit but got ${dst.limit}")
      }
      override def toString = "Expecting read" + (filePos, bufPos, bufLimit)
    })
  }

  def read [A] (dst: ByteBuffer, position: Long, attachment: A, handler: CompletionHandler [JavaInt, _ >: A]) {
    require (completion == null, "Pending callback on file.")
    require (!expectations.isEmpty, "No expectations.")
    expectations.remove().read (dst, position)
    completion = {
      case Success (result) =>
        completion = null;
        if (result > 0)
          dst.position (dst.position + result)
        handler.completed (result, attachment)
      case Failure (thrown) =>
        completion = null
        handler.failed (thrown, attachment)
    }}

  def expectWrite (filePos: Long, bufPos: Int, bufLimit: Int) {
    expectations.add (new Expectation {
      override def write (src: ByteBuffer, _filePos: Long) {
        assert (_filePos == filePos, s"Expected file position $filePos but got ${_filePos}")
        assert (src.position == bufPos, s"Expected buffer position $bufPos but got ${src.position}")
        assert (src.limit == bufLimit, s"Expected buffer limit $bufLimit but got ${src.limit}")
      }
      override def toString = "Expecting write" + (filePos, bufPos, bufLimit)
    })
  }

  def write [A] (src: ByteBuffer, position: Long, attachment: A, handler: CompletionHandler [JavaInt, _ >: A]) {
    require (completion == null, "Pending callback on file.")
    require (!expectations.isEmpty, "No expectations.")
    expectations.remove().write (src, position)
    completion = {
      case Success (result) =>
        completion = null
        if (result > 0)
          src.position (src.position + result)
        handler.completed (result, attachment)
      case Failure (thrown) =>
        completion = null
        handler.failed (thrown, attachment)
    }}

  def close(): Unit = ???
  def force (metaData: Boolean): Unit = ???
  def isOpen(): Boolean = ???
  def lock (position: Long, size: Long, shared: Boolean): Future [FileLock] = ???
  def lock [A] (position: Long, size: Long, shared: Boolean, attachment: A, handler: CompletionHandler [FileLock, _ >: A]): Unit = ???
  def read (dst: ByteBuffer, position: Long): Future [JavaInt] = ???
  def size (): Long = ???
  def truncate (size: Long): AsynchronousFileChannel = ???
  def tryLock (position: Long, size: Long, shared: Boolean): FileLock = ???
  def write (src: ByteBuffer, position: Long): Future [JavaInt] = ???

  override def toString = "AsyncFileMock" + (expectations mkString ("[", ",", "]"), completion)
}

{'repo_name': 'Treode/store', 'stars': '181', 'repo_language': 'Scala', 'file_name': 'SchemaParserSpec.scala', 'mime_type': 'text/x-pascal', 'hash': 4930078361449314730, 'source_dataset': 'data'}


module ApplicationHelper

	def resource_name
		:user
	end

	def resource
		@resource ||= User.new
	end

	def devise_mapping
		@devise_mapping ||= Devise.mappings[:user]
	end

end

{'repo_name': 'guardianproject/OSTel', 'stars': '114', 'repo_language': 'JavaScript', 'file_name': 'index.html', 'mime_type': 'text/html', 'hash': -8730282818800531924, 'source_dataset': 'data'}


/// Source : https://leetcode.com/problems/daily-temperatures/description/
/// Author : liuyubobobo
/// Time   : 2018-08-28

#include <iostream>
#include <vector>

using namespace std;

/// Binary Search the higher temperature
/// Time Complexity: O(n*t*logn) where n is the number of data and t is the max temperature
/// Space Complexity: O(n)
class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {

        vector<vector<int>> records;
        for(int i = 0 ; i <= 100 ; i ++){
            vector<int> empty_vec;
            records.push_back(empty_vec);
        }

        for(int i = 0 ; i < temperatures.size() ; i ++)
            records[temperatures[i]].push_back(i);

        vector<int> res;
        for(int i = 0 ; i < temperatures.size() ; i ++){
            int future = getWarmerDay(temperatures[i], i, records);
            if(future == -1)
                res.push_back(0);
            else
                res.push_back(future - i);
        }

        return res;
    }

private:
    int getWarmerDay(int t, int curDay, const vector<vector<int>>& records){

        int res = INT_MAX;
        for(int i = t + 1 ; i <= 100 ; i ++){
            vector<int>::const_iterator iter = upper_bound(records[i].begin(), records[i].end(), curDay);
            if(iter != records[i].end())
                res = min(res, *iter);
        }

        return res == INT_MAX ? -1 : res;
    }
};

void printVec(const vector<int>& vec){
    for(int e: vec)
        cout << e << " ";
    cout << endl;
}

int main() {

    vector<int> vec = {73, 74, 75, 71, 69, 72, 76, 73};
    printVec(Solution().dailyTemperatures(vec));
    // 1 1 4 2 1 1 0 0

    return 0;
}

{'repo_name': 'liuyubobobo/Play-Leetcode', 'stars': '1583', 'repo_language': 'C++', 'file_name': 'CMakeLists.txt', 'mime_type': 'text/plain', 'hash': 7839650241401937795, 'source_dataset': 'data'}


///////////////////////////////////////////////////////////////////////////////
// as_action.hpp
//
//  Copyright 2008 Eric Niebler.
//  Copyright 2008 David Jenkins.
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_ACTION_HPP_EAN_04_05_2007
#define BOOST_XPRESSIVE_DETAIL_STATIC_TRANSFORMS_AS_ACTION_HPP_EAN_04_05_2007

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/mpl/sizeof.hpp>
#include <boost/mpl/min_max.hpp>
#include <boost/mpl/apply_wrap.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/matcher/attr_end_matcher.hpp>
#include <boost/xpressive/detail/static/static.hpp>
#include <boost/xpressive/detail/static/transforms/as_quantifier.hpp>
#include <boost/proto/core.hpp>
#include <boost/proto/transform/arg.hpp>
#include <boost/proto/transform/call.hpp>
#include <boost/proto/transform/make.hpp>
#include <boost/proto/transform/when.hpp>
#include <boost/proto/transform/fold.hpp>
#include <boost/proto/transform/fold_tree.hpp>

namespace boost { namespace xpressive { namespace detail
{
    ///////////////////////////////////////////////////////////////////////////////
    // read_attr
    //  Placeholder that knows the slot number of an attribute as well as the type
    //  of the object stored in it.
    template<typename Nbr, typename Matcher>
    struct read_attr
    {
        typedef Nbr nbr_type;
        typedef Matcher matcher_type;
        static Nbr nbr() { return Nbr(); }
    };

    template<typename Nbr, typename Matcher>
    struct read_attr<Nbr, Matcher &>
    {
        typedef Nbr nbr_type;
        typedef Matcher matcher_type;
    };

}}}

namespace boost { namespace xpressive { namespace grammar_detail
{
    ///////////////////////////////////////////////////////////////////////////////
    // FindAttr
    //  Look for patterns like (a1= terminal<RHS>) and return the type of the RHS.
    template<typename Nbr>
    struct FindAttr
      : or_<
            // Ignore nested actions, because attributes are scoped
            when< subscript<_, _>,                                  _state >
          , when< terminal<_>,                                      _state >
          , when< proto::assign<terminal<detail::attribute_placeholder<Nbr> >, _>, call<_value(_right)> >
          , otherwise< fold<_, _state, FindAttr<Nbr> > >
        >
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // as_read_attr
    //  For patterns like (a1 = RHS)[ref(i) = a1], transform to
    //  (a1 = RHS)[ref(i) = read_attr<1, RHS>] so that when reading the attribute
    //  we know what type is stored in the attribute slot.
    struct as_read_attr : proto::transform<as_read_attr>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename impl::expr expr_type;
            typedef
                typename FindAttr<typename expr_type::proto_child0::nbr_type>::template impl<
                    State
                  , mpl::void_
                  , int
                >::result_type
            attr_type;

            typedef
                typename proto::terminal<
                    detail::read_attr<
                        typename expr_type::proto_child0::nbr_type
                      , BOOST_PROTO_UNCVREF(attr_type)
                    >
                >::type
            result_type;

            result_type operator ()(proto::ignore, proto::ignore, proto::ignore) const
            {
                result_type that = {{}};
                return that;
            }
        };
    };

    ///////////////////////////////////////////////////////////////////////////////
    // DeepCopy
    //  Turn all refs into values, and also bind all attribute placeholders with
    //  the types from which they are being assigned.
    struct DeepCopy
      : or_<
            when< terminal<detail::attribute_placeholder<_> >,  as_read_attr>
          , when< terminal<_>,                                  proto::_deep_copy>
          , otherwise< nary_expr<_, vararg<DeepCopy> > >
        >
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // attr_nbr
    //  For an attribute placeholder, return the attribute's slot number.
    struct attr_nbr : proto::transform<attr_nbr>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename impl::expr expr_type;
            typedef typename expr_type::proto_child0::nbr_type::type result_type;
        };
    };

    struct max_attr;

    ///////////////////////////////////////////////////////////////////////////////
    // MaxAttr
    //  In an action (rx)[act], find the largest attribute slot being used.
    struct MaxAttr
      : or_<
            when< terminal<detail::attribute_placeholder<_> >, attr_nbr>
          , when< terminal<_>, make<mpl::int_<0> > >
            // Ignore nested actions, because attributes are scoped:
          , when< subscript<_, _>, make<mpl::int_<0> > >
          , otherwise< fold<_, make<mpl::int_<0> >, max_attr> >
        >
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // max_attr
    //  Take the maximum of the current attr slot number and the state.
    struct max_attr : proto::transform<max_attr>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef
                typename mpl::max<
                    typename impl::state
                  , typename MaxAttr::template impl<Expr, State, Data>::result_type
                >::type
            result_type;
        };
    };

    ///////////////////////////////////////////////////////////////////////////////
    // as_attr_matcher
    //  turn a1=matcher into attr_matcher<Matcher>(1)
    struct as_attr_matcher : proto::transform<as_attr_matcher>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename impl::expr expr_type;
            typedef typename impl::data data_type;
            typedef
                detail::attr_matcher<
                    typename proto::result_of::value<typename expr_type::proto_child1>::type
                  , typename data_type::traits_type
                  , typename data_type::icase_type
                >
            result_type;

            result_type operator ()(
                typename impl::expr_param expr
              , typename impl::state_param
              , typename impl::data_param data
            ) const
            {
                return result_type(
                    proto::value(proto::left(expr)).nbr()
                  , proto::value(proto::right(expr))
                  , data.traits()
                );
            }
        };
    };

    ///////////////////////////////////////////////////////////////////////////////
    // add_attrs
    //  Wrap an expression in attr_begin_matcher/attr_end_matcher pair
    struct add_attrs : proto::transform<add_attrs>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef
                detail::attr_begin_matcher<
                    typename MaxAttr::template impl<Expr, mpl::int_<0>, int>::result_type
                >
            begin_type;

            typedef typename impl::expr expr_type;

            typedef
                typename shift_right<
                    typename terminal<begin_type>::type
                  , typename shift_right<
                        Expr
                      , terminal<detail::attr_end_matcher>::type
                    >::type
                >::type
            result_type;

            result_type operator ()(
                typename impl::expr_param expr
              , typename impl::state_param
              , typename impl::data_param
            ) const
            {
                begin_type begin;
                detail::attr_end_matcher end;
                result_type that = {{begin}, {expr, {end}}};
                return that;
            }
        };
    };

    ///////////////////////////////////////////////////////////////////////////////
    // InsertAttrs
    struct InsertAttrs
      : if_<MaxAttr, add_attrs, _>
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // CheckAssertion
    struct CheckAssertion
      : proto::function<terminal<detail::check_tag>, _>
    {};

    ///////////////////////////////////////////////////////////////////////////////
    // action_transform
    //  Turn A[B] into (mark_begin(n) >> A >> mark_end(n) >> action_matcher<B>(n))
    //  If A and B use attributes, wrap the above expression in
    //  a attr_begin_matcher<Count> / attr_end_matcher pair, where Count is
    //  the number of attribute slots used by the pattern/action.
    struct as_action : proto::transform<as_action>
    {
        template<typename Expr, typename State, typename Data>
        struct impl : proto::transform_impl<Expr, State, Data>
        {
            typedef typename proto::result_of::left<Expr>::type expr_type;
            typedef typename proto::result_of::right<Expr>::type action_type;

            typedef
                typename DeepCopy::impl<action_type, expr_type, int>::result_type
            action_copy_type;

            typedef
                typename InsertMark::impl<expr_type, State, Data>::result_type
            marked_expr_type;

            typedef
                typename mpl::if_c<
                    proto::matches<action_type, CheckAssertion>::value
                  , detail::predicate_matcher<action_copy_type>
                  , detail::action_matcher<action_copy_type>
                >::type
            matcher_type;

            typedef
                typename proto::shift_right<
                    marked_expr_type
                  , typename proto::terminal<matcher_type>::type
                >::type
            no_attr_type;

            typedef
                typename InsertAttrs::impl<no_attr_type, State, Data>::result_type
            result_type;

            result_type operator ()(
                typename impl::expr_param expr
              , typename impl::state_param state
              , typename impl::data_param data
            ) const
            {
                int dummy = 0;
                marked_expr_type marked_expr =
                    InsertMark::impl<expr_type, State, Data>()(proto::left(expr), state, data);

                no_attr_type that = {
                    marked_expr
                  , {
                        matcher_type(
                            DeepCopy::impl<action_type, expr_type, int>()(
                                proto::right(expr)
                              , proto::left(expr)
                              , dummy
                            )
                          , proto::value(proto::left(marked_expr)).mark_number_
                        )
                    }
                };
                return InsertAttrs::impl<no_attr_type, State, Data>()(that, state, data);
            }
        };
    };

}}}

#endif

{'repo_name': 'bumptop/BumpTop', 'stars': '337', 'repo_language': 'C++', 'file_name': 'windows.pro', 'mime_type': 'text/plain', 'hash': -3799511589655701863, 'source_dataset': 'data'}


// AFNetworkReachabilityManager.h
// Copyright (c) 2011–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>

#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>

#ifndef NS_DESIGNATED_INITIALIZER
#if __has_attribute(objc_designated_initializer)
#define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))
#else
#define NS_DESIGNATED_INITIALIZER
#endif
#endif

typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
    AFNetworkReachabilityStatusUnknown          = -1,
    AFNetworkReachabilityStatusNotReachable     = 0,
    AFNetworkReachabilityStatusReachableViaWWAN = 1,
    AFNetworkReachabilityStatusReachableViaWiFi = 2,
};

NS_ASSUME_NONNULL_BEGIN

/**
 `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces.

 Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability.

 See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/)

 @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined.
 */
@interface AFNetworkReachabilityManager : NSObject

/**
 The current network reachability status.
 */
@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus;

/**
 Whether or not the network is currently reachable.
 */
@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable;

/**
 Whether or not the network is currently reachable via WWAN.
 */
@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN;

/**
 Whether or not the network is currently reachable via WiFi.
 */
@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi;

///---------------------
/// @name Initialization
///---------------------

/**
 Returns the shared network reachability manager.
 */
+ (instancetype)sharedManager;

/**
 Creates and returns a network reachability manager for the specified domain.

 @param domain The domain used to evaluate network reachability.

 @return An initialized network reachability manager, actively monitoring the specified domain.
 */
+ (instancetype)managerForDomain:(NSString *)domain;

/**
 Creates and returns a network reachability manager for the socket address.

 @param address The socket address (`sockaddr_in`) used to evaluate network reachability.

 @return An initialized network reachability manager, actively monitoring the specified socket address.
 */
+ (instancetype)managerForAddress:(const void *)address;

/**
 Initializes an instance of a network reachability manager from the specified reachability object.

 @param reachability The reachability object to monitor.

 @return An initialized network reachability manager, actively monitoring the specified reachability.
 */
- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER;

///--------------------------------------------------
/// @name Starting & Stopping Reachability Monitoring
///--------------------------------------------------

/**
 Starts monitoring for changes in network reachability status.
 */
- (void)startMonitoring;

/**
 Stops monitoring for changes in network reachability status.
 */
- (void)stopMonitoring;

///-------------------------------------------------
/// @name Getting Localized Reachability Description
///-------------------------------------------------

/**
 Returns a localized string representation of the current network reachability status.
 */
- (NSString *)localizedNetworkReachabilityStatusString;

///---------------------------------------------------
/// @name Setting Network Reachability Change Callback
///---------------------------------------------------

/**
 Sets a callback to be executed when the network availability of the `baseURL` host changes.

 @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`.
 */
- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block;

@end

///----------------
/// @name Constants
///----------------

/**
 ## Network Reachability

 The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses.

 enum {
 AFNetworkReachabilityStatusUnknown,
 AFNetworkReachabilityStatusNotReachable,
 AFNetworkReachabilityStatusReachableViaWWAN,
 AFNetworkReachabilityStatusReachableViaWiFi,
 }

 `AFNetworkReachabilityStatusUnknown`
 The `baseURL` host reachability is not known.

 `AFNetworkReachabilityStatusNotReachable`
 The `baseURL` host cannot be reached.

 `AFNetworkReachabilityStatusReachableViaWWAN`
 The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS.

 `AFNetworkReachabilityStatusReachableViaWiFi`
 The `baseURL` host can be reached via a Wi-Fi connection.

 ### Keys for Notification UserInfo Dictionary

 Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification.

 `AFNetworkingReachabilityNotificationStatusItem`
 A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification.
 The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status.
 */

///--------------------
/// @name Notifications
///--------------------

/**
 Posted when network reachability changes.
 This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability.

 @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import <SystemConfiguration/SystemConfiguration.h>` to the header prefix of the project (`Prefix.pch`).
 */
extern NSString * const AFNetworkingReachabilityDidChangeNotification;
extern NSString * const AFNetworkingReachabilityNotificationStatusItem;

///--------------------
/// @name Functions
///--------------------

/**
 Returns a localized string representation of an `AFNetworkReachabilityStatus` value.
 */
extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status);

NS_ASSUME_NONNULL_END
#endif

{'repo_name': 'agilie/AGLocationDispatcher', 'stars': '151', 'repo_language': 'Objective-C', 'file_name': 'contents.xcworkspacedata', 'mime_type': 'text/xml', 'hash': 4614841989286115512, 'source_dataset': 'data'}


#ifndef BOOST_DETAIL_LIGHTWEIGHT_MUTEX_HPP_INCLUDED
#define BOOST_DETAIL_LIGHTWEIGHT_MUTEX_HPP_INCLUDED

// MS compatible compilers support #pragma once

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

//
//  boost/detail/lightweight_mutex.hpp - lightweight mutex
//
//  Copyright (c) 2002, 2003 Peter Dimov and Multi Media Ltd.
//
//  Distributed under the Boost Software License, Version 1.0.
//  See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt
//

#include <boost/smart_ptr/detail/lightweight_mutex.hpp>

#endif // #ifndef BOOST_DETAIL_LIGHTWEIGHT_MUTEX_HPP_INCLUDED

{'repo_name': 'LiangliangNan/MVStudio', 'stars': '128', 'repo_language': 'C++', 'file_name': 'K.txt', 'mime_type': 'text/plain', 'hash': -8602608764821631406, 'source_dataset': 'data'}