text:
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <asm/dbdma.h>
#include <asm/io.h>
#include <asm/pgtable.h>
#include <asm/prom.h>
#include <asm/system.h>
#include <asm/pci-bridge.h>
#include <asm/macio.h>

#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>

#include "mac53c94.h"

enum fsc_phase {
	idle,
	selecting,
	dataing,
	completing,
	busfreeing,
};

struct fsc_state {
	struct	mac53c94_regs __iomem *regs;
	int	intr;
	struct	dbdma_regs __iomem *dma;
	int	dmaintr;
	int	clk_freq;
	struct	Scsi_Host *host;
	struct scsi_cmnd *request_q;
	struct scsi_cmnd *request_qtail;
	struct scsi_cmnd *current_req;		/* req we're currently working on */
	enum fsc_phase phase;		/* what we're currently trying to do */
	struct dbdma_cmd *dma_cmds;	/* space for dbdma commands, aligned */
	void	*dma_cmd_space;
	struct	pci_dev *pdev;
	dma_addr_t dma_addr;
	struct macio_dev *mdev;
};

static void mac53c94_init(struct fsc_state *);
static void mac53c94_start(struct fsc_state *);
static void mac53c94_interrupt(int, void *);
static irqreturn_t do_mac53c94_interrupt(int, void *);
static void cmd_done(struct fsc_state *, int result);
static void set_dma_cmds(struct fsc_state *, struct scsi_cmnd *);

static int mac53c94_queue_lck(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
{
	struct fsc_state *state;

#if 0
	if (cmd->sc_data_direction == DMA_TO_DEVICE) {
		int i;
		printk(KERN_DEBUG "mac53c94_queue %p: command is", cmd);
		for (i = 0; i < cmd->cmd_len; ++i)
			printk(KERN_CONT " %.2x", cmd->cmnd[i]);
		printk(KERN_CONT "\n");
		printk(KERN_DEBUG "use_sg=%d request_bufflen=%d request_buffer=%p\n",
		       scsi_sg_count(cmd), scsi_bufflen(cmd), scsi_sglist(cmd));
	}
#endif

	cmd->scsi_done = done;
	cmd->host_scribble = NULL;

	state = (struct fsc_state *) cmd->device->host->hostdata;

	if (state->request_q == NULL)
		state->request_q = cmd;
	else
		state->request_qtail->host_scribble = (void *) cmd;
	state->request_qtail = cmd;

	if (state->phase == idle)
		mac53c94_start(state);

	return 0;
}

static DEF_SCSI_QCMD(mac53c94_queue)

static int mac53c94_host_reset(struct scsi_cmnd *cmd)
{
	struct fsc_state *state = (struct fsc_state *) cmd->device->host->hostdata;
	struct mac53c94_regs __iomem *regs = state->regs;
	struct dbdma_regs __iomem *dma = state->dma;
	unsigned long flags;

	spin_lock_irqsave(cmd->device->host->host_lock, flags);

	writel((RUN|PAUSE|FLUSH|WAKE) << 16, &dma->control);
	writeb(CMD_SCSI_RESET, &regs->command);	/* assert RST */
	udelay(100);			/* leave it on for a while (>= 25us) */
	writeb(CMD_RESET, &regs->command);
	udelay(20);
	mac53c94_init(state);
	writeb(CMD_NOP, &regs->command);

	spin_unlock_irqrestore(cmd->device->host->host_lock, flags);
	return SUCCESS;
}

static void mac53c94_init(struct fsc_state *state)
{
	struct mac53c94_regs __iomem *regs = state->regs;
	struct dbdma_regs __iomem *dma = state->dma;
	int x;

	writeb(state->host->this_id | CF1_PAR_ENABLE, &regs->config1);
	writeb(TIMO_VAL(250), &regs->sel_timeout);	/* 250ms */
	writeb(CLKF_VAL(state->clk_freq), &regs->clk_factor);
	writeb(CF2_FEATURE_EN, &regs->config2);
	writeb(0, &regs->config3);
	writeb(0, &regs->sync_period);
	writeb(0, &regs->sync_offset);
	x = readb(&regs->interrupt);
	writel((RUN|PAUSE|FLUSH|WAKE) << 16, &dma->control);
}

/*
 * Start the next command for a 53C94.
 * Should be called with interrupts disabled.
 */
static void mac53c94_start(struct fsc_state *state)
{
	struct scsi_cmnd *cmd;
	struct mac53c94_regs __iomem *regs = state->regs;
	int i;

	if (state->phase != idle || state->current_req != NULL)
		panic("inappropriate mac53c94_start (state=%p)", state);
	if (state->request_q == NULL)
		return;
	state->current_req = cmd = state->request_q;
	state->request_q = (struct scsi_cmnd *) cmd->host_scribble;

	/* Off we go */
	writeb(0, &regs->count_lo);
	writeb(0, &regs->count_mid);
	writeb(0, &regs->count_hi);
	writeb(CMD_NOP + CMD_DMA_MODE, &regs->command);
	udelay(1);
	writeb(CMD_FLUSH, &regs->command);
	udelay(1);
	writeb(cmd->device->id, &regs->dest_id);
	writeb(0, &regs->sync_period);
	writeb(0, &regs->sync_offset);

	/* load the command into the FIFO */
	for (i = 0; i < cmd->cmd_len; ++i)
		writeb(cmd->cmnd[i], &regs->fifo);

	/* do select without ATN XXX */
	writeb(CMD_SELECT, &regs->command);
	state->phase = selecting;

	set_dma_cmds(state, cmd);
}

static irqreturn_t do_mac53c94_interrupt(int irq, void *dev_id)
{
	unsigned long flags;
	struct Scsi_Host *dev = ((struct fsc_state *) dev_id)->current_req->device->host;

	spin_lock_irqsave(dev->host_lock, flags);
	mac53c94_interrupt(irq, dev_id);
	spin_unlock_irqrestore(dev->host_lock, flags);
	return IRQ_HANDLED;
}

static void mac53c94_interrupt(int irq, void *dev_id)
{
	struct fsc_state *state = (struct fsc_state *) dev_id;
	struct mac53c94_regs __iomem *regs = state->regs;
	struct dbdma_regs __iomem *dma = state->dma;
	struct scsi_cmnd *cmd = state->current_req;
	int nb, stat, seq, intr;
	static int mac53c94_errors;

	/*
	 * Apparently, reading the interrupt register unlatches
	 * the status and sequence step registers.
	 */
	seq = readb(&regs->seqstep);
	stat = readb(&regs->status);
	intr = readb(&regs->interrupt);

#if 0
	printk(KERN_DEBUG "mac53c94_intr, intr=%x stat=%x seq=%x phase=%d\n",
	       intr, stat, seq, state->phase);
#endif

	if (intr & INTR_RESET) {
		/* SCSI bus was reset */
		printk(KERN_INFO "external SCSI bus reset detected\n");
		writeb(CMD_NOP, &regs->command);
		writel(RUN << 16, &dma->control);	/* stop dma */
		cmd_done(state, DID_RESET << 16);
		return;
	}
	if (intr & INTR_ILL_CMD) {
		printk(KERN_ERR "53c94: invalid cmd, intr=%x stat=%x seq=%x phase=%d\n",
		       intr, stat, seq, state->phase);
		cmd_done(state, DID_ERROR << 16);
		return;
	}
	if (stat & STAT_ERROR) {
#if 0
		/* XXX these seem to be harmless? */
		printk("53c94: bad error, intr=%x stat=%x seq=%x phase=%d\n",
		       intr, stat, seq, state->phase);
#endif
		++mac53c94_errors;
		writeb(CMD_NOP + CMD_DMA_MODE, &regs->command);
	}
	if (cmd == 0) {
		printk(KERN_DEBUG "53c94: interrupt with no command active?\n");
		return;
	}
	if (stat & STAT_PARITY) {
		printk(KERN_ERR "mac53c94: parity error\n");
		cmd_done(state, DID_PARITY << 16);
		return;
	}
	switch (state->phase) {
	case selecting:
		if (intr & INTR_DISCONNECT) {
			/* selection timed out */
			cmd_done(state, DID_BAD_TARGET << 16);
			return;
		}
		if (intr != INTR_BUS_SERV + INTR_DONE) {
			printk(KERN_DEBUG "got intr %x during selection\n", intr);
			cmd_done(state, DID_ERROR << 16);
			return;
		}
		if ((seq & SS_MASK) != SS_DONE) {
			printk(KERN_DEBUG "seq step %x after command\n", seq);
			cmd_done(state, DID_ERROR << 16);
			return;
		}
		writeb(CMD_NOP, &regs->command);
		/* set DMA controller going if any data to transfer */
		if ((stat & (STAT_MSG|STAT_CD)) == 0
		    && (scsi_sg_count(cmd) > 0 || scsi_bufflen(cmd))) {
			nb = cmd->SCp.this_residual;
			if (nb > 0xfff0)
				nb = 0xfff0;
			cmd->SCp.this_residual -= nb;
			writeb(nb, &regs->count_lo);
			writeb(nb >> 8, &regs->count_mid);
			writeb(CMD_DMA_MODE + CMD_NOP, &regs->command);
			writel(virt_to_phys(state->dma_cmds), &dma->cmdptr);
			writel((RUN << 16) | RUN, &dma->control);
			writeb(CMD_DMA_MODE + CMD_XFER_DATA, &regs->command);
			state->phase = dataing;
			break;
		} else if ((stat & STAT_PHASE) == STAT_CD + STAT_IO) {
			/* up to status phase already */
			writeb(CMD_I_COMPLETE, &regs->command);
			state->phase = completing;
		} else {
			printk(KERN_DEBUG "in unexpected phase %x after cmd\n",
			       stat & STAT_PHASE);
			cmd_done(state, DID_ERROR << 16);
			return;
		}
		break;

	case dataing:
		if (intr != INTR_BUS_SERV) {
			printk(KERN_DEBUG "got intr %x before status\n", intr);
			cmd_done(state, DID_ERROR << 16);
			return;
		}
		if (cmd->SCp.this_residual != 0
		    && (stat & (STAT_MSG|STAT_CD)) == 0) {
			/* Set up the count regs to transfer more */
			nb = cmd->SCp.this_residual;
			if (nb > 0xfff0)
				nb = 0xfff0;
			cmd->SCp.this_residual -= nb;
			writeb(nb, &regs->count_lo);
			writeb(nb >> 8, &regs->count_mid);
			writeb(CMD_DMA_MODE + CMD_NOP, &regs->command);
			writeb(CMD_DMA_MODE + CMD_XFER_DATA, &regs->command);
			break;
		}
		if ((stat & STAT_PHASE) != STAT_CD + STAT_IO) {
			printk(KERN_DEBUG "intr %x before data xfer complete\n", intr);
		}
		writel(RUN << 16, &dma->control);	/* stop dma */
		scsi_dma_unmap(cmd);
		/* should check dma status */
		writeb(CMD_I_COMPLETE, &regs->command);
		state->phase = completing;
		break;
	case completing:
		if (intr != INTR_DONE) {
			printk(KERN_DEBUG "got intr %x on completion\n", intr);
			cmd_done(state, DID_ERROR << 16);
			return;
		}
		cmd->SCp.Status = readb(&regs->fifo);
		cmd->SCp.Message = readb(&regs->fifo);
		cmd->result = CMD_ACCEPT_MSG;
		writeb(CMD_ACCEPT_MSG, &regs->command);
		state->phase = busfreeing;
		break;
	case busfreeing:
		if (intr != INTR_DISCONNECT) {
			printk(KERN_DEBUG "got intr %x when expected disconnect\n", intr);
		}
		cmd_done(state, (DID_OK << 16) + (cmd->SCp.Message << 8)
			 + cmd->SCp.Status);
		break;
	default:
		printk(KERN_DEBUG "don't know about phase %d\n", state->phase);
	}
}

static void cmd_done(struct fsc_state *state, int result)
{
	struct scsi_cmnd *cmd;

	cmd = state->current_req;
	if (cmd != 0) {
		cmd->result = result;
		(*cmd->scsi_done)(cmd);
		state->current_req = NULL;
	}
	state->phase = idle;
	mac53c94_start(state);
}

/*
 * Set up DMA commands for transferring data.
 */
static void set_dma_cmds(struct fsc_state *state, struct scsi_cmnd *cmd)
{
	int i, dma_cmd, total, nseg;
	struct scatterlist *scl;
	struct dbdma_cmd *dcmds;
	dma_addr_t dma_addr;
	u32 dma_len;

	nseg = scsi_dma_map(cmd);
	BUG_ON(nseg < 0);
	if (!nseg)
		return;

	dma_cmd = cmd->sc_data_direction == DMA_TO_DEVICE ?
			OUTPUT_MORE : INPUT_MORE;
	dcmds = state->dma_cmds;
	total = 0;

	scsi_for_each_sg(cmd, scl, nseg, i) {
		dma_addr = sg_dma_address(scl);
		dma_len = sg_dma_len(scl);
		if (dma_len > 0xffff)
			panic("mac53c94: scatterlist element >= 64k");
		total += dma_len;
		st_le16(&dcmds->req_count, dma_len);
		st_le16(&dcmds->command, dma_cmd);
		st_le32(&dcmds->phy_addr, dma_addr);
		dcmds->xfer_status = 0;
		++dcmds;
	}

	dma_cmd += OUTPUT_LAST - OUTPUT_MORE;
	st_le16(&dcmds[-1].command, dma_cmd);
	st_le16(&dcmds->command, DBDMA_STOP);
	cmd->SCp.this_residual = total;
}

static struct scsi_host_template mac53c94_template = {
	.proc_name	= "53c94",
	.name		= "53C94",
	.queuecommand	= mac53c94_queue,
	.eh_host_reset_handler = mac53c94_host_reset,
	.can_queue	= 1,
	.this_id	= 7,
	.sg_tablesize	= SG_ALL,
	.cmd_per_lun	= 1,
	.use_clustering	= DISABLE_CLUSTERING,
};

static int mac53c94_probe(struct macio_dev *mdev, const struct of_device_id *match)
{
	struct device_node *node = macio_get_of_node(mdev);
	struct pci_dev *pdev = macio_get_pci_dev(mdev);
	struct fsc_state *state;
	struct Scsi_Host *host;
	void *dma_cmd_space;
	const unsigned char *clkprop;
	int proplen, rc = -ENODEV;

	if (macio_resource_count(mdev) != 2 || macio_irq_count(mdev) != 2) {
		printk(KERN_ERR "mac53c94: expected 2 addrs and intrs"
		       " (got %d/%d)\n",
		       macio_resource_count(mdev), macio_irq_count(mdev));
		return -ENODEV;
	}

	if (macio_request_resources(mdev, "mac53c94") != 0) {
       		printk(KERN_ERR "mac53c94: unable to request memory resources");
		return -EBUSY;
	}

       	host = scsi_host_alloc(&mac53c94_template, sizeof(struct fsc_state));
	if (host == NULL) {
		printk(KERN_ERR "mac53c94: couldn't register host");
		rc = -ENOMEM;
		goto out_release;
	}

	state = (struct fsc_state *) host->hostdata;
	macio_set_drvdata(mdev, state);
	state->host = host;
	state->pdev = pdev;
	state->mdev = mdev;

	state->regs = (struct mac53c94_regs __iomem *)
		ioremap(macio_resource_start(mdev, 0), 0x1000);
	state->intr = macio_irq(mdev, 0);
	state->dma = (struct dbdma_regs __iomem *)
		ioremap(macio_resource_start(mdev, 1), 0x1000);
	state->dmaintr = macio_irq(mdev, 1);
	if (state->regs == NULL || state->dma == NULL) {
		printk(KERN_ERR "mac53c94: ioremap failed for %s\n",
		       node->full_name);
		goto out_free;
	}

	clkprop = of_get_property(node, "clock-frequency", &proplen);
       	if (clkprop == NULL || proplen != sizeof(int)) {
       		printk(KERN_ERR "%s: can't get clock frequency, "
       		       "assuming 25MHz\n", node->full_name);
       		state->clk_freq = 25000000;
       	} else
       		state->clk_freq = *(int *)clkprop;

       	/* Space for dma command list: +1 for stop command,
       	 * +1 to allow for aligning.
	 * XXX FIXME: Use DMA consistent routines
	 */
       	dma_cmd_space = kmalloc((host->sg_tablesize + 2) *
       				sizeof(struct dbdma_cmd), GFP_KERNEL);
       	if (dma_cmd_space == 0) {
       		printk(KERN_ERR "mac53c94: couldn't allocate dma "
       		       "command space for %s\n", node->full_name);
		rc = -ENOMEM;
       		goto out_free;
       	}
	state->dma_cmds = (struct dbdma_cmd *)DBDMA_ALIGN(dma_cmd_space);
	memset(state->dma_cmds, 0, (host->sg_tablesize + 1)
	       * sizeof(struct dbdma_cmd));
	state->dma_cmd_space = dma_cmd_space;

	mac53c94_init(state);

	if (request_irq(state->intr, do_mac53c94_interrupt, 0, "53C94",state)) {
		printk(KERN_ERR "mac53C94: can't get irq %d for %s\n",
		       state->intr, node->full_name);
		goto out_free_dma;
	}

	rc = scsi_add_host(host, &mdev->ofdev.dev);
	if (rc != 0)
		goto out_release_irq;

	scsi_scan_host(host);
	return 0;

 out_release_irq:
	free_irq(state->intr, state);
 out_free_dma:
	kfree(state->dma_cmd_space);
 out_free:
	if (state->dma != NULL)
		iounmap(state->dma);
	if (state->regs != NULL)
		iounmap(state->regs);
	scsi_host_put(host);
 out_release:
	macio_release_resources(mdev);

	return rc;
}

static int mac53c94_remove(struct macio_dev *mdev)
{
	struct fsc_state *fp = (struct fsc_state *)macio_get_drvdata(mdev);
	struct Scsi_Host *host = fp->host;

	scsi_remove_host(host);

	free_irq(fp->intr, fp);

	if (fp->regs)
		iounmap(fp->regs);
	if (fp->dma)
		iounmap(fp->dma);
	kfree(fp->dma_cmd_space);

	scsi_host_put(host);

	macio_release_resources(mdev);

	return 0;
}

static struct of_device_id mac53c94_match[] =
{
	{
	.name 		= "53c94",
	},
	{},
};
MODULE_DEVICE_TABLE (of, mac53c94_match);

static struct macio_driver mac53c94_driver =
{
	.driver = {
		.name 		= "mac53c94",
		.owner		= THIS_MODULE,
		.of_match_table	= mac53c94_match,
	},
	.probe		= mac53c94_probe,
	.remove		= mac53c94_remove,
};

static int __init init_mac53c94(void)
{
	return macio_register_driver(&mac53c94_driver);
}

static void __exit exit_mac53c94(void)
{
	return macio_unregister_driver(&mac53c94_driver);
}

module_init(init_mac53c94);
module_exit(exit_mac53c94);

MODULE_DESCRIPTION("PowerMac 53c94 SCSI driver");
MODULE_AUTHOR("Paul Mackerras <paulus@samba.org>");
MODULE_LICENSE("GPL");


text: module.exports = require("github:aurelia/html-template-element@0.1.3/HTMLTemplateElement.min");

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: wliu
 * Date: 14-11-17
 * Time: 下午6:21
 */

namespace Rudder\Mvc\Intercept;

use Rudder\AppConstant;
use Rudder\Mvc\Message;
use Rudder\Mvc\ResponseApi;

class LoginInterceptor implements Interceptor{

    /**
     * 校验拦截器,用以传入参数的校验。
     * @param \Phalcon\Events\Event $event
     * @param \Phalcon\Mvc\Dispatcher $dispatcher
     * @param array $params
     * @return mixed
     */
    public function action($event,$dispatcher,$params) {
        //$module = $dispatcher->getModuleName();
        //$controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();
        if ($action=='auth') return;

        $auth = $dispatcher->getDI()->get(AppConstant::DI_SERVICE_SESSION)->get(AppConstant::HTTP_USER_AUTH);
        if (!$auth) {
            ResponseApi::sendErrorAndEnd(null,Message::$_ERROR_UNLOGIN);
        }
    }
}


text:
package org.osgi.service.useradmin;

/**
 * The {@code Authorization} interface encapsulates an authorization context on
 * which bundles can base authorization decisions, where appropriate.
 *

 * Bundles associate the privilege to access restricted resources or operations
 * with roles. Before granting access to a restricted resource or operation, a
 * bundle will check if the {@code Authorization} object passed to it possess
 * the required role, by calling its {@code hasRole} method.
 *

 * Authorization contexts are instantiated by calling the
 * {@link UserAdmin#getAuthorization(User)} method.
 *
 *

 * Trusting Authorization objects
 *

 * There are no restrictions regarding the creation of {@code Authorization}
 * objects. Hence, a service must only accept {@code Authorization} objects from
 * bundles that has been authorized to use the service using code based (or Java
 * 2) permissions.
 *
 *

 * In some cases it is useful to use {@code ServicePermission} to do the code
 * based access control. A service basing user access control on
 * {@code Authorization} objects passed to it, will then require that a calling
 * bundle has the {@code ServicePermission} to get the service in question. This
 * is the most convenient way. The OSGi environment will do the code based
 * permission check when the calling bundle attempts to get the service from the
 * service registry.
 *

 * Example: A servlet using a service on a user's behalf. The bundle with the
 * servlet must be given the {@code ServicePermission} to get the Http Service.
 *

 * However, in some cases the code based permission checks need to be more
 * fine-grained. A service might allow all bundles to get it, but require
 * certain code based permissions for some of its methods.
 *

 * Example: A servlet using a service on a user's behalf, where some service
 * functionality is open to anyone, and some is restricted by code based
 * permissions. When a restricted method is called (e.g., one handing over an
 * {@code Authorization} object), the service explicitly checks that the calling
 * bundle has permission to make the call.
 *
 * @noimplement
 * @author $Id$
 */
public interface Authorization {
	/**
	 * Gets the name of the {@link User} that this {@code Authorization} context
	 * was created for.
	 *
	 * @return The name of the {@link User} object that this
	 *         {@code Authorization} context was created for, or {@code null} if
	 *         no user was specified when this {@code Authorization} context was
	 *         created.
	 */
	public String getName();

	/**
	 * Checks if the role with the specified name is implied by this
	 * {@code Authorization} context.
	 *

	 *
	 * Bundles must define globally unique role names that are associated with
	 * the privilege of accessing restricted resources or operations. Operators
	 * will grant users access to these resources, by creating a {@link Group}
	 * object for each role and adding {@link User} objects to it.
	 *
	 * @param name The name of the role to check for.
	 *
	 * @return {@code true} if this {@code Authorization} context implies the
	 *         specified role, otherwise {@code false}.
	 */
	public boolean hasRole(String name);

	/**
	 * Gets the names of all roles implied by this {@code Authorization}
	 * context.
	 *
	 * @return The names of all roles implied by this {@code Authorization}
	 *         context, or {@code null} if no roles are in the context. The
	 *         predefined role {@code user.anyone} will not be included in this
	 *         list.
	 */
	public String[] getRoles();
}


text:
package org.softeg.slartus.forpdaplus.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.nineoldandroids.view.ViewPropertyAnimator;

import org.softeg.slartus.forpdaapi.NewsApi;
import org.softeg.slartus.forpdacommon.AdBlocker;
import org.softeg.slartus.forpdacommon.FileUtils;
import org.softeg.slartus.forpdacommon.PatternExtensions;
import org.softeg.slartus.forpdacommon.ShowInBrowserException;
import org.softeg.slartus.forpdaplus.App;
import org.softeg.slartus.forpdaplus.Client;
import org.softeg.slartus.forpdaplus.IntentActivity;
import org.softeg.slartus.forpdaplus.R;
import org.softeg.slartus.forpdaplus.classes.AdvWebView;
import org.softeg.slartus.forpdaplus.classes.History;
import org.softeg.slartus.forpdaplus.classes.HtmlBuilder;
import org.softeg.slartus.forpdaplus.classes.common.ExtUrl;
import org.softeg.slartus.forpdaplus.common.AppLog;
import org.softeg.slartus.forpdaplus.controls.imageview.ImgViewer;
import org.softeg.slartus.forpdaplus.prefs.Preferences;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by radiationx on 17.10.15.
 */
public class NewsFragment extends WebViewFragment implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    private static final String URL_KEY = "Url";

    private final Handler mHandler = new Handler();
    private AdvWebView webView;

    private Boolean m_FromHistory = false;
    private int m_ScrollY = 0;
    private int m_ScrollX = 0;
    private String m_NewsUrl;
    private final ArrayList<History> m_History = new ArrayList<>();
    private boolean loadImages;
    private String m_Title = App.getContext().getString(R.string.news);
    private FloatingActionButton fab;
    private FrameLayout buttonsPanel;

    public static NewsFragment newInstance(String url) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(URL_KEY, url);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public String getTitle() {
        return m_Title;
    }

    public String getUrl() {
        return m_NewsUrl;
    }

    @Override
    public void reload() {
        refresh();
    }

    @Override
    public boolean closeTab() {
        return false;
    }

    @Override
    public WebViewClient getWebViewClient() {
        return new MyWebViewClient();
    }

    public void refresh() {
        showNews(m_NewsUrl);
    }

    public AdvWebView getWebView() {
        return webView;
    }

    @Override
    public String Prefix() {
        return "news";
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        getMainActivity().setContentView(R.layout.main);
    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
        return false;
    }

    @SuppressLint("AddJavascriptInterface")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.news_fragment, container, false);
        webView = (AdvWebView) findViewById(R.id.wvBody);
        initSwipeRefreshLayout();
        registerForContextMenu(webView);
        setWebViewSettings();
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setDefaultFontSize(Preferences.News.getFontSize());
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        loadImages = webView.getSettings().getLoadsImagesAutomatically();

        webView.setWebViewClient(new MyWebViewClient());
        webView.addJavascriptInterface(this, "HTMLOUT");

        assert getArguments() != null;
        m_NewsUrl = getArguments().getString(URL_KEY);
        assert m_NewsUrl != null;
        showNews(m_NewsUrl);

        fab = (FloatingActionButton) findViewById(R.id.fab);

        if (!App.getInstance().getPreferences().getBoolean("pancilInActionBar", false)) {
            fab.setOnClickListener(view -> {
                if (Client.getInstance().getLogined())
                    respond();
                else
                    Toast.makeText(getContext(), R.string.need_login, Toast.LENGTH_SHORT).show();
            });
            setHideFab(fab);
            setFabColors(fab);
        } else {
            fab.hide();
        }

        buttonsPanel = (FrameLayout) findViewById(R.id.buttonsPanel);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
        //fab.setImageResource(R.drawable.pencil);
        //fab.setImageDrawable(ContextCompat.getDrawable(App.getContext(), R.drawable.pencil));
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        boolean pencil = App.getInstance().getPreferences().getBoolean("pancilInActionBar", false);
        menu.findItem(R.id.comment_item).setVisible(Client.getInstance().getLogined() & pencil);
        menu.findItem(R.id.hide_pencil_item).setChecked(Preferences.isHideFab());
        menu.findItem(R.id.LoadImages_item).setChecked(getWebView().getSettings().getLoadsImagesAutomatically());
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.comment_item:
                respond();
                return true;
            case R.id.refresh_item:
                refresh();
                return true;
            case R.id.thumb_up_item:
                like();
                return true;
            case R.id.hide_pencil_item:
                Preferences.setHideFab(!Preferences.isHideFab());
                setHideFab(fab);
                item.setChecked(Preferences.isHideFab());
                return true;
            case R.id.font_size_item:
                showFontSizeDialog();
                return true;
            case R.id.LoadImages_item:
                boolean loadImagesAutomatically1 = getWebView().getSettings().getLoadsImagesAutomatically();
                getWebView().getSettings().setLoadsImagesAutomatically(!loadImagesAutomatically1);
                item.setChecked(!loadImagesAutomatically1);
                return true;
            case R.id.link_item:
                ExtUrl.showSelectActionDialog(getMainActivity(), getString(R.string.link), getUrl());
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        if (inflater != null)
            inflater.inflate(R.menu.news, menu);
    }

    @Override
    public boolean onBackPressed() {
        if (!m_History.isEmpty()) {
            m_FromHistory = true;
            History history = m_History.get(m_History.size() - 1);
            m_History.remove(m_History.size() - 1);
            m_ScrollX = history.scrollX;
            m_ScrollY = history.scrollY;
            showNews(history.url);
            return true;
        } else {
            return false;
        }
    }

    private final static int FILECHOOSER_RESULTCODE = 1;

    @SuppressWarnings("unused")
    @JavascriptInterface
    public void showChooseCssDialog() {
        getMainActivity().runOnUiThread(() -> {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setType("file/*");

                // intent.setDataAndType(Uri.parseCount("file://" + lastSelectDirPath), "file/*");
                startActivityForResult(intent, FILECHOOSER_RESULTCODE);

            } catch (ActivityNotFoundException ex) {
                Toast.makeText(getMainActivity(), R.string.no_app_for_get_file, Toast.LENGTH_LONG).show();
            } catch (Exception ex) {
                AppLog.e(getMainActivity(), ex);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                 Intent data) {
        getMainActivity();
        if (resultCode == Activity.RESULT_OK && requestCode == FILECHOOSER_RESULTCODE) {
            Uri uri = data.getData();
            assert uri != null;
            String attachFilePath = FileUtils.getRealPathFromURI(getMainActivity(), uri);
            String cssData = FileUtils.readFileText(attachFilePath)
                    .replace("\\", "\\\\")
                    .replace("'", "\\'").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "");
            webView.evalJs("window['HtmlInParseLessContent']('" + cssData + "');");
        }
    }

    @SuppressWarnings("unused")
    @JavascriptInterface
    public void sendNewsAttaches(final String json) {
        getMainActivity().runOnUiThread(() -> {
            for (JsonElement s : new JsonParser().parse(json).getAsJsonArray()) {
                ArrayList<String> list1 = new ArrayList<>();
                for (JsonElement a : s.getAsJsonArray())
                    list1.add(a.getAsString());
                imageAttaches.add(list1);
            }
        });

    }

    public List<ArrayList<String>> imageAttaches = new ArrayList<>();

    private class MyWebViewClient extends WebViewClient {

        private final Map<String, Boolean> loadedUrls = new HashMap<>();

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            boolean ad;
            url = IntentActivity.getRedirectUrl(url);
            if (!loadedUrls.containsKey(url)) {
                ad = AdBlocker.isAd(url);
                loadedUrls.put(url, ad);
            } else {
                ad = loadedUrls.get(url);
            }
            return ad ? AdBlocker.createEmptyResource() :
                    super.shouldInterceptRequest(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean ad;
            url = IntentActivity.getRedirectUrl(url);
            if (!loadedUrls.containsKey(url)) {
                ad = AdBlocker.isAd(url);
                loadedUrls.put(url, ad);
            } else {
                ad = loadedUrls.get(url);
            }
            if (ad)
                return false;

            m_ScrollY = 0;
            m_ScrollX = 0;

            if (checkIsImage(url))
                return true;

            if (isReplyUrl(url))
                return true;

            if (isAnchor(url)) {
                showAnchor(url);
                return true;
            }

            if (IntentActivity.isNews(url)) {
                showNews(url);
                return true;
            }

            if (IntentActivity.isYoutube(url)) {
                IntentActivity.showInDefaultBrowser(getActivity(), url);
                return true;
            }

            IntentActivity.tryShowUrl(getMainActivity(), mHandler, url, true, false);

            return true;
        }

        private boolean checkIsImage(final String url) {
            final Pattern imagePattern = PatternExtensions.compile("https?://.*?\\.(png|jpg|jpeg|gif)$");
            Uri uri = Uri.parse(url.toLowerCase());
            String host = uri.getHost();
            if (imagePattern.matcher(uri.toString()).find()
                    || (host != null && (host.toLowerCase().contains("ggpht.com")
                    || host.toLowerCase().contains("googleusercontent.com")
                    || host.toLowerCase().contains("windowsphone.com")))) {
                if (!Client.getInstance().getLogined() && !Client.getInstance().hasLoginCookies()) {
                    Client.getInstance().showLoginForm(getContext());
                } else {
                    showImage(url);
                }
                return true;
            }
            return false;
        }

        private void showImage(String url) {
            for (ArrayList<String> list : imageAttaches) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).equals(url)) {
                        ImgViewer.startActivity(getContext(), list, i);
                        return;
                    }
                }
            }
            ImgViewer.startActivity(getContext(), url);
        }
    }

    private Boolean isReplyUrl(String url) {
        Matcher m = Pattern.compile("4pdaservice.org/(\\d+)/(\\d+)").matcher(url);
        if (m.find()) {
            respond(m.group(1), m.group(2), null);
            return true;
        }

        if (Pattern.compile("4pdaservice.org/#commentform").matcher(url).find()) {
            respond();
            return true;
        }

        return false;
    }

    private String getPostId() {
        final Pattern pattern = Pattern.compile(App.Host + "/\\d{4}/\\d{2}/\\d{2}/(\\d+)");
        Matcher m = pattern.matcher(m_NewsUrl);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    public static Boolean isAnchor(String url) {
        final Pattern pattern = Pattern.compile(App.Host + "/\\d{4}/\\d{2}/\\d{2}/\\d+/*#.*");
        return pattern.matcher(url).find();
    }

    private void showAnchor(String url) {
        final Pattern pattern = Pattern.compile(App.Host + "/\\d{4}/\\d{2}/\\d{2}/\\d+/*#(.*)");
        Matcher m = pattern.matcher(url);
        if (m.find()) {
            webView.evalJs("scrollToElement('" + m.group(1) + "');");
        }
    }

    private static class NewsHtmlBuilder extends HtmlBuilder {
        @Override
        public HtmlBuilder endBody() {
            m_Body.append("\n");
            return super.endBody();
        }

        @Override
        public void addScripts() {
            super.addScripts();
            m_Body.append("\n");
        }

        @Override
        public void addStyleSheetLink(StringBuilder sb) {
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file://").append(getStyle()).append("\" />\n");
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/fonts/roboto/import.css\"/>\n");
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/fonts/flaticons/import.css\"/>\n");
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/fonts/fontello/import.css\"/>\n");
            sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/forum/css/youtube_video.css\" type=\"text/css\" />\n");
        }
    }

    private GetNewsTask asyncTask = null;

    @Override
    public AsyncTask getAsyncTask() {
        return asyncTask;
    }

    private void showNews(String url) {
        m_NewsUrl = url.trim();
        webView.setWebViewClient(new MyWebViewClient());
        saveHistory(m_NewsUrl);

        asyncTask = new GetNewsTask();
        asyncTask.execute(m_NewsUrl.replace("|", ""));
    }

    public void showBody(String body) throws Exception {
        super.showBody();
        try {
            setTitle(m_Title);
            webView.loadDataWithBaseURL("https://" + App.Host + "/forum/", body, "text/html", "UTF-8", null);
            if (buttonsPanel.getTranslationY() != 0)
                ViewPropertyAnimator.animate(buttonsPanel)
                        .setInterpolator(new AccelerateDecelerateInterpolator())
                        .setDuration(500)
                        .translationY(0);
        } catch (Exception ex) {
            AppLog.e(getMainActivity(), ex);
        }
    }

    private void saveHistory(String nextUrl) {
        if (m_FromHistory) {
            m_FromHistory = false;
            return;
        }
        if (m_NewsUrl != null && !TextUtils.isEmpty(m_NewsUrl) && !m_NewsUrl.equals(nextUrl)) {
            History history = new History();
            history.url = m_NewsUrl;
            history.scrollX = m_ScrollX;
            history.scrollY = m_ScrollY;
            m_History.add(history);
        }
    }

    private class GetNewsTask extends AsyncTask<String, String, Boolean> {

        String Comment = null;
        String ReplyId;
        String Dp;

        private String m_ThemeBody;

        @Override
        protected Boolean doInBackground(String... forums) {
            try {
                if (isCancelled()) return false;
                Client client = Client.getInstance();

                if (TextUtils.isEmpty(Comment))
                    m_ThemeBody = transformBody(client.performGet(m_NewsUrl).getResponseBody());
                else {
                    Map<String, String> additionalHeaders = new HashMap<>();
                    additionalHeaders.put("comment", Comment);
                    additionalHeaders.put("comment_post_ID", getPostId());
                    additionalHeaders.put("submit", "Отправить комментарий");
                    additionalHeaders.put("comment_reply_ID", ReplyId);
                    additionalHeaders.put("comment_reply_dp", Dp);
                    m_ThemeBody = transformBody(client.performPost("https://" + App.Host + "/wp-comments-post.php", additionalHeaders, "UTF-8").getResponseBody());
                }
                return true;
            } catch (Throwable e) {
                // Log.e(ThemeActivity.this, e);
                ex = e;
                return false;
            }
        }

        private String transformBody(String body) {
            NewsHtmlBuilder builder = new NewsHtmlBuilder();
            m_Title = App.getContext().getString(R.string.news);
            builder.beginHtml(m_Title);
            builder.beginBody("news", null, loadImages);
            builder.append("
\n");
            builder.append("
");
            body = body.replaceAll("\"//", "\"https://");

            Matcher matcher = PatternExtensions.compile("ModKarma\\((\\{?[\\s\\S]*?\\}?)(?:,\\s?\\d+)?\\)").matcher(body);
            builder.append(parseBody(body));

            if (matcher.find()) {
                builder.append("");
                builder.append("");
            }
            builder.append("
");
            builder.endBody();
            builder.endHtml();
            return builder.getHtml().toString();
        }

        private String parseBody(String body) {

            body = NewsApi.parseNewsBody(body);

            // удалим все стили
            body = body.replaceAll("<link rel=\"stylesheet\"[^>]*>", "");
            return normalizeCommentUrls(body);
        }

        private String normalizeCommentUrls(String body) {
            if (App.getInstance().getPreferences().getBoolean("loadNewsComment", false)) {
                body = body.replaceAll("(
[\\s\\S]*?
[\\s\\S]*?<\\/ul>)", "");
            }

            body = Pattern.compile("<]*?src=\"http://www.youtube.com/embed/([^\"/]*)\".*?(?:|/>)", Pattern.CASE_INSENSITIVE)
                    .matcher(body)
                    .replaceAll("");
            return body
                    // удаляем форму ответа
                    .replaceAll("<form[^>]*action=\"/wp-comments-post.php\"[^>]*>[\\s\\S]*</form>",
                            "")
                    // заменяем обрезанные ссылки
                    .replace("href=\"/", "href=\"https://" + App.Host + "/")
                    .replace("href=\"#commentform\"", "href=\"https://4pdaservice.org/#commentform");
        }

        @Override
        protected void onPreExecute() {
            try {
                setLoading(true);
            } catch (Exception ex) {
                this.cancel(true);
            }
        }

        private Throwable ex;

        @Override
        protected void onPostExecute(final Boolean success) {
            Comment = null;
            if (isCancelled()) return;
            if (success) {
                try {
                    showBody(m_ThemeBody);
                } catch (Exception e) {
                    AppLog.e(e);
                }
                setLoading(false);
            } else {
                setTitle(ex.getMessage());
                webView.loadDataWithBaseURL("https://" + App.Host + "/forum/", m_ThemeBody, "text/html", "UTF-8", null);
                AppLog.e(getMainActivity(), ex);
            }
        }
    }

    public void respond() {
        respond("0", "0", null);
    }

    public void respond(final String replyId, final String dp, String user) {
        LayoutInflater inflater = (LayoutInflater) getMainActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        assert inflater != null;
        View layout = inflater.inflate(R.layout.news_comment_edit, null);

        assert layout != null;
        final EditText message_edit = layout.findViewById(R.id.comment);
        if (user != null)
            message_edit.setText(String.format("%s,", URLDecoder.decode(user)));
        new MaterialDialog.Builder(getMainActivity())
                .title(R.string.LeaveComment)
                .customView(layout, true)
                .positiveText(R.string.send)
                .negativeText(R.string.cancel)
                .onPositive((dialog, which) -> {
                    String message = message_edit.getText().toString();
                    if (TextUtils.isEmpty(message.trim())) {
                        Toast.makeText(getMainActivity(), R.string.empty_text, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    asyncTask = new GetNewsTask();
                    asyncTask.Comment = message;
                    asyncTask.ReplyId = replyId;
                    asyncTask.Dp = dp;
                    asyncTask.execute(m_NewsUrl);
                })
                .show();
    }

    private void like() {
        Toast.makeText(getMainActivity(), R.string.request_sent, Toast.LENGTH_SHORT).show();
        new Thread(() -> {

            Exception ex = null;

            try {
                Client.getInstance().likeNews(getPostId());
            } catch (Exception e) {
                ex = e;
            }

            final Exception finalEx = ex;
            mHandler.post(() -> {
                try {
                    if (finalEx != null) {
                        Toast.makeText(getMainActivity(), R.string.error_request, Toast.LENGTH_SHORT).show();
                        AppLog.e(getMainActivity(), finalEx);
                    } else {
                        Toast.makeText(getMainActivity(), R.string.request_performed, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception ex1) {
                    AppLog.e(getMainActivity(), ex1);
                }
            });
        }).start();
    }

    @SuppressWarnings("unused")
    @JavascriptInterface
    public void likeComment(final String id, final String comment) {
        getMainActivity().runOnUiThread(() -> sendLikeComment(id, comment));
    }

    private void sendLikeComment(final String id, final String comment) {
        Toast.makeText(getMainActivity(), R.string.request_sent, Toast.LENGTH_SHORT).show();
        new Thread(() -> {

            Exception ex = null;

            try {
                Client.getInstance().likeComment(id, comment);
            } catch (Exception e) {
                if (!(e instanceof ShowInBrowserException)) {
                    ex = e;
                }
            }

            final Exception finalEx = ex;
            mHandler.post(() -> {
                try {
                    if (finalEx != null) {
                        Toast.makeText(getMainActivity(), R.string.error_request, Toast.LENGTH_SHORT).show();
                        AppLog.e(getMainActivity(), finalEx);
                    } else {
                        Toast.makeText(getMainActivity(), R.string.request_performed, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception ex1) {
                    AppLog.e(getMainActivity(), ex1);
                }
            });
        }).start();
    }
}


text:
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JdSdk.Response.Wms
{
    [Serializable]
    public class LogisticsOtherOutstoreQueryreturnbarcodeResponse : JdResponse
    {
        [JsonProperty("process_code")]
        public Nullable<Int32> ProcessCode
        {
            get;
            set;
        }

        [JsonProperty("process_status")]
        public String ProcessStatus
        {
            get;
            set;
        }

        [JsonProperty("error_message")]
        public String ErrorMessage
        {
            get;
            set;
        }

        [JsonProperty("josl_outbound_no")]
        public String JoslOutboundNo
        {
            get;
            set;
        }

        [JsonProperty("isv_outbound_no")]
        public String IsvOutboundNo
        {
            get;
            set;
        }

        [JsonProperty("josl_status")]
        public String JoslStatus
        {
            get;
            set;
        }

        [JsonProperty("complete_time")]
        public Nullable<DateTime> CompleteTime
        {
            get;
            set;
        }

        [JsonProperty("order_details")]
        public List<ResponseOrderOtherDetail> OrderDetails
        {
            get;
            set;
        }

        [JsonProperty("carriers_id")]
        public String CarriersId
        {
            get;
            set;
        }

        [JsonProperty("carriers_name")]
        public String CarriersName
        {
            get;
            set;
        }

        [JsonProperty("delivery_no_list")]
        public List<String> DeliveryNoList
        {
            get;
            set;
        }

    }

}


text:
import functools
import warnings
import logging

from django.conf import settings
from django.core.cache.backends.base import BaseCache

from .util import load_class
from .exceptions import ConnectionInterrupted

DJANGO_REDIS_IGNORE_EXCEPTIONS = getattr(settings, "DJANGO_REDIS_IGNORE_EXCEPTIONS", False)
DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = getattr(settings, "DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS", False)
DJANGO_REDIS_LOGGER = getattr(settings, "DJANGO_REDIS_LOGGER", False)

if DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS:
    logger = logging.getLogger((DJANGO_REDIS_LOGGER or __name__))

def omit_exception(method=None, return_value=None):
    """
    Simple decorator that intercepts connection
    errors and ignores these if settings specify this.
    """

    if method is None:
        return functools.partial(omit_exception, return_value=return_value)

    @functools.wraps(method)
    def _decorator(self, *args, **kwargs):
        try:
            return method(self, *args, **kwargs)
        except ConnectionInterrupted as e:
            if self._ignore_exceptions:
                if DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS:
                    logger.error(str(e))

                return return_value
            raise e.parent

    return _decorator

class RedisCache(BaseCache):
    def __init__(self, server, params):
        super(RedisCache, self).__init__(params)
        self._server = server
        self._params = params

        options = params.get("OPTIONS", {})
        self._client_cls = options.get("CLIENT_CLASS", "django_redis.client.DefaultClient")
        self._client_cls = load_class(self._client_cls)
        self._client = None

        self._ignore_exceptions = options.get("IGNORE_EXCEPTIONS", DJANGO_REDIS_IGNORE_EXCEPTIONS)

    @property
    def client(self):
        """
        Lazy client connection property.
        """
        if self._client is None:
            self._client = self._client_cls(self._server, self._params, self)
        return self._client

    @omit_exception
    def set(self, *args, **kwargs):
        return self.client.set(*args, **kwargs)

    @omit_exception
    def incr_version(self, *args, **kwargs):
        return self.client.incr_version(*args, **kwargs)

    @omit_exception
    def add(self, *args, **kwargs):
        return self.client.add(*args, **kwargs)

    @omit_exception
    def get(self, key, default=None, version=None, client=None):
        try:
            return self.client.get(key, default=default, version=version,
                                                            client=client)
        except ConnectionInterrupted as e:
            if self._ignore_exceptions:
                if DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS:
                    logger.error(str(e))
                return default
            raise

    @omit_exception
    def delete(self, *args, **kwargs):
        return self.client.delete(*args, **kwargs)

    @omit_exception
    def delete_pattern(self, *args, **kwargs):
        return self.client.delete_pattern(*args, **kwargs)

    @omit_exception
    def delete_many(self, *args, **kwargs):
        return self.client.delete_many(*args, **kwargs)

    @omit_exception
    def clear(self):
        return self.client.clear()

    @omit_exception(return_value={})
    def get_many(self, *args, **kwargs):
        return self.client.get_many(*args, **kwargs)

    @omit_exception
    def set_many(self, *args, **kwargs):
        return self.client.set_many(*args, **kwargs)

    @omit_exception
    def incr(self, *args, **kwargs):
        return self.client.incr(*args, **kwargs)

    @omit_exception
    def decr(self, *args, **kwargs):
        return self.client.decr(*args, **kwargs)

    @omit_exception
    def has_key(self, *args, **kwargs):
        return self.client.has_key(*args, **kwargs)

    @omit_exception
    def keys(self, *args, **kwargs):
        return self.client.keys(*args, **kwargs)

    @omit_exception
    def iter_keys(self, *args, **kwargs):
        return self.client.iter_keys(*args, **kwargs)

    @omit_exception
    def ttl(self, *args, **kwargs):
        return self.client.ttl(*args, **kwargs)

    @omit_exception
    def persist(self, *args, **kwargs):
        return self.client.persist(*args, **kwargs)

    @omit_exception
    def expire(self, *args, **kwargs):
        return self.client.expire(*args, **kwargs)

    @omit_exception
    def lock(self, *args, **kwargs):
        return self.client.lock(*args, **kwargs)

    @omit_exception
    def close(self, **kwargs):
        self.client.close(**kwargs)


text:
package com.linecorp.armeria.internal.client.dns;

import static com.linecorp.armeria.client.endpoint.dns.TestDnsServer.newAddressRecord;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Test;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import com.linecorp.armeria.client.DnsCache;
import com.linecorp.armeria.client.endpoint.dns.TestDnsServer;
import com.linecorp.armeria.common.CommonPools;
import com.linecorp.armeria.common.util.TransportType;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.handler.codec.dns.DefaultDnsQuestion;
import io.netty.handler.codec.dns.DefaultDnsResponse;
import io.netty.handler.codec.dns.DnsRecordType;
import io.netty.handler.codec.dns.DnsSection;
import io.netty.resolver.HostsFileEntriesResolver;
import io.netty.resolver.dns.DnsNameResolverBuilder;
import io.netty.resolver.dns.DnsServerAddresses;

class DefaultDnsResolverTest {

    /**
     * This test does not check anything but makes the future returned by
     * {@link DefaultDnsResolver#resolve(List, String)}} is completed even before the DNS responses
     * are received. By doing so, we can make our leak detectors detect any leaks if we forgot to release
     * the DNS responses. See https://github.com/line/armeria/pull/2951 for more information.
     */
    @Test
    void responseReceivedAfterCancellation() throws Exception {
        try (TestDnsServer dnsServer = new TestDnsServer(
                ImmutableMap.of(new DefaultDnsQuestion("foo.com.", DnsRecordType.A),
                                new DefaultDnsResponse(0).addRecord(DnsSection.ANSWER,
                                                                    newAddressRecord("foo.com.", "1.2.3.4")),
                                new DefaultDnsQuestion("bar.com.", DnsRecordType.A),
                                new DefaultDnsResponse(0).addRecord(DnsSection.ANSWER,
                                                                    newAddressRecord("bar.com.", "5.6.7.8"))),
                new ChannelOutboundHandlerAdapter() {
                    @Override
                    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
                        ctx.executor().schedule(() -> ctx.writeAndFlush(msg, promise), 1, TimeUnit.SECONDS);
                    }
                })) {

            final EventLoop eventLoop = CommonPools.workerGroup().next();
            final DefaultDnsResolver resolver =
                    DefaultDnsResolver.of(
                            new DnsNameResolverBuilder(eventLoop)
                                    .channelType(TransportType.datagramChannelType(eventLoop))
                                    .queryTimeoutMillis(Long.MAX_VALUE)
                                    .nameServerProvider(
                                            name -> DnsServerAddresses.sequential(dnsServer.addr()).stream())
                                    .build(),
                            DnsCache.ofDefault(), eventLoop, ImmutableList.of(), 1,
                            1, HostsFileEntriesResolver.DEFAULT);

            final DnsQuestionContext ctx = new DnsQuestionContext(eventLoop, 1);
            resolver.resolveAll(ctx,
                                ImmutableList.of(new DefaultDnsQuestion("foo.com.", DnsRecordType.A),
                                                 new DefaultDnsQuestion("bar.com.", DnsRecordType.A)),
                                "");

            // Cancel the queries immediately.
            ctx.whenCancelled().cancel(false);

            // Wait until the DNS server sends the response.
            Thread.sleep(2000);
            resolver.close();
        }
    }
}


text:
cssRefresh
=======
Based on http://cssrefresh.frebsite.nl/

- Added a variable named duration to contorol the CSS reload time duration
- All the <link> tags with rel="autoload" will only be reloaded
- Include the script in your webpage: <script type="text/javascript" src="https://raw.githubusercontent.com/robinflyhigh/cssRefresh/master/cssrefresh.js"></script>


text:
package OptimizationTests.AutoFastJNIDetection.TryCatchJava02;

/* Test add */
public class Main {

    public  final int iterations = 5000;
    static
    {
        System.loadLibrary("JniTest");
    }

    public native int nativeTryCatchJava02(int a, int b, int c);

    public int inlineNativeCall(int a, int b, int c) {
        return nativeTryCatchJava02(a, b, c);
    }

    // Test case harnesses
    public int PleaseInlineMe() {
        int sum = 1000;
        for (int i = 0; i < iterations; i++) {
            try {
            Thread.currentThread().sleep(1);
            } catch (Exception e) {
                System.out.println(e);
            }
            try {
                sum /= i-10;
            } catch (Exception ae) {
                sum += inlineNativeCall(1 - i, 2, i);
            }
        }
        return sum;
    }

    public static void main(String[] args)
    {
        Main test = new Main();
        System.out.println("result: " + test.PleaseInlineMe());
        System.out.println("Test completed");
    }

}


text:
export const singaporePrimaryColor = "#babab9" // a gray a bit darker than from the merlion
export const singaporePrimaryColorDarker = "#9e9e9c" // 15% darker


text:
var request = require('request');
var fs = require('fs');

request('http://www.google.com').pipe(fs.createWriteStream('google.html'));


text:
This directory contains tests related to the lua routing code.
These tests that can be run in a non-functional server environment.
You should not need a running chef-server to perform these tests.
You simply have to set a few environment variables.

### If Running These Tests From A Functioning Chef Server

There Should be sane defaults for all the environment variables. Simply run:

```
./run_lua_tests.sh
```

### If running these tests locally from the opscode-omnibus repo

#### Install dependencies on your system

You will need a few dependencies. On mac:

```
brew install lua
brew install luarocks
luarocks install lpeg
luarocks install lua-cjson
```

On ubuntu:

```
sudo apt-get install lua5.1
sudo apt-get install luarocks
luarocks install lpeg
luarocks install lua-cjson
```

Also, the script itself will let you know if you are missing something.

#### Determine where lua is installed and set $LUALIB

The tests will need to symlink a few important files.
Set $LUALIB to the directory that contains `lpeg.so` and `cjson.so`, like so:

```
# if you don't know where those files live
$ find / -name lpeg.so

# use that result here
$ export LUALIB=<path to the files>

# for example
$ export LUALIB=/usr/local/lib/lua/5.2
```

#### Set $USE_OMNIBUS_FILES=0

```
$ export USE_OMNIBUS_FILES=0
```

This will let the script know that you are using local copies of the lua code in Chef template form.

#### Run the tests

```
./run_lua_tests.sh
```

The script will determine if you have the necessary components
installed, and will inform you as to next steps if not.  Once everything
is installed, it will run the tests.


text:
The layout container is used to wrap the grid system and page content. It is automatically centered horizontally and has a left and right padding, which work with `.row` to neutralize the margins on the left and right of `.row`.

A layout container has padding, so one container should not wrap another container, which causes extra padding.

ZUI has three types of containers for layouts: responsive, liquid-width, and fixed-width.

## Responsive Container

A responsive container automatically adjusts the width of the container based on the width of the page.

```html
<div class="container">
  ...
</div>
```

## Liquid-width Container

A liquid-width Container is 100% wide all the time and takes 100% width of the parent container.

```html
<div class="container-fluid">
  ...
</div>
```

## Fixed-width Container

A fixed-width Container is fixed. Below are four types of fix-width containers:

<template class="table-auto table-bordered"/>

| Class                 | Width  |
|-----------------------|--------|
| `.container-fixed`    | 1160px |
| `.container-fixed-md` | 960px  |
| `.container-fixed-sm` | 740px  |
| `.container-fixed-xs` | 440px  |

```html
<div class="container-fixed">
  ...
</div>
```


text:
Preboot is a collection of LESS mixins and variables for quickly writing CSS. As the precursor to [Bootstrap](http://getbootstrap.com), it serves as a lightweight and interface agnostic approach to jumpstarting your next web project. Use it how you see fit.

## Getting started

Preboot requires [LESS](http://lesscss.org). Head over to their documentation and familiarize yourself with the project. Once you're up and running, including and using Preboot is a breeze.

1. Create a new LESS file (e.g., application.less)
2. Include Preboot via `@import "preboot.less";`
3. Start writing your own LESS-flavored CSS

We highly recommend using Preboot in conjunction with [Normalize](http://necolas.github.com/normalize.css), a powerful tool for more consistent rendering of web components across various browsers and devices.

## Bugs and feature requests

Have a bug or a feature request? [Please open a new issue](https://github.com/mdo/preboot/issues). Before opening any issue, please search for existing issues and read the [Issue Guidelines](https://github.com/necolas/issue-guidelines), written by [Nicolas Gallagher](https://github.com/necolas/).

## Author

**Mark Otto**

+ [http://twitter.com/mdo](http://twitter.com/mdo)
+ [http://github.com/mdo](http://github.com/mdo)

## Brief history

Preboot was originally released in March 2011 under the name Bootstrap.less. Sensing the need for a larger and more comprehensive framework, I copped the name and created Bootstrap based on the original variables and mixins work here. To avoid obivous naming issues, I renamed this Preboot and essentially didn't touch the project for two years.

Fast forward two years and I'm backporting many of Bootstrap's variables and mixins back into Preboot as v2.

Disclaimer: Preboot v1 (Bootstrap.less) was released under a Creative Commons license and is still available. Preboot 2 is now under MIT.

## Copyright and license

[MIT](LICENSE.md)


text:
It is possible to run Bitcoin ABC as a Tor onion service, and connect to such services.

The following directions assume you have a Tor proxy running on port 9050. Many distributions default to having a SOCKS proxy listening on port 9050, but others may not. In particular, the Tor Browser Bundle defaults to listening on port 9150. See [Tor Project FAQ:TBBSocksPort](https://www.torproject.org/docs/faq.html.en#TBBSocksPort) for how to properly
configure Tor.

## How to see information about your Tor configuration via Bitcoin ABC

There are several ways to see your local onion address in Bitcoin ABC:
- in the debug log (grep for "tor:" or "AddLocal")
- in the output of RPC `getnetworkinfo` in the "localaddresses" section
- in the output of the CLI `-netinfo` peer connections dashboard

You may set the `-debug=tor` config logging option to have additional
information in the debug log about your Tor configuration.

## 1. Run Bitcoin ABC behind a Tor proxy

The first step is running Bitcoin ABC behind a Tor proxy. This will already anonymize all
outgoing connections, but more is possible.

	-proxy=ip:port  Set the proxy server. If SOCKS5 is selected (default), this proxy
	                server will be used to try to reach .onion addresses as well.
	                You need to use -noonion or -onion=0 to explicitly disable
	                outbound access to onion services.

	-onion=ip:port  Set the proxy server to use for Tor onion services. You do not
	                need to set this if it's the same as -proxy. You can use -onion=0
	                to explicitly disable access to onion services.
	                Note: Only the -proxy option sets the proxy for DNS requests;
	                with -onion they will not route over Tor, so use -proxy if you
	                have privacy concerns.

	-listen         When using -proxy, listening is disabled by default. If you want
	                to manually configure an onion service (see section 3), you'll
	                need to enable it explicitly.

	-connect=X      When behind a Tor proxy, you can specify .onion addresses instead
	-addnode=X      of IP addresses or hostnames in these parameters. It requires
	-seednode=X     SOCKS5. In Tor mode, such addresses can also be exchanged with
	                other P2P nodes.

	-onlynet=onion  Make outgoing connections only to .onion addresses. Incoming
	                connections are not affected by this option. This option can be
	                specified multiple times to allow multiple network types, e.g.
	                ipv4, ipv6 or onion. If you use this option with values other
	                than onion you *cannot* disable onion connections; outgoing onion
	                connections will be enabled when you use -proxy or -onion. Use
	                -noonion or -onion=0 if you want to be sure there are no outbound
	                onion connections over the default proxy or your defined -proxy.

In a typical situation, this suffices to run behind a Tor proxy:

	./bitcoind -proxy=127.0.0.1:9050

## 2. Automatically create a Bitcoin ABC onion service

Bitcoin ABC makes use of Tor's control socket API to create and destroy
ephemeral onion services programmatically. This means that if Tor is running and
proper authentication has been configured, Bitcoin ABC automatically creates an
onion service to listen on. The goal is to increase the number of available
onion nodes.

This feature is enabled by default if Bitcoin ABC is listening (`-listen`) and
it requires a Tor connection to work. It can be explicitly disabled with
`-listenonion=0`. If it is not disabled, it can be configured using the
`-torcontrol` and `-torpassword` settings.

To see verbose Tor information in the bitcoind debug log, pass `-debug=tor`.

### Control Port

You may need to set up the Tor Control Port. On Linux distributions there may be
some or all of the following settings in `/etc/tor/torrc`, generally commented
out by default (if not, add them):

```
ControlPort 9051
CookieAuthentication 1
CookieAuthFileGroupReadable 1
```

Add or uncomment those, save, and restart Tor (usually `systemctl restart tor`
or `sudo systemctl restart tor` on most systemd-based systems, including recent
Debian and Ubuntu, or just restart the computer).

On some systems (such as Arch Linux), you may also need to add the following
line:

```
DataDirectoryGroupReadable 1
```

### Authentication

Connecting to Tor's control socket API requires one of two authentication
methods to be configured: cookie authentication or bitcoind's `-torpassword`
configuration option.

#### Cookie authentication

For cookie authentication, the user running bitcoind must have read access to
the `CookieAuthFile` specified in the Tor configuration. In some cases this is
preconfigured and the creation of an onion service is automatic. Don't forget to
use the `-debug=tor` bitcoind configuration option to enable Tor debug logging.

If a permissions problem is seen in the debug log, e.g. `tor: Authentication
cookie /run/tor/control.authcookie could not be opened (check permissions)`, it
can be resolved by adding both the user running Tor and the user running
bitcoind to the same Tor group and setting permissions appropriately.

On Debian-derived systems, the Tor group will likely be `debian-tor` and one way
to verify could be to list the groups and grep for a "tor" group name:

```
getent group | cut -d: -f1 | grep -i tor
```

You can also check the group of the cookie file. On most Linux systems, the Tor
auth cookie will usually be `/run/tor/control.authcookie`:

```
stat -c '%G' /run/tor/control.authcookie
```

Once you have determined the `${TORGROUP}` and selected the `${USER}` that will
run bitcoind, run this as root:

```
usermod -a -G ${TORGROUP} ${USER}
```

Then restart the computer (or log out) and log in as the `${USER}` that will run
bitcoind.

#### `torpassword` authentication

For the `-torpassword=password` option, the password is the clear text form that
was used when generating the hashed password for the `HashedControlPassword`
option in the Tor configuration file.

The hashed password can be obtained with the command `tor --hash-password
password` (refer to the [Tor Dev
Manual](https://2019.www.torproject.org/docs/tor-manual.html.en) for more
details).

## 3. Manually create a Bitcoin ABC onion service

You can also manually configure your node to be reachable from the Tor network.
Add these lines to your `/etc/tor/torrc` (or equivalent config file):

	HiddenServiceDir /var/lib/tor/bitcoin-service/
	HiddenServicePort 8333 127.0.0.1:8334

The directory can be different of course, but virtual port numbers should be equal to
your bitcoind's P2P listen port (8333 by default), and target addresses and ports
should be equal to binding address and port for inbound Tor connections (127.0.0.1:8334 by default).

	-externalip=X   You can tell bitcoind about its publicly reachable addresses using
	                this option, and this can be an onion address. Given the above
	                configuration, you can find your onion address in
	                /var/lib/tor/bitcoin-service/hostname. For connections
	                coming from unroutable addresses (such as 127.0.0.1, where the
	                Tor proxy typically runs), onion addresses are given
	                preference for your node to advertise itself with.

	                You can set multiple local addresses with -externalip. The
	                one that will be rumoured to a particular peer is the most
	                compatible one and also using heuristics, e.g. the address
	                with the most incoming connections, etc.

	-listen         You'll need to enable listening for incoming connections, as this
	                is off by default behind a proxy.

	-discover       When -externalip is specified, no attempt is made to discover local
	                IPv4 or IPv6 addresses. If you want to run a dual stack, reachable
	                from both Tor and IPv4 (or IPv6), you'll need to either pass your
	                other addresses using -externalip, or explicitly enable -discover.
	                Note that both addresses of a dual-stack system may be easily
	                linkable using traffic analysis.

In a typical situation, where you're only reachable via Tor, this should suffice:

	./bitcoind -proxy=127.0.0.1:9050 -externalip=7zvj7a2imdgkdbg4f2dryd5rgtrn7upivr5eeij4cicjh65pooxeshid.onion -listen

(obviously, replace the .onion address with your own). It should be noted that you still
listen on all devices and another node could establish a clearnet connection, when knowing
your address. To mitigate this, additionally bind the address of your Tor proxy:

	./bitcoind ... -bind=127.0.0.1

If you don't care too much about hiding your node, and want to be reachable on IPv4
as well, use `discover` instead:

	./bitcoind ... -discover

and open port 8333 on your firewall (or use port mapping, i.e., `-upnp` or `-natpmp`).

If you only want to use Tor to reach .onion addresses, but not use it as a proxy
for normal IPv4/IPv6 communication, use:

	./bitcoind -onion=127.0.0.1:9050 -externalip=7zvj7a2imdgkdbg4f2dryd5rgtrn7upivr5eeij4cicjh65pooxeshid.onion -discover

## 4. Privacy recommendations

- Do not add anything but Bitcoin ABC ports to the onion service created in section 3.
  If you run a web service too, create a new onion service for that.
  Otherwise it is trivial to link them, which may reduce privacy. Onion
  services created automatically (as in section 2) always have only one port
  open.


text:
package io.github.microcks.domain;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;
import java.util.Map;
/**
 * Aggregate bean for grouping a Service and its messages pairs.
 * @author laurent
 */
public class ServiceView {

   private Service service;
   private Map<String, List<? extends Exchange>> messagesMap;

   @JsonCreator
   public ServiceView(@JsonProperty("service") Service service, @JsonProperty("messagesMap") Map<String, List<? extends Exchange>> messagesMap) {
      this.service = service;
      this.messagesMap = messagesMap;
   }

   public Service getService() {
      return service;
   }

   public Map<String, List<? extends Exchange>> getMessagesMap() {
      return messagesMap;
   }
}


text:
package hu.juranyi.zsolt.jauthortagger.util;

import java.util.regex.Pattern;

/**
 * Abstract String filtering utility which accepts a readable
 * filter as input, immediately converts it to a regular expression and provides
 * a test method. A conversion is what is abstract. Readable filter is usually a
 * simple search term with jokers ('?', '*') inside, but it's handled by the
 * implementation.
 *
 * @author Zsolt Jurányi
 *
 */
public abstract class AbstractStringFilter {

	private final String filter;
	private final Pattern pattern;

	/**
	 * Creates an instance using a readable filter which will be converted into
	 * a regular expression. The filterToPattern method will be
	 * called to perform the conversion.
	 *
	 * @param filter
	 *            - Readable filter String to use.
	 * @see #filterToPattern(String)
	 */
	public AbstractStringFilter(String filter) {
		this.filter = filter;
		this.pattern = filterToPattern(filter);
	}

	/**
	 * Tests the given input String whether it matches the stored
	 * pattern.
	 *
	 * @param str
	 *            - Input String to test.
	 * @return true if the input is non-null and matches the stored
	 *         pattern, false otherwise.
	 */
	public boolean accept(String str) {
		return null != str && pattern.matcher(str).find();
	}

	/**
	 * Method to convert the readable filter into a regular expression.
	 *
	 * @param filter
	 *            - The filter String to convert.
	 * @return The regular expression as a Pattern object.
	 */
	protected abstract Pattern filterToPattern(String filter);

	/**
	 * Returns the readable filter.
	 *
	 * @return The readable filter.
	 */
	public String getFilter() {
		return filter;
	}

	/**
	 * Returns the regular expression as a Pattern object.
	 *
	 * @return The regular expression as a Pattern object.
	 */
	public Pattern getPattern() {
		return pattern;
	}

	@Override
	public String toString() {
		return "AbstractStringFilter [filter=" + filter + ", pattern=" + pattern + "]";
	}

}


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

namespace csse
{
    public class Configuration
    {
        public bool LoadFromCommandLineIfEmpty { get; set; }
        public string LogFolder { get; set; }
        public string LogFilename { get; set; }
        public bool DebugLoggingEnabled { get; set; }
        public string ScriptFolder { get; set; }
        public string TemplateFile { get; set; }
        public string EnvironmentFolder { get; set; }
        public string BuildFolder { get; set; }
        public string EditorPath { get; set; }
        public string ArchiveFolder { get; set; }
    }
}


text:
class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end


text:
import * as React from 'react'
import * as M from '@material-ui/core'
import * as Lab from '@material-ui/lab'

import * as IPC from 'utils/electron/ipc-provider'
import * as Config from 'utils/Config'
import * as TeleportUri from 'utils/TeleportUri'
import { PackageHandle } from 'utils/packageHandle'
import { readableBytes } from 'utils/string'

const SIZE_THRESHOLD = 1024 * 1024 * 100

const isNumber = (v: any) => typeof v === 'number' && !Number.isNaN(v)

interface OpenInDesktopProps {
  onClose: () => void
  onConfirm: () => Promise<void>
  open: boolean
  size?: number
}

export function Dialog({ onClose, onConfirm, open, size }: OpenInDesktopProps) {
  const [error, setError] = React.useState<Error | null>(null)
  const [disabled, setDisabled] = React.useState(false)
  const handleConfirm = React.useCallback(async () => {
    try {
      setDisabled(true)
      await onConfirm()
      setDisabled(false)
      onClose()
    } catch (e) {
      if (e instanceof Error) setError(e)
    }
  }, [onClose, onConfirm])
  return (
    <M.Dialog open={open} onClose={onClose}>
      <M.DialogTitle>Open in Teleport</M.DialogTitle>
      <M.DialogContent>
        <M.Typography>Download package and open in desktop application</M.Typography>
        {isNumber(size) && (
          <M.Typography>Total size of package is {readableBytes(size)}</M.Typography>
        )}
        <M.Typography>It could take a while</M.Typography>
        {error && <Lab.Alert severity="error">{error.message}</Lab.Alert>}
      </M.DialogContent>
      <M.DialogActions>
        <M.Button onClick={onClose}>Cancel</M.Button>
        <M.Button
          color="primary"
          disabled={disabled}
          onClick={handleConfirm}
          variant="contained"
        >
          Confirm
        </M.Button>
      </M.DialogActions>
    </M.Dialog>
  )
}

function useOpenInDesktop(packageHandle: PackageHandle, size?: number) {
  const { desktop } = Config.use()
  const ipc = IPC.use()

  const [confirming, setConfirming] = React.useState(false)
  const openInDesktop = React.useCallback(async () => {
    if (desktop) {
      await ipc.invoke(IPC.EVENTS.DOWNLOAD_PACKAGE, packageHandle)
    } else {
      const deepLink = TeleportUri.stringify(packageHandle)
      window.location.assign(deepLink)
    }
  }, [desktop, ipc, packageHandle])
  const unconfirm = React.useCallback(() => setConfirming(false), [])
  const confirm = React.useCallback(() => {
    if (!size || size > SIZE_THRESHOLD) {
      setConfirming(true)
    } else {
      openInDesktop()
    }
  }, [openInDesktop, size])
  // TODO: probably rename OpenInDesktop to something
  //       then you can rename confirm → open, unconfirm → close
  return {
    confirm,
    confirming,
    openInDesktop,
    unconfirm,
  }
}

export const use = useOpenInDesktop


text:
  (holder)->GetInstanceForVersionDoNotCallDirectly(             \
      std::remove_pointer<decltype(                             \
          holder)>::type::Instance::k##method_name##MinVersion, \
      #method_name)

namespace arc {

namespace internal {

// Small helper to implement HasInit<> trait below.
// Note that only Check() declaration is needed.
// - If InstanceType::Init exists, Check(InstanceType()) would return
//   std::true_type, because 1) the template param is successfully substituted,
//   and 2) Check(...) is weaker than the template's so there is no overload
//   conflict.
// - If not, Check(InstanceType()) would return std::false_type, because
//   template param substitution is failed, but it won't be compile error
//   thanks to SFINAE, thus Check(...) is the only candidate.
struct HasInitImpl {
  template <typename InstanceType>
  static auto Check(InstanceType* v)
      -> decltype(&InstanceType::Init, std::true_type());
  static std::false_type Check(...);
};

// Type trait to return whether InstanceType has Init() or not.
template <typename InstanceType>
using HasInit =
    decltype(HasInitImpl::Check(static_cast<InstanceType*>(nullptr)));

// Full duplex Mojo connection holder implementation.
// InstanceType and HostType are Mojo interface types (arc::mojom::XxxInstance,
// and arc::mojom::XxxHost respectively).
template <typename InstanceType, typename HostType>
class ConnectionHolderImpl {
 public:
  explicit ConnectionHolderImpl(ConnectionNotifier* connection_notifier)
      : connection_notifier_(connection_notifier) {}

  ConnectionHolderImpl(const ConnectionHolderImpl&) = delete;
  ConnectionHolderImpl& operator=(const ConnectionHolderImpl&) = delete;

  InstanceType* instance() { return IsConnected() ? instance_ : nullptr; }
  uint32_t instance_version() const {
    return IsConnected() ? instance_version_ : 0;
  }

  // Returns true if |receiver_| is set.
  bool IsConnected() const { return receiver_.get(); }

  // Sets (or resets if |host| is nullptr) the host.
  void SetHost(HostType* host) {
    // Some tests overwrite host, now. It is safe iff the |instance_| is
    // not yet set.
    // TODO(hidehiko): Make check more strict.
    DCHECK(host == nullptr || host_ == nullptr || instance_ == nullptr);

    if (host_ == host)
      return;

    host_ = host;
    OnChanged();
  }

  // Sets the instance.
  void SetInstance(InstanceType* instance,
                   uint32_t version = InstanceType::version_) {
    DCHECK(instance);
    DCHECK(instance_ != instance);

    instance_ = instance;
    instance_version_ = version;
    OnChanged();
  }

  // Resets the instance if it matches |instance|.
  void CloseInstance(InstanceType* instance) {
    DCHECK(instance);

    if (instance != instance_) {
      DVLOG(1) << "Dropping request to close a stale instance";
      return;
    }

    instance_ = nullptr;
    instance_version_ = 0;
    OnChanged();
  }

 private:
  // Called when |instance_| or |host_| are updated.
  void OnChanged() {
    // Cancel any in-flight connection requests. This also prevents Observers
    // from being notified of a spurious OnConnectionClosed() before an
    // OnConnectionReady() event.
    weak_ptr_factory_.InvalidateWeakPtrs();
    if (receiver_.get()) {
      // Regardless of what has changed, the old connection is now stale. Reset
      // the current receiver and notify any listeners. Since |receiver_| is set
      // just before the OnConnectionReady() event, we never notify observers of
      // OnConnectionClosed() without seeing the former event first.
      if (instance_ && host_)
        LOG(ERROR) << "Unbinding instance of a stale connection";
      OnConnectionClosed();
    }
    if (!instance_ || !host_)
      return;
    // When both the instance and host are ready, start connection.
    // TODO(crbug.com/750563): Fix the race issue.
    auto receiver = std::make_unique<mojo::Receiver<HostType>>(host_);
    mojo::PendingRemote<HostType> host_proxy;
    receiver->Bind(host_proxy.InitWithNewPipeAndPassReceiver());
    instance_->Init(
        std::move(host_proxy),
        base::BindOnce(&ConnectionHolderImpl::OnConnectionReady,
                       weak_ptr_factory_.GetWeakPtr(), std::move(receiver)));
  }

  // Resets the receiver and notifies all the observers that the connection is
  // closed.
  void OnConnectionClosed() {
    DCHECK(receiver_);
    receiver_.reset();
    connection_notifier_->NotifyConnectionClosed();
  }

  // Notifies all the observers that the connection is ready.
  void OnConnectionReady(std::unique_ptr<mojo::Receiver<HostType>> receiver) {
    DCHECK(!receiver_);
    // Now that we can finally commit to this connection and will deliver the
    // OnConnectionReady() event, set the connection error handler to notify
    // Observers of connection closures.
    // Note: because the callback will be destroyed with |receiver_|,
    // base::Unretained() can be safely used.
    receiver->set_disconnect_handler(base::BindOnce(
        &ConnectionHolderImpl::OnConnectionClosed, base::Unretained(this)));

    receiver_ = std::move(receiver);
    connection_notifier_->NotifyConnectionReady();
  }

  // This class does not have ownership. The pointers should be managed by the
  // caller.
  ConnectionNotifier* const connection_notifier_;
  InstanceType* instance_ = nullptr;
  uint32_t instance_version_ = 0;
  HostType* host_ = nullptr;

  // Created when both |instance_| and |host_| ptr are set.
  std::unique_ptr<mojo::Receiver<HostType>> receiver_;

  base::WeakPtrFactory<ConnectionHolderImpl> weak_ptr_factory_{this};
};

// Single direction Mojo connection holder implementation.
// (HostType == void means single direction).
// InstanceType should be Mojo interface type (arc::mojom::XxxInstance).
template <typename InstanceType>
class ConnectionHolderImpl<InstanceType, void> {
 public:
  // InstanceType must not have Init() method, which should be for a
  // full-duplex connection.
  static_assert(!HasInit<InstanceType>::value,
                "Full duplex ConnectionHolderImpl should be used instead");

  explicit ConnectionHolderImpl(ConnectionNotifier* connection_notifier)
      : connection_notifier_(connection_notifier) {}

  ConnectionHolderImpl(const ConnectionHolderImpl&) = delete;
  ConnectionHolderImpl& operator=(const ConnectionHolderImpl&) = delete;

  InstanceType* instance() { return instance_; }
  uint32_t instance_version() const { return instance_version_; }

  // For single direction connection, when Instance proxy is obtained,
  // it means connected.
  bool IsConnected() const { return instance_; }

  void SetHost(void* unused) {
    static_assert(!sizeof(*this),
                  "ConnectionHolder::SetHost for single direction connection "
                  "is called unexpectedly.");
    NOTREACHED();
  }

  // Sets the instance.
  void SetInstance(InstanceType* instance,
                   uint32_t version = InstanceType::version_) {
    DCHECK(instance);
    DCHECK(instance_ != instance);

    instance_ = instance;
    instance_version_ = version;

    // There is nothing more than setting in this case. Notify observers.
    connection_notifier_->NotifyConnectionReady();
  }

  // Resets the instance if it matches |instance|.
  void CloseInstance(InstanceType* instance) {
    DCHECK(instance);

    if (instance != instance_) {
      DVLOG(1) << "Dropping request to close a stale instance";
      return;
    }

    instance_ = nullptr;
    instance_version_ = 0;
    connection_notifier_->NotifyConnectionClosed();
  }

 private:
  // This class does not have ownership. The pointers should be managed by the
  // caller.
  ConnectionNotifier* const connection_notifier_;
  InstanceType* instance_ = nullptr;
  uint32_t instance_version_ = 0;
};

}  // namespace internal

// Holds a Mojo connection. This also allows for listening for state changes
// for the particular connection.
// InstanceType and HostType should be Mojo interface type
// (arc::mojom::XxxInstance and arc::mojom::XxxHost respectively).
// If HostType is void, it is single direction Mojo connection, so it only
// looks at Instance pointer.
// Otherwise, it is full duplex Mojo connection. When both Instance and Host
// pointers are set, it calls Instance::Init() method to pass Host pointer
// to the ARC container.
template <typename InstanceType, typename HostType = void>
class ConnectionHolder {
 public:
  using Observer = ConnectionObserver<InstanceType>;
  using Instance = InstanceType;

  ConnectionHolder() = default;

  ConnectionHolder(const ConnectionHolder&) = delete;
  ConnectionHolder& operator=(const ConnectionHolder&) = delete;

  // Returns instance version if instance is connected or 0 otherwise.
  // This method is not intended to be used directly. Instead, prefer to use
  // ARC_GET_INSTANCE_FOR_METHOD() with the expected version and check if it
  // is nullptr.
  uint32_t instance_version() const { return impl_.instance_version(); }

  // Returns true if the Mojo interface is ready at least for its version 0
  // interface. Use an Observer if you want to be notified when this is ready.
  // This can only be called on the thread that this class was created on.
  bool IsConnected() const { return impl_.IsConnected(); }

  // Gets the Mojo interface that's intended to call for
  // |method_name_for_logging|, but only if its reported version is at least
  // |min_version|. Returns nullptr if the connection is either not ready or
  // the instance does not have the requested version, and logs appropriately.
  // This function should not be called directly. Instead, use the
  // ARC_GET_INSTANCE_FOR_METHOD() macro.
  InstanceType* GetInstanceForVersionDoNotCallDirectly(
      uint32_t min_version,
      const char method_name_for_logging[]) {
    if (!impl_.IsConnected()) {
      VLOG(1) << "Instance " << InstanceType::Name_ << " not available.";
      return nullptr;
    }
    if (impl_.instance_version() < min_version) {
      LOG(ERROR) << "Instance for " << InstanceType::Name_
                 << "::" << method_name_for_logging
                 << " version mismatch. Expected " << min_version << " got "
                 << impl_.instance_version();
      return nullptr;
    }
    return impl_.instance();
  }

  // Adds or removes observers. This can only be called on the thread that this
  // class was created on. RemoveObserver does nothing if |observer| is not in
  // the list.
  void AddObserver(Observer* observer) {
    connection_notifier_.AddObserver(observer);
    if (impl_.IsConnected())
      connection_notifier_.NotifyConnectionReady();
  }

  void RemoveObserver(Observer* observer) {
    connection_notifier_.RemoveObserver(observer);
  }

  // Sets |host|. This can be called in both cases; on ready, or on closed.
  // Passing nullptr to |host| means closing.
  // This must not be called if HostType is void (i.e. single direciton
  // connection).
  void SetHost(HostType* host) {
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
    impl_.SetHost(host);
  }

  // Sets |instance| with |version|.
  void SetInstance(InstanceType* instance,
                   uint32_t version = InstanceType::Version_) {
    DCHECK(instance);
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
    impl_.SetInstance(instance, version);
  }

  // Closes |instance|, if it matches against the current instance. Otherwise,
  // it is a no-op.
  void CloseInstance(InstanceType* instance) {
    DCHECK(instance);
    DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
    impl_.CloseInstance(instance);
  }

 private:
  THREAD_CHECKER(thread_checker_);
  internal::ConnectionNotifier connection_notifier_;
  internal::ConnectionHolderImpl<InstanceType, HostType> impl_{
      &connection_notifier_};
};

}  // namespace arc

#endif  // ASH_COMPONENTS_ARC_SESSION_CONNECTION_HOLDER_H_


text:
log = require( 'db-migrate/lib/log' );

exports.connect = function ( config, callback )
{
    var driver, req;

    if ( config.driver === undefined || config.altDriver === undefined )
    {
        throw new Error( 'config must include a driver key specifing which driver to use' );
    }

    if( config.altDriver && typeof( config.altDriver ) === 'object' )
    {
        log.verbose( 'require:', config.altDriver.require );
        driver = require( config.altDriver.require );
    }
    else
    {
        req = 'umigrate-' + ( config.altDriver || config.driver );
        log.verbose( 'require:', req );
        try
        {
            driver = require( req );
        }
        catch ( Exception )
        {
            driver = require( '../../../' + req );
        }
    }

    log.verbose( 'connecting' );
    driver.connect( config, function ( err, db )
    {

        if ( err )
        {

            callback( err );
            return;
        }
        log.verbose( 'connected' );
        callback( null, db );
    } );
};


text:
package com.microsoft.azure.management.compute;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Defines values for DiskSkuTypes.
 */
//TODO: Naming: this should really be DiskSkuType
public final class DiskSkuTypes {
    // This needs to be at the beginning for the initialization to happen correctly
    private static final Map<String, DiskSkuTypes> VALUES_BY_NAME = new HashMap<>();

    /** Static value Aligned for DiskSkuTypes. */
    public static final DiskSkuTypes STANDARD_LRS = new DiskSkuTypes(StorageAccountTypes.STANDARD_LRS);

    /** Static value Classic for DiskSkuTypes. */
    public static final DiskSkuTypes PREMIUM_LRS = new DiskSkuTypes(StorageAccountTypes.PREMIUM_LRS);

    /** The actual serialized value for a DiskSkuTypes instance. */
    private StorageAccountTypes value;

    /**
     * @return predefined disk SKU types
     */
    public static DiskSkuTypes[] values() {
        Collection<DiskSkuTypes> valuesCollection = VALUES_BY_NAME.values();
        return valuesCollection.toArray(new DiskSkuTypes[valuesCollection.size()]);
    }

    /**
     * Creates a custom value for DiskSkuTypes.
     * @param value the custom value
     */
    public DiskSkuTypes(StorageAccountTypes value) {
        // TODO: This constructor should be private, but keeping as is for now to keep 1.0.0 back compat
        this.value = value;
        if (value != null) {
            VALUES_BY_NAME.put(value.toString().toLowerCase(), this);
        }
    }

    /**
     * Parses a value into a disk SKU type and creates a new DiskSkuType instance if not found among the existing ones.
     *
     * @param value a disk SKU type name
     * @return the parsed or created disk SKU type
     */
    public static DiskSkuTypes fromStorageAccountType(StorageAccountTypes value) {
        if (value == null) {
            return null;
        }

        DiskSkuTypes result = VALUES_BY_NAME.get(value.toString().toLowerCase());
        if (result != null) {
            return result;
        } else {
            return new DiskSkuTypes(value);
        }
    }

    /**
     * @return the account type associated with the SKU.
     */
    public StorageAccountTypes accountType() {
        return this.value;
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof DiskSkuTypes)) {
            return false;
        } else if (obj == this) {
            return true;
        } else  if (value == null) {
            return ((DiskSkuTypes) obj).value == null;
        } else {
            return value.equals(((DiskSkuTypes) obj).value);
        }
    }
}