code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:07:22 PM BST
//
package com.oracle.xmlns.apps.crmcommon.interactions.interactionservice.types;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.adf.svc.types.ProcessControl;
import com.oracle.xmlns.apps.crmcommon.interactions.interactionservice.InteractionAssociation;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="changeOperation" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="interactionAssociationWS" type="{http://xmlns.oracle.com/apps/crmCommon/interactions/interactionService/}InteractionAssociation" maxOccurs="unbounded" minOccurs="0"/>
* <element name="processControl" type="{http://xmlns.oracle.com/adf/svc/types/}ProcessControl"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"changeOperation",
"interactionAssociationWS",
"processControl"
})
@XmlRootElement(name = "processInteractionAssociation")
public class ProcessInteractionAssociation {
@XmlElement(required = true)
protected String changeOperation;
protected List<InteractionAssociation> interactionAssociationWS;
@XmlElement(required = true)
protected ProcessControl processControl;
/**
* Gets the value of the changeOperation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChangeOperation() {
return changeOperation;
}
/**
* Sets the value of the changeOperation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChangeOperation(String value) {
this.changeOperation = value;
}
/**
* Gets the value of the interactionAssociationWS property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the interactionAssociationWS property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getInteractionAssociationWS().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link InteractionAssociation }
*
*
*/
public List<InteractionAssociation> getInteractionAssociationWS() {
if (interactionAssociationWS == null) {
interactionAssociationWS = new ArrayList<InteractionAssociation>();
}
return this.interactionAssociationWS;
}
/**
* Gets the value of the processControl property.
*
* @return
* possible object is
* {@link ProcessControl }
*
*/
public ProcessControl getProcessControl() {
return processControl;
}
/**
* Sets the value of the processControl property.
*
* @param value
* allowed object is
* {@link ProcessControl }
*
*/
public void setProcessControl(ProcessControl value) {
this.processControl = value;
}
}
| dushmis/Oracle-Cloud | PaaS_SaaS_Accelerator_RESTFulFacade/XJC_Beans/src/com/oracle/xmlns/apps/crmcommon/interactions/interactionservice/types/ProcessInteractionAssociation.java | Java | bsd-3-clause | 4,291 |
package edu.team597.support;
/**
* @author Tom Bottiglieri
* Team 254, The Cheesy Poofs
*/
import edu.wpi.first.wpilibj.Timer;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.ServerSocketConnection;
import javax.microedition.io.SocketConnection;
public class CheesyVisionServer implements Runnable {
private static CheesyVisionServer instance_;
Thread serverThread = new Thread(this);
private int listenPort_;
private Vector connections_;
private boolean counting_ = false;
private int leftCount_ = 0, rightCount_ = 0, totalCount_ = 0;
private boolean curLeftStatus_ = false, curRightStatus_ = false;
double lastHeartbeatTime_ = -1;
private boolean listening_ = true;
public static CheesyVisionServer getInstance() {
if (instance_ == null) {
instance_ = new CheesyVisionServer();
}
return instance_;
}
public void start() {
serverThread.start();
}
public void stop() {
listening_ = false;
}
private CheesyVisionServer() {
this(1180);
}
private CheesyVisionServer(int port) {
listenPort_ = port;
connections_ = new Vector();
}
public boolean hasClientConnection() {
return lastHeartbeatTime_ > 0 && (Timer.getFPGATimestamp() - lastHeartbeatTime_) < 3.0;
}
public void setPort(int port) {
listenPort_ = port;
}
private void updateCounts(boolean left, boolean right) {
if (counting_) {
leftCount_ += left ? 1 : 0;
rightCount_ += right ? 1 : 0;
totalCount_++;
}
}
public void startSamplingCounts() {
counting_ = true;
}
public void stopSamplingCounts() {
counting_ = false;
}
public void reset() {
leftCount_ = rightCount_ = totalCount_ = 0;
curLeftStatus_ = curRightStatus_ = false;
}
public int getLeftCount() {
return leftCount_;
}
public int getRightCount() {
return rightCount_;
}
public int getTotalCount() {
return totalCount_;
}
public boolean getLeftStatus() {
return curLeftStatus_;
}
public boolean getRightStatus() {
return curRightStatus_;
}
// This class handles incoming TCP connections
private class VisionServerConnectionHandler implements Runnable {
SocketConnection connection;
public VisionServerConnectionHandler(SocketConnection c) {
connection = c;
}
public void run() {
try {
InputStream is = connection.openInputStream();
int ch = 0;
byte[] b = new byte[1024];
double timeout = 10.0;
double lastHeartbeat = Timer.getFPGATimestamp();
CheesyVisionServer.this.lastHeartbeatTime_ = lastHeartbeat;
while (Timer.getFPGATimestamp() < lastHeartbeat + timeout) {
boolean gotData = false;
while (is.available() > 0) {
gotData = true;
int read = is.read(b);
for (int i = 0; i < read; ++i) {
byte reading = b[i];
boolean leftStatus = (reading & (1 << 1)) > 0;
boolean rightStatus = (reading & (1 << 0)) > 0;
CheesyVisionServer.this.curLeftStatus_ = leftStatus;
CheesyVisionServer.this.curRightStatus_ = rightStatus;
CheesyVisionServer.this.updateCounts(leftStatus, rightStatus);
}
lastHeartbeat = Timer.getFPGATimestamp();
CheesyVisionServer.this.lastHeartbeatTime_ = lastHeartbeat;
}
try {
Thread.sleep(50); // sleep a bit
} catch (InterruptedException ex) {
System.out.println("Thread sleep failed.");
}
}
is.close();
connection.close();
} catch (IOException e) {
}
}
}
// run() to implement Runnable
// This method listens for incoming connections and spawns new
// VisionServerConnectionHandlers to handle them
public void run() {
ServerSocketConnection s = null;
try {
s = (ServerSocketConnection) Connector.open("serversocket://:" + listenPort_);
while (listening_) {
SocketConnection connection = (SocketConnection) s.acceptAndOpen();
Thread t = new Thread(new CheesyVisionServer.VisionServerConnectionHandler(connection));
t.start();
connections_.addElement(connection);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
System.out.println("Thread sleep failed.");
}
}
} catch (IOException e) {
System.out.println("Socket failure.");
e.printStackTrace();
}
}
}
| Team597/FRC-2014-StartLifter-Code | src/edu/team597/support/CheesyVisionServer.java | Java | bsd-3-clause | 4,666 |
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Index, Integer, String
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.sql.functions import GenericFunction
from qcfractal.storage_sockets.models.sql_base import Base, MsgpackExt
# class json_agg(GenericFunction):
# type = postgresql.JSON
class json_build_object(GenericFunction):
type = postgresql.JSON
class CollectionORM(Base):
"""
A base collection class of precomuted workflows such as datasets, ..
This is a dynamic document, so it will accept any number of
extra fields (expandable and uncontrolled schema)
"""
__tablename__ = "collection"
id = Column(Integer, primary_key=True)
collection_type = Column(String) # for inheritance
collection = Column(String(100), nullable=False)
lname = Column(String(100), nullable=False)
name = Column(String(100), nullable=False)
tags = Column(JSON)
tagline = Column(String)
description = Column(String)
group = Column(String(100), nullable=False)
visibility = Column(Boolean, nullable=False)
view_url_hdf5 = Column(String)
view_url_plaintext = Column(String)
view_metadata = Column(JSON)
view_available = Column(Boolean, nullable=False)
provenance = Column(JSON)
extra = Column(JSON) # extra data related to specific collection type
def update_relations(self, **kwarg):
pass
__table_args__ = (
Index("ix_collection_lname", "collection", "lname", unique=True),
Index("ix_collection_type", "collection_type"),
)
__mapper_args__ = {"polymorphic_on": "collection_type"}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class DatasetMixin:
"""
Mixin class for common Dataset attributes.
"""
default_benchmark = Column(String)
default_keywords = Column(JSON)
default_driver = Column(String)
default_units = Column(String)
alias_keywords = Column(JSON)
default_program = Column(String)
history_keys = Column(JSON)
history = Column(JSON)
class ContributedValuesORM(Base):
"""One group of a contibuted values per dataset
Each dataset can have multiple rows in this table"""
__tablename__ = "contributed_values"
collection_id = Column(Integer, ForeignKey("collection.id", ondelete="cascade"), primary_key=True)
name = Column(String, nullable=False, primary_key=True)
values = Column(MsgpackExt, nullable=False)
index = Column(MsgpackExt, nullable=False)
values_structure = Column(JSON, nullable=False)
theory_level = Column(JSON, nullable=False)
units = Column(String, nullable=False)
theory_level_details = Column(JSON)
citations = Column(JSON)
external_url = Column(String)
doi = Column(String)
comments = Column(String)
class DatasetEntryORM(Base):
"""Association table for many to many"""
__tablename__ = "dataset_entry"
dataset_id = Column(Integer, ForeignKey("dataset.id", ondelete="cascade"), primary_key=True)
# TODO: check the cascase_delete with molecule
molecule_id = Column(Integer, ForeignKey("molecule.id"), nullable=False)
name = Column(String, nullable=False, primary_key=True)
comment = Column(String)
local_results = Column(JSON)
class DatasetORM(CollectionORM, DatasetMixin):
"""
The Dataset class for homogeneous computations on many molecules.
"""
__tablename__ = "dataset"
id = Column(Integer, ForeignKey("collection.id", ondelete="CASCADE"), primary_key=True)
contributed_values_obj = relationship(ContributedValuesORM, lazy="selectin", cascade="all, delete-orphan")
records_obj = relationship(
DatasetEntryORM, lazy="selectin", cascade="all, delete-orphan", backref="dataset" # lazy='noload',
)
@hybrid_property
def contributed_values(self):
return self._contributed_values(self.contributed_values_obj)
@staticmethod
def _contributed_values(contributed_values_obj):
if not contributed_values_obj:
return {}
if not isinstance(contributed_values_obj, list):
contributed_values_obj = [contributed_values_obj]
ret = {}
try:
for obj in contributed_values_obj:
ret[obj.name.lower()] = obj.to_dict(exclude=["collection_id"])
except Exception as err:
pass
return ret
@contributed_values.setter
def contributed_values(self, dict_values):
return dict_values
@hybrid_property
def records(self):
"""calculated property when accessed, not saved in the DB
A view of the many to many relation"""
return self._records(self.records_obj)
@staticmethod
def _records(records_obj):
if not records_obj:
return []
if not isinstance(records_obj, list):
records_obj = [records_obj]
ret = []
try:
for rec in records_obj:
ret.append(rec.to_dict(exclude=["dataset_id"]))
except Exception as err:
# raises exception of first access!!
pass
return ret
@records.setter
def records(self, dict_values):
return dict_values
def update_relations(self, records=None, contributed_values=None, **kwarg):
self.records_obj = []
records = [] if not records else records
for rec_dict in records:
rec = DatasetEntryORM(dataset_id=int(self.id), **rec_dict)
self.records_obj.append(rec)
self.contributed_values_obj = []
contributed_values = {} if not contributed_values else contributed_values
for key, rec_dict in contributed_values.items():
rec = ContributedValuesORM(collection_id=int(self.id), **rec_dict)
self.contributed_values_obj.append(rec)
__table_args__ = (
# Index('ix_results_molecule', 'molecule'), # b-tree index
# UniqueConstraint("program", "driver", "method", "basis", "keywords", "molecule", name='uix_results_keys'),
)
__mapper_args__ = {
"polymorphic_identity": "dataset",
# to have separate select when querying CollectionORM
"polymorphic_load": "selectin",
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class ReactionDatasetEntryORM(Base):
"""Association table for many to many"""
__tablename__ = "reaction_dataset_entry"
reaction_dataset_id = Column(Integer, ForeignKey("reaction_dataset.id", ondelete="cascade"), primary_key=True)
attributes = Column(JSON)
name = Column(String, nullable=False, primary_key=True)
reaction_results = Column(JSON)
stoichiometry = Column(JSON)
extras = Column(JSON)
class ReactionDatasetORM(CollectionORM, DatasetMixin):
"""
Reaction Dataset
"""
__tablename__ = "reaction_dataset"
id = Column(Integer, ForeignKey("collection.id", ondelete="CASCADE"), primary_key=True)
ds_type = Column(String)
records_obj = relationship(
ReactionDatasetEntryORM, lazy="selectin", cascade="all, delete-orphan", backref="reaction_dataset"
)
contributed_values_obj = relationship(ContributedValuesORM, lazy="selectin", cascade="all, delete-orphan")
@hybrid_property
def contributed_values(self):
return self._contributed_values(self.contributed_values_obj)
@staticmethod
def _contributed_values(contributed_values_obj):
return DatasetORM._contributed_values(contributed_values_obj)
@contributed_values.setter
def contributed_values(self, dict_values):
return dict_values
def update_relations(self, records=None, contributed_values=None, **kwarg):
self.records_obj = []
records = records or []
for rec_dict in records:
rec = ReactionDatasetEntryORM(reaction_dataset_id=int(self.id), **rec_dict)
self.records_obj.append(rec)
self.contributed_values_obj = []
contributed_values = {} if not contributed_values else contributed_values
for key, rec_dict in contributed_values.items():
rec = ContributedValuesORM(collection_id=int(self.id), **rec_dict)
self.contributed_values_obj.append(rec)
@hybrid_property
def records(self):
"""calculated property when accessed, not saved in the DB
A view of the many to many relation"""
return self._records(self.records_obj)
@staticmethod
def _records(records_obj):
if not records_obj:
return []
if not isinstance(records_obj, list):
records_obj = [records_obj]
ret = []
try:
for rec in records_obj:
ret.append(rec.to_dict(exclude=["reaction_dataset_id"]))
except Exception as err:
# raises exception of first access!!
pass
return ret
@records.setter
def records(self, dict_values):
return dict_values
__table_args__ = (
# Index('ix_results_molecule', 'molecule'), # b-tree index
# UniqueConstraint("program", "driver", "method", "basis", "keywords", "molecule", name='uix_results_keys'),
)
__mapper_args__ = {
"polymorphic_identity": "reactiondataset",
# to have separate select when querying CollectionORM
"polymorphic_load": "selectin",
}
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| psi4/mongo_qcdb | qcfractal/storage_sockets/models/collections_models.py | Python | bsd-3-clause | 9,556 |
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/layout/TextAutosizer.h"
#include "core/dom/Document.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/VisualViewport.h"
#include "core/html/HTMLTextAreaElement.h"
#include "core/layout/LayoutBlock.h"
#include "core/layout/LayoutListItem.h"
#include "core/layout/LayoutListMarker.h"
#include "core/layout/LayoutTableCell.h"
#include "core/layout/LayoutView.h"
#include "core/layout/line/InlineIterator.h"
#include "core/page/Page.h"
#ifdef AUTOSIZING_DOM_DEBUG_INFO
#include "core/dom/ExecutionContextTask.h"
#endif
namespace blink {
#ifdef AUTOSIZING_DOM_DEBUG_INFO
class WriteDebugInfoTask : public ExecutionContextTask {
public:
WriteDebugInfoTask(PassRefPtrWillBeRawPtr<Element> element, AtomicString value)
: m_element(element)
, m_value(value)
{
}
virtual void performTask(ExecutionContext*)
{
m_element->setAttribute("data-autosizing", m_value, ASSERT_NO_EXCEPTION);
}
private:
RefPtrWillBePersistent<Element> m_element;
AtomicString m_value;
};
static void writeDebugInfo(LayoutObject* layoutObject, const AtomicString& output)
{
Node* node = layoutObject->node();
if (!node)
return;
if (node->isDocumentNode())
node = toDocument(node)->documentElement();
if (!node->isElementNode())
return;
node->document().postTask(adoptPtr(new WriteDebugInfoTask(toElement(node), output)));
}
void TextAutosizer::writeClusterDebugInfo(Cluster* cluster)
{
String explanation = "";
if (cluster->m_flags & SUPPRESSING) {
explanation = "[suppressed]";
} else if (!(cluster->m_flags & (INDEPENDENT | WIDER_OR_NARROWER))) {
explanation = "[inherited]";
} else if (cluster->m_supercluster) {
explanation = "[supercluster]";
} else if (!clusterHasEnoughTextToAutosize(cluster)) {
explanation = "[insufficient-text]";
} else {
const LayoutBlock* widthProvider = clusterWidthProvider(cluster->m_root);
if (cluster->m_hasTableAncestor && cluster->m_multiplier < multiplierFromBlock(widthProvider)) {
explanation = "[table-ancestor-limited]";
} else {
explanation = String::format("[from width %d of %s]",
static_cast<int>(widthFromBlock(widthProvider)), widthProvider->debugName().utf8().data());
}
}
String pageInfo = "";
if (cluster->m_root->isLayoutView()) {
pageInfo = String::format("; pageinfo: bm %f * (lw %d / fw %d)",
m_pageInfo.m_baseMultiplier, m_pageInfo.m_layoutWidth, m_pageInfo.m_frameWidth);
}
float multiplier = cluster->m_flags & SUPPRESSING ? 1.0 : cluster->m_multiplier;
writeDebugInfo(const_cast<LayoutBlock*>(cluster->m_root),
AtomicString(String::format("cluster: %f %s%s", multiplier,
explanation.utf8().data(), pageInfo.utf8().data())));
}
#endif
static const LayoutObject* parentElementLayoutObject(const LayoutObject* layoutObject)
{
// At style recalc, the layoutObject's parent may not be attached,
// so we need to obtain this from the DOM tree.
const Node* node = layoutObject->node();
if (!node)
return nullptr;
// FIXME: This should be using LayoutTreeBuilderTraversal::parent().
if (Element* parent = node->parentElement())
return parent->layoutObject();
return nullptr;
}
static bool isNonTextAreaFormControl(const LayoutObject* layoutObject)
{
const Node* node = layoutObject ? layoutObject->node() : nullptr;
if (!node || !node->isElementNode())
return false;
const Element* element = toElement(node);
return (element->isFormControlElement() && !isHTMLTextAreaElement(element));
}
static bool isPotentialClusterRoot(const LayoutObject* layoutObject)
{
// "Potential cluster roots" are the smallest unit for which we can
// enable/disable text autosizing.
// - Must have children.
// An exception is made for LayoutView which should create a root to
// maintain consistency with documents that have no child nodes but may
// still have LayoutObject children.
// - Must not be inline, as different multipliers on one line looks terrible.
// Exceptions are inline-block and alike elements (inline-table, -webkit-inline-*),
// as they often contain entire multi-line columns of text.
// - Must not be normal list items, as items in the same list should look
// consistent, unless they are floating or position:absolute/fixed.
Node* node = layoutObject->generatingNode();
if (node && !node->hasChildren() && !layoutObject->isLayoutView())
return false;
if (!layoutObject->isLayoutBlock())
return false;
if (layoutObject->isInline() && !layoutObject->style()->isDisplayReplacedType())
return false;
if (layoutObject->isListItem())
return (layoutObject->isFloating() || layoutObject->isOutOfFlowPositioned());
return true;
}
static bool isIndependentDescendant(const LayoutBlock* layoutObject)
{
ASSERT(isPotentialClusterRoot(layoutObject));
LayoutBlock* containingBlock = layoutObject->containingBlock();
return layoutObject->isLayoutView()
|| layoutObject->isFloating()
|| layoutObject->isOutOfFlowPositioned()
|| layoutObject->isTableCell()
|| layoutObject->isTableCaption()
|| layoutObject->isFlexibleBoxIncludingDeprecated()
|| (containingBlock && containingBlock->isHorizontalWritingMode() != layoutObject->isHorizontalWritingMode())
|| layoutObject->style()->isDisplayReplacedType()
|| layoutObject->isTextArea()
|| layoutObject->style()->userModify() != READ_ONLY;
}
static bool blockIsRowOfLinks(const LayoutBlock* block)
{
// A "row of links" is a block for which:
// 1. It does not contain non-link text elements longer than 3 characters
// 2. It contains a minimum of 3 inline links and all links should
// have the same specified font size.
// 3. It should not contain <br> elements.
// 4. It should contain only inline elements unless they are containers,
// children of link elements or children of sub-containers.
int linkCount = 0;
LayoutObject* layoutObject = block->firstChild();
float matchingFontSize = -1;
while (layoutObject) {
if (!isPotentialClusterRoot(layoutObject)) {
if (layoutObject->isText() && toLayoutText(layoutObject)->text().stripWhiteSpace().length() > 3)
return false;
if (!layoutObject->isInline() || layoutObject->isBR())
return false;
}
if (layoutObject->style()->isLink()) {
linkCount++;
if (matchingFontSize < 0)
matchingFontSize = layoutObject->style()->specifiedFontSize();
else if (matchingFontSize != layoutObject->style()->specifiedFontSize())
return false;
// Skip traversing descendants of the link.
layoutObject = layoutObject->nextInPreOrderAfterChildren(block);
continue;
}
layoutObject = layoutObject->nextInPreOrder(block);
}
return (linkCount >= 3);
}
static bool blockHeightConstrained(const LayoutBlock* block)
{
// FIXME: Propagate constrainedness down the tree, to avoid inefficiently walking back up from each box.
// FIXME: This code needs to take into account vertical writing modes.
// FIXME: Consider additional heuristics, such as ignoring fixed heights if the content is already overflowing before autosizing kicks in.
for (; block; block = block->containingBlock()) {
const ComputedStyle& style = block->styleRef();
if (style.overflowY() >= OSCROLL)
return false;
if (style.height().isSpecified() || style.maxHeight().isSpecified() || block->isOutOfFlowPositioned()) {
// Some sites (e.g. wikipedia) set their html and/or body elements to height:100%,
// without intending to constrain the height of the content within them.
return !block->isDocumentElement() && !block->isBody() && !block->isLayoutView();
}
if (block->isFloating())
return false;
}
return false;
}
static bool blockOrImmediateChildrenAreFormControls(const LayoutBlock* block)
{
if (isNonTextAreaFormControl(block))
return true;
const LayoutObject* layoutObject = block->firstChild();
while (layoutObject) {
if (isNonTextAreaFormControl(layoutObject))
return true;
layoutObject = layoutObject->nextSibling();
}
return false;
}
// Some blocks are not autosized even if their parent cluster wants them to.
static bool blockSuppressesAutosizing(const LayoutBlock* block)
{
if (blockOrImmediateChildrenAreFormControls(block))
return true;
if (blockIsRowOfLinks(block))
return true;
// Don't autosize block-level text that can't wrap (as it's likely to
// expand sideways and break the page's layout).
if (!block->style()->autoWrap())
return true;
if (blockHeightConstrained(block))
return true;
return false;
}
static bool hasExplicitWidth(const LayoutBlock* block)
{
// FIXME: This heuristic may need to be expanded to other ways a block can be wider or narrower
// than its parent containing block.
return block->style() && block->style()->width().isSpecified();
}
TextAutosizer::TextAutosizer(const Document* document)
: m_document(document)
, m_firstBlockToBeginLayout(nullptr)
#if ENABLE(ASSERT)
, m_blocksThatHaveBegunLayout()
#endif
, m_superclusters()
, m_clusterStack()
, m_fingerprintMapper()
, m_pageInfo()
, m_updatePageInfoDeferred(false)
{
}
void TextAutosizer::record(const LayoutBlock* block)
{
if (!m_pageInfo.m_settingEnabled)
return;
ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
if (!classifyBlock(block, INDEPENDENT | EXPLICIT_WIDTH))
return;
if (Fingerprint fingerprint = computeFingerprint(block))
m_fingerprintMapper.addTentativeClusterRoot(block, fingerprint);
}
void TextAutosizer::destroy(const LayoutBlock* block)
{
if (!m_pageInfo.m_settingEnabled && !m_fingerprintMapper.hasFingerprints())
return;
ASSERT(!m_blocksThatHaveBegunLayout.contains(block));
if (m_fingerprintMapper.remove(block) && m_firstBlockToBeginLayout) {
// LayoutBlock with a fingerprint was destroyed during layout.
// Clear the cluster stack and the supercluster map to avoid stale pointers.
// Speculative fix for http://crbug.com/369485.
m_firstBlockToBeginLayout = nullptr;
m_clusterStack.clear();
m_superclusters.clear();
}
}
TextAutosizer::BeginLayoutBehavior TextAutosizer::prepareForLayout(const LayoutBlock* block)
{
#if ENABLE(ASSERT)
m_blocksThatHaveBegunLayout.add(block);
#endif
if (!m_firstBlockToBeginLayout) {
m_firstBlockToBeginLayout = block;
prepareClusterStack(block->parent());
} else if (block == currentCluster()->m_root) {
// Ignore beginLayout on the same block twice.
// This can happen with paginated overflow.
return StopLayout;
}
return ContinueLayout;
}
void TextAutosizer::prepareClusterStack(const LayoutObject* layoutObject)
{
if (!layoutObject)
return;
prepareClusterStack(layoutObject->parent());
if (layoutObject->isLayoutBlock()) {
const LayoutBlock* block = toLayoutBlock(layoutObject);
#if ENABLE(ASSERT)
m_blocksThatHaveBegunLayout.add(block);
#endif
if (Cluster* cluster = maybeCreateCluster(block))
m_clusterStack.append(adoptPtr(cluster));
}
}
void TextAutosizer::beginLayout(LayoutBlock* block)
{
ASSERT(shouldHandleLayout());
if (prepareForLayout(block) == StopLayout)
return;
ASSERT(!m_clusterStack.isEmpty() || block->isLayoutView());
if (Cluster* cluster = maybeCreateCluster(block))
m_clusterStack.append(adoptPtr(cluster));
ASSERT(!m_clusterStack.isEmpty());
// Cells in auto-layout tables are handled separately by inflateAutoTable.
bool isAutoTableCell = block->isTableCell() && !toLayoutTableCell(block)->table()->style()->isFixedTableLayout();
if (!isAutoTableCell && !m_clusterStack.isEmpty())
inflate(block);
}
void TextAutosizer::inflateAutoTable(LayoutTable* table)
{
ASSERT(table);
ASSERT(!table->style()->isFixedTableLayout());
ASSERT(table->containingBlock());
Cluster* cluster = currentCluster();
if (cluster->m_root != table)
return;
// Pre-inflate cells that have enough text so that their inflated preferred widths will be used
// for column sizing.
for (LayoutObject* section = table->firstChild(); section; section = section->nextSibling()) {
if (!section->isTableSection())
continue;
for (LayoutTableRow* row = toLayoutTableSection(section)->firstRow(); row; row = row->nextRow()) {
for (LayoutTableCell* cell = row->firstCell(); cell; cell = cell->nextCell()) {
if (!cell->needsLayout())
continue;
beginLayout(cell);
inflate(cell, DescendToInnerBlocks);
endLayout(cell);
}
}
}
}
void TextAutosizer::endLayout(LayoutBlock* block)
{
ASSERT(shouldHandleLayout());
if (block == m_firstBlockToBeginLayout) {
m_firstBlockToBeginLayout = nullptr;
m_clusterStack.clear();
m_superclusters.clear();
m_stylesRetainedDuringLayout.clear();
#if ENABLE(ASSERT)
m_blocksThatHaveBegunLayout.clear();
#endif
// Tables can create two layout scopes for the same block so the isEmpty
// check below is needed to guard against endLayout being called twice.
} else if (!m_clusterStack.isEmpty() && currentCluster()->m_root == block) {
m_clusterStack.removeLast();
}
}
float TextAutosizer::inflate(LayoutObject* parent, InflateBehavior behavior, float multiplier)
{
Cluster* cluster = currentCluster();
bool hasTextChild = false;
LayoutObject* child = nullptr;
if (parent->isLayoutBlock() && (parent->childrenInline() || behavior == DescendToInnerBlocks))
child = toLayoutBlock(parent)->firstChild();
else if (parent->isLayoutInline())
child = toLayoutInline(parent)->firstChild();
while (child) {
if (child->isText()) {
hasTextChild = true;
// We only calculate this multiplier on-demand to ensure the parent block of this text
// has entered layout.
if (!multiplier)
multiplier = cluster->m_flags & SUPPRESSING ? 1.0f : clusterMultiplier(cluster);
applyMultiplier(child, multiplier);
// FIXME: Investigate why MarkOnlyThis is sufficient.
if (parent->isLayoutInline())
child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
} else if (child->isLayoutInline()) {
multiplier = inflate(child, behavior, multiplier);
} else if (child->isLayoutBlock() && behavior == DescendToInnerBlocks
&& !classifyBlock(child, INDEPENDENT | EXPLICIT_WIDTH | SUPPRESSING)) {
multiplier = inflate(child, behavior, multiplier);
}
child = child->nextSibling();
}
if (hasTextChild) {
applyMultiplier(parent, multiplier); // Parent handles line spacing.
} else if (!parent->isListItem()) {
// For consistency, a block with no immediate text child should always have a
// multiplier of 1.
applyMultiplier(parent, 1);
}
if (parent->isListItem()) {
float multiplier = clusterMultiplier(cluster);
applyMultiplier(parent, multiplier);
// The list item has to be treated special because we can have a tree such that you have
// a list item for a form inside it. The list marker then ends up inside the form and when
// we try to get the clusterMultiplier we have the wrong cluster root to work from and get
// the wrong value.
LayoutListItem* item = toLayoutListItem(parent);
if (LayoutListMarker* marker = item->marker()) {
applyMultiplier(marker, multiplier);
marker->setPreferredLogicalWidthsDirty(MarkOnlyThis);
}
}
return multiplier;
}
bool TextAutosizer::shouldHandleLayout() const
{
return m_pageInfo.m_settingEnabled && m_pageInfo.m_pageNeedsAutosizing && !m_updatePageInfoDeferred;
}
bool TextAutosizer::pageNeedsAutosizing() const
{
return m_pageInfo.m_pageNeedsAutosizing;
}
void TextAutosizer::updatePageInfoInAllFrames()
{
ASSERT(!m_document->frame() || m_document->frame()->isMainFrame());
for (Frame* frame = m_document->frame(); frame; frame = frame->tree().traverseNext()) {
if (!frame->isLocalFrame())
continue;
Document* document = toLocalFrame(frame)->document();
// If document is being detached, skip updatePageInfo.
if (!document || !document->isActive())
continue;
if (TextAutosizer* textAutosizer = document->textAutosizer())
textAutosizer->updatePageInfo();
}
}
void TextAutosizer::updatePageInfo()
{
if (m_updatePageInfoDeferred || !m_document->page() || !m_document->settings())
return;
PageInfo previousPageInfo(m_pageInfo);
m_pageInfo.m_settingEnabled = m_document->settings()->textAutosizingEnabled();
if (!m_pageInfo.m_settingEnabled || m_document->printing()) {
m_pageInfo.m_pageNeedsAutosizing = false;
} else {
LayoutView* layoutView = m_document->layoutView();
bool horizontalWritingMode = isHorizontalWritingMode(layoutView->style()->writingMode());
// FIXME: With out-of-process iframes, the top frame can be remote and
// doesn't have sizing information. Just return if this is the case.
Frame* frame = m_document->frame()->tree().top();
if (frame->isRemoteFrame())
return;
LocalFrame* mainFrame = toLocalFrame(frame);
IntSize frameSize = m_document->settings()->textAutosizingWindowSizeOverride();
if (frameSize.isEmpty())
frameSize = windowSize();
m_pageInfo.m_frameWidth = horizontalWritingMode ? frameSize.width() : frameSize.height();
IntSize layoutSize = mainFrame->view()->layoutSize();
m_pageInfo.m_layoutWidth = horizontalWritingMode ? layoutSize.width() : layoutSize.height();
// Compute the base font scale multiplier based on device and accessibility settings.
m_pageInfo.m_baseMultiplier = m_document->settings()->accessibilityFontScaleFactor();
// If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
const ViewportDescription& viewportDescription = mainFrame->document()->viewportDescription();
if (!viewportDescription.isSpecifiedByAuthor()) {
float deviceScaleAdjustment = m_document->settings()->deviceScaleAdjustment();
m_pageInfo.m_baseMultiplier *= deviceScaleAdjustment;
}
m_pageInfo.m_pageNeedsAutosizing = !!m_pageInfo.m_frameWidth
&& (m_pageInfo.m_baseMultiplier * (static_cast<float>(m_pageInfo.m_layoutWidth) / m_pageInfo.m_frameWidth) > 1.0f);
}
if (m_pageInfo.m_pageNeedsAutosizing) {
// If page info has changed, multipliers may have changed. Force a layout to recompute them.
if (m_pageInfo.m_frameWidth != previousPageInfo.m_frameWidth
|| m_pageInfo.m_layoutWidth != previousPageInfo.m_layoutWidth
|| m_pageInfo.m_baseMultiplier != previousPageInfo.m_baseMultiplier
|| m_pageInfo.m_settingEnabled != previousPageInfo.m_settingEnabled)
setAllTextNeedsLayout();
} else if (previousPageInfo.m_hasAutosized) {
// If we are no longer autosizing the page, we won't do anything during the next layout.
// Set all the multipliers back to 1 now.
resetMultipliers();
m_pageInfo.m_hasAutosized = false;
}
}
IntSize TextAutosizer::windowSize() const
{
Page * page = m_document->page();
ASSERT(page);
return page->frameHost().visualViewport().size();
}
void TextAutosizer::resetMultipliers()
{
LayoutObject* layoutObject = m_document->layoutView();
while (layoutObject) {
if (const ComputedStyle* style = layoutObject->style()) {
if (style->textAutosizingMultiplier() != 1)
applyMultiplier(layoutObject, 1, LayoutNeeded);
}
layoutObject = layoutObject->nextInPreOrder();
}
}
void TextAutosizer::setAllTextNeedsLayout()
{
LayoutObject* layoutObject = m_document->layoutView();
while (layoutObject) {
if (layoutObject->isText())
layoutObject->setNeedsLayoutAndFullPaintInvalidation(LayoutInvalidationReason::TextAutosizing);
layoutObject = layoutObject->nextInPreOrder();
}
}
TextAutosizer::BlockFlags TextAutosizer::classifyBlock(const LayoutObject* layoutObject, BlockFlags mask) const
{
if (!layoutObject->isLayoutBlock())
return 0;
const LayoutBlock* block = toLayoutBlock(layoutObject);
BlockFlags flags = 0;
if (isPotentialClusterRoot(block)) {
if (mask & POTENTIAL_ROOT)
flags |= POTENTIAL_ROOT;
if ((mask & INDEPENDENT) && (isIndependentDescendant(block) || block->isTable()))
flags |= INDEPENDENT;
if ((mask & EXPLICIT_WIDTH) && hasExplicitWidth(block))
flags |= EXPLICIT_WIDTH;
if ((mask & SUPPRESSING) && blockSuppressesAutosizing(block))
flags |= SUPPRESSING;
}
return flags;
}
bool TextAutosizer::clusterWouldHaveEnoughTextToAutosize(const LayoutBlock* root, const LayoutBlock* widthProvider)
{
Cluster hypotheticalCluster(root, classifyBlock(root), nullptr);
return clusterHasEnoughTextToAutosize(&hypotheticalCluster, widthProvider);
}
bool TextAutosizer::clusterHasEnoughTextToAutosize(Cluster* cluster, const LayoutBlock* widthProvider)
{
if (cluster->m_hasEnoughTextToAutosize != UnknownAmountOfText)
return cluster->m_hasEnoughTextToAutosize == HasEnoughText;
const LayoutBlock* root = cluster->m_root;
if (!widthProvider)
widthProvider = clusterWidthProvider(root);
// TextAreas and user-modifiable areas get a free pass to autosize regardless of text content.
if (root->isTextArea() || (root->style() && root->style()->userModify() != READ_ONLY)) {
cluster->m_hasEnoughTextToAutosize = HasEnoughText;
return true;
}
if (cluster->m_flags & SUPPRESSING) {
cluster->m_hasEnoughTextToAutosize = NotEnoughText;
return false;
}
// 4 lines of text is considered enough to autosize.
float minimumTextLengthToAutosize = widthFromBlock(widthProvider) * 4;
float length = 0;
LayoutObject* descendant = root->firstChild();
while (descendant) {
if (descendant->isLayoutBlock()) {
if (classifyBlock(descendant, INDEPENDENT | SUPPRESSING)) {
descendant = descendant->nextInPreOrderAfterChildren(root);
continue;
}
} else if (descendant->isText()) {
// Note: Using text().stripWhiteSpace().length() instead of resolvedTextLength() because
// the lineboxes will not be built until layout. These values can be different.
// Note: This is an approximation assuming each character is 1em wide.
length += toLayoutText(descendant)->text().stripWhiteSpace().length() * descendant->style()->specifiedFontSize();
if (length >= minimumTextLengthToAutosize) {
cluster->m_hasEnoughTextToAutosize = HasEnoughText;
return true;
}
}
descendant = descendant->nextInPreOrder(root);
}
cluster->m_hasEnoughTextToAutosize = NotEnoughText;
return false;
}
TextAutosizer::Fingerprint TextAutosizer::getFingerprint(const LayoutObject* layoutObject)
{
Fingerprint result = m_fingerprintMapper.get(layoutObject);
if (!result) {
result = computeFingerprint(layoutObject);
m_fingerprintMapper.add(layoutObject, result);
}
return result;
}
TextAutosizer::Fingerprint TextAutosizer::computeFingerprint(const LayoutObject* layoutObject)
{
Node* node = layoutObject->generatingNode();
if (!node || !node->isElementNode())
return 0;
FingerprintSourceData data;
if (const LayoutObject* parent = parentElementLayoutObject(layoutObject))
data.m_parentHash = getFingerprint(parent);
data.m_qualifiedNameHash = QualifiedNameHash::hash(toElement(node)->tagQName());
if (const ComputedStyle* style = layoutObject->style()) {
data.m_packedStyleProperties = style->direction();
data.m_packedStyleProperties |= (style->position() << 1);
data.m_packedStyleProperties |= (style->floating() << 4);
data.m_packedStyleProperties |= (style->display() << 6);
data.m_packedStyleProperties |= (style->width().type() << 11);
// packedStyleProperties effectively using 15 bits now.
// consider for adding: writing mode, padding.
data.m_width = style->width().getFloatValue();
}
// Use nodeIndex as a rough approximation of column number
// (it's too early to call LayoutTableCell::col).
// FIXME: account for colspan
if (layoutObject->isTableCell())
data.m_column = layoutObject->node()->nodeIndex();
return StringHasher::computeHash<UChar>(
static_cast<const UChar*>(static_cast<const void*>(&data)),
sizeof data / sizeof(UChar));
}
TextAutosizer::Cluster* TextAutosizer::maybeCreateCluster(const LayoutBlock* block)
{
BlockFlags flags = classifyBlock(block);
if (!(flags & POTENTIAL_ROOT))
return nullptr;
Cluster* parentCluster = m_clusterStack.isEmpty() ? nullptr : currentCluster();
ASSERT(parentCluster || block->isLayoutView());
// If a non-independent block would not alter the SUPPRESSING flag, it doesn't need to be a cluster.
bool parentSuppresses = parentCluster && (parentCluster->m_flags & SUPPRESSING);
if (!(flags & INDEPENDENT) && !(flags & EXPLICIT_WIDTH) && !!(flags & SUPPRESSING) == parentSuppresses)
return nullptr;
Cluster* cluster = new Cluster(block, flags, parentCluster, getSupercluster(block));
#ifdef AUTOSIZING_DOM_DEBUG_INFO
// Non-SUPPRESSING clusters are annotated in clusterMultiplier.
if (flags & SUPPRESSING)
writeClusterDebugInfo(cluster);
#endif
return cluster;
}
TextAutosizer::Supercluster* TextAutosizer::getSupercluster(const LayoutBlock* block)
{
Fingerprint fingerprint = m_fingerprintMapper.get(block);
if (!fingerprint)
return nullptr;
BlockSet* roots = m_fingerprintMapper.getTentativeClusterRoots(fingerprint);
if (!roots || roots->size() < 2 || !roots->contains(block))
return nullptr;
SuperclusterMap::AddResult addResult = m_superclusters.add(fingerprint, PassOwnPtr<Supercluster>());
if (!addResult.isNewEntry)
return addResult.storedValue->value.get();
Supercluster* supercluster = new Supercluster(roots);
addResult.storedValue->value = adoptPtr(supercluster);
return supercluster;
}
float TextAutosizer::clusterMultiplier(Cluster* cluster)
{
if (cluster->m_multiplier)
return cluster->m_multiplier;
// FIXME: why does isWiderOrNarrowerDescendant crash on independent clusters?
if (!(cluster->m_flags & INDEPENDENT) && isWiderOrNarrowerDescendant(cluster))
cluster->m_flags |= WIDER_OR_NARROWER;
if (cluster->m_flags & (INDEPENDENT | WIDER_OR_NARROWER)) {
if (cluster->m_supercluster)
cluster->m_multiplier = superclusterMultiplier(cluster);
else if (clusterHasEnoughTextToAutosize(cluster))
cluster->m_multiplier = multiplierFromBlock(clusterWidthProvider(cluster->m_root));
else
cluster->m_multiplier = 1.0f;
} else {
cluster->m_multiplier = cluster->m_parent ? clusterMultiplier(cluster->m_parent) : 1.0f;
}
#ifdef AUTOSIZING_DOM_DEBUG_INFO
writeClusterDebugInfo(cluster);
#endif
ASSERT(cluster->m_multiplier);
return cluster->m_multiplier;
}
bool TextAutosizer::superclusterHasEnoughTextToAutosize(Supercluster* supercluster, const LayoutBlock* widthProvider)
{
if (supercluster->m_hasEnoughTextToAutosize != UnknownAmountOfText)
return supercluster->m_hasEnoughTextToAutosize == HasEnoughText;
for (auto* root : *supercluster->m_roots) {
if (clusterWouldHaveEnoughTextToAutosize(root, widthProvider)) {
supercluster->m_hasEnoughTextToAutosize = HasEnoughText;
return true;
}
}
supercluster->m_hasEnoughTextToAutosize = NotEnoughText;
return false;
}
float TextAutosizer::superclusterMultiplier(Cluster* cluster)
{
Supercluster* supercluster = cluster->m_supercluster;
if (!supercluster->m_multiplier) {
const LayoutBlock* widthProvider = maxClusterWidthProvider(cluster->m_supercluster, cluster->m_root);
supercluster->m_multiplier = superclusterHasEnoughTextToAutosize(supercluster, widthProvider)
? multiplierFromBlock(widthProvider) : 1.0f;
}
ASSERT(supercluster->m_multiplier);
return supercluster->m_multiplier;
}
const LayoutBlock* TextAutosizer::clusterWidthProvider(const LayoutBlock* root) const
{
if (root->isTable() || root->isTableCell())
return root;
return deepestBlockContainingAllText(root);
}
const LayoutBlock* TextAutosizer::maxClusterWidthProvider(const Supercluster* supercluster, const LayoutBlock* currentRoot) const
{
const LayoutBlock* result = clusterWidthProvider(currentRoot);
float maxWidth = widthFromBlock(result);
const BlockSet* roots = supercluster->m_roots;
for (const auto* root : *roots) {
const LayoutBlock* widthProvider = clusterWidthProvider(root);
if (widthProvider->needsLayout())
continue;
float width = widthFromBlock(widthProvider);
if (width > maxWidth) {
maxWidth = width;
result = widthProvider;
}
}
RELEASE_ASSERT(result);
return result;
}
float TextAutosizer::widthFromBlock(const LayoutBlock* block) const
{
RELEASE_ASSERT(block);
RELEASE_ASSERT(block->style());
if (!(block->isTable() || block->isTableCell() || block->isListItem()))
return block->contentLogicalWidth().toFloat();
if (!block->containingBlock())
return 0;
// Tables may be inflated before computing their preferred widths. Try several methods to
// obtain a width, and fall back on a containing block's width.
for (; block; block = block->containingBlock()) {
float width;
Length specifiedWidth = block->isTableCell()
? toLayoutTableCell(block)->styleOrColLogicalWidth() : block->style()->logicalWidth();
if (specifiedWidth.isFixed()) {
if ((width = specifiedWidth.value()) > 0)
return width;
}
if (specifiedWidth.hasPercent()) {
if (float containerWidth = block->containingBlock()->contentLogicalWidth().toFloat()) {
if ((width = floatValueForLength(specifiedWidth, containerWidth)) > 0)
return width;
}
}
if ((width = block->contentLogicalWidth().toFloat()) > 0)
return width;
}
return 0;
}
float TextAutosizer::multiplierFromBlock(const LayoutBlock* block)
{
// If block->needsLayout() is false, it does not need to be in m_blocksThatHaveBegunLayout.
// This can happen during layout of a positioned object if the cluster's DBCAT is deeper
// than the positioned object's containing block, and wasn't marked as needing layout.
ASSERT(m_blocksThatHaveBegunLayout.contains(block) || !block->needsLayout());
// Block width, in CSS pixels.
float blockWidth = widthFromBlock(block);
float multiplier = m_pageInfo.m_frameWidth ? std::min(blockWidth, static_cast<float>(m_pageInfo.m_layoutWidth)) / m_pageInfo.m_frameWidth : 1.0f;
return std::max(m_pageInfo.m_baseMultiplier * multiplier, 1.0f);
}
const LayoutBlock* TextAutosizer::deepestBlockContainingAllText(Cluster* cluster)
{
if (!cluster->m_deepestBlockContainingAllText)
cluster->m_deepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_root);
return cluster->m_deepestBlockContainingAllText;
}
// FIXME: Refactor this to look more like TextAutosizer::deepestCommonAncestor.
const LayoutBlock* TextAutosizer::deepestBlockContainingAllText(const LayoutBlock* root) const
{
size_t firstDepth = 0;
const LayoutObject* firstTextLeaf = findTextLeaf(root, firstDepth, First);
if (!firstTextLeaf)
return root;
size_t lastDepth = 0;
const LayoutObject* lastTextLeaf = findTextLeaf(root, lastDepth, Last);
ASSERT(lastTextLeaf);
// Equalize the depths if necessary. Only one of the while loops below will get executed.
const LayoutObject* firstNode = firstTextLeaf;
const LayoutObject* lastNode = lastTextLeaf;
while (firstDepth > lastDepth) {
firstNode = firstNode->parent();
--firstDepth;
}
while (lastDepth > firstDepth) {
lastNode = lastNode->parent();
--lastDepth;
}
// Go up from both nodes until the parent is the same. Both pointers will point to the LCA then.
while (firstNode != lastNode) {
firstNode = firstNode->parent();
lastNode = lastNode->parent();
}
if (firstNode->isLayoutBlock())
return toLayoutBlock(firstNode);
// containingBlock() should never leave the cluster, since it only skips ancestors when finding
// the container of position:absolute/fixed blocks, and those cannot exist between a cluster and
// its text node's lowest common ancestor as isAutosizingCluster would have made them into their
// own independent cluster.
const LayoutBlock* containingBlock = firstNode->containingBlock();
if (!containingBlock)
return root;
ASSERT(containingBlock->isDescendantOf(root));
return containingBlock;
}
const LayoutObject* TextAutosizer::findTextLeaf(const LayoutObject* parent, size_t& depth, TextLeafSearch firstOrLast) const
{
// List items are treated as text due to the marker.
if (parent->isListItem())
return parent;
if (parent->isText())
return parent;
++depth;
const LayoutObject* child = (firstOrLast == First) ? parent->slowFirstChild() : parent->slowLastChild();
while (child) {
// Note: At this point clusters may not have been created for these blocks so we cannot rely
// on m_clusters. Instead, we use a best-guess about whether the block will become a cluster.
if (!classifyBlock(child, INDEPENDENT)) {
if (const LayoutObject* leaf = findTextLeaf(child, depth, firstOrLast))
return leaf;
}
child = (firstOrLast == First) ? child->nextSibling() : child->previousSibling();
}
--depth;
return nullptr;
}
void TextAutosizer::applyMultiplier(LayoutObject* layoutObject, float multiplier, RelayoutBehavior relayoutBehavior)
{
ASSERT(layoutObject);
ComputedStyle& currentStyle = layoutObject->mutableStyleRef();
if (currentStyle.textAutosizingMultiplier() == multiplier)
return;
// We need to clone the layoutObject style to avoid breaking style sharing.
RefPtr<ComputedStyle> style = ComputedStyle::clone(currentStyle);
style->setTextAutosizingMultiplier(multiplier);
style->setUnique();
switch (relayoutBehavior) {
case AlreadyInLayout:
// Don't free currentStyle until the end of the layout pass. This allows other parts of the system
// to safely hold raw ComputedStyle* pointers during layout, e.g. BreakingContext::m_currentStyle.
m_stylesRetainedDuringLayout.append(¤tStyle);
layoutObject->setStyleInternal(style.release());
layoutObject->setNeedsLayoutAndFullPaintInvalidation(LayoutInvalidationReason::TextAutosizing);
break;
case LayoutNeeded:
layoutObject->setStyle(style.release());
break;
}
if (multiplier != 1)
m_pageInfo.m_hasAutosized = true;
}
bool TextAutosizer::isWiderOrNarrowerDescendant(Cluster* cluster)
{
// FIXME: Why do we return true when hasExplicitWidth returns false??
if (!cluster->m_parent || !hasExplicitWidth(cluster->m_root))
return true;
const LayoutBlock* parentDeepestBlockContainingAllText = deepestBlockContainingAllText(cluster->m_parent);
ASSERT(m_blocksThatHaveBegunLayout.contains(cluster->m_root));
ASSERT(m_blocksThatHaveBegunLayout.contains(parentDeepestBlockContainingAllText));
float contentWidth = cluster->m_root->contentLogicalWidth().toFloat();
float clusterTextWidth = parentDeepestBlockContainingAllText->contentLogicalWidth().toFloat();
// Clusters with a root that is wider than the deepestBlockContainingAllText of their parent
// autosize independently of their parent.
if (contentWidth > clusterTextWidth)
return true;
// Clusters with a root that is significantly narrower than the deepestBlockContainingAllText of
// their parent autosize independently of their parent.
static float narrowWidthDifference = 200;
if (clusterTextWidth - contentWidth > narrowWidthDifference)
return true;
return false;
}
TextAutosizer::Cluster* TextAutosizer::currentCluster() const
{
ASSERT_WITH_SECURITY_IMPLICATION(!m_clusterStack.isEmpty());
return m_clusterStack.last().get();
}
#if ENABLE(ASSERT)
void TextAutosizer::FingerprintMapper::assertMapsAreConsistent()
{
// For each fingerprint -> block mapping in m_blocksForFingerprint we should have an associated
// map from block -> fingerprint in m_fingerprints.
ReverseFingerprintMap::iterator end = m_blocksForFingerprint.end();
for (ReverseFingerprintMap::iterator fingerprintIt = m_blocksForFingerprint.begin(); fingerprintIt != end; ++fingerprintIt) {
Fingerprint fingerprint = fingerprintIt->key;
BlockSet* blocks = fingerprintIt->value.get();
for (BlockSet::iterator blockIt = blocks->begin(); blockIt != blocks->end(); ++blockIt) {
const LayoutBlock* block = (*blockIt);
ASSERT(m_fingerprints.get(block) == fingerprint);
}
}
}
#endif
void TextAutosizer::FingerprintMapper::add(const LayoutObject* layoutObject, Fingerprint fingerprint)
{
remove(layoutObject);
m_fingerprints.set(layoutObject, fingerprint);
#if ENABLE(ASSERT)
assertMapsAreConsistent();
#endif
}
void TextAutosizer::FingerprintMapper::addTentativeClusterRoot(const LayoutBlock* block, Fingerprint fingerprint)
{
add(block, fingerprint);
ReverseFingerprintMap::AddResult addResult = m_blocksForFingerprint.add(fingerprint, PassOwnPtr<BlockSet>());
if (addResult.isNewEntry)
addResult.storedValue->value = adoptPtr(new BlockSet);
addResult.storedValue->value->add(block);
#if ENABLE(ASSERT)
assertMapsAreConsistent();
#endif
}
bool TextAutosizer::FingerprintMapper::remove(const LayoutObject* layoutObject)
{
Fingerprint fingerprint = m_fingerprints.take(layoutObject);
if (!fingerprint || !layoutObject->isLayoutBlock())
return false;
ReverseFingerprintMap::iterator blocksIter = m_blocksForFingerprint.find(fingerprint);
if (blocksIter == m_blocksForFingerprint.end())
return false;
BlockSet& blocks = *blocksIter->value;
blocks.remove(toLayoutBlock(layoutObject));
if (blocks.isEmpty())
m_blocksForFingerprint.remove(blocksIter);
#if ENABLE(ASSERT)
assertMapsAreConsistent();
#endif
return true;
}
TextAutosizer::Fingerprint TextAutosizer::FingerprintMapper::get(const LayoutObject* layoutObject)
{
return m_fingerprints.get(layoutObject);
}
TextAutosizer::BlockSet* TextAutosizer::FingerprintMapper::getTentativeClusterRoots(Fingerprint fingerprint)
{
return m_blocksForFingerprint.get(fingerprint);
}
TextAutosizer::LayoutScope::LayoutScope(LayoutBlock* block)
: m_textAutosizer(block->document().textAutosizer())
, m_block(block)
{
if (!m_textAutosizer)
return;
if (m_textAutosizer->shouldHandleLayout())
m_textAutosizer->beginLayout(m_block);
else
m_textAutosizer = nullptr;
}
TextAutosizer::LayoutScope::~LayoutScope()
{
if (m_textAutosizer)
m_textAutosizer->endLayout(m_block);
}
TextAutosizer::TableLayoutScope::TableLayoutScope(LayoutTable* table)
: LayoutScope(table)
{
if (m_textAutosizer) {
ASSERT(m_textAutosizer->shouldHandleLayout());
m_textAutosizer->inflateAutoTable(table);
}
}
TextAutosizer::DeferUpdatePageInfo::DeferUpdatePageInfo(Page* page)
: m_mainFrame(page->deprecatedLocalMainFrame())
{
if (TextAutosizer* textAutosizer = m_mainFrame->document()->textAutosizer()) {
ASSERT(!textAutosizer->m_updatePageInfoDeferred);
textAutosizer->m_updatePageInfoDeferred = true;
}
}
TextAutosizer::DeferUpdatePageInfo::~DeferUpdatePageInfo()
{
if (TextAutosizer* textAutosizer = m_mainFrame->document()->textAutosizer()) {
ASSERT(textAutosizer->m_updatePageInfoDeferred);
textAutosizer->m_updatePageInfoDeferred = false;
textAutosizer->updatePageInfoInAllFrames();
}
}
float TextAutosizer::computeAutosizedFontSize(float specifiedSize, float multiplier)
{
// Somewhat arbitrary "pleasant" font size.
const float pleasantSize = 16;
// Multiply fonts that the page author has specified to be larger than
// pleasantSize by less and less, until huge fonts are not increased at all.
// For specifiedSize between 0 and pleasantSize we directly apply the
// multiplier; hence for specifiedSize == pleasantSize, computedSize will be
// multiplier * pleasantSize. For greater specifiedSizes we want to
// gradually fade out the multiplier, so for every 1px increase in
// specifiedSize beyond pleasantSize we will only increase computedSize
// by gradientAfterPleasantSize px until we meet the
// computedSize = specifiedSize line, after which we stay on that line (so
// then every 1px increase in specifiedSize increases computedSize by 1px).
const float gradientAfterPleasantSize = 0.5;
float computedSize;
if (specifiedSize <= pleasantSize) {
computedSize = multiplier * specifiedSize;
} else {
computedSize = multiplier * pleasantSize + gradientAfterPleasantSize * (specifiedSize - pleasantSize);
if (computedSize < specifiedSize)
computedSize = specifiedSize;
}
return computedSize;
}
DEFINE_TRACE(TextAutosizer)
{
visitor->trace(m_document);
}
} // namespace blink
| Bysmyyr/chromium-crosswalk | third_party/WebKit/Source/core/layout/TextAutosizer.cpp | C++ | bsd-3-clause | 44,757 |
d = {}
for i in range(100000):
d[i] = i
JS_CODE = '''
var d = {};
for (var i = 0; i < 100000; i++) {
d[i] = i;
}
'''
| kikocorreoso/brython | www/speed/benchmarks/add_dict.py | Python | bsd-3-clause | 124 |
<?php
/**
* PHPFrame/Mapper/PersistentObjectCollection.php
*
* PHP version 5
*
* @category PHPFrame
* @package Mapper
* @author Lupo Montero <lupo@e-noise.com>
* @copyright 2010 The PHPFrame Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link http://github.com/PHPFrame/PHPFrame
*/
/**
* Persistent Object Collection Class
*
* @category PHPFrame
* @package Mapper
* @author Lupo Montero <lupo@e-noise.com>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link http://github.com/PHPFrame/PHPFrame
* @since 1.0
*/
class PHPFrame_PersistentObjectCollection extends PHPFrame_Collection
{
/**
* A domain factory object used to create objects in collection
*
* @var PHPFrame_PersistentObjectFactory
*/
private $_obj_fact;
/**
* Raw array used to generate persistent objects
*
* @var array
*/
private $_raw;
/**
* Limit of entries per page
*
* @var int
*/
private $_limit;
/**
* Position at which the current page starts
*
* @var int
*/
private $_limitstart;
/**
* The total number of elements in the collection (this will normally be a
* subset determined by pagination parameters)
*
* @var int
*/
private $_total_subset;
/**
* The total number of elements in the storage media
*
* @var int
*/
private $_total_superset;
/**
* Internal array pointer
*
* @var int
*/
private $_pointer = 0;
/**
* Storage array used to manage the collection's objects
*
* @var array;
*/
private $_objects = array();
/**
* Constructor
*
* @param array $raw [Optional] Array
* containig the raw
* collection data.
* @param PHPFrame_PersistentObjectFactory $obj_factory [Optional] Instance
* of persistence object
* factory.
* @param int $total [Optional] The total
* number of records in
* the superset.
* @param int $limit [Optional] The number
* of records the current
* subset is lmited to.
* Default value is '-1',
* which means there is
* no limit, so we will
* get all the records.
* @param int $limitstart [Optional] The entry
* number from which to
* start the subset.
* If ommited default
* value '0' will be
* used, meaning that
* we start from the
* first page of results.
*
* @return void
* @since 1.0
*/
public function __construct(
array $raw=null,
PHPFrame_PersistentObjectFactory $obj_factory=null,
$total=null,
$limit=-1,
$limitstart=0
) {
if (!is_null($raw) && !is_null($obj_factory)) {
// If the raw array is only one level of depth we assume it is
// only one element and we wrap it in an array to make is a
// collection of a single entry
$array_obj = new PHPFrame_Array($raw);
if ($array_obj->depth() == 1) {
$raw = array($raw);
}
$this->_raw = $raw;
$this->_total_subset = count($raw);
}
$this->_obj_fact = $obj_factory;
$this->_limit = (int) $limit;
$this->_limitstart = (int) $limitstart;
if (!is_null($total)) {
$this->_total_superset = (int) $total;
} else {
$this->_total_superset = $this->_total_subset;
}
}
/**
* Get persistent object at given key
*
* @param string $key The key of the element to get.
*
* @return PHPFrame_PersistentObject
* @since 1.0
*/
public function getElement($key)
{
if ($key >= $this->count() || $key < 0) {
return null;
}
if (isset($this->_objects[$key])) {
return $this->_objects[$key];
}
if (isset($this->_raw[$key])) {
$this->_objects[$key] = $this->_obj_fact->createObject(
$this->_raw[$key]
);
return $this->_objects[$key];
}
}
/**
* Add persistent object to the collection
*
* @param PHPFrame_PersistentObject $obj An instance of a persistent object
* to add to the collection.
*
* @return void
* @since 1.0
*/
public function addElement(PHPFrame_PersistentObject $obj)
{
if (in_array($obj, $this->_objects)) {
return;
}
$this->_objects[$this->_total_subset++] = $obj;
}
/**
* Remove persistent object from the collection
*
* @param PHPFrame_PersistentObject $obj An instance of a persistent object
* to remove from the collection.
*
* @return void
* @since 1.0
*/
public function removeElement(PHPFrame_PersistentObject $obj)
{
if (in_array($obj, $this->_objects)) {
$keys = array_keys($this->_objects, $obj);
unset($this->_objects[$keys[0]]);
}
$updated_raw = array();
foreach ($this->_raw as $raw_item) {
if (isset($raw_item["id"]) && $raw_item["id"] == $obj->id()) {
continue;
}
$updated_raw[] = $raw_item;
}
$this->_raw = $updated_raw;
$this->_total_subset--;
$this->_total_superset--;
}
/**
* Get limit
*
* @return int
* @see PHPFrame/Base/PHPFrame_Collection#getLimit()
* @since 1.0
*/
public function getLimit()
{
return $this->_limit;
}
/**
* Get limitstart.
*
* @return int
* @see PHPFrame/Base/PHPFrame_Collection#getLimitstart()
* @since 1.0
*/
public function getLimitstart()
{
return $this->_limitstart;
}
/**
* Get total records in superset.
*
* @return int
* @see PHPFrame/Base/PHPFrame_Collection#getTotal()
* @since 1.0
*/
public function getTotal()
{
return $this->_total_superset;
}
/**
* Implementation of Iterator::current()
*
* @return PHPFrame_PersistentObject
* @since 1.0
*/
public function current()
{
return $this->getElement($this->key());
}
/**
* Implementation of Iterator::next()
*
* @return void
* @since 1.0
*/
public function next()
{
$this->_pointer++;
}
/**
* Implementation of Iterator::key()
*
* @return int
* @since 1.0
*/
public function key()
{
return $this->_pointer;
}
/**
* Implementation of Iterator::valid()
*
* @return bool
* @since 1.0
*/
public function valid()
{
return ($this->key() < $this->count());
}
/**
* Implementation of Iterator::rewind()
*
* @return void
* @since 1.0
*/
public function rewind()
{
$this->_pointer = 0;
}
/**
* Implementation of the Countable interface. It returns the number of
* objects in the current subset.
*
* @return int
* @since 1.0
*/
public function count()
{
return $this->_total_subset;
}
}
| PHPFrame/PHPFrame | src/PHPFrame/Mapper/PersistentObjectCollection.php | PHP | bsd-3-clause | 8,561 |
# -*- encoding : utf-8 -*-
ActiveAdmin.register Version, :sort_order => 'id_desc' do
actions :index, :show
menu :label => "Tablica zmian", :priority => 1
index do
column 'Data', :sortable => :created_at do |e|
l e.created_at, :format => :short
end
column 'Autor' do |e|
if e.whodunnit
user = User.where(:id => e.whodunnit).first
if user
link_to user.email, admin_user_path(user.id)
else
"##{e.whodunnit}"
end
else
"admin"
end
end
column 'Zródło' do |e|
e.source
end
column 'Akcja' do |e|
t("version.event." + e.event)
end
column 'Zasób' do |e|
name = t("version.item_type." + e.item_type)
object = e.preview
next unless object
case e.item_type
when "Relic"
link_to name, admin_relic_path(e.item_id), :title => object.identification
when "Document"
link_to name, admin_document_path(e.item_id), :title => object.name
when "Photo"
link_to name, admin_photo_path(e.item_id), :title => "zabytku #{object.relic.try(:identification)}"
when "Entry"
link_to name, admin_entry_path(e.item_id), :title => object.title
when "Event"
link_to name, admin_event_path(e.item_id), :title => object.name
when "Link"
link_to name, admin_link_path(e.item_id), :title => object.name
end
end
column 'Szybki podgląd' do |e|
object = e.preview
next unless object
ignores = ["commune_id", "voivodeship_id", "district_id"]
dl :style => "width: 300px;" do
if e.event == 'update'
e.changeset.each do |key, (before, after)|
next if ignores.include?(key)
next if before.blank? && after.blank?
dt t("activerecord.attributes.#{e.item_type.downcase}.#{key}")
if after.class == String
if key == 'file' and e.item_type == 'Document'
dd do
store_dir = "/system/uploads/document/file/%d/%s"
span link_to("dokument", store_dir % [e.item_id, before])
span "=>"
span link_to("dokument", store_dir % [e.item_id, after])
end
elsif key == 'file' and e.item_type == 'Photo'
dd do
store_dir = "/system/uploads/photo/file/%d/midi_%s"
span image_tag(store_dir % [e.item_id, before])
span "=>"
span image_tag(store_dir % [e.item_id, after])
end
else
dd sanitize(HTMLDiff::DiffBuilder.new(before || "", after || "").build)
end
elsif after.class == Array
dd do
((after || []) - (before || [])).each do |e|
ins e
span " "
end
((before || []) - (after || [])).each do |e|
del e
span " "
end
end
else
dd "#{before || "pusty"} => #{after || "~"}"
end
end
elsif e.event == 'create' || e.event == 'destroy'
if e.item_type == "Photo"
para do
image_tag object.file.midi.url
end
elsif e.item_type == "Document"
para do
link_to "pobierz dokument #{object.file.identifier}", object.file.url
end
elsif e.item_type == "Event"
dl do
dt "Nazwa"
dd object.name
dt "Data"
dd object.date
end
elsif e.item_type == "Link"
dl do
dt "Nazwa"
dd object.name
dt "URL"
dd object.url
end
elsif e.item_type == "Entry"
dl do
dt "Tytuł"
dd object.title
dt "Treść"
dd sanitize object.body
end
end
end
e.event == "update" ? "brak poważnych zmian" : ""
end
end
column do |e|
para do
link_to("Cofnij", revert_admin_version_path(e), :method => :put, :'data-confirm' => 'Na pewno?')
end
end
default_actions
end
member_action :revert, :method => :put do
@version = Version.find(params[:id])
@object = @version.reify
if @version.event == 'create'
Kernel.const_get(@version.item_type).find(@version.item_id).destroy
redirect_to admin_versions_path, :notice => "Objekt został przywrócony do wersji przed zmianami."
else
if @object.save
redirect_to admin_versions_path, :notice => "Objekt został przywrócony do wersji przed zmianami."
else
flash[:error] = @version.errors.full_messages
redirect_to admin_version_path(@version.id)
end
end
end
action_item :only => :show do
link_to "Przywróć do wersji przed zmianą", revert_admin_version_path(resource), :method => :put, :'data-confirm' => 'Na pewno?'
end
filter :created_at, :label => "Czas zmiany"
filter :whodunnit, :as => :string, :label => "ID użytkownika"
filter :event, :label => "Akcja", :as => :select,
:collection => [["aktualizacja", "update"], ["usunięcie", "destroy"], ["utworzenie", "create"]]
filter :item_type, :label => "Rodzaj", :as => :select,
:collection => [["Zabytek", "Relic"], ["Dokument", "Document"], ["Zdjęcie", "Photo"], ["Wpis", "Entry"], ["Wydarzenie", "Event"], ["Link", "Link"]]
filter :item_id, :as => :numeric, :label => "ID rekordu"
end
| netkodo/otwartezabytki | app/admin/versions.rb | Ruby | bsd-3-clause | 5,707 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int_fgets_multiply_72b.cpp
Label Definition File: CWE190_Integer_Overflow__int.label.xml
Template File: sources-sinks-72b.tmpl.cpp
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Set data to a small, non-zero number (two)
* Sinks: multiply
* GoodSink: Ensure there will not be an overflow before multiplying data by 2
* BadSink : If data is positive, multiply by 2, which can cause an overflow
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
using namespace std;
namespace CWE190_Integer_Overflow__int_fgets_multiply_72
{
#ifndef OMITBAD
void badSink(vector<int> dataVector)
{
/* copy data out of dataVector */
int data = dataVector[2];
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > INT_MAX, this will overflow */
int result = data * 2;
printIntLine(result);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<int> dataVector)
{
int data = dataVector[2];
if(data > 0) /* ensure we won't have an underflow */
{
/* POTENTIAL FLAW: if (data*2) > INT_MAX, this will overflow */
int result = data * 2;
printIntLine(result);
}
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<int> dataVector)
{
int data = dataVector[2];
if(data > 0) /* ensure we won't have an underflow */
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data < (INT_MAX/2))
{
int result = data * 2;
printIntLine(result);
}
else
{
printLine("data value is too large to perform arithmetic safely.");
}
}
}
#endif /* OMITGOOD */
} /* close namespace */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE190_Integer_Overflow/s03/CWE190_Integer_Overflow__int_fgets_multiply_72b.cpp | C++ | bsd-3-clause | 2,121 |
using System.Collections.Generic;
namespace UnitySpineImporter{
public class SpineSkinSlotAttachments : Dictionary<string, SpineSkinAttachment> {
}
} | abraksil/unity-spine-importer | Assets/UnitySpineImporter/Scripts/Editor/Model/Spine/Data/Skin/SpineSkinSlotAttachments.cs | C# | bsd-3-clause | 156 |
class Void < ActiveRecord::Base
include PaymentGateway
attr_accessor :authorization
attr_accessor :response
def before_create
self.response = gateway.void(authorization)
self.status = response.params['Status']
self.status_detail = response.params['StatusDetail']
end
end
| camelpunch/simply_agile | app/models/void.rb | Ruby | bsd-3-clause | 296 |
#include "ScrollMsg.h"
#include "QVBoxLayout"
#include "QHBoxLayout"
#include "UI/Config/Config.h"
#include <QTextLayout>
#include <QTextBlock>
#include "Common/ScrollBar.h"
CScrollMsg::CScrollMsg(AppListInterface * pList, QWidget *parent) : AppBase(pList, parent)
{
InitLayout();
connect(&m_timer,SIGNAL(timeout()),this,SLOT(timeoutSlots()));
connect(this, SIGNAL(onSpaceCliced()), this, SLOT(onSpaceClicedSlots()));
connect(this,SIGNAL(scrollMsgAbort(int)),this,SLOT(scrollMsgAbortSlots(int)));
}
CScrollMsg::~CScrollMsg()
{
}
void CScrollMsg::InitLayout()
{
m_listWidget=new AppListWidget(ui_app_width*0.1,0,ui_app_width*2.0/3.0,ui_app_height,this);
m_editText = new QTextEdit(this);
char* image[4]={":/images/softbutton_alert.png",
":/images/softbutton_alert_left.png",
":/images/softbutton_alert_right.png",
":/images/softbutton_alert.png"};
char* text[4]={"Soft1","Soft2","Soft3","Soft4"};
for(int i=0;i<4;i++){
m_btnSoft[i]=new CButton(this);
m_btnSoft[i]->initParameter(ui_btn_width,ui_aler_height,image[i],image[i],"",text[i]);
m_btnSoft[i]->setTextStyle("border:0px;font: 42px \"Liberation Serif\";color:rgb(255,255,254)");
}
connect(m_listWidget,SIGNAL(clicked(int)),this,SLOT(onItemClicked(int)));
connect(m_listWidget,SIGNAL(longclicked(int)),this,SLOT(onItemLongClicked(int)));
QPalette pll = m_editText->palette();
pll.setBrush(QPalette::Base,QBrush(QColor(255,0,0,0)));
m_editText->setPalette(pll);
// m_editText->setFixedSize(600,250);
m_editText->setAttribute(Qt::WA_TranslucentBackground, true);
//m_editText->setReadOnly(true); //设置不可编辑
m_editText->setFrameShape(QFrame::NoFrame); //设置无边框
m_editText->setStyleSheet(ScrollBar::cssString()+"border:1px;background-color:white;color:grey;font:36px \"Liberation Serif\";");
m_editText->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
// m_listWidget->hide();
m_listWidget->setFixedSize(ui_app_width*2/3,ui_app_height);
}
void CScrollMsg::UpdateLayout()
{
if(m_listButton.size()<=4){
for(int i=0;i<m_listButton.size();i++){
setButtonStyle(i,m_listButton.at(i).btnId,m_listButton.at(i).btnText,
m_listButton.at(i).isLighted);
}
for(int i=m_listButton.size();i<4;i++){
m_btnSoft[i]->setText("-");
}
}
else{
for(int i=0;i<3;i++){
setButtonStyle(i,m_listButton.at(i).btnId,m_listButton.at(i).btnText,
m_listButton.at(i).isLighted);
}
m_btnSoft[3]->setText("More");
m_listWidget->DelListItemWidget();
m_listWidget->SetScrollParams(4,m_listButton.size());
for(int i=0;i<m_listButton.size();i++){
m_listWidget->AddListItemWidget(m_listButton.at(i).btnText,false);
}
}
ChangeLayout(0);
}
void CScrollMsg::delLayout(QLayout *layout)
{
if(layout==NULL)
return;
int count=layout->count();
if(count==0)
return;
for(int i=count-1;i>=0;i--){
QLayoutItem *item=layout->itemAt(i);
delLayout(item->layout());
layout->removeItem(item);
}
}
void CScrollMsg::ChangeLayout(int flag)
{
//delLayout(m_pMainLayout);
if(flag==0){
m_editText->show();
m_editText->setGeometry(10,10,ui_app_width-20,ui_app_height*3/4-15);
for(int i=0;i<4;i++){
m_btnSoft[i]->show();
m_btnSoft[i]->setGeometry(5+i*ui_btn_width,ui_app_height*3/4+15,ui_btn_width,ui_app_height*1/4-20);
}
m_listWidget->hide();
// QHBoxLayout midLayout;
// midLayout.addStretch(5);
// midLayout.addWidget(m_editText, 85);
// midLayout.addStretch(10);
// QHBoxLayout bottomLayout;
// bottomLayout.addWidget(m_btnSoft[0]);
// bottomLayout.addWidget(m_btnSoft[1]);
// bottomLayout.addWidget(m_btnSoft[2]);
// bottomLayout.addWidget(m_btnSoft[3]);
// m_pMainLayout->addStretch(2);
// // m_pMainLayout->addLayout(upLayout, 7);
// // mLayout->addWidget(m_editText, 66, Qt::AlignCenter);
// m_pMainLayout->addLayout(&midLayout, 61);
// m_pMainLayout->addStretch(2);
// m_pMainLayout->addLayout(&bottomLayout, 20);
// m_pMainLayout->addStretch(1);
// m_pMainLayout->setMargin(0);
// this->setLayout(&mainLayout);
}
else{
m_listWidget->show();
m_editText->hide();
for(int i=0;i<4;i++){
m_btnSoft[i]->hide();
}
// m_pMainLayout->addStretch(4);
// m_pMainLayout->addWidget(m_listWidget,92,Qt::AlignCenter);
// m_pMainLayout->addStretch(4);
}
}
void CScrollMsg::setTimeOut(int duration)
{
m_timer.start(duration);
}
void CScrollMsg::timeoutSlots()
{
m_timer.stop();
emit scrollMsgAbort(0);
}
void CScrollMsg::setMessage(QString msg)
{
m_editText->setText(msg);
}
void CScrollMsg::setButtonStyle(int index,int btnId, QString text, bool highLight)
{
switch (index)
{
case 0:
{
m_btnSoft[0]->setId(btnId);
m_btnSoft[0]->setText(text);
if(highLight)
{
m_btnSoft[0]->setIconNormal(":/images/highlightsoftbutton_alert.png");
m_btnSoft[0]->setIconPressed(":/images/highlightsoftbutton_alert.png");
}
else
{
m_btnSoft[0]->setIconNormal(":/images/softbutton_alert.png");
m_btnSoft[0]->setIconPressed(":/images/softbutton_alert.png");
}
}
break;
case 1:
{
m_btnSoft[1]->setId(btnId);
m_btnSoft[1]->setText(text);
if(highLight)
{
m_btnSoft[1]->setIconNormal(":/images/highlightsoftbutton_alert_left.png");
m_btnSoft[1]->setIconPressed(":/images/highlightsoftbutton_alert_left.png");
}
else
{
m_btnSoft[1]->setIconNormal(":/images/softbutton_alert_left.png");
m_btnSoft[1]->setIconPressed(":/images/softbutton_alert_left.png");
}
}
break;
case 2:
{
m_btnSoft[2]->setId(btnId);
m_btnSoft[2]->setText(text);
if(highLight)
{
m_btnSoft[2]->setIconNormal(":/images/highlightsoftbutton_alert_right.png");
m_btnSoft[2]->setIconPressed(":/images/highlightsoftbutton_alert_right.png");
}
else
{
m_btnSoft[2]->setIconNormal(":/images/softbutton_alert_right.png");
m_btnSoft[2]->setIconPressed(":/images/softbutton_alert_right.png");
}
}
break;
case 3:
{
m_btnSoft[3]->setId(btnId);
m_btnSoft[3]->setText(text);
if(highLight)
{
m_btnSoft[3]->setIconNormal(":/images/highlightsoftbutton_alert.png");
m_btnSoft[3]->setIconPressed(":/images/highlightsoftbutton_alert.png");
}
else
{
m_btnSoft[3]->setIconNormal(":/images/softbutton_alert.png");
m_btnSoft[3]->setIconPressed(":/images/softbutton_alert.png");
}
}
break;
}
}
void CScrollMsg::addSoftButton(int btnId, QString text, bool highLight)
{
SoftButton button;
button.btnId=btnId;
button.btnText=text;
button.isLighted=highLight;
m_listButton.append(button);
}
void CScrollMsg::onSpaceClicedSlots()
{
m_timer.stop();
emit scrollMsgAbort(2);
}
void CScrollMsg::onButtonClickedSlots(int btID)
{
if (m_listButton.size()>4){
CButton *button = static_cast<CButton*>(sender());
if (m_btnSoft[3] == button){
ChangeLayout(1);
return;
}
}
m_timer.stop();
emit scrollMsgAbort(1);
if(btID != 0)
{
AppControl->OnSoftButtonClick(btID, 0);
}
}
void CScrollMsg::onButtonClickedLongSlots(int btID)
{
if(m_listButton.size()>4){
CButton *button=static_cast<CButton*>(sender());
if(m_btnSoft[3]==button){
ChangeLayout(1);
return;
}
}
m_timer.stop();
emit scrollMsgAbort(1);
if(btID != 0)
{
AppControl->OnSoftButtonClick(btID, 1);
}
}
void CScrollMsg::onItemClicked(int index)
{
m_timer.stop();
emit scrollMsgAbort(1);
AppControl->OnSoftButtonClick(m_listButton.at(index).btnId,0);
}
void CScrollMsg::onItemLongClicked(int index)
{
m_timer.stop();
emit scrollMsgAbort(1);
AppControl->OnSoftButtonClick(m_listButton.at(index).btnId,1);
}
void CScrollMsg::scrollMsgAbortSlots(int reason)
{
//_D("smID=%d, reason=%d\n",smID,reason);
AppControl->OnScrollMessageResponse(reason);
}
void CScrollMsg::showEvent(QShowEvent * e)
{
for(int i = 0;i != 4;++i)
{
disconnect(m_btnSoft[i], SIGNAL(clicked(int)), this, SLOT(onButtonClickedSlots(int)));
}
if (AppControl)
{
m_listButton.clear();
Json::Value m_jsonData = AppControl->getScrollableMsgJson()["params"];
setTimeOut(m_jsonData["timeout"].asInt());
if (m_jsonData.isMember("messageText"))
{
setMessage(m_jsonData["messageText"]["fieldText"].asString().data());
}
if (m_jsonData.isMember("softButtons"))
{
int size=m_jsonData["softButtons"].size();
for (int i = 0; i < size; i++)
{
addSoftButton(m_jsonData["softButtons"][i]["softButtonID"].asInt(),
m_jsonData["softButtons"][i]["text"].asString().c_str(),m_jsonData["softButtons"][i]["isHighlighted"].asBool());
connect(m_btnSoft[i], SIGNAL(clicked(int)), this, SLOT(onButtonClickedSlots(int)));
connect(m_btnSoft[i], SIGNAL(clickedLong(int)), this, SLOT(onButtonClickedLongSlots(int)));
}
}
UpdateLayout();
}
}
| smartdevice475/hmi_sdk | UIShare/UI/ScrollableMessage/ScrollMsg.cpp | C++ | bsd-3-clause | 9,867 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from flask.ext.script import Manager, Shell, Server
from flask.ext.migrate import MigrateCommand
from foobar.app import create_app
from foobar.user.models import User
from foobar.settings import DevConfig, ProdConfig
from foobar.database import db
if os.environ.get("FOOBAR_ENV") == 'prod':
app = create_app(ProdConfig)
else:
app = create_app(DevConfig)
HERE = os.path.abspath(os.path.dirname(__file__))
TEST_PATH = os.path.join(HERE, 'tests')
manager = Manager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, db, and the User model by default.
"""
return {'app': app, 'db': db, 'User': User}
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| ghofranehr/foobar | manage.py | Python | bsd-3-clause | 1,092 |
'use strict';
exports.__esModule = true;
const moduleRequire = require('./module-require').default;
const extname = require('path').extname;
const fs = require('fs');
const log = require('debug')('eslint-plugin-import:parse');
function getBabelEslintVisitorKeys(parserPath) {
if (parserPath.endsWith('index.js')) {
const hypotheticalLocation = parserPath.replace('index.js', 'visitor-keys.js');
if (fs.existsSync(hypotheticalLocation)) {
const keys = moduleRequire(hypotheticalLocation);
return keys.default || keys;
}
}
return null;
}
function keysFromParser(parserPath, parserInstance, parsedResult) {
// Exposed by @typescript-eslint/parser and @babel/eslint-parser
if (parsedResult && parsedResult.visitorKeys) {
return parsedResult.visitorKeys;
}
if (/.*espree.*/.test(parserPath)) {
return parserInstance.VisitorKeys;
}
if (/.*babel-eslint.*/.test(parserPath)) {
return getBabelEslintVisitorKeys(parserPath);
}
return null;
}
exports.default = function parse(path, content, context) {
if (context == null) throw new Error('need context to parse properly');
let parserOptions = context.parserOptions;
const parserPath = getParserPath(path, context);
if (!parserPath) throw new Error('parserPath is required!');
// hack: espree blows up with frozen options
parserOptions = Object.assign({}, parserOptions);
parserOptions.ecmaFeatures = Object.assign({}, parserOptions.ecmaFeatures);
// always include comments and tokens (for doc parsing)
parserOptions.comment = true;
parserOptions.attachComment = true; // keeping this for backward-compat with older parsers
parserOptions.tokens = true;
// attach node locations
parserOptions.loc = true;
parserOptions.range = true;
// provide the `filePath` like eslint itself does, in `parserOptions`
// https://github.com/eslint/eslint/blob/3ec436ee/lib/linter.js#L637
parserOptions.filePath = path;
// @typescript-eslint/parser will parse the entire project with typechecking if you provide
// "project" or "projects" in parserOptions. Removing these options means the parser will
// only parse one file in isolate mode, which is much, much faster.
// https://github.com/import-js/eslint-plugin-import/issues/1408#issuecomment-509298962
delete parserOptions.project;
delete parserOptions.projects;
// require the parser relative to the main module (i.e., ESLint)
const parser = moduleRequire(parserPath);
if (typeof parser.parseForESLint === 'function') {
let ast;
try {
const parserRaw = parser.parseForESLint(content, parserOptions);
ast = parserRaw.ast;
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, parserRaw),
};
} catch (e) {
console.warn();
console.warn('Error while parsing ' + parserOptions.filePath);
console.warn('Line ' + e.lineNumber + ', column ' + e.column + ': ' + e.message);
}
if (!ast || typeof ast !== 'object') {
console.warn(
'`parseForESLint` from parser `' +
parserPath +
'` is invalid and will just be ignored'
);
} else {
return {
ast,
visitorKeys: keysFromParser(parserPath, parser, undefined),
};
}
}
const keys = keysFromParser(parserPath, parser, undefined);
return {
ast: parser.parse(content, parserOptions),
visitorKeys: keys,
};
};
function getParserPath(path, context) {
const parsers = context.settings['import/parsers'];
if (parsers != null) {
const extension = extname(path);
for (const parserPath in parsers) {
if (parsers[parserPath].indexOf(extension) > -1) {
// use this alternate parser
log('using alt parser:', parserPath);
return parserPath;
}
}
}
// default to use ESLint parser
return context.parserPath;
}
| ChromeDevTools/devtools-frontend | node_modules/eslint-module-utils/parse.js | JavaScript | bsd-3-clause | 3,870 |
<?php
namespace Auth;
class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap($e)
{
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
if ('Auth' === $moduleNamespace ) {
$controller->layout('layout/auth');
}
}, 100);
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
| blue-ray/ocorrencia | module/Auth/Module.php | PHP | bsd-3-clause | 997 |
// Copyright (c) 2013, salesforce.com, inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided
// that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
(function ($$){
var sr, mobile, postType, thumbnailUrl;
myPublisher = {
init : function(signedRequest, isMobile) {
sr = signedRequest;
mobile = isMobile;
},
// Auto resize the iframe to fit the current content.
resize : function() {
$$.client.resize(sr.client);
},
// Simply display incoming events in order
logEvent : function(name) {
var elem = $$.byId("events");
var sep = ($$.isNil(elem.value)) ? "" : ",";
elem.value += sep + name
},
selectPostType : function(e) {
console.log("got click", e);
postType = e;
// Enable the share button
$$.client.publish(sr.client, {name : "publisher.setValidForSubmit", payload : true});
},
clearPostTypes : function() {
var i, elements = $$.byClass('postType');
for (i = 0; i < elements.length; i+=1) {
elements[i].checked=false;
}
},
canvasOptions : function(elem, option) {
var bool = Sfdc.canvas.indexOf(sr.context.application.options, option) == -1;
elem.innerHTML = (bool) ? "✓" : "✗";
elem.style.color = (bool) ? "green" : "red";
},
updateContent : function() {
if (!mobile) {
$$.byId('name').innerHTML = sr.context.user.firstName + " " + sr.context.user.lastName;
$$.byId('location').innerHTML = sr.context.environment.displayLocation;
myPublisher.canvasOptions($$.byId('header-enabled'), "HideHeader");
myPublisher.canvasOptions($$.byId('share-enabled'), "HideShare");
}
},
selectThumbnail: function(e) {
thumbnailUrl = (e === "none") ? null : window.location.origin + e;
console.log("Thumbnail URL " + thumbnailUrl);
},
handlers : function() {
var handlers = {
onSetupPanel : function (payload) {
myPublisher.resize(); // Do I want to do this on iphone?
myPublisher.logEvent("setupPanel");
},
onShowPanel : function(payload) {
myPublisher.logEvent("showPanel");
},
onClearPanelState : function(payload) {
myPublisher.logEvent("clearPanelState");
myPublisher.clearPostTypes();
// Clear all the text fields and reset radio buttons
},
onSuccess : function() {
myPublisher.logEvent("success");
},
onFailure : function (payload) {
myPublisher.logEvent("failure");
myPublisher.clearPostTypes();
if (payload && payload.errors && payload.errors.message) {
alert("Error: " + payload.errors.message);
}
},
onGetPayload : function() {
myPublisher.logEvent("getPayload");
var p = {};
if (postType === 'Text') {
// Example of a Text Post
p.feedItemType = "TextPost";
p.auxText = $$.byId('auxText').value;
}
else if (postType === 'Link') {
// Example of a Link Post
p.feedItemType = "LinkPost";
p.auxText = $$.byId('auxText').value;
p.url = "http://www.salesforce.com";
p.urlName = $$.byId('title').value;
}
else if (postType === 'Canvas') {
// Example of a Canvas Post
p.feedItemType = "CanvasPost";
p.auxText = $$.byId('auxText').value;
p.namespace = sr.context.application.namespace;
p.developerName = sr.context.application.developerName;
p.height = $$.byId('height').value;
p.title = $$.byId('title').value;
p.description = $$.byId('description').value;
p.parameters = $$.byId('parameters').value;
p.thumbnailUrl = thumbnailUrl;
}
$$.client.publish(sr.client, {name : 'publisher.setPayload', payload : p});
}
};
return {
subscriptions : [
{name : 'publisher.setupPanel', onData : handlers.onSetupPanel},
{name : 'publisher.showPanel', onData : handlers.onShowPanel},
{name : 'publisher.clearPanelState', onData : handlers.onClearPanelState},
{name : 'publisher.failure', onData : handlers.onFailure},
{name : 'publisher.success', onData : handlers.onSuccess},
{name : 'publisher.getPayload', onData : handlers.onGetPayload}
]
};
}
};
}(Sfdc.canvas));
| jthurst01/canvas-app-json | src/main/webapp/Publisher/publisher.js | JavaScript | bsd-3-clause | 6,834 |
/**
*
* <i>Copyright (c) 2017 ItsAsbreuk - http://itsasbreuk.nl</i><br>
* New BSD License - http://choosealicense.com/licenses/bsd-3-clause/
*
*
* @since 16.2.0
*/
'use strict';
const reload = require('require-reload')(require), // see https://github.com/fastest963/require-reload
cwd = process.cwd(),
generateServiceWorker = require('../..//serviceworker/generate-serviceworker'),
OFFLINE_IMAGE = require('../../offline-image'),
OFFLINE_PAGE = '/offline/',
EXPIRE_ONE_YEAR = 365 * 24 * 60 * 60 * 1000,
EXPIRE_TEN_YEARS = 10 * EXPIRE_ONE_YEAR;
const generate = async (server, urlsToCache, appConfig, startupTime) => {
const prefix = '/build',
cwdPrefix = cwd+prefix,
serverConnection = server.root,
favicon = ((appConfig.cdn && appConfig.cdn.enabled) ? appConfig.cdn.url : cwdPrefix+'/public/') + 'assets/' + appConfig.packageVersion + '/favicon.ico',
routes = reload(cwd+'/src/routes.js');
if (appConfig.pageNotFoundView) {
server.root.ext('onPreResponse', function(request, reply) {
// manage mismatches based upon the `scope`:
let response = request.response,
splitted, uri, isHtmlPage;
if (response.isBoom && response.output && (response.output.statusCode===404)) {
// if request to a page, then redirect:
splitted = request.url.path.split('?');
uri = splitted[0].toUpperCase();
isHtmlPage = uri.endsWith('.HTML') || uri.endsWith('.HTM') || (uri.lastIndexOf('.')<uri.lastIndexOf('/'));
if (isHtmlPage) {
return reply.reactview(appConfig.pageNotFoundView);
}
}
return reply.continue();
});
}
serverConnection.activateRoutes = function() {
var startRouting = setTimeout(function() {
console.error('Error: failied to load routes');
}, 5000);
try {
serverConnection.route(routes);
}
catch (err) {
console.warn(err);
}
clearTimeout(startRouting);
serverConnection.routes = {
prefix: prefix
};
};
routes.push({
method: 'GET',
path: '/favicon.ico',
handler: function(request, reply) {
if (appConfig.cdn && appConfig.cdn.enabled) {
reply().redirect(favicon).permanent().rewritable();
}
else {
reply.file(favicon);
}
},
config: {
cache: {
expiresIn: EXPIRE_ONE_YEAR,
privacy: 'private'
}
}
});
// assets created with `require` follow with as deep nested as needed, they also have a version in the url:
routes.push({
method: 'GET',
path: '/assets/'+appConfig.packageVersion+'/{filename*}',
handler: function(request, reply) {
// inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same.
reply.file(cwdPrefix+'/public/assets/'+appConfig.packageVersion+'/'+request.params.filename);
},
config: {
cache: {
expiresIn: EXPIRE_ONE_YEAR,
privacy: 'private'
}
}
});
// assets created with `require` follow with as deep nested as needed, they also have a version in the url:
routes.push({
method: 'GET',
path: '/assets-private/'+appConfig.packageVersion+'/{filename*}',
handler: function(request, reply) {
// inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same.
reply.file(cwdPrefix+'/private/assets-private/'+appConfig.packageVersion+'/'+request.params.filename);
},
config: {
cache: {
expiresIn: EXPIRE_ONE_YEAR,
privacy: 'private'
}
}
});
// external modules, created by webpack
routes.push({
method: 'GET',
path: '/assets/_itsa_server_external_modules/{versionedmodule*}',
handler: function(request, reply) {
reply.file(cwdPrefix+'/public/assets/_itsa_server_external_modules/'+request.params.versionedmodule);
},
config: {
cache: {
expiresIn: EXPIRE_TEN_YEARS,
privacy: 'private'
}
}
});
routes.push({
method: 'GET',
path: '/assets/local/{filename*}',
handler: function(request, reply) {
// inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same.
reply.file(cwdPrefix+'/private/assets/'+request.params.filename);
},
config: {
cache: {
expiresIn: EXPIRE_ONE_YEAR,
privacy: 'private'
}
}
});
routes.push({
method: 'GET',
path: '/assets/{filename*}',
handler: function(request, reply) {
// inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same.
reply.file(cwdPrefix+'/public/assets/'+appConfig.packageVersion+'/'+request.params.filename);
},
config: {
cache: {
expiresIn: EXPIRE_ONE_YEAR,
privacy: 'private'
}
}
});
routes.push({
method: 'GET',
path: '/_itsa_server_serviceworker.js',
handler: function(request, reply) {
if (appConfig['service-workers'] && appConfig['service-workers'].enabled) {
// inert will set an eTag. We leave `no-cache` because the file might change while the name keeps the same.
generateServiceWorker.generateFile(startupTime, urlsToCache, OFFLINE_IMAGE, OFFLINE_PAGE, appConfig.socketPort || 4002, (appConfig.cdn && appConfig.cdn.enabled) ? appConfig.cdn.url : null)
.then(fileContent => reply(fileContent).type('application/javascript; charset=utf-8').header('Cache-Control', 'no-cache, no-store, must-revalidate'))
.catch(err => {
console.warn(err);
reply(err);
});
}
else {
reply('').type('application/javascript; charset=utf-8').header('Cache-Control', 'no-cache, no-store, must-revalidate');
}
}
});
serverConnection.activateRoutes();
};
module.exports = {
generate
};
| ItsAsbreuk/itsa-react-server | lib/hapi-plugin/helpers/apply-server-routes.js | JavaScript | bsd-3-clause | 6,635 |
#include <PrecompiledHeader.h>
#include "Macro/UnitGroup.h"
using namespace BWAPI;
using namespace std;
bool passesFlag(Unit* u, int f)
{
if (f<0)
return !passesFlag(u,-f);
switch(f)
{
case exists:
if (u->exists()) return true;
break;
case isAccelerating:
if (u->isAccelerating()) return true;
break;
case isAttacking:
if (u->isAttacking()) return true;
break;
case isBeingConstructed:
if (u->isBeingConstructed()) return true;
break;
case isBeingGathered:
if (u->isBeingGathered()) return true;
break;
case isBeingHealed:
if (u->isBeingHealed()) return true;
break;
case isBlind:
if (u->isBlind()) return true;
break;
case isBraking:
if (u->isBraking()) return true;
break;
case isBurrowed:
if (u->isBurrowed()) return true;
break;
case isCarryingGas:
if (u->isCarryingGas()) return true;
break;
case isCarryingMinerals:
if (u->isCarryingMinerals()) return true;
break;
case isCloaked:
if (u->isCloaked()) return true;
break;
case isCompleted:
if (u->isCompleted()) return true;
break;
case isConstructing:
if (u->isConstructing()) return true;
break;
case isDefenseMatrixed:
if (u->isDefenseMatrixed()) return true;
break;
case isDetected:
if (u->isDetected()) return true;
break;
case isEnsnared:
if (u->isEnsnared()) return true;
break;
case isFollowing:
if (u->isFollowing()) return true;
break;
case isGatheringGas:
if (u->isGatheringGas()) return true;
break;
case isGatheringMinerals:
if (u->isGatheringMinerals()) return true;
break;
case isHallucination:
if (u->isHallucination()) return true;
break;
case isHoldingPosition:
if (u->isHoldingPosition()) return true;
break;
case isIdle:
if (u->isIdle()) return true;
break;
case isInterruptible:
if (u->isInterruptible()) return true;
break;
case isIrradiated:
if (u->isIrradiated()) return true;
break;
case isLifted:
if (u->isLifted()) return true;
break;
case isLoaded:
if (u->isLoaded()) return true;
break;
case isLockedDown:
if (u->isLockedDown()) return true;
break;
case isMaelstrommed:
if (u->isMaelstrommed()) return true;
break;
case isMorphing:
if (u->isMorphing()) return true;
break;
case isMoving:
if (u->isMoving()) return true;
break;
case isParasited:
if (u->isParasited()) return true;
break;
case isPatrolling:
if (u->isPatrolling()) return true;
break;
case isPlagued:
if (u->isPlagued()) return true;
break;
case isRepairing:
if (u->isRepairing()) return true;
break;
case isResearching:
if (u->isResearching()) return true;
break;
case isSelected:
if (u->isSelected()) return true;
break;
case isSieged:
if (u->isSieged()) return true;
break;
case isStartingAttack:
if (u->isStartingAttack()) return true;
break;
case isStasised:
if (u->isStasised()) return true;
break;
case isStimmed:
if (u->isStimmed()) return true;
break;
case isStuck:
if (u->isStuck()) return true;
break;
case isTraining:
if (u->isTraining()) return true;
break;
case isUnderStorm:
if (u->isUnderStorm()) return true;
break;
case isUnpowered:
if (u->isUnpowered()) return true;
break;
case isUpgrading:
if (u->isUpgrading()) return true;
break;
case isVisible:
if (u->isVisible()) return true;
break;
case canProduce:
if (u->getType().canProduce()) return true;
break;
case canAttack:
if (u->getType().canAttack()) return true;
break;
case canMove:
if (u->getType().canMove()) return true;
break;
case isFlyer:
if (u->getType().isFlyer()) return true;
break;
case regeneratesHP:
if (u->getType().regeneratesHP()) return true;
break;
case isSpellcaster:
if (u->getType().isSpellcaster()) return true;
break;
case hasPermanentCloak:
if (u->getType().hasPermanentCloak()) return true;
break;
case isInvincible:
if (u->getType().isInvincible()) return true;
break;
case isOrganic:
if (u->getType().isOrganic()) return true;
break;
case isMechanical:
if (u->getType().isMechanical()) return true;
break;
case isRobotic:
if (u->getType().isRobotic()) return true;
break;
case isDetector:
if (u->getType().isDetector()) return true;
break;
case isResourceContainer:
if (u->getType().isResourceContainer()) return true;
break;
case isResourceDepot:
if (u->getType().isResourceDepot()) return true;
break;
case isRefinery:
if (u->getType().isRefinery()) return true;
break;
case isWorker:
if (u->getType().isWorker()) return true;
break;
case requiresPsi:
if (u->getType().requiresPsi()) return true;
break;
case requiresCreep:
if (u->getType().requiresCreep()) return true;
break;
case isTwoUnitsInOneEgg:
if (u->getType().isTwoUnitsInOneEgg()) return true;
break;
case isBurrowable:
if (u->getType().isBurrowable()) return true;
break;
case isCloakable:
if (u->getType().isCloakable()) return true;
break;
case isBuilding:
if (u->getType().isBuilding()) return true;
break;
case isAddon:
if (u->getType().isAddon()) return true;
break;
case isFlyingBuilding:
if (u->getType().isFlyingBuilding()) return true;
break;
case isNeutral:
if (u->getType().isNeutral()) return true;
break;
case isHero:
if (u->getType().isHero()) return true;
break;
case isPowerup:
if (u->getType().isPowerup()) return true;
break;
case isBeacon:
if (u->getType().isBeacon()) return true;
break;
case isFlagBeacon:
if (u->getType().isFlagBeacon()) return true;
break;
case isSpecialBuilding:
if (u->getType().isSpecialBuilding()) return true;
break;
case isSpell:
if (u->getType().isSpell()) return true;
break;
case Firebat:
if(u->getType()==UnitTypes::Terran_Firebat) return true;
break;
case Ghost:
if(u->getType()==UnitTypes::Terran_Ghost) return true;
break;
case Goliath:
if(u->getType()==UnitTypes::Terran_Goliath) return true;
break;
case Marine:
if(u->getType()==UnitTypes::Terran_Marine) return true;
break;
case Medic:
if(u->getType()==UnitTypes::Terran_Medic) return true;
break;
case SCV:
if(u->getType()==UnitTypes::Terran_SCV) return true;
break;
case Siege_Tank:
if(u->getType()==UnitTypes::Terran_Siege_Tank_Tank_Mode) return true;
if(u->getType()==UnitTypes::Terran_Siege_Tank_Siege_Mode) return true;
break;
case Vulture:
if(u->getType()==UnitTypes::Terran_Vulture) return true;
break;
case Vulture_Spider_Mine:
if(u->getType()==UnitTypes::Terran_Vulture_Spider_Mine) return true;
break;
case Battlecruiser:
if(u->getType()==UnitTypes::Terran_Battlecruiser) return true;
break;
case Dropship:
if(u->getType()==UnitTypes::Terran_Dropship) return true;
break;
case Nuclear_Missile:
if(u->getType()==UnitTypes::Terran_Nuclear_Missile) return true;
break;
case Science_Vessel:
if(u->getType()==UnitTypes::Terran_Science_Vessel) return true;
break;
case Valkyrie:
if(u->getType()==UnitTypes::Terran_Valkyrie) return true;
break;
case Wraith:
if(u->getType()==UnitTypes::Terran_Wraith) return true;
break;
case Alan_Schezar:
if(u->getType()==UnitTypes::Hero_Alan_Schezar) return true;
break;
case Alexei_Stukov:
if(u->getType()==UnitTypes::Hero_Alexei_Stukov) return true;
break;
case Arcturus_Mengsk:
if(u->getType()==UnitTypes::Hero_Arcturus_Mengsk) return true;
break;
case Edmund_Duke:
if(u->getType()==UnitTypes::Hero_Edmund_Duke_Siege_Mode) return true;
if(u->getType()==UnitTypes::Hero_Edmund_Duke_Tank_Mode) return true;
break;
case Gerard_DuGalle:
if(u->getType()==UnitTypes::Hero_Gerard_DuGalle) return true;
break;
case Gui_Montag:
if(u->getType()==UnitTypes::Hero_Gui_Montag) return true;
break;
case Hyperion:
if(u->getType()==UnitTypes::Hero_Hyperion) return true;
break;
case Jim_Raynor_Marine:
if(u->getType()==UnitTypes::Hero_Jim_Raynor_Marine) return true;
break;
case Jim_Raynor_Vulture:
if(u->getType()==UnitTypes::Hero_Jim_Raynor_Vulture) return true;
break;
case Magellan:
if(u->getType()==UnitTypes::Hero_Magellan) return true;
break;
case Norad_II:
if(u->getType()==UnitTypes::Hero_Norad_II) return true;
break;
case Samir_Duran:
if(u->getType()==UnitTypes::Hero_Samir_Duran) return true;
break;
case Sarah_Kerrigan:
if(u->getType()==UnitTypes::Hero_Sarah_Kerrigan) return true;
break;
case Tom_Kazansky:
if(u->getType()==UnitTypes::Hero_Tom_Kazansky) return true;
break;
case Civilian:
if(u->getType()==UnitTypes::Terran_Civilian) return true;
break;
case Academy:
if(u->getType()==UnitTypes::Terran_Academy) return true;
break;
case Armory:
if(u->getType()==UnitTypes::Terran_Armory) return true;
break;
case Barracks:
if(u->getType()==UnitTypes::Terran_Barracks) return true;
break;
case Bunker:
if(u->getType()==UnitTypes::Terran_Bunker) return true;
break;
case Command_Center:
if(u->getType()==UnitTypes::Terran_Command_Center) return true;
break;
case Engineering_Bay:
if(u->getType()==UnitTypes::Terran_Engineering_Bay) return true;
break;
case Factory:
if(u->getType()==UnitTypes::Terran_Factory) return true;
break;
case Missile_Turret:
if(u->getType()==UnitTypes::Terran_Missile_Turret) return true;
break;
case Refinery:
if(u->getType()==UnitTypes::Terran_Refinery) return true;
break;
case Science_Facility:
if(u->getType()==UnitTypes::Terran_Science_Facility) return true;
break;
case Starport:
if(u->getType()==UnitTypes::Terran_Starport) return true;
break;
case Supply_Depot:
if(u->getType()==UnitTypes::Terran_Supply_Depot) return true;
break;
case Comsat_Station:
if(u->getType()==UnitTypes::Terran_Comsat_Station) return true;
break;
case Control_Tower:
if(u->getType()==UnitTypes::Terran_Control_Tower) return true;
break;
case Covert_Ops:
if(u->getType()==UnitTypes::Terran_Covert_Ops) return true;
break;
case Machine_Shop:
if(u->getType()==UnitTypes::Terran_Machine_Shop) return true;
break;
case Nuclear_Silo:
if(u->getType()==UnitTypes::Terran_Nuclear_Silo) return true;
break;
case Physics_Lab:
if(u->getType()==UnitTypes::Terran_Physics_Lab) return true;
break;
case Crashed_Norad_II:
if(u->getType()==UnitTypes::Special_Crashed_Norad_II) return true;
break;
case Ion_Cannon:
if(u->getType()==UnitTypes::Special_Ion_Cannon) return true;
break;
case Power_Generator:
if(u->getType()==UnitTypes::Special_Power_Generator) return true;
break;
case Psi_Disrupter:
if(u->getType()==UnitTypes::Special_Psi_Disrupter) return true;
break;
case Archon:
if(u->getType()==UnitTypes::Protoss_Archon) return true;
break;
case Dark_Archon:
if(u->getType()==UnitTypes::Protoss_Dark_Archon) return true;
break;
case Dark_Templar:
if(u->getType()==UnitTypes::Protoss_Dark_Templar) return true;
break;
case Dragoon:
if(u->getType()==UnitTypes::Protoss_Dragoon) return true;
break;
case High_Templar:
if(u->getType()==UnitTypes::Protoss_High_Templar) return true;
break;
case Probe:
if(u->getType()==UnitTypes::Protoss_Probe) return true;
break;
case Reaver:
if(u->getType()==UnitTypes::Protoss_Reaver) return true;
break;
case Scarab:
if(u->getType()==UnitTypes::Protoss_Scarab) return true;
break;
case Zealot:
if(u->getType()==UnitTypes::Protoss_Zealot) return true;
break;
case Arbiter:
if(u->getType()==UnitTypes::Protoss_Arbiter) return true;
break;
case Carrier:
if(u->getType()==UnitTypes::Protoss_Carrier) return true;
break;
case Corsair:
if(u->getType()==UnitTypes::Protoss_Corsair) return true;
break;
case Interceptor:
if(u->getType()==UnitTypes::Protoss_Interceptor) return true;
break;
case Observer:
if(u->getType()==UnitTypes::Protoss_Observer) return true;
break;
case Scout:
if(u->getType()==UnitTypes::Protoss_Scout) return true;
break;
case Shuttle:
if(u->getType()==UnitTypes::Protoss_Shuttle) return true;
break;
case Aldaris:
if(u->getType()==UnitTypes::Hero_Aldaris) return true;
break;
case Artanis:
if(u->getType()==UnitTypes::Hero_Artanis) return true;
break;
case Danimoth:
if(u->getType()==UnitTypes::Hero_Danimoth) return true;
break;
case Hero_Dark_Templar:
if(u->getType()==UnitTypes::Hero_Dark_Templar) return true;
break;
case Fenix_Dragoon:
if(u->getType()==UnitTypes::Hero_Fenix_Dragoon) return true;
break;
case Fenix_Zealot:
if(u->getType()==UnitTypes::Hero_Fenix_Zealot) return true;
break;
case Gantrithor:
if(u->getType()==UnitTypes::Hero_Gantrithor) return true;
break;
case Mojo:
if(u->getType()==UnitTypes::Hero_Mojo) return true;
break;
case Raszagal:
if(u->getType()==UnitTypes::Hero_Raszagal) return true;
break;
case Tassadar:
if(u->getType()==UnitTypes::Hero_Tassadar) return true;
break;
case Tassadar_Zeratul_Archon:
if(u->getType()==UnitTypes::Hero_Tassadar_Zeratul_Archon) return true;
break;
case Warbringer:
if(u->getType()==UnitTypes::Hero_Warbringer) return true;
break;
case Zeratul:
if(u->getType()==UnitTypes::Hero_Zeratul) return true;
break;
case Arbiter_Tribunal:
if(u->getType()==UnitTypes::Protoss_Arbiter_Tribunal) return true;
break;
case Assimilator:
if(u->getType()==UnitTypes::Protoss_Assimilator) return true;
break;
case Citadel_of_Adun:
if(u->getType()==UnitTypes::Protoss_Citadel_of_Adun) return true;
break;
case Cybernetics_Core:
if(u->getType()==UnitTypes::Protoss_Cybernetics_Core) return true;
break;
case Fleet_Beacon:
if(u->getType()==UnitTypes::Protoss_Fleet_Beacon) return true;
break;
case Forge:
if(u->getType()==UnitTypes::Protoss_Forge) return true;
break;
case Gateway:
if(u->getType()==UnitTypes::Protoss_Gateway) return true;
break;
case Nexus:
if(u->getType()==UnitTypes::Protoss_Nexus) return true;
break;
case Observatory:
if(u->getType()==UnitTypes::Protoss_Observatory) return true;
break;
case Photon_Cannon:
if(u->getType()==UnitTypes::Protoss_Photon_Cannon) return true;
break;
case Pylon:
if(u->getType()==UnitTypes::Protoss_Pylon) return true;
break;
case Robotics_Facility:
if(u->getType()==UnitTypes::Protoss_Robotics_Facility) return true;
break;
case Robotics_Support_Bay:
if(u->getType()==UnitTypes::Protoss_Robotics_Support_Bay) return true;
break;
case Shield_Battery:
if(u->getType()==UnitTypes::Protoss_Shield_Battery) return true;
break;
case Stargate:
if(u->getType()==UnitTypes::Protoss_Stargate) return true;
break;
case Templar_Archives:
if(u->getType()==UnitTypes::Protoss_Templar_Archives) return true;
break;
case Khaydarin_Crystal_Form:
if(u->getType()==UnitTypes::Special_Khaydarin_Crystal_Form) return true;
break;
case Protoss_Temple:
if(u->getType()==UnitTypes::Special_Protoss_Temple) return true;
break;
case Stasis_Cell_Prison:
if(u->getType()==UnitTypes::Special_Stasis_Cell_Prison) return true;
break;
case Warp_Gate:
if(u->getType()==UnitTypes::Special_Warp_Gate) return true;
break;
case XelNaga_Temple:
if(u->getType()==UnitTypes::Special_XelNaga_Temple) return true;
break;
case Broodling:
if(u->getType()==UnitTypes::Zerg_Broodling) return true;
break;
case Defiler:
if(u->getType()==UnitTypes::Zerg_Defiler) return true;
break;
case Drone:
if(u->getType()==UnitTypes::Zerg_Drone) return true;
break;
case Egg:
if(u->getType()==UnitTypes::Zerg_Egg) return true;
break;
case Hydralisk:
if(u->getType()==UnitTypes::Zerg_Hydralisk) return true;
break;
case Infested_Terran:
if(u->getType()==UnitTypes::Zerg_Infested_Terran) return true;
break;
case Larva:
if(u->getType()==UnitTypes::Zerg_Larva) return true;
break;
case Lurker:
if(u->getType()==UnitTypes::Zerg_Lurker) return true;
break;
case Lurker_Egg:
if(u->getType()==UnitTypes::Zerg_Lurker_Egg) return true;
break;
case Ultralisk:
if(u->getType()==UnitTypes::Zerg_Ultralisk) return true;
break;
case Zergling:
if(u->getType()==UnitTypes::Zerg_Zergling) return true;
break;
case Cocoon:
if(u->getType()==UnitTypes::Zerg_Cocoon) return true;
break;
case Devourer:
if(u->getType()==UnitTypes::Zerg_Devourer) return true;
break;
case Guardian:
if(u->getType()==UnitTypes::Zerg_Guardian) return true;
break;
case Mutalisk:
if(u->getType()==UnitTypes::Zerg_Mutalisk) return true;
break;
case Overlord:
if(u->getType()==UnitTypes::Zerg_Overlord) return true;
break;
case Queen:
if(u->getType()==UnitTypes::Zerg_Queen) return true;
break;
case Scourge:
if(u->getType()==UnitTypes::Zerg_Scourge) return true;
break;
case Devouring_One:
if(u->getType()==UnitTypes::Hero_Devouring_One) return true;
break;
case Hunter_Killer:
if(u->getType()==UnitTypes::Hero_Hunter_Killer) return true;
break;
case Infested_Duran:
if(u->getType()==UnitTypes::Hero_Infested_Duran) return true;
break;
case Infested_Kerrigan:
if(u->getType()==UnitTypes::Hero_Infested_Kerrigan) return true;
break;
case Kukulza_Guardian:
if(u->getType()==UnitTypes::Hero_Kukulza_Guardian) return true;
break;
case Kukulza_Mutalisk:
if(u->getType()==UnitTypes::Hero_Kukulza_Mutalisk) return true;
break;
case Matriarch:
if(u->getType()==UnitTypes::Hero_Matriarch) return true;
break;
case Torrasque:
if(u->getType()==UnitTypes::Hero_Torrasque) return true;
break;
case Unclean_One:
if(u->getType()==UnitTypes::Hero_Unclean_One) return true;
break;
case Yggdrasill:
if(u->getType()==UnitTypes::Hero_Yggdrasill) return true;
break;
case Creep_Colony:
if(u->getType()==UnitTypes::Zerg_Creep_Colony) return true;
break;
case Defiler_Mound:
if(u->getType()==UnitTypes::Zerg_Defiler_Mound) return true;
break;
case Evolution_Chamber:
if(u->getType()==UnitTypes::Zerg_Evolution_Chamber) return true;
break;
case Extractor:
if(u->getType()==UnitTypes::Zerg_Extractor) return true;
break;
case Greater_Spire:
if(u->getType()==UnitTypes::Zerg_Greater_Spire) return true;
break;
case Hatchery:
if(u->getType()==UnitTypes::Zerg_Hatchery) return true;
break;
case Hive:
if(u->getType()==UnitTypes::Zerg_Hive) return true;
break;
case Hydralisk_Den:
if(u->getType()==UnitTypes::Zerg_Hydralisk_Den) return true;
break;
case Infested_Command_Center:
if(u->getType()==UnitTypes::Zerg_Infested_Command_Center) return true;
break;
case Lair:
if(u->getType()==UnitTypes::Zerg_Lair) return true;
break;
case Nydus_Canal:
if(u->getType()==UnitTypes::Zerg_Nydus_Canal) return true;
break;
case Queens_Nest:
if(u->getType()==UnitTypes::Zerg_Queens_Nest) return true;
break;
case Spawning_Pool:
if(u->getType()==UnitTypes::Zerg_Spawning_Pool) return true;
break;
case Spire:
if(u->getType()==UnitTypes::Zerg_Spire) return true;
break;
case Spore_Colony:
if(u->getType()==UnitTypes::Zerg_Spore_Colony) return true;
break;
case Sunken_Colony:
if(u->getType()==UnitTypes::Zerg_Sunken_Colony) return true;
break;
case Ultralisk_Cavern:
if(u->getType()==UnitTypes::Zerg_Ultralisk_Cavern) return true;
break;
case Cerebrate:
if(u->getType()==UnitTypes::Special_Cerebrate) return true;
break;
case Cerebrate_Daggoth:
if(u->getType()==UnitTypes::Special_Cerebrate_Daggoth) return true;
break;
case Mature_Chrysalis:
if(u->getType()==UnitTypes::Special_Mature_Chrysalis) return true;
break;
case Overmind:
if(u->getType()==UnitTypes::Special_Overmind) return true;
break;
case Overmind_Cocoon:
if(u->getType()==UnitTypes::Special_Overmind_Cocoon) return true;
break;
case Overmind_With_Shell:
if(u->getType()==UnitTypes::Special_Overmind_With_Shell) return true;
break;
case Bengalaas:
if(u->getType()==UnitTypes::Critter_Bengalaas) return true;
break;
case Kakaru:
if(u->getType()==UnitTypes::Critter_Kakaru) return true;
break;
case Ragnasaur:
if(u->getType()==UnitTypes::Critter_Ragnasaur) return true;
break;
case Rhynadon:
if(u->getType()==UnitTypes::Critter_Rhynadon) return true;
break;
case Scantid:
if(u->getType()==UnitTypes::Critter_Scantid) return true;
break;
case Ursadon:
if(u->getType()==UnitTypes::Critter_Ursadon) return true;
break;
case Mineral_Field:
if(u->getType()==UnitTypes::Resource_Mineral_Field) return true;
break;
case Vespene_Geyser:
if(u->getType()==UnitTypes::Resource_Vespene_Geyser) return true;
break;
case Dark_Swarm:
if(u->getType()==UnitTypes::Spell_Dark_Swarm) return true;
break;
case Disruption_Web:
if(u->getType()==UnitTypes::Spell_Disruption_Web) return true;
break;
case Scanner_Sweep:
if(u->getType()==UnitTypes::Spell_Scanner_Sweep) return true;
break;
case Protoss_Beacon:
if(u->getType()==UnitTypes::Special_Protoss_Beacon) return true;
break;
case Protoss_Flag_Beacon:
if(u->getType()==UnitTypes::Special_Protoss_Flag_Beacon) return true;
break;
case Terran_Beacon:
if(u->getType()==UnitTypes::Special_Terran_Beacon) return true;
break;
case Terran_Flag_Beacon:
if(u->getType()==UnitTypes::Special_Terran_Flag_Beacon) return true;
break;
case Zerg_Beacon:
if(u->getType()==UnitTypes::Special_Zerg_Beacon) return true;
break;
case Zerg_Flag_Beacon:
if(u->getType()==UnitTypes::Special_Zerg_Flag_Beacon) return true;
break;
case Powerup_Data_Disk:
if(u->getType()==UnitTypes::Powerup_Data_Disk) return true;
break;
case Powerup_Flag:
if(u->getType()==UnitTypes::Powerup_Flag) return true;
break;
case Powerup_Khalis_Crystal:
if(u->getType()==UnitTypes::Powerup_Khalis_Crystal) return true;
break;
case Powerup_Khaydarin_Crystal:
if(u->getType()==UnitTypes::Powerup_Khaydarin_Crystal) return true;
break;
case Powerup_Psi_Emitter:
if(u->getType()==UnitTypes::Powerup_Psi_Emitter) return true;
break;
case Powerup_Uraj_Crystal:
if(u->getType()==UnitTypes::Powerup_Uraj_Crystal) return true;
break;
case Powerup_Young_Chrysalis:
if(u->getType()==UnitTypes::Powerup_Young_Chrysalis) return true;
break;
case None:
if(u->getType()==UnitTypes::None) return true;
break;
case Unknown_Unit:
if(u->getType()==UnitTypes::Unknown) return true;
break;
}
return false;
}
double getAttribute(Unit* u, FliterAttributeScalar a)
{
switch(a)
{
case HitPoints:
return u->getHitPoints();
break;
case InitialHitPoints:
return u->getInitialHitPoints();
break;
case Shields:
return u->getShields();
break;
case Energy:
return u->getEnergy();
break;
case Resources:
return u->getResources();
break;
case InitialResources:
return u->getInitialResources();
break;
case KillCount:
return u->getKillCount();
break;
case GroundWeaponCooldown:
return u->getGroundWeaponCooldown();
break;
case AirWeaponCooldown:
return u->getAirWeaponCooldown();
break;
case SpellCooldown:
return u->getSpellCooldown();
break;
case DefenseMatrixPoints:
return u->getDefenseMatrixPoints();
break;
case DefenseMatrixTimer:
return u->getDefenseMatrixTimer();
break;
case EnsnareTimer:
return u->getEnsnareTimer();
break;
case IrradiateTimer:
return u->getIrradiateTimer();
break;
case LockdownTimer:
return u->getLockdownTimer();
break;
case MaelstromTimer:
return u->getMaelstromTimer();
break;
case PlagueTimer:
return u->getPlagueTimer();
break;
case RemoveTimer:
return u->getRemoveTimer();
break;
case StasisTimer:
return u->getStasisTimer();
break;
case StimTimer:
return u->getStimTimer();
break;
case PositionX:
return u->getPosition().x();
break;
case PositionY:
return u->getPosition().y();
break;
case InitialPositionX:
return u->getInitialPosition().x();
break;
case InitialPositionY:
return u->getInitialPosition().y();
break;
case TilePositionX:
return u->getTilePosition().x();
break;
case TilePositionY:
return u->getTilePosition().y();
break;
case InitialTilePositionX:
return u->getInitialTilePosition().x();
break;
case InitialTilePositionY:
return u->getInitialTilePosition().y();
break;
case Angle:
return u->getAngle();
break;
case VelocityX:
return u->getVelocityX();
break;
case VelocityY:
return u->getVelocityY();
break;
case TargetPositionX:
return u->getTargetPosition().x();
break;
case TargetPositionY:
return u->getTargetPosition().y();
break;
case OrderTimer:
return u->getOrderTimer();
break;
case RemainingBuildTime:
return u->getRemainingBuildTime();
break;
case RemainingTrainTime:
return u->getRemainingTrainTime();
break;
case TrainingQueueCount:
return u->getTrainingQueue().size();
break;
case LoadedUnitsCount:
return u->getLoadedUnits().size();
break;
case InterceptorCount:
return u->getInterceptorCount();
break;
case ScarabCount:
return u->getScarabCount();
break;
case SpiderMineCount:
return u->getSpiderMineCount();
break;
case RemainingResearchTime:
return u->getRemainingResearchTime();
break;
case RemainingUpgradeTime:
return u->getRemainingUpgradeTime();
break;
case RallyPositionX:
return u->getRallyPosition().x();
break;
case RallyPositionY:
return u->getRallyPosition().y();
break;
}
return 0;
}
Unit* getUnit(Unit* u,FilterAttributeUnit a)
{
switch(a)
{
case GetTarget:
return u->getTarget();
break;
case GetOrderTarget:
return u->getOrderTarget();
break;
case GetBuildUnit:
return u->getBuildUnit();
break;
case GetTransport:
return u->getTransport();
break;
case GetRallyUnit:
return u->getRallyUnit();
break;
case GetAddon:
return u->getAddon();
break;
}
return u;
}
UnitGroup UnitGroup::operator+(const UnitGroup& other) const
{
UnitGroup result=*this;
result+=other;
return result;
}
UnitGroup UnitGroup::operator*(const UnitGroup& other) const
{
UnitGroup result=*this;
result*=other;
return result;
}
UnitGroup UnitGroup::operator^(const UnitGroup& other) const
{
UnitGroup result=*this;
result^=other;
return result;
}
UnitGroup UnitGroup::operator-(const UnitGroup& other) const
{
UnitGroup result=*this;
result-=other;
return result;
}
UnitGroup UnitGroup::operator()(int f1) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (passesFlag(*i,f1))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(int f1, int f2) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (passesFlag(*i,f1) || passesFlag(*i,f2))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(int f1, int f2, int f3) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(int f1, int f2, int f3, int f4) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3) || passesFlag(*i,f4))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(int f1, int f2, int f3, int f4, int f5) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3) || passesFlag(*i,f4) || passesFlag(*i,f5))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FliterAttributeScalar a, const char* compare, double value) const
{
UnitGroup result;
string cmp(compare);
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
double val=getAttribute(*i,a);
bool passes=false;
if (cmp=="=" || cmp=="==" || cmp=="<=" || cmp==">=")
if (val==value)
passes=true;
if (cmp=="<" || cmp=="<=" || cmp=="!=" || cmp=="<>")
if (val<value)
passes=true;
if (cmp==">" || cmp==">=" || cmp=="!=" || cmp=="<>")
if (val>value)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FliterAttributeScalar a, const char* compare, int value) const
{
UnitGroup result;
string cmp(compare);
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
int val=(int)getAttribute(*i,a);
bool passes=false;
if (cmp=="=" || cmp=="==" || cmp=="<=" || cmp==">=")
if (val==value)
passes=true;
if (cmp=="<" || cmp=="<=" || cmp=="!=" || cmp=="<>")
if (val<value)
passes=true;
if (cmp==">" || cmp==">=" || cmp=="!=" || cmp=="<>")
if (val>value)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(BWAPI::Player* player) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if ((*i)->getPlayer()==player)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeUnit a, BWAPI::Unit* unit) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
Unit* target=getUnit(*i,a);
if (target==unit)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeType a, BWAPI::UnitType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetType)
if ((*i)->getType()==type)
passes=true;
if (a==GetInitialType)
if ((*i)->getInitialType()==type)
passes=true;
if (a==GetBuildType)
if ((*i)->getBuildType()==type)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeType a, BWAPI::TechType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetTech)
if ((*i)->getTech()==type)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeOrder a, BWAPI::Order type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetOrder)
if ((*i)->getOrder()==type)
passes=true;
if (a==GetSecondaryOrder)
if ((*i)->getSecondaryOrder()==type)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeType a, BWAPI::UpgradeType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetUpgrade)
if ((*i)->getUpgrade()==type)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributePosition a, BWAPI::Position position) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetPosition)
if ((*i)->getPosition()==position)
passes=true;
if (a==GetInitialPosition)
if ((*i)->getInitialPosition()==position)
passes=true;
if (a==GetTargetPosition)
if ((*i)->getTargetPosition()==position)
passes=true;
if (a==GetRallyPosition)
if ((*i)->getRallyPosition()==position)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::operator()(FilterAttributeTilePosition a, BWAPI::TilePosition position) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetPosition)
if ((*i)->getTilePosition()==position)
passes=true;
if (a==GetInitialPosition)
if ((*i)->getInitialTilePosition()==position)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(int f1) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (!(passesFlag(*i,f1)))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(int f1, int f2) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (!(passesFlag(*i,f1) || passesFlag(*i,f2)))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(int f1, int f2, int f3) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (!(passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3)))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(int f1, int f2, int f3, int f4) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (!(passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3) || passesFlag(*i,f4)))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(int f1, int f2, int f3, int f4, int f5) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (!(passesFlag(*i,f1) || passesFlag(*i,f2) || passesFlag(*i,f3) || passesFlag(*i,f4) || passesFlag(*i,f5)))
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FliterAttributeScalar a, const char* compare, double value) const
{
UnitGroup result;
string cmp(compare);
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
double val=getAttribute(*i,a);
bool passes=false;
if (cmp=="=" || cmp=="==" || cmp=="<=" || cmp==">=")
if (val==value)
passes=true;
if (cmp=="<" || cmp=="<=" || cmp=="!=" || cmp=="<>")
if (val<value)
passes=true;
if (cmp==">" || cmp==">=" || cmp=="!=" || cmp=="<>")
if (val>value)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FliterAttributeScalar a, const char* compare, int value) const
{
UnitGroup result;
string cmp(compare);
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
int val=(int)getAttribute(*i,a);
bool passes=false;
if (cmp=="=" || cmp=="==" || cmp=="<=" || cmp==">=")
if (val==value)
passes=true;
if (cmp=="<" || cmp=="<=" || cmp=="!=" || cmp=="<>")
if (val<value)
passes=true;
if (cmp==">" || cmp==">=" || cmp=="!=" || cmp=="<>")
if (val>value)
passes=true;
if (passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(BWAPI::Player* player) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if ((*i)->getPlayer()!=player)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeUnit a, BWAPI::Unit* unit) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
Unit* target=getUnit(*i,a);
if (target!=unit)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeType a, BWAPI::UnitType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetType)
if ((*i)->getType()==type)
passes=true;
if (a==GetInitialType)
if ((*i)->getInitialType()==type)
passes=true;
if (a==GetBuildType)
if ((*i)->getBuildType()==type)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeType a, BWAPI::TechType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetTech)
if ((*i)->getTech()==type)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeOrder a, BWAPI::Order type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetOrder)
if ((*i)->getOrder()==type)
passes=true;
if (a==GetSecondaryOrder)
if ((*i)->getSecondaryOrder()==type)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeType a, BWAPI::UpgradeType type) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetUpgrade)
if ((*i)->getUpgrade()==type)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributePosition a, BWAPI::Position position) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetPosition)
if ((*i)->getPosition()==position)
passes=true;
if (a==GetInitialPosition)
if ((*i)->getInitialPosition()==position)
passes=true;
if (a==GetTargetPosition)
if ((*i)->getTargetPosition()==position)
passes=true;
if (a==GetRallyPosition)
if ((*i)->getRallyPosition()==position)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::not(FilterAttributeTilePosition a, BWAPI::TilePosition position) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
bool passes=false;
if (a==GetPosition)
if ((*i)->getTilePosition()==position)
passes=true;
if (a==GetInitialPosition)
if ((*i)->getInitialTilePosition()==position)
passes=true;
if (!passes)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::inRadius(double radius,BWAPI::Position position) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if ((*i)->getDistance(position)<=radius)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::inRegion(BWTA::Region* region) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (BWTA::getRegion((*i)->getTilePosition())==region)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::onlyNearestChokepoint(BWTA::Chokepoint* choke) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (BWTA::getNearestChokepoint((*i)->getTilePosition())==choke)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::onlyNearestBaseLocation(BWTA::BaseLocation* location) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (BWTA::getNearestBaseLocation((*i)->getTilePosition())==location)
result.insert(*i);
}
return result;
}
UnitGroup UnitGroup::onlyNearestUnwalkablePolygon(BWTA::Polygon* polygon) const
{
UnitGroup result;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
if (BWTA::getNearestUnwalkablePolygon((*i)->getTilePosition())==polygon)
result.insert(*i);
}
return result;
}
UnitGroup& UnitGroup::operator+=(const UnitGroup& other)
{
for(set<Unit*>::const_iterator i=other.begin();i!=other.end();i++)
this->insert(*i);
return *this;
}
UnitGroup& UnitGroup::operator*=(const UnitGroup& other)
{
set<Unit*>::iterator i2;
for(set<Unit*>::iterator i=this->begin();i!=this->end();i=i2)
{
i2=i;
i2++;
if (!other.contains(*i))
this->erase(*i);
}
return *this;
}
UnitGroup& UnitGroup::operator^=(const UnitGroup& other)
{
UnitGroup result=*this;
for(set<Unit*>::const_iterator i=other.begin();i!=other.end();i++)
{
if (this->contains(*i))
this->erase(*i);
else
this->insert(*i);
}
return *this;
}
UnitGroup& UnitGroup::operator-=(const UnitGroup& other)
{
for(set<Unit*>::const_iterator i=other.begin();i!=other.end();i++)
this->erase(*i);
return *this;
}
BWAPI::Unit* UnitGroup::getNearest(BWAPI::Position position) const
{
if (this->empty()) return NULL;
set<Unit*>::const_iterator i=this->begin();
Unit* result=*i;
double d=(*i)->getDistance(position);
i++;
for(;i!=this->end();i++)
{
double d2=(*i)->getDistance(position);
if (d2<d)
{
d=d2;
result=*i;
}
}
return result;
}
bool UnitGroup::contains(BWAPI::Unit* u) const
{
return this->find(u)!=this->end();
}
Position UnitGroup::getCenter() const
{
if (this->empty())
return Positions::None;
if (this->size()==1)
return ((*this->begin())->getPosition());
int count=0;
double x=0;
double y=0;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
Position p((*i)->getPosition());
if (p!=Positions::None && p!=Positions::Unknown)
{
count++;
x+=p.x();
y+=p.y();
}
}
if (count==0)
{
return Positions::None;
}
return Position((int)(x/count),(int)(y/count));
}
bool UnitGroup::attack(Position position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->attack(position);
}
return retval;
}
bool UnitGroup::attackUnit(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->attack(target);
}
return retval;
}
bool UnitGroup::rightClick(Position position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->rightClick(position);
}
return retval;
}
bool UnitGroup::rightClick(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->rightClick(target);
}
return retval;
}
bool UnitGroup::train(UnitType type) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->train(type);
}
return retval;
}
bool UnitGroup::build(TilePosition position, UnitType type) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->build(position,type);
}
return retval;
}
bool UnitGroup::buildAddon(UnitType type) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->buildAddon(type);
}
return retval;
}
bool UnitGroup::research(TechType tech) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->research(tech);
}
return retval;
}
bool UnitGroup::upgrade(UpgradeType upgrade) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->upgrade(upgrade);
}
return retval;
}
bool UnitGroup::stop() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->stop();
}
return retval;
}
bool UnitGroup::holdPosition() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->holdPosition();
}
return retval;
}
bool UnitGroup::patrol(Position position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->patrol(position);
}
return retval;
}
bool UnitGroup::follow(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->follow(target);
}
return retval;
}
bool UnitGroup::setRallyPoint(Position target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->setRallyPoint(target);
}
return retval;
}
bool UnitGroup::setRallyPoint(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->setRallyPoint(target);
}
return retval;
}
bool UnitGroup::repair(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->repair(target);
}
return retval;
}
bool UnitGroup::morph(UnitType type) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->morph(type);
}
return retval;
}
bool UnitGroup::burrow() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->burrow();
}
return retval;
}
bool UnitGroup::unburrow() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->unburrow();
}
return retval;
}
bool UnitGroup::siege() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->siege();
}
return retval;
}
bool UnitGroup::unsiege() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->unsiege();
}
return retval;
}
bool UnitGroup::cloak() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cloak();
}
return retval;
}
bool UnitGroup::decloak() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->decloak();
}
return retval;
}
bool UnitGroup::lift() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->lift();
}
return retval;
}
bool UnitGroup::land(TilePosition position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->land(position);
}
return retval;
}
bool UnitGroup::load(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->load(target);
}
return retval;
}
bool UnitGroup::unload(Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->unload(target);
}
return retval;
}
bool UnitGroup::unloadAll() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->unloadAll();
}
return retval;
}
bool UnitGroup::unloadAll(Position position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->unloadAll(position);
}
return retval;
}
bool UnitGroup::cancelConstruction() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelConstruction();
}
return retval;
}
bool UnitGroup::haltConstruction() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->haltConstruction();
}
return retval;
}
bool UnitGroup::cancelMorph() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelMorph();
}
return retval;
}
bool UnitGroup::cancelTrain() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelTrain();
}
return retval;
}
bool UnitGroup::cancelTrain(int slot) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelTrain(slot);
}
return retval;
}
bool UnitGroup::cancelAddon() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelAddon();
}
return retval;
}
bool UnitGroup::cancelResearch() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelResearch();
}
return retval;
}
bool UnitGroup::cancelUpgrade() const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->cancelUpgrade();
}
return retval;
}
bool UnitGroup::useTech(TechType tech) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->useTech(tech);
}
return retval;
}
bool UnitGroup::useTech(TechType tech, Position position) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->useTech(tech,position);
}
return retval;
}
bool UnitGroup::useTech(TechType tech, Unit* target) const
{
bool retval=true;
for(set<Unit*>::const_iterator i=this->begin();i!=this->end();i++)
{
retval = retval && (*i)->useTech(tech,target);
}
return retval;
} | SnippyHolloW/BroodwarBotQ | src/Macro/UnitGroup.cpp | C++ | bsd-3-clause | 53,840 |
#include "zvectorgenerator.h"
| stephenplaza/NeuTu | neurolabi/gui/zvectorgenerator.cpp | C++ | bsd-3-clause | 30 |
/*
Copyright (c) 2014, Sam Schetterer, Nathan Kutz, University of Washington
Authors: Sam Schetterer
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DMD_HPP
#define DMD_HPP
#include "defs.hpp"
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/SVD>
template<class T, class mat>
struct eigenval_type{
typedef Eigen::EigenSolver<mat> solver;
};
template<class T, class mat>
struct eigenval_type<std::complex<T>, mat>{
typedef Eigen::ComplexEigenSolver<mat> solver;
};
template<class T, int storage>
using dmat = Eigen::Matrix<T, Dynamic, Dynamic, storage>;
template<class T>
using dvec = Eigen::Matrix<T, Eigen::Dynamic, 1>;
//if invals is in R(n*m+1)
template<class T, int storage, int storage_out1, int storage_out2>
inline void _dmd_(const dmat<T, storage>& invals,
dmat<T, storage_out1>& evecs, dvec<T>& evals, dmat<T, storage_out2>* pod_ptr,
double energy){
//from Tu, theory and application of DMD, we can use the thin models
//(rank of input determines SVD dimensions
Eigen::JacobiSVD<dmat<T, storage>>
svd(invals.rightCols(invals.cols()-1),Eigen::ComputeThinU | Eigen::ComputeThinV);
//trunctuate the svd after a certain energy point
const auto& sing_vals = svd.singularValues();
double ener =sing_vals.squaredNorm();
decltype(svd.nonzeroSingularValues()) num_keep=0;
double ener_cum_sum=0;
while(ener_cum_sum < ener){
ener_cum_sum += sing_vals[num_keep]*sing_vals[num_keep];
num_keep++;
if(num_keep >= svd.nonzeroSingularValues()){
break;
}
}
dmat<T, storage> S(num_keep, num_keep);
//calculate the dmd
S.noalias() = svd.matrixU().leftCols(num_keep).adjoint()*
invals.leftCols(invals.cols()-1)*svd.matrixV().leftCols(num_keep) *
(1.0/svd.singularValues().head(num_keep).array()).matrix().asDiagonal();
//calculate eigenvalues/eigenvectors
eigenval_type<T, dmat<T, storage>::solver esolver(S);
if(esolver.info() != Eigen::Success){
err("Eigenvalues failed to compute", "dmd",
"utils/dmd.hpp", FATAL_ERROR);
}
//calculate the modes from POD and eigenvectors
evecs.noalias() = svd.matrixU().leftolcs(num_keep)*esolver.eigenvectors();
evals = esolver.eigenvalues();
if(pod_ptr){
*(pod_ptr) = svd.matrixU().leftCols(num_keep);
}
}
template<class T, int storage, int storage_out1>
inline void dmd(const dmat<T, storage>& invals,
dmat<T, storage_out1>& evecs, dvec<T>& evals, double energy){
_dmd_(invals, evecs, evals, 0, energy);
}
template<class T, int storage, int storage_out1, int storage_out2>
inline void dmd(const dmat<T, storage>& invals,
dmat<T, storage_out1>& evecs, dvec<T>& evals, dmat<T, storage_out2>& pod_dat,
double energy){
_dmd_(invals, evecs, evals, &pod_dat, energy);
}
template<class matrix>
inline matrix pod(const matrix& invals, double energy=1){
Eigen::JacobiSVD<matrix>
svd(invals.rightCols(invals.cols()-1),Eigen::ComputeThinU);
//from Tu, theory and application of DMD, we can use the thin models
//(rank of input determines SVD dimensions
const auto& sing_vals = svd.singularValues();
double ener =sing_vals.squaredNorm();
decltype(sing_vals.nonzeroSingularValues()) num_keep=0;
double ener_cum_sum=0;
while(ener_cum_sum < ener){
ener_cum_sum += sing_vals[num_keep]*sing_vals[num_keep];
num_keep++;
if(num_keep >= sing_vals.nonzeroSingularValues()){
break;
}
}
return svd.matrixU().leftCols(num_keep);
}
#endif
| UW-Kutz-Lab/lilac | src/utils/dmd.hpp | C++ | bsd-3-clause | 5,032 |
// Copyright 2017 The Crashpad Authors. All rights reserved.
//
// 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.
#include "util/posix/signals.h"
#include <unistd.h>
#include <vector>
#include "base/check_op.h"
#include "base/cxx17_backports.h"
#include "base/logging.h"
namespace crashpad {
namespace {
// These are the core-generating signals.
//
// On macOS, these come from 10.12.3 xnu-3789.41.3/bsd/sys/signalvar.h sigprop:
// entries with SA_CORE are in the set.
//
// For Linux, see linux-4.4.52/kernel/signal.c get_signal() and
// linux-4.4.52/include/linux/signal.h sig_kernel_coredump(): signals in
// SIG_KERNEL_COREDUMP_MASK are in the set.
constexpr int kCrashSignals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGQUIT,
SIGSEGV,
SIGSYS,
SIGTRAP,
#if defined(SIGEMT)
SIGEMT,
#endif // defined(SIGEMT)
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
SIGXCPU,
SIGXFSZ,
#endif // defined(OS_LINUX) || defined(OS_CHROMEOS)
};
// These are the non-core-generating but terminating signals.
//
// On macOS, these come from 10.12.3 xnu-3789.41.3/bsd/sys/signalvar.h sigprop:
// entries with SA_KILL but not SA_CORE are in the set. SIGKILL is excluded
// because it is uncatchable.
//
// For Linux, see linux-4.4.52/kernel/signal.c get_signal() and
// linux-4.4.52/include/linux/signal.h sig_kernel_coredump(),
// sig_kernel_ignore(), and sig_kernel_stop(): signals not in
// SIG_KERNEL_COREDUMP_MASK, SIG_KERNEL_IGNORE_MASK, or SIG_KERNEL_STOP_MASK are
// in the set. SIGKILL is excluded because it is uncatchable (it’s in
// SIG_KERNEL_ONLY_MASK and qualifies for sig_kernel_only()). Real-time signals
// in the range [SIGRTMIN, SIGRTMAX) also have termination as the default
// action, although they are not listed here.
constexpr int kTerminateSignals[] = {
SIGALRM,
SIGHUP,
SIGINT,
SIGPIPE,
SIGPROF,
SIGTERM,
SIGUSR1,
SIGUSR2,
SIGVTALRM,
#if defined(SIGPWR)
SIGPWR,
#endif // defined(SIGPWR)
#if defined(SIGSTKFLT)
SIGSTKFLT,
#endif // defined(SIGSTKFLT)
#if defined(OS_APPLE)
SIGXCPU,
SIGXFSZ,
#endif // defined(OS_APPLE)
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
SIGIO,
#endif // defined(OS_LINUX) || defined(OS_CHROMEOS)
};
bool InstallHandlers(const std::vector<int>& signals,
Signals::Handler handler,
int flags,
Signals::OldActions* old_actions,
const std::set<int>* unhandled_signals) {
bool success = true;
for (int sig : signals) {
if (unhandled_signals &&
unhandled_signals->find(sig) != unhandled_signals->end()) {
continue;
}
success &= Signals::InstallHandler(
sig,
handler,
flags,
old_actions ? old_actions->ActionForSignal(sig) : nullptr);
}
return success;
}
bool IsSignalInSet(int sig, const int* set, size_t set_size) {
for (size_t index = 0; index < set_size; ++index) {
if (sig == set[index]) {
return true;
}
}
return false;
}
} // namespace
struct sigaction* Signals::OldActions::ActionForSignal(int sig) {
DCHECK_GT(sig, 0);
const size_t slot = sig - 1;
DCHECK_LT(slot, base::size(actions_));
return &actions_[slot];
}
// static
bool Signals::InstallHandler(int sig,
Handler handler,
int flags,
struct sigaction* old_action) {
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = flags | SA_SIGINFO;
action.sa_sigaction = handler;
if (sigaction(sig, &action, old_action) != 0) {
PLOG(ERROR) << "sigaction " << sig;
return false;
}
return true;
}
// static
bool Signals::InstallDefaultHandler(int sig) {
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = SIG_DFL;
return sigaction(sig, &action, nullptr) == 0;
}
// static
bool Signals::InstallCrashHandlers(Handler handler,
int flags,
OldActions* old_actions,
const std::set<int>* unhandled_signals) {
return InstallHandlers(
std::vector<int>(kCrashSignals,
kCrashSignals + base::size(kCrashSignals)),
handler,
flags,
old_actions,
unhandled_signals);
}
// static
bool Signals::InstallTerminateHandlers(Handler handler,
int flags,
OldActions* old_actions) {
return InstallHandlers(
std::vector<int>(kTerminateSignals,
kTerminateSignals + base::size(kTerminateSignals)),
handler,
flags,
old_actions,
nullptr);
}
// static
bool Signals::WillSignalReraiseAutonomously(const siginfo_t* siginfo) {
// Signals received other than via hardware faults, such as those raised
// asynchronously via kill() and raise(), and those arising via hardware traps
// such as int3 on x86 (resulting in SIGTRAP but advancing the instruction
// pointer), will not reoccur on their own when returning from the signal
// handler.
//
// Unfortunately, on macOS, when SIGBUS (on all CPUs) and SIGILL and SIGSEGV
// (on arm64) is received asynchronously via kill(), siginfo->si_code makes it
// appear as though it was actually received via a hardware fault. See 10.15.6
// xnu-6153.141.1/bsd/dev/i386/unix_signal.c sendsig() and 10.15.6
// xnu-6153.141.1/bsd/dev/arm/unix_signal.c sendsig(). Received
// asynchronously, these signals will not re-raise themselves autonomously,
// but this function (acting on information from the kernel) behaves as though
// they will. This isn’t ideal, but these signals occurring asynchronously is
// an unexpected condition. The alternative, to never treat these signals as
// autonomously re-raising, is a bad idea because the explicit re-raise would
// lose properties associated with the the original signal, which are valuable
// for debugging and are visible to a Mach exception handler. Since these
// signals are normally received synchronously in response to a hardware
// fault, don’t sweat the unexpected asynchronous case.
//
// SIGSEGV on macOS on x86[_64] originating from a general protection fault is
// a more difficult case: si_code is cleared, making the signal appear
// asynchronous. See 10.15.6 xnu-6153.141.1/bsd/dev/i386/unix_signal.c
// sendsig().
const int sig = siginfo->si_signo;
const int code = siginfo->si_code;
// Only these signals can be generated from hardware faults and can re-raise
// autonomously.
return (sig == SIGBUS ||
sig == SIGFPE ||
sig == SIGILL ||
sig == SIGSEGV) &&
// The signal was only generated from a hardware fault if the code is a
// positive number not matching one of these SI_* constants. See
// “Signal Actions” under XRAT “Rationale”/B.2.4 “Signal Concepts” in
// POSIX.1-2008, 2016 Edition, regarding si_code. The historical
// behavior does not use these SI_* constants and signals generated
// asynchronously show up with a code of 0. On macOS, the SI_*
// constants are defined but never used, and the historical value of 0
// remains. See 10.12.3 xnu-3789.41.3/bsd/kern/kern_sig.c
// psignal_internal().
(code > 0 &&
code != SI_ASYNCIO &&
code != SI_MESGQ &&
code != SI_QUEUE &&
code != SI_TIMER &&
code != SI_USER &&
#if defined(SI_DETHREAD)
code != SI_DETHREAD &&
#endif // defiend(SI_DETHREAD)
#if defined(SI_KERNEL)
// In Linux, SI_KERNEL is used for signals that are raised by the
// kernel in software, opposing SI_USER. See
// linux-4.4.52/kernel/signal.c __send_signal(). Signals originating
// from hardware faults do not use this SI_KERNEL, but a proper signal
// code translated in architecture-specific code from the
// characteristics of the hardware fault.
code != SI_KERNEL &&
#endif // defined(SI_KERNEL)
#if defined(SI_SIGIO)
code != SI_SIGIO &&
#endif // defined(SI_SIGIO)
#if defined(SI_TKILL)
code != SI_TKILL &&
#endif // defined(SI_TKILL)
true);
}
// static
void Signals::RestoreHandlerAndReraiseSignalOnReturn(
const siginfo_t* siginfo,
const struct sigaction* old_action) {
// Failures in this function should _exit(kFailureExitCode). This is a quick
// and quiet failure. This function runs in signal handler context, and it’s
// difficult to safely be loud from a signal handler.
constexpr int kFailureExitCode = 191;
struct sigaction default_action;
sigemptyset(&default_action.sa_mask);
default_action.sa_flags = 0;
default_action.sa_handler = SIG_DFL;
const struct sigaction* restore_action =
old_action ? old_action : &default_action;
// Try to restore restore_action. If that fails and restore_action was
// old_action, the problem may have been that old_action was bogus, so try to
// set the default action.
const int sig = siginfo->si_signo;
if (sigaction(sig, restore_action, nullptr) != 0 && old_action &&
sigaction(sig, &default_action, nullptr) != 0) {
_exit(kFailureExitCode);
}
// Explicitly re-raise the signal if it will not re-raise itself. Because
// signal handlers normally execute with their signal blocked, this raise()
// cannot immediately deliver the signal. Delivery is deferred until the
// signal handler returns and the signal becomes unblocked. The re-raised
// signal will appear with the same context as where it was initially
// triggered.
if (!WillSignalReraiseAutonomously(siginfo) && raise(sig) != 0) {
_exit(kFailureExitCode);
}
}
// static
bool Signals::IsCrashSignal(int sig) {
return IsSignalInSet(sig, kCrashSignals, base::size(kCrashSignals));
}
// static
bool Signals::IsTerminateSignal(int sig) {
return IsSignalInSet(sig, kTerminateSignals, base::size(kTerminateSignals));
}
} // namespace crashpad
| scheib/chromium | third_party/crashpad/crashpad/util/posix/signals.cc | C++ | bsd-3-clause | 10,661 |
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u2d5c\u2d49\u2d3c\u2d30\u2d61\u2d5c",
"\u2d5c\u2d30\u2d37\u2d33\u2d33\u2d6f\u2d30\u2d5c"
],
"DAY": [
"\u2d30\u2d59\u2d30\u2d4e\u2d30\u2d59",
"\u2d30\u2d62\u2d4f\u2d30\u2d59",
"\u2d30\u2d59\u2d49\u2d4f\u2d30\u2d59",
"\u2d30\u2d3d\u2d55\u2d30\u2d59",
"\u2d30\u2d3d\u2d61\u2d30\u2d59",
"\u2d30\u2d59\u2d49\u2d4e\u2d61\u2d30\u2d59",
"\u2d30\u2d59\u2d49\u2d39\u2d62\u2d30\u2d59"
],
"ERANAMES": [
"\u2d37\u2d30\u2d5c \u2d4f \u2d44\u2d49\u2d59\u2d30",
"\u2d37\u2d3c\u2d3c\u2d49\u2d54 \u2d4f \u2d44\u2d49\u2d59\u2d30"
],
"ERAS": [
"\u2d37\u2d30\u2d44",
"\u2d37\u2d3c\u2d44"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54",
"\u2d31\u2d55\u2d30\u2d62\u2d55",
"\u2d4e\u2d30\u2d55\u2d5a",
"\u2d49\u2d31\u2d54\u2d49\u2d54",
"\u2d4e\u2d30\u2d62\u2d62\u2d53",
"\u2d62\u2d53\u2d4f\u2d62\u2d53",
"\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63",
"\u2d56\u2d53\u2d5b\u2d5c",
"\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54",
"\u2d3d\u2d5c\u2d53\u2d31\u2d54",
"\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54",
"\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54"
],
"SHORTDAY": [
"\u2d30\u2d59\u2d30",
"\u2d30\u2d62\u2d4f",
"\u2d30\u2d59\u2d49",
"\u2d30\u2d3d\u2d55",
"\u2d30\u2d3d\u2d61",
"\u2d30\u2d59\u2d49\u2d4e",
"\u2d30\u2d59\u2d49\u2d39"
],
"SHORTMONTH": [
"\u2d49\u2d4f\u2d4f",
"\u2d31\u2d55\u2d30",
"\u2d4e\u2d30\u2d55",
"\u2d49\u2d31\u2d54",
"\u2d4e\u2d30\u2d62",
"\u2d62\u2d53\u2d4f",
"\u2d62\u2d53\u2d4d",
"\u2d56\u2d53\u2d5b",
"\u2d5b\u2d53\u2d5c",
"\u2d3d\u2d5c\u2d53",
"\u2d4f\u2d53\u2d61",
"\u2d37\u2d53\u2d4a"
],
"STANDALONEMONTH": [
"\u2d49\u2d4f\u2d4f\u2d30\u2d62\u2d54",
"\u2d31\u2d55\u2d30\u2d62\u2d55",
"\u2d4e\u2d30\u2d55\u2d5a",
"\u2d49\u2d31\u2d54\u2d49\u2d54",
"\u2d4e\u2d30\u2d62\u2d62\u2d53",
"\u2d62\u2d53\u2d4f\u2d62\u2d53",
"\u2d62\u2d53\u2d4d\u2d62\u2d53\u2d63",
"\u2d56\u2d53\u2d5b\u2d5c",
"\u2d5b\u2d53\u2d5c\u2d30\u2d4f\u2d31\u2d49\u2d54",
"\u2d3d\u2d5c\u2d53\u2d31\u2d54",
"\u2d4f\u2d53\u2d61\u2d30\u2d4f\u2d31\u2d49\u2d54",
"\u2d37\u2d53\u2d4a\u2d30\u2d4f\u2d31\u2d49\u2d54"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM, y HH:mm:ss",
"mediumDate": "d MMM, y",
"mediumTime": "HH:mm:ss",
"short": "d/M/y HH:mm",
"shortDate": "d/M/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "dh",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a4",
"posPre": "",
"posSuf": "\u00a4"
}
]
},
"id": "zgh-ma",
"localeID": "zgh_MA",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v == 0) {
return PLURAL_CATEGORY.ONE;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]);
| mudunuriRaju/tlr-live | tollbackend/web/js/angular-1.5.5/i18n/angular-locale_zgh-ma.js | JavaScript | bsd-3-clause | 5,388 |
# Copyright 2017, Google Inc. All rights reserved.
#
# 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.
require "google/cloud/speech/v1beta1/speech_client"
module Google
module Cloud
# rubocop:disable LineLength
##
# # Ruby Client for Google Cloud Speech API ([Alpha](https://github.com/GoogleCloudPlatform/google-cloud-ruby#versioning))
#
# [Google Cloud Speech API][Product Documentation]: Google Cloud Speech API.
# - [Product Documentation][]
#
# ## Quick Start
# In order to use this library, you first need to go through the following steps:
#
# 1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project)
# 2. [Enable the Google Cloud Speech API.](https://console.cloud.google.com/apis/api/speech)
# 3. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud/master/guides/authentication)
#
# ### Installation
# ```
# $ gem install google-cloud-speech
# ```
#
# ### Preview
# #### SpeechClient
# ```rb
# require "google/cloud/speech/v1beta1"
#
# speech_client = Google::Cloud::Speech::V1beta1.new
# language_code = "en-US"
# sample_rate = 44100
# encoding = :FLAC
# config = {
# language_code: language_code,
# sample_rate: sample_rate,
# encoding: encoding
# }
# uri = "gs://gapic-toolkit/hello.flac"
# audio = { uri: uri }
# response = speech_client.sync_recognize(config, audio)
# ```
#
# ### Next Steps
# - Read the [Google Cloud Speech API Product documentation][Product Documentation] to learn more about the product and see How-to Guides.
# - View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-ruby/blob/master/README.md) to see the full list of Cloud APIs that we cover.
#
# [Product Documentation]: https://cloud.google.com/speech
#
#
module Speech
##
# # Google Cloud Speech API Contents
#
# | Class | Description |
# | ----- | ----------- |
# | [SpeechClient][] | Google Cloud Speech API. |
# | [Data Types][] | Data types for Google::Cloud::Speech::V1beta1 |
#
# [SpeechClient]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-speech/latest/google/cloud/speech/v1beta1/v1beta1/speechclient
# [Data Types]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-speech/latest/google/cloud/speech/v1beta1/v1beta1/datatypes
#
module V1beta1
# rubocop:enable LineLength
##
# Service that implements Google Cloud Speech API.
#
# @param service_path [String]
# The domain name of the API remote host.
# @param port [Integer]
# The port on which to connect to the remote host.
# @param credentials
# [Google::Gax::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc]
# Provides the means for authenticating requests made by the client. This parameter can
# be many types.
# A `Google::Gax::Credentials` uses a the properties of its represented keyfile for
# authenticating requests made by this client.
# A `String` will be treated as the path to the keyfile to be used for the construction of
# credentials for this client.
# A `Hash` will be treated as the contents of a keyfile to be used for the construction of
# credentials for this client.
# A `GRPC::Core::Channel` will be used to make calls through.
# A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The channel credentials
# should already be composed with a `GRPC::Core::CallCredentials` object.
# A `Proc` will be used as an updater_proc for the Grpc channel. The proc transforms the
# metadata for requests, generally, to give OAuth credentials.
# @param scopes [Array<String>]
# The OAuth scopes for this service. This parameter is ignored if
# an updater_proc is supplied.
# @param client_config[Hash]
# A Hash for call options for each method. See
# Google::Gax#construct_settings for the structure of
# this data. Falls back to the default config if not specified
# or the specified config is missing data points.
# @param timeout [Numeric]
# The default timeout, in seconds, for calls made through this client.
def self.new(*args, **kwargs)
Google::Cloud::Speech::V1beta1::SpeechClient.new(*args, **kwargs)
end
end
end
end
end | eoogbe/api-client-staging | generated/ruby/google-cloud-speech-v1beta1/lib/google/cloud/speech/v1beta1.rb | Ruby | bsd-3-clause | 5,231 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/socket_posix.h"
#include <errno.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <utility>
#include "base/callback_helpers.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/posix/eintr_wrapper.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/sockaddr_storage.h"
namespace net {
namespace {
int MapAcceptError(int os_error) {
switch (os_error) {
// If the client aborts the connection before the server calls accept,
// POSIX specifies accept should fail with ECONNABORTED. The server can
// ignore the error and just call accept again, so we map the error to
// ERR_IO_PENDING. See UNIX Network Programming, Vol. 1, 3rd Ed., Sec.
// 5.11, "Connection Abort before accept Returns".
case ECONNABORTED:
return ERR_IO_PENDING;
default:
return MapSystemError(os_error);
}
}
int MapConnectError(int os_error) {
switch (os_error) {
case EINPROGRESS:
return ERR_IO_PENDING;
case EACCES:
return ERR_NETWORK_ACCESS_DENIED;
case ETIMEDOUT:
return ERR_CONNECTION_TIMED_OUT;
default: {
int net_error = MapSystemError(os_error);
if (net_error == ERR_FAILED)
return ERR_CONNECTION_FAILED; // More specific than ERR_FAILED.
return net_error;
}
}
}
} // namespace
SocketPosix::SocketPosix()
: socket_fd_(kInvalidSocket),
read_buf_len_(0),
write_buf_len_(0),
waiting_connect_(false) {}
SocketPosix::~SocketPosix() {
Close();
}
int SocketPosix::Open(int address_family) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(kInvalidSocket, socket_fd_);
DCHECK(address_family == AF_INET ||
address_family == AF_INET6 ||
address_family == AF_UNIX);
socket_fd_ = CreatePlatformSocket(
address_family,
SOCK_STREAM,
address_family == AF_UNIX ? 0 : IPPROTO_TCP);
if (socket_fd_ < 0) {
PLOG(ERROR) << "CreatePlatformSocket() returned an error, errno=" << errno;
return MapSystemError(errno);
}
if (!base::SetNonBlocking(socket_fd_)) {
int rv = MapSystemError(errno);
Close();
return rv;
}
return OK;
}
int SocketPosix::AdoptConnectedSocket(SocketDescriptor socket,
const SockaddrStorage& address) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(kInvalidSocket, socket_fd_);
socket_fd_ = socket;
if (!base::SetNonBlocking(socket_fd_)) {
int rv = MapSystemError(errno);
Close();
return rv;
}
SetPeerAddress(address);
return OK;
}
SocketDescriptor SocketPosix::ReleaseConnectedSocket() {
StopWatchingAndCleanUp();
SocketDescriptor socket_fd = socket_fd_;
socket_fd_ = kInvalidSocket;
return socket_fd;
}
int SocketPosix::Bind(const SockaddrStorage& address) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
int rv = bind(socket_fd_, address.addr, address.addr_len);
if (rv < 0) {
PLOG(ERROR) << "bind() returned an error, errno=" << errno;
return MapSystemError(errno);
}
return OK;
}
int SocketPosix::Listen(int backlog) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK_LT(0, backlog);
int rv = listen(socket_fd_, backlog);
if (rv < 0) {
PLOG(ERROR) << "listen() returned an error, errno=" << errno;
return MapSystemError(errno);
}
return OK;
}
int SocketPosix::Accept(std::unique_ptr<SocketPosix>* socket,
const CompletionCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK(accept_callback_.is_null());
DCHECK(socket);
DCHECK(!callback.is_null());
int rv = DoAccept(socket);
if (rv != ERR_IO_PENDING)
return rv;
if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
socket_fd_, true, base::MessageLoopForIO::WATCH_READ,
&accept_socket_watcher_, this)) {
PLOG(ERROR) << "WatchFileDescriptor failed on accept, errno " << errno;
return MapSystemError(errno);
}
accept_socket_ = socket;
accept_callback_ = callback;
return ERR_IO_PENDING;
}
int SocketPosix::Connect(const SockaddrStorage& address,
const CompletionCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK(!waiting_connect_);
DCHECK(!callback.is_null());
SetPeerAddress(address);
int rv = DoConnect();
if (rv != ERR_IO_PENDING)
return rv;
if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
socket_fd_, true, base::MessageLoopForIO::WATCH_WRITE,
&write_socket_watcher_, this)) {
PLOG(ERROR) << "WatchFileDescriptor failed on connect, errno " << errno;
return MapSystemError(errno);
}
write_callback_ = callback;
waiting_connect_ = true;
return ERR_IO_PENDING;
}
bool SocketPosix::IsConnected() const {
DCHECK(thread_checker_.CalledOnValidThread());
if (socket_fd_ == kInvalidSocket || waiting_connect_)
return false;
// Checks if connection is alive.
char c;
int rv = HANDLE_EINTR(recv(socket_fd_, &c, 1, MSG_PEEK));
if (rv == 0)
return false;
if (rv == -1 && errno != EAGAIN && errno != EWOULDBLOCK)
return false;
return true;
}
bool SocketPosix::IsConnectedAndIdle() const {
DCHECK(thread_checker_.CalledOnValidThread());
if (socket_fd_ == kInvalidSocket || waiting_connect_)
return false;
// Check if connection is alive and we haven't received any data
// unexpectedly.
char c;
int rv = HANDLE_EINTR(recv(socket_fd_, &c, 1, MSG_PEEK));
if (rv >= 0)
return false;
if (errno != EAGAIN && errno != EWOULDBLOCK)
return false;
return true;
}
int SocketPosix::Read(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK(!waiting_connect_);
CHECK(read_callback_.is_null());
// Synchronous operation not supported
DCHECK(!callback.is_null());
DCHECK_LT(0, buf_len);
int rv = DoRead(buf, buf_len);
if (rv != ERR_IO_PENDING)
return rv;
if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
socket_fd_, true, base::MessageLoopForIO::WATCH_READ,
&read_socket_watcher_, this)) {
PLOG(ERROR) << "WatchFileDescriptor failed on read, errno " << errno;
return MapSystemError(errno);
}
read_buf_ = buf;
read_buf_len_ = buf_len;
read_callback_ = callback;
return ERR_IO_PENDING;
}
int SocketPosix::Write(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK(!waiting_connect_);
CHECK(write_callback_.is_null());
// Synchronous operation not supported
DCHECK(!callback.is_null());
DCHECK_LT(0, buf_len);
int rv = DoWrite(buf, buf_len);
if (rv == ERR_IO_PENDING)
rv = WaitForWrite(buf, buf_len, callback);
return rv;
}
int SocketPosix::WaitForWrite(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_NE(kInvalidSocket, socket_fd_);
DCHECK(write_callback_.is_null());
// Synchronous operation not supported
DCHECK(!callback.is_null());
DCHECK_LT(0, buf_len);
if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
socket_fd_, true, base::MessageLoopForIO::WATCH_WRITE,
&write_socket_watcher_, this)) {
PLOG(ERROR) << "WatchFileDescriptor failed on write, errno " << errno;
return MapSystemError(errno);
}
write_buf_ = buf;
write_buf_len_ = buf_len;
write_callback_ = callback;
return ERR_IO_PENDING;
}
int SocketPosix::GetLocalAddress(SockaddrStorage* address) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(address);
if (getsockname(socket_fd_, address->addr, &address->addr_len) < 0)
return MapSystemError(errno);
return OK;
}
int SocketPosix::GetPeerAddress(SockaddrStorage* address) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(address);
if (!HasPeerAddress())
return ERR_SOCKET_NOT_CONNECTED;
*address = *peer_address_;
return OK;
}
void SocketPosix::SetPeerAddress(const SockaddrStorage& address) {
DCHECK(thread_checker_.CalledOnValidThread());
// |peer_address_| will be non-NULL if Connect() has been called. Unless
// Close() is called to reset the internal state, a second call to Connect()
// is not allowed.
// Please note that we don't allow a second Connect() even if the previous
// Connect() has failed. Connecting the same |socket_| again after a
// connection attempt failed results in unspecified behavior according to
// POSIX.
DCHECK(!peer_address_);
peer_address_.reset(new SockaddrStorage(address));
}
bool SocketPosix::HasPeerAddress() const {
DCHECK(thread_checker_.CalledOnValidThread());
return peer_address_ != NULL;
}
void SocketPosix::Close() {
DCHECK(thread_checker_.CalledOnValidThread());
StopWatchingAndCleanUp();
if (socket_fd_ != kInvalidSocket) {
if (IGNORE_EINTR(close(socket_fd_)) < 0)
PLOG(ERROR) << "close() returned an error, errno=" << errno;
socket_fd_ = kInvalidSocket;
}
}
void SocketPosix::DetachFromThread() {
thread_checker_.DetachFromThread();
}
void SocketPosix::OnFileCanReadWithoutBlocking(int fd) {
TRACE_EVENT0("net", "SocketPosix::OnFileCanReadWithoutBlocking");
DCHECK(!accept_callback_.is_null() || !read_callback_.is_null());
if (!accept_callback_.is_null()) {
AcceptCompleted();
} else { // !read_callback_.is_null()
ReadCompleted();
}
}
void SocketPosix::OnFileCanWriteWithoutBlocking(int fd) {
DCHECK(!write_callback_.is_null());
if (waiting_connect_) {
ConnectCompleted();
} else {
WriteCompleted();
}
}
int SocketPosix::DoAccept(std::unique_ptr<SocketPosix>* socket) {
SockaddrStorage new_peer_address;
int new_socket = HANDLE_EINTR(accept(socket_fd_,
new_peer_address.addr,
&new_peer_address.addr_len));
if (new_socket < 0)
return MapAcceptError(errno);
std::unique_ptr<SocketPosix> accepted_socket(new SocketPosix);
int rv = accepted_socket->AdoptConnectedSocket(new_socket, new_peer_address);
if (rv != OK)
return rv;
*socket = std::move(accepted_socket);
return OK;
}
void SocketPosix::AcceptCompleted() {
DCHECK(accept_socket_);
int rv = DoAccept(accept_socket_);
if (rv == ERR_IO_PENDING)
return;
bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
accept_socket_ = NULL;
base::ResetAndReturn(&accept_callback_).Run(rv);
}
int SocketPosix::DoConnect() {
int rv = HANDLE_EINTR(connect(socket_fd_,
peer_address_->addr,
peer_address_->addr_len));
DCHECK_GE(0, rv);
return rv == 0 ? OK : MapConnectError(errno);
}
void SocketPosix::ConnectCompleted() {
// Get the error that connect() completed with.
int os_error = 0;
socklen_t len = sizeof(os_error);
if (getsockopt(socket_fd_, SOL_SOCKET, SO_ERROR, &os_error, &len) == 0) {
// TCPSocketPosix expects errno to be set.
errno = os_error;
}
int rv = MapConnectError(errno);
if (rv == ERR_IO_PENDING)
return;
bool ok = write_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
waiting_connect_ = false;
base::ResetAndReturn(&write_callback_).Run(rv);
}
int SocketPosix::DoRead(IOBuffer* buf, int buf_len) {
int rv = HANDLE_EINTR(read(socket_fd_, buf->data(), buf_len));
return rv >= 0 ? rv : MapSystemError(errno);
}
void SocketPosix::ReadCompleted() {
int rv = DoRead(read_buf_.get(), read_buf_len_);
if (rv == ERR_IO_PENDING)
return;
bool ok = read_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
read_buf_ = NULL;
read_buf_len_ = 0;
base::ResetAndReturn(&read_callback_).Run(rv);
}
int SocketPosix::DoWrite(IOBuffer* buf, int buf_len) {
#if defined(OS_LINUX) || defined(OS_ANDROID)
// Disable SIGPIPE for this write. Although Chromium globally disables
// SIGPIPE, the net stack may be used in other consumers which do not do
// this. MSG_NOSIGNAL is a Linux-only API. On OS X, this is a setsockopt on
// socket creation.
int rv = HANDLE_EINTR(send(socket_fd_, buf->data(), buf_len, MSG_NOSIGNAL));
#else
int rv = HANDLE_EINTR(write(socket_fd_, buf->data(), buf_len));
#endif
return rv >= 0 ? rv : MapSystemError(errno);
}
void SocketPosix::WriteCompleted() {
int rv = DoWrite(write_buf_.get(), write_buf_len_);
if (rv == ERR_IO_PENDING)
return;
bool ok = write_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
write_buf_ = NULL;
write_buf_len_ = 0;
base::ResetAndReturn(&write_callback_).Run(rv);
}
void SocketPosix::StopWatchingAndCleanUp() {
bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
ok = read_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
ok = write_socket_watcher_.StopWatchingFileDescriptor();
DCHECK(ok);
if (!accept_callback_.is_null()) {
accept_socket_ = NULL;
accept_callback_.Reset();
}
if (!read_callback_.is_null()) {
read_buf_ = NULL;
read_buf_len_ = 0;
read_callback_.Reset();
}
if (!write_callback_.is_null()) {
write_buf_ = NULL;
write_buf_len_ = 0;
write_callback_.Reset();
}
waiting_connect_ = false;
peer_address_.reset();
}
} // namespace net
| danakj/chromium | net/socket/socket_posix.cc | C++ | bsd-3-clause | 13,989 |
export async function getNodeSummary(nodeId, nodeType) {
const bioentityUrl = `${biolink}bioentity/${nodeType}/${nodeId}`;
console.log('getNodeSummary bioentityUrl', nodeId, nodeType, bioentityUrl);
const params = {
fetch_objects: true,
unselect_evidence: false,
exclude_automatic_assertions: false,
use_compact_associations: false,
rows: 100,
};
const resp = await axios.get(bioentityUrl, { params });
const responseData = resp.data;
const graphUrl = `${biolink}graph/node/${nodeId}`;
const graphResponse = await axios.get(graphUrl);
const graphResponseData = graphResponse.data;
responseData.edges = graphResponseData.edges;
responseData.nodes = graphResponseData.nodes;
return responseData;
}
| kshefchek/monarch-app | ui/monarchAccess/demo.js | JavaScript | bsd-3-clause | 745 |
package com.oracle.ptsdemo.healthcare.wsclient.osc.salesparty.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="organizationParty" type="{http://xmlns.oracle.com/apps/cdm/foundation/parties/organizationService/}OrganizationParty"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"organizationParty"
})
@XmlRootElement(name = "createOrganizationPartyAsync")
public class CreateOrganizationPartyAsync {
@XmlElement(required = true)
protected OrganizationParty organizationParty;
/**
* Gets the value of the organizationParty property.
*
* @return
* possible object is
* {@link OrganizationParty }
*
*/
public OrganizationParty getOrganizationParty() {
return organizationParty;
}
/**
* Sets the value of the organizationParty property.
*
* @param value
* allowed object is
* {@link OrganizationParty }
*
*/
public void setOrganizationParty(OrganizationParty value) {
this.organizationParty = value;
}
}
| dushmis/Oracle-Cloud | PaaS-SaaS_HealthCareApp/DoctorPatientCRMExtension/HealthCare/HealthCareWSProxyClient/src/com/oracle/ptsdemo/healthcare/wsclient/osc/salesparty/generated/CreateOrganizationPartyAsync.java | Java | bsd-3-clause | 1,729 |
import git
from git.exc import InvalidGitRepositoryError
from git.config import GitConfigParser
from io import BytesIO
import weakref
# typing -----------------------------------------------------------------------
from typing import Any, Sequence, TYPE_CHECKING, Union
from git.types import PathLike
if TYPE_CHECKING:
from .base import Submodule
from weakref import ReferenceType
from git.repo import Repo
from git.refs import Head
from git import Remote
from git.refs import RemoteReference
__all__ = ('sm_section', 'sm_name', 'mkhead', 'find_first_remote_branch',
'SubmoduleConfigParser')
#{ Utilities
def sm_section(name: str) -> str:
""":return: section title used in .gitmodules configuration file"""
return f'submodule "{name}"'
def sm_name(section: str) -> str:
""":return: name of the submodule as parsed from the section name"""
section = section.strip()
return section[11:-1]
def mkhead(repo: 'Repo', path: PathLike) -> 'Head':
""":return: New branch/head instance"""
return git.Head(repo, git.Head.to_full_path(path))
def find_first_remote_branch(remotes: Sequence['Remote'], branch_name: str) -> 'RemoteReference':
"""Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError"""
for remote in remotes:
try:
return remote.refs[branch_name]
except IndexError:
continue
# END exception handling
# END for remote
raise InvalidGitRepositoryError("Didn't find remote branch '%r' in any of the given remotes" % branch_name)
#} END utilities
#{ Classes
class SubmoduleConfigParser(GitConfigParser):
"""
Catches calls to _write, and updates the .gitmodules blob in the index
with the new data, if we have written into a stream. Otherwise it will
add the local file to the index to make it correspond with the working tree.
Additionally, the cache must be cleared
Please note that no mutating method will work in bare mode
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._smref: Union['ReferenceType[Submodule]', None] = None
self._index = None
self._auto_write = True
super(SubmoduleConfigParser, self).__init__(*args, **kwargs)
#{ Interface
def set_submodule(self, submodule: 'Submodule') -> None:
"""Set this instance's submodule. It must be called before
the first write operation begins"""
self._smref = weakref.ref(submodule)
def flush_to_index(self) -> None:
"""Flush changes in our configuration file to the index"""
assert self._smref is not None
# should always have a file here
assert not isinstance(self._file_or_files, BytesIO)
sm = self._smref()
if sm is not None:
index = self._index
if index is None:
index = sm.repo.index
# END handle index
index.add([sm.k_modules_file], write=self._auto_write)
sm._clear_cache()
# END handle weakref
#} END interface
#{ Overridden Methods
def write(self) -> None: # type: ignore[override]
rval: None = super(SubmoduleConfigParser, self).write()
self.flush_to_index()
return rval
# END overridden methods
#} END classes
| gitpython-developers/GitPython | git/objects/submodule/util.py | Python | bsd-3-clause | 3,358 |
<?php
namespace BecklynLayout\Model;
use BecklynLayout\Entity\Download;
/**
*
*/
class DownloadModel
{
/**
* @var string
*/
private $downloadDir;
/**
* Relative to web/
*/
const RELATIVE_DOWNLOAD_DIR = "downloads";
/**
* @param $baseDir
*/
public function __construct ($baseDir)
{
$this->downloadDir = rtrim($baseDir, "/") . "/web/" . self::RELATIVE_DOWNLOAD_DIR;
}
/**
* Returns a list of all downloads
*
* @return Download[]
*/
public function getAllDownloads ()
{
try
{
$directoryIterator = new \DirectoryIterator($this->downloadDir);
$downloads = [];
foreach ($directoryIterator as $file)
{
if (!$file->isFile())
{
continue;
}
// skip hidden files
if ("." === $file->getBasename()[0])
{
continue;
}
$downloads[$file->getFilename()] = new Download($file, self::RELATIVE_DOWNLOAD_DIR);
}
ksort($downloads);
return $downloads;
}
catch (\UnexpectedValueException $e)
{
return [];
}
}
}
| Becklyn/Gluggi | src/Model/DownloadModel.php | PHP | bsd-3-clause | 1,330 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__CWE839_fscanf_83_bad.cpp
Label Definition File: CWE127_Buffer_Underread__CWE839.label.xml
Template File: sources-sinks-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 127 Buffer Underread
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Non-negative but less than 10
* Sinks:
* GoodSink: Ensure the array index is valid
* BadSink : Improperly check the array index by not checking to see if the value is negative
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE127_Buffer_Underread__CWE839_fscanf_83.h"
namespace CWE127_Buffer_Underread__CWE839_fscanf_83
{
CWE127_Buffer_Underread__CWE839_fscanf_83_bad::CWE127_Buffer_Underread__CWE839_fscanf_83_bad(int dataCopy)
{
data = dataCopy;
/* POTENTIAL FLAW: Read data from the console using fscanf() */
fscanf(stdin, "%d", &data);
}
CWE127_Buffer_Underread__CWE839_fscanf_83_bad::~CWE127_Buffer_Underread__CWE839_fscanf_83_bad()
{
{
int buffer[10] = { 0 };
/* POTENTIAL FLAW: Attempt to access a negative index of the array
* This check does not check to see if the array index is negative */
if (data < 10)
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is too big.");
}
}
}
}
#endif /* OMITBAD */
| JianpingZeng/xcc | xcc/test/juliet/testcases/CWE127_Buffer_Underread/s01/CWE127_Buffer_Underread__CWE839_fscanf_83_bad.cpp | C++ | bsd-3-clause | 1,578 |
package com.flat502.rox.server;
import java.nio.channels.SocketChannel;
import com.flat502.rox.processing.SSLSession;
/**
* A very simple accept policy interface.
* <p>
* An instance of this interface may be associated with an instance
* of {@link com.flat502.rox.server.HttpRpcServer}. After a new SSL connection has
* completed handshaking the installed {@link SSLSessionPolicy}
* is consulted to check if the SSL session should be retained.
* <p>
* If policy dictates that the connection not be retained it is closed
* immediately.
*/
public interface SSLSessionPolicy {
/**
* Consulted to determine whether or not the given
* {@link SSLSession} should be retained.
* <p>
* Implementations should avoid any calls on the channel
* that may block. Blocking the calling thread will have
* a significant impact on throughput on the server.
* @param channel
* The {@link SocketChannel} that has just been
* accepted.
* @param session
* The {@link SSLSession} that has just completed
* handshaking.
* @return
* <code>true</code> if the channel should be retained,
* or <code>false</code> if it should be closed and
* discarded.
*/
public boolean shouldRetain(SocketChannel channel, SSLSession session);
}
| cameronbraid/rox | src/main/java/com/flat502/rox/server/SSLSessionPolicy.java | Java | bsd-3-clause | 1,296 |
<?php defined('SYSPATH') OR die('No direct script access.');
/**
* Copyright © 2011–2013 Spadefoot Team.
* Copyright © 2012 CubedEye.
*
* Unless otherwise noted, LEAP is 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.
*/
/**
* This class represents a record in the "users" table.
*
* @package Leap
* @category Model
* @version 2013-01-28
*
* @abstract
*/
abstract class Base_Model_Leap_User extends DB_ORM_Model {
/**
* This constructor instantiates this class.
*
* @access public
*/
public function __construct() {
parent::__construct();
$this->fields = array(
'id' => new DB_ORM_Field_Integer($this, array(
'max_length' => 11,
'nullable' => FALSE,
'unsigned' => TRUE,
)),
'email' => new DB_ORM_Field_String($this, array(
'max_length' => 254,
'nullable' => FALSE,
)),
'username' => new DB_ORM_Field_String($this, array(
'default' => '',
'max_length' => 32,
'nullable' => FALSE,
)),
'password' => new DB_ORM_Field_String($this, array(
'max_length' => 64,
'nullable' => FALSE,
)),
// Personal Details
'firstname' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 35,
'nullable' => TRUE,
)),
'lastname' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 50,
'nullable' => TRUE,
)),
// Account Status Details
'activated' => new DB_ORM_Field_Boolean($this, array(
'default' => TRUE,
'nullable' => FALSE,
)),
'banned' => new DB_ORM_Field_Boolean($this, array(
'default' => FALSE,
'nullable' => FALSE,
)),
'ban_reason' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 255,
'nullable' => TRUE,
)),
// Account Utility Details
'new_password_key' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 64,
'nullable' => TRUE,
)),
'new_password_requested' => new DB_ORM_Field_Integer($this, array(
'default' => NULL,
'max_length' => 11,
'nullable' => TRUE,
)),
'new_email' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 254,
'nullable' => TRUE,
)),
'new_email_key' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 64,
'nullable' => TRUE,
)),
// Account Metrics Details
'logins' => new DB_ORM_Field_Integer($this, array(
'default' => 0,
'max_length' => 10,
'nullable' => FALSE,
'unsigned' => TRUE,
)),
'last_login' => new DB_ORM_Field_Integer($this, array(
'default' => NULL,
'max_length' => 10,
'nullable' => TRUE,
'unsigned' => TRUE,
)),
'last_ip' => new DB_ORM_Field_String($this, array(
'default' => NULL,
'max_length' => 39,
'nullable' => TRUE,
)),
);
$this->adaptors = array(
'last_login_formatted' => new DB_ORM_Field_Adaptor_DateTime($this, array(
'field' => 'last_login',
)),
'new_password_requested_formatted' => new DB_ORM_Field_Adaptor_DateTime($this, array(
'field' => 'new_password_requested',
)),
);
$this->relations = array(
'user_roles' => new DB_ORM_Relation_HasMany($this, array(
'child_key' => array('user_id'),
'child_model' => 'User_Role',
'parent_key' => array('id'),
)),
'user_token' => new DB_ORM_Relation_HasMany($this, array(
'child_key' => array('user_id'),
'child_model' => 'User_Token',
'parent_key' => array('id'),
)),
);
}
/**
* This function completes the user's login.
*
* @access public
*/
public function complete_login() {
$this->logins++;
$this->last_login = time();
$this->last_ip = Request::$client_ip;
$this->save();
}
/**
* This function returns the data source name.
*
* @access public
* @override
* @static
* @param integer $instance the data source instance to be used (e.g.
* 0 = master, 1 = slave, 2 = slave, etc.)
* @return string the data source name
*/
public static function data_source($instance = 0) {
return 'default';
}
/**
* This function returns the primary key for the database table.
*
* @access public
* @override
* @static
* @return array the primary key
*/
public static function primary_key() {
return array('id');
}
/**
* This function returns the database table's name.
*
* @access public
* @override
* @static
* @return string the database table's name
*/
public static function table() {
return 'users';
}
}
| ruslankus/invoice-crm | modules/leap/classes/Base/Model/Leap/User.php | PHP | bsd-3-clause | 5,167 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include "base/numerics/safe_conversions.h"
#include "base/optional.h"
#include "media/video/h264_parser.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
static volatile size_t volatile_sink;
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
if (!size)
return 0;
media::H264Parser parser;
parser.SetStream(data, base::checked_cast<off_t>(size));
// Parse until the end of stream/unsupported stream/error in stream is
// found.
while (true) {
media::H264NALU nalu;
media::H264Parser::Result res = parser.AdvanceToNextNALU(&nalu);
if (res != media::H264Parser::kOk)
break;
switch (nalu.nal_unit_type) {
case media::H264NALU::kIDRSlice:
case media::H264NALU::kNonIDRSlice: {
media::H264SliceHeader shdr;
res = parser.ParseSliceHeader(nalu, &shdr);
break;
}
case media::H264NALU::kSPS: {
int id;
res = parser.ParseSPS(&id);
if (res != media::H264Parser::kOk)
break;
const media::H264SPS* sps = parser.GetSPS(id);
if (!sps)
break;
// Also test the SPS helper methods. We make sure that the results are
// used so that the calls are not optimized away.
base::Optional<gfx::Size> coded_size = sps->GetCodedSize();
volatile_sink = coded_size.value_or(gfx::Size()).ToString().length();
base::Optional<gfx::Rect> visible_rect = sps->GetVisibleRect();
volatile_sink = visible_rect.value_or(gfx::Rect()).ToString().length();
break;
}
case media::H264NALU::kPPS: {
int id;
res = parser.ParsePPS(&id);
break;
}
case media::H264NALU::kSEIMessage: {
media::H264SEIMessage sei_msg;
res = parser.ParseSEI(&sei_msg);
break;
}
default:
// Skip any other NALU.
break;
}
if (res != media::H264Parser::kOk)
break;
}
return 0;
}
| endlessm/chromium-browser | media/video/h264_parser_fuzzertest.cc | C++ | bsd-3-clause | 2,198 |
package org.hisp.dhis.reporttable;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.analytics.AnalyticsMetaDataKey;
import org.hisp.dhis.analytics.NumberType;
import org.hisp.dhis.common.*;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.legend.LegendDisplayStrategy;
import org.hisp.dhis.legend.LegendDisplayStyle;
import org.hisp.dhis.legend.LegendSet;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.RelativePeriods;
import org.hisp.dhis.user.User;
import org.springframework.util.Assert;
import java.util.*;
import java.util.Objects;
import static org.hisp.dhis.common.DimensionalObject.*;
/**
* @author Lars Helge Overland
*/
@JacksonXmlRootElement( localName = "reportTable", namespace = DxfNamespaces.DXF_2_0 )
public class ReportTable
extends BaseAnalyticalObject implements MetadataObject
{
public static final String REPORTING_MONTH_COLUMN_NAME = "reporting_month_name";
public static final String PARAM_ORGANISATIONUNIT_COLUMN_NAME = "param_organisationunit_name";
public static final String ORGANISATION_UNIT_IS_PARENT_COLUMN_NAME = "organisation_unit_is_parent";
public static final String SEPARATOR = "_";
public static final String DASH_PRETTY_SEPARATOR = " - ";
public static final String SPACE = " ";
public static final String KEY_ORGUNIT_GROUPSET = "orgunit_groupset_";
public static final String TOTAL_COLUMN_NAME = "total";
public static final String TOTAL_COLUMN_PRETTY_NAME = "Total";
public static final DimensionalItemObject[] IRT = new DimensionalItemObject[0];
public static final DimensionalItemObject[][] IRT2D = new DimensionalItemObject[0][];
public static final String EMPTY = "";
private static final String ILLEGAL_FILENAME_CHARS_REGEX = "[/\\?%*:|\"'<>.]";
public static final Map<String, String> COLUMN_NAMES = DimensionalObjectUtils.asMap(
DATA_X_DIM_ID, "data",
CATEGORYOPTIONCOMBO_DIM_ID, "categoryoptioncombo",
PERIOD_DIM_ID, "period",
ORGUNIT_DIM_ID, "organisationunit"
);
// -------------------------------------------------------------------------
// Persisted properties
// -------------------------------------------------------------------------
/**
* Indicates the criteria to apply to data measures.
*/
private String measureCriteria;
/**
* Indicates whether the ReportTable contains regression columns.
*/
private boolean regression;
/**
* Indicates whether the ReportTable contains cumulative columns.
*/
private boolean cumulative;
/**
* Dimensions to crosstabulate / use as columns.
*/
private List<String> columnDimensions = new ArrayList<>();
/**
* Dimensions to use as rows.
*/
private List<String> rowDimensions = new ArrayList<>();
/**
* Dimensions to use as filter.
*/
private List<String> filterDimensions = new ArrayList<>();
/**
* The ReportParams of the ReportTable.
*/
private ReportParams reportParams;
/**
* Indicates rendering of row totals for the table.
*/
private boolean rowTotals;
/**
* Indicates rendering of column totals for the table.
*/
private boolean colTotals;
/**
* Indicates rendering of row sub-totals for the table.
*/
private boolean rowSubTotals;
/**
* Indicates rendering of column sub-totals for the table.
*/
private boolean colSubTotals;
/**
* Indicates whether to hide rows with no data values in the table.
*/
private boolean hideEmptyRows;
/**
* Indicates whether to hide columns with no data values in the table.
*/
private boolean hideEmptyColumns;
/**
* The display density of the text in the table.
*/
private DisplayDensity displayDensity;
/**
* The font size of the text in the table.
*/
private FontSize fontSize;
/**
* The legend set in the table.
*/
private LegendSet legendSet;
/**
* The legend set display strategy.
*/
private LegendDisplayStrategy legendDisplayStrategy;
/**
* The legend set display type.
*/
private LegendDisplayStyle legendDisplayStyle;
/**
* The number type.
*/
private NumberType numberType;
/**
* Indicates showing organisation unit hierarchy names.
*/
private boolean showHierarchy;
/**
* Indicates showing organisation unit hierarchy names.
*/
private boolean showDimensionLabels;
/**
* Indicates rounding values.
*/
private boolean skipRounding;
// -------------------------------------------------------------------------
// Transient properties
// -------------------------------------------------------------------------
/**
* All crosstabulated columns.
*/
private transient List<List<DimensionalItemObject>> gridColumns = new ArrayList<>();
/**
* All rows.
*/
private transient List<List<DimensionalItemObject>> gridRows = new ArrayList<>();
/**
* The name of the reporting month based on the report param.
*/
private transient String reportingPeriodName;
/**
* The title of the report table grid.
*/
private transient String gridTitle;
@Override
protected void clearTransientStateProperties()
{
gridColumns = new ArrayList<>();
gridRows = new ArrayList<>();
reportingPeriodName = null;
gridTitle = null;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Constructor for persistence purposes.
*/
public ReportTable()
{
}
/**
* Default constructor.
*
* @param name the name.
* @param dataElements the data elements.
* @param indicators the indicators.
* @param reportingRates the reporting rates.
* @param periods the periods. Cannot have the name property set.
* @param organisationUnits the organisation units.
* @param doIndicators indicating whether indicators should be crosstabulated.
* @param doPeriods indicating whether periods should be crosstabulated.
* @param doUnits indicating whether organisation units should be crosstabulated.
* @param relatives the relative periods.
* @param reportParams the report parameters.
* @param reportingPeriodName the reporting period name.
*/
public ReportTable( String name, List<DataElement> dataElements, List<Indicator> indicators,
List<ReportingRate> reportingRates, List<Period> periods,
List<OrganisationUnit> organisationUnits,
boolean doIndicators, boolean doPeriods, boolean doUnits, RelativePeriods relatives, ReportParams reportParams,
String reportingPeriodName )
{
this.name = name;
addAllDataDimensionItems( dataElements );
addAllDataDimensionItems( indicators );
addAllDataDimensionItems( reportingRates );
this.periods = periods;
this.organisationUnits = organisationUnits;
this.relatives = relatives;
this.reportParams = reportParams;
this.reportingPeriodName = reportingPeriodName;
if ( doIndicators )
{
columnDimensions.add( DATA_X_DIM_ID );
}
else
{
rowDimensions.add( DATA_X_DIM_ID );
}
if ( doPeriods )
{
columnDimensions.add( PERIOD_DIM_ID );
}
else
{
rowDimensions.add( PERIOD_DIM_ID );
}
if ( doUnits )
{
columnDimensions.add( ORGUNIT_DIM_ID );
}
else
{
rowDimensions.add( ORGUNIT_DIM_ID );
}
}
// -------------------------------------------------------------------------
// Init
// -------------------------------------------------------------------------
@Override
public void init( User user, Date date, OrganisationUnit organisationUnit,
List<OrganisationUnit> organisationUnitsAtLevel, List<OrganisationUnit> organisationUnitsInGroups, I18nFormat format )
{
verify( (periods != null && !periods.isEmpty()) || hasRelativePeriods(), "Must contain periods or relative periods" );
this.relativePeriodDate = date;
this.relativeOrganisationUnit = organisationUnit;
// Handle report parameters
if ( hasRelativePeriods() )
{
this.reportingPeriodName = relatives.getReportingPeriodName( date, format );
}
if ( organisationUnit != null && hasReportParams() && reportParams.isParamParentOrganisationUnit() )
{
organisationUnit.setCurrentParent( true );
addTransientOrganisationUnits( organisationUnit.getChildren() );
addTransientOrganisationUnit( organisationUnit );
}
if ( organisationUnit != null && hasReportParams() && reportParams.isParamOrganisationUnit() )
{
addTransientOrganisationUnit( organisationUnit );
}
// Handle special dimension
if ( isDimensional() )
{
transientCategoryOptionCombos.addAll( Objects.requireNonNull( getFirstCategoryCombo() ).getSortedOptionCombos() );
verify( nonEmptyLists( transientCategoryOptionCombos ) == 1, "Category option combos size must be larger than 0" );
}
// Populate grid
this.populateGridColumnsAndRows( date, user, organisationUnitsAtLevel, organisationUnitsInGroups, format );
}
// -------------------------------------------------------------------------
// Public methods
// -------------------------------------------------------------------------
public void populateGridColumnsAndRows( Date date, User user,
List<OrganisationUnit> organisationUnitsAtLevel, List<OrganisationUnit> organisationUnitsInGroups, I18nFormat format )
{
List<DimensionalItemObject[]> tableColumns = new ArrayList<>();
List<DimensionalItemObject[]> tableRows = new ArrayList<>();
List<DimensionalItemObject> filterItems = new ArrayList<>();
for ( String dimension : columnDimensions )
{
tableColumns.add( getDimensionalObject( dimension, date, user, false, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems().toArray( IRT ) );
}
for ( String dimension : rowDimensions )
{
tableRows.add( getDimensionalObject( dimension, date, user, true, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems().toArray( IRT ) );
}
for ( String filter : filterDimensions )
{
filterItems.addAll( getDimensionalObject( filter, date, user, true, organisationUnitsAtLevel, organisationUnitsInGroups, format ).getItems() );
}
gridColumns = new CombinationGenerator<>( tableColumns.toArray( IRT2D ) ).getCombinations();
gridRows = new CombinationGenerator<>( tableRows.toArray( IRT2D ) ).getCombinations();
addListIfEmpty( gridColumns );
addListIfEmpty( gridRows );
gridTitle = IdentifiableObjectUtils.join( filterItems );
}
@Override
public void populateAnalyticalProperties()
{
for ( String column : columnDimensions )
{
columns.add( getDimensionalObject( column ) );
}
for ( String row : rowDimensions )
{
rows.add( getDimensionalObject( row ) );
}
for ( String filter : filterDimensions )
{
filters.add( getDimensionalObject( filter ) );
}
}
/**
* Indicates whether this ReportTable is multi-dimensional.
*/
public boolean isDimensional()
{
return !getDataElements().isEmpty() && (
columnDimensions.contains( CATEGORYOPTIONCOMBO_DIM_ID ) || rowDimensions.contains( CATEGORYOPTIONCOMBO_DIM_ID ));
}
/**
* Generates a pretty column name based on the given display property of the
* argument objects. Null arguments are ignored in the name.
*/
public static String getPrettyColumnName( List<DimensionalItemObject> objects, DisplayProperty displayProperty )
{
StringBuilder builder = new StringBuilder();
for ( DimensionalItemObject object : objects )
{
builder.append( object != null ? ( object.getDisplayProperty( displayProperty ) + SPACE ) : EMPTY );
}
return builder.length() > 0 ? builder.substring( 0, builder.lastIndexOf( SPACE ) ) : TOTAL_COLUMN_PRETTY_NAME;
}
/**
* Generates a column name based on short-names of the argument objects.
* Null arguments are ignored in the name.
* <p/>
* The period column name must be static when on columns so it can be
* re-used in reports, hence the name property is used which will be formatted
* only when the period dimension is on rows.
*/
public static String getColumnName( List<DimensionalItemObject> objects )
{
StringBuffer buffer = new StringBuffer();
for ( DimensionalItemObject object : objects )
{
if ( object != null && object instanceof Period )
{
buffer.append( object.getName() ).append( SEPARATOR );
}
else
{
buffer.append( object != null ? ( object.getShortName() + SEPARATOR ) : EMPTY );
}
}
String column = columnEncode( buffer.toString() );
return column.length() > 0 ? column.substring( 0, column.lastIndexOf( SEPARATOR ) ) : TOTAL_COLUMN_NAME;
}
/**
* Generates a string which is acceptable as a filename.
*/
public static String columnEncode( String string )
{
if ( string != null )
{
string = string.replaceAll( "<", "_lt" );
string = string.replaceAll( ">", "_gt" );
string = string.replaceAll( ILLEGAL_FILENAME_CHARS_REGEX, EMPTY );
string = string.length() > 255 ? string.substring( 0, 255 ) : string;
string = string.toLowerCase();
}
return string;
}
/**
* Checks whether the given List of IdentifiableObjects contains an object
* which is an OrganisationUnit and has the currentParent property set to
* true.
*
* @param objects the List of IdentifiableObjects.
*/
public static boolean isCurrentParent( List<? extends IdentifiableObject> objects )
{
for ( IdentifiableObject object : objects )
{
if ( object != null && object instanceof OrganisationUnit && ((OrganisationUnit) object).isCurrentParent() )
{
return true;
}
}
return false;
}
/**
* Tests whether this report table has report params.
*/
public boolean hasReportParams()
{
return reportParams != null;
}
/**
* Returns the name of the parent organisation unit, or an empty string if null.
*/
public String getParentOrganisationUnitName()
{
return relativeOrganisationUnit != null ? relativeOrganisationUnit.getName() : EMPTY;
}
/**
* Adds an empty list of DimensionalItemObjects to the given list if empty.
*/
public static void addListIfEmpty( List<List<DimensionalItemObject>> list )
{
if ( list != null && list.size() == 0 )
{
list.add( Arrays.asList( new DimensionalItemObject[0] ) );
}
}
/**
* Generates a grid for this report table based on the given aggregate value
* map.
*
* @param grid the grid, should be empty and not null.
* @param valueMap the mapping of identifiers to aggregate values.
* @param displayProperty the display property to use for meta data.
* @param reportParamColumns whether to include report parameter columns.
* @return a grid.
*/
public Grid getGrid( Grid grid, Map<String, Object> valueMap, DisplayProperty displayProperty, boolean reportParamColumns )
{
valueMap = new HashMap<>( valueMap );
sortKeys( valueMap );
// ---------------------------------------------------------------------
// Title
// ---------------------------------------------------------------------
if ( name != null )
{
grid.setTitle( name );
grid.setSubtitle( gridTitle );
}
else
{
grid.setTitle( gridTitle );
}
// ---------------------------------------------------------------------
// Headers
// ---------------------------------------------------------------------
Map<String, String> metaData = getMetaData();
metaData.putAll( DimensionalObject.PRETTY_NAMES );
for ( String row : rowDimensions )
{
String name = StringUtils.defaultIfEmpty( metaData.get( row ), row );
String col = StringUtils.defaultIfEmpty( COLUMN_NAMES.get( row ), row );
grid.addHeader( new GridHeader( name + " ID", col + "id", ValueType.TEXT, String.class.getName(), true, true ) );
grid.addHeader( new GridHeader( name, col + "name", ValueType.TEXT, String.class.getName(), false, true ) );
grid.addHeader( new GridHeader( name + " code", col + "code", ValueType.TEXT, String.class.getName(), true, true ) );
grid.addHeader( new GridHeader( name + " description", col + "description", ValueType.TEXT, String.class.getName(), true, true ) );
}
if ( reportParamColumns )
{
grid.addHeader( new GridHeader( "Reporting month", REPORTING_MONTH_COLUMN_NAME,
ValueType.TEXT, String.class.getName(), true, true ) );
grid.addHeader( new GridHeader( "Organisation unit parameter", PARAM_ORGANISATIONUNIT_COLUMN_NAME,
ValueType.TEXT, String.class.getName(), true, true ) );
grid.addHeader( new GridHeader( "Organisation unit is parent", ORGANISATION_UNIT_IS_PARENT_COLUMN_NAME,
ValueType.TEXT, String.class.getName(), true, true ) );
}
final int startColumnIndex = grid.getHeaders().size();
final int numberOfColumns = getGridColumns().size();
for ( List<DimensionalItemObject> column : gridColumns )
{
grid.addHeader( new GridHeader( getColumnName( column ), getPrettyColumnName( column, displayProperty ),
ValueType.NUMBER, Double.class.getName(), false, false ) );
}
// ---------------------------------------------------------------------
// Values
// ---------------------------------------------------------------------
for ( List<DimensionalItemObject> row : gridRows )
{
grid.addRow();
// -----------------------------------------------------------------
// Row meta data
// -----------------------------------------------------------------
for ( DimensionalItemObject object : row )
{
grid.addValue( object.getDimensionItem() );
grid.addValue( object.getDisplayProperty( displayProperty ) );
grid.addValue( object.getCode() );
grid.addValue( object.getDisplayDescription() );
}
if ( reportParamColumns )
{
grid.addValue( reportingPeriodName );
grid.addValue( getParentOrganisationUnitName() );
grid.addValue( isCurrentParent( row ) ? "Yes" : "No" );
}
// -----------------------------------------------------------------
// Row data values
// -----------------------------------------------------------------
boolean hasValue = false;
for ( List<DimensionalItemObject> column : gridColumns )
{
String key = getIdentifier( column, row );
Object value = valueMap.get( key );
grid.addValue( value );
hasValue = hasValue || value != null;
}
if ( hideEmptyRows && !hasValue )
{
grid.removeCurrentWriteRow();
}
// TODO hide empty columns
}
if ( hideEmptyColumns )
{
grid.removeEmptyColumns();
}
if ( regression )
{
grid.addRegressionToGrid( startColumnIndex, numberOfColumns );
}
if ( cumulative )
{
grid.addCumulativesToGrid( startColumnIndex, numberOfColumns );
}
// ---------------------------------------------------------------------
// Sort and limit
// ---------------------------------------------------------------------
if ( sortOrder != BaseAnalyticalObject.NONE )
{
grid.sortGrid( grid.getWidth(), sortOrder );
}
if ( topLimit > 0 )
{
grid.limitGrid( topLimit );
}
// ---------------------------------------------------------------------
// Show hierarchy option
// ---------------------------------------------------------------------
if ( showHierarchy && rowDimensions.contains( ORGUNIT_DIM_ID ) && grid.hasInternalMetaDataKey( AnalyticsMetaDataKey.ORG_UNIT_ANCESTORS.getKey() ) )
{
int ouIdColumnIndex = rowDimensions.indexOf( ORGUNIT_DIM_ID ) * 4;
addHierarchyColumns( grid, ouIdColumnIndex );
}
return grid;
}
// -------------------------------------------------------------------------
// Supportive methods
// -------------------------------------------------------------------------
/**
* Adds grid columns for each organisation unit level.
*/
@SuppressWarnings( "unchecked" )
private void addHierarchyColumns( Grid grid, int ouIdColumnIndex )
{
Map<Object, List<?>> ancestorMap = (Map<Object, List<?>>) grid.getInternalMetaData().get( AnalyticsMetaDataKey.ORG_UNIT_ANCESTORS.getKey() );
Assert.notEmpty( ancestorMap, "Ancestor map cannot be null or empty when show hierarchy is enabled" );
int newColumns = ancestorMap.values().stream().mapToInt( List::size ).max().orElseGet( () -> 0 );
List<GridHeader> headers = new ArrayList<>();
for ( int i = 0; i < newColumns; i++ )
{
int level = i + 1;
String name = String.format( "Org unit level %d", level );
String column = String.format( "orgunitlevel%d", level );
headers.add( new GridHeader( name, column, ValueType.TEXT, String.class.getName(), false, true ) );
}
grid.addHeaders( ouIdColumnIndex, headers );
grid.addAndPopulateColumnsBefore( ouIdColumnIndex, ancestorMap, newColumns );
}
/**
* Returns the number of empty lists among the argument lists.
*/
private static int nonEmptyLists( List<?>... lists )
{
int nonEmpty = 0;
for ( List<?> list : lists )
{
if ( list != null && list.size() > 0 )
{
++nonEmpty;
}
}
return nonEmpty;
}
/**
* Supportive method.
*/
private static void verify( boolean expression, String falseMessage )
{
if ( !expression )
{
throw new IllegalStateException( falseMessage );
}
}
/**
* Returns the category combo of the first data element.
*/
private CategoryCombo getFirstCategoryCombo()
{
if ( !getDataElements().isEmpty() )
{
return getDataElements().get( 0 ).getCategoryCombos().iterator().next();
}
return null;
}
// -------------------------------------------------------------------------
// Get- and set-methods for persisted properties
// -------------------------------------------------------------------------
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public String getMeasureCriteria()
{
return measureCriteria;
}
public void setMeasureCriteria( String measureCriteria )
{
this.measureCriteria = measureCriteria;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isRegression()
{
return regression;
}
public void setRegression( boolean regression )
{
this.regression = regression;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isCumulative()
{
return cumulative;
}
public void setCumulative( boolean cumulative )
{
this.cumulative = cumulative;
}
@JsonProperty
@JacksonXmlElementWrapper( localName = "columnDimensions", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "columnDimension", namespace = DxfNamespaces.DXF_2_0 )
public List<String> getColumnDimensions()
{
return columnDimensions;
}
public void setColumnDimensions( List<String> columnDimensions )
{
this.columnDimensions = columnDimensions;
}
@JsonProperty
@JacksonXmlElementWrapper( localName = "rowDimensions", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "rowDimension", namespace = DxfNamespaces.DXF_2_0 )
public List<String> getRowDimensions()
{
return rowDimensions;
}
public void setRowDimensions( List<String> rowDimensions )
{
this.rowDimensions = rowDimensions;
}
@JsonProperty
@JacksonXmlElementWrapper( localName = "filterDimensions", namespace = DxfNamespaces.DXF_2_0 )
@JacksonXmlProperty( localName = "filterDimension", namespace = DxfNamespaces.DXF_2_0 )
public List<String> getFilterDimensions()
{
return filterDimensions;
}
public void setFilterDimensions( List<String> filterDimensions )
{
this.filterDimensions = filterDimensions;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public ReportParams getReportParams()
{
return reportParams;
}
public void setReportParams( ReportParams reportParams )
{
this.reportParams = reportParams;
}
@Override
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public int getSortOrder()
{
return sortOrder;
}
@Override
public void setSortOrder( int sortOrder )
{
this.sortOrder = sortOrder;
}
@Override
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public int getTopLimit()
{
return topLimit;
}
@Override
public void setTopLimit( int topLimit )
{
this.topLimit = topLimit;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isRowTotals()
{
return rowTotals;
}
public void setRowTotals( boolean rowTotals )
{
this.rowTotals = rowTotals;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isColTotals()
{
return colTotals;
}
public void setColTotals( boolean colTotals )
{
this.colTotals = colTotals;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isRowSubTotals()
{
return rowSubTotals;
}
public void setRowSubTotals( boolean rowSubTotals )
{
this.rowSubTotals = rowSubTotals;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isColSubTotals()
{
return colSubTotals;
}
public void setColSubTotals( boolean colSubTotals )
{
this.colSubTotals = colSubTotals;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isHideEmptyRows()
{
return hideEmptyRows;
}
public void setHideEmptyRows( boolean hideEmptyRows )
{
this.hideEmptyRows = hideEmptyRows;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isHideEmptyColumns()
{
return hideEmptyColumns;
}
public void setHideEmptyColumns( boolean hideEmptyColumns )
{
this.hideEmptyColumns = hideEmptyColumns;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public DisplayDensity getDisplayDensity()
{
return displayDensity;
}
public void setDisplayDensity( DisplayDensity displayDensity )
{
this.displayDensity = displayDensity;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public FontSize getFontSize()
{
return fontSize;
}
public void setFontSize( FontSize fontSize )
{
this.fontSize = fontSize;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public LegendSet getLegendSet()
{
return legendSet;
}
public void setLegendSet( LegendSet legendSet )
{
this.legendSet = legendSet;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public LegendDisplayStrategy getLegendDisplayStrategy()
{
return legendDisplayStrategy;
}
public void setLegendDisplayStrategy( LegendDisplayStrategy legendDisplayStrategy )
{
this.legendDisplayStrategy = legendDisplayStrategy;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public LegendDisplayStyle getLegendDisplayStyle()
{
return legendDisplayStyle;
}
public void setLegendDisplayStyle( LegendDisplayStyle legendDisplayStyle )
{
this.legendDisplayStyle = legendDisplayStyle;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public NumberType getNumberType()
{
return numberType;
}
public void setNumberType( NumberType numberType )
{
this.numberType = numberType;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isShowHierarchy()
{
return showHierarchy;
}
public void setShowHierarchy( boolean showHierarchy )
{
this.showHierarchy = showHierarchy;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isShowDimensionLabels()
{
return showDimensionLabels;
}
public void setShowDimensionLabels( boolean showDimensionLabels )
{
this.showDimensionLabels = showDimensionLabels;
}
@JsonProperty
@JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
public boolean isSkipRounding()
{
return skipRounding;
}
public void setSkipRounding( boolean skipRounding )
{
this.skipRounding = skipRounding;
}
// -------------------------------------------------------------------------
// Get- and set-methods for transient properties
// -------------------------------------------------------------------------
@JsonIgnore
public String getReportingPeriodName()
{
return reportingPeriodName;
}
@JsonIgnore
public ReportTable setReportingPeriodName( String reportingPeriodName )
{
this.reportingPeriodName = reportingPeriodName;
return this;
}
@JsonIgnore
public List<List<DimensionalItemObject>> getGridColumns()
{
return gridColumns;
}
public ReportTable setGridColumns( List<List<DimensionalItemObject>> gridColumns )
{
this.gridColumns = gridColumns;
return this;
}
@JsonIgnore
public List<List<DimensionalItemObject>> getGridRows()
{
return gridRows;
}
public ReportTable setGridRows( List<List<DimensionalItemObject>> gridRows )
{
this.gridRows = gridRows;
return this;
}
@JsonIgnore
public String getGridTitle()
{
return gridTitle;
}
public ReportTable setGridTitle( String gridTitle )
{
this.gridTitle = gridTitle;
return this;
}
}
| msf-oca-his/dhis-core | dhis-2/dhis-api/src/main/java/org/hisp/dhis/reporttable/ReportTable.java | Java | bsd-3-clause | 35,862 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.util.opus;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;
/**
* The callbacks used to access non-{@code FILE} stream resources.
*
* <p>The function prototypes are basically the same as for the stdio functions {@code fread()}, {@code fseek()}, {@code ftell()}, and {@code fclose()}. The
* differences are that the {@code FILE *} arguments have been replaced with a {@code void *}, which is to be used as a pointer to whatever internal data
* these functions might need, that {@code seek} and {@code tell} take and return 64-bit offsets, and that {@code seek} <em>must</em> return {@code -1} if
* the stream is unseekable.</p>
*
* <h3>Layout</h3>
*
* <pre><code>
* struct OpusFileCallbacks {
* {@link OPReadFuncI op_read_func} {@link #read};
* {@link OPSeekFuncI op_seek_func} {@link #seek};
* {@link OPTellFuncI op_tell_func} {@link #tell};
* {@link OPCloseFuncI op_close_func} {@link #close$ close};
* }</code></pre>
*/
public class OpusFileCallbacks extends Struct implements NativeResource {
/** The struct size in bytes. */
public static final int SIZEOF;
/** The struct alignment in bytes. */
public static final int ALIGNOF;
/** The struct member offsets. */
public static final int
READ,
SEEK,
TELL,
CLOSE;
static {
Layout layout = __struct(
__member(POINTER_SIZE),
__member(POINTER_SIZE),
__member(POINTER_SIZE),
__member(POINTER_SIZE)
);
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
READ = layout.offsetof(0);
SEEK = layout.offsetof(1);
TELL = layout.offsetof(2);
CLOSE = layout.offsetof(3);
}
/**
* Creates a {@code OpusFileCallbacks} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
public OpusFileCallbacks(ByteBuffer container) {
super(memAddress(container), __checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
/** used to read data from the stream. This must not be {@code NULL}. */
@NativeType("op_read_func")
public OPReadFunc read() { return nread(address()); }
/** used to seek in the stream. This may be {@code NULL} if seeking is not implemented. */
@Nullable
@NativeType("op_seek_func")
public OPSeekFunc seek() { return nseek(address()); }
/** used to return the current read position in the stream. This may be {@code NULL} if seeking is not implemented. */
@Nullable
@NativeType("op_tell_func")
public OPTellFunc tell() { return ntell(address()); }
/** used to close the stream when the decoder is freed. This may be {@code NULL} to leave the stream open. */
@Nullable
@NativeType("op_close_func")
public OPCloseFunc close$() { return nclose$(address()); }
/** Sets the specified value to the {@link #read} field. */
public OpusFileCallbacks read(@NativeType("op_read_func") OPReadFuncI value) { nread(address(), value); return this; }
/** Sets the specified value to the {@link #seek} field. */
public OpusFileCallbacks seek(@Nullable @NativeType("op_seek_func") OPSeekFuncI value) { nseek(address(), value); return this; }
/** Sets the specified value to the {@link #tell} field. */
public OpusFileCallbacks tell(@Nullable @NativeType("op_tell_func") OPTellFuncI value) { ntell(address(), value); return this; }
/** Sets the specified value to the {@link #close$} field. */
public OpusFileCallbacks close$(@Nullable @NativeType("op_close_func") OPCloseFuncI value) { nclose$(address(), value); return this; }
/** Initializes this struct with the specified values. */
public OpusFileCallbacks set(
OPReadFuncI read,
OPSeekFuncI seek,
OPTellFuncI tell,
OPCloseFuncI close$
) {
read(read);
seek(seek);
tell(tell);
close$(close$);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public OpusFileCallbacks set(OpusFileCallbacks src) {
memCopy(src.address(), address(), SIZEOF);
return this;
}
// -----------------------------------
/** Returns a new {@code OpusFileCallbacks} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static OpusFileCallbacks malloc() {
return wrap(OpusFileCallbacks.class, nmemAllocChecked(SIZEOF));
}
/** Returns a new {@code OpusFileCallbacks} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static OpusFileCallbacks calloc() {
return wrap(OpusFileCallbacks.class, nmemCallocChecked(1, SIZEOF));
}
/** Returns a new {@code OpusFileCallbacks} instance allocated with {@link BufferUtils}. */
public static OpusFileCallbacks create() {
ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF);
return wrap(OpusFileCallbacks.class, memAddress(container), container);
}
/** Returns a new {@code OpusFileCallbacks} instance for the specified memory address. */
public static OpusFileCallbacks create(long address) {
return wrap(OpusFileCallbacks.class, address);
}
/** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static OpusFileCallbacks createSafe(long address) {
return address == NULL ? null : wrap(OpusFileCallbacks.class, address);
}
/**
* Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer malloc(int capacity) {
return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity);
}
/**
* Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer calloc(int capacity) {
return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity);
}
/**
* Returns a new {@link OpusFileCallbacks.Buffer} instance allocated with {@link BufferUtils}.
*
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer create(int capacity) {
ByteBuffer container = __create(capacity, SIZEOF);
return wrap(Buffer.class, memAddress(container), capacity, container);
}
/**
* Create a {@link OpusFileCallbacks.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer create(long address, int capacity) {
return wrap(Buffer.class, address, capacity);
}
/** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */
@Nullable
public static OpusFileCallbacks.Buffer createSafe(long address, int capacity) {
return address == NULL ? null : wrap(Buffer.class, address, capacity);
}
/**
* Returns a new {@code OpusFileCallbacks} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static OpusFileCallbacks malloc(MemoryStack stack) {
return wrap(OpusFileCallbacks.class, stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@code OpusFileCallbacks} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static OpusFileCallbacks calloc(MemoryStack stack) {
return wrap(OpusFileCallbacks.class, stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link OpusFileCallbacks.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer malloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
}
/**
* Returns a new {@link OpusFileCallbacks.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param capacity the buffer capacity
*/
public static OpusFileCallbacks.Buffer calloc(int capacity, MemoryStack stack) {
return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
}
// -----------------------------------
/** Unsafe version of {@link #read}. */
public static OPReadFunc nread(long struct) { return OPReadFunc.create(memGetAddress(struct + OpusFileCallbacks.READ)); }
/** Unsafe version of {@link #seek}. */
@Nullable public static OPSeekFunc nseek(long struct) { return OPSeekFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.SEEK)); }
/** Unsafe version of {@link #tell}. */
@Nullable public static OPTellFunc ntell(long struct) { return OPTellFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.TELL)); }
/** Unsafe version of {@link #close$}. */
@Nullable public static OPCloseFunc nclose$(long struct) { return OPCloseFunc.createSafe(memGetAddress(struct + OpusFileCallbacks.CLOSE)); }
/** Unsafe version of {@link #read(OPReadFuncI) read}. */
public static void nread(long struct, OPReadFuncI value) { memPutAddress(struct + OpusFileCallbacks.READ, value.address()); }
/** Unsafe version of {@link #seek(OPSeekFuncI) seek}. */
public static void nseek(long struct, @Nullable OPSeekFuncI value) { memPutAddress(struct + OpusFileCallbacks.SEEK, memAddressSafe(value)); }
/** Unsafe version of {@link #tell(OPTellFuncI) tell}. */
public static void ntell(long struct, @Nullable OPTellFuncI value) { memPutAddress(struct + OpusFileCallbacks.TELL, memAddressSafe(value)); }
/** Unsafe version of {@link #close$(OPCloseFuncI) close$}. */
public static void nclose$(long struct, @Nullable OPCloseFuncI value) { memPutAddress(struct + OpusFileCallbacks.CLOSE, memAddressSafe(value)); }
/**
* Validates pointer members that should not be {@code NULL}.
*
* @param struct the struct to validate
*/
public static void validate(long struct) {
check(memGetAddress(struct + OpusFileCallbacks.READ));
}
// -----------------------------------
/** An array of {@link OpusFileCallbacks} structs. */
public static class Buffer extends StructBuffer<OpusFileCallbacks, Buffer> implements NativeResource {
private static final OpusFileCallbacks ELEMENT_FACTORY = OpusFileCallbacks.create(-1L);
/**
* Creates a new {@code OpusFileCallbacks.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link OpusFileCallbacks#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}
public Buffer(long address, int cap) {
super(address, null, -1, 0, cap, cap);
}
Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected OpusFileCallbacks getElementFactory() {
return ELEMENT_FACTORY;
}
/** @return the value of the {@link OpusFileCallbacks#read} field. */
@NativeType("op_read_func")
public OPReadFunc read() { return OpusFileCallbacks.nread(address()); }
/** @return the value of the {@link OpusFileCallbacks#seek} field. */
@Nullable
@NativeType("op_seek_func")
public OPSeekFunc seek() { return OpusFileCallbacks.nseek(address()); }
/** @return the value of the {@link OpusFileCallbacks#tell} field. */
@Nullable
@NativeType("op_tell_func")
public OPTellFunc tell() { return OpusFileCallbacks.ntell(address()); }
/** @return the value of the {@link OpusFileCallbacks#close$} field. */
@Nullable
@NativeType("op_close_func")
public OPCloseFunc close$() { return OpusFileCallbacks.nclose$(address()); }
/** Sets the specified value to the {@link OpusFileCallbacks#read} field. */
public OpusFileCallbacks.Buffer read(@NativeType("op_read_func") OPReadFuncI value) { OpusFileCallbacks.nread(address(), value); return this; }
/** Sets the specified value to the {@link OpusFileCallbacks#seek} field. */
public OpusFileCallbacks.Buffer seek(@Nullable @NativeType("op_seek_func") OPSeekFuncI value) { OpusFileCallbacks.nseek(address(), value); return this; }
/** Sets the specified value to the {@link OpusFileCallbacks#tell} field. */
public OpusFileCallbacks.Buffer tell(@Nullable @NativeType("op_tell_func") OPTellFuncI value) { OpusFileCallbacks.ntell(address(), value); return this; }
/** Sets the specified value to the {@link OpusFileCallbacks#close$} field. */
public OpusFileCallbacks.Buffer close$(@Nullable @NativeType("op_close_func") OPCloseFuncI value) { OpusFileCallbacks.nclose$(address(), value); return this; }
}
} | LWJGL-CI/lwjgl3 | modules/lwjgl/opus/src/generated/java/org/lwjgl/util/opus/OpusFileCallbacks.java | Java | bsd-3-clause | 14,770 |
from django.contrib import admin
from django.utils.translation import ugettext, ugettext_lazy as _
from ella.positions.models import Position
from ella.utils import timezone
class PositionOptions(admin.ModelAdmin):
def show_title(self, obj):
if not obj.target:
return '-- %s --' % ugettext('empty position')
else:
return u'%s [%s]' % (obj.target.title, ugettext(obj.target_ct.name),)
show_title.short_description = _('Title')
def is_filled(self, obj):
if obj.target:
return True
else:
return False
is_filled.short_description = _('Filled')
is_filled.boolean = True
def is_active(self, obj):
if obj.disabled:
return False
now = timezone.now()
active_from = not obj.active_from or obj.active_from <= now
active_till = not obj.active_till or obj.active_till > now
return active_from and active_till
is_active.short_description = _('Active')
is_active.boolean = True
list_display = ('name', 'category', 'box_type', 'is_active', 'is_filled', 'show_title', 'disabled',)
list_filter = ('category', 'name', 'disabled', 'active_from', 'active_till',)
search_fields = ('box_type', 'text',)
# suggest_fields = {'category': ('tree_path', 'title', 'slug',),}
admin.site.register(Position, PositionOptions)
| WhiskeyMedia/ella | ella/positions/admin.py | Python | bsd-3-clause | 1,381 |
// Copyright © 2010-2014 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#pragma once
#include "Stdafx.h"
#include "JavascriptPropertyWrapper.h"
#include "JavascriptObjectWrapper.h"
using namespace System;
namespace CefSharp
{
void JavascriptPropertyWrapper::Bind()
{
auto propertyName = StringUtils::ToNative(_javascriptProperty->JavascriptName);
auto clrPropertyName = _javascriptProperty->JavascriptName;
if (_javascriptProperty->IsComplexType)
{
auto javascriptObjectWrapper = gcnew JavascriptObjectWrapper(_javascriptProperty->JsObject, _browserProcess);
javascriptObjectWrapper->V8Value = V8Value.get();
javascriptObjectWrapper->Bind();
_javascriptObjectWrapper = javascriptObjectWrapper;
}
else
{
auto propertyAttribute = _javascriptProperty->IsReadOnly ? V8_PROPERTY_ATTRIBUTE_READONLY : V8_PROPERTY_ATTRIBUTE_NONE;
V8Value->SetValue(propertyName, V8_ACCESS_CONTROL_DEFAULT, propertyAttribute);
}
};
} | dreamsxin/CefSharp-37.0.0 | CefSharp.BrowserSubprocess.Core/JavascriptPropertyWrapper.cpp | C++ | bsd-3-clause | 1,163 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Offline message screen implementation.
*/
login.createScreen('ErrorMessageScreen', 'error-message', function() {
// Link which starts guest session for captive portal fixing.
/** @const */ var FIX_CAPTIVE_PORTAL_ID = 'captive-portal-fix-link';
/** @const */ var FIX_PROXY_SETTINGS_ID = 'proxy-settings-fix-link';
// Id of the element which holds current network name.
/** @const */ var CURRENT_NETWORK_NAME_ID = 'captive-portal-network-name';
// Link which triggers frame reload.
/** @const */ var RELOAD_PAGE_ID = 'proxy-error-signin-retry-link';
// Array of the possible UI states of the screen. Must be in the
// same order as ErrorScreen::UIState enum values.
/** @const */ var UI_STATES = [
ERROR_SCREEN_UI_STATE.UNKNOWN,
ERROR_SCREEN_UI_STATE.UPDATE,
ERROR_SCREEN_UI_STATE.SIGNIN,
ERROR_SCREEN_UI_STATE.MANAGED_USER_CREATION_FLOW,
ERROR_SCREEN_UI_STATE.KIOSK_MODE,
ERROR_SCREEN_UI_STATE.LOCAL_STATE_ERROR
];
// Possible error states of the screen.
/** @const */ var ERROR_STATE = {
UNKNOWN: 'error-state-unknown',
PORTAL: 'error-state-portal',
OFFLINE: 'error-state-offline',
PROXY: 'error-state-proxy',
AUTH_EXT_TIMEOUT: 'error-state-auth-ext-timeout'
};
// Possible error states of the screen. Must be in the same order as
// ErrorScreen::ErrorState enum values.
/** @const */ var ERROR_STATES = [
ERROR_STATE.UNKNOWN,
ERROR_STATE.PORTAL,
ERROR_STATE.OFFLINE,
ERROR_STATE.PROXY,
ERROR_STATE.AUTH_EXT_TIMEOUT
];
return {
EXTERNAL_API: [
'updateLocalizedContent',
'onBeforeShow',
'onBeforeHide',
'allowGuestSignin',
'allowOfflineLogin',
'setUIState',
'setErrorState'
],
// Error screen initial UI state.
ui_state_: ERROR_SCREEN_UI_STATE.UNKNOWN,
// Error screen initial error state.
error_state_: ERROR_STATE.UNKNOWN,
/** @override */
decorate: function() {
cr.ui.DropDown.decorate($('offline-networks-list'));
this.updateLocalizedContent();
},
/**
* Updates localized content of the screen that is not updated via template.
*/
updateLocalizedContent: function() {
$('captive-portal-message-text').innerHTML = loadTimeData.getStringF(
'captivePortalMessage',
'<b id="' + CURRENT_NETWORK_NAME_ID + '"></b>',
'<a id="' + FIX_CAPTIVE_PORTAL_ID + '" class="signin-link" href="#">',
'</a>');
$(FIX_CAPTIVE_PORTAL_ID).onclick = function() {
chrome.send('showCaptivePortal');
};
$('captive-portal-proxy-message-text').innerHTML =
loadTimeData.getStringF(
'captivePortalProxyMessage',
'<a id="' + FIX_PROXY_SETTINGS_ID + '" class="signin-link" href="#">',
'</a>');
$(FIX_PROXY_SETTINGS_ID).onclick = function() {
chrome.send('openProxySettings');
};
$('update-proxy-message-text').innerHTML = loadTimeData.getStringF(
'updateProxyMessageText',
'<a id="update-proxy-error-fix-proxy" class="signin-link" href="#">',
'</a>');
$('update-proxy-error-fix-proxy').onclick = function() {
chrome.send('openProxySettings');
};
$('signin-proxy-message-text').innerHTML = loadTimeData.getStringF(
'signinProxyMessageText',
'<a id="' + RELOAD_PAGE_ID + '" class="signin-link" href="#">',
'</a>',
'<a id="signin-proxy-error-fix-proxy" class="signin-link" href="#">',
'</a>');
$(RELOAD_PAGE_ID).onclick = function() {
var gaiaScreen = $(SCREEN_GAIA_SIGNIN);
// Schedules an immediate retry.
gaiaScreen.doReload();
};
$('signin-proxy-error-fix-proxy').onclick = function() {
chrome.send('openProxySettings');
};
$('error-guest-signin').innerHTML = loadTimeData.getStringF(
'guestSignin',
'<a id="error-guest-signin-link" class="signin-link" href="#">',
'</a>');
$('error-guest-signin-link').onclick = function() {
chrome.send('launchIncognito');
};
$('error-offline-login').innerHTML = loadTimeData.getStringF(
'offlineLogin',
'<a id="error-offline-login-link" class="signin-link" href="#">',
'</a>');
$('error-offline-login-link').onclick = function() {
chrome.send('offlineLogin');
};
this.onContentChange_();
},
/**
* Event handler that is invoked just before the screen in shown.
* @param {Object} data Screen init payload.
*/
onBeforeShow: function(data) {
cr.ui.Oobe.clearErrors();
cr.ui.DropDown.show('offline-networks-list', false);
if (data === undefined)
return;
if ('uiState' in data)
this.setUIState(data['uiState']);
if ('errorState' in data && 'network' in data)
this.setErrorState(data['errorState'], data['network']);
if ('guestSigninAllowed' in data)
this.allowGuestSignin(data['guestSigninAllowed']);
if ('offlineLoginAllowed' in data)
this.allowOfflineLogin(data['offlineLoginAllowed']);
},
/**
* Event handler that is invoked just before the screen is hidden.
*/
onBeforeHide: function() {
cr.ui.DropDown.hide('offline-networks-list');
},
/**
* Buttons in oobe wizard's button strip.
* @type {array} Array of Buttons.
*/
get buttons() {
var buttons = [];
var powerwashButton = this.ownerDocument.createElement('button');
powerwashButton.id = 'error-message-restart-and-powerwash-button';
powerwashButton.textContent =
loadTimeData.getString('localStateErrorPowerwashButton');
powerwashButton.classList.add('show-with-ui-state-local-state-error');
powerwashButton.addEventListener('click', function(e) {
chrome.send('localStateErrorPowerwashButtonClicked');
e.stopPropagation();
});
buttons.push(powerwashButton);
return buttons;
},
/**
* Sets current UI state of the screen.
* @param {string} ui_state New UI state of the screen.
* @private
*/
setUIState_: function(ui_state) {
this.classList.remove(this.ui_state);
this.ui_state = ui_state;
this.classList.add(this.ui_state);
if (ui_state == ERROR_SCREEN_UI_STATE.LOCAL_STATE_ERROR) {
// Hide header bar and progress dots, because there are no way
// from the error screen about broken local state.
Oobe.getInstance().headerHidden = true;
$('progress-dots').hidden = true;
}
this.onContentChange_();
},
/**
* Sets current error state of the screen.
* @param {string} error_state New error state of the screen.
* @param {string} network Name of the current network
* @private
*/
setErrorState_: function(error_state, network) {
this.classList.remove(this.error_state);
$(CURRENT_NETWORK_NAME_ID).textContent = network;
this.error_state = error_state;
this.classList.add(this.error_state);
this.onContentChange_();
},
/* Method called after content of the screen changed.
* @private
*/
onContentChange_: function() {
if (Oobe.getInstance().currentScreen === this)
Oobe.getInstance().updateScreenSize(this);
},
/**
* Prepares error screen to show guest signin link.
* @private
*/
allowGuestSignin: function(allowed) {
this.classList.toggle('allow-guest-signin', allowed);
this.onContentChange_();
},
/**
* Prepares error screen to show offline login link.
* @private
*/
allowOfflineLogin: function(allowed) {
this.classList.toggle('allow-offline-login', allowed);
this.onContentChange_();
},
/**
* Sets current UI state of the screen.
* @param {number} ui_state New UI state of the screen.
* @private
*/
setUIState: function(ui_state) {
this.setUIState_(UI_STATES[ui_state]);
},
/**
* Sets current error state of the screen.
* @param {number} error_state New error state of the screen.
* @param {string} network Name of the current network
* @private
*/
setErrorState: function(error_state, network) {
this.setErrorState_(ERROR_STATES[error_state], network);
}
};
});
| cvsuser-chromium/chromium | chrome/browser/resources/chromeos/login/screen_error_message.js | JavaScript | bsd-3-clause | 8,584 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
(function()
{
var imageDialog = function( editor, dialogType )
{
// Load image preview.
var IMAGE = 1,
LINK = 2,
PREVIEW = 4,
CLEANUP = 8,
regexGetSize = /^\s*(\d+)((px)|\%)?\s*$/i,
regexGetSizeOrEmpty = /(^\s*(\d+)((px)|\%)?\s*$)|^$/i,
pxLengthRegex = /^\d+px$/;
var onSizeChange = function()
{
var value = this.getValue(), // This = input element.
dialog = this.getDialog(),
aMatch = value.match( regexGetSize ); // Check value
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed - > unlock ratio.
switchLockRatio( dialog, false ); // Unlock.
value = aMatch[1];
}
// Only if ratio is locked
if ( dialog.lockRatio )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
if ( this.id == 'txtHeight' )
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.width * ( value / oImageOriginal.$.height ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtWidth', value );
}
else //this.id = txtWidth.
{
if ( value && value != '0' )
value = Math.round( oImageOriginal.$.height * ( value / oImageOriginal.$.width ) );
if ( !isNaN( value ) )
dialog.setValueOf( 'info', 'txtHeight', value );
}
}
}
updatePreview( dialog );
};
var updatePreview = function( dialog )
{
//Don't load before onShow.
if ( !dialog.originalElement || !dialog.preview )
return 1;
// Read attributes and update imagePreview;
dialog.commitContent( PREVIEW, dialog.preview );
return 0;
};
// Custom commit dialog logic, where we're intended to give inline style
// field (txtdlgGenStyle) higher priority to avoid overwriting styles contribute
// by other fields.
function commitContent()
{
var args = arguments;
var inlineStyleField = this.getContentElement( 'advanced', 'txtdlgGenStyle' );
inlineStyleField && inlineStyleField.commit.apply( inlineStyleField, args );
this.foreach( function( widget )
{
if ( widget.commit && widget.id != 'txtdlgGenStyle' )
widget.commit.apply( widget, args );
});
}
// Avoid recursions.
var incommit;
// Synchronous field values to other impacted fields is required, e.g. border
// size change should alter inline-style text as well.
function commitInternally( targetFields )
{
if ( incommit )
return;
incommit = 1;
var dialog = this.getDialog(),
element = dialog.imageElement;
if ( element )
{
// Commit this field and broadcast to target fields.
this.commit( IMAGE, element );
targetFields = [].concat( targetFields );
var length = targetFields.length,
field;
for ( var i = 0; i < length; i++ )
{
field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
// May cause recursion.
field && field.setup( IMAGE, element );
}
}
incommit = 0;
}
var switchLockRatio = function( dialog, value )
{
var oImageOriginal = dialog.originalElement;
// Dialog may already closed. (#5505)
if( !oImageOriginal )
return null;
var ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
if ( value == 'check' ) // Check image ratio and original image ratio.
{
var width = dialog.getValueOf( 'info', 'txtWidth' ),
height = dialog.getValueOf( 'info', 'txtHeight' ),
originalRatio = oImageOriginal.$.width * 1000 / oImageOriginal.$.height,
thisRatio = width * 1000 / height;
dialog.lockRatio = false; // Default: unlock ratio
if ( !width && !height )
dialog.lockRatio = true;
else if ( !isNaN( originalRatio ) && !isNaN( thisRatio ) )
{
if ( Math.round( originalRatio ) == Math.round( thisRatio ) )
dialog.lockRatio = true;
}
}
else if ( value != undefined )
dialog.lockRatio = value;
else
dialog.lockRatio = !dialog.lockRatio;
}
else if ( value != 'check' ) // I can't lock ratio if ratio is unknown.
dialog.lockRatio = false;
if ( dialog.lockRatio )
ratioButton.removeClass( 'cke_btn_unlocked' );
else
ratioButton.addClass( 'cke_btn_unlocked' );
var lang = dialog._.editor.lang.image,
label = lang[ dialog.lockRatio ? 'unlockRatio' : 'lockRatio' ];
ratioButton.setAttribute( 'title', label );
ratioButton.getFirst().setText( label );
return dialog.lockRatio;
};
var resetSize = function( dialog )
{
var oImageOriginal = dialog.originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
{
dialog.setValueOf( 'info', 'txtWidth', oImageOriginal.$.width );
dialog.setValueOf( 'info', 'txtHeight', oImageOriginal.$.height );
}
updatePreview( dialog );
};
var setupDimension = function( type, element )
{
if ( type != IMAGE )
return;
function checkDimension( size, defaultValue )
{
var aMatch = size.match( regexGetSize );
if ( aMatch )
{
if ( aMatch[2] == '%' ) // % is allowed.
{
aMatch[1] += '%';
switchLockRatio( dialog, false ); // Unlock ratio
}
return aMatch[1];
}
return defaultValue;
}
var dialog = this.getDialog(),
value = '',
dimension = (( this.id == 'txtWidth' )? 'width' : 'height' ),
size = element.getAttribute( dimension );
if ( size )
value = checkDimension( size, value );
value = checkDimension( element.getStyle( dimension ), value );
this.setValue( value );
};
var previewPreloader;
var onImgLoadEvent = function()
{
// Image is ready.
var original = this.originalElement;
original.setCustomData( 'isReady', 'true' );
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// New image -> new domensions
if ( !this.dontResetSize )
resetSize( this );
if ( this.firstLoad )
CKEDITOR.tools.setTimeout( function(){ switchLockRatio( this, 'check' ); }, 0, this );
this.firstLoad = false;
this.dontResetSize = false;
};
var onImgLoadErrorEvent = function()
{
// Error. Image is not loaded.
var original = this.originalElement;
original.removeListener( 'load', onImgLoadEvent );
original.removeListener( 'error', onImgLoadErrorEvent );
original.removeListener( 'abort', onImgLoadErrorEvent );
// Set Error image.
var noimage = CKEDITOR.getUrl( editor.skinPath + 'images/noimage.png' );
if ( this.preview )
this.preview.setAttribute( 'src', noimage );
// Hide loader
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
switchLockRatio( this, false ); // Unlock.
};
var numbering = function( id )
{
return CKEDITOR.tools.getNextId() + '_' + id;
},
btnLockSizesId = numbering( 'btnLockSizes' ),
btnResetSizeId = numbering( 'btnResetSize' ),
imagePreviewLoaderId = numbering( 'ImagePreviewLoader' ),
imagePreviewBoxId = numbering( 'ImagePreviewBox' ),
previewLinkId = numbering( 'previewLink' ),
previewImageId = numbering( 'previewImage' );
return {
title : editor.lang.image[ dialogType == 'image' ? 'title' : 'titleButton' ],
minWidth : 420,
minHeight : 360,
onShow : function()
{
this.imageElement = false;
this.linkElement = false;
// Default: create a new element.
this.imageEditMode = false;
this.linkEditMode = false;
this.lockRatio = true;
this.dontResetSize = false;
this.firstLoad = true;
this.addLink = false;
var editor = this.getParentEditor(),
sel = this.getParentEditor().getSelection(),
element = sel.getSelectedElement(),
link = element && element.getAscendant( 'a' );
//Hide loader.
CKEDITOR.document.getById( imagePreviewLoaderId ).setStyle( 'display', 'none' );
// Create the preview before setup the dialog contents.
previewPreloader = new CKEDITOR.dom.element( 'img', editor.document );
this.preview = CKEDITOR.document.getById( previewImageId );
// Copy of the image
this.originalElement = editor.document.createElement( 'img' );
this.originalElement.setAttribute( 'alt', '' );
this.originalElement.setCustomData( 'isReady', 'false' );
if ( link )
{
this.linkElement = link;
this.linkEditMode = true;
// Look for Image element.
var linkChildren = link.getChildren();
if ( linkChildren.count() == 1 ) // 1 child.
{
var childTagName = linkChildren.getItem( 0 ).getName();
if ( childTagName == 'img' || childTagName == 'input' )
{
this.imageElement = linkChildren.getItem( 0 );
if ( this.imageElement.getName() == 'img' )
this.imageEditMode = 'img';
else if ( this.imageElement.getName() == 'input' )
this.imageEditMode = 'input';
}
}
// Fill out all fields.
if ( dialogType == 'image' )
this.setupContent( LINK, link );
}
if ( element && element.getName() == 'img' && !element.data( 'cke-realelement' )
|| element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'image' )
{
this.imageEditMode = element.getName();
this.imageElement = element;
}
if ( this.imageEditMode )
{
// Use the original element as a buffer from since we don't want
// temporary changes to be committed, e.g. if the dialog is canceled.
this.cleanImageElement = this.imageElement;
this.imageElement = this.cleanImageElement.clone( true, true );
// Fill out all fields.
this.setupContent( IMAGE, this.imageElement );
// Refresh LockRatio button
switchLockRatio ( this, true );
}
else
this.imageElement = editor.document.createElement( 'img' );
// Dont show preview if no URL given.
if ( !CKEDITOR.tools.trim( this.getValueOf( 'info', 'txtUrl' ) ) )
{
this.preview.removeAttribute( 'src' );
this.preview.setStyle( 'display', 'none' );
}
},
onOk : function()
{
// Edit existing Image.
if ( this.imageEditMode )
{
var imgTagName = this.imageEditMode;
// Image dialog and Input element.
if ( dialogType == 'image' && imgTagName == 'input' && confirm( editor.lang.image.button2Img ) )
{
// Replace INPUT-> IMG
imgTagName = 'img';
this.imageElement = editor.document.createElement( 'img' );
this.imageElement.setAttribute( 'alt', '' );
editor.insertElement( this.imageElement );
}
// ImageButton dialog and Image element.
else if ( dialogType != 'image' && imgTagName == 'img' && confirm( editor.lang.image.img2Button ))
{
// Replace IMG -> INPUT
imgTagName = 'input';
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttributes(
{
type : 'image',
alt : ''
}
);
editor.insertElement( this.imageElement );
}
else
{
// Restore the original element before all commits.
this.imageElement = this.cleanImageElement;
delete this.cleanImageElement;
}
}
else // Create a new image.
{
// Image dialog -> create IMG element.
if ( dialogType == 'image' )
this.imageElement = editor.document.createElement( 'img' );
else
{
this.imageElement = editor.document.createElement( 'input' );
this.imageElement.setAttribute ( 'type' ,'image' );
}
this.imageElement.setAttribute( 'alt', '' );
}
// Create a new link.
if ( !this.linkEditMode )
this.linkElement = editor.document.createElement( 'a' );
// Set attributes.
this.commitContent( IMAGE, this.imageElement );
this.commitContent( LINK, this.linkElement );
// Remove empty style attribute.
if ( !this.imageElement.getAttribute( 'style' ) )
this.imageElement.removeAttribute( 'style' );
// Insert a new Image.
if ( !this.imageEditMode )
{
if ( this.addLink )
{
//Insert a new Link.
if ( !this.linkEditMode )
{
editor.insertElement(this.linkElement);
this.linkElement.append(this.imageElement, false);
}
else //Link already exists, image not.
editor.insertElement(this.imageElement );
}
else
editor.insertElement( this.imageElement );
}
else // Image already exists.
{
//Add a new link element.
if ( !this.linkEditMode && this.addLink )
{
editor.insertElement( this.linkElement );
this.imageElement.appendTo( this.linkElement );
}
//Remove Link, Image exists.
else if ( this.linkEditMode && !this.addLink )
{
editor.getSelection().selectElement( this.linkElement );
editor.insertElement( this.imageElement );
}
}
},
onLoad : function()
{
if ( dialogType != 'image' )
this.hidePage( 'Link' ); //Hide Link tab.
var doc = this._.element.getDocument();
this.addFocusable( doc.getById( btnResetSizeId ), 5 );
this.addFocusable( doc.getById( btnLockSizesId ), 5 );
this.commitContent = commitContent;
},
onHide : function()
{
if ( this.preview )
this.commitContent( CLEANUP, this.preview );
if ( this.originalElement )
{
this.originalElement.removeListener( 'load', onImgLoadEvent );
this.originalElement.removeListener( 'error', onImgLoadErrorEvent );
this.originalElement.removeListener( 'abort', onImgLoadErrorEvent );
this.originalElement.remove();
this.originalElement = false; // Dialog is closed.
}
delete this.imageElement;
},
contents : [
{
id : 'info',
label : editor.lang.image.infoTab,
accessKey : 'I',
elements :
[
{
type : 'vbox',
padding : 0,
children :
[
{
type : 'hbox',
widths : [ '280px', '110px' ],
align : 'right',
children :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
required: true,
onChange : function()
{
var dialog = this.getDialog(),
newUrl = this.getValue();
//Update original image
if ( newUrl.length > 0 ) //Prevent from load before onShow
{
dialog = this.getDialog();
var original = dialog.originalElement;
dialog.preview.removeStyle( 'display' );
original.setCustomData( 'isReady', 'false' );
// Show loader
var loader = CKEDITOR.document.getById( imagePreviewLoaderId );
if ( loader )
loader.setStyle( 'display', '' );
original.on( 'load', onImgLoadEvent, dialog );
original.on( 'error', onImgLoadErrorEvent, dialog );
original.on( 'abort', onImgLoadErrorEvent, dialog );
original.setAttribute( 'src', newUrl );
// Query the preloader to figure out the url impacted by based href.
previewPreloader.setAttribute( 'src', newUrl );
dialog.preview.setAttribute( 'src', previewPreloader.$.src );
updatePreview( dialog );
}
// Dont show preview if no URL given.
else if ( dialog.preview )
{
dialog.preview.removeAttribute( 'src' );
dialog.preview.setStyle( 'display', 'none' );
}
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var url = element.data( 'cke-saved-src' ) || element.getAttribute( 'src' );
var field = this;
this.getDialog().dontResetSize = true;
field.setValue( url ); // And call this.onChange()
// Manually set the initial value.(#4191)
field.setInitValue();
}
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.data( 'cke-saved-src', this.getValue() );
element.setAttribute( 'src', this.getValue() );
}
else if ( type == CLEANUP )
{
element.setAttribute( 'src', '' ); // If removeAttribute doesn't work.
element.removeAttribute( 'src' );
}
},
validate : CKEDITOR.dialog.validate.notEmpty( editor.lang.image.urlMissing )
},
{
type : 'button',
id : 'browse',
// v-align with the 'txtUrl' field.
// TODO: We need something better than a fixed size here.
style : 'display:inline-block;margin-top:10px;',
align : 'center',
label : editor.lang.common.browseServer,
hidden : true,
filebrowser : 'info:txtUrl'
}
]
}
]
},
{
id : 'txtAlt',
type : 'text',
label : editor.lang.image.alt,
accessKey : 'T',
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'alt' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'alt', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'alt' );
}
}
},
{
type : 'hbox',
children :
[
{
type : 'vbox',
children :
[
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
width: '40px',
id : 'txtWidth',
label : editor.lang.common.width,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty );
if ( !aMatch )
alert( editor.lang.common.invalidWidth );
return !!aMatch;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
else if ( !value && this.isChanged( ) )
element.removeStyle( 'width' );
!internalCommit && element.removeAttribute( 'width' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'width', oImageOriginal.$.width + 'px');
}
else
element.setStyle( 'width', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'width' );
element.removeStyle( 'width' );
}
}
},
{
type : 'text',
id : 'txtHeight',
width: '40px',
label : editor.lang.common.height,
onKeyUp : onSizeChange,
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : function()
{
var aMatch = this.getValue().match( regexGetSizeOrEmpty );
if ( !aMatch )
alert( editor.lang.common.invalidHeight );
return !!aMatch;
},
setup : setupDimension,
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE )
{
if ( value )
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
else if ( !value && this.isChanged( ) )
element.removeStyle( 'height' );
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'height' );
}
else if ( type == PREVIEW )
{
var aMatch = value.match( regexGetSize );
if ( !aMatch )
{
var oImageOriginal = this.getDialog().originalElement;
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' )
element.setStyle( 'height', oImageOriginal.$.height + 'px' );
}
else
element.setStyle( 'height', CKEDITOR.tools.cssLength( value ) );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'height' );
element.removeStyle( 'height' );
}
}
}
]
},
{
type : 'html',
style : 'margin-top:30px;width:40px;height:40px;',
onLoad : function()
{
// Activate Reset button
var resetButton = CKEDITOR.document.getById( btnResetSizeId ),
ratioButton = CKEDITOR.document.getById( btnLockSizesId );
if ( resetButton )
{
resetButton.on( 'click', function(evt)
{
resetSize( this );
evt.data.preventDefault();
}, this.getDialog() );
resetButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, resetButton );
resetButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, resetButton );
}
// Activate (Un)LockRatio button
if ( ratioButton )
{
ratioButton.on( 'click', function(evt)
{
var locked = switchLockRatio( this ),
oImageOriginal = this.originalElement,
width = this.getValueOf( 'info', 'txtWidth' );
if ( oImageOriginal.getCustomData( 'isReady' ) == 'true' && width )
{
var height = oImageOriginal.$.height / oImageOriginal.$.width * width;
if ( !isNaN( height ) )
{
this.setValueOf( 'info', 'txtHeight', Math.round( height ) );
updatePreview( this );
}
}
evt.data.preventDefault();
}, this.getDialog() );
ratioButton.on( 'mouseover', function()
{
this.addClass( 'cke_btn_over' );
}, ratioButton );
ratioButton.on( 'mouseout', function()
{
this.removeClass( 'cke_btn_over' );
}, ratioButton );
}
},
html : '<div>'+
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.unlockRatio +
'" class="cke_btn_locked" id="' + btnLockSizesId + '" role="button"><span class="cke_label">' + editor.lang.image.unlockRatio + '</span></a>' +
'<a href="javascript:void(0)" tabindex="-1" title="' + editor.lang.image.resetSize +
'" class="cke_btn_reset" id="' + btnResetSizeId + '" role="button"><span class="cke_label">' + editor.lang.image.resetSize + '</span></a>'+
'</div>'
}
]
},
{
type : 'vbox',
padding : 1,
children :
[
{
type : 'text',
id : 'txtBorder',
width: '60px',
label : editor.lang.image.border,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateBorder ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
borderStyle = element.getStyle( 'border-width' );
borderStyle = borderStyle && borderStyle.match( /^(\d+px)(?: \1 \1 \1)?$/ );
value = borderStyle && parseInt( borderStyle[ 1 ], 10 );
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'border' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'border-width', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'border-style', 'solid' );
}
else if ( !value && this.isChanged() )
{
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'border' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'border' );
element.removeStyle( 'border-width' );
element.removeStyle( 'border-style' );
element.removeStyle( 'border-color' );
}
}
},
{
type : 'text',
id : 'txtHSpace',
width: '60px',
label : editor.lang.image.hSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateHSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginLeftPx,
marginRightPx,
marginLeftStyle = element.getStyle( 'margin-left' ),
marginRightStyle = element.getStyle( 'margin-right' );
marginLeftStyle = marginLeftStyle && marginLeftStyle.match( pxLengthRegex );
marginRightStyle = marginRightStyle && marginRightStyle.match( pxLengthRegex );
marginLeftPx = parseInt( marginLeftStyle, 10 );
marginRightPx = parseInt( marginRightStyle, 10 );
value = ( marginLeftPx == marginRightPx ) && marginLeftPx;
isNaN( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'hspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-left', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-right', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'hspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'hspace' );
element.removeStyle( 'margin-left' );
element.removeStyle( 'margin-right' );
}
}
},
{
type : 'text',
id : 'txtVSpace',
width : '60px',
label : editor.lang.image.vSpace,
'default' : '',
onKeyUp : function()
{
updatePreview( this.getDialog() );
},
onChange : function()
{
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
validate : CKEDITOR.dialog.validate.integer( editor.lang.image.validateVSpace ),
setup : function( type, element )
{
if ( type == IMAGE )
{
var value,
marginTopPx,
marginBottomPx,
marginTopStyle = element.getStyle( 'margin-top' ),
marginBottomStyle = element.getStyle( 'margin-bottom' );
marginTopStyle = marginTopStyle && marginTopStyle.match( pxLengthRegex );
marginBottomStyle = marginBottomStyle && marginBottomStyle.match( pxLengthRegex );
marginTopPx = parseInt( marginTopStyle, 10 );
marginBottomPx = parseInt( marginBottomStyle, 10 );
value = ( marginTopPx == marginBottomPx ) && marginTopPx;
isNaN ( parseInt( value, 10 ) ) && ( value = element.getAttribute( 'vspace' ) );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = parseInt( this.getValue(), 10 );
if ( type == IMAGE || type == PREVIEW )
{
if ( !isNaN( value ) )
{
element.setStyle( 'margin-top', CKEDITOR.tools.cssLength( value ) );
element.setStyle( 'margin-bottom', CKEDITOR.tools.cssLength( value ) );
}
else if ( !value && this.isChanged( ) )
{
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
if ( !internalCommit && type == IMAGE )
element.removeAttribute( 'vspace' );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'vspace' );
element.removeStyle( 'margin-top' );
element.removeStyle( 'margin-bottom' );
}
}
},
{
id : 'cmbAlign',
type : 'select',
widths : [ '35%','65%' ],
style : 'width:90px',
label : editor.lang.common.align,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.alignLeft , 'left'],
[ editor.lang.common.alignRight , 'right']
// Backward compatible with v2 on setup when specified as attribute value,
// while these values are no more available as select options.
// [ editor.lang.image.alignAbsBottom , 'absBottom'],
// [ editor.lang.image.alignAbsMiddle , 'absMiddle'],
// [ editor.lang.image.alignBaseline , 'baseline'],
// [ editor.lang.image.alignTextTop , 'text-top'],
// [ editor.lang.image.alignBottom , 'bottom'],
// [ editor.lang.image.alignMiddle , 'middle'],
// [ editor.lang.image.alignTop , 'top']
],
onChange : function()
{
updatePreview( this.getDialog() );
commitInternally.call( this, 'advanced:txtdlgGenStyle' );
},
setup : function( type, element )
{
if ( type == IMAGE )
{
var value = element.getStyle( 'float' );
switch( value )
{
// Ignore those unrelated values.
case 'inherit':
case 'none':
value = '';
}
!value && ( value = ( element.getAttribute( 'align' ) || '' ).toLowerCase() );
this.setValue( value );
}
},
commit : function( type, element, internalCommit )
{
var value = this.getValue();
if ( type == IMAGE || type == PREVIEW )
{
if ( value )
element.setStyle( 'float', value );
else
element.removeStyle( 'float' );
if ( !internalCommit && type == IMAGE )
{
value = ( element.getAttribute( 'align' ) || '' ).toLowerCase();
switch( value )
{
// we should remove it only if it matches "left" or "right",
// otherwise leave it intact.
case 'left':
case 'right':
element.removeAttribute( 'align' );
}
}
}
else if ( type == CLEANUP )
element.removeStyle( 'float' );
}
}
]
}
]
},
{
type : 'vbox',
height : '250px',
children :
[
{
type : 'html',
style : 'width:95%;',
html : '<div>' + CKEDITOR.tools.htmlEncode( editor.lang.common.preview ) +'<br>'+
'<div id="' + imagePreviewLoaderId + '" class="ImagePreviewLoader" style="display:none"><div class="loading"> </div></div>'+
'<div id="' + imagePreviewBoxId + '" class="ImagePreviewBox"><table><tr><td>'+
'<a href="javascript:void(0)" target="_blank" onclick="return false;" id="' + previewLinkId + '">'+
'<img id="' + previewImageId + '" alt="" /></a>' +
( editor.config.image_previewText ||
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. '+
'Maecenas feugiat consequat diam. Maecenas metus. Vivamus diam purus, cursus a, commodo non, facilisis vitae, '+
'nulla. Aenean dictum lacinia tortor. Nunc iaculis, nibh non iaculis aliquam, orci felis euismod neque, sed ornare massa mauris sed velit. Nulla pretium mi et risus. Fusce mi pede, tempor id, cursus ac, ullamcorper nec, enim. Sed tortor. Curabitur molestie. Duis velit augue, condimentum at, ultrices a, luctus ut, orci. Donec pellentesque egestas eros. Integer cursus, augue in cursus faucibus, eros pede bibendum sem, in tempus tellus justo quis ligula. Etiam eget tortor. Vestibulum rutrum, est ut placerat elementum, lectus nisl aliquam velit, tempor aliquam eros nunc nonummy metus. In eros metus, gravida a, gravida sed, lobortis id, turpis. Ut ultrices, ipsum at venenatis fringilla, sem nulla lacinia tellus, eget aliquet turpis mauris non enim. Nam turpis. Suspendisse lacinia. Curabitur ac tortor ut ipsum egestas elementum. Nunc imperdiet gravida mauris.' ) +
'</td></tr></table></div></div>'
}
]
}
]
}
]
},
{
id : 'Link',
label : editor.lang.link.title,
padding : 0,
elements :
[
{
id : 'txtUrl',
type : 'text',
label : editor.lang.common.url,
style : 'width: 100%',
'default' : '',
setup : function( type, element )
{
if ( type == LINK )
{
var href = element.data( 'cke-saved-href' );
if ( !href )
href = element.getAttribute( 'href' );
this.setValue( href );
}
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
{
var url = decodeURI( this.getValue() );
element.data( 'cke-saved-href', url );
element.setAttribute( 'href', url );
if ( this.getValue() || !editor.config.image_removeLinkByEmptyURL )
this.getDialog().addLink = true;
}
}
}
},
{
type : 'button',
id : 'browse',
filebrowser :
{
action : 'Browse',
target: 'Link:txtUrl',
url: editor.config.filebrowserImageBrowseLinkUrl
},
style : 'float:right',
hidden : true,
label : editor.lang.common.browseServer
},
{
id : 'cmbTarget',
type : 'select',
label : editor.lang.common.target,
'default' : '',
items :
[
[ editor.lang.common.notSet , ''],
[ editor.lang.common.targetNew , '_blank'],
[ editor.lang.common.targetTop , '_top'],
[ editor.lang.common.targetSelf , '_self'],
[ editor.lang.common.targetParent , '_parent']
],
setup : function( type, element )
{
if ( type == LINK )
this.setValue( element.getAttribute( 'target' ) || '' );
},
commit : function( type, element )
{
if ( type == LINK )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'target', this.getValue() );
}
}
}
]
},
{
id : 'Upload',
hidden : true,
filebrowser : 'uploadButton',
label : editor.lang.image.upload,
elements :
[
{
type : 'file',
id : 'upload',
label : editor.lang.image.btnUpload,
style: 'height:40px',
size : 38
},
{
type : 'fileButton',
id : 'uploadButton',
filebrowser : 'info:txtUrl',
label : editor.lang.image.btnUpload,
'for' : [ 'Upload', 'upload' ]
}
]
},
{
id : 'advanced',
label : editor.lang.common.advancedTab,
elements :
[
{
type : 'hbox',
widths : [ '50%', '25%', '25%' ],
children :
[
{
type : 'text',
id : 'linkId',
label : editor.lang.common.id,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'id' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'id', this.getValue() );
}
}
},
{
id : 'cmbLangDir',
type : 'select',
style : 'width : 100px;',
label : editor.lang.common.langDir,
'default' : '',
items :
[
[ editor.lang.common.notSet, '' ],
[ editor.lang.common.langDirLtr, 'ltr' ],
[ editor.lang.common.langDirRtl, 'rtl' ]
],
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'dir' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'dir', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtLangCode',
label : editor.lang.common.langCode,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'lang' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'lang', this.getValue() );
}
}
}
]
},
{
type : 'text',
id : 'txtGenLongDescr',
label : editor.lang.common.longDescr,
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'longDesc' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'longDesc', this.getValue() );
}
}
},
{
type : 'hbox',
widths : [ '50%', '50%' ],
children :
[
{
type : 'text',
id : 'txtGenClass',
label : editor.lang.common.cssClass,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'class' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'class', this.getValue() );
}
}
},
{
type : 'text',
id : 'txtGenTitle',
label : editor.lang.common.advisoryTitle,
'default' : '',
onChange : function()
{
updatePreview( this.getDialog() );
},
setup : function( type, element )
{
if ( type == IMAGE )
this.setValue( element.getAttribute( 'title' ) );
},
commit : function( type, element )
{
if ( type == IMAGE )
{
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'title', this.getValue() );
}
else if ( type == PREVIEW )
{
element.setAttribute( 'title', this.getValue() );
}
else if ( type == CLEANUP )
{
element.removeAttribute( 'title' );
}
}
}
]
},
{
type : 'text',
id : 'txtdlgGenStyle',
label : editor.lang.common.cssStyle,
'default' : '',
setup : function( type, element )
{
if ( type == IMAGE )
{
var genStyle = element.getAttribute( 'style' );
if ( !genStyle && element.$.style.cssText )
genStyle = element.$.style.cssText;
this.setValue( genStyle );
var height = element.$.style.height,
width = element.$.style.width,
aMatchH = ( height ? height : '' ).match( regexGetSize ),
aMatchW = ( width ? width : '').match( regexGetSize );
this.attributesInStyle =
{
height : !!aMatchH,
width : !!aMatchW
};
}
},
onChange : function ()
{
commitInternally.call( this,
[ 'info:cmbFloat', 'info:cmbAlign',
'info:txtVSpace', 'info:txtHSpace',
'info:txtBorder',
'info:txtWidth', 'info:txtHeight' ] );
updatePreview( this );
},
commit : function( type, element )
{
if ( type == IMAGE && ( this.getValue() || this.isChanged() ) )
{
element.setAttribute( 'style', this.getValue() );
}
}
}
]
}
]
};
};
CKEDITOR.dialog.add( 'image', function( editor )
{
return imageDialog( editor, 'image' );
});
CKEDITOR.dialog.add( 'imagebutton', function( editor )
{
return imageDialog( editor, 'imagebutton' );
});
})();
| fredd-for/codice.v.1.1 | ckeditor/_source/plugins/image/dialogs/image.js | JavaScript | bsd-3-clause | 46,523 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
const FB_MODULE_RE = /^(.*) \[from (.*)\]$/;
const cachedDisplayNames = new WeakMap();
function getDisplayName(type: Function): string {
if (cachedDisplayNames.has(type)) {
return cachedDisplayNames.get(type);
}
let displayName = type.displayName || type.name || 'Unknown';
// Facebook-specific hack to turn "Image [from Image.react]" into just "Image".
// We need displayName with module name for error reports but it clutters the DevTools.
const match = displayName.match(FB_MODULE_RE);
if (match) {
const componentName = match[1];
const moduleName = match[2];
if (componentName && moduleName) {
if (
moduleName === componentName ||
moduleName.startsWith(componentName + '.')
) {
displayName = componentName;
}
}
}
cachedDisplayNames.set(type, displayName);
return displayName;
}
module.exports = getDisplayName;
| jhen0409/react-devtools | backend/getDisplayName.js | JavaScript | bsd-3-clause | 1,237 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Messages block
*
* @category Mage
* @package Mage_Core
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Core_Block_Messages extends Mage_Core_Block_Template
{
/**
* Messages collection
*
* @var Mage_Core_Model_Message_Collection
*/
protected $_messages;
/**
* Store first level html tag name for messages html output
*
* @var string
*/
protected $_messagesFirstLevelTagName = 'ul';
/**
* Store second level html tag name for messages html output
*
* @var string
*/
protected $_messagesSecondLevelTagName = 'li';
/**
* Store content wrapper html tag name for messages html output
*
* @var string
*/
protected $_messagesContentWrapperTagName = 'span';
/**
* Flag which require message text escape
*
* @var bool
*/
protected $_escapeMessageFlag = false;
/**
* Storage for used types of message storages
*
* @var array
*/
protected $_usedStorageTypes = array('core/session');
public function _prepareLayout()
{
$this->addMessages(Mage::getSingleton('core/session')->getMessages(true));
parent::_prepareLayout();
}
/**
* Set message escape flag
* @param bool $flag
* @return Mage_Core_Block_Messages
*/
public function setEscapeMessageFlag($flag)
{
$this->_escapeMessageFlag = $flag;
return $this;
}
/**
* Set messages collection
*
* @param Mage_Core_Model_Message_Collection $messages
* @return Mage_Core_Block_Messages
*/
public function setMessages(Mage_Core_Model_Message_Collection $messages)
{
$this->_messages = $messages;
return $this;
}
/**
* Add messages to display
*
* @param Mage_Core_Model_Message_Collection $messages
* @return Mage_Core_Block_Messages
*/
public function addMessages(Mage_Core_Model_Message_Collection $messages)
{
foreach ($messages->getItems() as $message) {
$this->getMessageCollection()->add($message);
}
return $this;
}
/**
* Retrieve messages collection
*
* @return Mage_Core_Model_Message_Collection
*/
public function getMessageCollection()
{
if (!($this->_messages instanceof Mage_Core_Model_Message_Collection)) {
$this->_messages = Mage::getModel('core/message_collection');
}
return $this->_messages;
}
/**
* Adding new message to message collection
*
* @param Mage_Core_Model_Message_Abstract $message
* @return Mage_Core_Block_Messages
*/
public function addMessage(Mage_Core_Model_Message_Abstract $message)
{
$this->getMessageCollection()->add($message);
return $this;
}
/**
* Adding new error message
*
* @param string $message
* @return Mage_Core_Block_Messages
*/
public function addError($message)
{
$this->addMessage(Mage::getSingleton('core/message')->error($message));
return $this;
}
/**
* Adding new warning message
*
* @param string $message
* @return Mage_Core_Block_Messages
*/
public function addWarning($message)
{
$this->addMessage(Mage::getSingleton('core/message')->warning($message));
return $this;
}
/**
* Adding new nitice message
*
* @param string $message
* @return Mage_Core_Block_Messages
*/
public function addNotice($message)
{
$this->addMessage(Mage::getSingleton('core/message')->notice($message));
return $this;
}
/**
* Adding new success message
*
* @param string $message
* @return Mage_Core_Block_Messages
*/
public function addSuccess($message)
{
$this->addMessage(Mage::getSingleton('core/message')->success($message));
return $this;
}
/**
* Retrieve messages array by message type
*
* @param string $type
* @return array
*/
public function getMessages($type=null)
{
return $this->getMessageCollection()->getItems($type);
}
/**
* Retrieve messages in HTML format
*
* @param string $type
* @return string
*/
public function getHtml($type=null)
{
$html = '<' . $this->_messagesFirstLevelTagName . ' id="admin_messages">';
foreach ($this->getMessages($type) as $message) {
$html.= '<' . $this->_messagesSecondLevelTagName . ' class="'.$message->getType().'-msg">'
. ($this->_escapeMessageFlag) ? $this->htmlEscape($message->getText()) : $message->getText()
. '</' . $this->_messagesSecondLevelTagName . '>';
}
$html .= '</' . $this->_messagesFirstLevelTagName . '>';
return $html;
}
/**
* Retrieve messages in HTML format grouped by type
*
* @param string $type
* @return string
*/
public function getGroupedHtml()
{
$types = array(
Mage_Core_Model_Message::ERROR,
Mage_Core_Model_Message::WARNING,
Mage_Core_Model_Message::NOTICE,
Mage_Core_Model_Message::SUCCESS
);
$html = '';
foreach ($types as $type) {
if ( $messages = $this->getMessages($type) ) {
if ( !$html ) {
$html .= '<' . $this->_messagesFirstLevelTagName . ' class="messages">';
}
$html .= '<' . $this->_messagesSecondLevelTagName . ' class="' . $type . '-msg">';
$html .= '<' . $this->_messagesFirstLevelTagName . '>';
foreach ( $messages as $message ) {
$html.= '<' . $this->_messagesSecondLevelTagName . '>';
$html.= '<' . $this->_messagesContentWrapperTagName . '>';
$html.= ($this->_escapeMessageFlag) ? $this->htmlEscape($message->getText()) : $message->getText();
$html.= '</' . $this->_messagesContentWrapperTagName . '>';
$html.= '</' . $this->_messagesSecondLevelTagName . '>';
}
$html .= '</' . $this->_messagesFirstLevelTagName . '>';
$html .= '</' . $this->_messagesSecondLevelTagName . '>';
}
}
if ( $html) {
$html .= '</' . $this->_messagesFirstLevelTagName . '>';
}
return $html;
}
protected function _toHtml()
{
return $this->getGroupedHtml();
}
/**
* Set messages first level html tag name for output messages as html
*
* @param string $tagName
*/
public function setMessagesFirstLevelTagName($tagName)
{
$this->_messagesFirstLevelTagName = $tagName;
}
/**
* Set messages first level html tag name for output messages as html
*
* @param string $tagName
*/
public function setMessagesSecondLevelTagName($tagName)
{
$this->_messagesSecondLevelTagName = $tagName;
}
/**
* Get cache key informative items
*
* @return array
*/
public function getCacheKeyInfo()
{
return array(
'storage_types' => serialize($this->_usedStorageTypes)
);
}
/**
* Add used storage type
*
* @param string $type
*/
public function addStorageType($type)
{
$this->_usedStorageTypes[] = $type;
}
}
| 5452/durex | includes/src/Mage_Core_Block_Messages.php | PHP | bsd-3-clause | 8,543 |
from django.contrib import admin
from panoptes.tracking.models import AccountFilter
class AccountFilterAdmin(admin.ModelAdmin):
list_display = ('location', 'include_users', 'exclude_users')
ordering = ('location',)
admin.site.register(AccountFilter, AccountFilterAdmin)
| cilcoberlin/panoptes | panoptes/tracking/admin.py | Python | bsd-3-clause | 277 |
'''
c++ finally
'''
def myfunc():
b = False
try:
print('trying something that will fail...')
print('some call that fails at runtime')
f = open('/tmp/nosuchfile')
except:
print('got exception')
finally:
print('finally cleanup')
b = True
TestError( b == True )
def main():
myfunc()
| kustomzone/Rusthon | regtests/c++/try_except_finally.py | Python | bsd-3-clause | 301 |
import {describe, it, display} from "./framework"
import {LayoutDOM, Row, Column, GridBox, Spacer, Tabs, Panel} from "@bokehjs/models/layouts/index"
import {ToolbarBox} from "@bokehjs/models/tools/toolbar_box"
import {
Button, Toggle, Dropdown,
CheckboxGroup, RadioGroup,
CheckboxButtonGroup, RadioButtonGroup,
TextInput, AutocompleteInput,
Select, MultiSelect,
Slider, RangeSlider, DateSlider, DateRangeSlider,
DatePicker,
Paragraph, Div, PreText,
} from "@bokehjs/models/widgets/index"
import {figure, gridplot, color} from "@bokehjs/api/plotting"
import {Matrix} from "@bokehjs/core/util/data_structures"
import {range} from "@bokehjs/core/util/array"
import {SizingPolicy} from "@bokehjs/core/layout"
import {Color} from "@bokehjs/core/types"
import {Location} from "@bokehjs/core/enums"
function grid(items: Matrix<LayoutDOM> | LayoutDOM[][], opts?: Partial<GridBox.Attrs>): GridBox {
const children = Matrix.from(items).to_sparse()
return new GridBox({...opts, children})
}
function row(children: LayoutDOM[], opts?: Partial<Row.Attrs>): Row {
return new Row({...opts, children})
}
function column(children: LayoutDOM[], opts?: Partial<Column.Attrs>): Column {
return new Column({...opts, children})
}
const spacer =
(width_policy: SizingPolicy, height_policy: SizingPolicy,
width: number | null, height: number | null,
min_width?: number, min_height?: number,
max_width?: number, max_height?: number) => (color: Color): Spacer => {
return new Spacer({
width_policy, height_policy,
width, height,
min_width, min_height,
max_width, max_height,
background: color,
})
}
describe("Row", () => {
it("should allow to expand when child policy is max", async () => {
const s0 = spacer("max", "fixed", null, 40)("red")
const s1 = spacer("min", "fixed", 120, 30)("green")
const l = row([s0, s1])
await display(l, [300, 300])
})
/* XXX: fix "max" column policy
it("should allow to expand when column policy is max", async () => {
const s0 = spacer("fixed", "fixed", 80, 40)("red")
const s1 = spacer("fixed", "fixed", 120, 30)("green")
const l = row([s0, s1], {cols: {0: "max", 1: "min"}})
await display(l, [300, 300])
})
*/
})
describe("3x3 GridBox", () => {
const colors = Matrix.from([
["red", "green", "blue" ],
["gray", "orange", "fuchsia"],
["aqua", "maroon", "yellow" ],
])
it("fixed spacers 50px x 50px", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const items = colors.apply([
[s0, s0, s0],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items)
await display(l, [300, 300])
})
it("fixed spacers 50px x 50px, spacing 5px", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const items = colors.apply([
[s0, s0, s0],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {spacing: 5})
await display(l, [300, 300])
})
it("fixed spacers 50px x 50px, vspacing 5px, hspacing 10px", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const items = colors.apply([
[s0, s0, s0],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {spacing: [5, 10]})
await display(l, [300, 300])
})
it("fixed and 1 x-max spacers, c2 auto", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const s1 = spacer("max", "fixed", 50, 50)
const items = colors.apply([
[s0, s0, s1],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {cols: {2: {policy: "auto"}}})
await display(l, [300, 300])
})
it("fixed and 2 x-max spacers, c2 auto", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const s1 = spacer("max", "fixed", 50, 50)
const items = colors.apply([
[s0, s1, s1],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {cols: {2: {policy: "auto"}}})
await display(l, [300, 300])
})
it("fixed and 2 x-max spacers, c2 flex=2", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const s1 = spacer("max", "fixed", 50, 50)
const items = colors.apply([
[s0, s1, s1],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {cols: {2: {policy: "max", flex: 2}}})
await display(l, [300, 300])
})
it("fixed and 3 x-max spacers, c2 flex=2", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const s1 = spacer("max", "fixed", 50, 50)
const items = colors.apply([
[s1, s1, s1],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {cols: {2: {policy: "max", flex: 2}}})
await display(l, [300, 300])
})
it("fixed and 3 x-max spacers, c2 flex=2 align=end", async () => {
const s0 = spacer("fixed", "fixed", 50, 50)
const s1 = spacer("max", "fixed", 50, 50)
const items = colors.apply([
[s1, s1, s1],
[s0, s0, s0],
[s0, s0, s0],
])
const l = grid(items, {cols: {2: {policy: "max", flex: 2, align: "end"}}})
await display(l, [300, 300])
})
it("fixed, inconsistent width/height, row/col auto align=start", async () => {
const s = (width: number, height: number) => spacer("fixed", "fixed", width, height)
const items = colors.apply([
[s(60, 30), s(30, 60), s(90, 90)],
[s(30, 60), s(90, 30), s(30, 90)],
[s(90, 90), s(60, 90), s(60, 30)],
])
const l = grid(items, {
rows: {"*": {policy: "auto", align: "start"}},
cols: {"*": {policy: "auto", align: "start"}},
})
await display(l, [300, 300])
})
it("fixed, inconsistent width/height, row/col auto align=center", async () => {
const s = (width: number, height: number) => spacer("fixed", "fixed", width, height)
const items = colors.apply([
[s(60, 30), s(30, 60), s(90, 90)],
[s(30, 60), s(90, 30), s(30, 90)],
[s(90, 90), s(60, 90), s(60, 30)],
])
const l = grid(items, {
rows: {"*": {policy: "auto", align: "center"}},
cols: {"*": {policy: "auto", align: "center"}},
})
await display(l, [300, 300])
})
it("fixed, inconsistent width/height, row/col auto align=end", async () => {
const s = (width: number, height: number) => spacer("fixed", "fixed", width, height)
const items = colors.apply([
[s(60, 30), s(30, 60), s(90, 90)],
[s(30, 60), s(90, 30), s(30, 90)],
[s(90, 90), s(60, 90), s(60, 30)],
])
const l = grid(items, {
rows: {"*": {policy: "auto", align: "end"}},
cols: {"*": {policy: "auto", align: "end"}},
})
await display(l, [300, 300])
})
})
describe("Plot", () => {
const fig = (location: Location | null, title?: string) => {
const p = figure({
width: 200, height: 200, tools: "pan,reset", title,
toolbar_location: location, title_location: location})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
return p
}
it("should allow no toolbar and no title", async () => {
await display(fig(null), [300, 300])
})
it("should allow toolbar placement above without title", async () => {
await display(fig("above"), [300, 300])
})
it("should allow toolbar placement below without title", async () => {
await display(fig("below"), [300, 300])
})
it("should allow toolbar placement left without title", async () => {
await display(fig("left"), [300, 300])
})
it("should allow toolbar placement right without title", async () => {
await display(fig("right"), [300, 300])
})
it("should allow toolbar placement above with title", async () => {
await display(fig("above", "Plot Title"), [300, 300])
})
it("should allow toolbar placement below with title", async () => {
await display(fig("below", "Plot Title"), [300, 300])
})
it("should allow toolbar placement left with title", async () => {
await display(fig("left", "Plot Title"), [300, 300])
})
it("should allow toolbar placement right with title", async () => {
await display(fig("right", "Plot Title"), [300, 300])
})
it("should allow fixed x fixed plot", async () => {
const p = figure({width_policy: "fixed", width: 200, height_policy: "fixed", height: 200})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x fixed plot", async () => {
const p = figure({width_policy: "max", height_policy: "fixed", height: 200})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow fixed x max plot", async () => {
const p = figure({width_policy: "fixed", width: 200, height_policy: "max"})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x max plot", async () => {
const p = figure({width_policy: "max", height_policy: "max"})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x fixed plot, aspect 0.8", async () => {
const p = figure({width_policy: "max", height_policy: "fixed", height: 200, aspect_ratio: 0.8})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow fixed x max plot, aspect 0.8", async () => {
const p = figure({width_policy: "fixed", width: 200, height_policy: "max", aspect_ratio: 0.8})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x max plot, aspect 0.8", async () => {
const p = figure({width_policy: "max", height_policy: "max", aspect_ratio: 0.8})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x fixed plot, aspect 1.0", async () => {
const p = figure({width_policy: "max", height_policy: "fixed", height: 200, aspect_ratio: 1.0})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow fixed x max plot, aspect 1.0", async () => {
const p = figure({width_policy: "fixed", width: 200, height_policy: "max", aspect_ratio: 1.0})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x max plot, aspect 1.0", async () => {
const p = figure({width_policy: "max", height_policy: "max", aspect_ratio: 1.0})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x fixed plot, aspect 1.25", async () => {
const p = figure({width_policy: "max", height_policy: "fixed", height: 200, aspect_ratio: 1.25})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow fixed x max plot, aspect 1.25", async () => {
const p = figure({width_policy: "fixed", width: 200, height_policy: "max", aspect_ratio: 1.25})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow max x max plot, aspect 1.25", async () => {
const p = figure({width_policy: "max", height_policy: "max", aspect_ratio: 1.25})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(p, [300, 300])
})
it("should allow fixed frame 300px x 300px", async () => {
const fig = figure({frame_width: 300, frame_height: 300})
fig.circle([0, 5, 10], [0, 5, 10], {size: 10})
await display(fig, [500, 500])
})
it("should allow fixed frame 200px x 200px in a layout", async () => {
const fig0 = figure({frame_width: 200, frame_height: 200})
fig0.circle([0, 5, 10], [0, 5, 10], {size: 10})
const fig1 = figure({frame_width: 200, frame_height: 200})
fig1.circle([0, 5, 10], [0, 5, 10], {size: 10})
const row = new Row({children: [fig0, fig1]})
await display(row, [600, 300])
})
it("should allow fixed frame 200px x 200px in a layout with a title", async () => {
const fig0 = figure({frame_width: 200, frame_height: 200, title: "A title"})
fig0.circle([0, 5, 10], [0, 5, 10], {size: 10})
const fig1 = figure({frame_width: 200, frame_height: 200})
fig1.circle([0, 5, 10], [0, 5, 10], {size: 10})
const row = new Row({children: [fig0, fig1]})
await display(row, [600, 300])
})
})
describe("ToolbarBox", () => {
const fig = (width: number = 100, height: number = 100) => {
const p = figure({width, height, tools: "pan,reset,help", toolbar_location: null})
p.circle([0, 5, 10], [0, 5, 10], {size: 10})
return p
}
function tb_above() {
const p = fig(250, 250)
const tb = new ToolbarBox({toolbar: p.toolbar, toolbar_location: "above"})
return column([tb, p])
}
function tb_below() {
const p = fig(250, 250)
const tb = new ToolbarBox({toolbar: p.toolbar, toolbar_location: "below"})
return column([p, tb])
}
function tb_left() {
const p = fig(250, 250)
const tb = new ToolbarBox({toolbar: p.toolbar, toolbar_location: "left"})
return row([tb, p])
}
function tb_right() {
const p = fig(250, 250)
const tb = new ToolbarBox({toolbar: p.toolbar, toolbar_location: "right"})
return row([p, tb])
}
it("should allow placement above a figure", async () => {
await display(tb_above(), [300, 300])
})
it("should allow placement below a figure", async () => {
await display(tb_below(), [300, 300])
})
it("should allow placement left of a figure", async () => {
await display(tb_left(), [300, 300])
})
it("should allow placement right of a figure", async () => {
await display(tb_right(), [300, 300])
})
})
describe("gridplot()", () => {
const layout = (toolbar_location: Location | null) => {
const coeffs = [10**3, 10**6, 10**9]
const values = (c: number) => range(10).map((v) => c*v)
const figs = coeffs.map((ycoeff) => {
return coeffs.map((xcoeff) => {
const fig = figure({plot_height: 200, plot_width: 200})
fig.xaxis.map((axis) => (axis.formatter as any).use_scientific = false)
fig.yaxis.map((axis) => (axis.formatter as any).use_scientific = false)
fig.xaxis.map((axis) => axis.major_label_orientation = "vertical")
fig.yaxis.map((axis) => axis.major_label_orientation = "horizontal")
fig.circle(values(xcoeff), values(ycoeff), {size: 5})
return fig
})
})
return gridplot(figs, {toolbar_location})
}
it("should align axes when toolbar_location=null", async () => {
await display(layout(null), [800, 800])
})
it("should align axes when toolbar_location=above", async () => {
await display(layout("above"), [800, 800])
})
it("should align axes when toolbar_location=right", async () => {
await display(layout("right"), [800, 800])
})
it("should align axes when toolbar_location=left", async () => {
await display(layout("left"), [800, 800])
})
it("should align axes when toolbar_location=below", async () => {
await display(layout("below"), [800, 800])
})
})
describe("GridBox", () => {
it("should allow 20x20 grids of 25x25 px spacers", async () => {
const s0 = spacer("fixed", "fixed", 25, 25)
const ncols = 20
const nrows = 20
const items = new Matrix(nrows, ncols, (row, col) => {
const x = 100.0/ncols*col
const y = 100.0/nrows*row
const [r, g, b] = [Math.floor(50 + 2*x), Math.floor(30 + 2*y), 150]
return s0(color(r, g, b))
})
const l = grid(items)
await display(l, [600, 600])
})
})
describe("Widgets", () => {
it("should allow Button", async () => {
const obj = new Button({label: "Button 1", button_type: "primary"})
await display(obj, [500, 100])
})
it("should allow Toggle", async () => {
const obj = new Toggle({label: "Toggle 1", button_type: "primary"})
await display(obj, [500, 100])
})
it("should allow Dropdown", async () => {
const menu = ["Item 1", "Item 2", null, "Item 3"]
const obj = new Dropdown({label: "Dropdown 1", button_type: "primary", menu})
await display(obj, [500, 100])
})
it("should allow split Dropdown", async () => {
const menu = ["Item 1", "Item 2", null, "Item 3"]
const obj = new Dropdown({label: "Dropdown 2", button_type: "primary", menu, split: true})
await display(obj, [500, 100])
})
it("should allow CheckboxGroup", async () => {
const obj = new CheckboxGroup({labels: ["Option 1", "Option 2", "Option 3"], active: [0, 1]})
await display(obj, [500, 100])
})
it("should allow RadioGroup", async () => {
const obj = new RadioGroup({labels: ["Option 1", "Option 2", "Option 3"], active: 0})
await display(obj, [500, 100])
})
it("should allow CheckboxButtonGroup", async () => {
const obj = new CheckboxButtonGroup({labels: ["Option 1", "Option 2", "Option 3"], active: [0, 1]})
await display(obj, [500, 100])
})
it("should allow RadioButtonGroup", async () => {
const obj = new RadioButtonGroup({labels: ["Option 1", "Option 2", "Option 3"], active: 0})
await display(obj, [500, 100])
})
it("should allow TextInput", async () => {
const obj = new TextInput({placeholder: "Enter value ..."})
await display(obj, [500, 100])
})
it("should allow AutocompleteInput", async () => {
const completions = ["aaa", "aab", "aac", "baa", "caa"]
const obj = new AutocompleteInput({placeholder: "Enter value ...", completions})
await display(obj, [500, 100])
})
it("should allow Select", async () => {
const obj = new Select({options: ["Option 1", "Option 2", "Option 3"]})
await display(obj, [500, 100])
})
it("should allow MultiSelect", async () => {
const options = range(16).map((i) => `Option ${i+1}`)
const obj = new MultiSelect({options, size: 6})
await display(obj, [500, 150])
})
it("should allow Slider", async () => {
const obj = new Slider({value: 10, start: 0, end: 100, step: 0.5})
await display(obj, [500, 100])
})
it("should allow DateSlider", async () => {
const obj = new DateSlider({
value: Date.UTC(2016, 1, 1),
start: Date.UTC(2015, 1, 1),
end: Date.UTC(2017, 12, 31),
})
await display(obj, [500, 100])
})
it("should allow RangeSlider", async () => {
const obj = new RangeSlider({value: [10, 90], start: 0, end: 100, step: 0.5})
await display(obj, [500, 100])
})
it("should allow DateRangeSlider", async () => {
const obj = new DateRangeSlider({
value: [Date.UTC(2016, 1, 1), Date.UTC(2016, 12, 31)],
start: Date.UTC(2015, 1, 1),
end: Date.UTC(2017, 12, 31),
})
await display(obj, [500, 100])
})
it("should allow DatePicker", async () => {
const obj = new DatePicker({value: new Date(Date.UTC(2017, 8, 1)).toDateString()})
await display(obj, [500, 100])
})
it("should allow Div", async () => {
const obj = new Div({text: "some <b>text</b>"})
await display(obj, [500, 100])
})
it("should allow Paragraph", async () => {
const obj = new Paragraph({text: "some text"})
await display(obj, [500, 100])
})
it("should allow PreText", async () => {
const obj = new PreText({text: "some text"})
await display(obj, [500, 100])
})
})
describe("Rows of widgets", () => {
it("should allow different content and fixed height", async () => {
const w0 = new TextInput({value: "Widget 1"})
const w1 = new TextInput({value: "Widget 2", height: 50})
const row = new Row({children: [w0, w1]})
await display(row, [500, 100])
})
})
describe("Tabs", () => {
const panel = (color: string) => {
const p = figure({width: 200, height: 200, toolbar_location: null})
p.circle([0, 5, 10], [0, 5, 10], {size: 10, color})
return new Panel({title: color, child: p})
}
const tabs = (tabs_location: Location) => {
return new Tabs({tabs: ["red", "green", "blue"].map(panel), tabs_location})
}
it("should allow tabs header location above", async () => {
const obj = tabs("above")
await display(obj, [300, 300])
})
it("should allow tabs header location below", async () => {
const obj = tabs("below")
await display(obj, [300, 300])
})
it("should allow tabs header location left", async () => {
const obj = tabs("left")
await display(obj, [300, 300])
})
it("should allow tabs header location right", async () => {
const obj = tabs("right")
await display(obj, [300, 300])
})
})
| stonebig/bokeh | bokehjs/test/integration.ts | TypeScript | bsd-3-clause | 20,323 |
// -*- C++ -*-
// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 2, or (at your option) any later
// version.
// 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
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.
// As a special exception, you may use this file as part of a free
// software library without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License. This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file node.hpp
* Contains an implementation struct for splay_tree_'s node.
*/
#ifndef PB_DS_SPLAY_TREE_NODE_HPP
#define PB_DS_SPLAY_TREE_NODE_HPP
namespace __gnu_pbds
{
namespace detail
{
template<typename Value_Type, class Metadata, class Allocator>
struct splay_tree_node_
{
public:
typedef Value_Type value_type;
typedef Metadata metadata_type;
typedef
typename Allocator::template rebind<
splay_tree_node_<Value_Type, Metadata, Allocator> >::other::pointer
node_pointer;
typedef
typename Allocator::template rebind<metadata_type>::other::reference
metadata_reference;
typedef
typename Allocator::template rebind<metadata_type>::other::const_reference
const_metadata_reference;
#ifdef PB_DS_BIN_SEARCH_TREE_TRACE_
void
trace() const
{ std::cout << PB_DS_V2F(m_value) << "(" << m_metadata << ")"; }
#endif
inline bool
special() const
{ return m_special; }
inline const_metadata_reference
get_metadata() const
{ return m_metadata; }
inline metadata_reference
get_metadata()
{ return m_metadata; }
value_type m_value;
bool m_special;
node_pointer m_p_left;
node_pointer m_p_right;
node_pointer m_p_parent;
metadata_type m_metadata;
};
template<typename Value_Type, typename Allocator>
struct splay_tree_node_<Value_Type, null_node_metadata, Allocator>
{
public:
typedef Value_Type value_type;
typedef null_node_metadata metadata_type;
typedef
typename Allocator::template rebind<
splay_tree_node_<Value_Type, null_node_metadata, Allocator> >::other::pointer
node_pointer;
inline bool
special() const
{ return m_special; }
#ifdef PB_DS_BIN_SEARCH_TREE_TRACE_
void
trace() const
{ std::cout << PB_DS_V2F(m_value); }
#endif
node_pointer m_p_left;
node_pointer m_p_right;
node_pointer m_p_parent;
value_type m_value;
bool m_special;
};
} // namespace detail
} // namespace __gnu_pbds
#endif
| jmolloy/pedigree | src/subsys/posix/include/c++/4.3.2/ext/pb_ds/detail/splay_tree_/node.hpp | C++ | isc | 4,101 |
/*
* Copyright (c) 2009-2011, 2014 AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package org.alljoyn.bus.ifaces;
import java.util.Map;
import org.alljoyn.bus.BusException;
import org.alljoyn.bus.Variant;
import org.alljoyn.bus.annotation.BusInterface;
import org.alljoyn.bus.annotation.BusMethod;
import org.alljoyn.bus.annotation.BusSignal;
/**
* The standard org.freedesktop.DBus.Properties interface that can be
* implemented by bus objects to expose a generic "setter/getter" inteface for
* user-defined properties on DBus.
*/
@BusInterface(name = "org.freedesktop.DBus.Properties")
public interface Properties {
/**
* Gets a property that exists on a named interface of a bus object.
*
* @param iface the interface that the property exists on
* @param propName the name of the property
* @return the value of the property
* @throws BusException if the named property doesn't exist
*/
@BusMethod
Variant Get(String iface, String propName) throws BusException;
/**
* Sets a property that exists on a named interface of a bus object.
*
* @param iface the interface that the property exists on
* @param propName the name of the property
* @param value the value for the property
* @throws BusException if the named property doesn't exist or cannot be set
*/
@BusMethod
void Set(String iface, String propName, Variant value) throws BusException;
/**
* Gets all properties for a given interface.
*
* @param iface the interface
* @return a Map of name/value associations
* @throws BusException if request cannot be honored
*/
@BusMethod(signature = "s", replySignature = "a{sv}")
Map<String, Variant> GetAll(String iface) throws BusException;
/**
* Notifies others about changes to properties.
*
* @param iface the interface
* @param changedProps a map of property names an their new values
* @param invalidatedProps a list of property names whose values are invalidated
* @throws BusException indicating failure sending PropertiesChanged signal
*/
@BusSignal(signature = "sa{sv}as")
void PropertiesChanged(String iface, Map<String, Variant> changedProps, String [] invalidatedProps) throws BusException;
}
| octoblu/alljoyn | alljoyn/alljoyn_java/src/org/alljoyn/bus/ifaces/Properties.java | Java | isc | 3,060 |
'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for each action that can be performed on the resource.
//
// - @param {Object} options
// - @param {Object} schema
//
// The `options` argument should have the following properties:
//
// - `resourceDefinition` - the definition of the resource and its actions from
// the schema definition.
// - `consumerkey` - the oauth consumerkey
// - `consumersecret` the oauth consumersecret
// - `schema` - the schema defintion
// - `format` - the desired response format
// - `logger` - for logging output
function Resource(options, schema) {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || schema.sslHost;
this.port = options.resourceDefinition.port || schema.port;
this.prefix = options.resourceDefinition.prefix || schema.prefix;
this.consumerkey = options.consumerkey;
this.consumersecret = options.consumersecret;
if(this.logger.silly) {
this.logger.silly('Creating constructor for resource: ' + this.resourceName);
}
_.each(options.resourceDefinition.actions,
function processAction(action) {
this.createAction(action, options.userManagement);
}, this);
}
// Figure out the appropriate method name for an action on a resource on
// the API
//
// - @param {Mixed} - actionDefinition - Either a string if the action method
// name is the same as the action path component on the underlying API call
// or a hash if they differ.
// - @return {String}
Resource.prototype.chooseMethodName = function (actionDefinition) {
var fnName;
// Default the action name to getXXX if we only have the URL slug as the
// action definition.
if (_.isString(actionDefinition)) {
fnName = 'get' + helpers.capitalize(actionDefinition);
} else {
fnName = actionDefinition.methodName;
}
return fnName;
};
// Utility method for creating the necessary methods on the Resource for
// dispatching the request to the 7digital API.
//
// - @param {Mixed} actionDefinition - Either a string if the action method
// name is the same as the action path component on the underlying API call
// or a hash if they differ.
Resource.prototype.createAction = function (actionDefinition, isManaged) {
var url;
var fnName = this.chooseMethodName(actionDefinition);
var action = typeof actionDefinition.apiCall === 'undefined' ?
actionDefinition : actionDefinition.apiCall;
var httpMethod = (actionDefinition.method || 'GET').toUpperCase();
var host = actionDefinition.host || this.host;
var sslHost = actionDefinition.sslHost || this.sslHost;
var port = actionDefinition.port || this.port;
var prefix = actionDefinition.prefix || this.prefix;
var authType = (actionDefinition.oauth
&& actionDefinition.oauth === '3-legged' && isManaged)
? '2-legged'
: actionDefinition.oauth;
if(this.logger.silly) {
this.logger.silly(
'Creating method: ' + fnName + ' for ' + action +
' action with ' + httpMethod + ' HTTP verb');
}
/*jshint validthis: true */
function invokeAction(requestData, callback) {
var self = this;
var endpointInfo = {
host: invokeAction.host,
sslHost: invokeAction.sslHost || sslHost,
port: invokeAction.port,
prefix: invokeAction.prefix,
authtype: authType,
url: helpers.formatPath(invokeAction.prefix, this.resourceName,
action)
};
var credentials = {
consumerkey: this.consumerkey,
consumersecret: this.consumersecret
};
if (_.isFunction(requestData)) {
callback = requestData;
requestData = {};
}
function checkAndParse(err, data, response) {
if (err) {
return callback(err);
}
return responseParser.parse(data, {
format: self.format,
logger: self.logger,
url: endpointInfo.url,
params: requestData,
contentType: response.headers['content-type']
}, getLocationForRedirectsAndCallback);
function getLocationForRedirectsAndCallback(err, parsed) {
if (err) {
return callback(err);
}
if (response && response.headers['location']) {
parsed.location = response.headers['location'];
}
return callback(null, parsed);
}
}
_.defaults(requestData, this.defaultParams);
if (httpMethod === 'GET') {
// Add the default parameters to the request data
return request.get(endpointInfo, requestData, this.headers,
credentials, this.logger, checkAndParse);
}
if (httpMethod === 'POST' || httpMethod === 'PUT') {
return request.postOrPut(httpMethod, endpointInfo, requestData,
this.headers, credentials, this.logger, checkAndParse);
}
return callback(new Error('Unsupported HTTP verb: ' + httpMethod));
}
invokeAction.action = action;
invokeAction.authtype = authType;
invokeAction.host = host;
invokeAction.sslHost = sslHost;
invokeAction.port = port;
invokeAction.prefix = prefix;
this[fnName] = invokeAction;
};
module.exports = Resource;
| raoulmillais/7digital-api | lib/resource.js | JavaScript | isc | 5,206 |
module Streak
module Util
# creatorKey => :creator_key
def self.symbolize_attribute(attr)
word = attr.to_s.dup
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word.to_sym
end
end
end
| jsboulanger/streak-ruby | lib/streak/util.rb | Ruby | mit | 306 |
/**
* Custom events to control showing and hiding of tooltip
*
* @attributes
* - `event` {String}
* - `eventOff` {String}
*/
export const checkStatus = function(dataEventOff, e) {
const { show } = this.state;
const { id } = this.props;
const isCapture = this.isCapture(e.currentTarget);
const currentItem = e.currentTarget.getAttribute('currentItem');
if (!isCapture) e.stopPropagation();
if (show && currentItem === 'true') {
if (!dataEventOff) this.hideTooltip(e);
} else {
e.currentTarget.setAttribute('currentItem', 'true');
setUntargetItems(e.currentTarget, this.getTargetArray(id));
this.showTooltip(e);
}
};
const setUntargetItems = function(currentTarget, targetArray) {
for (let i = 0; i < targetArray.length; i++) {
if (currentTarget !== targetArray[i]) {
targetArray[i].setAttribute('currentItem', 'false');
} else {
targetArray[i].setAttribute('currentItem', 'true');
}
}
};
const customListeners = {
id: '9b69f92e-d3fe-498b-b1b4-c5e63a51b0cf',
set(target, event, listener) {
if (this.id in target) {
const map = target[this.id];
map[event] = listener;
} else {
// this is workaround for WeakMap, which is not supported in older browsers, such as IE
Object.defineProperty(target, this.id, {
configurable: true,
value: { [event]: listener }
});
}
},
get(target, event) {
const map = target[this.id];
if (map !== undefined) {
return map[event];
}
}
};
export default function(target) {
target.prototype.isCustomEvent = function(ele) {
const { event } = this.state;
return event || !!ele.getAttribute('data-event');
};
/* Bind listener for custom event */
target.prototype.customBindListener = function(ele) {
const { event, eventOff } = this.state;
const dataEvent = ele.getAttribute('data-event') || event;
const dataEventOff = ele.getAttribute('data-event-off') || eventOff;
dataEvent.split(' ').forEach(event => {
ele.removeEventListener(event, customListeners.get(ele, event));
const customListener = checkStatus.bind(this, dataEventOff);
customListeners.set(ele, event, customListener);
ele.addEventListener(event, customListener, false);
});
if (dataEventOff) {
dataEventOff.split(' ').forEach(event => {
ele.removeEventListener(event, this.hideTooltip);
ele.addEventListener(event, this.hideTooltip, false);
});
}
};
/* Unbind listener for custom event */
target.prototype.customUnbindListener = function(ele) {
const { event, eventOff } = this.state;
const dataEvent = event || ele.getAttribute('data-event');
const dataEventOff = eventOff || ele.getAttribute('data-event-off');
ele.removeEventListener(dataEvent, customListeners.get(ele, event));
if (dataEventOff) ele.removeEventListener(dataEventOff, this.hideTooltip);
};
}
| wwayne/react-tooltip | src/decorators/customEvent.js | JavaScript | mit | 2,931 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace EmployeeRegistration.MVCWeb
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Employee", action = "EmployeeForm", id = UrlParameter.Optional }
);
}
}
}
| jansenbe/PnP-Transformation | InfoPath/Samples/EmployeeRegistration.MVC/EmployeeRegistration.MVCWeb/App_Start/RouteConfig.cs | C# | mit | 608 |
// Copyright 2017 Dan Ristic
#include "chimera/virtual/vtree.h"
namespace Chimera {
namespace Virtual {
VirtualElement::VirtualElement(
std::string _name,
std::vector<Attribute> _attributes)
: name{_name}
{
for (auto& attribute : _attributes) {
std::string key = attribute.getKey();
attributes[key] = attribute;
}
}
Element* VirtualElement::create(Document& document)
{
auto element = document.createElement(name);
if (attributes.count("id") == 1)
{
auto id = attributes.at("id");
element->id = id.asString();
}
if (attributes.count("class") == 1)
{
auto className = attributes.at("class");
element->className = className.asString();
}
if (attributes.count("src") == 1)
{
auto src = attributes.at("src");
auto img = dynamic_cast<Img*>(element);
if (img)
{
img->setSrc(src.asString());
}
}
if (attributes.count("onChange") == 1)
{
auto func = attributes.at("onChange");
element->on(EventType::Change, func.asCallback());
}
if (attributes.count("onMouseDown") == 1)
{
auto func = attributes.at("onMouseDown");
element->on(EventType::MouseDown, func.asCallback());
}
if (attributes.count("onCustom") == 1)
{
auto func = attributes.at("onCustom");
element->on(EventType::Custom, func.asCallback());
}
for (auto& attribute : attributes)
{
element->attributeChangedCallback(
attribute.first, "", attribute.second.asString());
}
element->textContent = textContent;
CHIMERA_DEBUG(
printf("[VElement] %s %s\n",
element->tagName.c_str(),
element->id.c_str());
)
for (auto& child : children)
{
element->append(child.create(document));
}
return element;
}
} // namespace Virtual
} // namespace Chimera
| dristic/chimera | chimera/virtual/vtree.cpp | C++ | mit | 1,954 |
var Request = require('request');
function NewsFetcher() {
this._newsLink = 'http://kaku.rocks/news.json';
}
NewsFetcher.prototype.get = function() {
var promise = new Promise((resolve, reject) => {
Request.get(this._newsLink, (error, response, body) => {
if (error) {
reject(error);
console.log(error);
}
else {
var result = JSON.parse(body);
resolve(result.news);
}
});
});
return promise;
};
module.exports = new NewsFetcher();
| uirsevla/Kaku | src/modules/NewsFetcher.js | JavaScript | mit | 506 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.applicationinsights.v2015_05_01.implementation;
import com.microsoft.azure.arm.collection.InnerSupportsGet;
import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import com.microsoft.azure.arm.collection.InnerSupportsListing;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.applicationinsights.v2015_05_01.ComponentPurgeBody;
import com.microsoft.azure.management.applicationinsights.v2015_05_01.TagsResource;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in Components.
*/
public class ComponentsInner implements InnerSupportsGet<ApplicationInsightsComponentInner>, InnerSupportsDelete<Void>, InnerSupportsListing<ApplicationInsightsComponentInner> {
/** The Retrofit service to perform REST calls. */
private ComponentsService service;
/** The service client containing this operation class. */
private ApplicationInsightsManagementClientImpl client;
/**
* Initializes an instance of ComponentsInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public ComponentsInner(Retrofit retrofit, ApplicationInsightsManagementClientImpl client) {
this.service = retrofit.create(ComponentsService.class);
this.client = client;
}
/**
* The interface defining all the services for Components to be
* used by Retrofit to perform actually REST calls.
*/
interface ComponentsService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Insights/components")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Body ApplicationInsightsComponentInner insightProperties, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components updateTags" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}")
Observable<Response<ResponseBody>> updateTags(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TagsResource componentTags, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components purge" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/purge")
Observable<Response<ResponseBody>> purge(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Query("api-version") String apiVersion, @Body ComponentPurgeBody body, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components getPurgeStatus" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/operations/{purgeId}")
Observable<Response<ResponseBody>> getPurgeStatus(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Path("resourceName") String resourceName, @Path("purgeId") String purgeId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.applicationinsights.v2015_05_01.Components listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<ApplicationInsightsComponentInner> object if successful.
*/
public PagedList<ApplicationInsightsComponentInner> list() {
ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<ApplicationInsightsComponentInner>(response.body()) {
@Override
public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<ApplicationInsightsComponentInner>> listAsync(final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<Page<ApplicationInsightsComponentInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() {
@Override
public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) {
return response.body();
}
});
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<ApplicationInsightsComponentInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.list(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<ApplicationInsightsComponentInner> object if successful.
*/
public PagedList<ApplicationInsightsComponentInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<ApplicationInsightsComponentInner>(response.body()) {
@Override
public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<ApplicationInsightsComponentInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<Page<ApplicationInsightsComponentInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() {
@Override
public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) {
return response.body();
}
});
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets a list of Application Insights components within a resource group.
*
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<ApplicationInsightsComponentInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Deletes an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String resourceName) {
deleteWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
}
/**
* Deletes an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String resourceName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback);
}
/**
* Deletes an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> deleteAsync(String resourceGroupName, String resourceName) {
return deleteWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String resourceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.delete(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = deleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> deleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Returns an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ApplicationInsightsComponentInner object if successful.
*/
public ApplicationInsightsComponentInner getByResourceGroup(String resourceGroupName, String resourceName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
}
/**
* Returns an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ApplicationInsightsComponentInner> getByResourceGroupAsync(String resourceGroupName, String resourceName, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback);
}
/**
* Returns an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ApplicationInsightsComponentInner> getByResourceGroupAsync(String resourceGroupName, String resourceName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() {
@Override
public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) {
return response.body();
}
});
}
/**
* Returns an Application Insights component.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String resourceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getByResourceGroup(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() {
@Override
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ApplicationInsightsComponentInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ApplicationInsightsComponentInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param insightProperties Properties that need to be specified to create an Application Insights component.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ApplicationInsightsComponentInner object if successful.
*/
public ApplicationInsightsComponentInner createOrUpdate(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties).toBlocking().single().body();
}
/**
* Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param insightProperties Properties that need to be specified to create an Application Insights component.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ApplicationInsightsComponentInner> createOrUpdateAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties), serviceCallback);
}
/**
* Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param insightProperties Properties that need to be specified to create an Application Insights component.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ApplicationInsightsComponentInner> createOrUpdateAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, insightProperties).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() {
@Override
public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) {
return response.body();
}
});
}
/**
* Creates (or updates) an Application Insights component. Note: You cannot specify a different value for InstrumentationKey nor AppId in the Put operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param insightProperties Properties that need to be specified to create an Application Insights component.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String resourceName, ApplicationInsightsComponentInner insightProperties) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
if (insightProperties == null) {
throw new IllegalArgumentException("Parameter insightProperties is required and cannot be null.");
}
Validator.validate(insightProperties);
return service.createOrUpdate(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), insightProperties, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() {
@Override
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ApplicationInsightsComponentInner> clientResponse = createOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ApplicationInsightsComponentInner> createOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ApplicationInsightsComponentInner object if successful.
*/
public ApplicationInsightsComponentInner updateTags(String resourceGroupName, String resourceName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, resourceName), serviceCallback);
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() {
@Override
public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) {
return response.body();
}
});
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String resourceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
final Map<String, String> tags = null;
TagsResource componentTags = new TagsResource();
componentTags.withTags(null);
return service.updateTags(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), componentTags, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() {
@Override
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ApplicationInsightsComponentInner> clientResponse = updateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param tags Resource tags
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ApplicationInsightsComponentInner object if successful.
*/
public ApplicationInsightsComponentInner updateTags(String resourceGroupName, String resourceName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags).toBlocking().single().body();
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param tags Resource tags
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, Map<String, String> tags, final ServiceCallback<ApplicationInsightsComponentInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags), serviceCallback);
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param tags Resource tags
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ApplicationInsightsComponentInner> updateTagsAsync(String resourceGroupName, String resourceName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName, tags).map(new Func1<ServiceResponse<ApplicationInsightsComponentInner>, ApplicationInsightsComponentInner>() {
@Override
public ApplicationInsightsComponentInner call(ServiceResponse<ApplicationInsightsComponentInner> response) {
return response.body();
}
});
}
/**
* Updates an existing component's tags. To update other fields use the CreateOrUpdate method.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param tags Resource tags
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ApplicationInsightsComponentInner object
*/
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String resourceName, Map<String, String> tags) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(tags);
TagsResource componentTags = new TagsResource();
componentTags.withTags(tags);
return service.updateTags(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), this.client.acceptLanguage(), componentTags, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ApplicationInsightsComponentInner>>>() {
@Override
public Observable<ServiceResponse<ApplicationInsightsComponentInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ApplicationInsightsComponentInner> clientResponse = updateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ApplicationInsightsComponentInner> updateTagsDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ApplicationInsightsComponentInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ApplicationInsightsComponentInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Purges data in an Application Insights component by a set of user-defined filters.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param body Describes the body of a request to purge data in a single table of an Application Insights component
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ComponentPurgeResponseInner object if successful.
*/
public ComponentPurgeResponseInner purge(String resourceGroupName, String resourceName, ComponentPurgeBody body) {
return purgeWithServiceResponseAsync(resourceGroupName, resourceName, body).toBlocking().single().body();
}
/**
* Purges data in an Application Insights component by a set of user-defined filters.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param body Describes the body of a request to purge data in a single table of an Application Insights component
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ComponentPurgeResponseInner> purgeAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body, final ServiceCallback<ComponentPurgeResponseInner> serviceCallback) {
return ServiceFuture.fromResponse(purgeWithServiceResponseAsync(resourceGroupName, resourceName, body), serviceCallback);
}
/**
* Purges data in an Application Insights component by a set of user-defined filters.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param body Describes the body of a request to purge data in a single table of an Application Insights component
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ComponentPurgeResponseInner object
*/
public Observable<ComponentPurgeResponseInner> purgeAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body) {
return purgeWithServiceResponseAsync(resourceGroupName, resourceName, body).map(new Func1<ServiceResponse<ComponentPurgeResponseInner>, ComponentPurgeResponseInner>() {
@Override
public ComponentPurgeResponseInner call(ServiceResponse<ComponentPurgeResponseInner> response) {
return response.body();
}
});
}
/**
* Purges data in an Application Insights component by a set of user-defined filters.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param body Describes the body of a request to purge data in a single table of an Application Insights component
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ComponentPurgeResponseInner object
*/
public Observable<ServiceResponse<ComponentPurgeResponseInner>> purgeWithServiceResponseAsync(String resourceGroupName, String resourceName, ComponentPurgeBody body) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
if (body == null) {
throw new IllegalArgumentException("Parameter body is required and cannot be null.");
}
Validator.validate(body);
return service.purge(resourceGroupName, this.client.subscriptionId(), resourceName, this.client.apiVersion(), body, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ComponentPurgeResponseInner>>>() {
@Override
public Observable<ServiceResponse<ComponentPurgeResponseInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ComponentPurgeResponseInner> clientResponse = purgeDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ComponentPurgeResponseInner> purgeDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ComponentPurgeResponseInner, CloudException>newInstance(this.client.serializerAdapter())
.register(202, new TypeToken<ComponentPurgeResponseInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Get status for an ongoing purge operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param purgeId In a purge status request, this is the Id of the operation the status of which is returned.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ComponentPurgeStatusResponseInner object if successful.
*/
public ComponentPurgeStatusResponseInner getPurgeStatus(String resourceGroupName, String resourceName, String purgeId) {
return getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId).toBlocking().single().body();
}
/**
* Get status for an ongoing purge operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param purgeId In a purge status request, this is the Id of the operation the status of which is returned.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ComponentPurgeStatusResponseInner> getPurgeStatusAsync(String resourceGroupName, String resourceName, String purgeId, final ServiceCallback<ComponentPurgeStatusResponseInner> serviceCallback) {
return ServiceFuture.fromResponse(getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId), serviceCallback);
}
/**
* Get status for an ongoing purge operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param purgeId In a purge status request, this is the Id of the operation the status of which is returned.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ComponentPurgeStatusResponseInner object
*/
public Observable<ComponentPurgeStatusResponseInner> getPurgeStatusAsync(String resourceGroupName, String resourceName, String purgeId) {
return getPurgeStatusWithServiceResponseAsync(resourceGroupName, resourceName, purgeId).map(new Func1<ServiceResponse<ComponentPurgeStatusResponseInner>, ComponentPurgeStatusResponseInner>() {
@Override
public ComponentPurgeStatusResponseInner call(ServiceResponse<ComponentPurgeStatusResponseInner> response) {
return response.body();
}
});
}
/**
* Get status for an ongoing purge operation.
*
* @param resourceGroupName The name of the resource group.
* @param resourceName The name of the Application Insights component resource.
* @param purgeId In a purge status request, this is the Id of the operation the status of which is returned.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ComponentPurgeStatusResponseInner object
*/
public Observable<ServiceResponse<ComponentPurgeStatusResponseInner>> getPurgeStatusWithServiceResponseAsync(String resourceGroupName, String resourceName, String purgeId) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceName == null) {
throw new IllegalArgumentException("Parameter resourceName is required and cannot be null.");
}
if (purgeId == null) {
throw new IllegalArgumentException("Parameter purgeId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
return service.getPurgeStatus(resourceGroupName, this.client.subscriptionId(), resourceName, purgeId, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ComponentPurgeStatusResponseInner>>>() {
@Override
public Observable<ServiceResponse<ComponentPurgeStatusResponseInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ComponentPurgeStatusResponseInner> clientResponse = getPurgeStatusDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ComponentPurgeStatusResponseInner> getPurgeStatusDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ComponentPurgeStatusResponseInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ComponentPurgeStatusResponseInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<ApplicationInsightsComponentInner> object if successful.
*/
public PagedList<ApplicationInsightsComponentInner> listNext(final String nextPageLink) {
ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<ApplicationInsightsComponentInner>(response.body()) {
@Override
public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<ApplicationInsightsComponentInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<ApplicationInsightsComponentInner>> serviceFuture, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<Page<ApplicationInsightsComponentInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() {
@Override
public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) {
return response.body();
}
});
}
/**
* Gets a list of all Application Insights components within a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets a list of all Application Insights components within a subscription.
*
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<ApplicationInsightsComponentInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<ApplicationInsightsComponentInner> object if successful.
*/
public PagedList<ApplicationInsightsComponentInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<ApplicationInsightsComponentInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<ApplicationInsightsComponentInner>(response.body()) {
@Override
public Page<ApplicationInsightsComponentInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<ApplicationInsightsComponentInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<ApplicationInsightsComponentInner>> serviceFuture, final ListOperationCallback<ApplicationInsightsComponentInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<Page<ApplicationInsightsComponentInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Page<ApplicationInsightsComponentInner>>() {
@Override
public Page<ApplicationInsightsComponentInner> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> response) {
return response.body();
}
});
}
/**
* Gets a list of Application Insights components within a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<ApplicationInsightsComponentInner> object
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<ApplicationInsightsComponentInner>>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(ServiceResponse<Page<ApplicationInsightsComponentInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets a list of Application Insights components within a resource group.
*
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<ApplicationInsightsComponentInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>>>() {
@Override
public Observable<ServiceResponse<Page<ApplicationInsightsComponentInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<ApplicationInsightsComponentInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<ApplicationInsightsComponentInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<ApplicationInsightsComponentInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<ApplicationInsightsComponentInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| selvasingh/azure-sdk-for-java | sdk/applicationinsights/mgmt-v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ComponentsInner.java | Java | mit | 73,618 |
require 'test/spec'
require 'rack/mock'
require 'rack/contrib/cookies'
context "Rack::Cookies" do
specify "should be able to read received cookies" do
app = lambda { |env|
cookies = env['rack.cookies']
foo, quux = cookies[:foo], cookies['quux']
[200, {'Content-Type' => 'text/plain'}, ["foo: #{foo}, quux: #{quux}"]]
}
app = Rack::Cookies.new(app)
response = Rack::MockRequest.new(app).get('/', 'HTTP_COOKIE' => 'foo=bar;quux=h&m')
response.body.should.equal('foo: bar, quux: h&m')
end
specify "should be able to set new cookies" do
app = lambda { |env|
cookies = env['rack.cookies']
cookies[:foo] = 'bar'
cookies['quux'] = 'h&m'
[200, {'Content-Type' => 'text/plain'}, []]
}
app = Rack::Cookies.new(app)
response = Rack::MockRequest.new(app).get('/')
response.headers['Set-Cookie'].should.equal("quux=h%26m; path=/\nfoo=bar; path=/")
end
specify "should be able to set cookie with options" do
app = lambda { |env|
cookies = env['rack.cookies']
cookies['foo'] = { :value => 'bar', :path => '/login', :secure => true }
[200, {'Content-Type' => 'text/plain'}, []]
}
app = Rack::Cookies.new(app)
response = Rack::MockRequest.new(app).get('/')
response.headers['Set-Cookie'].should.equal('foo=bar; path=/login; secure')
end
specify "should be able to delete received cookies" do
app = lambda { |env|
cookies = env['rack.cookies']
cookies.delete(:foo)
foo, quux = cookies['foo'], cookies[:quux]
[200, {'Content-Type' => 'text/plain'}, ["foo: #{foo}, quux: #{quux}"]]
}
app = Rack::Cookies.new(app)
response = Rack::MockRequest.new(app).get('/', 'HTTP_COOKIE' => 'foo=bar;quux=h&m')
response.body.should.equal('foo: , quux: h&m')
response.headers['Set-Cookie'].should.equal('foo=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT')
end
end
| igorgue/rack-contrib | test/spec_rack_cookies.rb | Ruby | mit | 1,923 |
// Copyright (c) Dropbox, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Package seen_state : has no documentation (yet)
package seen_state
import "github.com/dropbox/dropbox-sdk-go-unofficial/dropbox"
// PlatformType : Possible platforms on which a user may view content.
type PlatformType struct {
dropbox.Tagged
}
// Valid tag values for PlatformType
const (
PlatformTypeWeb = "web"
PlatformTypeMobile = "mobile"
PlatformTypeDesktop = "desktop"
PlatformTypeUnknown = "unknown"
PlatformTypeOther = "other"
)
| yonjah/rclone | vendor/github.com/dropbox/dropbox-sdk-go-unofficial/dropbox/seen_state/types.go | GO | mit | 1,563 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\ResourceBundle\Doctrine\ORM;
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\ArrayAdapter;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
/**
* @author Paweł Jędrzejewski <pawel@sylius.org>
*/
class EntityRepository extends BaseEntityRepository implements RepositoryInterface
{
/**
* {@inheritdoc}
*/
public function add(ResourceInterface $resource): void
{
$this->_em->persist($resource);
$this->_em->flush();
}
/**
* {@inheritdoc}
*/
public function remove(ResourceInterface $resource): void
{
if (null !== $this->find($resource->getId())) {
$this->_em->remove($resource);
$this->_em->flush();
}
}
/**
* {@inheritdoc}
*/
public function createPaginator(array $criteria = [], array $sorting = []): iterable
{
$queryBuilder = $this->createQueryBuilder('o');
$this->applyCriteria($queryBuilder, $criteria);
$this->applySorting($queryBuilder, $sorting);
return $this->getPaginator($queryBuilder);
}
/**
* @param QueryBuilder $queryBuilder
*
* @return Pagerfanta
*/
protected function getPaginator(QueryBuilder $queryBuilder): Pagerfanta
{
// Use output walkers option in DoctrineORMAdapter should be false as it affects performance greatly (see #3775)
return new Pagerfanta(new DoctrineORMAdapter($queryBuilder, false, false));
}
/**
* @param array $objects
*
* @return Pagerfanta
*/
protected function getArrayPaginator($objects): Pagerfanta
{
return new Pagerfanta(new ArrayAdapter($objects));
}
/**
* @param QueryBuilder $queryBuilder
* @param array $criteria
*/
protected function applyCriteria(QueryBuilder $queryBuilder, array $criteria = []): void
{
foreach ($criteria as $property => $value) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}
$name = $this->getPropertyName($property);
if (null === $value) {
$queryBuilder->andWhere($queryBuilder->expr()->isNull($name));
} elseif (is_array($value)) {
$queryBuilder->andWhere($queryBuilder->expr()->in($name, $value));
} elseif ('' !== $value) {
$parameter = str_replace('.', '_', $property);
$queryBuilder
->andWhere($queryBuilder->expr()->eq($name, ':'.$parameter))
->setParameter($parameter, $value)
;
}
}
}
/**
* @param QueryBuilder $queryBuilder
* @param array $sorting
*/
protected function applySorting(QueryBuilder $queryBuilder, array $sorting = []): void
{
foreach ($sorting as $property => $order) {
if (!in_array($property, array_merge($this->_class->getAssociationNames(), $this->_class->getFieldNames()), true)) {
continue;
}
if (!empty($order)) {
$queryBuilder->addOrderBy($this->getPropertyName($property), $order);
}
}
}
/**
* @param string $name
*
* @return string
*/
protected function getPropertyName(string $name): string
{
if (false === strpos($name, '.')) {
return 'o'.'.'.$name;
}
return $name;
}
}
| mkilmanas/Sylius | src/Sylius/Bundle/ResourceBundle/Doctrine/ORM/EntityRepository.php | PHP | mit | 4,029 |
<?php
/**
* Base class that represents a row from the 'sf_guard_remember_key' table.
*
*
*
* This class was autogenerated by Propel 1.3.0-dev on:
*
* Thu Jul 9 13:35:06 2009
*
* @package plugins.sfGuardPlugin.lib.model.om
*/
abstract class BasesfGuardRememberKey extends BaseObject implements Persistent {
const PEER = 'sfGuardRememberKeyPeer';
/**
* The Peer class.
* Instance provides a convenient way of calling static methods on a class
* that calling code may not be able to identify.
* @var sfGuardRememberKeyPeer
*/
protected static $peer;
/**
* The value for the user_id field.
* @var int
*/
protected $user_id;
/**
* The value for the remember_key field.
* @var string
*/
protected $remember_key;
/**
* The value for the ip_address field.
* @var string
*/
protected $ip_address;
/**
* The value for the created_at field.
* @var string
*/
protected $created_at;
/**
* @var sfGuardUser
*/
protected $asfGuardUser;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInSave = false;
/**
* Flag to prevent endless validation loop, if this object is referenced
* by another object which falls in this transaction.
* @var boolean
*/
protected $alreadyInValidation = false;
/**
* Initializes internal state of BasesfGuardRememberKey object.
* @see applyDefaults()
*/
public function __construct()
{
parent::__construct();
$this->applyDefaultValues();
}
/**
* Applies default values to this object.
* This method should be called from the object's constructor (or
* equivalent initialization method).
* @see __construct()
*/
public function applyDefaultValues()
{
}
/**
* Get the [user_id] column value.
*
* @return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Get the [remember_key] column value.
*
* @return string
*/
public function getRememberKey()
{
return $this->remember_key;
}
/**
* Get the [ip_address] column value.
*
* @return string
*/
public function getIpAddress()
{
return $this->ip_address;
}
/**
* Get the [optionally formatted] temporal [created_at] column value.
*
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the raw DateTime object will be returned.
* @return mixed Formatted date/time value as string or DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getCreatedAt($format = 'Y-m-d H:i:s')
{
if ($this->created_at === null) {
return null;
}
if ($this->created_at === '0000-00-00 00:00:00') {
// while technically this is not a default value of NULL,
// this seems to be closest in meaning.
return null;
} else {
try {
$dt = new DateTime($this->created_at);
} catch (Exception $x) {
throw new PropelException("Internally stored date/time/timestamp value could not be converted to DateTime: " . var_export($this->created_at, true), $x);
}
}
if ($format === null) {
// Because propel.useDateTimeClass is TRUE, we return a DateTime object.
return $dt;
} elseif (strpos($format, '%') !== false) {
return strftime($format, $dt->format('U'));
} else {
return $dt->format($format);
}
}
/**
* Set the value of [user_id] column.
*
* @param int $v new value
* @return sfGuardRememberKey The current object (for fluent API support)
*/
public function setUserId($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->user_id !== $v) {
$this->user_id = $v;
$this->modifiedColumns[] = sfGuardRememberKeyPeer::USER_ID;
}
if ($this->asfGuardUser !== null && $this->asfGuardUser->getId() !== $v) {
$this->asfGuardUser = null;
}
return $this;
} // setUserId()
/**
* Set the value of [remember_key] column.
*
* @param string $v new value
* @return sfGuardRememberKey The current object (for fluent API support)
*/
public function setRememberKey($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->remember_key !== $v) {
$this->remember_key = $v;
$this->modifiedColumns[] = sfGuardRememberKeyPeer::REMEMBER_KEY;
}
return $this;
} // setRememberKey()
/**
* Set the value of [ip_address] column.
*
* @param string $v new value
* @return sfGuardRememberKey The current object (for fluent API support)
*/
public function setIpAddress($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->ip_address !== $v) {
$this->ip_address = $v;
$this->modifiedColumns[] = sfGuardRememberKeyPeer::IP_ADDRESS;
}
return $this;
} // setIpAddress()
/**
* Sets the value of [created_at] column to a normalized version of the date/time value specified.
*
* @param mixed $v string, integer (timestamp), or DateTime value. Empty string will
* be treated as NULL for temporal objects.
* @return sfGuardRememberKey The current object (for fluent API support)
*/
public function setCreatedAt($v)
{
// we treat '' as NULL for temporal objects because DateTime('') == DateTime('now')
// -- which is unexpected, to say the least.
if ($v === null || $v === '') {
$dt = null;
} elseif ($v instanceof DateTime) {
$dt = $v;
} else {
// some string/numeric value passed; we normalize that so that we can
// validate it.
try {
if (is_numeric($v)) { // if it's a unix timestamp
$dt = new DateTime('@'.$v, new DateTimeZone('UTC'));
// We have to explicitly specify and then change the time zone because of a
// DateTime bug: http://bugs.php.net/bug.php?id=43003
$dt->setTimeZone(new DateTimeZone(date_default_timezone_get()));
} else {
$dt = new DateTime($v);
}
} catch (Exception $x) {
throw new PropelException('Error parsing date/time value: ' . var_export($v, true), $x);
}
}
if ( $this->created_at !== null || $dt !== null ) {
// (nested ifs are a little easier to read in this case)
$currNorm = ($this->created_at !== null && $tmpDt = new DateTime($this->created_at)) ? $tmpDt->format('Y-m-d H:i:s') : null;
$newNorm = ($dt !== null) ? $dt->format('Y-m-d H:i:s') : null;
if ( ($currNorm !== $newNorm) // normalized values don't match
)
{
$this->created_at = ($dt ? $dt->format('Y-m-d H:i:s') : null);
$this->modifiedColumns[] = sfGuardRememberKeyPeer::CREATED_AT;
}
} // if either are not null
return $this;
} // setCreatedAt()
/**
* Indicates whether the columns in this object are only set to default values.
*
* This method can be used in conjunction with isModified() to indicate whether an object is both
* modified _and_ has some values set which are non-default.
*
* @return boolean Whether the columns in this object are only been set with default values.
*/
public function hasOnlyDefaultValues()
{
// First, ensure that we don't have any columns that have been modified which aren't default columns.
if (array_diff($this->modifiedColumns, array())) {
return false;
}
// otherwise, everything was equal, so return TRUE
return true;
} // hasOnlyDefaultValues()
/**
* Hydrates (populates) the object variables with values from the database resultset.
*
* An offset (0-based "start column") is specified so that objects can be hydrated
* with a subset of the columns in the resultset rows. This is needed, for example,
* for results of JOIN queries where the resultset row includes columns from two or
* more tables.
*
* @param array $row The row returned by PDOStatement->fetch(PDO::FETCH_NUM)
* @param int $startcol 0-based offset column which indicates which restultset column to start with.
* @param boolean $rehydrate Whether this object is being re-hydrated from the database.
* @return int next starting column
* @throws PropelException - Any caught Exception will be rewrapped as a PropelException.
*/
public function hydrate($row, $startcol = 0, $rehydrate = false)
{
try {
$this->user_id = ($row[$startcol + 0] !== null) ? (int) $row[$startcol + 0] : null;
$this->remember_key = ($row[$startcol + 1] !== null) ? (string) $row[$startcol + 1] : null;
$this->ip_address = ($row[$startcol + 2] !== null) ? (string) $row[$startcol + 2] : null;
$this->created_at = ($row[$startcol + 3] !== null) ? (string) $row[$startcol + 3] : null;
$this->resetModified();
$this->setNew(false);
if ($rehydrate) {
$this->ensureConsistency();
}
// FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 4; // 4 = sfGuardRememberKeyPeer::NUM_COLUMNS - sfGuardRememberKeyPeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) {
throw new PropelException("Error populating sfGuardRememberKey object", $e);
}
}
/**
* Checks and repairs the internal consistency of the object.
*
* This method is executed after an already-instantiated object is re-hydrated
* from the database. It exists to check any foreign keys to make sure that
* the objects related to the current object are correct based on foreign key.
*
* You can override this method in the stub class, but you should always invoke
* the base method from the overridden method (i.e. parent::ensureConsistency()),
* in case your model changes.
*
* @throws PropelException
*/
public function ensureConsistency()
{
if ($this->asfGuardUser !== null && $this->user_id !== $this->asfGuardUser->getId()) {
$this->asfGuardUser = null;
}
} // ensureConsistency
/**
* Reloads this object from datastore based on primary key and (optionally) resets all associated objects.
*
* This will only work if the object has been saved and has a valid primary key set.
*
* @param boolean $deep (optional) Whether to also de-associated any related objects.
* @param PropelPDO $con (optional) The PropelPDO connection to use.
* @return void
* @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db
*/
public function reload($deep = false, PropelPDO $con = null)
{
if ($this->isDeleted()) {
throw new PropelException("Cannot reload a deleted object.");
}
if ($this->isNew()) {
throw new PropelException("Cannot reload an unsaved object.");
}
if ($con === null) {
$con = Propel::getConnection(sfGuardRememberKeyPeer::DATABASE_NAME, Propel::CONNECTION_READ);
}
// We don't need to alter the object instance pool; we're just modifying this instance
// already in the pool.
$stmt = sfGuardRememberKeyPeer::doSelectStmt($this->buildPkeyCriteria(), $con);
$row = $stmt->fetch(PDO::FETCH_NUM);
$stmt->closeCursor();
if (!$row) {
throw new PropelException('Cannot find matching row in the database to reload object values.');
}
$this->hydrate($row, 0, true); // rehydrate
if ($deep) { // also de-associate any related objects?
$this->asfGuardUser = null;
} // if (deep)
}
/**
* Removes this object from datastore and sets delete attribute.
*
* @param PropelPDO $con
* @return void
* @throws PropelException
* @see BaseObject::setDeleted()
* @see BaseObject::isDeleted()
*/
public function delete(PropelPDO $con = null)
{
foreach (sfMixer::getCallables('BasesfGuardRememberKey:delete:pre') as $callable)
{
$ret = call_user_func($callable, $this, $con);
if ($ret)
{
return;
}
}
if ($this->isDeleted()) {
throw new PropelException("This object has already been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(sfGuardRememberKeyPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
sfGuardRememberKeyPeer::doDelete($this, $con);
$this->setDeleted(true);
$con->commit();
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
foreach (sfMixer::getCallables('BasesfGuardRememberKey:delete:post') as $callable)
{
call_user_func($callable, $this, $con);
}
}
/**
* Persists this object to the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All modified related objects will also be persisted in the doSave()
* method. This method wraps all precipitate database operations in a
* single transaction.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see doSave()
*/
public function save(PropelPDO $con = null)
{
foreach (sfMixer::getCallables('BasesfGuardRememberKey:save:pre') as $callable)
{
$affectedRows = call_user_func($callable, $this, $con);
if (is_int($affectedRows))
{
return $affectedRows;
}
}
if ($this->isNew() && !$this->isColumnModified(sfGuardRememberKeyPeer::CREATED_AT))
{
$this->setCreatedAt(time());
}
if ($this->isDeleted()) {
throw new PropelException("You cannot save an object that has been deleted.");
}
if ($con === null) {
$con = Propel::getConnection(sfGuardRememberKeyPeer::DATABASE_NAME, Propel::CONNECTION_WRITE);
}
$con->beginTransaction();
try {
$affectedRows = $this->doSave($con);
$con->commit();
foreach (sfMixer::getCallables('BasesfGuardRememberKey:save:post') as $callable)
{
call_user_func($callable, $this, $con, $affectedRows);
}
sfGuardRememberKeyPeer::addInstanceToPool($this);
return $affectedRows;
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
}
/**
* Performs the work of inserting or updating the row in the database.
*
* If the object is new, it inserts it; otherwise an update is performed.
* All related objects are also updated in this method.
*
* @param PropelPDO $con
* @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
* @throws PropelException
* @see save()
*/
protected function doSave(PropelPDO $con)
{
$affectedRows = 0; // initialize var to track total num of affected rows
if (!$this->alreadyInSave) {
$this->alreadyInSave = true;
// We call the save method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->asfGuardUser !== null) {
if ($this->asfGuardUser->isModified() || $this->asfGuardUser->isNew()) {
$affectedRows += $this->asfGuardUser->save($con);
}
$this->setsfGuardUser($this->asfGuardUser);
}
// If this object has been modified, then save it to the database.
if ($this->isModified()) {
if ($this->isNew()) {
$pk = sfGuardRememberKeyPeer::doInsert($this, $con);
$affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which
// should always be true here (even though technically
// BasePeer::doInsert() can insert multiple rows).
$this->setNew(false);
} else {
$affectedRows += sfGuardRememberKeyPeer::doUpdate($this, $con);
}
$this->resetModified(); // [HL] After being saved an object is no longer 'modified'
}
$this->alreadyInSave = false;
}
return $affectedRows;
} // doSave()
/**
* Array of ValidationFailed objects.
* @var array ValidationFailed[]
*/
protected $validationFailures = array();
/**
* Gets any ValidationFailed objects that resulted from last call to validate().
*
*
* @return array ValidationFailed[]
* @see validate()
*/
public function getValidationFailures()
{
return $this->validationFailures;
}
/**
* Validates the objects modified field values and all objects related to this table.
*
* If $columns is either a column name or an array of column names
* only those columns are validated.
*
* @param mixed $columns Column name or an array of column names.
* @return boolean Whether all columns pass validation.
* @see doValidate()
* @see getValidationFailures()
*/
public function validate($columns = null)
{
$res = $this->doValidate($columns);
if ($res === true) {
$this->validationFailures = array();
return true;
} else {
$this->validationFailures = $res;
return false;
}
}
/**
* This function performs the validation work for complex object models.
*
* In addition to checking the current object, all related objects will
* also be validated. If all pass then <code>true</code> is returned; otherwise
* an aggreagated array of ValidationFailed objects will be returned.
*
* @param array $columns Array of column names to validate.
* @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
*/
protected function doValidate($columns = null)
{
if (!$this->alreadyInValidation) {
$this->alreadyInValidation = true;
$retval = null;
$failureMap = array();
// We call the validate method on the following object(s) if they
// were passed to this object by their coresponding set
// method. This object relates to these object(s) by a
// foreign key reference.
if ($this->asfGuardUser !== null) {
if (!$this->asfGuardUser->validate($columns)) {
$failureMap = array_merge($failureMap, $this->asfGuardUser->getValidationFailures());
}
}
if (($retval = sfGuardRememberKeyPeer::doValidate($this, $columns)) !== true) {
$failureMap = array_merge($failureMap, $retval);
}
$this->alreadyInValidation = false;
}
return (!empty($failureMap) ? $failureMap : true);
}
/**
* Retrieves a field from the object by name passed in as a string.
*
* @param string $name name
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return mixed Value of field.
*/
public function getByName($name, $type = BasePeer::TYPE_PHPNAME)
{
$pos = sfGuardRememberKeyPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
$field = $this->getByPosition($pos);
return $field;
}
/**
* Retrieves a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @return mixed Value of field at $pos
*/
public function getByPosition($pos)
{
switch($pos) {
case 0:
return $this->getUserId();
break;
case 1:
return $this->getRememberKey();
break;
case 2:
return $this->getIpAddress();
break;
case 3:
return $this->getCreatedAt();
break;
default:
return null;
break;
} // switch()
}
/**
* Exports the object as an array.
*
* You can specify the key type of the array by passing one of the class
* type constants.
*
* @param string $keyType (optional) One of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. Defaults to BasePeer::TYPE_PHPNAME.
* @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE.
* @return an associative array containing the field names (as keys) and field values
*/
public function toArray($keyType = BasePeer::TYPE_PHPNAME, $includeLazyLoadColumns = true)
{
$keys = sfGuardRememberKeyPeer::getFieldNames($keyType);
$result = array(
$keys[0] => $this->getUserId(),
$keys[1] => $this->getRememberKey(),
$keys[2] => $this->getIpAddress(),
$keys[3] => $this->getCreatedAt(),
);
return $result;
}
/**
* Sets a field from the object by name passed in as a string.
*
* @param string $name peer name
* @param mixed $value field value
* @param string $type The type of fieldname the $name is of:
* one of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM
* @return void
*/
public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME)
{
$pos = sfGuardRememberKeyPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM);
return $this->setByPosition($pos, $value);
}
/**
* Sets a field from the object by Position as specified in the xml schema.
* Zero-based.
*
* @param int $pos position in xml schema
* @param mixed $value field value
* @return void
*/
public function setByPosition($pos, $value)
{
switch($pos) {
case 0:
$this->setUserId($value);
break;
case 1:
$this->setRememberKey($value);
break;
case 2:
$this->setIpAddress($value);
break;
case 3:
$this->setCreatedAt($value);
break;
} // switch()
}
/**
* Populates the object using an array.
*
* This is particularly useful when populating an object from one of the
* request arrays (e.g. $_POST). This method goes through the column
* names, checking to see whether a matching key exists in populated
* array. If so the setByName() method is called for that column.
*
* You can specify the key type of the array by additionally passing one
* of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
* BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
* The default key type is the column's phpname (e.g. 'AuthorId')
*
* @param array $arr An array to populate the object from.
* @param string $keyType The type of keys the array uses.
* @return void
*/
public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
$keys = sfGuardRememberKeyPeer::getFieldNames($keyType);
if (array_key_exists($keys[0], $arr)) $this->setUserId($arr[$keys[0]]);
if (array_key_exists($keys[1], $arr)) $this->setRememberKey($arr[$keys[1]]);
if (array_key_exists($keys[2], $arr)) $this->setIpAddress($arr[$keys[2]]);
if (array_key_exists($keys[3], $arr)) $this->setCreatedAt($arr[$keys[3]]);
}
/**
* Build a Criteria object containing the values of all modified columns in this object.
*
* @return Criteria The Criteria object containing all modified values.
*/
public function buildCriteria()
{
$criteria = new Criteria(sfGuardRememberKeyPeer::DATABASE_NAME);
if ($this->isColumnModified(sfGuardRememberKeyPeer::USER_ID)) $criteria->add(sfGuardRememberKeyPeer::USER_ID, $this->user_id);
if ($this->isColumnModified(sfGuardRememberKeyPeer::REMEMBER_KEY)) $criteria->add(sfGuardRememberKeyPeer::REMEMBER_KEY, $this->remember_key);
if ($this->isColumnModified(sfGuardRememberKeyPeer::IP_ADDRESS)) $criteria->add(sfGuardRememberKeyPeer::IP_ADDRESS, $this->ip_address);
if ($this->isColumnModified(sfGuardRememberKeyPeer::CREATED_AT)) $criteria->add(sfGuardRememberKeyPeer::CREATED_AT, $this->created_at);
return $criteria;
}
/**
* Builds a Criteria object containing the primary key for this object.
*
* Unlike buildCriteria() this method includes the primary key values regardless
* of whether or not they have been modified.
*
* @return Criteria The Criteria object containing value(s) for primary key(s).
*/
public function buildPkeyCriteria()
{
$criteria = new Criteria(sfGuardRememberKeyPeer::DATABASE_NAME);
$criteria->add(sfGuardRememberKeyPeer::USER_ID, $this->user_id);
$criteria->add(sfGuardRememberKeyPeer::IP_ADDRESS, $this->ip_address);
return $criteria;
}
/**
* Returns the composite primary key for this object.
* The array elements will be in same order as specified in XML.
* @return array
*/
public function getPrimaryKey()
{
$pks = array();
$pks[0] = $this->getUserId();
$pks[1] = $this->getIpAddress();
return $pks;
}
/**
* Set the [composite] primary key.
*
* @param array $keys The elements of the composite key (order must match the order in XML file).
* @return void
*/
public function setPrimaryKey($keys)
{
$this->setUserId($keys[0]);
$this->setIpAddress($keys[1]);
}
/**
* Sets contents of passed object to values from current object.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param object $copyObj An object of sfGuardRememberKey (or compatible) type.
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @throws PropelException
*/
public function copyInto($copyObj, $deepCopy = false)
{
$copyObj->setUserId($this->user_id);
$copyObj->setRememberKey($this->remember_key);
$copyObj->setIpAddress($this->ip_address);
$copyObj->setCreatedAt($this->created_at);
$copyObj->setNew(true);
}
/**
* Makes a copy of this object that will be inserted as a new row in table when saved.
* It creates a new object filling in the simple attributes, but skipping any primary
* keys that are defined for the table.
*
* If desired, this method can also make copies of all associated (fkey referrers)
* objects.
*
* @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
* @return sfGuardRememberKey Clone of current object.
* @throws PropelException
*/
public function copy($deepCopy = false)
{
// we use get_class(), because this might be a subclass
$clazz = get_class($this);
$copyObj = new $clazz();
$this->copyInto($copyObj, $deepCopy);
return $copyObj;
}
/**
* Returns a peer instance associated with this om.
*
* Since Peer classes are not to have any instance attributes, this method returns the
* same instance for all member of this class. The method could therefore
* be static, but this would prevent one from overriding the behavior.
*
* @return sfGuardRememberKeyPeer
*/
public function getPeer()
{
if (self::$peer === null) {
self::$peer = new sfGuardRememberKeyPeer();
}
return self::$peer;
}
/**
* Declares an association between this object and a sfGuardUser object.
*
* @param sfGuardUser $v
* @return sfGuardRememberKey The current object (for fluent API support)
* @throws PropelException
*/
public function setsfGuardUser(sfGuardUser $v = null)
{
if ($v === null) {
$this->setUserId(NULL);
} else {
$this->setUserId($v->getId());
}
$this->asfGuardUser = $v;
// Add binding for other direction of this n:n relationship.
// If this object has already been added to the sfGuardUser object, it will not be re-added.
if ($v !== null) {
$v->addsfGuardRememberKey($this);
}
return $this;
}
/**
* Get the associated sfGuardUser object
*
* @param PropelPDO Optional Connection object.
* @return sfGuardUser The associated sfGuardUser object.
* @throws PropelException
*/
public function getsfGuardUser(PropelPDO $con = null)
{
if ($this->asfGuardUser === null && ($this->user_id !== null)) {
$c = new Criteria(sfGuardUserPeer::DATABASE_NAME);
$c->add(sfGuardUserPeer::ID, $this->user_id);
$this->asfGuardUser = sfGuardUserPeer::doSelectOne($c, $con);
/* The following can be used additionally to
guarantee the related object contains a reference
to this object. This level of coupling may, however, be
undesirable since it could result in an only partially populated collection
in the referenced object.
$this->asfGuardUser->addsfGuardRememberKeys($this);
*/
}
return $this->asfGuardUser;
}
/**
* Resets all collections of referencing foreign keys.
*
* This method is a user-space workaround for PHP's inability to garbage collect objects
* with circular references. This is currently necessary when using Propel in certain
* daemon or large-volumne/high-memory operations.
*
* @param boolean $deep Whether to also clear the references on all associated objects.
*/
public function clearAllReferences($deep = false)
{
if ($deep) {
} // if ($deep)
$this->asfGuardUser = null;
}
public function __call($method, $arguments)
{
if (!$callable = sfMixer::getCallable('BasesfGuardRememberKey:'.$method))
{
throw new sfException(sprintf('Call to undefined method BasesfGuardRememberKey::%s', $method));
}
array_unshift($arguments, $this);
return call_user_func_array($callable, $arguments);
}
} // BasesfGuardRememberKey
| xop32/propertyx | plugins/sfGuardPlugin/lib/model/om/BasesfGuardRememberKey.php | PHP | mit | 29,036 |
<?php
class Infusionsoft_OrderServiceBase extends Infusionsoft_Service {
public static function placeOrder($contactId, $creditCardId, $payPlanId, $productIds, $subscriptionPlanIds, $processSpecials, $promoCodes, $leadAffiliateId = 0, $affiliatedId = 0, Infusionsoft_App $app = null){
$params = array(
(int) $contactId,
(int) $creditCardId,
(int) $payPlanId,
$productIds,
$subscriptionPlanIds,
(boolean) $processSpecials,
$promoCodes,
$leadAffiliateId,
$affiliatedId
);
return parent::send($app, "OrderService.placeOrder", $params);
}
} | bmoelk/cerb-infusionsoft | api/Infusionsoft/OrderServiceBase.php | PHP | mit | 675 |
/**
* @fileoverview Tests for max-depth.
* @author Ian Christian Myers
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
eslintTester.addRuleTest("lib/rules/max-depth", {
valid: [
{ code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 3] },
"function foo() { if (true) { if (false) { if (true) { } } } }"
],
invalid: [
{ code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 2], errors: [{ message: "Blocks are nested too deeply (3).", type: "IfStatement"}] },
{ code: "function foo() { if (true) {} else { for(;;) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "ForStatement"}] },
{ code: "function foo() { while (true) { if (true) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}] },
{ code: "function foo() { while (true) { if (true) { if (false) { } } } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}, { message: "Blocks are nested too deeply (3).", type: "IfStatement"}] }
]
});
| natesilva/eslint | tests/lib/rules/max-depth.js | JavaScript | mit | 1,497 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
namespace Microsoft.Build.Construction
{
/// <summary>
/// Improvement to XmlDocument that during load attaches location information to all elements and attributes.
/// We don't need a real XmlDocument, as we are careful not to expose Xml types in our public API.
/// </summary>
/// <remarks>
/// XmlDocument has many members, and this can't substitute for all of them. Location finding probably won't work if
/// certain XmlDocument members are used. So for extra robustness, this could wrap an XmlDocument instead,
/// and expose the small number of members that the MSBuild code actually uses.
/// </remarks>
internal class XmlDocumentWithLocation : XmlDocument
{
/// <summary>
/// Used to cache strings used in attribute values and comments.
/// </summary>
private static ProjectStringCache s_globalStringCache = new ProjectStringCache();
/// <summary>
/// Used to cache tag names in loaded files.
/// </summary>
private static NameTable s_nameTable = new XmlNameTableThreadSafe();
/// <summary>
/// Whether we can selectively load as read-only (eg just when in program files directory)
/// </summary>
private static ReadOnlyLoadFlags s_readOnlyFlags;
/// <summary>
/// Reader we've hooked
/// </summary>
private IXmlLineInfo _reader;
/// <summary>
/// Path to the file loaded, if any, otherwise null.
/// Easier to intercept and store than to derive it from the XmlDocument.BaseUri property.
/// </summary>
private string _fullPath;
/// <summary>
/// Local cache of strings for attribute values and comments. Used for testing.
/// </summary>
private ProjectStringCache _stringCache;
/// <summary>
/// Whether we can expect to never save this file.
/// In such a case, we can discard as much as possible on load, like comments and whitespace.
/// </summary>
private bool? _loadAsReadOnly;
/// <summary>
/// Constructor
/// </summary>
internal XmlDocumentWithLocation()
: base(s_nameTable)
{
}
/// <summary>
/// Constructor
/// </summary>
internal XmlDocumentWithLocation(bool? loadAsReadOnly)
: this()
{
_loadAsReadOnly = loadAsReadOnly;
}
/// <summary>
/// Whether to load files read only
/// </summary>
private enum ReadOnlyLoadFlags
{
/// <summary>
/// Not determined
/// </summary>
Undefined,
/// <summary>
/// Always load writeable
/// </summary>
LoadAllWriteable,
/// <summary>
/// Always load read-only, to save memory
/// </summary>
LoadAllReadOnly,
/// <summary>
/// Load read only selectively, Eg., just when file names begin with "Microsoft."
/// </summary>
LoadReadOnlyIfAppropriate
}
/// <summary>
/// Path to the file loaded if any, otherwise null.
/// If the XmlDocument hasn't been loaded from a file, we wouldn't have a full path.
/// However the project might actually have been given a path - it might even have been saved.
/// In order to allow created elements to be able to provide a location with at least
/// that path, the setter here should be called when the project is given a path.
/// It may be set to null.
/// </summary>
internal string FullPath
{
get { return _fullPath; }
set { _fullPath = value; }
}
/// <summary>
/// Sets or gets the string cache used by this XmlDocument.
/// </summary>
/// <remarks>
/// When a particular instance has not been set will use the global string cache. The ability
/// to use a particular instance is useful for tests.
/// </remarks>
internal ProjectStringCache StringCache
{
get { return _stringCache ?? s_globalStringCache; }
set { _stringCache = value; }
}
/// <summary>
/// Loads from an XmlReader, intercepting the reader.
/// </summary>
/// <remarks>
/// This method is called within XmlDocument by all other
/// Load(..) overloads, and by LoadXml(..), so however the client loads XML,
/// we will grab the reader.
/// </remarks>
public override void Load(XmlReader reader)
{
if (reader.BaseURI.Length > 0)
{
DetermineWhetherToLoadReadOnly(new Uri(reader.BaseURI).LocalPath);
}
// Set the line info source if it is available given the specific implementation of XmlReader
// we've been given.
_reader = reader as IXmlLineInfo;
// This call results in calls to our CreateElement and CreateAttribute methods,
// which use this.reader within themselves.
base.Load(reader);
// After load, the reader is no use for location information; it isn't updated when
// the document is edited. So null it out, so that elements and attributes created by subsequent
// editing don't have meaningless location information.
_reader = null;
}
#if FEATURE_XML_LOADPATH
/// <summary>
/// Grab the path to the file, for use in our location information.
/// </summary>
public override void Load(string fullPath)
{
DetermineWhetherToLoadReadOnly(fullPath);
_fullPath = fullPath;
using(var xtr = XmlReaderExtension.Create(fullPath, _loadAsReadOnly ?? false))
{
this.Load(xtr.Reader);
}
}
#endif
/// <summary>
/// Called during load, to add an element.
/// </summary>
/// <remarks>
/// We create our own kind of element, that we can give location information to.
/// </remarks>
public override XmlElement CreateElement(string prefix, string localName, string namespaceURI)
{
if (_reader != null)
{
return new XmlElementWithLocation(prefix, localName, namespaceURI, this, _reader.LineNumber, _reader.LinePosition);
}
// Must be a subsequent edit; we can't provide location information
return new XmlElementWithLocation(prefix, localName, namespaceURI, this);
}
/// <summary>
/// Called during load, to add an attribute.
/// </summary>
/// <remarks>
/// We create our own kind of attribute, that we can give location information to.
/// </remarks>
public override XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI)
{
if (_reader != null)
{
return new XmlAttributeWithLocation(prefix, localName, namespaceURI, this, _reader.LineNumber, _reader.LinePosition);
}
// Must be a subsequent edit; we can't provide location information
return new XmlAttributeWithLocation(prefix, localName, namespaceURI, this);
}
/// <summary>
/// Create a whitespace node.
/// Overridden to cache attribute values.
/// </summary>
public override XmlWhitespace CreateWhitespace(string text)
{
if (_loadAsReadOnly.HasValue && _loadAsReadOnly.Value)
{
text = String.Empty;
}
string interned = StringCache.Add(text, this);
return base.CreateWhitespace(interned);
}
/// <summary>
/// Create a whitespace node. The definition of "significant" whitespace is obscure
/// and does not include whitespace in text values in element content, which we always want to keep.
/// Overridden to cache attribute values.
/// </summary>
public override XmlSignificantWhitespace CreateSignificantWhitespace(string text)
{
if (_loadAsReadOnly.HasValue && _loadAsReadOnly.Value)
{
text = String.Empty;
}
string interned = StringCache.Add(text, this);
return base.CreateSignificantWhitespace(interned);
}
/// <summary>
/// Create a text node.
/// Overridden to cache attribute values.
/// </summary>
public override XmlText CreateTextNode(string text)
{
string textNode = StringCache.Add(text, this);
return base.CreateTextNode(textNode);
}
/// <summary>
/// Create a comment node.
/// Overridden in order to cache comment strings.
/// </summary>
public override XmlComment CreateComment(string data)
{
if (_loadAsReadOnly.HasValue && _loadAsReadOnly.Value)
{
data = String.Empty;
}
string interned = StringCache.Add(data, this);
return base.CreateComment(interned);
}
/// <summary>
/// Override Save to verify file was not loaded as readonly
/// </summary>
public override void Save(Stream outStream)
{
VerifyThrowNotReadOnly();
base.Save(outStream);
}
#if FEATURE_XML_LOADPATH
/// <summary>
/// Override Save to verify file was not loaded as readonly
/// </summary>
public override void Save(string filename)
{
VerifyThrowNotReadOnly();
base.Save(filename);
}
#endif
/// <summary>
/// Override Save to verify file was not loaded as readonly
/// </summary>
public override void Save(TextWriter writer)
{
VerifyThrowNotReadOnly();
base.Save(writer);
}
/// <summary>
/// Override Save to verify file was not loaded as readonly
/// </summary>
public override void Save(XmlWriter writer)
{
VerifyThrowNotReadOnly();
base.Save(writer);
}
/// <summary>
/// Override IsReadOnly property to correctly indicate the mode to callers
/// </summary>
public override bool IsReadOnly => _loadAsReadOnly.GetValueOrDefault();
/// <summary>
/// Reset state for unit tests that want to set the env var
/// </summary>
internal static void ClearReadOnlyFlags_UnitTestsOnly()
{
s_readOnlyFlags = ReadOnlyLoadFlags.Undefined;
}
/// <summary>
/// Called when the XmlDocument is unloaded to remove this XML's
/// contribution to the string interning cache.
/// Does NOT zombie the ProjectRootElement or anything else.
/// </summary>
internal void ClearAnyCachedStrings()
{
StringCache.Clear(this);
}
/// <summary>
/// Determine whether we should load this file read only.
/// We decide yes if it is in program files or the OS directory, and the file name starts with "microsoft", else no.
/// We are very selective because we don't want to load files read only that the host might want to save, nor
/// any files in which comments within property/metadata values might be significant - MSBuild does not discard those, normally.
/// </summary>
private void DetermineWhetherToLoadReadOnly(string fullPath)
{
if (_loadAsReadOnly == null)
{
DetermineWhetherToLoadReadOnlyIfPossible();
if (s_readOnlyFlags == ReadOnlyLoadFlags.LoadAllReadOnly)
{
_loadAsReadOnly = true;
}
else if (s_readOnlyFlags == ReadOnlyLoadFlags.LoadReadOnlyIfAppropriate)
{
// Only files from Microsoft
if (Path.GetFileName(fullPath).StartsWith("Microsoft.", StringComparison.OrdinalIgnoreCase))
{
// If we are loading devdiv targets, we're in razzle
if (Path.GetFileName(fullPath).StartsWith("Microsoft.DevDiv", StringComparison.OrdinalIgnoreCase))
{
_loadAsReadOnly = true;
}
else // Else, only load if they're in program files or windows directories
{
ErrorUtilities.VerifyThrow(Path.IsPathRooted(fullPath), "should be full path");
string directory = Path.GetDirectoryName(fullPath);
string windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
if ((!String.IsNullOrEmpty(windowsFolder) && directory.StartsWith(windowsFolder, StringComparison.OrdinalIgnoreCase)) ||
(!String.IsNullOrEmpty(FrameworkLocationHelper.programFiles32) && directory.StartsWith(FrameworkLocationHelper.programFiles32, StringComparison.OrdinalIgnoreCase)) ||
(!String.IsNullOrEmpty(FrameworkLocationHelper.programFiles64) && directory.StartsWith(FrameworkLocationHelper.programFiles64, StringComparison.OrdinalIgnoreCase)))
{
_loadAsReadOnly = true;
}
}
}
}
}
}
/// <summary>
/// Determine whether we would ever load read only
/// </summary>
private void DetermineWhetherToLoadReadOnlyIfPossible()
{
if (s_readOnlyFlags == ReadOnlyLoadFlags.Undefined)
{
s_readOnlyFlags = ReadOnlyLoadFlags.LoadAllWriteable;
if (String.Equals(Environment.GetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly"), "true", StringComparison.OrdinalIgnoreCase))
{
s_readOnlyFlags = ReadOnlyLoadFlags.LoadReadOnlyIfAppropriate;
}
if (String.Equals(Environment.GetEnvironmentVariable("MSBUILDLOADALLFILESASREADONLY"), "1", StringComparison.OrdinalIgnoreCase))
{
s_readOnlyFlags = ReadOnlyLoadFlags.LoadAllReadOnly;
}
// "Escape hatch" should someone really need to edit these - since we'll be switching it on in VS and msbuild.exe wholesale.
if (String.Equals(Environment.GetEnvironmentVariable("MSBUILDLOADALLFILESASWRITEABLE"), "1", StringComparison.OrdinalIgnoreCase))
{
s_readOnlyFlags = ReadOnlyLoadFlags.LoadAllWriteable;
}
}
}
/// <summary>
/// Throw if this was loaded read only
/// </summary>
private void VerifyThrowNotReadOnly()
{
ErrorUtilities.VerifyThrowInvalidOperation(!_loadAsReadOnly.HasValue || !_loadAsReadOnly.Value, "OM_CannotSaveFileLoadedAsReadOnly", _fullPath);
}
}
}
| Microsoft/msbuild | src/Build/ElementLocation/XmlDocumentWithLocation.cs | C# | mit | 15,727 |
RSpec::Matchers.define :be_directory do
match do |actual|
ret = ssh_exec(commands.check_directory(actual))
ret[:exit_code] == 0
end
end
| gongo/serverspec | lib/serverspec/matchers/be_directory.rb | Ruby | mit | 148 |
import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";
import { AppComponent } from "./app.component";
@NgModule({
declarations: [AppComponent],
bootstrap: [AppComponent],
imports: [NativeScriptModule],
schemas: [NO_ERRORS_SCHEMA],
})
export class AppModule {}
| syzer/six-hackaton-2017 | app/ShopSquad/app/app.module.ts | TypeScript | mit | 355 |
using Microsoft.Xna.Framework.Graphics;
namespace Nez
{
public class VignettePostProcessor : PostProcessor
{
[Range(0.001f, 10f, 0.001f)]
public float Power
{
get => _power;
set
{
if (_power != value)
{
_power = value;
if (Effect != null)
_powerParam.SetValue(_power);
}
}
}
[Range(0.001f, 10f, 0.001f)]
public float Radius
{
get => _radius;
set
{
if (_radius != value)
{
_radius = value;
if (Effect != null)
_radiusParam.SetValue(_radius);
}
}
}
float _power = 1f;
float _radius = 1.25f;
EffectParameter _powerParam;
EffectParameter _radiusParam;
public VignettePostProcessor(int executionOrder) : base(executionOrder)
{
}
public override void OnAddedToScene(Scene scene)
{
base.OnAddedToScene(scene);
Effect = scene.Content.LoadEffect<Effect>("vignette", EffectResource.VignetteBytes);
_powerParam = Effect.Parameters["_power"];
_radiusParam = Effect.Parameters["_radius"];
_powerParam.SetValue(_power);
_radiusParam.SetValue(_radius);
}
public override void Unload()
{
_scene.Content.UnloadEffect(Effect);
base.Unload();
}
}
} | ericmbernier/Nez | Nez.Portable/Graphics/PostProcessing/PostProcessors/VignettePostProcessor.cs | C# | mit | 1,193 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** CustomAttributeBuilder is a helper class to help building custom attribute.
**
**
===========================================================*/
namespace System.Reflection.Emit {
using System;
using System.Reflection;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_CustomAttributeBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public class CustomAttributeBuilder : _CustomAttributeBuilder
{
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
{
InitCustomAttributeBuilder(con, constructorArgs,
new PropertyInfo[]{}, new Object[]{},
new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor, constructor
// parameters and named properties.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, new FieldInfo[]{}, new Object[]{});
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{},
new Object[]{}, namedFields, fieldValues);
}
// public constructor to form the custom attribute with constructor and constructor
// parameters.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
propertyValues, namedFields, fieldValues);
}
// Check that a type is suitable for use in a custom attribute.
private bool ValidateType(Type t)
{
if (t.IsPrimitive)
{
return t != typeof(IntPtr) && t != typeof(UIntPtr);
}
if (t == typeof(String) || t == typeof(Type))
{
return true;
}
if (t.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(t)))
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
return true;
default:
return false;
}
}
if (t.IsArray)
{
if (t.GetArrayRank() != 1)
return false;
return ValidateType(t.GetElementType());
}
return t == typeof(Object);
}
internal void InitCustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues,
FieldInfo[] namedFields, Object[] fieldValues)
{
if (con == null)
throw new ArgumentNullException(nameof(con));
if (constructorArgs == null)
throw new ArgumentNullException(nameof(constructorArgs));
if (namedProperties == null)
throw new ArgumentNullException(nameof(namedProperties));
if (propertyValues == null)
throw new ArgumentNullException(nameof(propertyValues));
if (namedFields == null)
throw new ArgumentNullException(nameof(namedFields));
if (fieldValues == null)
throw new ArgumentNullException(nameof(fieldValues));
if (namedProperties.Length != propertyValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
if (namedFields.Length != fieldValues.Length)
throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues");
Contract.EndContractBlock();
if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
(con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));
if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));
// Cache information used elsewhere.
m_con = con;
m_constructorArgs = new Object[constructorArgs.Length];
Array.Copy(constructorArgs, 0, m_constructorArgs, 0, constructorArgs.Length);
Type[] paramTypes;
int i;
// Get the types of the constructor's formal parameters.
paramTypes = con.GetParameterTypes();
// Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters.
if (paramTypes.Length != constructorArgs.Length)
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor"));
// Verify that the constructor has a valid signature (custom attributes only support a subset of our type system).
for (i = 0; i < paramTypes.Length; i++)
if (!ValidateType(paramTypes[i]))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
for (i = 0; i < paramTypes.Length; i++)
{
object constructorArg = constructorArgs[i];
if (constructorArg == null)
{
if (paramTypes[i].IsValueType)
{
throw new ArgumentNullException($"{nameof(constructorArgs)}[{i}]");
}
continue;
}
VerifyTypeAndPassedObjectType(paramTypes[i], constructorArg.GetType(), $"{nameof(constructorArgs)}[{i}]");
}
// Allocate a memory stream to represent the CA blob in the metadata and a binary writer to help format it.
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
// Write the blob protocol version (currently 1).
writer.Write((ushort)1);
// Now emit the constructor argument values (no need for types, they're inferred from the constructor signature).
for (i = 0; i < constructorArgs.Length; i++)
EmitValue(writer, paramTypes[i], constructorArgs[i]);
// Next a short with the count of properties and fields.
writer.Write((ushort)(namedProperties.Length + namedFields.Length));
// Emit all the property sets.
for (i = 0; i < namedProperties.Length; i++)
{
// Validate the property.
PropertyInfo property = namedProperties[i];
if (property == null)
throw new ArgumentNullException("namedProperties[" + i + "]");
// Allow null for non-primitive types only.
Type propType = property.PropertyType;
object propertyValue = propertyValues[i];
if (propertyValue == null && propType.IsValueType)
throw new ArgumentNullException("propertyValues[" + i + "]");
// Validate property type.
if (!ValidateType(propType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Property has to be writable.
if (!property.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));
// Property has to be from the same class or base class as ConstructorInfo.
if (property.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(property.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(property.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the property's declaring
// type is one.
if (!(property.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
}
}
// Make sure the property's type can take the given value.
// Note that there will be no coersion.
if (propertyValue != null)
{
VerifyTypeAndPassedObjectType(propType, propertyValue.GetType(), $"{nameof(propertyValues)}[{i}]");
}
// First a byte indicating that this is a property.
writer.Write((byte)CustomAttributeEncoding.Property);
// Emit the property type, name and value.
EmitType(writer, propType);
EmitString(writer, namedProperties[i].Name);
EmitValue(writer, propType, propertyValue);
}
// Emit all the field sets.
for (i = 0; i < namedFields.Length; i++)
{
// Validate the field.
FieldInfo namedField = namedFields[i];
if (namedField == null)
throw new ArgumentNullException("namedFields[" + i + "]");
// Allow null for non-primitive types only.
Type fldType = namedField.FieldType;
object fieldValue = fieldValues[i];
if (fieldValue == null && fldType.IsValueType)
throw new ArgumentNullException("fieldValues[" + i + "]");
// Validate field type.
if (!ValidateType(fldType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
// Field has to be from the same class or base class as ConstructorInfo.
if (namedField.DeclaringType != con.DeclaringType
&& (!(con.DeclaringType is TypeBuilderInstantiation))
&& !con.DeclaringType.IsSubclassOf(namedField.DeclaringType))
{
// Might have failed check because one type is a XXXBuilder
// and the other is not. Deal with these special cases
// separately.
if (!TypeBuilder.IsTypeEqual(namedField.DeclaringType, con.DeclaringType))
{
// IsSubclassOf is overloaded to do the right thing if
// the constructor is a TypeBuilder, but we still need
// to deal with the case where the field's declaring
// type is one.
if (!(namedField.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
}
}
// Make sure the field's type can take the given value.
// Note that there will be no coersion.
if (fieldValue != null)
{
VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]");
}
// First a byte indicating that this is a field.
writer.Write((byte)CustomAttributeEncoding.Field);
// Emit the field type, name and value.
EmitType(writer, fldType);
EmitString(writer, namedField.Name);
EmitValue(writer, fldType, fieldValue);
}
// Create the blob array.
m_blob = ((MemoryStream)writer.BaseStream).ToArray();
}
private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName)
{
if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type))
{
throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
}
if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr))
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName);
}
}
private void EmitType(BinaryWriter writer, Type type)
{
if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((byte)CustomAttributeEncoding.SByte);
break;
case TypeCode.Byte:
writer.Write((byte)CustomAttributeEncoding.Byte);
break;
case TypeCode.Char:
writer.Write((byte)CustomAttributeEncoding.Char);
break;
case TypeCode.Boolean:
writer.Write((byte)CustomAttributeEncoding.Boolean);
break;
case TypeCode.Int16:
writer.Write((byte)CustomAttributeEncoding.Int16);
break;
case TypeCode.UInt16:
writer.Write((byte)CustomAttributeEncoding.UInt16);
break;
case TypeCode.Int32:
writer.Write((byte)CustomAttributeEncoding.Int32);
break;
case TypeCode.UInt32:
writer.Write((byte)CustomAttributeEncoding.UInt32);
break;
case TypeCode.Int64:
writer.Write((byte)CustomAttributeEncoding.Int64);
break;
case TypeCode.UInt64:
writer.Write((byte)CustomAttributeEncoding.UInt64);
break;
case TypeCode.Single:
writer.Write((byte)CustomAttributeEncoding.Float);
break;
case TypeCode.Double:
writer.Write((byte)CustomAttributeEncoding.Double);
break;
default:
Debug.Assert(false, "Invalid primitive type");
break;
}
}
else if (type.IsEnum)
{
writer.Write((byte)CustomAttributeEncoding.Enum);
EmitString(writer, type.AssemblyQualifiedName);
}
else if (type == typeof(String))
{
writer.Write((byte)CustomAttributeEncoding.String);
}
else if (type == typeof(Type))
{
writer.Write((byte)CustomAttributeEncoding.Type);
}
else if (type.IsArray)
{
writer.Write((byte)CustomAttributeEncoding.Array);
EmitType(writer, type.GetElementType());
}
else
{
// Tagged object case.
writer.Write((byte)CustomAttributeEncoding.Object);
}
}
private void EmitString(BinaryWriter writer, String str)
{
// Strings are emitted with a length prefix in a compressed format (1, 2 or 4 bytes) as used internally by metadata.
byte[] utf8Str = Encoding.UTF8.GetBytes(str);
uint length = (uint)utf8Str.Length;
if (length <= 0x7f)
{
writer.Write((byte)length);
}
else if (length <= 0x3fff)
{
writer.Write((byte)((length >> 8) | 0x80));
writer.Write((byte)(length & 0xff));
}
else
{
writer.Write((byte)((length >> 24) | 0xc0));
writer.Write((byte)((length >> 16) & 0xff));
writer.Write((byte)((length >> 8) & 0xff));
writer.Write((byte)(length & 0xff));
}
writer.Write(utf8Str);
}
private void EmitValue(BinaryWriter writer, Type type, Object value)
{
if (type.IsEnum)
{
switch (Type.GetTypeCode(Enum.GetUnderlyingType(type)))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
default:
Debug.Assert(false, "Invalid enum base type");
break;
}
}
else if (type == typeof(String))
{
if (value == null)
writer.Write((byte)0xff);
else
EmitString(writer, (String)value);
}
else if (type == typeof(Type))
{
if (value == null)
writer.Write((byte)0xff);
else
{
String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
if (typeName == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA",
value.GetType()));
EmitString(writer, typeName);
}
}
else if (type.IsArray)
{
if (value == null)
writer.Write((uint)0xffffffff);
else
{
Array a = (Array)value;
Type et = type.GetElementType();
writer.Write(a.Length);
for (int i = 0; i < a.Length; i++)
EmitValue(writer, et, a.GetValue(i));
}
}
else if (type.IsPrimitive)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.SByte:
writer.Write((sbyte)value);
break;
case TypeCode.Byte:
writer.Write((byte)value);
break;
case TypeCode.Char:
writer.Write(Convert.ToUInt16((char)value));
break;
case TypeCode.Boolean:
writer.Write((byte)((bool)value ? 1 : 0));
break;
case TypeCode.Int16:
writer.Write((short)value);
break;
case TypeCode.UInt16:
writer.Write((ushort)value);
break;
case TypeCode.Int32:
writer.Write((int)value);
break;
case TypeCode.UInt32:
writer.Write((uint)value);
break;
case TypeCode.Int64:
writer.Write((long)value);
break;
case TypeCode.UInt64:
writer.Write((ulong)value);
break;
case TypeCode.Single:
writer.Write((float)value);
break;
case TypeCode.Double:
writer.Write((double)value);
break;
default:
Debug.Assert(false, "Invalid primitive type");
break;
}
}
else if (type == typeof(object))
{
// Tagged object case. Type instances aren't actually Type, they're some subclass (such as RuntimeType or
// TypeBuilder), so we need to canonicalize this case back to Type. If we have a null value we follow the convention
// used by C# and emit a null typed as a string (it doesn't really matter what type we pick as long as it's a
// reference type).
Type ot = value == null ? typeof(String) : value is Type ? typeof(Type) : value.GetType();
// value cannot be a "System.Object" object.
// If we allow this we will get into an infinite recursion
if (ot == typeof(object))
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
EmitType(writer, ot);
EmitValue(writer, ot, value);
}
else
{
string typename = "null";
if (value != null)
typename = value.GetType().ToString();
throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
}
}
// return the byte interpretation of the custom attribute
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
{
CreateCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con).Token, false);
}
//*************************************************
// Upon saving to disk, we need to create the memberRef token for the custom attribute's type
// first of all. So when we snap the in-memory module for on disk, this token will be there.
// We also need to enforce the use of MemberRef. Because MemberDef token might move.
// This function has to be called before we snap the in-memory module for on disk (i.e. Presave on
// ModuleBuilder.
//*************************************************
internal int PrepareCreateCustomAttributeToDisk(ModuleBuilder mod)
{
return mod.InternalGetConstructorToken(m_con, true).Token;
}
//*************************************************
// Call this function with toDisk=1, after on disk module has been snapped.
//*************************************************
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
{
TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
internal ConstructorInfo m_con;
internal Object[] m_constructorArgs;
internal byte[] m_blob;
}
}
| neurospeech/coreclr | src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs | C# | mit | 26,472 |
require 'optparse'
require 'oink/reports/base'
require 'oink/reports/active_record_instantiation_report'
require 'oink/reports/memory_usage_report'
module Oink
class Cli
def initialize(args)
@args = args
end
def process
options = { :format => :short_summary, :type => :memory }
op = OptionParser.new do |opts|
opts.banner = "Usage: oink [options] files"
opts.on("-t", "--threshold [INTEGER]", Integer,
"Memory threshold in MB") do |threshold|
options[:threshold] = threshold
end
opts.on("-f", "--file filepath", "Output to file") do |filename|
options[:output_file] = filename
end
format_list = (Oink::Reports::Base::FORMAT_ALIASES.keys + Oink::Reports::Base::FORMATS).join(',')
opts.on("--format FORMAT", Oink::Reports::Base::FORMATS, Oink::Reports::Base::FORMAT_ALIASES, "Select format",
" (#{format_list})") do |format|
options[:format] = format.to_sym
end
opts.on("-m", "--memory", "Check for Memory Threshold (default)") do |v|
options[:type] = :memory
end
opts.on("-r", "--active-record", "Check for Active Record Threshold") do |v|
options[:type] = :active_record
end
end
op.parse!(@args)
if @args.empty?
puts op
exit
end
output = nil
if options[:output_file]
output = File.open(options[:output_file], 'w')
else
output = STDOUT
end
files = get_file_listing(@args)
handles = files.map { |f| File.open(f) }
if options[:type] == :memory
options[:threshold] ||= 75
options[:threshold] *= 1024
Oink::Reports::MemoryUsageReport.new(handles, options[:threshold], :format => options[:format]).print(output)
elsif options[:type] == :active_record
options[:threshold] ||= 500
Oink::Reports::ActiveRecordInstantiationReport.new(handles, options[:threshold], :format => options[:format]).print(output)
end
output.close
handles.each { |h| h.close }
end
protected
def get_file_listing(args)
listing = []
args.each do |file|
unless File.exist?(file)
raise "Could not find \"#{file}\""
end
if File.directory?(file)
listing += Dir.glob("#{file}/**")
else
listing << file
end
end
listing
end
end
end
| zBMNForks/oink | lib/oink/cli.rb | Ruby | mit | 2,502 |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChildren = isReactChildren;
exports.createRouteFromReactElement = createRouteFromReactElement;
exports.createRoutesFromReactChildren = createRoutesFromReactChildren;
exports.createRoutes = createRoutes;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function isValidChild(object) {
return object == null || (0, _react.isValidElement)(object);
}
function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent';
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, componentName);
if (error instanceof Error) (0, _warning2['default'])(false, error.message);
}
}
}
function createRouteFromReactElement(element) {
var type = element.type;
var route = _extends({}, type.defaultProps, element.props);
if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route);
if (route.children) {
route.childRoutes = createRoutesFromReactChildren(route.children);
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router';
*
* var routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* );
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
function createRoutesFromReactChildren(children) {
var routes = [];
_react2['default'].Children.forEach(children, function (element) {
if ((0, _react.isValidElement)(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
routes.push(element.type.createRouteFromReactElement(element));
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (!Array.isArray(routes)) {
routes = [routes];
}
return routes;
} | yomolify/cc-server | node_modules/react-router/lib/RouteUtils.js | JavaScript | mit | 3,153 |
<?php
namespace Rad\Core;
/**
* Singleton trait
*
* @package Rad\Core\Pattern
*/
trait SingletonTrait
{
protected static $instance;
/**
* Get instance
*
* @return static
*/
final public static function getInstance()
{
if (!self::$instance) {
self::$instance = new static;
}
return self::$instance;
}
/**
* Constructor
*/
final private function __construct()
{
$this->init();
}
/**
* Init method for call in constructor
*/
protected function init()
{
}
/**
* Ignore magic clone
*/
final private function __clone()
{
}
/**
* Ignore sleep magic method
*/
final private function __sleep()
{
}
/**
* Ignore wakeup magic method
*/
final private function __wakeup()
{
}
}
| radphp/radphp | src/Core/SingletonTrait.php | PHP | mit | 892 |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package s2
// Shape interface enforcement
var (
_ Shape = (*PointVector)(nil)
)
// PointVector is a Shape representing a set of Points. Each point
// is represented as a degenerate edge with the same starting and ending
// vertices.
//
// This type is useful for adding a collection of points to an ShapeIndex.
//
// Its methods are on *PointVector due to implementation details of ShapeIndex.
type PointVector []Point
func (p *PointVector) NumEdges() int { return len(*p) }
func (p *PointVector) Edge(i int) Edge { return Edge{(*p)[i], (*p)[i]} }
func (p *PointVector) ReferencePoint() ReferencePoint { return OriginReferencePoint(false) }
func (p *PointVector) NumChains() int { return len(*p) }
func (p *PointVector) Chain(i int) Chain { return Chain{i, 1} }
func (p *PointVector) ChainEdge(i, j int) Edge { return Edge{(*p)[i], (*p)[j]} }
func (p *PointVector) ChainPosition(e int) ChainPosition { return ChainPosition{e, 0} }
func (p *PointVector) Dimension() int { return 0 }
func (p *PointVector) IsEmpty() bool { return defaultShapeIsEmpty(p) }
func (p *PointVector) IsFull() bool { return defaultShapeIsFull(p) }
func (p *PointVector) typeTag() typeTag { return typeTagPointVector }
func (p *PointVector) privateInterface() {}
| FrontierRobotics/pathfinder | vendor/github.com/golang/geo/s2/point_vector.go | GO | mit | 2,029 |
<?php
/**
* This file is part of the Zephir.
*
* (c) Phalcon Team <team@zephir-lang.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Zephir\Statements\Let;
use Zephir\ClassProperty;
use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Exception;
use Zephir\Exception\CompilerException;
use Zephir\Expression;
/**
* Zephir\Statements\Let\StaticPropertyArrayIndex.
*
* Updates object properties dynamically.
*/
class StaticPropertyArrayIndex extends ArrayIndex
{
/**
* Compiles ClassName::foo[index] = {expr}.
*
* @param string $className
* @param string $property
* @param CompiledExpression $resolvedExpr
* @param CompilationContext $compilationContext
* @param array $statement
*
* @throws Exception
* @throws CompilerException
*/
public function assignStatic(
$className,
$property,
CompiledExpression $resolvedExpr,
CompilationContext $compilationContext,
array $statement
) {
$compiler = $compilationContext->compiler;
if (!\in_array($className, ['self', 'static', 'parent'])) {
$className = $compilationContext->getFullName($className);
if ($compiler->isClass($className)) {
$classDefinition = $compiler->getClassDefinition($className);
} else {
if ($compiler->isBundledClass($className)) {
$classDefinition = $compiler->getInternalClassDefinition($className);
} else {
throw new CompilerException("Cannot locate class '".$className."'", $statement);
}
}
} else {
if (\in_array($className, ['self', 'static'])) {
$classDefinition = $compilationContext->classDefinition;
} else {
if ('parent' == $className) {
$classDefinition = $compilationContext->classDefinition;
$extendsClass = $classDefinition->getExtendsClass();
if (!$extendsClass) {
throw new CompilerException('Cannot assign static property "'.$property.'" on parent because class '.$classDefinition->getCompleteName().' does not extend any class', $statement);
} else {
$classDefinition = $classDefinition->getExtendsClassDefinition();
}
}
}
}
if (!$classDefinition->hasProperty($property)) {
throw new CompilerException("Class '".$classDefinition->getCompleteName()."' does not have a property called: '".$property."'", $statement);
}
/** @var ClassProperty $propertyDefinition */
$propertyDefinition = $classDefinition->getProperty($property);
if (!$propertyDefinition->isStatic()) {
throw new CompilerException("Cannot access non-static property '".$classDefinition->getCompleteName().'::'.$property."'", $statement);
}
if ($propertyDefinition->isPrivate()) {
if ($classDefinition != $compilationContext->classDefinition) {
throw new CompilerException("Cannot access private static property '".$classDefinition->getCompleteName().'::'.$property."' out of its declaring context", $statement);
}
}
$compilationContext->headersManager->add('kernel/object');
$classEntry = $classDefinition->getClassEntry($compilationContext);
$this->_assignStaticPropertyArrayMultipleIndex($classEntry, $property, $resolvedExpr, $compilationContext, $statement);
}
/**
* Compiles x::y[a][b] = {expr} (multiple offset assignment).
*
* @param string $classEntry
* @param string $property
* @param CompiledExpression $resolvedExpr
* @param CompilationContext $compilationContext,
* @param array $statement
*
* @throws Exception
* @throws CompilerException
*/
protected function _assignStaticPropertyArrayMultipleIndex(
$classEntry,
$property,
CompiledExpression $resolvedExpr,
CompilationContext $compilationContext,
$statement
) {
$property = $statement['property'];
$compilationContext->headersManager->add('kernel/object');
/**
* Create a temporal zval (if needed).
*/
$variableExpr = $this->_getResolvedArrayItem($resolvedExpr, $compilationContext);
/**
* Only string/variable/int.
*/
$offsetExpressions = [];
foreach ($statement['index-expr'] as $indexExpr) {
$indexExpression = new Expression($indexExpr);
$resolvedIndex = $indexExpression->compile($compilationContext);
switch ($resolvedIndex->getType()) {
case 'string':
case 'int':
case 'uint':
case 'ulong':
case 'long':
case 'variable':
break;
default:
throw new CompilerException(
sprintf('Expression: %s cannot be used as index without cast', $resolvedIndex->getType()),
$statement['index-expr']
);
}
$offsetExpressions[] = $resolvedIndex;
}
$compilationContext->backend->assignStaticPropertyArrayMulti(
$classEntry,
$variableExpr,
$property,
$offsetExpressions,
$compilationContext
);
if ($variableExpr->isTemporal()) {
$variableExpr->setIdle(true);
}
}
}
| phalcon/zephir | Library/Statements/Let/StaticPropertyArrayIndex.php | PHP | mit | 5,855 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.azure.eventprocessorhost;
import java.util.ArrayList;
import java.util.concurrent.ScheduledExecutorService;
import com.microsoft.azure.eventhubs.AzureActiveDirectoryTokenProvider;
public class PerTestSettings {
// In-out properties: may be set before test setup and then changed by setup.
final EPHConstructorArgs inoutEPHConstructorArgs;
// Output properties: any value set before test setup is ignored. The real value is
// established during test setup.
RealEventHubUtilities outUtils;
String outTelltale;
ArrayList<String> outPartitionIds;
PrefabGeneralErrorHandler outGeneralErrorHandler;
PrefabProcessorFactory outProcessorFactory;
EventProcessorHost outHost;
// Properties which are inputs to test setup. Constructor sets up defaults, except for hostName.
private String inDefaultHostName;
EventProcessorOptions inOptions; // can be null
PrefabEventProcessor.CheckpointChoices inDoCheckpoint;
boolean inEventHubDoesNotExist; // Prevents test code from doing certain checks that would fail on nonexistence before reaching product code.
boolean inSkipIfNoEventHubConnectionString; // Requires valid connection string even though event hub may not exist.
boolean inTelltaleOnTimeout; // Generates an empty telltale string, which causes PrefabEventProcessor to trigger telltale on timeout.
boolean inHasSenders;
PerTestSettings(String defaultHostName) {
this.inDefaultHostName = defaultHostName;
this.inOptions = EventProcessorOptions.getDefaultOptions();
this.inDoCheckpoint = PrefabEventProcessor.CheckpointChoices.CKP_NONE;
this.inEventHubDoesNotExist = false;
this.inSkipIfNoEventHubConnectionString = false;
this.inTelltaleOnTimeout = false;
this.inHasSenders = true;
this.inoutEPHConstructorArgs = new EPHConstructorArgs();
}
String getDefaultHostName() {
return this.inDefaultHostName;
}
class EPHConstructorArgs {
static final int HOST_OVERRIDE = 0x0001;
static final int EH_PATH_OVERRIDE = 0x0002;
static final int EH_PATH_REPLACE_IN_CONNECTION = 0x0004;
static final int EH_PATH_OVERRIDE_AND_REPLACE = EH_PATH_OVERRIDE | EH_PATH_REPLACE_IN_CONNECTION;
static final int CONSUMER_GROUP_OVERRIDE = 0x0008;
static final int EH_CONNECTION_OVERRIDE = 0x0010;
static final int EH_CONNECTION_REMOVE_PATH = 0x0020;
static final int STORAGE_CONNECTION_OVERRIDE = 0x0040;
static final int STORAGE_CONTAINER_OVERRIDE = 0x0080;
static final int STORAGE_BLOB_PREFIX_OVERRIDE = 0x0100;
static final int EXECUTOR_OVERRIDE = 0x0200;
static final int CHECKPOINT_MANAGER_OVERRIDE = 0x0400;
static final int LEASE_MANAGER_OVERRIDE = 0x0800;
static final int EXPLICIT_MANAGER = CHECKPOINT_MANAGER_OVERRIDE | LEASE_MANAGER_OVERRIDE;
static final int TELLTALE_ON_TIMEOUT = 0x1000;
static final int AUTH_CALLBACK = 0x2000;
private int flags;
private String hostName;
private String ehPath;
private String consumerGroupName;
private String ehConnection;
private AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback;
private String authAuthority;
private String storageConnection;
private String storageContainerName;
private String storageBlobPrefix;
private ScheduledExecutorService executor;
private ICheckpointManager checkpointManager;
private ILeaseManager leaseManager;
EPHConstructorArgs() {
this.flags = 0;
this.hostName = null;
this.ehPath = null;
this.consumerGroupName = null;
this.ehConnection = null;
this.authCallback = null;
this.authAuthority = null;
this.storageConnection = null;
this.storageContainerName = null;
this.storageBlobPrefix = null;
this.executor = null;
this.checkpointManager = null;
this.leaseManager = null;
}
int getFlags() {
return this.flags;
}
boolean isFlagSet(int testFlag) {
return ((this.flags & testFlag) != 0);
}
String getHostName() {
return this.hostName;
}
void setHostName(String hostName) {
this.hostName = hostName;
this.flags |= HOST_OVERRIDE;
}
void setEHPath(String ehPath, int flags) {
this.ehPath = ehPath;
this.flags |= (flags & EH_PATH_OVERRIDE_AND_REPLACE);
}
String getEHPath() {
return this.ehPath;
}
String getConsumerGroupName() {
return this.consumerGroupName;
}
void setConsumerGroupName(String consumerGroupName) {
this.consumerGroupName = consumerGroupName;
this.flags |= CONSUMER_GROUP_OVERRIDE;
}
void removePathFromEHConnection() {
this.flags |= EH_CONNECTION_REMOVE_PATH;
}
String getEHConnection() {
return this.ehConnection;
}
void setEHConnection(String ehConnection) {
this.ehConnection = ehConnection;
this.flags |= EH_CONNECTION_OVERRIDE;
}
AzureActiveDirectoryTokenProvider.AuthenticationCallback getAuthCallback() {
return this.authCallback;
}
String getAuthAuthority() {
return this.authAuthority;
}
void setAuthCallback(AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback, String authAuthority) {
this.authCallback = authCallback;
this.authAuthority = authAuthority;
this.flags |= AUTH_CALLBACK;
}
String getStorageConnection() {
return this.storageConnection;
}
void setStorageConnection(String storageConnection) {
this.storageConnection = storageConnection;
this.flags |= STORAGE_CONNECTION_OVERRIDE;
}
void dummyStorageConnection() {
setStorageConnection("DefaultEndpointsProtocol=https;AccountName=doesnotexist;AccountKey=dGhpcyBpcyBub3QgYSB2YWxpZCBrZXkgYnV0IGl0IGRvZXMgaGF2ZSA2MCBjaGFyYWN0ZXJzLjEyMzQ1Njc4OTAK;EndpointSuffix=core.windows.net");
}
void setDefaultStorageContainerName(String defaultStorageContainerName) {
this.storageContainerName = defaultStorageContainerName;
}
String getStorageContainerName() {
return this.storageContainerName;
}
void setStorageContainerName(String storageContainerName) {
this.storageContainerName = storageContainerName;
this.flags |= STORAGE_CONTAINER_OVERRIDE;
}
String getStorageBlobPrefix() {
return this.storageBlobPrefix;
}
void setStorageBlobPrefix(String storageBlobPrefix) {
this.storageBlobPrefix = storageBlobPrefix;
this.flags |= STORAGE_BLOB_PREFIX_OVERRIDE;
}
ScheduledExecutorService getExecutor() {
return this.executor;
}
void setExecutor(ScheduledExecutorService executor) {
this.executor = executor;
this.flags |= EXECUTOR_OVERRIDE;
}
boolean useExplicitManagers() {
return ((this.flags & EXPLICIT_MANAGER) != 0);
}
void setCheckpointManager(ICheckpointManager checkpointManager) {
this.checkpointManager = checkpointManager;
this.flags |= CHECKPOINT_MANAGER_OVERRIDE;
}
ICheckpointManager getCheckpointMananger() {
return this.checkpointManager;
}
ILeaseManager getLeaseManager() {
return this.leaseManager;
}
void setLeaseManager(ILeaseManager leaseManager) {
this.leaseManager = leaseManager;
this.flags |= LEASE_MANAGER_OVERRIDE;
}
}
}
| Azure/azure-sdk-for-java | sdk/eventhubs/microsoft-azure-eventhubs-eph/src/test/java/com/microsoft/azure/eventprocessorhost/PerTestSettings.java | Java | mit | 8,213 |
using UnityEngine;
using System.Collections;
namespace RootMotion.Demos {
/// <summary>
/// Contols animation for a third person person controller.
/// </summary>
[RequireComponent(typeof(Animator))]
public class CharacterAnimationThirdPerson: CharacterAnimationBase {
public CharacterThirdPerson characterController;
[SerializeField] float turnSensitivity = 0.2f; // Animator turning sensitivity
[SerializeField] float turnSpeed = 5f; // Animator turning interpolation speed
[SerializeField] float runCycleLegOffset = 0.2f; // The offset of leg positions in the running cycle
[Range(0.1f,3f)] [SerializeField] float animSpeedMultiplier = 1; // How much the animation of the character will be multiplied by
protected Animator animator;
private Vector3 lastForward;
private const string groundedDirectional = "Grounded Directional", groundedStrafe = "Grounded Strafe";
protected override void Start() {
base.Start();
animator = GetComponent<Animator>();
lastForward = transform.forward;
}
public override Vector3 GetPivotPoint() {
return animator.pivotPosition;
}
// Is the Animator playing the grounded animations?
public override bool animationGrounded {
get {
return animator.GetCurrentAnimatorStateInfo(0).IsName(groundedDirectional) || animator.GetCurrentAnimatorStateInfo(0).IsName(groundedStrafe);
}
}
// Update the Animator with the current state of the character controller
protected virtual void Update() {
if (Time.deltaTime == 0f) return;
// Jumping
if (characterController.animState.jump) {
float runCycle = Mathf.Repeat (animator.GetCurrentAnimatorStateInfo (0).normalizedTime + runCycleLegOffset, 1);
float jumpLeg = (runCycle < 0 ? 1 : -1) * characterController.animState.moveDirection.z;
animator.SetFloat ("JumpLeg", jumpLeg);
}
// Calculate the angular delta in character rotation
float angle = -GetAngleFromForward(lastForward);
lastForward = transform.forward;
angle *= turnSensitivity * 0.01f;
angle = Mathf.Clamp(angle / Time.deltaTime, -1f, 1f);
// Update Animator params
animator.SetFloat("Turn", Mathf.Lerp(animator.GetFloat("Turn"), angle, Time.deltaTime * turnSpeed));
animator.SetFloat("Forward", characterController.animState.moveDirection.z);
animator.SetFloat("Right", characterController.animState.moveDirection.x);
animator.SetBool("Crouch", characterController.animState.crouch);
animator.SetBool("OnGround", characterController.animState.onGround);
animator.SetBool("IsStrafing", characterController.animState.isStrafing);
if (!characterController.animState.onGround) {
animator.SetFloat ("Jump", characterController.animState.yVelocity);
}
// the anim speed multiplier allows the overall speed of walking/running to be tweaked in the inspector
if (characterController.animState.onGround && characterController.animState.moveDirection.z > 0f) {
animator.speed = animSpeedMultiplier;
} else {
// but we don't want to use that while airborne
animator.speed = 1;
}
}
// Call OnAnimatorMove manually on the character controller because it doesn't have the Animator component
void OnAnimatorMove() {
characterController.Move(animator.deltaPosition);
}
}
}
| mbottone/uga_hacks_2015 | UGA Hacks 2015/Assets/Plugins/RootMotion/Shared Demo Assets/Scripts/Character Controllers/CharacterAnimationThirdPerson.cs | C# | mit | 3,306 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ContentObserver } from '@angular/cdk/observers';
import { ElementRef, NgZone, OnDestroy, Provider } from '@angular/core';
/** Possible politeness levels. */
export declare type AriaLivePoliteness = 'off' | 'polite' | 'assertive';
export declare class LiveAnnouncer implements OnDestroy {
private readonly _liveElement;
private _document;
constructor(elementToken: any, _document: any);
/**
* Announces a message to screenreaders.
* @param message Message to be announced to the screenreader
* @param politeness The politeness of the announcer element
* @returns Promise that will be resolved when the message is added to the DOM.
*/
announce(message: string, politeness?: AriaLivePoliteness): Promise<void>;
ngOnDestroy(): void;
private _createLiveElement();
}
/**
* A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility
* with a wider range of browsers and screen readers.
*/
export declare class CdkAriaLive implements OnDestroy {
private _elementRef;
private _liveAnnouncer;
private _contentObserver;
private _ngZone;
/** The aria-live politeness level to use when announcing messages. */
politeness: AriaLivePoliteness;
private _politeness;
private _subscription;
constructor(_elementRef: ElementRef, _liveAnnouncer: LiveAnnouncer, _contentObserver: ContentObserver, _ngZone: NgZone);
ngOnDestroy(): void;
}
/** @docs-private @deprecated @breaking-change 7.0.0 */
export declare function LIVE_ANNOUNCER_PROVIDER_FACTORY(parentDispatcher: LiveAnnouncer, liveElement: any, _document: any): LiveAnnouncer;
/** @docs-private @deprecated @breaking-change 7.0.0 */
export declare const LIVE_ANNOUNCER_PROVIDER: Provider;
| friendsofagape/mt2414ui | node_modules/@angular/cdk/typings/esm5/a11y/live-announcer/live-announcer.d.ts | TypeScript | mit | 1,970 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_CatalogIndex
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Catalog indexer price processor
*
* @method Mage_CatalogIndex_Model_Resource_Indexer_Price _getResource()
* @method Mage_CatalogIndex_Model_Resource_Indexer_Price getResource()
* @method Mage_CatalogIndex_Model_Indexer_Price setEntityId(int $value)
* @method int getCustomerGroupId()
* @method Mage_CatalogIndex_Model_Indexer_Price setCustomerGroupId(int $value)
* @method int getWebsiteId()
* @method Mage_CatalogIndex_Model_Indexer_Price setWebsiteId(int $value)
* @method int getTaxClassId()
* @method Mage_CatalogIndex_Model_Indexer_Price setTaxClassId(int $value)
* @method float getPrice()
* @method Mage_CatalogIndex_Model_Indexer_Price setPrice(float $value)
* @method float getFinalPrice()
* @method Mage_CatalogIndex_Model_Indexer_Price setFinalPrice(float $value)
* @method float getMinPrice()
* @method Mage_CatalogIndex_Model_Indexer_Price setMinPrice(float $value)
* @method float getMaxPrice()
* @method Mage_CatalogIndex_Model_Indexer_Price setMaxPrice(float $value)
* @method float getTierPrice()
* @method Mage_CatalogIndex_Model_Indexer_Price setTierPrice(float $value)
*
* @category Mage
* @package Mage_CatalogIndex
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_CatalogIndex_Model_Indexer_Price extends Mage_CatalogIndex_Model_Indexer_Abstract
{
protected $_customerGroups = array();
protected $_processChildrenForConfigurable = false;
protected function _construct()
{
$this->_init('catalogindex/indexer_price');
$this->_customerGroups = Mage::getModel('customer/group')->getCollection();
}
public function createIndexData(Mage_Catalog_Model_Product $object, Mage_Eav_Model_Entity_Attribute_Abstract $attribute = null)
{
$data = array();
$data['store_id'] = $attribute->getStoreId();
$data['entity_id'] = $object->getId();
$data['attribute_id'] = $attribute->getId();
$data['value'] = $object->getData($attribute->getAttributeCode());
if ($attribute->getAttributeCode() == 'price') {
$result = array();
foreach ($this->_customerGroups as $group) {
$object->setCustomerGroupId($group->getId());
$finalPrice = $object->getFinalPrice();
$row = $data;
$row['customer_group_id'] = $group->getId();
$row['value'] = $finalPrice;
$result[] = $row;
}
return $result;
}
return $data;
}
protected function _isAttributeIndexable(Mage_Eav_Model_Entity_Attribute_Abstract $attribute)
{
if ($attribute->getFrontendInput() != 'price') {
return false;
}
if ($attribute->getAttributeCode() == 'tier_price') {
return false;
}
if ($attribute->getAttributeCode() == 'minimal_price') {
return false;
}
return true;
}
protected function _getIndexableAttributeConditions()
{
$conditions = "frontend_input = 'price' AND attribute_code <> 'price'";
return $conditions;
}
}
| fabiensebban/magento | app/code/core/Mage/CatalogIndex/Model/Indexer/Price.php | PHP | mit | 4,100 |
class Riemann::MetricThread
# A metric thread is simple: it wraps some metric object which responds to <<,
# and every interval seconds, calls #flush which replaces the object and calls
# a user specified function.
INTERVAL = 10
attr_accessor :interval
attr_accessor :metric
# client = Riemann::Client.new
# m = MetricThread.new Mtrc::Rate do |rate|
# client << rate
# end
#
# loop do
# sleep rand
# m << rand
# end
def initialize(klass, *klass_args, &f)
@klass = klass
@klass_args = klass_args
@f = f
@interval = INTERVAL
@metric = new_metric
start
end
def <<(*a)
@metric.<<(*a)
end
def new_metric
@klass.new *@klass_args
end
def flush
old, @metric = @metric, new_metric
@f[old]
end
def start
raise RuntimeError, "already running" if @runner
@running = true
@runner = Thread.new do
while @running
sleep @interval
begin
flush
rescue Exception => e
end
end
@runner = nil
end
end
def stop
stop!
@runner.join
end
def stop!
@running = false
end
end
| riemann/riemann-ruby-client | lib/riemann/metric_thread.rb | Ruby | mit | 1,154 |
semantic.dropdown = {};
// ready event
semantic.dropdown.ready = function() {
// selector cache
var
// alias
handler
;
// event handlers
handler = {
};
$('.first.example .menu .item')
.tab({
context: '.first.example'
})
;
$('.history.example .menu .item')
.tab({
context : '.history.example',
history : true,
path : '/modules/tab.html'
})
;
$('.dynamic.example .menu .item')
.tab({
context : '.dynamic.example',
auto : true,
path : '/modules/tab.html'
})
;
};
// attach ready event
$(document)
.ready(semantic.dropdown.ready)
; | taylorrose/taylorrose.github.io | blog/js/tab.js | JavaScript | mit | 690 |
#! /usr/bin/env python
"""
This is an example that demonstrates how to use an
RGB led with BreakfastSerial. It assumes you have an
RGB led wired up with red on pin 10, green on pin 9,
and blue on pin 8.
"""
from BreakfastSerial import RGBLed, Arduino
from time import sleep
board = Arduino()
led = RGBLed(board, { "red": 10, "green": 9, "blue": 8 })
# Red (R: on, G: off, B: off)
led.red()
sleep(1)
# Green (R: off, G: on, B: off)
led.green()
sleep(1)
# Blue (R: off, G: off, B: on)
led.blue()
sleep(1)
# Yellow (R: on, G: on, B: off)
led.yellow()
sleep(1)
# Cyan (R: off, G: on, B: on)
led.cyan()
sleep(1)
# Purple (R: on, G: off, B: on)
led.purple()
sleep(1)
# White (R: on, G: on, B: on)
led.white()
sleep(1)
# Off (R: off, G: off, B: off)
led.off()
# Run an interactive shell so you can play (not required)
import code
code.InteractiveConsole(locals=globals()).interact()
| andyclymer/ControlBoard | lib/modules/BreakfastSerial/examples/rgb_led.py | Python | mit | 887 |
/**
* Why has this not been moved to e.g. @tryghost/events or shared yet?
*
* - We currently massively overuse this utility, coupling together bits of the codebase in unexpected ways
* - We want to prevent this, not reinforce it
* * Having an @tryghost/events or shared/events module would reinforce this bad patter of using the same event emitter everywhere
*
* - Ideally, we want to refactor to:
* - either remove dependence on events where we can
* - or have separate event emitters for e.g. model layer and routing layer
*
*/
const events = require('events');
const util = require('util');
let EventRegistry;
let EventRegistryInstance;
EventRegistry = function () {
events.EventEmitter.call(this);
};
util.inherits(EventRegistry, events.EventEmitter);
EventRegistryInstance = new EventRegistry();
EventRegistryInstance.setMaxListeners(100);
module.exports = EventRegistryInstance;
| janvt/Ghost | core/server/lib/common/events.js | JavaScript | mit | 911 |
<?php
namespace AerialShip\SamlSPBundle\Tests\Bridge;
use AerialShip\LightSaml\Model\Assertion\Attribute;
use AerialShip\LightSaml\Model\Assertion\AuthnStatement;
use AerialShip\LightSaml\Model\Assertion\NameID;
use AerialShip\SamlSPBundle\Bridge\SamlSpInfo;
class SamlSpInfoHelper
{
/**
* @param string $nameIDValue
* @param string $nameIDFormat
* @return NameID
*/
public function getNameID(
$nameIDValue = 'nameID',
$nameIDFormat = 'nameIDFormat'
)
{
$nameID = new NameID();
$nameID->setValue($nameIDValue);
$nameID->setFormat($nameIDFormat);
return $nameID;
}
/**
* @param Attribute[] $attributes
* @return array
*/
public function getAttributes(array $attributes = array('a'=>1, 'b'=>array(2,3)))
{
$arrAttributes = array();
foreach ($attributes as $name=>$value) {
$a = new Attribute();
$a->setName($name);
if (!is_array($value)) {
$value = array($value);
}
$a->setValues($value);
$arrAttributes[] = $a;
}
return $arrAttributes;
}
/**
* @param string $sessionIndex
* @return AuthnStatement
*/
public function getAuthnStatement($sessionIndex = 'session_index')
{
$authnStatement = new AuthnStatement();
$authnStatement->setSessionIndex($sessionIndex);
return $authnStatement;
}
/**
* @param string $nameIDValue
* @param string $nameIDFormat
* @param array $attributes
* @param string $sessionIndex
* @return SamlSpInfo
*/
public function getSamlSpInfo(
$nameIDValue = 'nameID',
$nameIDFormat = 'nameIDFormat',
array $attributes = array('a'=>1, 'b'=>array(2,3)),
$sessionIndex = 'session_index'
) {
$nameID = $this->getNameID($nameIDValue, $nameIDFormat);
$arrAttributes = $this->getAttributes($attributes);
$authnStatement = $this->getAuthnStatement($sessionIndex);
$result = new SamlSpInfo('authServiceID', $nameID, $arrAttributes, $authnStatement);
return $result;
}
} | stof/SamlSPBundle | src/AerialShip/SamlSPBundle/Tests/Bridge/SamlSpInfoHelper.php | PHP | mit | 2,206 |
package org.beansugar.oauth.o10a.builder.api;
import org.beansugar.oauth.o10a.model.Token10a;
public class FlickrApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "https://www.flickr.com/services/oauth/authorize?oauth_token=%s";
private static final String REQUEST_TOKEN_RESOURCE = "https://www.flickr.com/services/oauth/request_token";
private static final String ACCESS_TOKEN_RESOURCE = "https://www.flickr.com/services/oauth/access_token";
@Override
public String getAuthorizationUrl(Token10a requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
@Override
public String getRequestTokenUrl() {
return REQUEST_TOKEN_RESOURCE;
}
@Override
public String getAccessTokenUrl() {
return ACCESS_TOKEN_RESOURCE;
}
}
| archmagece/bs-oauth-java | src/main/java/org/beansugar/oauth/o10a/builder/api/FlickrApi.java | Java | mit | 781 |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: org.apache.http.protocol.HttpRequestExecutor
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_DECL
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpResponse; } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpRequest; } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpClientConnection; } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace protocol { class HttpProcessor; } } } } }
namespace j2cpp { namespace org { namespace apache { namespace http { namespace protocol { class HttpContext; } } } } }
namespace j2cpp { namespace java { namespace lang { class Object; } } }
#include <java/lang/Object.hpp>
#include <org/apache/http/HttpClientConnection.hpp>
#include <org/apache/http/HttpRequest.hpp>
#include <org/apache/http/HttpResponse.hpp>
#include <org/apache/http/protocol/HttpContext.hpp>
#include <org/apache/http/protocol/HttpProcessor.hpp>
namespace j2cpp {
namespace org { namespace apache { namespace http { namespace protocol {
class HttpRequestExecutor;
class HttpRequestExecutor
: public object<HttpRequestExecutor>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
explicit HttpRequestExecutor(jobject jobj)
: object<HttpRequestExecutor>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
HttpRequestExecutor();
local_ref< org::apache::http::HttpResponse > execute(local_ref< org::apache::http::HttpRequest > const&, local_ref< org::apache::http::HttpClientConnection > const&, local_ref< org::apache::http::protocol::HttpContext > const&);
void preProcess(local_ref< org::apache::http::HttpRequest > const&, local_ref< org::apache::http::protocol::HttpProcessor > const&, local_ref< org::apache::http::protocol::HttpContext > const&);
void postProcess(local_ref< org::apache::http::HttpResponse > const&, local_ref< org::apache::http::protocol::HttpProcessor > const&, local_ref< org::apache::http::protocol::HttpContext > const&);
}; //class HttpRequestExecutor
} //namespace protocol
} //namespace http
} //namespace apache
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_IMPL
namespace j2cpp {
org::apache::http::protocol::HttpRequestExecutor::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
org::apache::http::protocol::HttpRequestExecutor::HttpRequestExecutor()
: object<org::apache::http::protocol::HttpRequestExecutor>(
call_new_object<
org::apache::http::protocol::HttpRequestExecutor::J2CPP_CLASS_NAME,
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_NAME(0),
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
local_ref< org::apache::http::HttpResponse > org::apache::http::protocol::HttpRequestExecutor::execute(local_ref< org::apache::http::HttpRequest > const &a0, local_ref< org::apache::http::HttpClientConnection > const &a1, local_ref< org::apache::http::protocol::HttpContext > const &a2)
{
return call_method<
org::apache::http::protocol::HttpRequestExecutor::J2CPP_CLASS_NAME,
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_NAME(2),
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_SIGNATURE(2),
local_ref< org::apache::http::HttpResponse >
>(get_jobject(), a0, a1, a2);
}
void org::apache::http::protocol::HttpRequestExecutor::preProcess(local_ref< org::apache::http::HttpRequest > const &a0, local_ref< org::apache::http::protocol::HttpProcessor > const &a1, local_ref< org::apache::http::protocol::HttpContext > const &a2)
{
return call_method<
org::apache::http::protocol::HttpRequestExecutor::J2CPP_CLASS_NAME,
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_NAME(3),
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_SIGNATURE(3),
void
>(get_jobject(), a0, a1, a2);
}
void org::apache::http::protocol::HttpRequestExecutor::postProcess(local_ref< org::apache::http::HttpResponse > const &a0, local_ref< org::apache::http::protocol::HttpProcessor > const &a1, local_ref< org::apache::http::protocol::HttpContext > const &a2)
{
return call_method<
org::apache::http::protocol::HttpRequestExecutor::J2CPP_CLASS_NAME,
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_NAME(6),
org::apache::http::protocol::HttpRequestExecutor::J2CPP_METHOD_SIGNATURE(6),
void
>(get_jobject(), a0, a1, a2);
}
J2CPP_DEFINE_CLASS(org::apache::http::protocol::HttpRequestExecutor,"org/apache/http/protocol/HttpRequestExecutor")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,1,"canResponseHaveBody","(Lorg/apache/http/HttpRequest;Lorg/apache/http/HttpResponse;)Z")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,2,"execute","(Lorg/apache/http/HttpRequest;Lorg/apache/http/HttpClientConnection;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/HttpResponse;")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,3,"preProcess","(Lorg/apache/http/HttpRequest;Lorg/apache/http/protocol/HttpProcessor;Lorg/apache/http/protocol/HttpContext;)V")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,4,"doSendRequest","(Lorg/apache/http/HttpRequest;Lorg/apache/http/HttpClientConnection;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/HttpResponse;")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,5,"doReceiveResponse","(Lorg/apache/http/HttpRequest;Lorg/apache/http/HttpClientConnection;Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/HttpResponse;")
J2CPP_DEFINE_METHOD(org::apache::http::protocol::HttpRequestExecutor,6,"postProcess","(Lorg/apache/http/HttpResponse;Lorg/apache/http/protocol/HttpProcessor;Lorg/apache/http/protocol/HttpContext;)V")
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_PROTOCOL_HTTPREQUESTEXECUTOR_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| hyEvans/ph-open | proj.android/jni/puzzleHero/platforms/android-8/org/apache/http/protocol/HttpRequestExecutor.hpp | C++ | mit | 6,953 |
package mineapi.furnace;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import mineapi.mod.ModLoader;
import net.minecraft.item.ItemStack;
public class FurnaceRecipeComponent
{
@Expose
@SerializedName("ItemName")
private String itemName;
@Expose
@SerializedName("ItemAmount")
private int itemAmount;
@Expose
@SerializedName("ParentModID")
private String parentModID;
@Expose
@SerializedName("MetaDamage")
private int metaDamage;
private boolean hasLoaded = false;
private ItemStack associatedItemStack = null;
FurnaceRecipeComponent(String parentModID, String internalName, int amount, int metaDamage)
{
super();
this.parentModID = parentModID;
this.itemName = internalName;
this.itemAmount = amount;
this.metaDamage = metaDamage;
}
public String getInternalName()
{
return this.itemName;
}
public int getAmount()
{
return this.itemAmount;
}
public String getNameWithModID()
{
return this.parentModID + ":" + this.itemName;
}
public int getMetaDamage()
{
return this.metaDamage;
}
public boolean isLoaded()
{
return this.hasLoaded;
}
public ItemStack getAssociatedItemStack()
{
if (! this.hasLoaded)
{
ModLoader.log().warning( "[FurnaceRecipeComponent]Cannot return associated itemstack for recipe since it was never loaded!" );
return null;
}
return this.associatedItemStack;
}
public void associateItemStackToRecipeComponent(ItemStack associatedItemStack)
{
// Prevent double-loading!
if (hasLoaded)
{
ModLoader.log().warning( "[FurnaceRecipeComponent]Already loaded and verified this recipe with GameRegistry!" );
return;
}
if (this.associatedItemStack != null)
{
ModLoader.log().warning( "[FurnaceRecipeComponent]Associated item stack is not null! How can this be?!" );
return;
}
// Make sure this cannot happen twice.
hasLoaded = true;
// Take a copy of the inputed parameter item for future reference.
this.associatedItemStack = associatedItemStack;
}
public String getModID()
{
return this.parentModID;
}
}
| Maxwolf/MineAPI.Java | src/main/java/mineapi/furnace/FurnaceRecipeComponent.java | Java | mit | 2,428 |
import ResourceProcessorBase from './resource-processor-base';
class ManifestProcessor extends ResourceProcessorBase {
processResource (manifest, ctx, charset, urlReplacer) {
var lines = manifest.split('\n');
for (var i = 0; i < lines.length; i++) {
var line = lines[i].trim();
if (line && line !== 'CACHE MANIFEST' && line !== 'NETWORK:' && line !== 'FALLBACK:' &&
line !== 'CACHE:' && line[0] !== '#' && line !== '*') {
var isFallbackItem = line.indexOf(' ') !== -1;
if (isFallbackItem) {
var urls = line.split(' ');
lines[i] = urlReplacer(urls[0]) + ' ' + urlReplacer(urls[1]);
}
else
lines[i] = urlReplacer(line);
}
}
return lines.join('\n');
}
shouldProcessResource (ctx) {
return ctx.contentInfo.isManifest;
}
}
export default new ManifestProcessor();
| georgiy-abbasov/testcafe-hammerhead | src/processing/resources/manifest.js | JavaScript | mit | 1,000 |
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/587f9d9cb018514c03434ccc0fc53ffcad32e8b7/whatwg-fetch/whatwg-fetch.d.ts
// Type definitions for fetch API
// Project: https://github.com/github/fetch
// Definitions by: Ryan Graham <https://github.com/ryan-codingintrigue>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare class Request extends Body {
constructor(input: string|Request, init?:RequestInit);
method: string;
url: string;
headers: Headers;
context: RequestContext;
referrer: string;
mode: RequestMode;
redirect: RequestRedirect;
credentials: RequestCredentials;
cache: RequestCache;
}
interface RequestInit {
method?: string;
headers?: HeaderInit|{ [index: string]: string };
body?: BodyInit;
mode?: RequestMode;
redirect?: RequestRedirect;
credentials?: RequestCredentials;
cache?: RequestCache;
}
type RequestContext =
"audio" | "beacon" | "cspreport" | "download" | "embed" |
"eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" |
"hyperlink" | "iframe" | "image" | "imageset" | "import" |
"internal" | "location" | "manifest" | "object" | "ping" | "plugin" |
"prefetch" | "script" | "serviceworker" | "sharedworker" |
"subresource" | "style" | "track" | "video" | "worker" |
"xmlhttprequest" | "xslt";
type RequestMode = "same-origin" | "no-cors" | "cors";
type RequestRedirect = "follow" | "error" | "manual";
type RequestCredentials = "omit" | "same-origin" | "include";
type RequestCache =
"default" | "no-store" | "reload" | "no-cache" |
"force-cache" | "only-if-cached";
declare class Headers {
append(name: string, value: string): void;
delete(name: string):void;
get(name: string): string;
getAll(name: string): Array<string>;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(callback: (value: string, name: string) => void): void;
}
declare class Body {
bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
formData(): Promise<FormData>;
json(): Promise<any>;
json<T>(): Promise<T>;
text(): Promise<string>;
}
declare class Response extends Body {
constructor(body?: BodyInit, init?: ResponseInit);
static error(): Response;
static redirect(url: string, status: number): Response;
type: ResponseType;
url: string;
status: number;
ok: boolean;
statusText: string;
headers: Headers;
clone(): Response;
}
type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";
interface ResponseInit {
status: number;
statusText?: string;
headers?: HeaderInit;
}
declare type HeaderInit = Headers|Array<string>;
declare type BodyInit = ArrayBuffer|ArrayBufferView|Blob|FormData|string;
declare type RequestInfo = Request|string;
interface Window {
fetch(url: string|Request, init?: RequestInit): Promise<Response>;
}
declare var fetch: typeof window.fetch; | Giovannini/Timer | typings/browser/ambient/whatwg-fetch/index.d.ts | TypeScript | mit | 2,900 |
import re
import datetime
import dateutil.parser
from django.conf import settings
from django.utils import feedgenerator
from django.utils.html import linebreaks
from apps.social.models import MSocialServices
from apps.reader.models import UserSubscription
from utils import log as logging
from vendor.facebook import GraphAPIError
class FacebookFetcher:
def __init__(self, feed, options=None):
self.feed = feed
self.options = options or {}
def fetch(self):
page_name = self.extract_page_name()
if not page_name:
return
facebook_user = self.facebook_user()
if not facebook_user:
return
# If 'video', use video API to get embed:
# f.get_object('tastyvegetarian', fields='posts')
# f.get_object('1992797300790726', fields='embed_html')
feed = self.fetch_page_feed(facebook_user, page_name, 'name,about,posts,videos,photos')
data = {}
data['title'] = feed.get('name', "%s on Facebook" % page_name)
data['link'] = feed.get('link', "https://facebook.com/%s" % page_name)
data['description'] = feed.get('about', "%s on Facebook" % page_name)
data['lastBuildDate'] = datetime.datetime.utcnow()
data['generator'] = 'NewsBlur Facebook API Decrapifier - %s' % settings.NEWSBLUR_URL
data['docs'] = None
data['feed_url'] = self.feed.feed_address
rss = feedgenerator.Atom1Feed(**data)
merged_data = []
posts = feed.get('posts', {}).get('data', None)
if posts:
for post in posts:
story_data = self.page_posts_story(facebook_user, post)
if not story_data:
continue
merged_data.append(story_data)
videos = feed.get('videos', {}).get('data', None)
if videos:
for video in videos:
story_data = self.page_video_story(facebook_user, video)
if not story_data:
continue
for seen_data in merged_data:
if story_data['link'] == seen_data['link']:
# Video wins over posts (and attachments)
seen_data['description'] = story_data['description']
seen_data['title'] = story_data['title']
break
for story_data in merged_data:
rss.add_item(**story_data)
return rss.writeString('utf-8')
def extract_page_name(self):
page = None
try:
page_groups = re.search('facebook.com/(\w+)/?', self.feed.feed_address)
if not page_groups:
return
page = page_groups.group(1)
except IndexError:
return
return page
def facebook_user(self):
facebook_api = None
social_services = None
if self.options.get('requesting_user_id', None):
social_services = MSocialServices.get_user(self.options.get('requesting_user_id'))
facebook_api = social_services.facebook_api()
if not facebook_api:
logging.debug(u' ***> [%-30s] ~FRFacebook fetch failed: %s: No facebook API for %s' %
(self.feed.log_title[:30], self.feed.feed_address, self.options))
return
else:
usersubs = UserSubscription.objects.filter(feed=self.feed)
if not usersubs:
logging.debug(u' ***> [%-30s] ~FRFacebook fetch failed: %s: No subscriptions' %
(self.feed.log_title[:30], self.feed.feed_address))
return
for sub in usersubs:
social_services = MSocialServices.get_user(sub.user_id)
if not social_services.facebook_uid:
continue
facebook_api = social_services.facebook_api()
if not facebook_api:
continue
else:
break
if not facebook_api:
logging.debug(u' ***> [%-30s] ~FRFacebook fetch failed: %s: No facebook API for %s' %
(self.feed.log_title[:30], self.feed.feed_address, usersubs[0].user.username))
return
return facebook_api
def fetch_page_feed(self, facebook_user, page, fields):
try:
stories = facebook_user.get_object(page, fields=fields)
except GraphAPIError, e:
message = str(e).lower()
if 'session has expired' in message:
logging.debug(u' ***> [%-30s] ~FRFacebook page failed/expired, disconnecting facebook: %s: %s' %
(self.feed.log_title[:30], self.feed.feed_address, e))
self.feed.save_feed_history(560, "Facebook Error: Expired token")
return {}
if not stories:
return {}
return stories
def page_posts_story(self, facebook_user, page_story):
categories = set()
if 'message' not in page_story:
# Probably a story shared on the page's timeline, not a published story
return
message = linebreaks(page_story['message'])
created_date = page_story['created_time']
if isinstance(created_date, unicode):
created_date = dateutil.parser.parse(created_date)
fields = facebook_user.get_object(page_story['id'], fields='permalink_url,link,attachments')
permalink = fields.get('link', fields['permalink_url'])
attachments_html = ""
if fields.get('attachments', None) and fields['attachments']['data']:
for attachment in fields['attachments']['data']:
if 'media' in attachment:
attachments_html += "<img src=\"%s\" />" % attachment['media']['image']['src']
if attachment.get('subattachments', None):
for subattachment in attachment['subattachments']['data']:
attachments_html += "<img src=\"%s\" />" % subattachment['media']['image']['src']
content = """<div class="NB-facebook-rss">
<div class="NB-facebook-rss-message">%s</div>
<div class="NB-facebook-rss-picture">%s</div>
</div>""" % (
message,
attachments_html
)
story = {
'title': message,
'link': permalink,
'description': content,
'categories': list(categories),
'unique_id': "fb_post:%s" % page_story['id'],
'pubdate': created_date,
}
return story
def page_video_story(self, facebook_user, page_story):
categories = set()
if 'description' not in page_story:
return
message = linebreaks(page_story['description'])
created_date = page_story['updated_time']
if isinstance(created_date, unicode):
created_date = dateutil.parser.parse(created_date)
permalink = facebook_user.get_object(page_story['id'], fields='permalink_url')['permalink_url']
embed_html = facebook_user.get_object(page_story['id'], fields='embed_html')
if permalink.startswith('/'):
permalink = "https://www.facebook.com%s" % permalink
content = """<div class="NB-facebook-rss">
<div class="NB-facebook-rss-message">%s</div>
<div class="NB-facebook-rss-embed">%s</div>
</div>""" % (
message,
embed_html.get('embed_html', '')
)
story = {
'title': page_story.get('story', message),
'link': permalink,
'description': content,
'categories': list(categories),
'unique_id': "fb_post:%s" % page_story['id'],
'pubdate': created_date,
}
return story
def favicon_url(self):
page_name = self.extract_page_name()
facebook_user = self.facebook_user()
if not facebook_user:
logging.debug(u' ***> [%-30s] ~FRFacebook icon failed, disconnecting facebook: %s' %
(self.feed.log_title[:30], self.feed.feed_address))
return
try:
picture_data = facebook_user.get_object(page_name, fields='picture')
except GraphAPIError, e:
message = str(e).lower()
if 'session has expired' in message:
logging.debug(u' ***> [%-30s] ~FRFacebook icon failed/expired, disconnecting facebook: %s: %s' %
(self.feed.log_title[:30], self.feed.feed_address, e))
return
if 'picture' in picture_data:
return picture_data['picture']['data']['url']
| AlphaCluster/NewsBlur | utils/facebook_fetcher.py | Python | mit | 9,072 |
class EnrollmentValidator < DocumentValidator
POLICY_SCHEMA = File.join(Rails.root, 'cv', 'policy.xsd')
def initialize(xml)
schema = Nokogiri::XML::Schema(File.open(POLICY_SCHEMA))
xml_doc = Nokogiri::XML(xml)
super(xml_doc, schema)
end
end
| blackeaglejs/gluedb | lib/enrollment_validator.rb | Ruby | mit | 262 |
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Moq;
using NBitcoin;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Features.Consensus;
using Stratis.Bitcoin.Features.Consensus.CoinViews;
using Stratis.Bitcoin.Features.MemoryPool.Fee;
using Stratis.Bitcoin.Tests.Common;
using Stratis.Bitcoin.Utilities;
using Xunit;
namespace Stratis.Bitcoin.Features.MemoryPool.Tests
{
/// <summary>
/// Unit tests for memory pool manager.
/// </summary>
public class MempoolManagerTest
{
/// <summary>
/// Expiry time to use for test in hours.
/// </summary>
private const int MempoolExpiry = MempoolValidator.DefaultMempoolExpiry;
/// <summary>
/// Creates a mock MempoolManager class for testing tx expiry.
/// </summary>
private MempoolManager TxExpiryManager
{
get
{
IDateTimeProvider dateTime = new DateTimeProvider();
var mockLoggerFactory = new Mock<ILoggerFactory>();
mockLoggerFactory.Setup(i => i.CreateLogger(It.IsAny<string>())).Returns(new Mock<ILogger>().Object);
ILoggerFactory loggerFactory = mockLoggerFactory.Object;
var settings = new MempoolSettings(NodeSettings.Default(KnownNetworks.TestNet))
{
MempoolExpiry = MempoolExpiry
};
NodeSettings nodeSettings = NodeSettings.Default(KnownNetworks.TestNet);
var blockPolicyEstimator = new BlockPolicyEstimator(settings, loggerFactory, nodeSettings);
var mempool = new TxMempool(dateTime, blockPolicyEstimator, loggerFactory, nodeSettings);
var mockTxMempool = new Mock<TxMempool>();
var mockValidator = new Mock<IMempoolValidator>();
mockValidator.Setup(i =>
i.AcceptToMemoryPoolWithTime(It.IsAny<MempoolValidationState>(), It.IsAny<Transaction>()))
.ReturnsAsync((MempoolValidationState state, Transaction tx) =>
{
var consensusOptions = new ConsensusOptions();
mempool.MapTx.Add(new TxMempoolEntry(tx, Money.Zero, 0, 0, 0, Money.Zero, false, 0, null, consensusOptions));
return true;
}
);
var mockPersist = new Mock<IMempoolPersistence>();
var mockCoinView = new Mock<ICoinView>();
return new MempoolManager(new MempoolSchedulerLock(), mempool, mockValidator.Object, dateTime, settings, mockPersist.Object, mockCoinView.Object, loggerFactory, nodeSettings.Network);
}
}
[Fact]
public async Task AddMempoolEntriesToMempool_WithNull_ThrowsNoExceptionAsync()
{
MempoolManager manager = this.TxExpiryManager;
Assert.NotNull(manager);
await manager.AddMempoolEntriesToMempoolAsync(null);
}
[Fact]
public async Task AddMempoolEntriesToMempool_WithExpiredTx_PurgesTxAsync()
{
MempoolManager manager = this.TxExpiryManager;
Assert.NotNull(manager);
long expiryInSeconds = MempoolValidator.DefaultMempoolExpiry * 60 * 60;
// tx with expiry twice as long as default expiry
var txs = new List<MempoolPersistenceEntry>
{
new MempoolPersistenceEntry
{
Tx =new Transaction(),
Time = manager.DateTimeProvider.GetTime() - expiryInSeconds*2
}
};
await manager.AddMempoolEntriesToMempoolAsync(txs);
long entries = await manager.MempoolSize();
// Should not add it because it's expired
Assert.Equal(0L, entries);
}
[Fact]
public async Task AddMempoolEntriesToMempool_WithUnexpiredTx_AddsTxAsync()
{
MempoolManager manager = this.TxExpiryManager;
Assert.NotNull(manager);
long expiryInSeconds = MempoolValidator.DefaultMempoolExpiry * 60 * 60;
// tx with expiry half as long as default expiry
var txs = new List<MempoolPersistenceEntry>
{
new MempoolPersistenceEntry
{
Tx =new Transaction(),
Time = manager.DateTimeProvider.GetTime() - expiryInSeconds/2
}
};
await manager.AddMempoolEntriesToMempoolAsync(txs);
long entries = await manager.MempoolSize();
// Not expired so should have been added
Assert.Equal(1L, entries);
}
}
}
| mikedennis/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.MemoryPool.Tests/MempoolManagerTest.cs | C# | mit | 4,865 |
import io
import sys
isPython3 = sys.version_info >= (3, 0)
class Scribe:
@staticmethod
def read(path):
with io.open(path, mode="rt", encoding="utf-8") as f:
s = f.read()
# go to beginning
f.seek(0)
return s
@staticmethod
def read_beginning(path, lines):
with io.open(path, mode="rt", encoding="utf-8") as f:
s = f.read(lines)
# go to beginning
f.seek(0)
return s
@staticmethod
def read_lines(path):
with io.open(path, mode="rt", encoding="utf-8") as f:
content = f.readlines()
return content
@staticmethod
def write(contents, path):
if isPython3:
with open(path, mode="wt", encoding="utf-8") as f:
# truncate previous contents
f.truncate()
f.write(contents)
else:
with io.open(path, mode="wt", encoding="utf-8") as f:
# truncate previous contents
f.truncate()
f.write(contents.decode("utf8"))
@staticmethod
def write_lines(lines, path):
if isPython3:
with open(path, mode="wt", encoding="utf-8") as f:
f.writelines([l + "\n" for l in lines])
else:
with io.open(path, mode="wt") as f:
for line in lines:
f.writelines(line.decode("utf8") + "\n")
@staticmethod
def add_content(contents, path):
if isPython3:
with open(path, mode="a", encoding="utf-8") as f:
f.writelines(contents)
else:
with io.open(path, mode="a") as f:
f.writelines(contents.decode("utf8"))
| RobertoPrevato/Humbular | tools/knight/core/literature/scribe.py | Python | mit | 1,844 |
// Type definitions for tcp-ping 0.1
// Project: https://github.com/wesolyromek/tcp-ping
// Definitions by: JUNG YONG WOO <https://github.com/stegano>
// rymate1234 <https://github.com/rymate1234>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface Options {
address?: string;
port?: number;
attempts?: number;
timeout?: number;
}
export interface Results {
seq: number;
time: number | undefined;
err?: Error;
}
export interface Result {
address: string;
port: number;
attempts: number;
avg: number;
max: number;
min: number;
results: Results[];
}
export function ping(options: Options, callback: (error: Error, result: Result) => void): void;
export function probe(address: string, port: number, callback: (error: Error, result: boolean) => void): void;
| georgemarshall/DefinitelyTyped | types/tcp-ping/index.d.ts | TypeScript | mit | 863 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'fo', {
access: 'Script atgongd',
accessAlways: 'Altíð',
accessNever: 'Ongantíð',
accessSameDomain: 'Sama navnaøki',
alignAbsBottom: 'Abs botnur',
alignAbsMiddle: 'Abs miðja',
alignBaseline: 'Basislinja',
alignTextTop: 'Tekst toppur',
bgcolor: 'Bakgrundslitur',
chkFull: 'Loyv fullan skerm',
chkLoop: 'Endurspæl',
chkMenu: 'Ger Flash skrá virkna',
chkPlay: 'Avspælingin byrjar sjálv',
flashvars: 'Variablar fyri Flash',
hSpace: 'Høgri breddi',
properties: 'Flash eginleikar',
propertiesTab: 'Eginleikar',
quality: 'Góðska',
qualityAutoHigh: 'Auto høg',
qualityAutoLow: 'Auto Lág',
qualityBest: 'Besta',
qualityHigh: 'Høg',
qualityLow: 'Lág',
qualityMedium: 'Meðal',
scale: 'Skalering',
scaleAll: 'Vís alt',
scaleFit: 'Neyv skalering',
scaleNoBorder: 'Eingin bordi',
title: 'Flash eginleikar',
vSpace: 'Vinstri breddi',
validateHSpace: 'HSpace má vera eitt tal.',
validateSrc: 'Vinarliga skriva tilknýti (URL)',
validateVSpace: 'VSpace má vera eitt tal.',
windowMode: 'Slag av rúti',
windowModeOpaque: 'Ikki transparent',
windowModeTransparent: 'Transparent',
windowModeWindow: 'Rútur'
});
| chiave/gamp | public_html/ckeditor/plugins/flash/lang/fo.js | JavaScript | mit | 1,374 |
/**
* @ngdoc filter
* @name map
* @kind function
*
* @description
* Returns a new collection of the results of each expression execution.
*/
angular.module('a8m.map', [])
.filter('map', ['$parse', function($parse) {
return function (collection, expression) {
collection = (isObject(collection))
? toArray(collection)
: collection;
if(!isArray(collection) || isUndefined(expression)) {
return collection;
}
return collection.map(function (elm) {
return $parse(expression)(elm);
});
}
}]);
| mallowigi/angular-filter | src/_filter/collection/map.js | JavaScript | mit | 572 |
import { Type } from 'angular2/src/facade/lang';
import { SetterFn, GetterFn, MethodFn } from './types';
import { PlatformReflectionCapabilities } from './platform_reflection_capabilities';
export { SetterFn, GetterFn, MethodFn } from './types';
export { PlatformReflectionCapabilities } from './platform_reflection_capabilities';
/**
* Reflective information about a symbol, including annotations, interfaces, and other metadata.
*/
export declare class ReflectionInfo {
annotations: any[];
parameters: any[][];
factory: Function;
interfaces: any[];
propMetadata: {
[key: string]: any[];
};
constructor(annotations?: any[], parameters?: any[][], factory?: Function, interfaces?: any[], propMetadata?: {
[key: string]: any[];
});
}
/**
* Provides access to reflection data about symbols. Used internally by Angular
* to power dependency injection and compilation.
*/
export declare class Reflector {
reflectionCapabilities: PlatformReflectionCapabilities;
constructor(reflectionCapabilities: PlatformReflectionCapabilities);
isReflectionEnabled(): boolean;
/**
* Causes `this` reflector to track keys used to access
* {@link ReflectionInfo} objects.
*/
trackUsage(): void;
/**
* Lists types for which reflection information was not requested since
* {@link #trackUsage} was called. This list could later be audited as
* potential dead code.
*/
listUnusedKeys(): any[];
registerFunction(func: Function, funcInfo: ReflectionInfo): void;
registerType(type: Type, typeInfo: ReflectionInfo): void;
registerGetters(getters: {
[key: string]: GetterFn;
}): void;
registerSetters(setters: {
[key: string]: SetterFn;
}): void;
registerMethods(methods: {
[key: string]: MethodFn;
}): void;
factory(type: Type): Function;
parameters(typeOrFunc: any): any[][];
annotations(typeOrFunc: any): any[];
propMetadata(typeOrFunc: any): {
[key: string]: any[];
};
interfaces(type: Type): any[];
getter(name: string): GetterFn;
setter(name: string): SetterFn;
method(name: string): MethodFn;
importUri(type: Type): string;
}
| hbthegreat/interactively | node_modules/angular2/src/core/reflection/reflector.d.ts | TypeScript | mit | 2,285 |
import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
import os = require('os');
let taskPath = path.join(__dirname, '..', 'xamarinios.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
process.env['HOME']='/user/home'; //replace with mock of setVariable when task-lib has the support
tr.setInput('solution', 'src/project.sln'); //path
tr.setInput('configuration', 'Release');
tr.setInput('args', '');
tr.setInput('clean', 'true');
tr.setInput('packageApp', ''); //boolean
tr.setInput('forSimulator', ''); //boolean
tr.setInput('runNugetRestore', 'true'); //boolean
tr.setInput('iosSigningIdentity', '');
tr.setInput('provProfileUuid', '');
tr.setInput('buildToolLocation', '/home/bin/msbuild');
// provide answers for task mock
let a: ma.TaskLibAnswers = <ma.TaskLibAnswers>{
"getVariable": {
"HOME": "/user/home"
},
"which": {
"nuget": "/home/bin/nuget"
},
"exec": {
"/home/bin/msbuild src/project.sln /p:Configuration=Release /p:Platform=iPhone /t:Clean": {
"code": 0,
"stdout": "msbuild"
},
"/home/bin/nuget restore src/project.sln": {
"code": 0,
"stdout": "nuget restore"
},
"/home/bin/msbuild src/project.sln /p:Configuration=Release /p:Platform=iPhone": {
"code": 0,
"stdout": "msbuild"
}
},
"checkPath" : {
"/user/build": true,
"/home/bin/msbuild": true,
"/home/bin/nuget": true,
"src/project.sln": true
},
"findMatch" : {
"src/project.sln": ["src/project.sln"]
}
};
tr.setAnswers(a);
os.platform = () => {
return 'darwin';
}
tr.registerMock('os', os);
tr.run();
| jotaylo/vsts-tasks | Tasks/XamariniOSV2/Tests/L0MSBuildLocation.ts | TypeScript | mit | 1,795 |
#include "Viewer.h"
#include "Scene_draw_interface.h"
Viewer::Viewer(QWidget* parent, bool antialiasing)
: QGLViewer(parent),
scene(0),
antialiasing(antialiasing),
twosides(false),
m_isInitialized(false)
{
setBackgroundColor(::Qt::white);
}
void Viewer::setScene(Scene_draw_interface* scene)
{
this->scene = scene;
}
void Viewer::setAntiAliasing(bool b)
{
antialiasing = b;
if(m_isInitialized)
updateGL();
}
void Viewer::setTwoSides(bool b)
{
twosides = b;
if(m_isInitialized)
updateGL();
}
void Viewer::draw()
{
draw_aux(false);
}
void Viewer::initializeGL()
{
m_isInitialized = true;
QGLViewer::initializeGL();
scene->initializeGL();
}
void Viewer::draw_aux(bool with_names)
{
QGLViewer::draw();
if(scene == 0)
return;
::glLineWidth(1.0f);
::glPointSize(2.f);
::glEnable(GL_POLYGON_OFFSET_FILL);
::glPolygonOffset(1.0f,1.0f);
::glClearColor(1.0f,1.0f,1.0f,0.0f);
::glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
if(twosides)
::glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
else
::glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
if(antiAliasing())
{
::glEnable(GL_BLEND);
::glEnable(GL_LINE_SMOOTH);
::glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
else
{
::glDisable(GL_BLEND);
::glDisable(GL_LINE_SMOOTH);
::glDisable(GL_POLYGON_SMOOTH_HINT);
::glBlendFunc(GL_ONE, GL_ZERO);
::glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST);
}
if(with_names)
scene->drawWithNames();
else
scene->draw();
}
void Viewer::drawWithNames()
{
draw_aux(true);
}
void Viewer::postSelection(const QPoint&)
{
emit selected(this->selectedName());
}
| alexandrustaetu/natural_editor | external/CGAL-4.4-beta1/demo/Surface_reconstruction_points_3/Viewer.cpp | C++ | mit | 1,718 |
var successCount = 0;
for each (arg in args) {
if (process(arg)) {
successCount++;
}
}
write(successCount + " out of " + args.length + " benchmarks passed the test", "test.result");
exit();
function process(name) {
log = name + ".result";
s = "";
stgWork = import(name + ".g");
s += "Processing STG:\n";
s += " - importing: ";
if (stgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
save(stgWork, name + ".stg.work");
s += " - verification: ";
if (checkStgCombined(stgWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - CSC check: ";
if (checkStgCsc(stgWork) == true) {
cscStgWork = stgWork;
s += "OK\n";
} else {
s += "CONFLICT\n";
s += " - Conflict resolution: ";
cscStgWork = resolveCscConflictMpsat(stgWork);
if (cscStgWork == null) {
cscStgWork = resolveCscConflictPetrify(stgWork);
if (cscStgWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
}
s += "OK\n";
save(cscStgWork, name + "-csc.stg.work");
}
s += "Complex gate:\n";
s += " - synthesis: ";
cgCircuitWork = synthComplexGateMpsat(cscStgWork);
if (cgCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(cgCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Generalised C-element:\n";
s += " - synthesis: ";
gcCircuitWork = synthGeneralisedCelementMpsat(cscStgWork);
if (gcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(gcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Standard C-element:\n";
s += " - synthesis: ";
stdcCircuitWork = synthStandardCelementMpsat(cscStgWork);
if (stdcCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(stdcCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += "Technology mapping:\n";
s += " - synthesis: ";
tmCircuitWork = synthTechnologyMappingMpsat(cscStgWork);
if (tmCircuitWork == null) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
s += " - verification: ";
if (checkCircuitCombined(tmCircuitWork) != true) {
s += "FAILED\n";
write(s, log);
return false;
}
s += "OK\n";
write(s, log);
return true;
}
| workcraft/workcraft | ci/flow-mpsat-g/test.js | JavaScript | mit | 3,041 |
<?php
defined('_JEXEC') or die('Restricted access');
require HelperGalleryUG::getPathHelperTemplate("header");
$selectedGalleryTab = "categorytabs";
require HelperGalleryUG::getPathHelperTemplate("gallery_edit_tabs");
?>
<div class="settings_panel">
<div class="settings_panel_left">
<div class="settings_panel_left_inner settings_panel_box">
<?php $outputMain->draw("form_gallery_category_settings",true)?>
<div class="vert_sap20"></div>
<div>* The lite version has a limitation of 4 category tabs per gallery in output. <a target="_blank" href="http://codecanyon.net/item/unite-gallery-wordpress-plugin/10458750?ref=valiano">Get Full Version!</a> </div>
<div class="vert_sap40"></div>
<div id="update_button_wrapper" class="update_button_wrapper">
<a class='unite-button-primary' href='javascript:void(0)' id="button_save_gallery" ><?php _e("Update Settings",UNITEGALLERY_TEXTDOMAIN); ?></a>
<div id="loader_update" class="loader_round" style="display:none;"><?php _e("Updating",UNITEGALLERY_TEXTDOMAIN); ?>...</div>
<div id="update_gallery_success" class="success_message" class="display:none;"></div>
</div>
<a id="button_close_gallery" class='unite-button-secondary float_left mleft_10' href='<?php echo HelperGalleryUG::getUrlViewGalleriesList() ?>' ><?php _e("Close",UNITEGALLERY_TEXTDOMAIN); ?></a>
<div class="vert_sap20"></div>
<div id="error_message_settings" class="unite_error_message" style="display:none"></div>
</div>
</div>
<div class="settings_panel_right">
<?php $outputParams->draw("form_gallery_category_settings_params",true); ?>
</div>
<div class="unite-clear"></div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
var objAdmin = new UGAdmin();
objAdmin.initCategoryTabsView();
});
</script>
| florianduport/slowvan | wp-content/plugins/unite-gallery-lite/helpers/templates/gallery_categorytabs.php | PHP | mit | 1,967 |
<?php
namespace Concrete\Core\Express\Entry;
use Concrete\Core\Entity\Express\Entity;
use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Entity\Express\Form;
use Concrete\Core\Express\Event\Event;
use Concrete\Core\Express\Form\Control\SaveHandler\SaveHandlerInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use Symfony\Component\HttpFoundation\Request;
class Manager
{
protected $entityManager;
protected $request;
public function __construct(EntityManagerInterface $entityManager, Request $request)
{
$this->request = $request;
$this->entityManager = $entityManager;
}
/**
* @TODO This function needs to do a better job of computing display order when in use by an
* owned entity. The problem is if you have an entity like Service owned by Category then if you add
* four categories with 40 services total, you'll get display order from 0 to 39; when in reality it should
* be split between the owned entities so that categories bound to service 1 go from 0 to 9, from service 2
* go from 0 to 10, etc...
*/
protected function getNewDisplayOrder(Entity $entity)
{
$query = $this->entityManager->createQuery('select max(e.exEntryDisplayOrder) as displayOrder from \Concrete\Core\Entity\Express\Entry e where e.entity = :entity');
$query->setParameter('entity', $entity);
$displayOrder = $query->getOneOrNullResult(Query::HYDRATE_SINGLE_SCALAR);
if (!$displayOrder) {
$displayOrder = 1;
} else {
++$displayOrder;
}
return $displayOrder;
}
public function addEntry(Entity $entity)
{
$entry = new Entry();
$entry->setEntity($entity);
if ($entity->supportsCustomDisplayOrder()) {
$entry->setEntryDisplayOrder($this->getNewDisplayOrder($entity));
}
$this->entityManager->persist($entry);
$this->entityManager->flush();
return $entry;
}
public function deleteEntry(Entry $entry)
{
// Get all associations that reference this entry.
$this->entityManager->remove($entry);
$this->entityManager->flush();
}
public function saveEntryAttributesForm(Form $form, Entry $entry)
{
foreach ($form->getControls() as $control) {
$type = $control->getControlType();
$saver = $type->getSaveHandler($control);
if ($saver instanceof SaveHandlerInterface) {
$saver->saveFromRequest($control, $entry, $this->request);
}
}
$this->entityManager->flush();
$ev = new Event($entry);
$ev->setEntityManager($this->entityManager);
\Events::dispatch('on_express_entry_saved', $ev);
return $ev->getEntry();
}
} | jaromirdalecky/concrete5 | concrete/src/Express/Entry/Manager.php | PHP | mit | 2,831 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script shows the categories on each page and lets you change them.
For each page in the target wiki:
* If the page contains no categories, you can specify a list of categories to
add to the page.
* If the page already contains one or more categories, you can specify a new
list of categories to replace the current list of categories of the page.
Usage:
python pwb.py catall [start]
If no starting name is provided, the bot starts at 'A'.
Options:
-onlynew : Only run on pages that do not yet have a category.
"""
#
# (C) Rob W.W. Hooft, Andre Engels, 2004
# (C) Pywikibot team, 2004-2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import pywikibot
from pywikibot import i18n, textlib
from pywikibot.bot import QuitKeyboardInterrupt
def choosecats(pagetext):
"""Coose categories."""
chosen = []
done = False
length = 1000
# TODO: → input_choice
pywikibot.output("""Give the new categories, one per line.
Empty line: if the first, don't change. Otherwise: Ready.
-: I made a mistake, let me start over.
?: Give the text of the page with GUI.
??: Give the text of the page in console.
xx: if the first, remove all categories and add no new.
q: quit.""")
while not done:
choice = pywikibot.input(u"?")
if choice == "":
done = True
elif choice == "-":
chosen = choosecats(pagetext)
done = True
elif choice == "?":
from pywikibot import editor as editarticle
editor = editarticle.TextEditor()
editor.edit(pagetext)
elif choice == "??":
pywikibot.output(pagetext[0:length])
length = length + 500
elif choice == "xx" and chosen == []:
chosen = None
done = True
elif choice == "q":
raise QuitKeyboardInterrupt
else:
chosen.append(choice)
return chosen
def make_categories(page, list, site=None):
"""Make categories."""
if site is None:
site = pywikibot.Site()
pllist = []
for p in list:
cattitle = "%s:%s" % (site.namespaces.CATEGORY, p)
pllist.append(pywikibot.Page(site, cattitle))
page.put_async(textlib.replaceCategoryLinks(page.get(), pllist,
site=page.site),
summary=i18n.twtranslate(site, 'catall-changing'))
def main(*args):
"""
Process command line arguments and perform task.
If args is an empty list, sys.argv is used.
@param args: command line arguments
@type args: list of unicode
"""
docorrections = True
start = 'A'
local_args = pywikibot.handle_args(args)
for arg in local_args:
if arg == '-onlynew':
docorrections = False
else:
start = arg
mysite = pywikibot.Site()
for p in mysite.allpages(start=start):
try:
text = p.get()
cats = p.categories()
if not cats:
pywikibot.output(u"========== %s ==========" % p.title())
pywikibot.output('No categories')
pywikibot.output('-' * 40)
newcats = choosecats(text)
if newcats != [] and newcats is not None:
make_categories(p, newcats, mysite)
elif docorrections:
pywikibot.output(u"========== %s ==========" % p.title())
for c in cats:
pywikibot.output(c.title())
pywikibot.output('-' * 40)
newcats = choosecats(text)
if newcats is None:
make_categories(p, [], mysite)
elif newcats != []:
make_categories(p, newcats, mysite)
except pywikibot.IsRedirectPage:
pywikibot.output(u'%s is a redirect' % p.title())
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pywikibot.output('\nQuitting program...')
| h4ck3rm1k3/pywikibot-core | scripts/catall.py | Python | mit | 4,132 |
(function () {
var common;
this.setAsDefault = function () {
var _external = window.external;
if (_external && ('AddSearchProvider' in _external) && ('IsSearchProviderInstalled' in _external)) {
var isInstalled = 0;
try {
isInstalled = _external.IsSearchProviderInstalled('https://gusouk.com');
if (isInstalled > 0) {
alert("已添加过此搜索引擎");
}
} catch (err) {
isInstalled = 0;
}
console.log("isInstalled: " + isInstalled);
_external.AddSearchProvider('https://gusouk.com/opensearch.xml');
} else {
window.open('http://mlongbo.com/set_as_default_search_engine/');
}
return false;
};
/**
* 切换弹出框显示
* @param {[type]} id [弹出框元素id]
* @param {[type]} eventName [事件名称]
*/
this.swithPopver = function (id,eventName) {
var ele = document.getElementById(id);
if ((eventName && eventName === 'blur') || ele.style.display === 'block') {
ele.style.display = 'none';
} else {
ele.style.display = 'block';
}
};
})();
console.info("谷搜客基于Google搜索,为喜爱谷歌搜索的朋友们免费提供高速稳定的搜索服务。搜索结果通过Google.com实时抓取,欢迎您在日常生活学习中使用谷搜客查询资料。");
console.info("如果你觉得谷搜客对你有帮助,请资助(支付宝账号: mlongbo@gmail.com)我一下,资金将用于支持我开发及购买服务器资源。^_^");
console.info("本站使用开源项目gso(https://github.com/lenbo-ma/gso)搭建");
console.info("希望能够让更多的获取知识,加油!"); | lenbo-ma/gso | public/javascripts/main.js | JavaScript | mit | 1,797 |
using System;
using System.IO;
using System.Threading;
using JetBrains.Annotations;
// ReSharper disable once CheckNamespace
namespace BenchmarkDotNet.Loggers
{
// BASEDON: https://github.com/dotnet/BenchmarkDotNet/blob/master/src/BenchmarkDotNet.Core/Loggers/StreamLogger.cs
/// <summary>
/// Implementation of <see cref="ILogger"/> that supports lazy initialization and prevents output interleaving.
/// </summary>
/// <seealso cref="ILogger"/>
[PublicAPI]
public sealed class LazySynchronizedStreamLogger : IFlushableLogger
{
private readonly Lazy<TextWriter> _writerLazy;
/// <summary>Initializes a new instance of the <see cref="LazySynchronizedStreamLogger"/> class.</summary>
/// <param name="writerFactory">Factory method for the writer the log output will be redirected.</param>
public LazySynchronizedStreamLogger([NotNull] Func<TextWriter> writerFactory)
{
if (writerFactory == null)
throw new ArgumentNullException(nameof(writerFactory));
_writerLazy = new Lazy<TextWriter>(
() => TextWriter.Synchronized(writerFactory()),
LazyThreadSafetyMode.ExecutionAndPublication);
}
/// <summary>Initializes a new instance of the <see cref="LazySynchronizedStreamLogger"/> class.</summary>
/// <param name="filePath">The file path for the log.</param>
/// <param name="append">
/// if set to <c>true</c> the log will be appended to existing file; if <c>false</c> the log wil be overwritten.
/// </param>
public LazySynchronizedStreamLogger([NotNull] string filePath, bool append = false)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentNullException(nameof(filePath));
_writerLazy = new Lazy<TextWriter>(
() => TextWriter.Synchronized(new StreamWriter(filePath, append)),
LazyThreadSafetyMode.ExecutionAndPublication);
}
/// <summary>Write the text.</summary>
/// <param name="logKind">Kind of text.</param>
/// <param name="text">The text to write.</param>
public void Write(LogKind logKind, string text) => _writerLazy.Value.Write(text);
/// <summary>Write empty line.</summary>
public void WriteLine() => _writerLazy.Value.WriteLine();
/// <summary>Write the line.</summary>
/// <param name="logKind">Kind of text.</param>
/// <param name="text">The text to write.</param>
public void WriteLine(LogKind logKind, string text) => _writerLazy.Value.WriteLine(text);
/// <summary>Flushes the log.</summary>
public void Flush()
{
if (_writerLazy.IsValueCreated)
{
_writerLazy.Value.Flush();
}
}
}
} | rsdn/CodeJam | PerfTests[WIP]/src/[L0_PortToBenchmerkDotNet]/Loggers/LazySynchronizedStreamLogger.cs | C# | mit | 2,533 |
define(
({
insertTableTitle: "Insertar tabla",
modifyTableTitle: "Modificar tabla",
rows: "Filas:",
columns: "Columnas:",
align: "Alinear:",
cellPadding: "Relleno de celda:",
cellSpacing: "Espaciado de celda:",
tableWidth: "Ancho de tabla:",
backgroundColor: "Color de fondo:",
borderColor: "Color de borde:",
borderThickness: "Grosor del borde:",
percent: "por ciento",
pixels: "píxeles",
"default": "default",
left: "izquierda",
center: "centro",
right: "derecha",
buttonSet: "Establecer", // translated elsewhere?
buttonInsert: "Insertar",
buttonCancel: "Cancelar",
selectTableLabel: "Seleccionar tabla",
insertTableRowBeforeLabel: "Añadir fila antes",
insertTableRowAfterLabel: "Añadir fila después",
insertTableColumnBeforeLabel: "Añadir columna antes",
insertTableColumnAfterLabel: "Añadir columna después",
deleteTableRowLabel: "Suprimir fila",
deleteTableColumnLabel: "Suprimir columna"
})
);
| synico/springframework | lobtool/src/main/webapp/resources/javascript/dojox/editor/plugins/nls/es/TableDialog.js | JavaScript | mit | 935 |
/**
* Copyright (c) 2015-2016 Angelo ZERR.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package ts.eclipse.ide.ui.hover;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.source.Annotation;
import ts.client.CommandNames;
import ts.client.codefixes.CodeAction;
import ts.eclipse.ide.core.resources.IIDETypeScriptProject;
import ts.eclipse.ide.core.utils.TypeScriptResourceUtil;
import ts.eclipse.ide.ui.TypeScriptUIPlugin;
import ts.resources.ITypeScriptFile;
import ts.resources.ITypeScriptProject;
/**
* Problem Hover used to display errors when mouse over a JS content which have
* a TypeScript error.
*
*/
public class ProblemTypeScriptHover extends AbstractAnnotationHover {
protected static class ProblemInfo extends AnnotationInfo {
private static final Class<?>[] EMPTY_CLASS = new Class[0];
private static final Object[] EMPTY_OBJECT = new Object[0];
private static final String GET_ATTRIBUTES_METHOD_NAME = "getAttributes";
private static final ICompletionProposal[] NO_PROPOSALS = new ICompletionProposal[0];
public ProblemInfo(Annotation annotation, Position position, ITextViewer textViewer) {
super(annotation, position, textViewer);
}
@Override
public ICompletionProposal[] getCompletionProposals() {
IDocument document = viewer.getDocument();
IFile file = TypeScriptResourceUtil.getFile(document);
try {
IIDETypeScriptProject tsProject = TypeScriptResourceUtil.getTypeScriptProject(file.getProject());
if (tsProject.canSupport(CommandNames.GetCodeFixes)) {
// Get code fixes with TypeScript 2.1.1
ITypeScriptFile tsFile = tsProject.openFile(file, document);
List<Integer> errorCodes = createErrorCodes(tsProject);
if (errorCodes != null) {
final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
List<CodeAction> codeActions = tsFile.getCodeFixes(position.getOffset(),
position.getOffset() + position.getLength(), errorCodes)
.get(5000, TimeUnit.MILLISECONDS);
for (CodeAction codeAction : codeActions) {
proposals.add(new CodeActionCompletionProposal(codeAction, tsFile.getName()));
}
return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
return NO_PROPOSALS;
}
} catch (Exception e) {
e.printStackTrace();
}
return NO_PROPOSALS;
}
private List<Integer> createErrorCodes(ITypeScriptProject tsProject) {
List<Integer> errorCodes = null;
try {
// Try to retrieve the TypeScript error code from the SSE
// TemporaryAnnotation.
Method getAttributesMethod = annotation.getClass().getMethod(GET_ATTRIBUTES_METHOD_NAME, EMPTY_CLASS);
Map getAttributes = (Map) getAttributesMethod.invoke(annotation, EMPTY_OBJECT);
Integer tsCode = (Integer) getAttributes.get("tsCode");
if (tsCode != null) {
Integer errorCode = tsCode;
if (tsProject.canFix(errorCode)) {
if (errorCodes == null) {
errorCodes = new ArrayList<Integer>();
}
errorCodes.add(errorCode);
}
}
} catch (NoSuchMethodException e) {
// The annotation is not a
// org.eclipse.wst.sse.ui.internal.reconcile.TemporaryAnnotation
// ignore the error.
} catch (Throwable e) {
TypeScriptUIPlugin.log("Error while getting TypeScript error code", e);
}
return errorCodes;
}
}
public ProblemTypeScriptHover() {
super(false);
}
@Override
protected AnnotationInfo createAnnotationInfo(Annotation annotation, Position position, ITextViewer textViewer) {
return new ProblemInfo(annotation, position, textViewer);
}
}
| webratio/typescript.java | eclipse/ts.eclipse.ide.ui/src/ts/eclipse/ide/ui/hover/ProblemTypeScriptHover.java | Java | mit | 4,362 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.data.processor.data.tileentity;
import static com.google.common.base.Preconditions.checkNotNull;
import com.flowpowered.math.vector.Vector3i;
import com.google.common.collect.ImmutableMap;
import net.minecraft.tileentity.TileEntityStructure;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataHolder;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.tileentity.ImmutableStructureData;
import org.spongepowered.api.data.manipulator.mutable.tileentity.StructureData;
import org.spongepowered.api.data.type.StructureMode;
import org.spongepowered.common.data.manipulator.mutable.tileentity.SpongeStructureData;
import org.spongepowered.common.data.processor.common.AbstractTileEntityDataProcessor;
import org.spongepowered.common.interfaces.block.tile.IMixinTileEntityStructure;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
public final class StructureDataProcessor extends AbstractTileEntityDataProcessor<TileEntityStructure, StructureData, ImmutableStructureData> {
public StructureDataProcessor() {
super(TileEntityStructure.class);
}
@Override
protected boolean doesDataExist(TileEntityStructure container) {
return true;
}
@Override
protected boolean set(TileEntityStructure container, Map<Key<?>, Object> map) {
@Nullable String author = (String) map.get(Keys.STRUCTURE_AUTHOR);
if (author != null) {
((IMixinTileEntityStructure) container).setAuthor(author);
}
container.setIgnoresEntities((Boolean) map.get(Keys.STRUCTURE_IGNORE_ENTITIES));
container.setIntegrity((Float) map.get(Keys.STRUCTURE_INTEGRITY));
@Nullable StructureMode mode = (StructureMode) map.get(Keys.STRUCTURE_MODE);
if (mode != null) {
((IMixinTileEntityStructure) container).setMode(mode);
}
@Nullable Vector3i position = (Vector3i) map.get(Keys.STRUCTURE_POSITION);
if (position != null) {
((IMixinTileEntityStructure) container).setPosition(position);
}
container.setPowered((Boolean) map.get(Keys.STRUCTURE_POWERED));
@Nullable Long seed = (Long) map.get(Keys.STRUCTURE_SEED);
if (seed != null) {
container.setSeed(seed);
}
container.setShowAir((Boolean) map.get(Keys.STRUCTURE_SHOW_AIR));
container.setShowBoundingBox((Boolean) map.get(Keys.STRUCTURE_SHOW_BOUNDING_BOX));
@Nullable Boolean showBoundingBox = (Boolean) map.get(Keys.STRUCTURE_SHOW_BOUNDING_BOX);
if (showBoundingBox != null) {
}
@Nullable Vector3i size = (Vector3i) map.get(Keys.STRUCTURE_SIZE);
if (size != null) {
((IMixinTileEntityStructure) container).setSize(size);
}
return true;
}
@Override
protected Map<Key<?>, ?> getValues(TileEntityStructure container) {
ImmutableMap.Builder<Key<?>, Object> builder = ImmutableMap.builder();
builder.put(Keys.STRUCTURE_AUTHOR, ((IMixinTileEntityStructure) container).getAuthor());
builder.put(Keys.STRUCTURE_IGNORE_ENTITIES, ((IMixinTileEntityStructure) container).shouldIgnoreEntities());
builder.put(Keys.STRUCTURE_INTEGRITY, ((IMixinTileEntityStructure) container).getIntegrity());
builder.put(Keys.STRUCTURE_MODE, ((IMixinTileEntityStructure) container).getMode());
builder.put(Keys.STRUCTURE_POSITION, ((IMixinTileEntityStructure) container).getPosition());
builder.put(Keys.STRUCTURE_POWERED, container.isPowered());
builder.put(Keys.STRUCTURE_SHOW_AIR, ((IMixinTileEntityStructure) container).shouldShowAir());
builder.put(Keys.STRUCTURE_SHOW_BOUNDING_BOX, ((IMixinTileEntityStructure) container).shouldShowBoundingBox());
builder.put(Keys.STRUCTURE_SIZE, ((IMixinTileEntityStructure) container).getSize());
return builder.build();
}
@Override
protected StructureData createManipulator() {
return new SpongeStructureData();
}
@Override
public Optional<StructureData> fill(DataContainer container, StructureData data) {
checkNotNull(data, "data");
Optional<String> author = container.getString(Keys.STRUCTURE_AUTHOR.getQuery());
if (author.isPresent()) {
data = data.set(Keys.STRUCTURE_AUTHOR, author.get());
}
Optional<Boolean> ignoreEntities = container.getBoolean(Keys.STRUCTURE_IGNORE_ENTITIES.getQuery());
if (ignoreEntities.isPresent()) {
data = data.set(Keys.STRUCTURE_IGNORE_ENTITIES, ignoreEntities.get());
}
Optional<Float> integrity = container.getFloat(Keys.STRUCTURE_INTEGRITY.getQuery());
if (integrity.isPresent()) {
data = data.set(Keys.STRUCTURE_INTEGRITY, integrity.get());
}
Optional<StructureMode> mode = container.getObject(Keys.STRUCTURE_MODE.getQuery(), StructureMode.class);
if (mode.isPresent()) {
data = data.set(Keys.STRUCTURE_MODE, mode.get());
}
Optional<Vector3i> position = container.getObject(Keys.STRUCTURE_POSITION.getQuery(), Vector3i.class);
if (position.isPresent()) {
data = data.set(Keys.STRUCTURE_POSITION, position.get());
}
Optional<Boolean> powered = container.getBoolean(Keys.STRUCTURE_POWERED.getQuery());
if (powered.isPresent()) {
data = data.set(Keys.STRUCTURE_POWERED, powered.get());
}
Optional<Boolean> showAir = container.getBoolean(Keys.STRUCTURE_SHOW_AIR.getQuery());
if (showAir.isPresent()) {
data = data.set(Keys.STRUCTURE_SHOW_AIR, showAir.get());
}
Optional<Boolean> showBoundingBox = container.getBoolean(Keys.STRUCTURE_SHOW_BOUNDING_BOX.getQuery());
if (showBoundingBox.isPresent()) {
data = data.set(Keys.STRUCTURE_SHOW_BOUNDING_BOX, showBoundingBox.get());
}
Optional<Vector3i> size = container.getObject(Keys.STRUCTURE_SIZE.getQuery(), Vector3i.class);
if (size.isPresent()) {
data = data.set(Keys.STRUCTURE_SIZE, size.get());
}
return Optional.of(data);
}
@Override
public DataTransactionResult remove(DataHolder container) {
return DataTransactionResult.failNoData();
}
}
| Grinch/SpongeCommon | src/main/java/org/spongepowered/common/data/processor/data/tileentity/StructureDataProcessor.java | Java | mit | 7,763 |