text:
package com.groupbyinc.api.tags;

import com.groupbyinc.api.Query;
import com.groupbyinc.api.model.Navigation;
import com.groupbyinc.api.model.Refinement;
import com.groupbyinc.common.jackson.Mappers;
import com.groupbyinc.common.jackson.core.type.TypeReference;
import com.groupbyinc.util.UrlBeautifier;

import javax.servlet.jsp.JspException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class UrlFunctions {

  private static final TypeReference<List<Navigation>> NAVIGATIONS_TYPE = new TypeReference<List<Navigation>>() {
  };

  public static String toUrlAdd(
      String identifier, String searchString, List<Navigation> navigations, String navigationName, Refinement refinement) throws JspException {
    UrlBeautifier urlBeautifier = getBeautifier(identifier);
    Query refinements = addRefinements(navigations, navigationName, refinement);
    try {
      return urlBeautifier.toUrl(searchString, refinements.getNavigations());
    } catch (UrlBeautifier.UrlBeautificationException e) {
      throw new JspException("Unable to add to url", e);
    }
  }

  private static UrlBeautifier getBeautifier(String identifier) throws JspException {
    UrlBeautifier urlBeautifier = UrlBeautifier.getUrlBeautifiers().get(identifier);
    if (urlBeautifier == null) {
      throw new JspException("Could not find UrlBeautifier named: " + identifier + ". Please call UrlBeautifier.createUrlBeautifier(String) to instantiate");
    }
    return urlBeautifier;
  }

  private static Query addRefinements(List<Navigation> navigations, String navigationName, Refinement refinement) {
    Query query = new Query();
    Map<String, Navigation> queryNavigations = query.getNavigations();
    if (navigations != null) {
      // copy navigations
      List<Navigation> navigationsCopy = Mappers.readValue(Mappers.writeValueAsBytes(navigations, false), NAVIGATIONS_TYPE, false);
      for (Navigation navigation : navigationsCopy) {
        queryNavigations.put(navigation.getName(), navigation);
      }
    }
    if (queryNavigations.get(navigationName) == null) {
      queryNavigations.put(navigationName, new Navigation().setName(navigationName));
    }
    if (refinement != null) {
      queryNavigations.get(navigationName).getRefinements().add(refinement);
    }
    return query;
  }

  public static String toUrlRemove(
      String identifier, String searchString, List<Navigation> navigations, String navigationName, Refinement refinement) throws JspException {
    UrlBeautifier urlBeautifier = getBeautifier(identifier);
    Query refinements = removeRefinements(navigations, navigationName, refinement);
    try {
      return urlBeautifier.toUrl(searchString, refinements.getNavigations());
    } catch (UrlBeautifier.UrlBeautificationException e) {
      throw new JspException("Unable to remove from url", e);
    }
  }

  private static Query removeRefinements(List<Navigation> navigations, String navigationName, Refinement refinement) {
    Query query = new Query();
    Map<String, Navigation> queryNavigations = query.getNavigations();

    for (Navigation n : navigations) {
      queryNavigations.put(n.getName(), n);
    }
    String stringRefinements = query.getRefinementString();
    query = new Query();
    query.addRefinementsByString(stringRefinements);
    queryNavigations = query.getNavigations();
    if (queryNavigations == null) {
      throw new IllegalStateException("No existing refinements so cannot remove a refinement");
    }
    if (refinement != null) {
      Iterator<Map.Entry<String, Navigation>> ni = queryNavigations.entrySet().iterator();
      while (ni.hasNext()) {
        Navigation n = ni.next().getValue();
        if (n.getName().equals(navigationName)) {
          Iterator<Refinement> ri = n.getRefinements().iterator();
          while (ri.hasNext()) {
            Refinement r = ri.next();
            if (r.toTildeString().equals(refinement.toTildeString())) {
              ri.remove();
            }
          }
          if (n.getRefinements().isEmpty()) {
            ni.remove();
          }
        }
      }
    }
    return query;
  }
}


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

001package org.slf4j;
002
003import java.util.concurrent.BrokenBarrierException;
004import java.util.concurrent.CyclicBarrier;
005
006/**
007 * This class demonstrates that threads accessing the STATE variable always see a consistent value.
008 *
009 * During ongoing initialization the observed value is either ONGOING_INITIALIZATION
010 * or one of {SUCCESS, FAILURE}.
011 *
012 * Post initialization the observed value is always one of  {SUCCESS, FAILURE}.
013 *
014 * See also http://jira.qos.ch/browse/SLF4J-167
015 *
016 * @author ceki
017 *
018 */
019public class DoubleCheckedInt {
020
021    final static int THREAD_COUNT = 10 + Runtime.getRuntime().availableProcessors() * 2;
022    final static int UNINITIALIZED_STATE = 0;
023    final static int ONGOING_INITIALIZATION = 1;
024    final static int SUCCESS = 2;
025    final static int FAILURE = 3;
026    final static int NUMBER_OF_STATES = FAILURE + 1;
027
028    private static int STATE = UNINITIALIZED_STATE;
029
030    public static int getState() {
031        if (STATE == 0) {
032            synchronized (DoubleCheckedInt.class) {
033                if (STATE == UNINITIALIZED_STATE) {
034                    STATE = ONGOING_INITIALIZATION;
035                    long r = System.nanoTime();
036                    try {
037                        Thread.sleep(10);
038                    } catch (InterruptedException e) {
039                    }
040                    if (r % 2 == 0) {
041                        STATE = SUCCESS;
042                    } else {
043                        STATE = FAILURE;
044                    }
045                }
046            }
047        }
048        return STATE;
049    }
050
051    static public void main(String[] args) throws InterruptedException, BrokenBarrierException {
052        StateAccessingThread[] preInitializationThreads = harness();
053        check(preInitializationThreads, false);
054
055        System.out.println("============");
056        StateAccessingThread[] postInitializationThreads = harness();
057        check(postInitializationThreads, true);
058    }
059
060    private static StateAccessingThread[] harness() throws InterruptedException, BrokenBarrierException {
061        StateAccessingThread[] threads = new StateAccessingThread[THREAD_COUNT];
062        final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1);
063        for (int i = 0; i < THREAD_COUNT; i++) {
064            threads[i] = new StateAccessingThread(barrier);
065            threads[i].start();
066        }
067
068        barrier.await();
069        for (int i = 0; i < THREAD_COUNT; i++) {
070            threads[i].join();
071        }
072        return threads;
073    }
074
075    private static void check(StateAccessingThread[] threads, boolean postInit) {
076
077        int[] stateCount = getStateCount(threads);
078        printStateCount(stateCount);
079
080        if (stateCount[UNINITIALIZED_STATE] != 0) {
081            throw new IllegalStateException("getState() should never return a zero value");
082        }
083
084        if (stateCount[SUCCESS] != 0 && stateCount[FAILURE] != 0) {
085            throw new IllegalStateException("getState() should return consistent values");
086        }
087
088        if (postInit) {
089            if (stateCount[SUCCESS] != THREAD_COUNT && stateCount[FAILURE] != THREAD_COUNT) {
090                throw new IllegalStateException("getState() should return consistent values");
091            }
092        }
093
094    }
095
096    private static void printStateCount(int[] stateCount) {
097        for (int i = 0; i < NUMBER_OF_STATES; i++) {
098            switch (i) {
099            case UNINITIALIZED_STATE:
100                System.out.println("UNINITIALIZED_STATE count: " + stateCount[i]);
101                break;
102            case ONGOING_INITIALIZATION:
103                System.out.println("ONGOING_INITIALIZATION count: " + stateCount[i]);
104                break;
105            case SUCCESS:
106                System.out.println("SUCCESS count: " + stateCount[i]);
107                break;
108            case FAILURE:
109                System.out.println("FAILURE count: " + stateCount[i]);
110                break;
111            }
112        }
113    }
114
115    private static int[] getStateCount(StateAccessingThread[] threads) {
116        int[] valCount = new int[NUMBER_OF_STATES];
117        for (int i = 0; i < threads.length; i++) {
118            int val = threads[i].state;
119            valCount[val] = valCount[val] + 1;
120        }
121        return valCount;
122    }
123
124    static class StateAccessingThread extends Thread {
125        public int state = -1;
126        final CyclicBarrier barrier;
127
128        StateAccessingThread(CyclicBarrier barrier) {
129            this.barrier = barrier;
130        }
131
132        public void run() {
133            try {
134                barrier.await();
135            } catch (Exception e) {
136                e.printStackTrace();
137            }
138            state = DoubleCheckedInt.getState();
139        }
140    };
141}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CacheTool\Command;

class OpcacheCompileScriptCommandTest extends CommandTest
{
    public function testCommand()
    {
        $this->assertHasOpcache();

        $result = $this->runCommand('opcache:compile:script src/CacheTool.php -v');

        $this->assertStringContainsString('opcache_compile_file(', $result);
        $this->assertStringContainsString('Compiled | Filename', $result);
    }
}


text:
#include <linux/pagemap.h>
#include <linux/backing-dev.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/xattr.h>
#include <linux/security.h>

#include "kernfs-internal.h"

static const struct address_space_operations kernfs_aops = {
	.readpage	= simple_readpage,
	.write_begin	= simple_write_begin,
	.write_end	= simple_write_end,
};

static const struct inode_operations kernfs_iops = {
	.permission	= kernfs_iop_permission,
	.setattr	= kernfs_iop_setattr,
	.getattr	= kernfs_iop_getattr,
	.setxattr	= kernfs_iop_setxattr,
	.removexattr	= kernfs_iop_removexattr,
	.getxattr	= kernfs_iop_getxattr,
	.listxattr	= kernfs_iop_listxattr,
};

static struct kernfs_iattrs *kernfs_iattrs(struct kernfs_node *kn)
{
	static DEFINE_MUTEX(iattr_mutex);
	struct kernfs_iattrs *ret;
	struct iattr *iattrs;

	mutex_lock(&iattr_mutex);

	if (kn->iattr)
		goto out_unlock;

	kn->iattr = kzalloc(sizeof(struct kernfs_iattrs), GFP_KERNEL);
	if (!kn->iattr)
		goto out_unlock;
	iattrs = &kn->iattr->ia_iattr;

	/* assign default attributes */
	iattrs->ia_mode = kn->mode;
	iattrs->ia_uid = GLOBAL_ROOT_UID;
	iattrs->ia_gid = GLOBAL_ROOT_GID;
	iattrs->ia_atime = iattrs->ia_mtime = iattrs->ia_ctime = CURRENT_TIME;

	simple_xattrs_init(&kn->iattr->xattrs);
out_unlock:
	ret = kn->iattr;
	mutex_unlock(&iattr_mutex);
	return ret;
}

static int __kernfs_setattr(struct kernfs_node *kn, const struct iattr *iattr)
{
	struct kernfs_iattrs *attrs;
	struct iattr *iattrs;
	unsigned int ia_valid = iattr->ia_valid;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	iattrs = &attrs->ia_iattr;

	if (ia_valid & ATTR_UID)
		iattrs->ia_uid = iattr->ia_uid;
	if (ia_valid & ATTR_GID)
		iattrs->ia_gid = iattr->ia_gid;
	if (ia_valid & ATTR_ATIME)
		iattrs->ia_atime = iattr->ia_atime;
	if (ia_valid & ATTR_MTIME)
		iattrs->ia_mtime = iattr->ia_mtime;
	if (ia_valid & ATTR_CTIME)
		iattrs->ia_ctime = iattr->ia_ctime;
	if (ia_valid & ATTR_MODE) {
		umode_t mode = iattr->ia_mode;
		iattrs->ia_mode = kn->mode = mode;
	}
	return 0;
}

/**
 * kernfs_setattr - set iattr on a node
 * @kn: target node
 * @iattr: iattr to set
 *
 * Returns 0 on success, -errno on failure.
 */
int kernfs_setattr(struct kernfs_node *kn, const struct iattr *iattr)
{
	int ret;

	mutex_lock(&kernfs_mutex);
	ret = __kernfs_setattr(kn, iattr);
	mutex_unlock(&kernfs_mutex);
	return ret;
}

int kernfs_iop_setattr(struct dentry *dentry, struct iattr *iattr)
{
	struct inode *inode = d_inode(dentry);
	struct kernfs_node *kn = dentry->d_fsdata;
	int error;

	if (!kn)
		return -EINVAL;

	mutex_lock(&kernfs_mutex);
	error = inode_change_ok(inode, iattr);
	if (error)
		goto out;

	error = __kernfs_setattr(kn, iattr);
	if (error)
		goto out;

	/* this ignores size changes */
	setattr_copy(inode, iattr);

out:
	mutex_unlock(&kernfs_mutex);
	return error;
}

static int kernfs_node_setsecdata(struct kernfs_node *kn, void **secdata,
				  u32 *secdata_len)
{
	struct kernfs_iattrs *attrs;
	void *old_secdata;
	size_t old_secdata_len;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	old_secdata = attrs->ia_secdata;
	old_secdata_len = attrs->ia_secdata_len;

	attrs->ia_secdata = *secdata;
	attrs->ia_secdata_len = *secdata_len;

	*secdata = old_secdata;
	*secdata_len = old_secdata_len;
	return 0;
}

int kernfs_iop_setxattr(struct dentry *dentry, const char *name,
			const void *value, size_t size, int flags)
{
	struct kernfs_node *kn = dentry->d_fsdata;
	struct kernfs_iattrs *attrs;
	void *secdata;
	int error;
	u32 secdata_len = 0;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	if (!strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN)) {
		const char *suffix = name + XATTR_SECURITY_PREFIX_LEN;
		error = security_inode_setsecurity(d_inode(dentry), suffix,
						value, size, flags);
		if (error)
			return error;
		error = security_inode_getsecctx(d_inode(dentry),
						&secdata, &secdata_len);
		if (error)
			return error;

		mutex_lock(&kernfs_mutex);
		error = kernfs_node_setsecdata(kn, &secdata, &secdata_len);
		mutex_unlock(&kernfs_mutex);

		if (secdata)
			security_release_secctx(secdata, secdata_len);
		return error;
	} else if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN)) {
		return simple_xattr_set(&attrs->xattrs, name, value, size,
					flags);
	}

	return -EINVAL;
}

int kernfs_iop_removexattr(struct dentry *dentry, const char *name)
{
	struct kernfs_node *kn = dentry->d_fsdata;
	struct kernfs_iattrs *attrs;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	return simple_xattr_remove(&attrs->xattrs, name);
}

ssize_t kernfs_iop_getxattr(struct dentry *dentry, const char *name, void *buf,
			    size_t size)
{
	struct kernfs_node *kn = dentry->d_fsdata;
	struct kernfs_iattrs *attrs;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	return simple_xattr_get(&attrs->xattrs, name, buf, size);
}

ssize_t kernfs_iop_listxattr(struct dentry *dentry, char *buf, size_t size)
{
	struct kernfs_node *kn = dentry->d_fsdata;
	struct kernfs_iattrs *attrs;

	attrs = kernfs_iattrs(kn);
	if (!attrs)
		return -ENOMEM;

	return simple_xattr_list(&attrs->xattrs, buf, size);
}

static inline void set_default_inode_attr(struct inode *inode, umode_t mode)
{
	inode->i_mode = mode;
	inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
}

static inline void set_inode_attr(struct inode *inode, struct iattr *iattr)
{
	inode->i_uid = iattr->ia_uid;
	inode->i_gid = iattr->ia_gid;
	inode->i_atime = iattr->ia_atime;
	inode->i_mtime = iattr->ia_mtime;
	inode->i_ctime = iattr->ia_ctime;
}

static void kernfs_refresh_inode(struct kernfs_node *kn, struct inode *inode)
{
	struct kernfs_iattrs *attrs = kn->iattr;

	inode->i_mode = kn->mode;
	if (attrs) {
		/*
		 * kernfs_node has non-default attributes get them from
		 * persistent copy in kernfs_node.
		 */
		set_inode_attr(inode, &attrs->ia_iattr);
		security_inode_notifysecctx(inode, attrs->ia_secdata,
					    attrs->ia_secdata_len);
	}

	if (kernfs_type(kn) == KERNFS_DIR)
		set_nlink(inode, kn->dir.subdirs + 2);
}

int kernfs_iop_getattr(struct vfsmount *mnt, struct dentry *dentry,
		   struct kstat *stat)
{
	struct kernfs_node *kn = dentry->d_fsdata;
	struct inode *inode = d_inode(dentry);

	mutex_lock(&kernfs_mutex);
	kernfs_refresh_inode(kn, inode);
	mutex_unlock(&kernfs_mutex);

	generic_fillattr(inode, stat);
	return 0;
}

static void kernfs_init_inode(struct kernfs_node *kn, struct inode *inode)
{
	kernfs_get(kn);
	inode->i_private = kn;
	inode->i_mapping->a_ops = &kernfs_aops;
	inode->i_op = &kernfs_iops;

	set_default_inode_attr(inode, kn->mode);
	kernfs_refresh_inode(kn, inode);

	/* initialize inode according to type */
	switch (kernfs_type(kn)) {
	case KERNFS_DIR:
		inode->i_op = &kernfs_dir_iops;
		inode->i_fop = &kernfs_dir_fops;
		if (kn->flags & KERNFS_EMPTY_DIR)
			make_empty_dir_inode(inode);
		break;
	case KERNFS_FILE:
		inode->i_size = kn->attr.size;
		inode->i_fop = &kernfs_file_fops;
		break;
	case KERNFS_LINK:
		inode->i_op = &kernfs_symlink_iops;
		break;
	default:
		BUG();
	}

	unlock_new_inode(inode);
}

/**
 *	kernfs_get_inode - get inode for kernfs_node
 *	@sb: super block
 *	@kn: kernfs_node to allocate inode for
 *
 *	Get inode for @kn.  If such inode doesn't exist, a new inode is
 *	allocated and basics are initialized.  New inode is returned
 *	locked.
 *
 *	LOCKING:
 *	Kernel thread context (may sleep).
 *
 *	RETURNS:
 *	Pointer to allocated inode on success, NULL on failure.
 */
struct inode *kernfs_get_inode(struct super_block *sb, struct kernfs_node *kn)
{
	struct inode *inode;

	inode = iget_locked(sb, kn->ino);
	if (inode && (inode->i_state & I_NEW))
		kernfs_init_inode(kn, inode);

	return inode;
}

/*
 * The kernfs_node serves as both an inode and a directory entry for
 * kernfs.  To prevent the kernfs inode numbers from being freed
 * prematurely we take a reference to kernfs_node from the kernfs inode.  A
 * super_operations.evict_inode() implementation is needed to drop that
 * reference upon inode destruction.
 */
void kernfs_evict_inode(struct inode *inode)
{
	struct kernfs_node *kn = inode->i_private;

	truncate_inode_pages_final(&inode->i_data);
	clear_inode(inode);
	kernfs_put(kn);
}

int kernfs_iop_permission(struct inode *inode, int mask)
{
	struct kernfs_node *kn;

	if (mask & MAY_NOT_BLOCK)
		return -ECHILD;

	kn = inode->i_private;

	mutex_lock(&kernfs_mutex);
	kernfs_refresh_inode(kn, inode);
	mutex_unlock(&kernfs_mutex);

	return generic_permission(inode, mask);
}


text:
<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class UsuarioController extends AbstractActionController {

    private $usuarioDao;
    private $configuracion;

    public function getUsuarioDao() {
        if (null === $this->usuarioDao) {
            $sm = $this->getServiceLocator();
            $this->usuarioDao = $sm->get('Model\Dao\UsuarioDao');
        }
        return $this->usuarioDao;
    }

    public function indexAction() {
        return $this->forward()->dispatch('Application\Controller\Usuario', array('action' => 'listar'));
    }

	public function getConfig(){

	$sm = $this->getServiceLocator();
	$this->configuracion = $sm->get('ConfigIni');

	return $this->configuracion;

}

    public function listarAction() {

	$this->getConfig();

	$titulo = $this->configuracion['parametros']['usuario']['listar']['titulo'];

        return new ViewModel(array('listaUsuario' => $this->getUsuarioDao()->obtenerTodos(),
                    'titulo' => "$titulo"));
    }

    public function verAction() {

	$this->getConfig();

	$titulo = $this->configuracion['parametros']['usuario']['ver']['titulo'];

        $id = (int) $this->params()->fromRoute("id", 0);

        $usuario = $this->getUsuarioDao()->obtenerPorId($id);

        if (null === $usuario) {
            return $this->redirect()->toRoute('application', array('controller' => 'usuario', 'action' => 'listar'));
        }

        return new ViewModel(array('usuario' => $usuario,
                    'titulo' => $titulo));
    }

    public function buscarAction() {

        $nombre = $this->getRequest()->getPost("nombre");

        if (null === $nombre || empty($nombre)) {
            return $this->redirect()->toRoute('application', array('controller' => 'usuario', 'action' => 'listar'));
        }

        $listaUsuario = $this->getUsuarioDao()->buscarPorNombre($nombre);
        $viewModel = new ViewModel(array('listaUsuario' => $listaUsuario,
                    'titulo' => 'Usuarios Encontrados (' . $listaUsuario->count() . ')'));

        $viewModel->setTemplate("application/usuario/listar");

        return $viewModel;
    }

}


text:
package com.ynswet.common.domain;

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

public class ListJsonStructure<T extends Object> extends BaseJsonStructure{

	private List<T> rows= new ArrayList<T>(0);

	public List<T> getRows() {
		return rows;
	}

	public void setRows(List<T> rows) {
		this.rows = rows;
	}

	@Override
	public String toString() {
		return "ListJsonStructure [success=" + getSuccess() + ", msg=" + getMsg()
				+ ", total=" + getTotal() + ", rows=" + rows + "]";
	}

}


text:
1. [Bootstrap](/)
2. [Documentation](/getting-started/introduction/)
3. [Examples](/examples/)
4. Foo [Themes](https://themes.getbootstrap.com)
5. [Expo](https://expo.getbootstrap.com)
6. [Blog](https://blog.getbootstrap.com)


text:
#include <aws/swf/model/LambdaFunctionTimedOutEventAttributes.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SWF
{
namespace Model
{

LambdaFunctionTimedOutEventAttributes::LambdaFunctionTimedOutEventAttributes() :
    m_scheduledEventId(0),
    m_scheduledEventIdHasBeenSet(false),
    m_startedEventId(0),
    m_startedEventIdHasBeenSet(false),
    m_timeoutTypeHasBeenSet(false)
{
}

LambdaFunctionTimedOutEventAttributes::LambdaFunctionTimedOutEventAttributes(const JsonValue& jsonValue) :
    m_scheduledEventId(0),
    m_scheduledEventIdHasBeenSet(false),
    m_startedEventId(0),
    m_startedEventIdHasBeenSet(false),
    m_timeoutTypeHasBeenSet(false)
{
  *this = jsonValue;
}

LambdaFunctionTimedOutEventAttributes& LambdaFunctionTimedOutEventAttributes::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("scheduledEventId"))
  {
    m_scheduledEventId = jsonValue.GetInt64("scheduledEventId");

    m_scheduledEventIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("startedEventId"))
  {
    m_startedEventId = jsonValue.GetInt64("startedEventId");

    m_startedEventIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("timeoutType"))
  {
    m_timeoutType = LambdaFunctionTimeoutTypeMapper::GetLambdaFunctionTimeoutTypeForName(jsonValue.GetString("timeoutType"));

    m_timeoutTypeHasBeenSet = true;
  }

  return *this;
}

JsonValue LambdaFunctionTimedOutEventAttributes::Jsonize() const
{
  JsonValue payload;

  if(m_scheduledEventIdHasBeenSet)
  {
   payload.WithInt64("scheduledEventId", m_scheduledEventId);

  }

  if(m_startedEventIdHasBeenSet)
  {
   payload.WithInt64("startedEventId", m_startedEventId);

  }

  if(m_timeoutTypeHasBeenSet)
  {
   payload.WithString("timeoutType", LambdaFunctionTimeoutTypeMapper::GetNameForLambdaFunctionTimeoutType(m_timeoutType));
  }

  return payload;
}

} // namespace Model
} // namespace SWF
} // namespace Aws


text:
#ifndef _SDL_main_h
#define _SDL_main_h

#include "SDL_stdinc.h"

/**
 *  \file SDL_main.h
 *
 *  Redefine main() on some platforms so that it is called by SDL.
 */

#ifndef SDL_MAIN_HANDLED
#if defined(__WIN32__)
/* On Windows SDL provides WinMain(), which parses the command line and passes
   the arguments to your main function.

   If you provide your own WinMain(), you may define SDL_MAIN_HANDLED
 */
#define SDL_MAIN_AVAILABLE

#elif defined(__WINRT__)
/* On WinRT, SDL provides a main function that initializes CoreApplication,
   creating an instance of IFrameworkView in the process.

   Please note that #include'ing SDL_main.h is not enough to get a main()
   function working.  In non-XAML apps, the file,
   src/main/winrt/SDL_WinRT_main_NonXAML.cpp, or a copy of it, must be compiled
   into the app itself.  In XAML apps, the function, SDL_WinRTRunApp must be
   called, with a pointer to the Direct3D-hosted XAML control passed in.
*/
#define SDL_MAIN_NEEDED

#elif defined(__IPHONEOS__)
/* On iOS SDL provides a main function that creates an application delegate
   and starts the iOS application run loop.

   See src/video/uikit/SDL_uikitappdelegate.m for more details.
 */
#define SDL_MAIN_NEEDED

#elif defined(__ANDROID__)
/* On Android SDL provides a Java class in SDLActivity.java that is the
   main activity entry point.

   See README-android.txt for more details on extending that class.
 */
#define SDL_MAIN_NEEDED

#elif defined(__NACL__)
/* On NACL we use ppapi_simple to set up the application helper code,
   then wait for the first PSE_INSTANCE_DIDCHANGEVIEW event before
   starting the user main function.
   All user code is run in a separate thread by ppapi_simple, thus
   allowing for blocking io to take place via nacl_io
*/
#define SDL_MAIN_NEEDED

#endif
#endif /* SDL_MAIN_HANDLED */

#ifdef __cplusplus
#define C_LINKAGE   "C"
#else
#define C_LINKAGE
#endif /* __cplusplus */

/**
 *  \file SDL_main.h
 *
 *  The application's main() function must be called with C linkage,
 *  and should be declared like this:
 *  \code
 *  #ifdef __cplusplus
 *  extern "C"
 *  #endif
 *  int main(int argc, char *argv[])
 *  {
 *  }
 *  \endcode
 */

#if defined(SDL_MAIN_NEEDED) || defined(SDL_MAIN_AVAILABLE)
#define main    SDL_main
#endif

/**
 *  The prototype for the application's main() function
 */
extern C_LINKAGE int SDL_main(int argc, char *argv[]);

#include "begin_code.h"
#ifdef __cplusplus
extern "C" {
#endif

/**
 *  This is called by the real SDL main function to let the rest of the
 *  library know that initialization was done properly.
 *
 *  Calling this yourself without knowing what you're doing can cause
 *  crashes and hard to diagnose problems with your application.
 */
extern DECLSPEC void SDLCALL SDL_SetMainReady(void);

#ifdef __WIN32__

/**
 *  This can be called to set the application class at startup
 */
extern DECLSPEC int SDLCALL SDL_RegisterApp(char *name, Uint32 style,
                                            void *hInst);
extern DECLSPEC void SDLCALL SDL_UnregisterApp(void);

#endif /* __WIN32__ */

#ifdef __WINRT__

/**
 *  \brief Initializes and launches an SDL/WinRT application.
 *
 *  \param mainFunction The SDL app's C-style main().
 *  \param xamlBackgroundPanel An optional, XAML-based, background panel.
 *     For Non-XAML apps, this value must be set to NULL.  For XAML apps,
 *     pass in a pointer to a SwapChainBackgroundPanel, casted to an
 *     IInspectable (via reinterpret_cast).
 *  \ret 0 on success, -1 on failure.  On failure, use SDL_GetError to retrieve more
 *      information on the failure.
 */
extern DECLSPEC int SDLCALL SDL_WinRTRunApp(int (*mainFunction)(int, char **), void * xamlBackgroundPanel);

#endif /* __WINRT__ */

#ifdef __cplusplus
}
#endif
#include "close_code.h"

#endif /* _SDL_main_h */

/* vi: set ts=4 sw=4 expandtab: */


text:
package io.virtdata.testmappers;

import io.virtdata.annotations.ThreadSafeMapper;

import java.util.function.LongFunction;

@ThreadSafeMapper
public class TestableTemplate implements LongFunction<String> {

    private LongFunction<?>[] funcs;
    private String separator;

    public TestableTemplate(String separator, LongFunction<?>... funcs) {
        this.funcs = funcs;
        this.separator = separator;
    }

    @Override
    public String apply(long value) {
        StringBuilder sb = new StringBuilder();
        for (LongFunction<?> func : funcs) {
            sb.append(func.apply(value).toString());
            sb.append(separator);
        }
        sb.setLength(sb.length()-separator.length());
        return sb.toString();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `db/src/add_retract_alter_set.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>add_retract_alter_set.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../normalize.css">
    <link rel="stylesheet" type="text/css" href="../../rustdoc.css"
          id="mainThemeStyle">

    <link rel="stylesheet" type="text/css" href="../../dark.css">
    <link rel="stylesheet" type="text/css" href="../../light.css" id="themeStyle">

☰

        <button id="theme-picker" aria-label="Pick another theme!">

        </button>

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

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

#![allow(dead_code)]

use std::collections::BTreeMap;

/// Witness assertions and retractions, folding (assertion, retraction) pairs into alterations.
/// Assumes that no assertion or retraction will be witnessed more than once.
///
/// This keeps track of when we see a :db/add, a :db/retract, or both :db/add and :db/retract in
/// some order.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialOrd, PartialEq)]
pub struct AddRetractAlterSet<K, V> {
    pub asserted: BTreeMap<K, V>,
    pub retracted: BTreeMap<K, V>,
    pub altered: BTreeMap<K, (V, V)>,
}

impl<K, V> Default for AddRetractAlterSet<K, V> where K: Ord {
    fn default() -> AddRetractAlterSet<K, V> {
        AddRetractAlterSet {
            asserted: BTreeMap::default(),
            retracted: BTreeMap::default(),
            altered: BTreeMap::default(),
        }
    }
}

impl<K, V> AddRetractAlterSet<K, V> where K: Ord {
    pub fn witness(&mut self, key: K, value: V, added: bool) {
        if added {
            if let Some(retracted_value) = self.retracted.remove(&key) {
                self.altered.insert(key, (retracted_value, value));
            } else {
                self.asserted.insert(key, value);
            }
        } else {
            if let Some(asserted_value) = self.asserted.remove(&key) {
                self.altered.insert(key, (value, asserted_value));
            } else {
                self.retracted.insert(key, value);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let mut set: AddRetractAlterSet<i64, char> = AddRetractAlterSet::default();
        // Assertion.
        set.witness(1, 'a', true);
        // Retraction.
        set.witness(2, 'b', false);
        // Alteration.
        set.witness(3, 'c', true);
        set.witness(3, 'd', false);
        // Alteration, witnessed in the with the retraction before the assertion.
        set.witness(4, 'e', false);
        set.witness(4, 'f', true);

        let mut asserted = BTreeMap::default();
        asserted.insert(1, 'a');
        let mut retracted = BTreeMap::default();
        retracted.insert(2, 'b');
        let mut altered = BTreeMap::default();
        altered.insert(3, ('d', 'c'));
        altered.insert(4, ('e', 'f'));

        assert_eq!(set.asserted, asserted);
        assert_eq!(set.retracted, retracted);
        assert_eq!(set.altered, altered);
    }
}

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

↑

Move up in search results

↓

Move down in search results

↹

Switch tab

⏎

Go to active search result

+

Expand all sections

-

Collapse all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
static CGFloat const AnimationDuration = 0.25;

@interface KCPhotoActionController ()
@property (nonatomic, weak) UIView *targetView;

@property (nonatomic, strong) UIImageView *bgView;

@property (nonatomic, strong) UITableView *actionView;

@end

@implementation KCPhotoActionController

- (instancetype)initWithTargetView:(UIView *)targetView
{
    if (self = [super init]) {
        self.modalPresentationStyle = UIModalPresentationCustom;

        self.targetView = targetView;
    }
    return self;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.view addSubview:self.bgView];
    [self.bgView addSubview:self.actionView];

}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    CGRect targetFrame = [self.targetView.superview convertRect:self.targetView.frame toView:self.view];

    CGFloat margin = 7;
    CGFloat bgW = self.bgView.image.size.width;

    CGFloat actionW = bgW - 2 * margin;
    CGFloat actionH = self.actionView.rowHeight * 4;

    self.actionView.frame = CGRectMake(margin, margin, actionW, actionH);

    CGFloat bgH = actionH + 3 * margin;

    CGFloat bgX = CGRectGetMidX(targetFrame) - bgW * 0.5;
    CGFloat bgY = targetFrame.origin.y - bgH;

    self.bgView.frame = CGRectMake(bgX, bgY, bgW, bgH);

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self show];
}

- (void)show
{

    self.bgView.transform = CGAffineTransformMakeScale(1, 0);
    self.bgView.alpha = 1;

    [UIView animateWithDuration:AnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.bgView.transform = CGAffineTransformIdentity;
    } completion:nil];

}

- (void)dismiss
{
    [UIView animateWithDuration:AnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

        self.bgView.alpha = 0;

    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self dismiss];
}

#pragma mark -Getter
- (UIImageView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"action_bg"]];
        _bgView.userInteractionEnabled = YES;
        _bgView.layer.anchorPoint = CGPointMake(0.5, 1);
    }
    return _bgView;
}

- (UITableView *)actionView
{
    if (!_actionView) {
        _actionView = [[UITableView alloc] init];
        _actionView.rowHeight = 35;
    }
    return _actionView;
}

@end


text: from simpleoncall.tasks.notificatons import *


text:
from libcloud.storage.types import Provider
from libcloud.storage.providers import get_driver

cls = get_driver(Provider.OPENSTACK_SWIFT)

driver = cls(
    "username",
    "api key",
    region="ord",
    ex_force_auth_url="https://auth.api.rackspacecloud.com:443",
    ex_force_service_type="object-store",
    ex_force_service_name="cloudFiles",
)

print(driver.list_containers())


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2014-5-10 21:21:33 by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
    <class name="com.ams.system.entity.Role" table="t_role" >
        <id name="roleId" type="string">
            <column name="role_Id" length="32" />
            <generator class="assigned" />
        </id>
        <property name="roleName" type="string">
            <column name="roleName" length="50" not-null="true">
                <comment>角色名称</comment>
            </column>
        </property>
    </class>
</hibernate-mapping>


text:
namespace content {
namespace devtools {
namespace tracing {

using Response = DevToolsProtocolClient::Response;

namespace {

const double kMinimumReportingInterval = 250.0;

class DevToolsTraceSinkProxy : public TracingController::TraceDataSink {
 public:
  explicit DevToolsTraceSinkProxy(base::WeakPtr<TracingHandler> handler)
      : tracing_handler_(handler) {}

  void AddTraceChunk(const std::string& chunk) override {
    if (TracingHandler* h = tracing_handler_.get())
      h->OnTraceDataCollected(chunk);
  }
  void Close() override {
    if (TracingHandler* h = tracing_handler_.get())
      h->OnTraceComplete();
  }

 private:
  ~DevToolsTraceSinkProxy() override {}

  base::WeakPtr<TracingHandler> tracing_handler_;
};

class DevToolsStreamTraceSink : public TracingController::TraceDataSink {
 public:
  explicit DevToolsStreamTraceSink(
      base::WeakPtr<TracingHandler> handler,
      const scoped_refptr<DevToolsIOContext::Stream>& stream)
      : stream_(stream),
        tracing_handler_(handler),
        first_chunk_(true) {}

  void AddTraceChunk(const std::string& chunk) override {
    // FIXME: change interface to pass chunks as refcounted strings.
    scoped_refptr<base::RefCountedString> ref_counted_chunk
        = new base::RefCountedString();
    std::string prefix = first_chunk_ ? "[" : ",";
    ref_counted_chunk->data() = prefix + chunk;
    first_chunk_ = false;
    stream_->Append(ref_counted_chunk);
  }

  void Close() override {
    if (TracingHandler* h = tracing_handler_.get()) {
      std::string suffix = "]";
      stream_->Append(base::RefCountedString::TakeString(&suffix));
      h->OnTraceToStreamComplete(stream_->handle());
    }
  }

 private:
  ~DevToolsStreamTraceSink() override {}

  scoped_refptr<DevToolsIOContext::Stream> stream_;
  base::WeakPtr<TracingHandler> tracing_handler_;
  bool first_chunk_;
};

}  // namespace

TracingHandler::TracingHandler(TracingHandler::Target target,
                               DevToolsIOContext* io_context)
    : target_(target),
      io_context_(io_context),
      did_initiate_recording_(false),
      return_as_stream_(false),
      weak_factory_(this) {}

TracingHandler::~TracingHandler() {
}

void TracingHandler::SetClient(scoped_ptr<Client> client) {
  client_.swap(client);
}

void TracingHandler::Detached() {
  if (did_initiate_recording_)
    StopTracing(scoped_refptr<TracingController::TraceDataSink>());
}

void TracingHandler::OnTraceDataCollected(const std::string& trace_fragment) {
  // Hand-craft protocol notification message so we can substitute JSON
  // that we already got as string as a bare object, not a quoted string.
  std::string message(
      "{ \"method\": \"Tracing.dataCollected\", \"params\": { \"value\": [");
  const size_t messageSuffixSize = 10;
  message.reserve(message.size() + trace_fragment.size() + messageSuffixSize);
  message += trace_fragment;
  message += "] } }";
  client_->SendRawNotification(message);
}

void TracingHandler::OnTraceComplete() {
  client_->TracingComplete(TracingCompleteParams::Create());
}

void TracingHandler::OnTraceToStreamComplete(const std::string& stream_handle) {
  client_->TracingComplete(
      TracingCompleteParams::Create()->set_stream(stream_handle));
}

Response TracingHandler::Start(DevToolsCommandId command_id,
                               const std::string* categories,
                               const std::string* options,
                               const double* buffer_usage_reporting_interval,
                               const std::string* transfer_mode) {
  if (IsTracing())
    return Response::InternalError("Tracing is already started");

  did_initiate_recording_ = true;
  return_as_stream_ =
      transfer_mode && *transfer_mode == start::kTransferModeReturnAsStream;
  base::trace_event::TraceConfig trace_config(
      categories ? *categories : std::string(),
      options ? *options : std::string());
  if (buffer_usage_reporting_interval)
    SetupTimer(*buffer_usage_reporting_interval);

  // If inspected target is a render process Tracing.start will be handled by
  // tracing agent in the renderer.
  if (target_ == Renderer) {
    TracingController::GetInstance()->StartTracing(
        trace_config,
        TracingController::StartTracingDoneCallback());
    return Response::FallThrough();
  }

  TracingController::GetInstance()->StartTracing(
      trace_config,
      base::Bind(&TracingHandler::OnRecordingEnabled,
                 weak_factory_.GetWeakPtr(),
                 command_id));
  return Response::OK();
}

Response TracingHandler::End(DevToolsCommandId command_id) {
  // Startup tracing triggered by --trace-config-file is a special case, where
  // tracing is started automatically upon browser startup and can be stopped
  // via DevTools.
  if (!did_initiate_recording_ && !IsStartupTracingActive())
    return Response::InternalError("Tracing is not started");

  scoped_refptr<TracingController::TraceDataSink> proxy;
  if (return_as_stream_) {
    proxy = new DevToolsStreamTraceSink(
        weak_factory_.GetWeakPtr(), io_context_->CreateTempFileBackedStream());
  } else {
    proxy = new DevToolsTraceSinkProxy(weak_factory_.GetWeakPtr());
  }
  StopTracing(proxy);
  // If inspected target is a render process Tracing.end will be handled by
  // tracing agent in the renderer.
  return target_ == Renderer ? Response::FallThrough() : Response::OK();
}

Response TracingHandler::GetCategories(DevToolsCommandId command_id) {
  TracingController::GetInstance()->GetCategories(
      base::Bind(&TracingHandler::OnCategoriesReceived,
                 weak_factory_.GetWeakPtr(),
                 command_id));
  return Response::OK();
}

void TracingHandler::OnRecordingEnabled(DevToolsCommandId command_id) {
  client_->SendStartResponse(command_id, StartResponse::Create());
}

void TracingHandler::OnBufferUsage(float percent_full,
                                   size_t approximate_event_count) {
  // TODO(crbug426117): remove set_value once all clients have switched to
  // the new interface of the event.
  client_->BufferUsage(BufferUsageParams::Create()
                           ->set_value(percent_full)
                           ->set_percent_full(percent_full)
                           ->set_event_count(approximate_event_count));
}

void TracingHandler::OnCategoriesReceived(
    DevToolsCommandId command_id,
    const std::set<std::string>& category_set) {
  std::vector<std::string> categories;
  for (const std::string& category : category_set)
    categories.push_back(category);
  client_->SendGetCategoriesResponse(command_id,
      GetCategoriesResponse::Create()->set_categories(categories));
}

Response TracingHandler::RequestMemoryDump(DevToolsCommandId command_id) {
  if (!IsTracing())
    return Response::InternalError("Tracing is not started");

  base::trace_event::MemoryDumpManager::GetInstance()->RequestGlobalDump(
      base::trace_event::MemoryDumpType::EXPLICITLY_TRIGGERED,
      base::trace_event::MemoryDumpLevelOfDetail::DETAILED,
      base::Bind(&TracingHandler::OnMemoryDumpFinished,
                 weak_factory_.GetWeakPtr(), command_id));
  return Response::OK();
}

void TracingHandler::OnMemoryDumpFinished(DevToolsCommandId command_id,
                                          uint64 dump_guid,
                                          bool success) {
  client_->SendRequestMemoryDumpResponse(
      command_id,
      RequestMemoryDumpResponse::Create()
          ->set_dump_guid(base::StringPrintf("0x%" PRIx64, dump_guid))
          ->set_success(success));
}

void TracingHandler::SetupTimer(double usage_reporting_interval) {
  if (usage_reporting_interval == 0) return;

  if (usage_reporting_interval < kMinimumReportingInterval)
      usage_reporting_interval = kMinimumReportingInterval;

  base::TimeDelta interval = base::TimeDelta::FromMilliseconds(
      std::ceil(usage_reporting_interval));
  buffer_usage_poll_timer_.reset(new base::Timer(
      FROM_HERE, interval,
      base::Bind(base::IgnoreResult(&TracingController::GetTraceBufferUsage),
                 base::Unretained(TracingController::GetInstance()),
                 base::Bind(&TracingHandler::OnBufferUsage,
                            weak_factory_.GetWeakPtr())),
      true));
  buffer_usage_poll_timer_->Reset();
}

void TracingHandler::StopTracing(
    const scoped_refptr<TracingController::TraceDataSink>& trace_data_sink) {
  buffer_usage_poll_timer_.reset();
  TracingController::GetInstance()->StopTracing(trace_data_sink);
  did_initiate_recording_ = false;
}

bool TracingHandler::IsTracing() const {
  return TracingController::GetInstance()->IsTracing();
}

bool TracingHandler::IsStartupTracingActive() {
  return ::tracing::TraceConfigFile::GetInstance()->IsEnabled() &&
      TracingController::GetInstance()->IsTracing();
}

}  // namespace tracing
}  // namespace devtools
}  // namespace content


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

namespace Wifinian.Models.Wlan
{
	internal interface IWlanWorker : IDisposable
	{
		bool IsWorkable { get; }

		event EventHandler NetworkRefreshed;
		event EventHandler AvailabilityChanged;
		event EventHandler InterfaceChanged;
		event EventHandler ConnectionChanged;
		event EventHandler ProfileChanged;

		Task ScanNetworkAsync(TimeSpan timeout);

		Task<IEnumerable<ProfileItem>> GetProfilesAsync();

		Task<bool> SetProfileOptionAsync(ProfileItem profileItem);
		Task<bool> SetProfilePositionAsync(ProfileItem profileItem, int position);
		Task<bool> RenameProfileAsync(ProfileItem profileItem, string profileName);
		Task<bool> DeleteProfileAsync(ProfileItem profileItem);

		Task<bool> ConnectNetworkAsync(ProfileItem profileItem, TimeSpan timeout);
		Task<bool> DisconnectNetworkAsync(ProfileItem profileItem, TimeSpan timeout);
	}
}


text:
Given(/^a set of (\d+) squeeks$/) do |number|
  user = Fabricate(:user, username: "username")
  number.to_i.times do |num|
    Squeek.create!(body: "Squeek #{num + 1}", user: user, consumers_only: false)
  end
end

Then(/^I should see (\d+) squeeks$/) do |number|
  page.should have_css("ul.squeeks li", count: number)
end

Then(/^I should see pagination links$/) do
  page.should have_css("nav.pagination", count: 1)
end


text:
package com.tyust.sys.web;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tyust.dao.RoleFuncComDao;
import com.tyust.util.RequestUtils;
import com.tyust.util.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.tyust.sys.facade.SysUserFacade;

import com.alibaba.fastjson.JSONObject;

/**
 * 系统名称:

 * 模块名称:

 * 中文类名:

 * 概要说明:

 * @author bhz(Alienware)
 * @since 2016年2月29日
 */
@Controller
public class SysIndexController {

	@Resource
	private SysUserFacade sysUserFacade;

	private RoleFuncComDao roleFuncComDao;

	public RoleFuncComDao getRoleFuncComDao() {
		return roleFuncComDao;
	}
	@Autowired
	public void setRoleFuncComDao(RoleFuncComDao roleFuncComDao) {
		this.roleFuncComDao = roleFuncComDao;
	}

	/**
     * 方法名称:系统首页

     * 概要说明:

     *
     * @param request 页面请求
     * @param response 页面响应
     * @return ModelAndView 模型视图
     */
    @RequestMapping("/sysindex.html")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView ret = new ModelAndView();
        String userId = RequestUtils.getCurrentUserId(request);
        String userName = RequestUtils.getCurrentUserName(request);
        String roleCode = RequestUtils.getCurrentRoleCode(request);
        String orgId = RequestUtils.getCurrentOrgId(request);
        List<JSONObject> funcList = this.roleFuncComDao.getFuncList(roleCode, "01");
        ret.addObject("funcList", funcList.toString());
        return ret;
    }

    @RequestMapping("/sysFuncList.json")
    public void sysFuncList(HttpServletRequest request, HttpServletResponse response, String id){
    	String roleCode = RequestUtils.getCurrentRoleCode(request);
    	List<JSONObject> records = new ArrayList<JSONObject>();
    	List<JSONObject> funcList = this.roleFuncComDao.getFuncList(roleCode, id);
    	for (JSONObject jsonObject : funcList) {
			JSONObject record = new JSONObject();
			//'id' ,'text' , 'type' , 'leaf', 'url'
			record.put("id", jsonObject.getString("FUNC_CODE"));
			record.put("text", jsonObject.getString("FUNC_NAME"));
			record.put("type", jsonObject.getString("FUNC_TYPE"));
			record.put("leaf", true);
			record.put("url", jsonObject.getString("FUNC_PATH"));
			records.add(record);
		}
    	ResponseUtils.putJsonResponse(response, records);

    }

}


text:
{-# LANGUAGE DeriveGeneric #-}
-- | Functions for working with the Login Endpoint.

module IG.REST.Login where

import Control.Lens hiding ((.=))
import Data.Aeson
import Data.Aeson.Lens
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.String.Conversions
import Data.Text as Text
import Data.Text.Encoding as TE
import Data.Scientific
import GHC.Generics
import IG (ApiError, apiError, decodeError, host)
import IG.REST
import Network.Wreq

data Credentials = Credentials { demo :: Credential
                               , production :: Credential
                               } deriving (Generic, Show)

instance FromJSON Credentials

data Credential = Credential { apiKey :: Text
                  , username :: Text
                  , pass :: Text
                  } deriving (Generic, Show)

instance FromJSON Credential

loginToApi :: Bool -> IO (Either String (AuthHeaders, LoginResponse))
loginToApi isDemo = do
    (apiKey, loginDetails) <- getCredentials isDemo
    response <- login isDemo apiKey loginDetails
    return $ response

getCredentials :: Bool -> IO (Text, LoginBody)
getCredentials isDemo = do
  file <- readFile "ig_creds.json"
  let allCreds = fromJust . decode $ cs file
  let creds = if isDemo then demo allCreds else production allCreds
  let a = apiKey creds
  let identifier = username creds
  let p = pass creds
  let loginDetails = LoginBody False identifier p
  return $ (a, loginDetails)

getKey :: String -> Text -> Text
getKey creds k = fromJust $ creds ^? key k . _String

-- | Represents the payload returned by the API when the user successfully logs
-- in.
data LoginResponse = LoginResponse {
                                   -- | AccountInfo object
                                     accountInfo :: AccountInfo
                                   -- | Account type
                                   , accountType :: AccountType
                                   -- | Array of details for each user account
                                   , accounts :: [AccountDetails]
                                   -- | Client Identifier
                                   , clientId :: Text
                                   -- | Id of account in use
                                   , currentAccountId :: Text
                                   -- | Account Currency
                                   , currencyIsoCode :: Text
                                   -- | Account currency symbol
                                   , currencySymbol :: Text
                                   -- | Whether or not the account can deal
                                   , dealingEnabled :: Bool
                                   -- | True if the client has active demo accounts
                                   , hasActiveDemoAccounts :: Bool
                                   -- | True if the client has active live accounts
                                   , hasActiveLiveAccounts :: Bool
                                   -- | The endpoint for subscribing to Lightstreamer
                                   , lightstreamerEndpoint :: Text
                                   -- | Describes the environment to be used as the rerouting destination
                                   , reroutingEnvironment :: Maybe ReroutingEnvironment
                                   -- | Client account timezone offset relative to UTC, expressed in hours
                                   , timezoneOffset :: Integer
                                   -- | True if client can use trailing stops
                                   , trailingStopsEnabled :: Bool
                                   } deriving (Eq, Generic, Show)

instance FromJSON LoginResponse

-- | Client Account Info as returned by a login request
data AccountInfo = AccountInfo {
                               -- | Account funds available for trading
                                 available :: Scientific
                               -- | Balance of funds in the account
                               , balance :: Scientific
                               -- | Minimum deposit required for margins
                               , deposit :: Scientific
                               -- | Account profit and loss
                               , profitLoss :: Scientific
                               } deriving (Eq, Generic, Show)

instance FromJSON AccountInfo

-- | The three different types of account that IG support
data AccountType = CFD
                 | PHYSICAL
                 | SPREADBET
                 deriving (Eq, Generic, Show)

instance FromJSON AccountType

-- | The Details of an account
data AccountDetails = AccountDetails {
                                     -- | The account id
                                       accountId :: Text
                                     -- | The Account name
                                     , accountName :: Text
                                     -- | The type of account
                                     , accountType' :: AccountType
                                     -- | Indicates where or not this is the preferred account
                                     , preferred :: Bool
                                     } deriving (Eq, Generic, Show)

instance FromJSON AccountDetails where

  parseJSON = withObject "accountDetails" $ \o -> do
    id <- o .: "accountId"
    name <- o .: "accountName"
    type' <- o .: "accountType"
    pref <- o .: "preferred"
    return $ AccountDetails id name type' pref

-- | TODO: What is the Rerouting Environment?
data ReroutingEnvironment = DEMO
                          | LIVE
                          | TEST
                          | UAT
                          deriving (Eq, Generic, Show)

instance FromJSON ReroutingEnvironment

-- | Represents the body content required to successfully log into the api
data LoginBody = LoginBody {
                           -- | Whether or not the password has been encrypted
                             encryptedPassword :: Bool
                           -- | Client login identifier (username)
                           , identifier :: Text
                           -- | The client password
                           , password :: Text
                           } deriving (Eq, Generic, Show)

instance ToJSON LoginBody

restPath :: Text
restPath = "gateway/deal/session"

-- | Log in to the IG API. On success, a
login :: Bool -> Text -> LoginBody -> IO (Either String (AuthHeaders, LoginResponse))
login isDemo key logBody = do
  response <- postWith (loginOptions key) loginUrl (toJSON logBody)
  case response ^. responseStatus . statusCode of
       200  -> do
         -- TODO could we use either here instead of cascading cases?
         let loginResponse = eitherDecode (response ^. responseBody) :: Either String LoginResponse
         case loginResponse of
              Left e -> return $ Left e
              Right res ->
                let tokens = getSecurityHeaders response
                in case tokens of
                        Just (cst, xst) -> do
                          let clientToken = decodeUtf8 cst
                          let sessToken = decodeUtf8 xst
                          return $ Right (AuthHeaders clientToken sessToken key isDemo, res)
                        Nothing -> return $ Left "Could not parse tokens"
       _ -> apiError response Map.empty
  where loginUrl = cs $ host isDemo </> restPath

loginOptions :: Text -> Options
loginOptions key = baseHeaders "2" key

getSecurityHeaders :: Response BL.ByteString -> Maybe (BS.ByteString, BS.ByteString)
getSecurityHeaders response = (,) <$> cst <*> xst
  where cst = response ^? responseHeader "CST"
        xst = response ^? responseHeader "X-SECURITY-TOKEN"

-- | Log out of the API
logout :: AuthHeaders -> IO (Either ApiError ())
logout headers = do
  let opts = buildHeaders "1" headers
  r <- deleteWith opts $ cs (host (isDemo headers) </> restPath)
  case r ^. responseStatus ^. statusCode of
       204 -> do return $ Right ()
       _   -> do return . Left $ decodeError (r ^. responseBody)

-- | Details of the current session as returned by GET /session Note that
-- all of the fields in this object terminate with an apostrophe. This is to
-- avoid name collisions with LoginResponse and will be updated in future
-- releases, OverloadedRecordFields is implemented in GHC
data SessionDetails = SessionDetails { clientId' :: Text
                                     , accountId' :: Text
                                     , timezoneOffset' :: Int
                                     , locale' :: Text
                                     , currency' :: Text
                                     , lightstreamerEndpoint' :: Text
                                     } deriving (Eq, Generic, Show)

instance FromJSON SessionDetails where

  parseJSON = withObject "SessionDetails" $ \o -> do
    cId <- o .: "clientId"
    aId <- o .: "accountId"
    tzO <- o .: "timezoneOffset"
    loc <- o .: "locale"
    cny <- o .: "currency"
    lse <- o .: "lightstreamerEndpoint"
    return $ SessionDetails cId aId tzO loc cny lse

-- | Return an instance of SessionDetails for the active account
sessionDetails :: AuthHeaders -> IO (Either ApiError SessionDetails)
sessionDetails a@(AuthHeaders _ _ _ isLogin) = do
  let opts = buildHeaders "1" a
  r <- getWith opts (cs $ host isLogin <> restPath)
  let bod = r ^. responseBody
  case r ^. responseStatus ^. statusCode of
       200 -> do
         either (\_ -> error "Could not decode session details")
                (\sessionDetails -> do return $ Right sessionDetails)
                (eitherDecode bod)
       _ -> do
         return $ Left (decodeError bod)

-- Data required for a switchAccount request
data SwitchAccountData = SwitchAccountData Text Bool deriving (Eq, Generic, Show)

instance ToJSON SwitchAccountData where
  toJSON (SwitchAccountData accId defaultAccount) =
    object [ "accountId" .= accId
           , "defaultAccount" .= defaultAccount
           ]

-- | Switch to a different user account. Untested as of 26/01/2016 since 403
-- error was constantly returned by the Api Companion when testing
switchAccount :: AuthHeaders -> Text -> Bool -> IO (Either String ())
switchAccount a@(AuthHeaders _ _ _ isLogin) id isDefault = do
  let payload = toJSON $ SwitchAccountData id isDefault
  let opts = buildHeaders "1" a
  r <- putWith opts (cs $ host isLogin </> restPath) payload
  case r ^. responseStatus ^. statusCode of
       200 -> return $ Right ()
       _   -> apiError r Map.empty

accountsPath :: Bool -> String
accountsPath isLogin = cs $ host isLogin </> restPath


text:
#include <rose/Rose.hpp>
#include <rose/ControlList.hpp>
#include <rose/ctl/Widget.hpp>

using namespace rose;
using namespace rose::ctl;

void ControlList::Enable()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->SetDisabled(false);
    }
}

void ControlList::Disable()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->SetDisabled(true);
    }
}

void ControlList::Show()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->Show();
    }
}

void ControlList::Hide()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->Hide();
    }
}

rose::String ControlList::GetValue()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        return ( *it)->GetValue();
    }

    return "";
}

void ControlList::SetValue(const rose::String& value)
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->SetValue(value);
    }
}

void ControlList::MoveBy(const rose::Point & point)
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->MoveBy(point.x, point.y);
    }
}

void ControlList::DoAction()
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->DoAction();
    }
}

void ControlList::SetActionInternal(rose::EventHandler* pObject, void ( rose::EventHandler::*f)(rose::CEventInfoRef), const rose::Packet & packet)
{
    for(List::const_iterator it = list.begin(); it != list.end(); ++it)
    {
        (*it)->SetAction(pObject, f, packet);
    }
}


text:
title: Access Property Names with Bracket Notation
localeTitle: الوصول إلى خاصية الأسماء مع تدرج قوس
---
## الوصول إلى خاصية الأسماء مع تدرج قوس

طريقة:

*   باستخدام `checkInventory()` قوس ببساطة اكتب بيان الإرجاع في الدالة `checkInventory()` .
*   كتلة التعليمات البرمجية التالية يوضح بناء الجملة المطلوب.

## مثال:

 `let juice = {
  apple: 1.15,
  orange: 1.45
 };
 function checkInventory(scannedItem) {
  return juice[scannedItem];
 }
`

## حل:

 `let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
 };
 // do not change code above this line

 function checkInventory(scannedItem) {
  // change code below this line
  return foods[scannedItem];
 }

 // change code below this line to test different cases:
 console.log(checkInventory("apples"));
`


text:
var cardsAssort = [
    {name: "Circle", type: "circle"},
    {name: "Triangle", type: "triangle"},
    {name: "Square", type: "square"}
];

Cards = function (options) {

    options = options || {};
    var cards = [],
        self = this;

    this.create = function (name) {

        var cardType = _.find(cardsAssort, function (cardType) {
            return cardType.name === name;
        });

        if (cardType) {
            cards.push(cardType);
        }
    };

    this.build = function () {

        var playfieldCards = [];
        _.each(cards, function (card) {

            playfieldCards.push(_.clone(card));
            playfieldCards.push(_.clone(card));
        });
        return playfieldCards.shuffle();
    };

    var getRandomizedCardType = function () {

        var cardTypes = ["Circle", "Triangle", "Square"];
        var randomized = Math.random() * (cardTypes.length - 1);
        var randomizedCardType = cardTypes[Math.round(randomized)];

        var found = _.find(cards, function (card) {
            return card.name === randomizedCardType;
        });

        return (found) ? getRandomizedCardType() : randomizedCardType;
    };

    var init = function () {

        if (options.amount && _.isNumber(options.amount) && options.amount > 0) {

            var thisCards = _.range(options.amount);
            _.each(thisCards, function (value, key) {

                var randomized = getRandomizedCardType();
                self.create(randomized);
            });
        }
    };

    init();
    return this;
};


text:
Change log
==========

3.5.0 (2022-06-23)
------------------

* Properly implemented tracking and display of PostgreSQL transactions.
* Removed third party panels which have been archived on GitHub.
* Added Django 4.1b1 to the CI matrix.
* Stopped crashing when ``request.GET`` and ``request.POST`` are neither
  dictionaries nor ``QueryDict`` instances. Using anything but ``QueryDict``
  instances isn't a valid use of Django but, again, django-debug-toolbar
  shouldn't crash.
* Fixed the cache panel to work correctly in the presence of concurrency by
  avoiding the use of signals.
* Reworked the cache panel instrumentation mechanism to monkey patch methods on
  the cache instances directly instead of replacing cache instances with
  wrapper classes.
* Added a :meth:`debug_toolbar.panels.Panel.ready` class method that panels can
  override to perform any initialization or instrumentation that needs to be
  done unconditionally at startup time.
* Added pyflame (for flame graphs) to the list of third-party panels.
* Fixed the cache panel to correctly count cache misses from the get_many()
  cache method.
* Removed some obsolete compatibility code from the stack trace recording code.
* Added a new mechanism for capturing stack traces which includes per-request
  caching to reduce expensive file system operations.  Updated the cache and
  SQL panels to record stack traces using this new mechanism.
* Changed the ``docs`` tox environment to allow passing positional arguments.
  This allows e.g. building a HTML version of the docs using ``tox -e docs
  html``.
* Stayed on top of pre-commit hook updates.
* Replaced ``OrderedDict`` by ``dict`` where possible.

Deprecated features
~~~~~~~~~~~~~~~~~~~

* The ``debug_toolbar.utils.get_stack()`` and
  ``debug_toolbar.utils.tidy_stacktrace()`` functions are deprecated in favor
  of the new ``debug_toolbar.utils.get_stack_trace()`` function.  They will
  removed in the next major version of the Debug Toolbar.

3.4.0 (2022-05-03)
------------------

* Fixed issue of stacktrace having frames that have no path to the file,
  but are instead a string of the code such as
  ``'<frozen importlib._bootstrap>'``.
* Renamed internal SQL tracking context var from ``recording`` to
  ``allow_sql``.

3.3.0 (2022-04-28)
------------------

* Track calls to :py:meth:`django.core.caches.cache.get_or_set`.
* Removed support for Django < 3.2.
* Updated check ``W006`` to look for
  ``django.template.loaders.app_directories.Loader``.
* Reset settings when overridden in tests. Packages or projects using
  django-debug-toolbar can now use Django's test settings tools, like
  ``@override_settings``, to reconfigure the toolbar during tests.
* Optimize rendering of SQL panel, saving about 30% of its run time.
* New records in history panel will flash green.
* Automatically update History panel on AJAX requests from client.

3.2.4 (2021-12-15)
------------------

* Revert PR 1426 - Fixes issue with SQL parameters having leading and
  trailing characters stripped away.

3.2.3 (2021-12-12)
------------------

* Changed cache monkey-patching for Django 3.2+ to iterate over existing
  caches and patch them individually rather than attempting to patch
  ``django.core.caches`` as a whole. The ``middleware.cache`` is still
  being patched as a whole in order to attempt to catch any cache
  usages before ``enable_instrumentation`` is called.
* Add check ``W006`` to warn that the toolbar is incompatible with
  ``TEMPLATES`` settings configurations with ``APP_DIRS`` set to ``False``.
* Create ``urls`` module and update documentation to no longer require
  importing the toolbar package.

3.2.2 (2021-08-14)
------------------

* Ensured that the handle stays within bounds when resizing the window.
* Disabled ``HistoryPanel`` when ``RENDER_PANELS`` is ``True``
  or if ``RENDER_PANELS`` is ``None`` and the WSGI container is
  running with multiple processes.
* Fixed ``RENDER_PANELS`` functionality so that when ``True`` panels are
  rendered during the request and not loaded asynchronously.
* HistoryPanel now shows status codes of responses.
* Support ``request.urlconf`` override when checking for toolbar requests.

3.2.1 (2021-04-14)
------------------

* Fixed SQL Injection vulnerability, CVE-2021-30459. The toolbar now
  calculates a signature on all fields for the SQL select, explain,
  and analyze forms.
* Changed ``djdt.cookie.set()`` to set ``sameSite=Lax`` by default if
  callers do not provide a value.
* Added ``PRETTIFY_SQL`` configuration option to support controlling
  SQL token grouping. By default it's set to True. When set to False,
  a performance improvement can be seen by the SQL panel.
* Added a JavaScript event when a panel loads of the format
  ``djdt.panel.[PanelId]`` where PanelId is the ``panel_id`` property
  of the panel's Python class. Listening for this event corrects the bug
  in the Timer Panel in which it didn't insert the browser timings
  after switching requests in the History Panel.
* Fixed issue with the toolbar expecting URL paths to start with
  ``/__debug__/`` while the documentation indicates it's not required.

3.2 (2020-12-03)
----------------

* Moved CI to GitHub Actions: https://github.com/jazzband/django-debug-toolbar/actions
* Stopped crashing when ``request.GET`` and ``request.POST`` are
  dictionaries instead of ``QueryDict`` instances. This isn't a valid
  use of Django but django-debug-toolbar shouldn't crash anyway.
* Fixed a crash in the history panel when sending a  JSON POST request
  with invalid JSON.
* Added missing signals to the signals panel by default.
* Documented how to avoid CORS errors now that we're using JavaScript
  modules.
* Verified support for Python 3.9.
* Added a ``css`` and a ``js`` template block to
  ``debug_toolbar/base.html`` to allow overriding CSS and JS.

3.2a1 (2020-10-19)
------------------

* Fixed a regression where the JavaScript code crashed with an invalid
  CSS selector when searching for an element to replace.
* Replaced remaining images with CSS.
* Continued refactoring the HTML and CSS code for simplicity, continued
  improving the use of semantic HTML.
* Stopped caring about prehistoric browsers for good. Started splitting
  up the JavaScript code to take advantage of JavaScript modules.
* Continued removing unused CSS.
* Started running Selenium tests on Travis CI.
* Added a system check which prevents using django-debug-toolbar without
  any enabled panels.
* Added :meth:`Panel.run_checks() <debug_toolbar.panels.Panel.run_checks>` for
  panels to verify the configuration before the application starts.
* Validate the static file paths specified in ``STATICFILES_DIRS``
  exist via :class:`~debug_toolbar.panels.staticfiles.StaticFilesPanel`
* Introduced `prettier <https://prettier.io/>`__ to format the frontend
  code.
* Started accessing history views using GET requests since they do not
  change state on the server.
* Fixed a bug where unsuccessful requests (e.g. network errors) were
  silently ignored.
* Started spellchecking the documentation.
* Removed calls to the deprecated ``request.is_ajax()`` method. These calls
  were unnecessary now that most endpoints return JSON anyway.
* Removed support for Python 3.5.

3.1 (2020-09-21)
----------------

* Fixed a crash in the history panel when sending an empty JSON POST
  request.
* Made ``make example`` also set up the database and a superuser
  account.
* Added a Makefile target for regenerating the django-debug-toolbar
  screenshot.
* Added automatic escaping of panel titles resp. disallowed HTML tags.
* Removed some CSS
* Restructured the SQL stats template.
* Changed command line examples to prefer ``python -m pip`` to ``pip``.

3.0 (2020-09-20)
----------------

* Added an ``.editorconfig`` file specifying indentation rules etc.
* Updated the Italian translation.
* Added support for Django 3.1a1. ``fetch()`` and ``jQuery.ajax`` requests are
  now detected by the absence of a ``Accept: text/html`` header instead of the
  jQuery-specific ``X-Requested-With`` header on Django 3.1 or better.
* Pruned unused CSS and removed hacks for ancient browsers.
* Added the new :attr:`Panel.scripts <debug_toolbar.panels.Panel.scripts>`
  property. This property should return a list of JavaScript resources to be
  loaded in the browser when displaying the panel. Right now, this is used by a
  single panel, the Timer panel. Third party panels can use this property to
  add scripts rather then embedding them in the content HTML.
* Switched from JSHint to ESLint. Added an ESLint job to the Travis CI matrix.
* Debug toolbar state which is only needed in the JavaScript code now uses
  ``localStorage``.
* Updated the code to avoid a few deprecation warnings and resource warnings.
* Started loading JavaScript as ES6 modules.
* Added support for :meth:`cache.touch() <django.core.caches.cache.touch>` when
  using django-debug-toolbar.
* Eliminated more inline CSS.
* Updated ``tox.ini`` and ``Makefile`` to use isort>=5.
* Increased RESULTS_CACHE_SIZE to 25 to better support AJAX requests.
* Fixed the close button CSS by explicitly specifying the
  ``box-sizing`` property.
* Simplified the ``isort`` configuration by taking advantage of isort's
  ``black`` profile.
* Added :class:`~debug_toolbar.panels.history.HistoryPanel` including support
  for AJAX requests.

**Backwards incompatible changes**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* Loading panel content no longer executes the scripts elements embedded in the
  HTML. Third party panels that require JavaScript resources should now use the
  :attr:`Panel.scripts <debug_toolbar.panels.Panel.scripts>` property.
* Removed support for end of life Django 1.11. The minimum supported Django is
  now 2.2.
* The Debug Toolbar now loads a `JavaScript module`_. Typical local development
  using Django ``runserver`` is not impacted. However, if your application
  server and static files server are at different origins, you may see CORS
  errors in your browser's development console. See the "Cross-Origin Request
  Blocked" section of the :doc:`installation docs <installation>` for details
  on how to resolve this issue.

.. _JavaScript module: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

2.2 (2020-01-31)
----------------

* Removed support for end of life Django 2.0 and 2.1.
* Added support for Python 3.8.
* Add locals() option for SQL panel.
* Added support for Django 3.0.

2.1 (2019-11-12)
----------------

* Changed the Travis CI matrix to run style checks first.
* Exposed the ``djdt.init`` function too.
* Small improvements to the code to take advantage of newer Django APIs
  and avoid warnings because of deprecated code.
* Verified compatibility with the upcoming Django 3.0 (at the time of
  writing).

2.0 (2019-06-20)
----------------

* Updated :class:`~debug_toolbar.panels.staticfiles.StaticFilesPanel` to be
  compatible with Django 3.0.
* The :class:`~debug_toolbar.panels.profiling.ProfilingPanel` is now enabled
  but inactive by default.
* Fixed toggling of table rows in the profiling panel UI.
* The :class:`~debug_toolbar.panels.profiling.ProfilingPanel` no longer skips
  remaining panels or middlewares.
* Improved the installation documentation.
* Fixed a possible crash in the template panel.
* Added support for psycopg2 ``Composed`` objects.
* Changed the Jinja2 tests to use Django's own Jinja2 template backend.
* Added instrumentation to queries using server side cursors.
* Too many small improvements and cleanups to list them all.

**Backwards incompatible changes**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Removed support for Python 2.
* Removed support for Django's deprecated ``MIDDLEWARE_CLASSES`` setting.
* Restructured :class:`debug_toolbar.panels.Panel` to execute more like the
  new-style Django MIDDLEWARE. The ``Panel.__init__()`` method is now passed
  ``get_response`` as the first positional argument. The
  :meth:`debug_toolbar.panels.Panel.process_request` method must now always
  return a response. Usually this is the response returned by
  ``get_response()`` but the panel may also return a different response as is
  the case in the :class:`~debug_toolbar.panels.redirects.RedirectsPanel`.
  Third party panels must adjust to this new architecture.
  ``Panel.process_response()`` and ``Panel.process_view()`` have been removed
  as a result of this change.

The deprecated API, ``debug_toolbar.panels.DebugPanel``, has been removed.
Third party panels should use :class:`debug_toolbar.panels.Panel` instead.

The following deprecated settings have been removed:

* ``HIDDEN_STACKTRACE_MODULES``
* ``HIDE_DJANGO_SQL``
* ``INTERCEPT_REDIRECTS``
* ``RESULTS_STORE_SIZE``
* ``ROOT_TAG_ATTRS``
* ``TAG``

1.11 (2018-12-03)
-----------------

* Use ``defer`` on all ``<script>`` tags to avoid blocking HTML parsing,
  removed inline JavaScript.
* Stop inlining images in CSS to avoid Content Security Policy errors
  altogether.
* Reformatted the code using `black <https://github.com/ambv/black>`__.
* Added the Django mail panel to the list of third-party panels.
* Convert system check errors to warnings to accommodate exotic
  configurations.
* Fixed a crash when explaining raw querysets.
* Fixed an obscure Unicode error with binary data fields.
* Added MariaDB and Python 3.7 builds to the CI.

1.10.1 (2018-09-11)
-------------------

* Fixed a problem where the duplicate query detection breaks for
  unhashable query parameters.
* Added support for structured types when recording SQL.
* Made Travis CI also run one test no PostgreSQL.
* Added fallbacks for inline images in CSS.
* Improved cross-browser compatibility around ``URLSearchParams`` usage.
* Fixed a few typos and redundancies in the documentation, removed
  mentions of django-debug-toolbar's jQuery which aren't accurate
  anymore.

1.10 (2018-09-06)
-----------------

* Removed support for Django < 1.11.
* Added support and testing for Django 2.1 and Python 3.7. No actual code
  changes were required.
* Removed the jQuery dependency. This means that django-debug-toolbar
  now requires modern browsers with support for ``fetch``, ``classList``
  etc. The ``JQUERY_URL`` setting is also removed because it isn't
  necessary anymore. If you depend on jQuery, integrate it yourself.
* Added support for the server timing header.
* Added a differentiation between similar and duplicate queries. Similar
  queries are what duplicate queries used to be (same SQL, different
  parameters).
* Stopped hiding frames from Django's contrib apps in stacktraces by
  default.
* Lots of small cleanups and bug fixes.

1.9.1 (2017-11-15)
------------------

* Fix erroneous ``ContentNotRenderedError`` raised by the redirects panel.

1.9 (2017-11-13)
----------------

This version is compatible with Django 2.0 and requires Django 1.8 or
later.

Bug fixes
~~~~~~~~~

* The profiling panel now escapes reported data resulting in valid HTML.
* Many minor cleanups and bug fixes.

1.8 (2017-05-05)
----------------

This version is compatible with Django 1.11 and requires Django 1.8 or
later.

**Backwards incompatible changes**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* ``debug_toolbar.middleware.show_toolbar`` (the default value of setting
  ``SHOW_TOOLBAR_CALLBACK``) no longer returns ``False`` for AJAX requests.
  This is to allow reusing the ``SHOW_TOOLBAR_CALLBACK`` function to verify
  access to panel views requested via AJAX. Projects defining a custom
  ``SHOW_TOOLBAR_CALLBACK`` should remove checks for AJAX requests in order to
  continue to allow access to these panels.

Features
~~~~~~~~

* New decorator ``debug_toolbar.decorators.require_show_toolbar`` prevents
  unauthorized access to decorated views by checking ``SHOW_TOOLBAR_CALLBACK``
  every request. Unauthorized access results in a 404.
* The ``SKIP_TEMPLATE_PREFIXES`` setting allows skipping templates in
  the templates panel. Template-based form widgets' templates are
  skipped by default to avoid panel sizes going into hundreds of
  megabytes of HTML.

Bug fixes
~~~~~~~~~

* All views are now decorated with
  ``debug_toolbar.decorators.require_show_toolbar`` preventing unauthorized
  access.
* The templates panel now reuses contexts' pretty printed version which
  makes the debug toolbar usable again with Django 1.11's template-based
  forms rendering.
* Long SQL statements are now forcibly wrapped to fit on the screen.

1.7 (2017-03-05)
----------------

Bug fixes
~~~~~~~~~

* Recursive template extension is now understood.
* Deprecation warnings were fixed.
* The SQL panel uses HMAC instead of simple hashes to verify that SQL
  statements have not been changed. Also, the handling of bytes and text
  for hashing has been hardened. Also, a bug with Python's division
  handling has been fixed for improved Python 3 support.
* An error with django-jinja has been fixed.
* A few CSS classes have been prefixed with ``djdt-`` to avoid
  conflicting class names.

1.6 (2016-10-05)
----------------

The debug toolbar was adopted by Jazzband.

Removed features
~~~~~~~~~~~~~~~~

* Support for automatic setup has been removed as it was frequently
  problematic. Installation now requires explicit setup. The
  ``DEBUG_TOOLBAR_PATCH_SETTINGS`` setting has also been removed as it is now
  unused. See the :doc:`installation documentation <installation>` for details.

Bug fixes
~~~~~~~~~

* The ``DebugToolbarMiddleware`` now also supports Django 1.10's ``MIDDLEWARE``
  setting.

1.5 (2016-07-21)
----------------

This version is compatible with Django 1.10 and requires Django 1.8 or later.

Support for Python 3.2 is dropped.

Bug fixes
~~~~~~~~~

* Restore compatibility with sqlparse ≥ 0.2.0.
* Add compatibility with Bootstrap 4, Pure CSS, MDL, etc.
* Improve compatibility with RequireJS / AMD.
* Improve the UI slightly.
* Fix invalid (X)HTML.

1.4 (2015-10-06)
----------------

This version is compatible with Django 1.9 and requires Django 1.7 or later.

New features
~~~~~~~~~~~~

* New panel method :meth:`debug_toolbar.panels.Panel.generate_stats` allows
  panels to only record stats when the toolbar is going to be inserted into
  the response.

Bug fixes
~~~~~~~~~

* Response time for requests of projects with numerous media files has
  been improved.

1.3 (2015-03-10)
----------------

This is the first version compatible with Django 1.8.

New features
~~~~~~~~~~~~

* A new panel is available: Template Profiler.
* The ``SHOW_TOOLBAR_CALLBACK`` accepts a callable.
* The toolbar now provides a :ref:`javascript-api`.

Bug fixes
~~~~~~~~~

* The toolbar handle cannot leave the visible area anymore when the toolbar is
  collapsed.
* The root level logger is preserved.
* The ``RESULTS_CACHE_SIZE`` setting is taken into account.
* CSS classes are prefixed with ``djdt-`` to prevent name conflicts.
* The private copy of jQuery no longer registers as an AMD module on sites
  that load RequireJS.

1.2 (2014-04-25)
----------------

New features
~~~~~~~~~~~~

* The ``JQUERY_URL`` setting defines where the toolbar loads jQuery from.

Bug fixes
~~~~~~~~~

* The toolbar now always loads a private copy of jQuery in order to avoid
  using an incompatible version. It no longer attempts to integrate with AMD.

  This private copy is available in ``djdt.jQuery``. Third-party panels are
  encouraged to use it because it should be as stable as the toolbar itself.

1.1 (2014-04-12)
----------------

This is the first version compatible with Django 1.7.

New features
~~~~~~~~~~~~

* The SQL panel colors queries depending on the stack level.
* The Profiler panel allows configuring the maximum depth.

Bug fixes
~~~~~~~~~

* Support languages where lowercase and uppercase strings may have different
  lengths.
* Allow using cursor as context managers.
* Make the SQL explain more helpful on SQLite.
* Various JavaScript improvements.

Deprecated features
~~~~~~~~~~~~~~~~~~~

* The ``INTERCEPT_REDIRECTS`` setting is superseded by the more generic
  ``DISABLE_PANELS``.

1.0 (2013-12-21)
----------------

This is the first stable version of the Debug Toolbar!

It includes many new features and performance improvements as well a few
backwards-incompatible changes to make the toolbar easier to deploy, use,
extend and maintain in the future.

You're strongly encouraged to review the installation and configuration docs
and redo the setup in your projects.

Third-party panels will need to be updated to work with this version.


text:
import Component from '@ember/component';
import { className, tagName } from '@ember-decorators/component';
import { alias } from '@ember/object/computed';
import { htmlSafe } from '@ember/template';
import { set } from '@ember/object';

@tagName('article')
export default class BlogPost extends Component {
  @alias('post.author')
  author;

  @alias('post.attributes.date')
  date;

  @alias('post.attributes.nextSlug')
  nextSlug;

  @alias('post.attributes.nextTitle')
  nextTitle;

  @alias('post.attributes.previousSlug')
  previousSlug;

  @alias('post.attributes.previousTitle')
  previousTitle;

  @alias('post.attributes.slug')
  @className
  slug;

  @alias('post.attributes.title')
  title;

  didReceiveAttrs() {
    super.didReceiveAttrs(...arguments);
    set(this, 'content', htmlSafe(this.post.attributes.html));
  }

  didRender() {
    super.didRender(...arguments);

    let nodeList = this.element.querySelectorAll('pre:not(.no-line-numbers) > code');

    if (nodeList) {
      // console.log(nodeList);
      nodeList.forEach((code) => {
        code.parentNode.classList.add('line-numbers');
      });
    }

    Prism.highlightAll();
  }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;

using JavaScriptEngineSwitcher.Core.Extensions;
using JavaScriptEngineSwitcher.Core.Helpers;

using CoreStrings = JavaScriptEngineSwitcher.Core.Resources.Strings;

namespace JavaScriptEngineSwitcher.NiL.Helpers
{
	/// <summary>
	/// JS error helpers
	/// </summary>
	internal static class NiLJsErrorHelpers
	{
		#region Error location

		private const string AtLinePrefix = "   at ";
		private const string DotNetStackTraceLinePrefix = AtLinePrefix + "NiL.JS.";

		private const string OriginalGlobalCode = "anonymous";
		private const string OriginalAnonymousFunctionName = "<anonymous method>";
		private const string WrapperGlobalCode = "Global code";
		private const string WrapperAnonymousFunctionName = "Anonymous function";

		/// <summary>
		/// Regular expression for working with line of the script error location
		/// </summary>
		private static readonly Regex _errorLocationLineRegex =
			new Regex(@"^" + AtLinePrefix +
				@"(?<functionName>" +
					@"[\w][\w ]*" +
					@"|" +
					CommonRegExps.JsFullNamePattern +
					@"|" +
					Regex.Escape(OriginalAnonymousFunctionName) +
				@")" +
				@"(?::line (?<lineNumber>\d+):(?<columnNumber>\d+))?$");

		/// <summary>
		/// Parses a string representation of the script error location to produce an array of
		/// <see cref="ErrorLocationItem"/> instances
		/// </summary>
		/// <param name="errorLocation">String representation of the script error location</param>
		/// <returns>An array of <see cref="ErrorLocationItem"/> instances</returns>
		public static ErrorLocationItem[] ParseErrorLocation(string errorLocation)
		{
			if (string.IsNullOrWhiteSpace(errorLocation))
			{
				return new ErrorLocationItem[0];
			}

			var errorLocationItems = new List<ErrorLocationItem>();
			string[] lines = errorLocation.SplitToLines();
			int lineCount = lines.Length;

			for (int lineIndex = 0; lineIndex < lineCount; lineIndex++)
			{
				string line = lines[lineIndex];

				if (line.Length == 0)
				{
					continue;
				}

				// Completing parsing when a .NET stack trace is found
				if (line.StartsWith(DotNetStackTraceLinePrefix, StringComparison.Ordinal))
				{
					break;
				}

				Match lineMatch = _errorLocationLineRegex.Match(line);
				if (lineMatch.Success)
				{
					GroupCollection lineGroups = lineMatch.Groups;
					Group lineNumberGroup = lineGroups["lineNumber"];
					Group columnNumberGroup = lineGroups["columnNumber"];

					var errorLocationItem = new ErrorLocationItem
					{
						FunctionName = lineGroups["functionName"].Value,
						LineNumber = lineNumberGroup.Success ? int.Parse(lineNumberGroup.Value) : 0,
						ColumnNumber = columnNumberGroup.Success ? int.Parse(columnNumberGroup.Value) : 0,
					};
					errorLocationItems.Add(errorLocationItem);
				}
				else
				{
					Debug.WriteLine(string.Format(CoreStrings.Runtime_InvalidErrorLocationLineFormat, line));
					return new ErrorLocationItem[0];
				}
			}

			return errorLocationItems.ToArray();
		}

		/// <summary>
		/// Fixes a error location items
		/// </summary>
		/// <param name="errorLocationItems">An array of <see cref="ErrorLocationItem"/> instances</param>
		public static void FixErrorLocationItems(ErrorLocationItem[] errorLocationItems)
		{
			foreach (ErrorLocationItem errorLocationItem in errorLocationItems)
			{
				string functionName = errorLocationItem.FunctionName;
				if (functionName.Length == 0 || functionName == OriginalGlobalCode)
				{
					errorLocationItem.FunctionName = WrapperGlobalCode;
				}
				else if (functionName == OriginalAnonymousFunctionName)
				{
					errorLocationItem.FunctionName = WrapperAnonymousFunctionName;
				}
			}
		}

		#endregion
	}
}


text:
<?php

class Google_Service_Container_UpdateMasterRequest extends Google_Model
{
  public $masterVersion;

  public function setMasterVersion($masterVersion)
  {
    $this->masterVersion = $masterVersion;
  }
  public function getMasterVersion()
  {
    return $this->masterVersion;
  }
}


text:
<?xml version="1.0"?>

<!--                                                                                -->
<!-- Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved. -->
<!--                                                                                -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.arjuna.dbplugins.test</groupId>
        <artifactId>test-plugin-parent</artifactId>
        <version>1.0.0p1m1</version>
    </parent>

    <artifactId>twitter-plugin-ear</artifactId>

    <packaging>ear</packaging>

    <name>Twitter Plugin EAR</name>

    <dependencies>
        <dependency>
            <groupId>com.twitter</groupId>
            <artifactId>hbc-core</artifactId>
            <version>2.2.0</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>com.arjuna.dbplugins.test</groupId>
            <artifactId>twitter-plugin</artifactId>
            <version>1.0.0p1m1</version>
            <scope>provided</scope>
            <type>ejb</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-ear-plugin</artifactId>
                <configuration>
                    <includeLibInApplicationXml>true</includeLibInApplicationXml>
                    <modules>
                        <jarModule>
                            <groupId>com.twitter</groupId>
                            <artifactId>hbc-core</artifactId>
                            <includeInApplicationXml>true</includeInApplicationXml>
                        </jarModule>
                        <ejbModule>
                            <groupId>com.arjuna.dbplugins.test</groupId>
                            <artifactId>twitter-plugin</artifactId>
                        </ejbModule>
                    </modules>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>jbossas</id>

            <build>
                <plugins>
                    <plugin>
                        <groupId>org.jboss.as.plugins</groupId>
                        <artifactId>jboss-as-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>install</phase>
                                <goals>
                                    <goal>deploy</goal>
                                </goals>
                            </execution>
                       </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>