text:
"""The graphical representation of devices as nodes"""

import sys, time, os
if sys.version_info < (2, 6):
    print "importing newer subprocess module from python 2.6"
    from Core import subprocess
else:
    import subprocess
from PyQt4 import QtCore, QtGui
from Core.globals import options, environ, mainWidgets, defaultOptions
from Properties import *
from Core.Item import *
# from StatsWindow import *

class DropItem(QtGui.QGraphicsItem):

    def __init__(self, itemType=None):
        """
        Create a draggable item, which can be dropped into the canvas.
        """
        QtGui.QGraphicsItem.__init__(self)
        if itemType:
            self.type = itemType

        self.image = QtGui.QImage(environ["images"] + self.type + ".gif")
        if self.image.isNull():
            mainWidgets["log"].append("Unknown node type " + str(self.type))
            return
        #matrix = QtGui.QMatrix(40.0/image.width(),0,0,40.0/image.height(),0,0)
        #self.image = image.transformed(matrix, QtCore.Qt.SmoothTransformation)

        self.setCursor(QtCore.Qt.OpenHandCursor)
        if itemType in unimplementedTypes:
            self.setToolTip(self.type.center(13) + "\nImplement me.")
            self.setEnabled(False)
        else:
            self.setToolTip(self.type.center(21) + "\nDrag onto the canvas.")

    def paint(self, painter, option, widget):
        """
        Draw the representation.
        """
        painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, options["smoothing"])
        if not self.isEnabled():
            transparency = QtGui.QImage(self.image)
            transparency.fill(QtGui.qRgba(0,0,0,50))
            painter.drawImage(QtCore.QPoint(-self.image.width()/2, -self.image.height()/2), transparency)
        painter.drawImage(QtCore.QPoint(-self.image.width()/2, -self.image.height()/2), self.image)
        painter.drawText(QtCore.QRectF(-70, self.image.height()/2, 145, 60), self.type, QtGui.QTextOption(QtCore.Qt.AlignHCenter))

    def boundingRect(self):
        """
        Get the bounding rectangle of the item.
        """
        rect = self.image.rect()
        return QtCore.QRectF(rect.left() - rect.width()/2, rect.top() - rect.height()/2, rect.width(), rect.height())

    def mousePressEvent(self, event):
        """
        Handle the mouse events on this item.
        """
        if event.button() != QtCore.Qt.LeftButton:
            event.ignore()
            return

        drag = QtGui.QDrag(event.widget())
        mime = QtCore.QMimeData()
        mime.setText(self.type)
        drag.setMimeData(mime)

        drag.setPixmap(QtGui.QPixmap.fromImage(self.image))
        drag.setHotSpot(QtCore.QPoint(15, 30))

        drag.start()

class Node(DropItem, Item):

    def __init__(self, itemType = None):
        """
        Create a draggable item for the main scene to represent devices.
        """
        DropItem.__init__(self, itemType)

        itemTypes = nodeTypes[self.type]
        index = self.findNextIndex(itemTypes[self.type])
        if index == 0:
            raise Exception
        name = self.type + "_%d" % index
        self.properties = {QtCore.QString("Name"):QtCore.QString(name)}
        self.interfaces = []

        self.edgeList = []
        self.newPos = QtCore.QPointF()
        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
        self.setZValue(1)
        self.setToolTip(name)

        self.shell = None

        self.status = None
        self.inc = 4
        self.color = QtGui.QColor(0,0,0)

        # Context Menu
        self.menu = QtGui.QMenu()
        self.menu.setPalette(defaultOptions["palette"])
        self.menu.addAction("Delete", self.delete)

#       if self.type == "Mobile":
#           self.wstatsWindow = StatsWindow(self.getName(), mainWidgets["canvas"])
#           self.setAcceptsHoverEvents(True)
#       elif self.type == "Router":
#           self.tail = None
#           self.wshark = None
#           self.rstatsWindow = None

        scene = mainWidgets["canvas"].scene()
        QtCore.QObject.connect(scene.getTimer(), QtCore.SIGNAL("timeout()"), self.updateColor)

    def findNextIndex(self, index):
        """
        Find the next index for the node's type.
        """
        firstPass = True
        newIndex = index + 1
        if newIndex > 126:
            newIndex = 1
            firstPass = False
        scene = mainWidgets["canvas"].scene()
        while scene.findItem(self.type + "_%d" % newIndex) or newIndex == index:
            newIndex += 1
            if newIndex > 126:
                if not firstPass:
                    return 0
                newIndex = 1
                firstPass = False
        itemTypes = nodeTypes[self.type]
        itemTypes[self.type] = newIndex
        return newIndex

    def setIndex(self, index):
        """
        Set the index of the node.
        """
        itemTypes = nodeTypes[self.type]
        if index > itemTypes[self.type]:
            itemTypes[self.type] = index
        name = self.type + "_%d" % index
        self.setProperty("Name", name)
        self.setToolTip(name)

    def setStatus(self, status):
        """
        Set the status of the node.
        """
        if self.status == status:
            return
        if not self.status and self.type == "Wireless_access_point":
            client = mainWidgets["client"]
            if client:
                client.send("attachdetach %d" % self.getID())

        self.status = status

        if not status:
            self.scene().stopRefresh()
        elif status == "attached":
            self.color = QtGui.QColor(0,255,0)
        elif status == "detached":
            self.color = QtGui.QColor(255,255,0)
        else:
            self.color = QtGui.QColor(255,0,0)

        if not options["glowingLights"]:
            self.scene().update()

    def setWirelessStats(self, stats):
        """
        Update the wireless stats of the node.
        """
        self.wstatsWindow.updateStats(stats)

    def setRouterStats(self, queue, size, rate):
        """
        Update the router stats of the node.
        """
        self.rstatsWindow.updateStats(queue, size, rate)

    def updateColor(self):
        """
        Update the color of the glowing light.
        """
        if not options["glowingLights"] or not self.status:
            return

        currentGreen = self.color.green()
        if currentGreen == 255:
            self.inc = -4
        elif currentGreen == 127:
            self.inc = 4

        currentRed = self.color.red()
        if currentRed == 255:
            self.inc = -4
        elif currentRed == 127:
            self.inc = 4

        if self.status == "attached":
            self.color.setGreen(self.color.green() + self.inc)
        elif self.status == "detached":
            self.color.setGreen(self.color.green() + self.inc)
            self.color.setRed(self.color.red() + self.inc)
        else:
            self.color.setRed(self.color.red() + self.inc)

    def paint(self, painter, option, widget):
        """
        Draw the representation and its name.
        """
        painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, options["smoothing"])
        painter.drawImage(QtCore.QPoint(-self.image.width()/2, -self.image.height()/2), self.image)
        if options["names"]:
            painter.drawText(QtCore.QRectF(-90, self.image.height()/2, 180, 60), self.getProperty("Name"), QtGui.QTextOption(QtCore.Qt.AlignHCenter))

        if self.status:
            painter.setBrush(self.color)
            painter.drawEllipse(self.lightPoint, 5, 5)

        painter.setBrush(QtCore.Qt.NoBrush)

        if self.isSelected():
            painter.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.DashLine))
            painter.drawRect(self.boundingRect())

    def addEdge(self, edge):
        """
        Add a connection with another node.
        """
        self.edgeList.append(edge)
        edge.adjust()

    def removeEdge(self, edge):
        """
        Remove a connection with another node.
        """
        self.edgeList.remove(edge)

    def edges(self):
        """
        Return all of the node's current connections.
        """
        newList = []
        for edge in self.edgeList:
            newList.append(edge)
        return newList

    def calculateForces(self):
        """
        Calculate the forces to determine movement of the arrange action.
        """
        if not self.scene() or self.scene().mouseGrabberItem() is self:
            self.newPos = self.pos()
            return

        # Sum up all forces pushing this item away.
        xvel = 0.0
        yvel = 0.0
        for item in self.scene().items():
            if not isinstance(item, Node):
                continue

            line = QtCore.QLineF(self.mapFromItem(item, 0, 0), QtCore.QPointF(0, 0))
            dx = line.dx()
            dy = line.dy()
            l = 2.0 * (dx * dx + dy * dy)
            if l > 0:
                xvel += (dx * 150.0) / l
                yvel += (dy * 150.0) / l

        # Now subtract all forces pulling items together.
        weight = (len(self.edgeList) + 1) * 50.0
        for edge in self.edgeList:
            if edge.sourceNode() is self:
                pos = self.mapFromItem(edge.destNode(), 0, 0)
            else:
                pos = self.mapFromItem(edge.sourceNode(), 0, 0)
            xvel += pos.x() / weight
            yvel += pos.y() / weight

        if QtCore.qAbs(xvel) < 0.1 and QtCore.qAbs(yvel) < 0.1:
            xvel = yvel = 0.0

        sceneRect = self.scene().sceneRect()
        self.newPos = self.pos() + QtCore.QPointF(xvel, yvel)
        self.newPos.setX(min(max(self.newPos.x(), sceneRect.left() + 10), sceneRect.right() - 10))
        self.newPos.setY(min(max(self.newPos.y(), sceneRect.top() + 10), sceneRect.bottom() - 10))

    def advance(self):
        """
        Determine if nodes are to be advanced.
        """
        if self.newPos == self.pos():
            return False

        self.setPos(self.newPos)
        return True

    def shape(self):
        """
        Get the shape of the node.
        """
        path = QtGui.QPainterPath()
        path.addEllipse(self.boundingRect())
        return path

    def itemChange(self, change, value):
        """
        Handle movement of the node.
        """
        if change == QtGui.QGraphicsItem.ItemPositionChange:
            for edge in self.edgeList:
                edge.adjust()
            mainWidgets["canvas"].itemMoved()

            if self.type == "Mobile":
                self.moveStats()

        return QtGui.QGraphicsItem.itemChange(self, change, value)

    def mousePressEvent(self, event):
        """
        Handle mouse press events on the node.
        """
        self.update()
        if event.button() == QtCore.Qt.RightButton:
            mainWidgets["canvas"].connectNode(self)
        else:
            QtGui.QGraphicsItem.mousePressEvent(self, event)

    def mouseMoveEvent(self, event):
        """
        Handle mouse move events on the node.
        """
        self.update()
        if mainWidgets["main"].isRunning() and \
           self.type != "Mobile" and \
           event.buttons() == QtCore.Qt.LeftButton:
            popup = mainWidgets["popup"]
            popup.setWindowTitle("Moving Disabled")
            popup.setText("Cannot move devices other than Mobile in a running topology!")
            popup.show()
            return

        QtGui.QGraphicsItem.mouseMoveEvent(self, event)

    def mouseReleaseEvent(self, event):
        """
        Handle mouse release events on the node.
        """
        self.update()
        QtGui.QGraphicsItem.mouseReleaseEvent(self, event)

        if mainWidgets["main"].isRunning() and \
           self.type == "Mobile" and \
           event.button() == QtCore.Qt.LeftButton:
            edges = self.edges()
            if not edges:
                return
            wap = edges[0].getOtherDevice(self)
            relpos = wap.pos()
            pos = self.pos()
            x = (pos.x() - relpos.x()) / 4
            y = (pos.y() - relpos.y()) / 4

            # propogate the change to the real wireless_access_point
            client = mainWidgets["client"]
            if client:
                client.send("screen -S WAP_%d -X eval 'stuff \"mov set node %d location %d %d 0\"\\015'" \
                                                        % (wap.getID(), self.getID(), x, y))

    def attach(self):
        """
        Attach to corresponding device on backend.
        """
        return

    def mouseDoubleClickEvent(self, event):
        """
        Handle mouse double click events on the node.
        """
        if mainWidgets["main"].isRunning():
            self.attach()

    def nudge(self):
        """
        Nudge the node to trigger a sequence of movements.
        """
        pos = self.pos()
        self.newPos.setX(pos.x() + 1)
        self.newPos.setY(pos.y() + 1)
        self.advance()
        self.newPos.setX(pos.x())
        self.newPos.setY(pos.y())
        self.advance()

    def delete(self):
        """
        Delete the node and its edges.
        """
        if mainWidgets["main"].isRunning():
            mainWidgets["log"].append("You cannot delete items from a running topology!")
            return

        from Tutorial import Tutorial
        if isinstance(mainWidgets["canvas"], Tutorial):
            mainWidgets["log"].append("You cannot delete items from the tutorial!")
            return

        for edge in self.edges():
            edge.delete()
        self.scene().removeItem(self)

    def restart(self):
        """
        Restart the running device.
        """
        if not mainWidgets["main"].isRunning():
            mainWidgets["log"].append("You must start the topology first!")
            return

        client = mainWidgets["client"]
        if client:
            client.send("restart " + self.getName())

    def terminate(self):
        """
        Terminate the running device.
        """
        if not mainWidgets["main"].isRunning():
            mainWidgets["log"].append("You must start the topology first!")
            return

        client = mainWidgets["client"]
        if client:
            client.send("terminate " + self.getName())

    def contextMenu(self, pos):
        """
        Pop up the context menu in the location given by pos
        """
        self.menu.exec_(pos)

    def stop(self):
        """
        Handle special stop actions on a stopped topology.
        """
        try:
            if self.rstatsWindow: # FIXME
                self.rstatsWindow.close()
            if self.tail:   # FIXME
                self.tail.terminate()
            if self.wshark: # FIXME
                self.wshark.terminate()
        except Exception, inst:
            print type(inst)
            print inst
            print inst.args

    def moveStats(self):
        """
        Move the wireless stats window along with the node.
        """
        self.wstatsWindow.move(mainWidgets["main"].pos() +
                        mainWidgets["canvas"].pos() +
                        mainWidgets["canvas"].mapFromScene(self.pos()) +
                        QtCore.QPoint(-100,-55))

    def hoverEnterEvent(self, event):
        """
        Handle a hover event over the node.
        """
        if not mainWidgets["main"].isRunning():
            return

        self.moveStats()
        self.wstatsWindow.show()

    def hoverMoveEvent(self, event):
        pass

    def hoverLeaveEvent(self, event):
        """
        Handle a hover event leaving the node.
        """
        if not mainWidgets["main"].isRunning():
            return

        self.wstatsWindow.hide()

    def toString(self):
        """
        Return a string representation of the graphical node.
        """
        graphical = self.getName() + ":(%f,%f)\n" % (self.pos().x(), self.pos().y())
        logical = ""
        for prop, value in self.properties.iteritems():
            logical += "\t" + prop + ":" + value + "\n"

        return graphical + logical


text:
layout: page
title: Beijing
---

## Contact

* Email: [beijng@sectalks.org](mailto:beijing@sectalks.org)
* Twitter: [@sectalks_bjs](https://twitter.com/sectalks_bjs)
* Weixin: sectalkbeijing (you can follow us by searching 'sectalkbeijing' in your webchat)

## Organising team
Pengfei Li, [@lpf37777514](https://twitter.com/lpf37777514), [Email](mailto:beijing@sectalks.org)

## Date & Time
The first sectalk_beijng meetup will be held at 7:00- 8:30 pm February 24th 2017

## Location
We will hold the first meetup at Block B No.4 Wangjing East Road Chaoyang District Beijing.

## Want to speak?
Whether it is a [lightning talk](https://en.wikipedia.org/wiki/Lightning_talk), 10min short presentation, or an hour long hands-on workshop, whether it is your first time to present, SecTalks is great place to get feedback and improve on.
Fill up [SecTalks CFP](http://j.mp/sectalkscfp) form.

## Sponsors
We will add it later

## Upcoming meetup
We will add it later

## How to join
SecTalks is always open to anyone who is keen to learn infosec. We run a mix of meetups for both beginners and people with experience.You can register this meetup at [huodongxing](http://www.huodongxing.com/event/7371734817900)

redpajama_set_name: RedPajamaGithub


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2012 Live Networks, Inc.  All rights reserved.
// Framed Filters
// C++ header

#ifndef _FRAMED_FILTER_HH
#define _FRAMED_FILTER_HH

#ifndef _FRAMED_SOURCE_HH
#include "FramedSource.hh"
#endif

class FramedFilter: public FramedSource {
public:
  FramedSource* inputSource() const { return fInputSource; }

  // Call before destruction if you want to prevent the destructor from closing the input source
  void detachInputSource() { fInputSource = NULL; }

protected:
  FramedFilter(UsageEnvironment& env, FramedSource* inputSource);
	 // abstract base class
  virtual ~FramedFilter();

protected:
  // Redefined virtual functions (with default 'null' implementations):
  virtual char const* MIMEtype() const;
  virtual void getAttributes() const;
  virtual void doStopGettingFrames();

protected:
  FramedSource* fInputSource;
};

#endif


text:
'use strict';
module.exports = function (model, view, intent) {
  if (view) { view.observe(model); }
  if (intent) { intent.observe(view); }
  if (model) { model.observe(intent); }
};


text:
using System.Collections.Generic;

#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
namespace DotLiquidCore.Util
{
	public static class ListExtensionMethods
	{
		/// <summary>
		/// Removes the first element from the list and returns it,
		/// or null if the list is empty.
		/// </summary>
		/// <param name="list"></param>
		/// <returns></returns>
		public static T Shift<T>(this List<T> list)
			where T : class
		{
			if (list == null || list.Count == 0)
				return null;

			T result = list[0];
			list.RemoveAt(0);

			return result;
		}

		/// <summary>
		/// Removes the last element from the list and returns it,
		/// or null if the list is empty.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="list"></param>
		/// <returns></returns>
		public static T Pop<T>(this List<T> list)
			where T : class
		{
			if (list == null || list.Count == 0)
				return null;

			T result = list[list.Count - 1];
			list.RemoveAt(list.Count - 1);

			return result;
		}
	}
}


text:
  - added `simple` param, this option allows to render a simple html
  select. In this mode the component only accepts the `items`, `selectedValue`
  and `selectedItem` attributes and emits the `select`. The `items` is required
  to be an array with objects of the format: `{ label: 'label', value: 'value'}`.

### 0.3.0 (November 4, 2015)

Global Ember VCL release, compatible with Ember 2.1.0 and new services.
### 0.2.5 (October 30, 2015)
  - bumped keyboard navigation support

### 0.2.4 (October 26, 2015)
  - removed expand on tab behavior

### 0.2.3 (October 5, 2015)

  - default to optimized version

### 0.2.2 (October 5, 2015)

  - added `ddau` (data down actions up) option. When set to `true` it disables
    automatic selection of clicked items and instead relies on the user to
    select them by handling the `select` action and setting one of the following
    bindings: `selectedItems`, `selectedItem` or `selectedValue`.

### 0.2.1 (October 5, 2015)

  - multiselect enabled (`maxSelectableItems` has to be greater then 1)
  - added keyboard navigation for multiselect
  - fixed selection by value
  - internal cleanup

### 0.2.0 (September 28, 2015)

  - [DEPRECATION] - "selectAction" is now deprecated, change the name to "select" instead
  - improved keyboard navigation
  - initial support for multiple selection (not working yet)
  - internal refactor

### 0.1.3 (August 10, 2015)

classNames -> class.

### 0.1.2 (July 7, 2015)

Used optimized version of dropdown. Disables tap to expand due to buggy implementation.

### 0.1.0 (June 23, 2015)

Full reset. New initial version.


text:
package org.elasticsearch.search;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.QueryCachingPolicy;
import org.apache.lucene.search.Sort;
import org.apache.lucene.store.Directory;
import org.elasticsearch.Version;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.MockBigArrays;
import org.elasticsearch.common.util.MockPageCacheRecycler;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.cache.IndexCache;
import org.elasticsearch.index.cache.query.QueryCache;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.search.internal.AliasFilter;
import org.elasticsearch.search.internal.ScrollContext;
import org.elasticsearch.search.internal.ShardSearchRequest;
import org.elasticsearch.search.query.QueryPhaseExecutionException;
import org.elasticsearch.search.rescore.RescoreContext;
import org.elasticsearch.search.slice.SliceBuilder;
import org.elasticsearch.search.sort.SortAndFormats;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.test.ESTestCase;

import java.util.UUID;

import static org.hamcrest.Matchers.equalTo;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class DefaultSearchContextTests extends ESSingleNodeTestCase {

    public void testPreProcess() throws Exception {
        TimeValue timeout = new TimeValue(randomIntBetween(1, 100));
        ShardSearchRequest shardSearchRequest = mock(ShardSearchRequest.class);
        when(shardSearchRequest.searchType()).thenReturn(SearchType.DEFAULT);
        ShardId shardId = new ShardId("index", UUID.randomUUID().toString(), 1);
        when(shardSearchRequest.shardId()).thenReturn(shardId);
        when(shardSearchRequest.types()).thenReturn(new String[]{});

        IndexShard indexShard = mock(IndexShard.class);
        QueryCachingPolicy queryCachingPolicy = mock(QueryCachingPolicy.class);
        when(indexShard.getQueryCachingPolicy()).thenReturn(queryCachingPolicy);

        int maxResultWindow = randomIntBetween(50, 100);
        int maxRescoreWindow = randomIntBetween(50, 100);
        int maxSlicesPerScroll = randomIntBetween(50, 100);
        Settings settings = Settings.builder()
            .put("index.max_result_window", maxResultWindow)
            .put("index.max_slices_per_scroll", maxSlicesPerScroll)
            .put("index.max_rescore_window", maxRescoreWindow)
            .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
            .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)
            .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 2)
            .build();

        IndexService indexService = mock(IndexService.class);
        IndexCache indexCache = mock(IndexCache.class);
        QueryCache queryCache = mock(QueryCache.class);
        when(indexCache.query()).thenReturn(queryCache);
        when(indexService.cache()).thenReturn(indexCache);
        QueryShardContext queryShardContext = mock(QueryShardContext.class);
        when(indexService.newQueryShardContext(eq(shardId.id()), anyObject(), anyObject(), anyString())).thenReturn(queryShardContext);
        MapperService mapperService = mock(MapperService.class);
        when(mapperService.hasNested()).thenReturn(randomBoolean());
        when(indexService.mapperService()).thenReturn(mapperService);

        IndexMetaData indexMetaData = IndexMetaData.builder("index").settings(settings).build();
        IndexSettings indexSettings = new IndexSettings(indexMetaData, Settings.EMPTY);
        when(indexService.getIndexSettings()).thenReturn(indexSettings);
        when(mapperService.getIndexSettings()).thenReturn(indexSettings);

        BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService());

        try (Directory dir = newDirectory();
             RandomIndexWriter w = new RandomIndexWriter(random(), dir);
             IndexReader reader = w.getReader();
             Engine.Searcher searcher = new Engine.Searcher("test", new IndexSearcher(reader), reader)) {

            SearchShardTarget target = new SearchShardTarget("node", shardId, null, OriginalIndices.NONE);

            DefaultSearchContext context1 = new DefaultSearchContext(1L, shardSearchRequest, target, searcher, clusterService(), indexService,
                indexShard, bigArrays, null, timeout, null, Version.CURRENT);
            context1.from(300);

            // resultWindow greater than maxResultWindow and scrollContext is null
            QueryPhaseExecutionException exception = expectThrows(QueryPhaseExecutionException.class, () -> context1.preProcess(false));
            assertThat(exception.getMessage(), equalTo("Result window is too large, from + size must be less than or equal to:"
                + " [" + maxResultWindow + "] but was [310]. See the scroll api for a more efficient way to request large data sets. "
                + "This limit can be set by changing the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey()
                + "] index level setting."));

            // resultWindow greater than maxResultWindow and scrollContext isn't null
            context1.scrollContext(new ScrollContext());
            exception = expectThrows(QueryPhaseExecutionException.class, () -> context1.preProcess(false));
            assertThat(exception.getMessage(), equalTo("Batch size is too large, size must be less than or equal to: ["
                + maxResultWindow + "] but was [310]. Scroll batch sizes cost as much memory as result windows so they are "
                + "controlled by the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting."));

            // resultWindow not greater than maxResultWindow and both rescore and sort are not null
            context1.from(0);
            DocValueFormat docValueFormat = mock(DocValueFormat.class);
            SortAndFormats sortAndFormats = new SortAndFormats(new Sort(), new DocValueFormat[]{docValueFormat});
            context1.sort(sortAndFormats);

            RescoreContext rescoreContext = mock(RescoreContext.class);
            when(rescoreContext.getWindowSize()).thenReturn(500);
            context1.addRescore(rescoreContext);

            exception = expectThrows(QueryPhaseExecutionException.class, () -> context1.preProcess(false));
            assertThat(exception.getMessage(), equalTo("Cannot use [sort] option in conjunction with [rescore]."));

            // rescore is null but sort is not null and rescoreContext.getWindowSize() exceeds maxResultWindow
            context1.sort(null);
            exception = expectThrows(QueryPhaseExecutionException.class, () -> context1.preProcess(false));

            assertThat(exception.getMessage(), equalTo("Rescore window [" + rescoreContext.getWindowSize() + "] is too large. "
                + "It must be less than [" + maxRescoreWindow + "]. This prevents allocating massive heaps for storing the results "
                + "to be rescored. This limit can be set by changing the [" + IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey()
                + "] index level setting."));

            // rescore is null but sliceBuilder is not null
            DefaultSearchContext context2 = new DefaultSearchContext(2L, shardSearchRequest, target, searcher,
                clusterService(), indexService, indexShard, bigArrays, null, timeout, null, Version.CURRENT);

            SliceBuilder sliceBuilder = mock(SliceBuilder.class);
            int numSlices = maxSlicesPerScroll + randomIntBetween(1, 100);
            when(sliceBuilder.getMax()).thenReturn(numSlices);
            context2.sliceBuilder(sliceBuilder);

            exception = expectThrows(QueryPhaseExecutionException.class, () -> context2.preProcess(false));
            assertThat(exception.getMessage(), equalTo("The number of slices [" + numSlices + "] is too large. It must "
                + "be less than [" + maxSlicesPerScroll + "]. This limit can be set by changing the [" +
                IndexSettings.MAX_SLICES_PER_SCROLL.getKey() + "] index level setting."));

            // No exceptions should be thrown
            when(shardSearchRequest.getAliasFilter()).thenReturn(AliasFilter.EMPTY);
            when(shardSearchRequest.indexBoost()).thenReturn(AbstractQueryBuilder.DEFAULT_BOOST);

            DefaultSearchContext context3 = new DefaultSearchContext(3L, shardSearchRequest, target, searcher, clusterService(),
                indexService, indexShard, bigArrays, null, timeout, null, Version.CURRENT);
            ParsedQuery parsedQuery = ParsedQuery.parsedMatchAllQuery();
            context3.sliceBuilder(null).parsedQuery(parsedQuery).preProcess(false);
            assertEquals(context3.query(), context3.buildFilteredQuery(parsedQuery.query()));
        }
    }
}


text:
dd if=/dev/zero of=/swapfile1 bs=2048 count=2097152
chown root:root /swapfile1
chmod 0600 /swapfile1
mkswap /swapfile1
swapon /swapfile1
echo "/swapfile1 swap swap defaults 0 0" >> /etc/fstab


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

module.exports = function http_build_query(formdata, numericPrefix, argSeparator) {
  // eslint-disable-line camelcase
  //  discuss at: http://locutus.io/php/http_build_query/
  // original by: Kevin van Zonneveld (http://kvz.io)
  // improved by: Legaev Andrey
  // improved by: Michael White (http://getsprink.com)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // improved by: Brett Zamir (http://brett-zamir.me)
  //  revised by: stag019
  //    input by: Dreamer
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  // bugfixed by: MIO_KODUKI (http://mio-koduki.blogspot.com/)
  //      note 1: If the value is null, key and value are skipped in the
  //      note 1: http_build_query of PHP while in locutus they are not.
  //   example 1: http_build_query({foo: 'bar', php: 'hypertext processor', baz: 'boom', cow: 'milk'}, '', '&')
  //   returns 1: 'foo=bar&php=hypertext+processor&baz=boom&cow=milk'
  //   example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1: 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_')
  //   returns 2: 'myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&php=hypertext+processor&cow=milk'

  var urlencode = require('../url/urlencode');

  var value;
  var key;
  var tmp = [];

  var _httpBuildQueryHelper = function _httpBuildQueryHelper(key, val, argSeparator) {
    var k;
    var tmp = [];
    if (val === true) {
      val = '1';
    } else if (val === false) {
      val = '0';
    }
    if (val !== null) {
      if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object') {
        for (k in val) {
          if (val[k] !== null) {
            tmp.push(_httpBuildQueryHelper(key + '[' + k + ']', val[k], argSeparator));
          }
        }
        return tmp.join(argSeparator);
      } else if (typeof val !== 'function') {
        return urlencode(key) + '=' + urlencode(val);
      } else {
        throw new Error('There was an error processing for http_build_query().');
      }
    } else {
      return '';
    }
  };

  if (!argSeparator) {
    argSeparator = '&';
  }
  for (key in formdata) {
    value = formdata[key];
    if (numericPrefix && !isNaN(key)) {
      key = String(numericPrefix) + key;
    }
    var query = _httpBuildQueryHelper(key, value, argSeparator);
    if (query !== '') {
      tmp.push(query);
    }
  }

  return tmp.join(argSeparator);
};
//# sourceMappingURL=http_build_query.js.map


text:
@interface PMAppDelegate () <PMAddAccountVCDelegate>

@end

@implementation PMAppDelegate

#pragma mark - Launch Cycle

- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (application.applicationState == UIApplicationStateInactive) {
        [PMAccountStore sharedStore];
        [PMTagStore sharedStore];
        [PMBookmarkStore sharedStore];
    }

    return YES;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (application.applicationState == UIApplicationStateInactive) {
        NSString *username = [PMAccountStore sharedStore].defaultUsername;
        if (!username || [username isEqualToString:@""]) {
            PMAddAccountVC *addVC = [[PMAddAccountVC alloc] init];
            addVC.delegate = self;
            self.window.rootViewController = addVC;
        }
    }

    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSArray *usernames = [PMAccountStore sharedStore].associatedUsernames;
    for (NSString *username in usernames) {
        NSString *token = [[PMAccountStore sharedStore] authTokenForUsername:username];
        if (token) {
            void (^success)(NSDictionary *) = ^(NSDictionary *responseDictionary) {
                NSArray *sortedTags = [[[responseDictionary keysSortedByValueUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
                [[PMTagStore sharedStore] updateTags:sortedTags username:username];
            };

            [PMPinboardService requestTagsForAPIToken:token success:success failure:nil];
        }
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    BOOL result = YES;
    UIViewController *viewController = self.window.rootViewController;
    if ([viewController isKindOfClass:[PMNavigationVC class]]) {
        PMNavigationVC *navigationVC = (PMNavigationVC *)viewController;
        [navigationVC openURL:url];
    }

    return result;
}

- (UIViewController *)application:(UIApplication *)application viewControllerWithRestorationIdentifierPath:(NSArray *)identifierComponents coder:(NSCoder *)coder {
    return nil;
}

- (BOOL)application:(UIApplication *)application shouldSaveApplicationState:(NSCoder *)coder {
    return YES;
}

- (BOOL)application:(UIApplication *)application shouldRestoreApplicationState:(NSCoder *)coder {
    return YES;
}

#pragma mark - PMAddAccountVCDelegate

- (void)didFinishAddingAccount {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Pinmarker" bundle:nil];
    self.window.rootViewController = [storyboard instantiateInitialViewController];
}

- (void)didFinishUpdatingAccount {
    [self didFinishAddingAccount];
}

- (BOOL)shouldAddAccountAsDefault {
    return YES;
}

@end


text:
/***********************************************************************/
/*                                                                     */
/*                           Objective Caml                            */
/*                                                                     */
/*  Contributed by Sylvain Le Gall for Lexifi                          */
/*                                                                     */
/*  Copyright 2008 Institut National de Recherche en Informatique et   */
/*  en Automatique.  All rights reserved.  This file is distributed    */
/*  under the terms of the GNU Library General Public License, with    */
/*  the special exception on linking described in file ../../LICENSE.  */
/*                                                                     */
/***********************************************************************/

/* $Id: windbug.c 10467 2010-05-25 13:01:06Z xleroy $ */

#include "windbug.h"

int debug_test (void)
{
  static int debug_init = 0;
  static int debug = 0;

#ifdef DEBUG
  if (!debug_init)
  {
    debug = (getenv("OCAMLDEBUG") != NULL);
    debug_init = 1;
  };
#endif

  return debug;
}


text:
package com.webpagebytes.authgitkit;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GitkitLoginPage extends HttpServlet {

private static final long serialVersionUID = 1L;
public static final String LOGIN_PAGE_FILE = "loginPageFilePath";
private String loginPageContent;

public void init() throws ServletException
{
	Map<String, String> configs = ConfigReader.getConfigs();
	if (!configs.containsKey(LOGIN_PAGE_FILE))
	{
		throw new ServletException("No 'loginPagePath' config set for GitkitLoginPage servlet");
	}
	String loginPagePath = configs.get(LOGIN_PAGE_FILE);
	try
	{
		byte[] bytes = Files.readAllBytes(Paths.get(loginPagePath));
		loginPageContent = new String(bytes, "UTF-8");
	} catch (IOException e)
	{
		throw new ServletException("Reading file from 'loginPageFilePath'", e);
	}
}

public void doGet(HttpServletRequest req, HttpServletResponse resp)
	     throws ServletException, java.io.IOException
{
	resp.setContentType("text/html");
	resp.getOutputStream().write(loginPageContent.getBytes("UTF-8"));
	resp.getOutputStream().flush();
}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
	     throws ServletException, java.io.IOException
{
	resp.setContentType("text/html");
    StringBuilder builder = new StringBuilder();
    String line;
    try {
      while ((line = req.getReader().readLine()) != null) {
        builder.append(line);
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    String postBody = URLEncoder.encode(builder.toString(), "UTF-8");
    String content = loginPageContent;
    content = content.replaceAll("JAVASCRIPT_ESCAPED_POST_BODY", postBody);

	resp.getOutputStream().write(content.getBytes("UTF-8"));
	resp.getOutputStream().flush();
}

}


text:
package util

// ClusterYaml represents the structure of the Yaml definition that is to be
// copied over to the admin host, which will be eventually used to create the
// Anthos Baremetal cluster
type ClusterYaml struct {
	Kind     *string  `yaml:"kind"`
	Metadata Metadata `yaml:"metadata"`
	Spec     *Spec    `yaml:"spec"`
}

// Metadata represents the the metadata definition on the different resource
// types used on the cluster Yaml describing the Anthos Baremetal cluster. This
// struct includes a union of all possible metadata values for different kings
// of resources (i.e: Nodepools, Cluster, Namespace)
type Metadata struct {
	Name      string `yaml:"name"`
	Namespace string `yaml:"namespace"`
}

// Spec represents the the spec definition on the different resource types
// used on the cluster Yaml describing the Anthos Baremetal cluster. This
// struct includes a union of all possible spec values for different kings
// of resources (i.e: Nodepools, Cluster, Namespace)
type Spec struct {
	ClusterName       *string            `yaml:"clusterName"`
	ControlPlane      *ControlPlane      `yaml:"controlPlane"`
	GkeConnect        *GkeConnect        `yaml:"gkeConnect"`
	ClusterOperations *ClusterOperations `yaml:"clusterOperations"`
	Nodes             *[]Node            `yaml:"nodes"`
}

// GkeConnect represents the gkeConnect attribute in the spec definition for
// the resource kind Cluster in the Yaml for the Anthos Baremetal cluster
type GkeConnect struct {
	ProjectID string `yaml:"projectID"`
}

// ClusterOperations represents the clusterOperations attribute in the spec
// definition for the resource kind Cluster in the Yaml for the
// Anthos Baremetal cluster
type ClusterOperations struct {
	ProjectID string `yaml:"projectID"`
}

// Node represents a single node definition in the spec definition for the
// resource kind Cluster and Nodepools in the Yaml for the
// Anthos Baremetal cluster
type Node struct {
	Address string `yaml:"address"`
}

// ControlPlane represents the controlPlane attribute in the spec definition
// for the resource kind Cluster in the Yaml for the Anthos Baremetal cluster
type ControlPlane struct {
	NodePoolSpec *NodePoolSpec `yaml:"nodePoolSpec"`
}

// NodePoolSpec represents the nodePoolSpec attribute in the spec.controlPlane
// definition for the resource kind Cluster in the Yaml for the
// Anthos Baremetal cluster
type NodePoolSpec struct {
	ClusterName string  `yaml:"clusterName"`
	Nodes       *[]Node `yaml:"nodes"`
}


text:
namespace Oryol {

struct Input::_state* Input::state = nullptr;

//------------------------------------------------------------------------------
void
Input::Setup(const InputSetup& setup) {
    o_assert_dbg(!IsValid());
    state = Memory::New<_state>();
    state->inputManager.setup(setup);
}

//------------------------------------------------------------------------------
void
Input::Discard() {
    o_assert_dbg(IsValid());
    state->inputManager.Mouse.clearPointerLockHandler();
    state->inputManager.discard();
    Memory::Delete(state);
    state = nullptr;
}

//------------------------------------------------------------------------------
bool
Input::IsValid() {
    return nullptr != state;
}

//------------------------------------------------------------------------------
void
Input::BeginCaptureText() {
    o_assert_dbg(IsValid());
    state->inputManager.beginCaptureText();
}

//------------------------------------------------------------------------------
void
Input::EndCaptureText() {
    o_assert_dbg(IsValid());
    return state->inputManager.endCaptureText();
}

//------------------------------------------------------------------------------
const class Keyboard&
Input::Keyboard() {
    o_assert_dbg(IsValid());
    return state->inputManager.Keyboard;
}

//------------------------------------------------------------------------------
const class Mouse&
Input::Mouse() {
    o_assert_dbg(IsValid());
    return state->inputManager.Mouse;
}

//------------------------------------------------------------------------------
const class Gamepad&
Input::Gamepad(int32 index) {
    o_assert_dbg(IsValid());
    return state->inputManager.Gamepad[index];
}

//------------------------------------------------------------------------------
const class Touchpad&
Input::Touchpad() {
    o_assert_dbg(IsValid());
    return state->inputManager.Touchpad;
}

//------------------------------------------------------------------------------
const class Sensors&
Input::Sensors() {
    o_assert_dbg(IsValid());
    return state->inputManager.Sensors;
}

//------------------------------------------------------------------------------
Keyboard::EventHandlerId
Input::SubscribeKeyboard(Keyboard::EventHandler handler) {
    o_assert_dbg(IsValid());
    return state->inputManager.Keyboard.subscribe(handler);
}

//------------------------------------------------------------------------------
void
Input::UnsubscribeKeyboard(Keyboard::EventHandlerId id) {
    o_assert_dbg(IsValid());
    state->inputManager.Keyboard.unsubscribe(id);
}

//------------------------------------------------------------------------------
Mouse::EventHandlerId
Input::SubscribeMouse(Mouse::EventHandler handler) {
    o_assert_dbg(IsValid());
    return state->inputManager.Mouse.subscribe(handler);
}

//------------------------------------------------------------------------------
void
Input::UnsubscribeMouse(Mouse::EventHandlerId id) {
    o_assert_dbg(IsValid());
    state->inputManager.Mouse.unsubscribe(id);
}

//------------------------------------------------------------------------------
Touchpad::EventHandlerId
Input::SubscribeTouchpad(Touchpad::EventHandler handler) {
    o_assert_dbg(IsValid());
    return state->inputManager.Touchpad.subscribe(handler);
}

//------------------------------------------------------------------------------
void
Input::UnsubscribeTouchpad(Touchpad::EventHandlerId id) {
    o_assert_dbg(IsValid());
    state->inputManager.Touchpad.unsubscribe(id);
}

//------------------------------------------------------------------------------
void
Input::SetMousePointerLockHandler(Mouse::PointerLockHandler handler) {
    o_assert_dbg(IsValid());
    state->inputManager.Mouse.setPointerLockHandler(handler);
}

//------------------------------------------------------------------------------
void
Input::ClearMousePointerLockHandler() {
    o_assert_dbg(IsValid());
    state->inputManager.Mouse.clearPointerLockHandler();
}

} // namespace Input


text:
/**
 * Bridget makes jQuery widgets
 * v1.0.1
 */

( function( window ) {

'use strict';

// -------------------------- utils -------------------------- //

var slice = Array.prototype.slice;

function noop() {}

// -------------------------- definition -------------------------- //

function defineBridget( $ ) {

// bail if no jQuery
if ( !$ ) {
  return;
}

// -------------------------- addOptionMethod -------------------------- //

/**
 * adds option method -> $().plugin('option', {...})
 * @param {Function} PluginClass - constructor class
 */
function addOptionMethod( PluginClass ) {
  // don't overwrite original option method
  if ( PluginClass.prototype.option ) {
    return;
  }

  // option setter
  PluginClass.prototype.option = function( opts ) {
    // bail out if not an object
    if ( !$.isPlainObject( opts ) ){
      return;
    }
    this.options = $.extend( true, this.options, opts );
  };
}

// -------------------------- plugin bridge -------------------------- //

// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
  function( message ) {
    console.error( message );
  };

/**
 * jQuery plugin bridge, access methods like $elem.plugin('method')
 * @param {String} namespace - plugin name
 * @param {Function} PluginClass - constructor class
 */
function bridge( namespace, PluginClass ) {
  // add to jQuery fn namespace
  $.fn[ namespace ] = function( options ) {
    if ( typeof options === 'string' ) {
      // call plugin method when first argument is a string
      // get arguments for method
      var args = slice.call( arguments, 1 );

      for ( var i=0, len = this.length; i < len; i++ ) {
        var elem = this[i];
        var instance = $.data( elem, namespace );
        if ( !instance ) {
          logError( "cannot call methods on " + namespace + " prior to initialization; " +
            "attempted to call '" + options + "'" );
          continue;
        }
        if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
          logError( "no such method '" + options + "' for " + namespace + " instance" );
          continue;
        }

        // trigger method with arguments
        var returnValue = instance[ options ].apply( instance, args );

        // break look and return first value if provided
        if ( returnValue !== undefined ) {
          return returnValue;
        }
      }
      // return this if no return value
      return this;
    } else {
      return this.each( function() {
        var instance = $.data( this, namespace );
        if ( instance ) {
          // apply options & init
          instance.option( options );
          instance._init();
        } else {
          // initialize new instance
          instance = new PluginClass( this, options );
          $.data( this, namespace, instance );
        }
      });
    }
  };

}

// -------------------------- bridget -------------------------- //

/**
 * converts a Prototypical class into a proper jQuery plugin
 *   the class must have a ._init method
 * @param {String} namespace - plugin name, used in $().pluginName
 * @param {Function} PluginClass - constructor class
 */
$.bridget = function( namespace, PluginClass ) {
  addOptionMethod( PluginClass );
  bridge( namespace, PluginClass );
};

return $.bridget;

}

// transport
if ( typeof define === 'function' && define.amd ) {
  // AMD
  define( [ 'jquery' ], defineBridget );
} else {
  // get jquery from browser global
  defineBridget( window.jQuery );
}

})( window );


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

?>

Home Banners

            <a class="btn btn-success btn-sm" href="<? echo site_url('administrator/banner/add') ?>">

    <?
        foreach ($query->result() as $row){
            echo '
';
            echo '
';
            echo 'id_banner).'"> ';
            echo 'id_banner.');">';
            echo '
';
            echo '
';
            echo 'filename).'" />';
            echo '
';
            echo '
';
            echo '
'.$row->title.'
';
            echo '
'.$row->sub_title.'
';
            echo '';
            if ($row->link != ''){
                echo 'Linked to link.'">'.$row->link.' - ';
            }
            echo 'Created on '.date('d F Y', strtotime($row->insert_date));
            echo '';
            echo '
';
            echo '
';
        }
    ?>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Delete Banner

Are you sure to delete the banner?

      <form method="post" action="">
        <input type="hidden" name="id_banner" id="id_banner" value="" />
        <button type="button" class="btn btn-danger" data-dismiss="modal">No</button>
        <button type="submit" class="btn btn-primary" name="delete">Yes</button>
      </form>


text:
<!doctype html>

  <meta charset='utf-8'>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width">

  <title>UDD Huella Digital</title>

  <link  href='https://cdn.rawgit.com/rstacruz/flatdoc/v0.9.0/theme-white/style.css' rel='stylesheet'>

  <meta content="UDD Huella Digital" property="og:title">
  <meta content="Un plugin para WordPress para crear listas de personas con información del portal corporativo UDD." name="description">

UDD Huella Digital

Ver en GitHub

Issues


text:
package gov.healthit.chpl.dao.impl;

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

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;

import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;

import gov.healthit.chpl.auth.permission.GrantedPermission;
import gov.healthit.chpl.auth.user.JWTAuthenticatedUser;
import gov.healthit.chpl.dao.EntityRetrievalException;
import gov.healthit.chpl.dao.ProductDAO;
import gov.healthit.chpl.dto.ProductDTO;
import gov.healthit.chpl.entity.ProductEntity;
import junit.framework.TestCase;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { gov.healthit.chpl.CHPLTestConfig.class })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class })
@DatabaseSetup("classpath:data/testData.xml")
public class ProductDaoTest extends TestCase {

	@Autowired
	private ProductDAO productDao;

	private static JWTAuthenticatedUser authUser;

	@BeforeClass
	public static void setUpClass() throws Exception {
		authUser = new JWTAuthenticatedUser();
		authUser.setFirstName("Admin");
		authUser.setId(-2L);
		authUser.getPermissions().add(new GrantedPermission("ROLE_ADMIN"));
	}

	@Test
	public void getAllProducts() {
		List<ProductDTO> results = productDao.findAll();
		assertNotNull(results);
		assertEquals(4, results.size());
	}

	@Test
	public void getProductById() {
		Long productId = 1L;
		ProductDTO product = null;
		try {
			product = productDao.getById(productId);
		} catch(EntityRetrievalException ex) {
			fail("Could not find product with id " + productId);
		}
		assertNotNull(product);
		assertEquals(1, product.getId().longValue());
	}

	@Test
	public void getProductByDeveloper() {
		Long developerId = -1L;
		List<ProductDTO> products = null;
		products = productDao.getByDeveloper(developerId);
		assertNotNull(products);
		assertEquals(3, products.size());
	}

	@Test
	public void getProductByDevelopers() {
		List<Long> developerIds = new ArrayList<Long>();
		developerIds.add(-1L);
		developerIds.add(-2L);
		List<ProductDTO> products = null;
		products = productDao.getByDevelopers(developerIds);
		assertNotNull(products);
		assertEquals(4, products.size());
	}

	@Test
	public void updateProduct() throws EntityRetrievalException {
		ProductDTO product = productDao.getById(1L);
		product.setDeveloperId(-2L);

		ProductEntity result = null;
		try {
			result = productDao.update(product);
		} catch(Exception ex) {
			fail("could not update product!");
			System.out.println(ex.getStackTrace());
		}
		assertNotNull(result);

		try {
			ProductDTO updatedProduct = productDao.getById(product.getId());
			assertTrue(updatedProduct.getDeveloperId() == -2L);
		} catch(Exception ex) {
			fail("could not find product!");
			System.out.println(ex.getStackTrace());
		}
	}
}


text:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ThreadServlet extends HttpServlet implements SingleThreadModel {
	private int count = 0;

	public void service(HttpServletRequest request,
		HttpServletResponse response)
		throws ServletException, IOException {
		count++;
		try {
			Thread.sleep(500);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		String text = "this is the "+count+" time to visit this servlet, Thread:"+Thread.currentThread().getName();
		System.out.println(text);
		PrintWriter out = response.getWriter();
		out.println(text);
	}
}


text:
/**
 * @fileoverview Enforce label tags have htmlFor attribute.
 * @author Ethan Cohen
 */

// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------

import { getProp, getPropValue, elementType } from 'jsx-ast-utils';
import { generateObjSchema, arraySchema, enumArraySchema } from '../util/schemas';
import hasAccessibleChild from '../util/hasAccessibleChild';

const enumValues = ['nesting', 'id'];
const schema = {
  type: 'object',
  properties: {
    components: arraySchema,
    required: {
      oneOf: [
        { type: 'string', enum: enumValues },
        generateObjSchema({ some: enumArraySchema(enumValues) }, ['some']),
        generateObjSchema({ every: enumArraySchema(enumValues) }, ['every']),
      ],
    },
    allowChildren: { type: 'boolean' },
  },
};
// Breadth-first search, assuming that HTML for forms is shallow.
function validateNesting(node) {
  let queue = [...node.parent.children];
  let child;
  let opener;
  while (queue.length) {
    child = queue.shift();
    opener = child.openingElement;
    if (child.type === 'JSXElement' && opener && (opener.name.name === 'input' || opener.name.name === 'textarea' || opener.name.name === 'select')) {
      return true;
    }
    if (child.children) {
      queue = queue.concat(child.children);
    }
  }
  return false;
}

const validateId = (node) => {
  const htmlForAttr = getProp(node.attributes, 'htmlFor');
  const htmlForValue = getPropValue(htmlForAttr);

  return htmlForAttr !== false && !!htmlForValue;
};

const validate = (node, required, allowChildren) => {
  if (allowChildren === true) {
    return hasAccessibleChild(node.parent);
  }
  if (required === 'nesting') {
    return validateNesting(node);
  }
  return validateId(node);
};

const getValidityStatus = (node, required, allowChildren) => {
  if (Array.isArray(required.some)) {
    const isValid = required.some.some((rule) => validate(node, rule, allowChildren));
    const message = !isValid
      ? `Form label must have ANY of the following types of associated control: ${required.some.join(', ')}`
      : null;
    return { isValid, message };
  }
  if (Array.isArray(required.every)) {
    const isValid = required.every.every((rule) => validate(node, rule, allowChildren));
    const message = !isValid
      ? `Form label must have ALL of the following types of associated control: ${required.every.join(', ')}`
      : null;
    return { isValid, message };
  }

  const isValid = validate(node, required, allowChildren);
  const message = !isValid
    ? `Form label must have the following type of associated control: ${required}`
    : null;
  return { isValid, message };
};

export default {
  meta: {
    deprecated: true,
    docs: {
      url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/label-has-for.md',
    },
    schema: [schema],
  },

  create: (context) => ({
    JSXOpeningElement: (node) => {
      const options = context.options[0] || {};
      const componentOptions = options.components || [];
      const typesToValidate = ['label'].concat(componentOptions);
      const nodeType = elementType(node);

      // Only check 'label' elements and custom types.
      if (typesToValidate.indexOf(nodeType) === -1) {
        return;
      }

      const required = options.required || { every: ['nesting', 'id'] };
      const allowChildren = options.allowChildren || false;

      const { isValid, message } = getValidityStatus(node, required, allowChildren);
      if (!isValid) {
        context.report({
          node,
          message,
        });
      }
    },
  }),
};


text:
use core::marker::PhantomData;

#[cfg(feature = "formatting")]
use serde::ser::Error as _;
#[cfg(feature = "parsing")]
use serde::Deserializer;
#[cfg(feature = "formatting")]
use serde::{Serialize, Serializer};

#[cfg(feature = "parsing")]
use super::Visitor;
use crate::format_description::well_known::iso8601::{Config, EncodedConfig};
use crate::format_description::well_known::Iso8601;
use crate::OffsetDateTime;

/// The configuration of ISO 8601 used for serde implementations.
pub(crate) const SERDE_CONFIG: EncodedConfig =
    Config::DEFAULT.set_year_is_six_digits(true).encode();

/// Serialize an [`OffsetDateTime`] using the well-known ISO 8601 format.
#[cfg(feature = "formatting")]
pub fn serialize<S: Serializer>(
    datetime: &OffsetDateTime,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    datetime
        .format(&Iso8601::<SERDE_CONFIG>)
        .map_err(S::Error::custom)?
        .serialize(serializer)
}

/// Deserialize an [`OffsetDateTime`] from its ISO 8601 representation.
#[cfg(feature = "parsing")]
pub fn deserialize<'a, D: Deserializer<'a>>(deserializer: D) -> Result<OffsetDateTime, D::Error> {
    deserializer.deserialize_any(Visitor::<Iso8601<SERDE_CONFIG>>(PhantomData))
}

/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`Option<OffsetDateTime>`].
///
/// Use this module in combination with serde's [`#[with]`][with] attribute.
///
/// [ISO 8601 format]: https://www.iso.org/iso-8601-date-and-time-format.html
/// [with]: https://serde.rs/field-attrs.html#with
pub mod option {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    /// Serialize an [`Option<OffsetDateTime>`] using the well-known ISO 8601 format.
    #[cfg(feature = "formatting")]
    pub fn serialize<S: Serializer>(
        option: &Option<OffsetDateTime>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        option
            .map(|odt| odt.format(&Iso8601::<SERDE_CONFIG>))
            .transpose()
            .map_err(S::Error::custom)?
            .serialize(serializer)
    }

    /// Deserialize an [`Option<OffsetDateTime>`] from its ISO 8601 representation.
    #[cfg(feature = "parsing")]
    pub fn deserialize<'a, D: Deserializer<'a>>(
        deserializer: D,
    ) -> Result<Option<OffsetDateTime>, D::Error> {
        deserializer.deserialize_option(Visitor::<Option<Iso8601<SERDE_CONFIG>>>(PhantomData))
    }
}


text:
import {BaseElement} from '../src/base-element';
import {Services} from '../src/services';
import {createPixel} from '../src/pixel';
import {dev, userAssert} from '../src/log';
import {registerElement} from '../src/service/custom-element-registry';

const TAG = 'amp-pixel';

/**
 * A simple analytics instrument. Fires as an impression signal.
 */
export class AmpPixel extends BaseElement {
  /** @override */
  constructor(element) {
    super(element);

    /** @private {?Promise<!Image>} */
    this.triggerPromise_ = null;
  }

  /** @override */
  isLayoutSupported(unusedLayout) {
    // No matter what layout is: the pixel is always non-displayed.
    return true;
  }

  /** @override */
  buildCallback() {
    // Element is invisible.
    this.element.setAttribute('aria-hidden', 'true');

    /** @private {?string} */
    this.referrerPolicy_ = this.element.getAttribute('referrerpolicy');
    if (this.referrerPolicy_) {
      // Safari doesn't support referrerPolicy yet. We're using an
      // iframe based trick to remove referrer, which apparently can
      // only do "no-referrer".
      userAssert(
        this.referrerPolicy_ == 'no-referrer',
        `${TAG}: invalid "referrerpolicy" value "${this.referrerPolicy_}".` +
          ' Only "no-referrer" is supported'
      );
    }
    if (
      this.element.hasAttribute('i-amphtml-ssr') &&
      this.element.querySelector('img')
    ) {
      dev().info(TAG, 'inabox img already present');
      return;
    }
    // Trigger, but only when visible.
    this.getAmpDoc()
      .whenFirstVisible()
      .then(this.trigger_.bind(this));
  }

  /**
   * Triggers the signal.
   * @return {*} TODO(#23582): Specify return type
   * @private
   */
  trigger_() {
    if (this.triggerPromise_) {
      // TODO(dvoytenko, #8780): monitor, confirm if there's a bug and remove.
      dev().error(TAG, 'duplicate pixel');
      return this.triggerPromise_;
    }
    // Delay(1) provides a rudimentary "idle" signal.
    // TODO(dvoytenko): use an improved idle signal when available.
    this.triggerPromise_ = Services.timerFor(this.win)
      .promise(1)
      .then(() => {
        const src = this.element.getAttribute('src');
        if (!src) {
          return;
        }
        return Services.urlReplacementsForDoc(this.element)
          .expandUrlAsync(this.assertSource_(src))
          .then(src => {
            if (!this.win) {
              return;
            }
            const pixel = createPixel(this.win, src, this.referrerPolicy_);
            dev().info(TAG, 'pixel triggered: ', src);
            return pixel;
          });
      });
  }

  /**
   * @param {?string} src
   * @return {string}
   * @private
   */
  assertSource_(src) {
    userAssert(
      /^(https\:\/\/|\/\/)/i.test(src),
      'The <amp-pixel> src attribute must start with ' +
        '"https://" or "//". Invalid value: ' +
        src
    );
    return /** @type {string} */ (src);
  }
}

/**
 * @param {!Window} win Destination window for the new element.
 */
export function installPixel(win) {
  registerElement(win, TAG, AmpPixel);
}


text:
define(
[
    'underscore',
    'utils',
    'models',
    'jsx!views/dialogs',
    'views/cluster_page_tabs/nodes_tab_screens/screen'
],
function(_, utils, models, dialogs, Screen) {
    'use strict';
    var EditNodeScreen;

    EditNodeScreen = Screen.extend({
        constructorName: 'EditNodeScreen',
        keepScrollPosition: true,
        disableControls: function(disable) {
            this.updateButtonsState(disable || this.isLocked());
        },
        returnToNodeList: function() {
            if (this.hasChanges()) {
                dialogs.DiscardSettingsChangesDialog.show({cb: _.bind(this.goToNodeList, this)});
            } else {
                this.goToNodeList();
            }
        },
        initialize: function(options) {
            _.defaults(this, options);
            var nodeIds = utils.deserializeTabOptions(this.screenOptions[0]).nodes.split(',').map(function(id) {return parseInt(id, 10);});
            this.nodes = new models.Nodes(this.cluster.get('nodes').getByIds(nodeIds));
        }
    });

    return EditNodeScreen;
});


text:
package com.google.javascript.rhino.jstype;

import com.google.common.collect.ImmutableSet;
import com.google.javascript.rhino.jstype.ObjectType;

/**
 * Represents the prototype of a {@link FunctionType}.
 * @author nicksantos@google.com (Nick Santos)
 */
public class FunctionPrototypeType extends PrototypeObjectType {
  private static final long serialVersionUID = 1L;

  private final FunctionType ownerFunction;

  FunctionPrototypeType(JSTypeRegistry registry, FunctionType ownerFunction,
      ObjectType implicitPrototype, boolean isNative) {
    super(registry, null /* has no class name */, implicitPrototype,
        isNative);
    this.ownerFunction = ownerFunction;
  }

  FunctionPrototypeType(JSTypeRegistry registry, FunctionType ownerFunction,
      ObjectType implicitPrototype) {
    this(registry, ownerFunction, implicitPrototype, false);
  }

  @Override
  public String getReferenceName() {
    if (ownerFunction == null) {
      return "{...}.prototype";
    } else {
      return ownerFunction.getReferenceName() + ".prototype";
    }
  }

  @Override
  public boolean hasReferenceName() {
    return ownerFunction != null && ownerFunction.hasReferenceName();
  }

  @Override
  public boolean isFunctionPrototypeType() {
    return true;
  }

  public FunctionType getOwnerFunction() {
    return ownerFunction;
  }

  @Override
  public Iterable<ObjectType> getCtorImplementedInterfaces() {
    return getOwnerFunction().getImplementedInterfaces();
  }

  @Override
  public Iterable<ObjectType> getCtorExtendedInterfaces() {
    if (getOwnerFunction() != null) {
      return getOwnerFunction().getExtendedInterfaces();
    } else {
      return ImmutableSet.of();
    }
  }

  // The owner will always be a resolved type, so there's no need to set
  // the ownerFunction in resolveInternal.
  // (it would lead to infinite loops if we did).
  // JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope);
}


text:
/**
 */
package com.rockwellcollins.atc.resolute.resolute;

/**
 *
 * A representation of the model object 'Let Expr'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link com.rockwellcollins.atc.resolute.resolute.LetExpr#getBinding Binding}

 *
{@link com.rockwellcollins.atc.resolute.resolute.LetExpr#getExpr Expr}

 *

 *

 *
 * @see com.rockwellcollins.atc.resolute.resolute.ResolutePackage#getLetExpr()
 * @model
 * @generated
 */
public interface LetExpr extends Expr
{
  /**
   * Returns the value of the 'Binding' containment reference.
   *
   *

   * If the meaning of the 'Binding' containment reference isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Binding' containment reference.
   * @see #setBinding(LetBinding)
   * @see com.rockwellcollins.atc.resolute.resolute.ResolutePackage#getLetExpr_Binding()
   * @model containment="true"
   * @generated
   */
  LetBinding getBinding();

  /**
   * Sets the value of the '{@link com.rockwellcollins.atc.resolute.resolute.LetExpr#getBinding Binding}' containment reference.
   *
   *
   * @param value the new value of the 'Binding' containment reference.
   * @see #getBinding()
   * @generated
   */
  void setBinding(LetBinding value);

  /**
   * Returns the value of the 'Expr' containment reference.
   *
   *

   * If the meaning of the 'Expr' containment reference isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Expr' containment reference.
   * @see #setExpr(Expr)
   * @see com.rockwellcollins.atc.resolute.resolute.ResolutePackage#getLetExpr_Expr()
   * @model containment="true"
   * @generated
   */
  Expr getExpr();

  /**
   * Sets the value of the '{@link com.rockwellcollins.atc.resolute.resolute.LetExpr#getExpr Expr}' containment reference.
   *
   *
   * @param value the new value of the 'Expr' containment reference.
   * @see #getExpr()
   * @generated
   */
  void setExpr(Expr value);

} // LetExpr


text:
using namespace cocos2d::ui;

class PlayerHeadUI : public cocos2d::CCLayer
{
public:
	PlayerHeadUI(void);
	~PlayerHeadUI(void);

	virtual void update(float delta);

	void bindPlayer(Player* pPlayer)
	{player = pPlayer;}
private:
	void initWidget();

	void processPlayerLife();
	void processPlayerHP();

	void setHPBarPercent(int percent);

	UILayer* uiLayer;

	Player* player;
	int playerLifeRecorder;
	int playerHPRecorder;
};

#endif


text: * #1 Add base interfaces


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LoggingWeaver.cs" company="Catel development team">
//   Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Catel.Fody.Weaving.Logging
{
    using System;
    using System.Linq;
    using Mono.Cecil;
    using Mono.Cecil.Cil;
    using Mono.Cecil.Rocks;

    public class LoggingWeaver
    {
        private const string CatelLoggingClass = "Catel.Logging.ILog";

        private readonly TypeDefinition _type;

        public LoggingWeaver(TypeDefinition type)
        {
            _type = type;
        }

        public void Execute()
        {
            var loggingFields = (from field in _type.Fields
                                 where field.IsStatic && string.Equals(field.FieldType.FullName, CatelLoggingClass)
                                 select field).ToList();

            if (loggingFields.Count == 0)
            {
                return;
            }

            var staticConstructor = _type.GetStaticConstructor();
            if (staticConstructor is null)
            {
                FodyEnvironment.WriteWarning($"Cannot weave ILog fields without a static constructor, ignoring type '{_type.FullName}'");
                return;
            }

            FodyEnvironment.WriteDebug($"\tExecuting '{GetType().Name}' for '{_type.FullName}'");

            var body = staticConstructor.Body;
            body.SimplifyMacros();

            try
            {
                UpdateCallsToGetCurrentClassLogger(body);
            }
            catch (Exception ex)
            {
                FodyEnvironment.WriteWarning($"Failed to update static log definition in '{_type.FullName}', '{ex.Message}'");
            }

            body.OptimizeMacros();
            staticConstructor.UpdateDebugInfo();
        }

        private void UpdateCallsToGetCurrentClassLogger(MethodBody ctorBody)
        {
            // Convert this:
            //
            // call class [Catel.Core]Catel.Logging.ILog [Catel.Core]Catel.Logging.LogManager::GetCurrentClassLogger()
            // stsfld class [Catel.Core]Catel.Logging.ILog Catel.Fody.TestAssembly.LoggingClass::AutoLog
            //
            // into this:
            //
            // ldtoken Catel.Fody.TestAssembly.LoggingClass
            // call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
            // call class [Catel.Core]Catel.Logging.ILog [Catel.Core]Catel.Logging.LogManager::GetLogger(class [mscorlib]System.Type)
            // stsfld class [Catel.Core]Catel.Logging.ILog Catel.Fody.TestAssembly.LoggingClass::ManualLog

            var type = ctorBody.Method.DeclaringType;
            var instructions = ctorBody.Instructions;

            for (var i = 0; i < instructions.Count; i++)
            {
                var instruction = instructions[i];

                if (instruction.Operand is MethodReference methodReference)
                {
                    if (string.Equals(methodReference.Name, "GetCurrentClassLogger"))
                    {
                        // We have a possible match
                        var getLoggerMethod = GetGetLoggerMethod(methodReference.DeclaringType);
                        if (getLoggerMethod is null)
                        {
                            var point = methodReference.Resolve().GetSequencePoint(instruction);

                            var message = $"Cannot change method call for log '{type.FullName}', the GetLogger(type) method does not exist on the calling type (try to use LogManager.GetCurrentClassLogger())";

                            if (point is not null)
                            {
                                FodyEnvironment.WriteWarningPoint(message, point);
                            }
                            else
                            {
                                FodyEnvironment.WriteWarning(message);
                            }
                            continue;
                        }

                        FodyEnvironment.WriteDebug($"Weaving auto log to specific log for '{type.FullName}'");

                        var getTypeFromHandle = type.Module.GetMethodAndImport("GetTypeFromHandle");

                        instructions.RemoveAt(i);

                        instructions.Insert(i,
                            Instruction.Create(OpCodes.Ldtoken, type),
                            Instruction.Create(OpCodes.Call, getTypeFromHandle),
                            Instruction.Create(OpCodes.Call, type.Module.ImportReference(getLoggerMethod)));
                    }
                }
            }
        }

        private MethodDefinition GetGetLoggerMethod(TypeReference logManagerType)
        {
            var typeDefinition = logManagerType.Resolve();

            return (from method in typeDefinition.Methods
                    where method.IsStatic && string.Equals(method.Name, "GetLogger") && method.Parameters.Count == 1
                    select method).FirstOrDefault();
        }
    }
}


text:
@interface SETFlipsideViewController ()

@end

@implementation SETFlipsideViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Actions

- (IBAction)done:(id)sender
{
    [self.delegate flipsideViewControllerDidFinish:self];
}

@end


text:
import simplejson as json
import os
from operator import itemgetter
from settings import CONFIG_ROOT, CONFIG_FILE, DB_ROOT, DBSUFFIX
import tempfile
from shutil import copy
import datetime
from uuid import uuid1 as uuid

__version__ = "0.2.0"

# required for python <=python2.5
## from __future__ import with

class Model(object):
    def __init__(self, *args, **kwargs):
        self.config = CONFIG_FILE
        # an individually selected object
        self.obj = None
        try:
            self.objects = self._load()
        except:
            self.objects = {}
        if (kwargs is not None):
            self.objects.update(kwargs)

    def _load(self, **kargs):
        """
        Keeping the kwarg for quick loads
        """
        retpath = os.path.join(CONFIG_ROOT, self.config)
        with open(retpath, 'r') as retfile:
            retjson = retfile.read()
        ret = json.loads(retjson)
        # Just get the slides, not the _doc
        return ret

    def _loaddb(self, dbname="models", dbpath=None):
        if dbpath is None:
            retpath = os.path.join(DB_ROOT, "%s.jsondb" % dbname)
            with open(retpath, 'r') as retfile:
                retjson = retfile.read()
        else:
            with open(dbpath, 'r') as f:
                retjson = f.read()
        ret = json.loads(retjson)
        return ret

    def _write(self, config):
        """
        Writes to the CONFIG_FILE
        """
        retpath = os.path.join(CONFIG_ROOT, self.config)
        fh, fp = tempfile.mkstemp(suffix=DBSUFFIX, dir=DB_ROOT)
        try:
            configtowrite = json.dumps(config)
        except:
            print "ERROR Dumping Config JSON"
            return False
        try:
            with os.fdopen(fh, 'w') as f:
                f.write(configtowrite)
            f.close()
            return True
        except:
            print "ERROR Writing File"
            return False

    def objects(self):
        return self.objects

    def by_field(self, slide_id):
        return [x[str(slide_id)] for x in self.objects]

    def fields(self):
        ret = []
        fields = [x.keys() for x in self.objects]
        for field in fields:
            ret.extend(field)
        return set(ret)

    def find(self, query):
        ret = []
        for field in self.fields():
            try:
                ret.extend([x['title'] for x in self.objects if x.get(field, 0).lower() == query.lower()])
            except KeyError:
                print "No such key 'title'"
                return False
        return ret

class Slide(Model):
    def __init__(self, *args, **kwargs):
        self.db = self._loaddb()
        self.tmpon = False
        self.dbfp = ""
        super(Slide, self).__init__(*args, **kwargs)
        if self.config is None:
            self.config = CONFIG_FILE
        if kwargs is not None:
            self.objects.update(kwargs)

    def _load(self):
        return dict(slides=super(Slide, self)._load()['slides'])

    def _loaddb(self):
        return super(Slide, self)._loaddb('slidedb')

    def _tmpdb(self, dbdata=None, db=DB_ROOT):
        """
        make a temporary file to write the db into
        """
        fh, fp = tempfile.mkstemp(suffix=DBSUFFIX, dir=db)
        if dbdata is not None:
            try:
                dbtowrite = json.dumps(dbdata)
            except:
                print 'Could not dump json to db'
                return False
            try:
                with os.fdopen(fh, 'w+') as f:
                    f.write(dbtowrite)
                f.close()
                self.tmpon, self.dbfp, self.dbfh = True, fp, fh
                return True
            except:
                print "Error writing DB"
                return False
        with os.fdopen(fh, 'w+') as f:
            f.write(json.dumps(self.objects))
        f.close()
        self.tmpon, self.dbfp, self.dbfh = True, fp, fh
        return True

    def _dynodb(self, dbname=None, db=DB_ROOT):
        """
        writes all dynamic keys (id, datetime/RT, and slide order)
        to the dynamicdb
        I think this is a JOIN operation, but I'm not an expert.
        """
        if self.tmpon:
            try:
                incr = 0
                for slide in self.by_weight():
                    incr += 1
                    _metadata = dict(_metadata=dict(
                        id=incr,
                        uuid=str(uuid()),
                        ## replace with dynamic url-builder
                        url="/s/%i" % incr
                        ))
                    print slide
                    slide.update(_metadata)
                    print "updated to %s" % slide
                try:
                    with open(self.dbfp, "w") as f:
                        f.write(json.dumps(slide))
                    f.close()
                    self.db = super(Slide, self)._loaddb(dbpath=self.dbfp)
                except:
                    print "ERROR, couldn't write file"
                    return False
            except:
                print "ERROR, couldn't insert into file"
                return False

    def _writedb(self, dbname=None, db=DB_ROOT):
        """
        simply copies the tmp file to the db
        folder and adds a timestamp to the
        filename.
        """
        if dbname is not None:
            dbname = "%s.jsondb" % dbname
        dbname = "%(dbname)s-%(timestamp)s.jsondb" % dict(dbname='slidedb',
                timestamp=datetime.datetime.strftime(datetime.datetime.now(),
                    format="%Y%m%d-%H%M%S"))
        fp = os.path.join(db, dbname)
        copy(self.dbfp, fp)
        self.tmpon, self.dbfp = False, fp
        return True

    def slides(self):
        return self.objects['slides']

    def by_weight(self):
        return sorted(self.objects['slides'], key=itemgetter('weight'))

    def by_id(self, sid):
        """
        The id <sid> is determined by weight order and is only available to
        items already in the database.
        """
        slide = {}
        try:
            for obj in self.objects['slides']:
                ## this key isn't in for some reason
                if obj['_metadata']['id'] == sid:
                ##if obj['id'] == sid:
                    slide.update(obj)
        except:
            print "No ID on model"
            return False
        self.obj = slide
        return slide

    def sorted_id(self):
        """
        sorted by id
        """
        slides = sorted(self.objects['slides'], key=itemgetter('id'))
        return slides

    def nxt(self, sid=1):
        """
        finds the next slide in relation to the current one
        """
        if self.obj:
            ret = self.by_id(self.obj['_metadata']['id'] + 1)
            try:
                meta = ret['_metadata']
                return ret
            except:
                return False
        return False

    def previous(self):
        """
        finds the previous slide in relation to the current one
        """
        if self.obj:
            ret = self.by_id(self.obj['_metadata']['id'] - 1)
            try:
                meta = ret['_metadata']
                return ret
            except:
                return False
        return False

class Config(Model):
    """
    A config model for taking in configured files
    """
    pass

class Result(Model):
    """
    A result model for writing, computing, and displaying results
    """
    pass


text:
package jp.co.ctc_g.jse.core.validation.constraints.feature.fixedgreaterthanequalsto;

import java.math.BigDecimal;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import jp.co.ctc_g.jse.core.validation.constraints.FixedGreaterThanEqualsTo;
import jp.co.ctc_g.jse.core.validation.util.Validators;

/**
 *

 * このクラスは、{@link FixedGreaterThanEqualsTo}バリデータの検証アルゴリズムを実装しています。
 *

 *

 * {@link FixedGreaterThanEqualsTo}バリデータの検証アルゴリズムは、プロパティの値が比較対象の数値よりも大きいかあるいが同じかどうかを検証しています。
 *

 * @author ITOCHU Techno-Solutions Corporation.
 * @see FixedGreaterThanEqualsTo
 */
public class FixedGreaterThanEqualsToValidatorForNumber implements ConstraintValidator<FixedGreaterThanEqualsTo, Number> {

    private BigDecimal target;

    /**
     * デフォルトコンストラクタです。
     */
    public FixedGreaterThanEqualsToValidatorForNumber() {}

    /**
     * {@inheritDoc}
     */
    @Override
    public void initialize(FixedGreaterThanEqualsTo constraint) {
        target = Validators.toBigDecimal(constraint.value(), true);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isValid(Number suspect, ConstraintValidatorContext context) {
        if (suspect == null) return true;
        return Validators.greaterThanEqualsTo(suspect, target);
    }
}


text:
namespace Fortis.Model
{
	public interface ICustomItemFactory : IItemFactory
	{
	}
}


text:
//
// このファイルは、JavaTM Architecture for XML Binding(JAXB) Reference Implementation、v2.2.8-b130911.1802によって生成されました
// http://java.sun.com/xml/jaxbを参照してください
// ソース・スキーマの再コンパイル時にこのファイルの変更は失われます。
// 生成日: 2015.08.24 時間 02:38:24 AM JST
//

package com.eitax.recall.rest.ebay.shopping.xsd;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 * 				Type for expressing sales tax data.
 *
 *
 *
SalesTaxType complex typeのJavaクラス。
 *
 *
次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。
 *
 *

 * <complexType name="SalesTaxType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="SalesTaxPercent" type="{http://www.w3.org/2001/XMLSchema}float" minOccurs="0"/>
 *         <element name="SalesTaxState" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ShippingIncludedInTax" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="SalesTaxAmount" type="{urn:ebay:apis:eBLBaseComponents}AmountType" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SalesTaxType", propOrder = {
    "salesTaxPercent",
    "salesTaxState",
    "shippingIncludedInTax",
    "salesTaxAmount"
})
public class SalesTaxType {

    @XmlElement(name = "SalesTaxPercent")
    protected Float salesTaxPercent;
    @XmlElement(name = "SalesTaxState")
    protected String salesTaxState;
    @XmlElement(name = "ShippingIncludedInTax")
    protected Boolean shippingIncludedInTax;
    @XmlElement(name = "SalesTaxAmount")
    protected AmountType salesTaxAmount;

    /**
     * salesTaxPercentプロパティの値を取得します。
     *
     * @return
     *     possible object is
     *     {@link Float }
     *
     */
    public Float getSalesTaxPercent() {
        return salesTaxPercent;
    }

    /**
     * salesTaxPercentプロパティの値を設定します。
     *
     * @param value
     *     allowed object is
     *     {@link Float }
     *
     */
    public void setSalesTaxPercent(Float value) {
        this.salesTaxPercent = value;
    }

    /**
     * salesTaxStateプロパティの値を取得します。
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSalesTaxState() {
        return salesTaxState;
    }

    /**
     * salesTaxStateプロパティの値を設定します。
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSalesTaxState(String value) {
        this.salesTaxState = value;
    }

    /**
     * shippingIncludedInTaxプロパティの値を取得します。
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isShippingIncludedInTax() {
        return shippingIncludedInTax;
    }

    /**
     * shippingIncludedInTaxプロパティの値を設定します。
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setShippingIncludedInTax(Boolean value) {
        this.shippingIncludedInTax = value;
    }

    /**
     * salesTaxAmountプロパティの値を取得します。
     *
     * @return
     *     possible object is
     *     {@link AmountType }
     *
     */
    public AmountType getSalesTaxAmount() {
        return salesTaxAmount;
    }

    /**
     * salesTaxAmountプロパティの値を設定します。
     *
     * @param value
     *     allowed object is
     *     {@link AmountType }
     *
     */
    public void setSalesTaxAmount(AmountType value) {
        this.salesTaxAmount = value;
    }

}


text:
"""
sudo.decorators
~~~~~~~~~~~~~~~

:copyright: (c) 2020 by Matt Robenolt.
:license: BSD, see LICENSE for more details.
"""
from functools import wraps

from sudo.views import redirect_to_sudo

def sudo_required(func):
    """
    Enforces a view to have elevated privileges.
    Should likely be paired with ``@login_required``.

    >>> @sudo_required
    >>> def secure_page(request):
    >>>     ...
    """

    @wraps(func)
    def inner(request, *args, **kwargs):
        if not request.is_sudo():
            return redirect_to_sudo(request.get_full_path())
        return func(request, *args, **kwargs)

    return inner