code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package source
import "os"
type File struct {
*os.File
}
func (File) Continuable() bool { return true }
| phenomenes/varnishbeat | vendor/github.com/elastic/beats/filebeat/harvester/source/file.go | GO | bsd-2-clause | 108 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = /Users/amitupadhyay/projects/importd/bin/sphinx-build
PAPER =
BUILDDIR = /Users/amitupadhyay/projects/importd/docs
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) /Users/amitupadhyay/projects/importd/docs/source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/docs.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/docs.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/docs"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/docs"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| pombredanne/importd | docs/Makefile | Makefile | bsd-3-clause | 4,703 |
// 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.
//
// Class that handles the details of sending and receiving client
// invalidation packets.
#ifndef SYNC_NOTIFIER_CACHE_INVALIDATION_PACKET_HANDLER_H_
#define SYNC_NOTIFIER_CACHE_INVALIDATION_PACKET_HANDLER_H_
#pragma once
#include <string>
#include "base/basictypes.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/non_thread_safe.h"
#include "google/cacheinvalidation/include/system-resources.h"
#include "jingle/notifier/listener/push_notifications_listen_task.h"
#include "jingle/notifier/listener/push_notifications_subscribe_task.h"
namespace buzz {
class XmppTaskParentInterface;
} // namespace buzz
namespace sync_notifier {
class CacheInvalidationPacketHandler
: public notifier::PushNotificationsSubscribeTaskDelegate,
public notifier::PushNotificationsListenTaskDelegate {
public:
// Starts routing packets from |invalidation_client| using
// |base_task|. |base_task.get()| must still be non-NULL.
// |invalidation_client| must not already be routing packets through
// something. Does not take ownership of |invalidation_client|.
CacheInvalidationPacketHandler(
base::WeakPtr<buzz::XmppTaskParentInterface> base_task);
// Makes the invalidation client passed into the constructor not
// route packets through the XMPP client passed into the constructor
// anymore.
virtual ~CacheInvalidationPacketHandler();
// If |base_task| is non-NULL, sends the outgoing message.
virtual void SendMessage(const std::string& outgoing_message);
virtual void SetMessageReceiver(
invalidation::MessageCallback* incoming_receiver);
// Sends a message requesting a subscription to the notification channel.
virtual void SendSubscriptionRequest();
// PushNotificationsSubscribeTaskDelegate implementation.
virtual void OnSubscribed() OVERRIDE;
virtual void OnSubscriptionError() OVERRIDE;
// PushNotificationsListenTaskDelegate implementation.
virtual void OnNotificationReceived(
const notifier::Notification& notification) OVERRIDE;
private:
FRIEND_TEST_ALL_PREFIXES(CacheInvalidationPacketHandlerTest, Basic);
base::NonThreadSafe non_thread_safe_;
base::WeakPtrFactory<CacheInvalidationPacketHandler> weak_factory_;
base::WeakPtr<buzz::XmppTaskParentInterface> base_task_;
scoped_ptr<invalidation::MessageCallback> incoming_receiver_;
// Parameters for sent messages.
// Monotonically increasing sequence number.
int seq_;
// Service context.
std::string service_context_;
// Scheduling hash.
int64 scheduling_hash_;
DISALLOW_COPY_AND_ASSIGN(CacheInvalidationPacketHandler);
};
} // namespace sync_notifier
#endif // SYNC_NOTIFIER_CACHE_INVALIDATION_PACKET_HANDLER_H_
| ropik/chromium | sync/notifier/cache_invalidation_packet_handler.h | C | bsd-3-clause | 2,937 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkFontMgr.h"
#include "SkFontMgr_indirect.h"
#include "SkFontStyle.h"
#include "SkMutex.h"
#include "SkOnce.h"
#include "SkRefCnt.h"
#include "SkRemotableFontMgr.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTArray.h"
#include "SkTypeface.h"
#include "SkTypes.h"
#include "SkTemplates.h"
class SkData;
class SkStyleSet_Indirect : public SkFontStyleSet {
public:
/** Takes ownership of the SkRemotableFontIdentitySet. */
SkStyleSet_Indirect(const SkFontMgr_Indirect* owner, int familyIndex,
SkRemotableFontIdentitySet* data)
: fOwner(SkRef(owner)), fFamilyIndex(familyIndex), fData(data)
{ }
int count() override { return fData->count(); }
void getStyle(int index, SkFontStyle* fs, SkString* style) override {
if (fs) {
*fs = fData->at(index).fFontStyle;
}
if (style) {
// TODO: is this useful? Current locale?
style->reset();
}
}
SkTypeface* createTypeface(int index) override {
return fOwner->createTypefaceFromFontId(fData->at(index));
}
SkTypeface* matchStyle(const SkFontStyle& pattern) override {
if (fFamilyIndex >= 0) {
SkFontIdentity id = fOwner->fProxy->matchIndexStyle(fFamilyIndex, pattern);
return fOwner->createTypefaceFromFontId(id);
}
return this->matchStyleCSS3(pattern);
}
private:
sk_sp<const SkFontMgr_Indirect> fOwner;
int fFamilyIndex;
sk_sp<SkRemotableFontIdentitySet> fData;
};
int SkFontMgr_Indirect::onCountFamilies() const {
return 0;
}
void SkFontMgr_Indirect::onGetFamilyName(int index, SkString* familyName) const {
SK_ABORT("Not implemented");
}
SkFontStyleSet* SkFontMgr_Indirect::onCreateStyleSet(int index) const {
SK_ABORT("Not implemented");
return nullptr;
}
SkFontStyleSet* SkFontMgr_Indirect::onMatchFamily(const char familyName[]) const {
return new SkStyleSet_Indirect(this, -1, fProxy->matchName(familyName));
}
SkTypeface* SkFontMgr_Indirect::createTypefaceFromFontId(const SkFontIdentity& id) const {
if (id.fDataId == SkFontIdentity::kInvalidDataId) {
return nullptr;
}
SkAutoMutexAcquire ama(fDataCacheMutex);
sk_sp<SkTypeface> dataTypeface;
int dataTypefaceIndex = 0;
for (int i = 0; i < fDataCache.count(); ++i) {
const DataEntry& entry = fDataCache[i];
if (entry.fDataId == id.fDataId) {
if (entry.fTtcIndex == id.fTtcIndex &&
!entry.fTypeface->weak_expired() && entry.fTypeface->try_ref())
{
return entry.fTypeface;
}
if (dataTypeface.get() == nullptr &&
!entry.fTypeface->weak_expired() && entry.fTypeface->try_ref())
{
dataTypeface.reset(entry.fTypeface);
dataTypefaceIndex = entry.fTtcIndex;
}
}
if (entry.fTypeface->weak_expired()) {
fDataCache.removeShuffle(i);
--i;
}
}
// No exact match, but did find a data match.
if (dataTypeface.get() != nullptr) {
std::unique_ptr<SkStreamAsset> stream(dataTypeface->openStream(nullptr));
if (stream.get() != nullptr) {
return fImpl->makeFromStream(std::move(stream), dataTypefaceIndex).release();
}
}
// No data match, request data and add entry.
std::unique_ptr<SkStreamAsset> stream(fProxy->getData(id.fDataId));
if (stream.get() == nullptr) {
return nullptr;
}
sk_sp<SkTypeface> typeface(fImpl->makeFromStream(std::move(stream), id.fTtcIndex));
if (typeface.get() == nullptr) {
return nullptr;
}
DataEntry& newEntry = fDataCache.push_back();
typeface->weak_ref();
newEntry.fDataId = id.fDataId;
newEntry.fTtcIndex = id.fTtcIndex;
newEntry.fTypeface = typeface.get(); // weak reference passed to new entry.
return typeface.release();
}
SkTypeface* SkFontMgr_Indirect::onMatchFamilyStyle(const char familyName[],
const SkFontStyle& fontStyle) const {
SkFontIdentity id = fProxy->matchNameStyle(familyName, fontStyle);
return this->createTypefaceFromFontId(id);
}
SkTypeface* SkFontMgr_Indirect::onMatchFamilyStyleCharacter(const char familyName[],
const SkFontStyle& style,
const char* bcp47[],
int bcp47Count,
SkUnichar character) const {
SkFontIdentity id = fProxy->matchNameStyleCharacter(familyName, style, bcp47,
bcp47Count, character);
return this->createTypefaceFromFontId(id);
}
SkTypeface* SkFontMgr_Indirect::onMatchFaceStyle(const SkTypeface* familyMember,
const SkFontStyle& fontStyle) const {
SkString familyName;
familyMember->getFamilyName(&familyName);
return this->matchFamilyStyle(familyName.c_str(), fontStyle);
}
sk_sp<SkTypeface> SkFontMgr_Indirect::onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream,
int ttcIndex) const {
return fImpl->makeFromStream(std::move(stream), ttcIndex);
}
sk_sp<SkTypeface> SkFontMgr_Indirect::onMakeFromFile(const char path[], int ttcIndex) const {
return fImpl->makeFromFile(path, ttcIndex);
}
sk_sp<SkTypeface> SkFontMgr_Indirect::onMakeFromData(sk_sp<SkData> data, int ttcIndex) const {
return fImpl->makeFromData(std::move(data), ttcIndex);
}
sk_sp<SkTypeface> SkFontMgr_Indirect::onLegacyMakeTypeface(const char familyName[],
SkFontStyle style) const {
sk_sp<SkTypeface> face(this->matchFamilyStyle(familyName, style));
if (nullptr == face.get()) {
face.reset(this->matchFamilyStyle(nullptr, style));
}
if (nullptr == face.get()) {
SkFontIdentity fontId = this->fProxy->matchIndexStyle(0, style);
face.reset(this->createTypefaceFromFontId(fontId));
}
return face;
}
| Hikari-no-Tenshi/android_external_skia | src/fonts/SkFontMgr_indirect.cpp | C++ | bsd-3-clause | 6,424 |
import errno
import smtplib
import socket
from email.mime.text import MIMEText
from amgut import media_locale
from amgut.lib.config_manager import AMGUT_CONFIG
def send_email(message, subject, recipient='[email protected]',
sender=media_locale['HELP_EMAIL'], html=False):
"""Send an email from your local host"""
msg = MIMEText(message, "html" if html else "plain")
# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
# Send the message via our own SMTP server, but don't include the
# envelope header.
if AMGUT_CONFIG.smtp_ssl:
s = smtplib.SMTP_SSL()
else:
s = smtplib.SMTP()
try:
s.connect(AMGUT_CONFIG.smtp_host, AMGUT_CONFIG.smtp_port)
except socket.error as e:
# TODO: Inability to connect to the mail server shouldn't prevent pages
# from loading but it should be logged in some way
if e.errno == errno.ECONNREFUSED:
return
else:
raise
# try tls, if not available on server just ignore error
try:
s.starttls()
except smtplib.SMTPException:
pass
s.ehlo_or_helo_if_needed()
if AMGUT_CONFIG.smtp_user:
s.login(AMGUT_CONFIG.smtp_user, AMGUT_CONFIG.smtp_password)
s.sendmail(sender, [recipient], msg.as_string())
s.quit()
| adamrp/american-gut-web | amgut/lib/mail.py | Python | bsd-3-clause | 1,428 |
def blank_featured_images(apps, schema_editor):
PrimaryHero = apps.get_model('hero', 'PrimaryHero')
for shelf in PrimaryHero.objects.all():
if shelf.image:
shelf.image = ''
shelf.save()
| bqbn/addons-server | src/olympia/hero/migrations/__init__.py | Python | bsd-3-clause | 226 |
using System;
using UIKit;
using Eto.Forms;
namespace Eto.iOS.Forms
{
public class ScreenHandler : WidgetHandler<UIScreen, Screen, Screen.ICallback>, Screen.IHandler
{
public ScreenHandler(UIScreen control)
{
Control = control;
}
public float Scale
{
get { return 1f; }
}
public float RealScale
{
get { return (float)Control.Scale; }
}
public int BitsPerPixel
{
get { return 32; }
}
public Eto.Drawing.RectangleF Bounds
{
get { return Control.Bounds.ToEto(); }
}
public Eto.Drawing.RectangleF WorkingArea
{
get { return Control.ApplicationFrame.ToEto(); }
}
public bool IsPrimary
{
get { return Control.Handle == UIScreen.MainScreen.Handle; }
}
}
}
| PowerOfCode/Eto | Source/Eto.iOS/Forms/ScreenHandler.cs | C# | bsd-3-clause | 723 |
module M1 (g) where
import M
f :: T -> Int
f (C1 x y) = x + y
g = f (C1 1 2)
l = k
| SAdams601/HaRe | old/testing/removeCon/M1.hs | Haskell | bsd-3-clause | 89 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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 [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_View
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';
/**
* @category Zend
* @package Zend_View
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Foo_FooController extends Zend_Controller_Action
{
public function barAction()
{
$this->view->bar = 'bar';
}
public function nestAction()
{
$this->render();
}
public function nestedAction()
{
$this->render();
}
}
| sandsmedia/zf | tests/Zend/View/Helper/_files/modules/foo/controllers/FooController.php | PHP | bsd-3-clause | 1,321 |
/*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef AXProgressIndicator_h
#define AXProgressIndicator_h
#include "modules/accessibility/AXRenderObject.h"
namespace blink {
class AXObjectCacheImpl;
class HTMLProgressElement;
class RenderProgress;
class AXProgressIndicator final : public AXRenderObject {
public:
static PassRefPtr<AXProgressIndicator> create(RenderProgress*, AXObjectCacheImpl*);
private:
virtual AccessibilityRole roleValue() const override { return ProgressIndicatorRole; }
virtual bool isProgressIndicator() const override { return true; }
virtual float valueForRange() const override;
virtual float maxValueForRange() const override;
virtual float minValueForRange() const override;
AXProgressIndicator(RenderProgress*, AXObjectCacheImpl*);
HTMLProgressElement* element() const;
virtual bool computeAccessibilityIsIgnored() const override;
};
} // namespace blink
#endif // AXProgressIndicator_h
| CTSRD-SOAAP/chromium-42.0.2311.135 | third_party/WebKit/Source/modules/accessibility/AXProgressIndicator.h | C | bsd-3-clause | 1,775 |
package com.jme3.anim.util;
import com.jme3.export.Savable;
import com.jme3.math.Transform;
public interface HasLocalTransform extends Savable {
public void setLocalTransform(Transform transform);
public Transform getLocalTransform();
}
| atomixnmc/jmonkeyengine | jme3-core/src/main/java/com/jme3/anim/util/HasLocalTransform.java | Java | bsd-3-clause | 248 |
var searchData=
[
['blas_20and_20auxiliary',['BLAS and auxiliary',['../group___b_l_a_s.html',1,'']]]
];
| shengren/magma-1.6.1 | docs/html/search/groups_0.js | JavaScript | bsd-3-clause | 106 |
#ifndef THC_GENERIC_FILE
#define THC_GENERIC_FILE "generic/THCTensorMasked.h"
#else
THC_API void THCTensor_(maskedFill)(THCState *state,
THCTensor *tensor,
THCudaByteTensor *mask,
real value);
// FIXME: remove now that we have THCudaByteTensor?
THC_API void THCTensor_(maskedFillByte)(THCState *state,
THCTensor *tensor,
THByteTensor *mask,
real value);
THC_API void THCTensor_(maskedCopy)(THCState *state,
THCTensor *tensor,
THCudaByteTensor *mask,
THCTensor *src);
// FIXME: remove now that we have THCudaByteTensor?
THC_API void THCTensor_(maskedCopyByte)(THCState *state,
THCTensor *tensor,
THByteTensor *mask,
THCTensor *src);
THC_API void THCTensor_(maskedSelect)(THCState *state,
THCTensor *tensor,
THCTensor *src,
THCudaByteTensor *mask);
// FIXME: remove now that we have THCudaByteTensor?
THC_API void THCTensor_(maskedSelectByte)(THCState *state,
THCTensor *tensor,
THCTensor *src,
THByteTensor *mask);
#endif
| RPGOne/Skynet | pytorch-master/torch/lib/THC/generic/THCTensorMasked.h | C | bsd-3-clause | 1,624 |
# Authors: Alexandre Gramfort <[email protected]>
# License: BSD 3 clause
from tempfile import mkdtemp
import shutil
import numpy as np
from scipy import sparse
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_raises_regex
from sklearn.utils.testing import assert_allclose
from sklearn.linear_model.randomized_l1 import (lasso_stability_path,
RandomizedLasso,
RandomizedLogisticRegression)
from sklearn.datasets import load_diabetes, load_iris
from sklearn.feature_selection import f_regression, f_classif
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model.base import _preprocess_data
diabetes = load_diabetes()
X = diabetes.data
y = diabetes.target
X = StandardScaler().fit_transform(X)
X = X[:, [2, 3, 6, 7, 8]]
# test that the feature score of the best features
F, _ = f_regression(X, y)
def test_lasso_stability_path():
# Check lasso stability path
# Load diabetes data and add noisy features
scaling = 0.3
coef_grid, scores_path = lasso_stability_path(X, y, scaling=scaling,
random_state=42,
n_resampling=30)
assert_array_equal(np.argsort(F)[-3:],
np.argsort(np.sum(scores_path, axis=1))[-3:])
def test_randomized_lasso_error_memory():
scaling = 0.3
selection_threshold = 0.5
tempdir = 5
clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42,
scaling=scaling,
selection_threshold=selection_threshold,
memory=tempdir)
assert_raises_regex(ValueError, "'memory' should either be a string or"
" a sklearn.externals.joblib.Memory instance",
clf.fit, X, y)
def test_randomized_lasso():
# Check randomized lasso
scaling = 0.3
selection_threshold = 0.5
n_resampling = 20
# or with 1 alpha
clf = RandomizedLasso(verbose=False, alpha=1, random_state=42,
scaling=scaling, n_resampling=n_resampling,
selection_threshold=selection_threshold)
feature_scores = clf.fit(X, y).scores_
assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:])
# or with many alphas
clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42,
scaling=scaling, n_resampling=n_resampling,
selection_threshold=selection_threshold)
feature_scores = clf.fit(X, y).scores_
assert_equal(clf.all_scores_.shape, (X.shape[1], 2))
assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:])
# test caching
try:
tempdir = mkdtemp()
clf = RandomizedLasso(verbose=False, alpha=[1, 0.8], random_state=42,
scaling=scaling,
selection_threshold=selection_threshold,
memory=tempdir)
feature_scores = clf.fit(X, y).scores_
assert_equal(clf.all_scores_.shape, (X.shape[1], 2))
assert_array_equal(np.argsort(F)[-3:], np.argsort(feature_scores)[-3:])
finally:
shutil.rmtree(tempdir)
X_r = clf.transform(X)
X_full = clf.inverse_transform(X_r)
assert_equal(X_r.shape[1], np.sum(feature_scores > selection_threshold))
assert_equal(X_full.shape, X.shape)
clf = RandomizedLasso(verbose=False, alpha='aic', random_state=42,
scaling=scaling, n_resampling=100)
feature_scores = clf.fit(X, y).scores_
assert_allclose(feature_scores, [1., 1., 1., 0.225, 1.], rtol=0.2)
clf = RandomizedLasso(verbose=False, scaling=-0.1)
assert_raises(ValueError, clf.fit, X, y)
clf = RandomizedLasso(verbose=False, scaling=1.1)
assert_raises(ValueError, clf.fit, X, y)
def test_randomized_lasso_precompute():
# Check randomized lasso for different values of precompute
n_resampling = 20
alpha = 1
random_state = 42
G = np.dot(X.T, X)
clf = RandomizedLasso(alpha=alpha, random_state=random_state,
precompute=G, n_resampling=n_resampling)
feature_scores_1 = clf.fit(X, y).scores_
for precompute in [True, False, None, 'auto']:
clf = RandomizedLasso(alpha=alpha, random_state=random_state,
precompute=precompute, n_resampling=n_resampling)
feature_scores_2 = clf.fit(X, y).scores_
assert_array_equal(feature_scores_1, feature_scores_2)
def test_randomized_logistic():
# Check randomized sparse logistic regression
iris = load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
X = X[y != 2]
y = y[y != 2]
F, _ = f_classif(X, y)
scaling = 0.3
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
X_orig = X.copy()
feature_scores = clf.fit(X, y).scores_
assert_array_equal(X, X_orig) # fit does not modify X
assert_array_equal(np.argsort(F), np.argsort(feature_scores))
clf = RandomizedLogisticRegression(verbose=False, C=[1., 0.5],
random_state=42, scaling=scaling,
n_resampling=50, tol=1e-3)
feature_scores = clf.fit(X, y).scores_
assert_array_equal(np.argsort(F), np.argsort(feature_scores))
clf = RandomizedLogisticRegression(verbose=False, C=[[1., 0.5]])
assert_raises(ValueError, clf.fit, X, y)
def test_randomized_logistic_sparse():
# Check randomized sparse logistic regression on sparse data
iris = load_iris()
X = iris.data[:, [0, 2]]
y = iris.target
X = X[y != 2]
y = y[y != 2]
# center here because sparse matrices are usually not centered
# labels should not be centered
X, _, _, _, _ = _preprocess_data(X, y, True, True)
X_sp = sparse.csr_matrix(X)
F, _ = f_classif(X, y)
scaling = 0.3
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
feature_scores = clf.fit(X, y).scores_
clf = RandomizedLogisticRegression(verbose=False, C=1., random_state=42,
scaling=scaling, n_resampling=50,
tol=1e-3)
feature_scores_sp = clf.fit(X_sp, y).scores_
assert_array_equal(feature_scores, feature_scores_sp)
| Titan-C/scikit-learn | sklearn/linear_model/tests/test_randomized_l1.py | Python | bsd-3-clause | 6,836 |
// 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.
#include "chrome/browser/chromeos/contacts/google_contact_store.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "chrome/browser/chromeos/contacts/contact.pb.h"
#include "chrome/browser/chromeos/contacts/contact_store_observer.h"
#include "chrome/browser/chromeos/contacts/contact_test_util.h"
#include "chrome/browser/chromeos/contacts/fake_contact_database.h"
#include "chrome/browser/chromeos/contacts/gdata_contacts_service_stub.h"
#include "chrome/browser/google_apis/time_util.h"
#include "chrome/test/base/testing_profile.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/test/test_browser_thread.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_request_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
using content::BrowserThread;
namespace contacts {
namespace test {
// ContactStoreObserver implementation that just counts the number of times
// that it's been told that a store has been updated.
class TestContactStoreObserver : public ContactStoreObserver {
public:
TestContactStoreObserver() : num_updates_(0) {}
virtual ~TestContactStoreObserver() {}
int num_updates() const { return num_updates_; }
void reset_stats() { num_updates_ = 0; }
// ContactStoreObserver overrides:
virtual void OnContactsUpdated(ContactStore* store) OVERRIDE {
DCHECK(store);
num_updates_++;
}
private:
// Number of times that OnContactsUpdated() has been called.
int num_updates_;
DISALLOW_COPY_AND_ASSIGN(TestContactStoreObserver);
};
class GoogleContactStoreTest : public testing::Test {
public:
GoogleContactStoreTest() : ui_thread_(BrowserThread::UI, &message_loop_) {}
virtual ~GoogleContactStoreTest() {}
protected:
// testing::Test implementation.
virtual void SetUp() OVERRIDE {
// Create a mock NetworkChangeNotifier so the store won't be notified about
// changes to the system's actual network state.
network_change_notifier_.reset(net::NetworkChangeNotifier::CreateMock());
profile_.reset(new TestingProfile);
store_.reset(new GoogleContactStore(NULL, // request_context_getter
profile_.get()));
store_->AddObserver(&observer_);
test_api_.reset(new GoogleContactStore::TestAPI(store_.get()));
db_ = new FakeContactDatabase;
test_api_->SetDatabase(db_);
gdata_service_ = new GDataContactsServiceStub;
test_api_->SetGDataService(gdata_service_);
}
base::MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
TestContactStoreObserver observer_;
scoped_ptr<net::NetworkChangeNotifier> network_change_notifier_;
scoped_ptr<TestingProfile> profile_;
scoped_ptr<GoogleContactStore> store_;
scoped_ptr<GoogleContactStore::TestAPI> test_api_;
FakeContactDatabase* db_; // not owned
GDataContactsServiceStub* gdata_service_; // not owned
private:
DISALLOW_COPY_AND_ASSIGN(GoogleContactStoreTest);
};
TEST_F(GoogleContactStoreTest, LoadFromDatabase) {
// Store two contacts in the database.
const std::string kContactId1 = "contact1";
const std::string kContactId2 = "contact2";
scoped_ptr<Contact> contact1(new Contact);
InitContact(kContactId1, "1", false, contact1.get());
scoped_ptr<Contact> contact2(new Contact);
InitContact(kContactId2, "2", false, contact2.get());
ContactPointers db_contacts;
db_contacts.push_back(contact1.get());
db_contacts.push_back(contact2.get());
UpdateMetadata db_metadata;
db_->SetContacts(db_contacts, db_metadata);
// Tell the GData service to report failure, initialize the store, and check
// that the contacts from the database are loaded.
gdata_service_->set_download_should_succeed(false);
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(VarContactsToString(2, contact1.get(), contact2.get()),
ContactsToString(loaded_contacts));
EXPECT_TRUE(test_api_->update_scheduled());
EXPECT_EQ(1, observer_.num_updates());
// Check that we can also grab the contact via its ID.
const Contact* loaded_contact1 = store_->GetContactById(kContactId1);
ASSERT_TRUE(loaded_contact1);
EXPECT_EQ(ContactToString(*contact1), ContactToString(*loaded_contact1));
// We should get NULL if we request a nonexistent contact.
EXPECT_FALSE(store_->GetContactById("bogus_id"));
}
TEST_F(GoogleContactStoreTest, LoadFromGData) {
// Store two contacts in the GData service.
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", false, contact2.get());
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact1.get());
gdata_contacts.push_back(contact2.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
// Initialize the store and check that the contacts are loaded from GData.
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(VarContactsToString(2, contact1.get(), contact2.get()),
ContactsToString(loaded_contacts));
EXPECT_TRUE(test_api_->update_scheduled());
EXPECT_EQ(1, observer_.num_updates());
// The contacts should've been saved to the database, too.
EXPECT_EQ(VarContactsToString(2, contact1.get(), contact2.get()),
ContactMapToString(db_->contacts()));
}
TEST_F(GoogleContactStoreTest, UpdateFromGData) {
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", false, contact2.get());
scoped_ptr<Contact> contact3(new Contact);
InitContact("contact3", "3", false, contact3.get());
// Store the first two contacts in the database.
ContactPointers db_contacts;
db_contacts.push_back(contact1.get());
db_contacts.push_back(contact2.get());
UpdateMetadata db_metadata;
db_->SetContacts(db_contacts, db_metadata);
// Store all three in the GData service. We expect the update request to ask
// for all contacts updated one millisecond after the newest contact in the
// database.
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact1.get());
gdata_contacts.push_back(contact2.get());
gdata_contacts.push_back(contact3.get());
gdata_service_->SetContacts(
gdata_contacts,
base::Time::FromInternalValue(contact2->update_time()) +
base::TimeDelta::FromMilliseconds(1));
// Check that the store ends up with all three contacts.
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(VarContactsToString(
3, contact1.get(), contact2.get(), contact3.get()),
ContactsToString(loaded_contacts));
EXPECT_EQ(2, observer_.num_updates());
// All three contacts should've been saved to the database.
EXPECT_EQ(VarContactsToString(
3, contact1.get(), contact2.get(), contact3.get()),
ContactMapToString(db_->contacts()));
EXPECT_EQ(3, db_->num_saved_contacts());
EXPECT_TRUE(test_api_->update_scheduled());
}
TEST_F(GoogleContactStoreTest, FetchUpdatedContacts) {
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", false, contact2.get());
scoped_ptr<Contact> contact3(new Contact);
InitContact("contact3", "3", false, contact3.get());
ContactPointers kAllContacts;
kAllContacts.push_back(contact1.get());
kAllContacts.push_back(contact2.get());
kAllContacts.push_back(contact3.get());
// Tell the GData service to return all three contacts in response to a full
// update.
ContactPointers gdata_contacts(kAllContacts);
gdata_service_->SetContacts(gdata_contacts, base::Time());
// All the contacts should be loaded and saved to the database.
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(kAllContacts), ContactsToString(loaded_contacts));
EXPECT_EQ(ContactsToString(kAllContacts),
ContactMapToString(db_->contacts()));
EXPECT_EQ(static_cast<int>(kAllContacts.size()), db_->num_saved_contacts());
EXPECT_TRUE(test_api_->update_scheduled());
EXPECT_EQ(1, observer_.num_updates());
observer_.reset_stats();
// Update the third contact.
contact3->set_full_name("new full name");
base::Time old_contact3_update_time =
base::Time::FromInternalValue(contact3->update_time());
contact3->set_update_time(
(old_contact3_update_time +
base::TimeDelta::FromSeconds(10)).ToInternalValue());
gdata_contacts.clear();
gdata_contacts.push_back(contact3.get());
gdata_service_->SetContacts(
gdata_contacts,
old_contact3_update_time + base::TimeDelta::FromMilliseconds(1));
// Check that the updated contact is loaded (i.e. the store passed the
// correct minimum update time to the service) and saved back to the database.
db_->reset_stats();
test_api_->DoUpdate();
loaded_contacts.clear();
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(kAllContacts), ContactsToString(loaded_contacts));
EXPECT_EQ(ContactsToString(kAllContacts),
ContactMapToString(db_->contacts()));
EXPECT_EQ(1, db_->num_saved_contacts());
EXPECT_TRUE(test_api_->update_scheduled());
EXPECT_EQ(1, observer_.num_updates());
observer_.reset_stats();
// The next update should be based on the third contact's new update time.
contact3->set_full_name("yet another full name");
gdata_service_->SetContacts(
gdata_contacts,
base::Time::FromInternalValue(contact3->update_time()) +
base::TimeDelta::FromMilliseconds(1));
db_->reset_stats();
test_api_->DoUpdate();
loaded_contacts.clear();
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(kAllContacts), ContactsToString(loaded_contacts));
EXPECT_EQ(ContactsToString(kAllContacts),
ContactMapToString(db_->contacts()));
EXPECT_EQ(1, db_->num_saved_contacts());
EXPECT_TRUE(test_api_->update_scheduled());
EXPECT_EQ(1, observer_.num_updates());
}
TEST_F(GoogleContactStoreTest, DontReturnDeletedContacts) {
// Tell GData to return a single deleted contact.
const std::string kContactId = "contact";
scoped_ptr<Contact> contact(new Contact);
InitContact(kContactId, "1", true, contact.get());
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
// The contact shouldn't be returned by AppendContacts() or
// GetContactById().
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_TRUE(loaded_contacts.empty());
EXPECT_FALSE(store_->GetContactById(kContactId));
}
// Test that we do a full refresh from GData if enough time has passed since the
// last refresh that we might've missed some contact deletions (see
// |kForceFullUpdateDays| in google_contact_store.cc).
TEST_F(GoogleContactStoreTest, FullRefreshAfterThirtyDays) {
base::Time::Exploded kInitTimeExploded = { 2012, 3, 0, 1, 16, 34, 56, 123 };
base::Time kInitTime = base::Time::FromUTCExploded(kInitTimeExploded);
base::Time kOldUpdateTime = kInitTime - base::TimeDelta::FromDays(31);
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
contact1->set_update_time(kOldUpdateTime.ToInternalValue());
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", false, contact2.get());
contact2->set_update_time(kOldUpdateTime.ToInternalValue());
// Put both contacts in the database, along with metadata saying that the last
// successful update was 31 days in the past.
ContactPointers db_contacts;
db_contacts.push_back(contact1.get());
db_contacts.push_back(contact2.get());
UpdateMetadata db_metadata;
db_metadata.set_last_update_start_time(kOldUpdateTime.ToInternalValue());
db_->SetContacts(db_contacts, db_metadata);
// Tell the GData service to return only the first contact and to expect a
// full refresh (since it's been a long time since the last update).
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact1.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
test_api_->set_current_time(kInitTime);
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(gdata_contacts),
ContactsToString(loaded_contacts));
EXPECT_TRUE(test_api_->update_scheduled());
// Make GData return both contacts now in response to an incremental update.
gdata_contacts.clear();
contact2->set_update_time(kInitTime.ToInternalValue());
gdata_contacts.push_back(contact1.get());
gdata_contacts.push_back(contact2.get());
gdata_service_->SetContacts(
gdata_contacts, kOldUpdateTime + base::TimeDelta::FromMilliseconds(1));
// Advance the time by twenty days and check that the update is successful.
base::Time kFirstUpdateTime = kInitTime + base::TimeDelta::FromDays(20);
test_api_->set_current_time(kFirstUpdateTime);
test_api_->DoUpdate();
loaded_contacts.clear();
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(gdata_contacts),
ContactsToString(loaded_contacts));
// After we advance the time by 31 days, we should do a full refresh again.
gdata_contacts.clear();
gdata_contacts.push_back(contact1.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
base::Time kSecondUpdateTime =
kFirstUpdateTime + base::TimeDelta::FromDays(31);
test_api_->set_current_time(kSecondUpdateTime);
test_api_->DoUpdate();
loaded_contacts.clear();
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(gdata_contacts),
ContactsToString(loaded_contacts));
}
TEST_F(GoogleContactStoreTest, HandleDatabaseInitFailure) {
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
// Store a contact in the database but make initialization fail.
ContactPointers db_contacts;
db_contacts.push_back(contact1.get());
UpdateMetadata db_metadata;
db_->SetContacts(db_contacts, db_metadata);
db_->set_init_success(false);
// Create a second contact and tell the GData service to return it.
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", false, contact2.get());
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact2.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
// Initialize the store. We shouldn't get the first contact (since DB
// initialization failed) but we should still fetch the second one from GData
// and schedule an update.
store_->Init();
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(gdata_contacts),
ContactsToString(loaded_contacts));
EXPECT_TRUE(test_api_->update_scheduled());
}
TEST_F(GoogleContactStoreTest, AvoidUpdatesWhenOffline) {
EXPECT_EQ(0, gdata_service_->num_download_requests());
// Notify the store that we're offline. Init() shouldn't attempt an update
// and the update timer shouldn't be running.
test_api_->NotifyAboutNetworkStateChange(false);
store_->Init();
EXPECT_EQ(0, gdata_service_->num_download_requests());
EXPECT_FALSE(test_api_->update_scheduled());
// We should do an update and schedule further updates as soon as we go
// online.
gdata_service_->reset_stats();
test_api_->NotifyAboutNetworkStateChange(true);
EXPECT_EQ(1, gdata_service_->num_download_requests());
EXPECT_TRUE(test_api_->update_scheduled());
// If we call DoUpdate() to mimic the code path that's used for a timer-driven
// update while we're offline, we should again defer the update.
gdata_service_->reset_stats();
test_api_->NotifyAboutNetworkStateChange(false);
test_api_->DoUpdate();
EXPECT_EQ(0, gdata_service_->num_download_requests());
// When we're back online, the update should happen.
gdata_service_->reset_stats();
test_api_->NotifyAboutNetworkStateChange(true);
EXPECT_EQ(1, gdata_service_->num_download_requests());
}
TEST_F(GoogleContactStoreTest, DropDeletedContacts) {
// Tell the GData service to return a single contact.
scoped_ptr<Contact> contact1(new Contact);
InitContact("contact1", "1", false, contact1.get());
ContactPointers gdata_contacts;
gdata_contacts.push_back(contact1.get());
gdata_service_->SetContacts(gdata_contacts, base::Time());
// Check that the contact store loads it into memory and saves it to the
// database.
store_->Init();
EXPECT_EQ(0, gdata_service_->num_download_requests_with_wrong_timestamps());
EXPECT_EQ(base::Time::FromInternalValue(contact1->update_time()),
test_api_->last_contact_update_time());
EXPECT_EQ(VarContactsToString(1, contact1.get()),
ContactsToString(*test_api_->GetLoadedContacts()));
EXPECT_EQ(VarContactsToString(1, contact1.get()),
ContactMapToString(db_->contacts()));
EXPECT_EQ(contact1->update_time(),
db_->metadata().last_contact_update_time());
EXPECT_TRUE(test_api_->update_scheduled());
// Now tell the GData service to return a more-newly-updated, already deleted
// contact.
scoped_ptr<Contact> contact2(new Contact);
InitContact("contact2", "2", true, contact2.get());
contact2->set_update_time(
(base::Time::FromInternalValue(contact1->update_time()) +
base::TimeDelta::FromSeconds(5)).ToInternalValue());
gdata_contacts.clear();
gdata_contacts.push_back(contact2.get());
gdata_service_->SetContacts(
gdata_contacts,
base::Time::FromInternalValue(contact1->update_time()) +
base::TimeDelta::FromMilliseconds(1));
// The contact store should save the last update time from the deleted
// contact, but the contact itself shouldn't be loaded into memory or written
// to the database.
test_api_->DoUpdate();
EXPECT_EQ(0, gdata_service_->num_download_requests_with_wrong_timestamps());
EXPECT_EQ(base::Time::FromInternalValue(contact2->update_time()),
test_api_->last_contact_update_time());
EXPECT_EQ(VarContactsToString(1, contact1.get()),
ContactsToString(*test_api_->GetLoadedContacts()));
EXPECT_EQ(VarContactsToString(1, contact1.get()),
ContactMapToString(db_->contacts()));
EXPECT_EQ(contact2->update_time(),
db_->metadata().last_contact_update_time());
// Tell the GData service to report the first contact as having been deleted.
contact1->set_update_time(
(base::Time::FromInternalValue(contact2->update_time()) +
base::TimeDelta::FromSeconds(10)).ToInternalValue());
contact1->set_deleted(true);
gdata_contacts.clear();
gdata_contacts.push_back(contact1.get());
gdata_service_->SetContacts(
gdata_contacts,
base::Time::FromInternalValue(contact2->update_time()) +
base::TimeDelta::FromMilliseconds(1));
// The contact store should drop the first contact after another update.
test_api_->DoUpdate();
EXPECT_EQ(0, gdata_service_->num_download_requests_with_wrong_timestamps());
EXPECT_EQ(base::Time::FromInternalValue(contact1->update_time()),
test_api_->last_contact_update_time());
EXPECT_TRUE(test_api_->GetLoadedContacts()->empty());
EXPECT_TRUE(db_->contacts().empty());
EXPECT_EQ(contact1->update_time(),
db_->metadata().last_contact_update_time());
}
TEST_F(GoogleContactStoreTest, UseLastContactUpdateTimeFromMetadata) {
base::Time::Exploded kInitTimeExploded = { 2012, 3, 0, 1, 16, 34, 56, 123 };
base::Time kInitTime = base::Time::FromUTCExploded(kInitTimeExploded);
// Configure the metadata to say that a contact was updated one day before the
// current time. We won't create a contact that actually contains this time,
// though; this mimics the situation where the most-recently-updated contact
// has been deleted and wasn't saved to the database.
base::Time kDeletedContactUpdateTime =
kInitTime - base::TimeDelta::FromDays(1);
UpdateMetadata db_metadata;
db_metadata.set_last_contact_update_time(
kDeletedContactUpdateTime.ToInternalValue());
// Create a non-deleted contact with an update time one day prior to the
// update time in the metadata.
base::Time kNonDeletedContactUpdateTime =
kDeletedContactUpdateTime - base::TimeDelta::FromDays(1);
scoped_ptr<Contact> non_deleted_contact(new Contact);
InitContact("contact", "1", false, non_deleted_contact.get());
non_deleted_contact->set_update_time(
kNonDeletedContactUpdateTime.ToInternalValue());
// Save the contact to the database.
ContactPointers db_contacts;
db_contacts.push_back(non_deleted_contact.get());
db_->SetContacts(db_contacts, db_metadata);
// Tell the GData service to expect the deleted contact's update time.
ContactPointers gdata_contacts;
gdata_contacts.push_back(non_deleted_contact.get());
gdata_service_->SetContacts(
gdata_contacts,
kDeletedContactUpdateTime + base::TimeDelta::FromMilliseconds(1));
test_api_->set_current_time(kInitTime);
store_->Init();
EXPECT_EQ(0, gdata_service_->num_download_requests_with_wrong_timestamps());
ContactPointers loaded_contacts;
store_->AppendContacts(&loaded_contacts);
EXPECT_EQ(ContactsToString(gdata_contacts),
ContactsToString(loaded_contacts));
EXPECT_TRUE(test_api_->update_scheduled());
}
} // namespace test
} // namespace contacts
| windyuuy/opera | chromium/src/chrome/browser/chromeos/contacts/google_contact_store_unittest.cc | C++ | bsd-3-clause | 21,882 |
// Copyright 2015 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.
#ifndef CONTENT_RENDERER_ANDROID_SYNCHRONOUS_COMPOSITOR_PROXY_H_
#define CONTENT_RENDERER_ANDROID_SYNCHRONOUS_COMPOSITOR_PROXY_H_
#include <stddef.h>
#include <stdint.h>
#include "base/macros.h"
#include "content/common/input/input_event_ack_state.h"
#include "content/renderer/android/synchronous_compositor_external_begin_frame_source.h"
#include "content/renderer/android/synchronous_compositor_output_surface.h"
#include "content/renderer/input/input_handler_manager_client.h"
#include "ui/events/blink/synchronous_input_handler_proxy.h"
#include "ui/gfx/geometry/scroll_offset.h"
#include "ui/gfx/geometry/size_f.h"
namespace IPC {
class Message;
class Sender;
} // namespace IPC
namespace blink {
class WebInputEvent;
} // namespace blink
namespace cc {
class CompositorFrame;
} // namespace cc
namespace content {
class SynchronousCompositorOutputSurface;
struct SyncCompositorCommonBrowserParams;
struct SyncCompositorCommonRendererParams;
struct SyncCompositorDemandDrawHwParams;
struct SyncCompositorDemandDrawSwParams;
struct SyncCompositorSetSharedMemoryParams;
class SynchronousCompositorProxy
: public ui::SynchronousInputHandler,
public SynchronousCompositorExternalBeginFrameSourceClient,
public SynchronousCompositorOutputSurfaceClient {
public:
SynchronousCompositorProxy(
int routing_id,
IPC::Sender* sender,
SynchronousCompositorOutputSurface* output_surface,
SynchronousCompositorExternalBeginFrameSource* begin_frame_source,
ui::SynchronousInputHandlerProxy* input_handler_proxy,
InputHandlerManagerClient::Handler* handler);
~SynchronousCompositorProxy() override;
// ui::SynchronousInputHandler overrides.
void SetNeedsSynchronousAnimateInput() override;
void UpdateRootLayerState(const gfx::ScrollOffset& total_scroll_offset,
const gfx::ScrollOffset& max_scroll_offset,
const gfx::SizeF& scrollable_size,
float page_scale_factor,
float min_page_scale_factor,
float max_page_scale_factor) override;
// SynchronousCompositorExternalBeginFrameSourceClient overrides.
void OnNeedsBeginFramesChange(bool needs_begin_frames) override;
// SynchronousCompositorOutputSurfaceClient overrides.
void Invalidate() override;
void SwapBuffers(cc::CompositorFrame* frame) override;
void OnMessageReceived(const IPC::Message& message);
bool Send(IPC::Message* message);
void DidOverscroll(const DidOverscrollParams& did_overscroll_params);
private:
struct SharedMemoryWithSize;
void ProcessCommonParams(
const SyncCompositorCommonBrowserParams& common_params);
void PopulateCommonParams(SyncCompositorCommonRendererParams* params);
// IPC handlers.
void HandleInputEvent(
const SyncCompositorCommonBrowserParams& common_params,
const blink::WebInputEvent* event,
SyncCompositorCommonRendererParams* common_renderer_params,
InputEventAckState* ack);
void BeginFrame(const SyncCompositorCommonBrowserParams& common_params,
const cc::BeginFrameArgs& args,
SyncCompositorCommonRendererParams* common_renderer_params);
void OnComputeScroll(
const SyncCompositorCommonBrowserParams& common_params,
base::TimeTicks animation_time,
SyncCompositorCommonRendererParams* common_renderer_params);
void DemandDrawHw(const SyncCompositorCommonBrowserParams& common_params,
const SyncCompositorDemandDrawHwParams& params,
IPC::Message* reply_message);
void SetSharedMemory(
const SyncCompositorCommonBrowserParams& common_params,
const SyncCompositorSetSharedMemoryParams& params,
bool* success,
SyncCompositorCommonRendererParams* common_renderer_params);
void ZeroSharedMemory();
void DemandDrawSw(const SyncCompositorCommonBrowserParams& common_params,
const SyncCompositorDemandDrawSwParams& params,
IPC::Message* reply_message);
void SwapBuffersHw(cc::CompositorFrame* frame);
void SendDemandDrawHwReply(cc::CompositorFrame* frame,
IPC::Message* reply_message);
void DoDemandDrawSw(const SyncCompositorDemandDrawSwParams& params);
void SwapBuffersSw(cc::CompositorFrame* frame);
void SendDemandDrawSwReply(bool success,
cc::CompositorFrame* frame,
IPC::Message* reply_message);
void DidActivatePendingTree();
void DeliverMessages();
void SendAsyncRendererStateIfNeeded();
const int routing_id_;
IPC::Sender* const sender_;
SynchronousCompositorOutputSurface* const output_surface_;
SynchronousCompositorExternalBeginFrameSource* const begin_frame_source_;
ui::SynchronousInputHandlerProxy* const input_handler_proxy_;
InputHandlerManagerClient::Handler* const input_handler_;
bool inside_receive_;
IPC::Message* hardware_draw_reply_;
IPC::Message* software_draw_reply_;
// From browser.
size_t bytes_limit_;
scoped_ptr<SharedMemoryWithSize> software_draw_shm_;
// To browser.
uint32_t version_;
gfx::ScrollOffset total_scroll_offset_; // Modified by both.
gfx::ScrollOffset max_scroll_offset_;
gfx::SizeF scrollable_size_;
float page_scale_factor_;
float min_page_scale_factor_;
float max_page_scale_factor_;
bool need_animate_scroll_;
bool need_invalidate_;
bool need_begin_frame_;
bool did_activate_pending_tree_;
DISALLOW_COPY_AND_ASSIGN(SynchronousCompositorProxy);
};
} // namespace content
#endif // CONTENT_RENDERER_ANDROID_SYNCHRONOUS_COMPOSITOR_PROXY_H_
| js0701/chromium-crosswalk | content/renderer/android/synchronous_compositor_proxy.h | C | bsd-3-clause | 5,839 |
// 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 "ui/gfx/render_text_harfbuzz.h"
#include <limits>
#include <map>
#include "base/i18n/bidi_line_iterator.h"
#include "base/i18n/break_iterator.h"
#include "base/i18n/char_iterator.h"
#include "base/lazy_instance.h"
#include "third_party/harfbuzz-ng/src/hb.h"
#include "third_party/icu/source/common/unicode/ubidi.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkTypeface.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/font_fallback.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/utf16_indexing.h"
#if defined(OS_WIN)
#include "ui/gfx/font_fallback_win.h"
#endif
namespace gfx {
namespace {
// The maximum number of scripts a Unicode character can belong to. This value
// is arbitrarily chosen to be a good limit because it is unlikely for a single
// character to belong to more scripts.
const size_t kMaxScripts = 5;
// Maps from code points to glyph indices in a font.
typedef std::map<uint32_t, uint16_t> GlyphCache;
// Font data provider for HarfBuzz using Skia. Copied from Blink.
// TODO(ckocagil): Eliminate the duplication. http://crbug.com/368375
struct FontData {
FontData(GlyphCache* glyph_cache) : glyph_cache_(glyph_cache) {}
SkPaint paint_;
GlyphCache* glyph_cache_;
};
hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value) {
return SkScalarToFixed(value);
}
// Deletes the object at the given pointer after casting it to the given type.
template<typename Type>
void DeleteByType(void* data) {
Type* typed_data = reinterpret_cast<Type*>(data);
delete typed_data;
}
template<typename Type>
void DeleteArrayByType(void* data) {
Type* typed_data = reinterpret_cast<Type*>(data);
delete[] typed_data;
}
// Outputs the |width| and |extents| of the glyph with index |codepoint| in
// |paint|'s font.
void GetGlyphWidthAndExtents(SkPaint* paint,
hb_codepoint_t codepoint,
hb_position_t* width,
hb_glyph_extents_t* extents) {
DCHECK_LE(codepoint, 0xFFFFU);
paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
SkScalar sk_width;
SkRect sk_bounds;
uint16_t glyph = codepoint;
paint->getTextWidths(&glyph, sizeof(glyph), &sk_width, &sk_bounds);
if (width)
*width = SkiaScalarToHarfBuzzPosition(sk_width);
if (extents) {
// Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be
// y-grows-up.
extents->x_bearing = SkiaScalarToHarfBuzzPosition(sk_bounds.fLeft);
extents->y_bearing = SkiaScalarToHarfBuzzPosition(-sk_bounds.fTop);
extents->width = SkiaScalarToHarfBuzzPosition(sk_bounds.width());
extents->height = SkiaScalarToHarfBuzzPosition(-sk_bounds.height());
}
}
// Writes the |glyph| index for the given |unicode| code point. Returns whether
// the glyph exists, i.e. it is not a missing glyph.
hb_bool_t GetGlyph(hb_font_t* font,
void* data,
hb_codepoint_t unicode,
hb_codepoint_t variation_selector,
hb_codepoint_t* glyph,
void* user_data) {
FontData* font_data = reinterpret_cast<FontData*>(data);
GlyphCache* cache = font_data->glyph_cache_;
bool exists = cache->count(unicode) != 0;
if (!exists) {
SkPaint* paint = &font_data->paint_;
paint->setTextEncoding(SkPaint::kUTF32_TextEncoding);
paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &(*cache)[unicode]);
}
*glyph = (*cache)[unicode];
return !!*glyph;
}
// Returns the horizontal advance value of the |glyph|.
hb_position_t GetGlyphHorizontalAdvance(hb_font_t* font,
void* data,
hb_codepoint_t glyph,
void* user_data) {
FontData* font_data = reinterpret_cast<FontData*>(data);
hb_position_t advance = 0;
GetGlyphWidthAndExtents(&font_data->paint_, glyph, &advance, 0);
return advance;
}
hb_bool_t GetGlyphHorizontalOrigin(hb_font_t* font,
void* data,
hb_codepoint_t glyph,
hb_position_t* x,
hb_position_t* y,
void* user_data) {
// Just return true, like the HarfBuzz-FreeType implementation.
return true;
}
hb_position_t GetGlyphKerning(FontData* font_data,
hb_codepoint_t first_glyph,
hb_codepoint_t second_glyph) {
SkTypeface* typeface = font_data->paint_.getTypeface();
const uint16_t glyphs[2] = { static_cast<uint16_t>(first_glyph),
static_cast<uint16_t>(second_glyph) };
int32_t kerning_adjustments[1] = { 0 };
if (!typeface->getKerningPairAdjustments(glyphs, 2, kerning_adjustments))
return 0;
SkScalar upm = SkIntToScalar(typeface->getUnitsPerEm());
SkScalar size = font_data->paint_.getTextSize();
return SkiaScalarToHarfBuzzPosition(
SkScalarMulDiv(SkIntToScalar(kerning_adjustments[0]), size, upm));
}
hb_position_t GetGlyphHorizontalKerning(hb_font_t* font,
void* data,
hb_codepoint_t left_glyph,
hb_codepoint_t right_glyph,
void* user_data) {
FontData* font_data = reinterpret_cast<FontData*>(data);
if (font_data->paint_.isVerticalText()) {
// We don't support cross-stream kerning.
return 0;
}
return GetGlyphKerning(font_data, left_glyph, right_glyph);
}
hb_position_t GetGlyphVerticalKerning(hb_font_t* font,
void* data,
hb_codepoint_t top_glyph,
hb_codepoint_t bottom_glyph,
void* user_data) {
FontData* font_data = reinterpret_cast<FontData*>(data);
if (!font_data->paint_.isVerticalText()) {
// We don't support cross-stream kerning.
return 0;
}
return GetGlyphKerning(font_data, top_glyph, bottom_glyph);
}
// Writes the |extents| of |glyph|.
hb_bool_t GetGlyphExtents(hb_font_t* font,
void* data,
hb_codepoint_t glyph,
hb_glyph_extents_t* extents,
void* user_data) {
FontData* font_data = reinterpret_cast<FontData*>(data);
GetGlyphWidthAndExtents(&font_data->paint_, glyph, 0, extents);
return true;
}
class FontFuncs {
public:
FontFuncs() : font_funcs_(hb_font_funcs_create()) {
hb_font_funcs_set_glyph_func(font_funcs_, GetGlyph, 0, 0);
hb_font_funcs_set_glyph_h_advance_func(
font_funcs_, GetGlyphHorizontalAdvance, 0, 0);
hb_font_funcs_set_glyph_h_kerning_func(
font_funcs_, GetGlyphHorizontalKerning, 0, 0);
hb_font_funcs_set_glyph_h_origin_func(
font_funcs_, GetGlyphHorizontalOrigin, 0, 0);
hb_font_funcs_set_glyph_v_kerning_func(
font_funcs_, GetGlyphVerticalKerning, 0, 0);
hb_font_funcs_set_glyph_extents_func(
font_funcs_, GetGlyphExtents, 0, 0);
hb_font_funcs_make_immutable(font_funcs_);
}
~FontFuncs() {
hb_font_funcs_destroy(font_funcs_);
}
hb_font_funcs_t* get() { return font_funcs_; }
private:
hb_font_funcs_t* font_funcs_;
DISALLOW_COPY_AND_ASSIGN(FontFuncs);
};
base::LazyInstance<FontFuncs>::Leaky g_font_funcs = LAZY_INSTANCE_INITIALIZER;
// Returns the raw data of the font table |tag|.
hb_blob_t* GetFontTable(hb_face_t* face, hb_tag_t tag, void* user_data) {
SkTypeface* typeface = reinterpret_cast<SkTypeface*>(user_data);
const size_t table_size = typeface->getTableSize(tag);
if (!table_size)
return 0;
scoped_ptr<char[]> buffer(new char[table_size]);
if (!buffer)
return 0;
size_t actual_size = typeface->getTableData(tag, 0, table_size, buffer.get());
if (table_size != actual_size)
return 0;
char* buffer_raw = buffer.release();
return hb_blob_create(buffer_raw, table_size, HB_MEMORY_MODE_WRITABLE,
buffer_raw, DeleteArrayByType<char>);
}
void UnrefSkTypeface(void* data) {
SkTypeface* skia_face = reinterpret_cast<SkTypeface*>(data);
SkSafeUnref(skia_face);
}
// Wrapper class for a HarfBuzz face created from a given Skia face.
class HarfBuzzFace {
public:
HarfBuzzFace() : face_(NULL) {}
~HarfBuzzFace() {
if (face_)
hb_face_destroy(face_);
}
void Init(SkTypeface* skia_face) {
SkSafeRef(skia_face);
face_ = hb_face_create_for_tables(GetFontTable, skia_face, UnrefSkTypeface);
DCHECK(face_);
}
hb_face_t* get() {
return face_;
}
private:
hb_face_t* face_;
};
// Creates a HarfBuzz font from the given Skia face and text size.
hb_font_t* CreateHarfBuzzFont(SkTypeface* skia_face, int text_size) {
typedef std::pair<HarfBuzzFace, GlyphCache> FaceCache;
// TODO(ckocagil): This shouldn't grow indefinitely. Maybe use base::MRUCache?
static std::map<SkFontID, FaceCache> face_caches;
FaceCache* face_cache = &face_caches[skia_face->uniqueID()];
if (face_cache->first.get() == NULL)
face_cache->first.Init(skia_face);
hb_font_t* harfbuzz_font = hb_font_create(face_cache->first.get());
const int scale = SkScalarToFixed(text_size);
hb_font_set_scale(harfbuzz_font, scale, scale);
FontData* hb_font_data = new FontData(&face_cache->second);
hb_font_data->paint_.setTypeface(skia_face);
hb_font_data->paint_.setTextSize(text_size);
hb_font_set_funcs(harfbuzz_font, g_font_funcs.Get().get(), hb_font_data,
DeleteByType<FontData>);
hb_font_make_immutable(harfbuzz_font);
return harfbuzz_font;
}
// Returns true if characters of |block_code| may trigger font fallback.
bool IsUnusualBlockCode(UBlockCode block_code) {
return block_code == UBLOCK_GEOMETRIC_SHAPES ||
block_code == UBLOCK_MISCELLANEOUS_SYMBOLS;
}
// Returns the index of the first unusual character after a usual character or
// vice versa. Unusual characters are defined by |IsUnusualBlockCode|.
size_t FindUnusualCharacter(const base::string16& text,
size_t run_start,
size_t run_break) {
const int32 run_length = static_cast<int32>(run_break - run_start);
base::i18n::UTF16CharIterator iter(text.c_str() + run_start,
run_length);
const UBlockCode first_block_code = ublock_getCode(iter.get());
const bool first_block_unusual = IsUnusualBlockCode(first_block_code);
while (iter.Advance() && iter.array_pos() < run_length) {
const UBlockCode current_block_code = ublock_getCode(iter.get());
if (current_block_code != first_block_code &&
(first_block_unusual || IsUnusualBlockCode(current_block_code))) {
return run_start + iter.array_pos();
}
}
return run_break;
}
// If the given scripts match, returns the one that isn't USCRIPT_COMMON or
// USCRIPT_INHERITED, i.e. the more specific one. Otherwise returns
// USCRIPT_INVALID_CODE.
UScriptCode ScriptIntersect(UScriptCode first, UScriptCode second) {
if (first == second ||
(second > USCRIPT_INVALID_CODE && second <= USCRIPT_INHERITED)) {
return first;
}
if (first > USCRIPT_INVALID_CODE && first <= USCRIPT_INHERITED)
return second;
return USCRIPT_INVALID_CODE;
}
// Writes the script and the script extensions of the character with the
// Unicode |codepoint|. Returns the number of written scripts.
int GetScriptExtensions(UChar32 codepoint, UScriptCode* scripts) {
UErrorCode icu_error = U_ZERO_ERROR;
// ICU documentation incorrectly states that the result of
// |uscript_getScriptExtensions| will contain the regular script property.
// Write the character's script property to the first element.
scripts[0] = uscript_getScript(codepoint, &icu_error);
if (U_FAILURE(icu_error))
return 0;
// Fill the rest of |scripts| with the extensions.
int count = uscript_getScriptExtensions(codepoint, scripts + 1,
kMaxScripts - 1, &icu_error);
if (U_FAILURE(icu_error))
count = 0;
return count + 1;
}
// Intersects the script extensions set of |codepoint| with |result| and writes
// to |result|, reading and updating |result_size|.
void ScriptSetIntersect(UChar32 codepoint,
UScriptCode* result,
size_t* result_size) {
UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
int count = GetScriptExtensions(codepoint, scripts);
size_t out_size = 0;
for (size_t i = 0; i < *result_size; ++i) {
for (int j = 0; j < count; ++j) {
UScriptCode intersection = ScriptIntersect(result[i], scripts[j]);
if (intersection != USCRIPT_INVALID_CODE) {
result[out_size++] = intersection;
break;
}
}
}
*result_size = out_size;
}
// Find the longest sequence of characters from 0 and up to |length| that
// have at least one common UScriptCode value. Writes the common script value to
// |script| and returns the length of the sequence. Takes the characters' script
// extensions into account. http://www.unicode.org/reports/tr24/#ScriptX
//
// Consider 3 characters with the script values {Kana}, {Hira, Kana}, {Kana}.
// Without script extensions only the first script in each set would be taken
// into account, resulting in 3 runs where 1 would be enough.
// TODO(ckocagil): Write a unit test for the case above.
int ScriptInterval(const base::string16& text,
size_t start,
size_t length,
UScriptCode* script) {
DCHECK_GT(length, 0U);
UScriptCode scripts[kMaxScripts] = { USCRIPT_INVALID_CODE };
base::i18n::UTF16CharIterator char_iterator(text.c_str() + start, length);
size_t scripts_size = GetScriptExtensions(char_iterator.get(), scripts);
*script = scripts[0];
while (char_iterator.Advance()) {
ScriptSetIntersect(char_iterator.get(), scripts, &scripts_size);
if (scripts_size == 0U)
return char_iterator.array_pos();
*script = scripts[0];
}
return length;
}
// A port of hb_icu_script_to_script because harfbuzz on CrOS is built without
// hb-icu. See http://crbug.com/356929
inline hb_script_t ICUScriptToHBScript(UScriptCode script) {
if (script == USCRIPT_INVALID_CODE)
return HB_SCRIPT_INVALID;
return hb_script_from_string(uscript_getShortName(script), -1);
}
// Helper template function for |TextRunHarfBuzz::GetClusterAt()|. |Iterator|
// can be a forward or reverse iterator type depending on the text direction.
template <class Iterator>
void GetClusterAtImpl(size_t pos,
Range range,
Iterator elements_begin,
Iterator elements_end,
bool reversed,
Range* chars,
Range* glyphs) {
Iterator element = std::upper_bound(elements_begin, elements_end, pos);
chars->set_end(element == elements_end ? range.end() : *element);
glyphs->set_end(reversed ? elements_end - element : element - elements_begin);
DCHECK(element != elements_begin);
while (--element != elements_begin && *element == *(element - 1));
chars->set_start(*element);
glyphs->set_start(
reversed ? elements_end - element : element - elements_begin);
if (reversed)
*glyphs = Range(glyphs->end(), glyphs->start());
DCHECK(!chars->is_reversed());
DCHECK(!chars->is_empty());
DCHECK(!glyphs->is_reversed());
DCHECK(!glyphs->is_empty());
}
} // namespace
namespace internal {
TextRunHarfBuzz::TextRunHarfBuzz()
: width(0.0f),
preceding_run_widths(0.0f),
is_rtl(false),
level(0),
script(USCRIPT_INVALID_CODE),
glyph_count(static_cast<size_t>(-1)),
font_size(0),
font_style(0),
strike(false),
diagonal_strike(false),
underline(false) {}
TextRunHarfBuzz::~TextRunHarfBuzz() {}
void TextRunHarfBuzz::GetClusterAt(size_t pos,
Range* chars,
Range* glyphs) const {
DCHECK(range.Contains(Range(pos, pos + 1)));
DCHECK(chars);
DCHECK(glyphs);
if (glyph_count == 0) {
*chars = range;
*glyphs = Range();
return;
}
if (is_rtl) {
GetClusterAtImpl(pos, range, glyph_to_char.rbegin(), glyph_to_char.rend(),
true, chars, glyphs);
return;
}
GetClusterAtImpl(pos, range, glyph_to_char.begin(), glyph_to_char.end(),
false, chars, glyphs);
}
Range TextRunHarfBuzz::CharRangeToGlyphRange(const Range& char_range) const {
DCHECK(range.Contains(char_range));
DCHECK(!char_range.is_reversed());
DCHECK(!char_range.is_empty());
Range start_glyphs;
Range end_glyphs;
Range temp_range;
GetClusterAt(char_range.start(), &temp_range, &start_glyphs);
GetClusterAt(char_range.end() - 1, &temp_range, &end_glyphs);
return is_rtl ? Range(end_glyphs.start(), start_glyphs.end()) :
Range(start_glyphs.start(), end_glyphs.end());
}
size_t TextRunHarfBuzz::CountMissingGlyphs() const {
static const int kMissingGlyphId = 0;
size_t missing = 0;
for (size_t i = 0; i < glyph_count; ++i)
missing += (glyphs[i] == kMissingGlyphId) ? 1 : 0;
return missing;
}
Range TextRunHarfBuzz::GetGraphemeBounds(
base::i18n::BreakIterator* grapheme_iterator,
size_t text_index) {
DCHECK_LT(text_index, range.end());
// TODO(msw): Support floating point grapheme bounds.
const int preceding_run_widths_int = SkScalarRoundToInt(preceding_run_widths);
if (glyph_count == 0)
return Range(preceding_run_widths_int, preceding_run_widths_int + width);
Range chars;
Range glyphs;
GetClusterAt(text_index, &chars, &glyphs);
const int cluster_begin_x = SkScalarRoundToInt(positions[glyphs.start()].x());
const int cluster_end_x = glyphs.end() < glyph_count ?
SkScalarRoundToInt(positions[glyphs.end()].x()) : width;
// A cluster consists of a number of code points and corresponds to a number
// of glyphs that should be drawn together. A cluster can contain multiple
// graphemes. In order to place the cursor at a grapheme boundary inside the
// cluster, we simply divide the cluster width by the number of graphemes.
if (chars.length() > 1 && grapheme_iterator) {
int before = 0;
int total = 0;
for (size_t i = chars.start(); i < chars.end(); ++i) {
if (grapheme_iterator->IsGraphemeBoundary(i)) {
if (i < text_index)
++before;
++total;
}
}
DCHECK_GT(total, 0);
if (total > 1) {
if (is_rtl)
before = total - before - 1;
DCHECK_GE(before, 0);
DCHECK_LT(before, total);
const int cluster_width = cluster_end_x - cluster_begin_x;
const int grapheme_begin_x = cluster_begin_x + static_cast<int>(0.5f +
cluster_width * before / static_cast<float>(total));
const int grapheme_end_x = cluster_begin_x + static_cast<int>(0.5f +
cluster_width * (before + 1) / static_cast<float>(total));
return Range(preceding_run_widths_int + grapheme_begin_x,
preceding_run_widths_int + grapheme_end_x);
}
}
return Range(preceding_run_widths_int + cluster_begin_x,
preceding_run_widths_int + cluster_end_x);
}
} // namespace internal
RenderTextHarfBuzz::RenderTextHarfBuzz()
: RenderText(),
needs_layout_(false) {}
RenderTextHarfBuzz::~RenderTextHarfBuzz() {}
Size RenderTextHarfBuzz::GetStringSize() {
const SizeF size_f = GetStringSizeF();
return Size(std::ceil(size_f.width()), size_f.height());
}
SizeF RenderTextHarfBuzz::GetStringSizeF() {
EnsureLayout();
return lines()[0].size;
}
SelectionModel RenderTextHarfBuzz::FindCursorPosition(const Point& point) {
EnsureLayout();
int x = ToTextPoint(point).x();
int offset = 0;
size_t run_index = GetRunContainingXCoord(x, &offset);
if (run_index >= runs_.size())
return EdgeSelectionModel((x < 0) ? CURSOR_LEFT : CURSOR_RIGHT);
const internal::TextRunHarfBuzz& run = *runs_[run_index];
for (size_t i = 0; i < run.glyph_count; ++i) {
const SkScalar end =
i + 1 == run.glyph_count ? run.width : run.positions[i + 1].x();
const SkScalar middle = (end + run.positions[i].x()) / 2;
if (offset < middle) {
return SelectionModel(LayoutIndexToTextIndex(
run.glyph_to_char[i] + (run.is_rtl ? 1 : 0)),
(run.is_rtl ? CURSOR_BACKWARD : CURSOR_FORWARD));
}
if (offset < end) {
return SelectionModel(LayoutIndexToTextIndex(
run.glyph_to_char[i] + (run.is_rtl ? 0 : 1)),
(run.is_rtl ? CURSOR_FORWARD : CURSOR_BACKWARD));
}
}
return EdgeSelectionModel(CURSOR_RIGHT);
}
std::vector<RenderText::FontSpan> RenderTextHarfBuzz::GetFontSpansForTesting() {
NOTIMPLEMENTED();
return std::vector<RenderText::FontSpan>();
}
Range RenderTextHarfBuzz::GetGlyphBounds(size_t index) {
EnsureLayout();
const size_t run_index =
GetRunContainingCaret(SelectionModel(index, CURSOR_FORWARD));
// Return edge bounds if the index is invalid or beyond the layout text size.
if (run_index >= runs_.size())
return Range(GetStringSize().width());
const size_t layout_index = TextIndexToLayoutIndex(index);
internal::TextRunHarfBuzz* run = runs_[run_index];
Range bounds = run->GetGraphemeBounds(grapheme_iterator_.get(), layout_index);
return run->is_rtl ? Range(bounds.end(), bounds.start()) : bounds;
}
int RenderTextHarfBuzz::GetLayoutTextBaseline() {
EnsureLayout();
return lines()[0].baseline;
}
SelectionModel RenderTextHarfBuzz::AdjacentCharSelectionModel(
const SelectionModel& selection,
VisualCursorDirection direction) {
DCHECK(!needs_layout_);
internal::TextRunHarfBuzz* run;
size_t run_index = GetRunContainingCaret(selection);
if (run_index >= runs_.size()) {
// The cursor is not in any run: we're at the visual and logical edge.
SelectionModel edge = EdgeSelectionModel(direction);
if (edge.caret_pos() == selection.caret_pos())
return edge;
int visual_index = (direction == CURSOR_RIGHT) ? 0 : runs_.size() - 1;
run = runs_[visual_to_logical_[visual_index]];
} else {
// If the cursor is moving within the current run, just move it by one
// grapheme in the appropriate direction.
run = runs_[run_index];
size_t caret = selection.caret_pos();
bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
if (forward_motion) {
if (caret < LayoutIndexToTextIndex(run->range.end())) {
caret = IndexOfAdjacentGrapheme(caret, CURSOR_FORWARD);
return SelectionModel(caret, CURSOR_BACKWARD);
}
} else {
if (caret > LayoutIndexToTextIndex(run->range.start())) {
caret = IndexOfAdjacentGrapheme(caret, CURSOR_BACKWARD);
return SelectionModel(caret, CURSOR_FORWARD);
}
}
// The cursor is at the edge of a run; move to the visually adjacent run.
int visual_index = logical_to_visual_[run_index];
visual_index += (direction == CURSOR_LEFT) ? -1 : 1;
if (visual_index < 0 || visual_index >= static_cast<int>(runs_.size()))
return EdgeSelectionModel(direction);
run = runs_[visual_to_logical_[visual_index]];
}
bool forward_motion = run->is_rtl == (direction == CURSOR_LEFT);
return forward_motion ? FirstSelectionModelInsideRun(run) :
LastSelectionModelInsideRun(run);
}
SelectionModel RenderTextHarfBuzz::AdjacentWordSelectionModel(
const SelectionModel& selection,
VisualCursorDirection direction) {
if (obscured())
return EdgeSelectionModel(direction);
base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD);
bool success = iter.Init();
DCHECK(success);
if (!success)
return selection;
// Match OS specific word break behavior.
#if defined(OS_WIN)
size_t pos;
if (direction == CURSOR_RIGHT) {
pos = std::min(selection.caret_pos() + 1, text().length());
while (iter.Advance()) {
pos = iter.pos();
if (iter.IsWord() && pos > selection.caret_pos())
break;
}
} else { // direction == CURSOR_LEFT
// Notes: We always iterate words from the beginning.
// This is probably fast enough for our usage, but we may
// want to modify WordIterator so that it can start from the
// middle of string and advance backwards.
pos = std::max<int>(selection.caret_pos() - 1, 0);
while (iter.Advance()) {
if (iter.IsWord()) {
size_t begin = iter.pos() - iter.GetString().length();
if (begin == selection.caret_pos()) {
// The cursor is at the beginning of a word.
// Move to previous word.
break;
} else if (iter.pos() >= selection.caret_pos()) {
// The cursor is in the middle or at the end of a word.
// Move to the top of current word.
pos = begin;
break;
}
pos = iter.pos() - iter.GetString().length();
}
}
}
return SelectionModel(pos, CURSOR_FORWARD);
#else
SelectionModel cur(selection);
for (;;) {
cur = AdjacentCharSelectionModel(cur, direction);
size_t run = GetRunContainingCaret(cur);
if (run == runs_.size())
break;
const bool is_forward = runs_[run]->is_rtl == (direction == CURSOR_LEFT);
size_t cursor = cur.caret_pos();
if (is_forward ? iter.IsEndOfWord(cursor) : iter.IsStartOfWord(cursor))
break;
}
return cur;
#endif
}
std::vector<Rect> RenderTextHarfBuzz::GetSubstringBounds(const Range& range) {
DCHECK(!needs_layout_);
DCHECK(Range(0, text().length()).Contains(range));
Range layout_range(TextIndexToLayoutIndex(range.start()),
TextIndexToLayoutIndex(range.end()));
DCHECK(Range(0, GetLayoutText().length()).Contains(layout_range));
std::vector<Rect> rects;
if (layout_range.is_empty())
return rects;
std::vector<Range> bounds;
// Add a Range for each run/selection intersection.
for (size_t i = 0; i < runs_.size(); ++i) {
internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
Range intersection = run->range.Intersect(layout_range);
if (!intersection.IsValid())
continue;
DCHECK(!intersection.is_reversed());
const Range leftmost_character_x = run->GetGraphemeBounds(
grapheme_iterator_.get(),
run->is_rtl ? intersection.end() - 1 : intersection.start());
const Range rightmost_character_x = run->GetGraphemeBounds(
grapheme_iterator_.get(),
run->is_rtl ? intersection.start() : intersection.end() - 1);
Range range_x(leftmost_character_x.start(), rightmost_character_x.end());
DCHECK(!range_x.is_reversed());
if (range_x.is_empty())
continue;
// Union this with the last range if they're adjacent.
DCHECK(bounds.empty() || bounds.back().GetMax() <= range_x.GetMin());
if (!bounds.empty() && bounds.back().GetMax() == range_x.GetMin()) {
range_x = Range(bounds.back().GetMin(), range_x.GetMax());
bounds.pop_back();
}
bounds.push_back(range_x);
}
for (size_t i = 0; i < bounds.size(); ++i) {
std::vector<Rect> current_rects = TextBoundsToViewBounds(bounds[i]);
rects.insert(rects.end(), current_rects.begin(), current_rects.end());
}
return rects;
}
size_t RenderTextHarfBuzz::TextIndexToLayoutIndex(size_t index) const {
DCHECK_LE(index, text().length());
ptrdiff_t i = obscured() ? UTF16IndexToOffset(text(), 0, index) : index;
CHECK_GE(i, 0);
// Clamp layout indices to the length of the text actually used for layout.
return std::min<size_t>(GetLayoutText().length(), i);
}
size_t RenderTextHarfBuzz::LayoutIndexToTextIndex(size_t index) const {
if (!obscured())
return index;
DCHECK_LE(index, GetLayoutText().length());
const size_t text_index = UTF16OffsetToIndex(text(), 0, index);
DCHECK_LE(text_index, text().length());
return text_index;
}
bool RenderTextHarfBuzz::IsValidCursorIndex(size_t index) {
if (index == 0 || index == text().length())
return true;
if (!IsValidLogicalIndex(index))
return false;
EnsureLayout();
return !grapheme_iterator_ || grapheme_iterator_->IsGraphemeBoundary(index);
}
void RenderTextHarfBuzz::ResetLayout() {
needs_layout_ = true;
}
void RenderTextHarfBuzz::EnsureLayout() {
if (needs_layout_) {
runs_.clear();
grapheme_iterator_.reset();
if (!GetLayoutText().empty()) {
grapheme_iterator_.reset(new base::i18n::BreakIterator(GetLayoutText(),
base::i18n::BreakIterator::BREAK_CHARACTER));
if (!grapheme_iterator_->Init())
grapheme_iterator_.reset();
ItemizeText();
for (size_t i = 0; i < runs_.size(); ++i)
ShapeRun(runs_[i]);
// Precalculate run width information.
float preceding_run_widths = 0.0f;
for (size_t i = 0; i < runs_.size(); ++i) {
internal::TextRunHarfBuzz* run = runs_[visual_to_logical_[i]];
run->preceding_run_widths = preceding_run_widths;
preceding_run_widths += run->width;
}
}
needs_layout_ = false;
std::vector<internal::Line> empty_lines;
set_lines(&empty_lines);
}
if (lines().empty()) {
std::vector<internal::Line> lines;
lines.push_back(internal::Line());
lines[0].baseline = font_list().GetBaseline();
lines[0].size.set_height(font_list().GetHeight());
int current_x = 0;
SkPaint paint;
for (size_t i = 0; i < runs_.size(); ++i) {
const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
internal::LineSegment segment;
segment.x_range = Range(current_x, current_x + run.width);
segment.char_range = run.range;
segment.run = i;
lines[0].segments.push_back(segment);
paint.setTypeface(run.skia_face.get());
paint.setTextSize(run.font_size);
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
lines[0].size.set_width(lines[0].size.width() + run.width);
lines[0].size.set_height(std::max(lines[0].size.height(),
metrics.fDescent - metrics.fAscent));
lines[0].baseline = std::max(lines[0].baseline,
SkScalarRoundToInt(-metrics.fAscent));
}
set_lines(&lines);
}
}
void RenderTextHarfBuzz::DrawVisualText(Canvas* canvas) {
DCHECK(!needs_layout_);
internal::SkiaTextRenderer renderer(canvas);
ApplyFadeEffects(&renderer);
ApplyTextShadows(&renderer);
#if defined(OS_WIN) || defined(OS_LINUX)
renderer.SetFontRenderParams(
font_list().GetPrimaryFont().GetFontRenderParams(),
background_is_transparent());
#endif
ApplyCompositionAndSelectionStyles();
int current_x = 0;
const Vector2d line_offset = GetLineOffset(0);
for (size_t i = 0; i < runs_.size(); ++i) {
const internal::TextRunHarfBuzz& run = *runs_[visual_to_logical_[i]];
renderer.SetTypeface(run.skia_face.get());
renderer.SetTextSize(run.font_size);
Vector2d origin = line_offset + Vector2d(current_x, lines()[0].baseline);
scoped_ptr<SkPoint[]> positions(new SkPoint[run.glyph_count]);
for (size_t j = 0; j < run.glyph_count; ++j) {
positions[j] = run.positions[j];
positions[j].offset(SkIntToScalar(origin.x()), SkIntToScalar(origin.y()));
}
for (BreakList<SkColor>::const_iterator it =
colors().GetBreak(run.range.start());
it != colors().breaks().end() && it->first < run.range.end();
++it) {
const Range intersection = colors().GetRange(it).Intersect(run.range);
const Range colored_glyphs = run.CharRangeToGlyphRange(intersection);
// The range may be empty if a portion of a multi-character grapheme is
// selected, yielding two colors for a single glyph. For now, this just
// paints the glyph with a single style, but it should paint it twice,
// clipped according to selection bounds. See http://crbug.com/366786
if (colored_glyphs.is_empty())
continue;
renderer.SetForegroundColor(it->second);
renderer.DrawPosText(&positions[colored_glyphs.start()],
&run.glyphs[colored_glyphs.start()],
colored_glyphs.length());
int width = (colored_glyphs.end() == run.glyph_count ? run.width :
run.positions[colored_glyphs.end()].x()) -
run.positions[colored_glyphs.start()].x();
renderer.DrawDecorations(origin.x(), origin.y(), width, run.underline,
run.strike, run.diagonal_strike);
}
current_x += run.width;
}
renderer.EndDiagonalStrike();
UndoCompositionAndSelectionStyles();
}
size_t RenderTextHarfBuzz::GetRunContainingCaret(
const SelectionModel& caret) const {
DCHECK(!needs_layout_);
size_t layout_position = TextIndexToLayoutIndex(caret.caret_pos());
LogicalCursorDirection affinity = caret.caret_affinity();
for (size_t run = 0; run < runs_.size(); ++run) {
if (RangeContainsCaret(runs_[run]->range, layout_position, affinity))
return run;
}
return runs_.size();
}
size_t RenderTextHarfBuzz::GetRunContainingXCoord(int x, int* offset) const {
DCHECK(!needs_layout_);
if (x < 0)
return runs_.size();
// Find the text run containing the argument point (assumed already offset).
int current_x = 0;
for (size_t i = 0; i < runs_.size(); ++i) {
size_t run = visual_to_logical_[i];
current_x += runs_[run]->width;
if (x < current_x) {
*offset = x - (current_x - runs_[run]->width);
return run;
}
}
return runs_.size();
}
SelectionModel RenderTextHarfBuzz::FirstSelectionModelInsideRun(
const internal::TextRunHarfBuzz* run) {
size_t position = LayoutIndexToTextIndex(run->range.start());
position = IndexOfAdjacentGrapheme(position, CURSOR_FORWARD);
return SelectionModel(position, CURSOR_BACKWARD);
}
SelectionModel RenderTextHarfBuzz::LastSelectionModelInsideRun(
const internal::TextRunHarfBuzz* run) {
size_t position = LayoutIndexToTextIndex(run->range.end());
position = IndexOfAdjacentGrapheme(position, CURSOR_BACKWARD);
return SelectionModel(position, CURSOR_FORWARD);
}
void RenderTextHarfBuzz::ItemizeText() {
const base::string16& text = GetLayoutText();
const bool is_text_rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT;
DCHECK_NE(0U, text.length());
// If ICU fails to itemize the text, we create a run that spans the entire
// text. This is needed because leaving the runs set empty causes some clients
// to misbehave since they expect non-zero text metrics from a non-empty text.
base::i18n::BiDiLineIterator bidi_iterator;
if (!bidi_iterator.Open(text, is_text_rtl, false)) {
internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
run->range = Range(0, text.length());
runs_.push_back(run);
visual_to_logical_ = logical_to_visual_ = std::vector<int32_t>(1, 0);
return;
}
// Temporarily apply composition underlines and selection colors.
ApplyCompositionAndSelectionStyles();
// Build the list of runs from the script items and ranged styles. Use an
// empty color BreakList to avoid breaking runs at color boundaries.
BreakList<SkColor> empty_colors;
empty_colors.SetMax(text.length());
internal::StyleIterator style(empty_colors, styles());
for (size_t run_break = 0; run_break < text.length();) {
internal::TextRunHarfBuzz* run = new internal::TextRunHarfBuzz;
run->range.set_start(run_break);
run->font_style = (style.style(BOLD) ? Font::BOLD : 0) |
(style.style(ITALIC) ? Font::ITALIC : 0);
run->strike = style.style(STRIKE);
run->diagonal_strike = style.style(DIAGONAL_STRIKE);
run->underline = style.style(UNDERLINE);
int32 script_item_break = 0;
bidi_iterator.GetLogicalRun(run_break, &script_item_break, &run->level);
// Odd BiDi embedding levels correspond to RTL runs.
run->is_rtl = (run->level % 2) == 1;
// Find the length and script of this script run.
script_item_break = ScriptInterval(text, run_break,
script_item_break - run_break, &run->script) + run_break;
// Find the next break and advance the iterators as needed.
run_break = std::min(static_cast<size_t>(script_item_break),
TextIndexToLayoutIndex(style.GetRange().end()));
// Break runs adjacent to character substrings in certain code blocks.
// This avoids using their fallback fonts for more characters than needed,
// in cases like "\x25B6 Media Title", etc. http://crbug.com/278913
if (run_break > run->range.start())
run_break = FindUnusualCharacter(text, run->range.start(), run_break);
DCHECK(IsValidCodePointIndex(text, run_break));
style.UpdatePosition(LayoutIndexToTextIndex(run_break));
run->range.set_end(run_break);
runs_.push_back(run);
}
// Undo the temporarily applied composition underlines and selection colors.
UndoCompositionAndSelectionStyles();
const size_t num_runs = runs_.size();
std::vector<UBiDiLevel> levels(num_runs);
for (size_t i = 0; i < num_runs; ++i)
levels[i] = runs_[i]->level;
visual_to_logical_.resize(num_runs);
ubidi_reorderVisual(&levels[0], num_runs, &visual_to_logical_[0]);
logical_to_visual_.resize(num_runs);
ubidi_reorderLogical(&levels[0], num_runs, &logical_to_visual_[0]);
}
void RenderTextHarfBuzz::ShapeRun(internal::TextRunHarfBuzz* run) {
const Font& primary_font = font_list().GetPrimaryFont();
const std::string primary_font_name = primary_font.GetFontName();
run->font_size = primary_font.GetFontSize();
size_t best_font_missing = std::numeric_limits<size_t>::max();
std::string best_font;
std::string current_font;
// Try shaping with |primary_font|.
if (ShapeRunWithFont(run, primary_font_name)) {
current_font = primary_font_name;
size_t current_missing = run->CountMissingGlyphs();
if (current_missing == 0)
return;
if (current_missing < best_font_missing) {
best_font_missing = current_missing;
best_font = current_font;
}
}
#if defined(OS_WIN)
Font uniscribe_font;
const base::char16* run_text = &(GetLayoutText()[run->range.start()]);
if (GetUniscribeFallbackFont(primary_font, run_text, run->range.length(),
&uniscribe_font) &&
ShapeRunWithFont(run, uniscribe_font.GetFontName())) {
current_font = uniscribe_font.GetFontName();
size_t current_missing = run->CountMissingGlyphs();
if (current_missing == 0)
return;
if (current_missing < best_font_missing) {
best_font_missing = current_missing;
best_font = current_font;
}
}
#endif
// Try shaping with the fonts in the fallback list except the first, which is
// |primary_font|.
std::vector<std::string> fonts = GetFallbackFontFamilies(primary_font_name);
for (size_t i = 1; i < fonts.size(); ++i) {
if (!ShapeRunWithFont(run, fonts[i]))
continue;
current_font = fonts[i];
size_t current_missing = run->CountMissingGlyphs();
if (current_missing == 0)
return;
if (current_missing < best_font_missing) {
best_font_missing = current_missing;
best_font = current_font;
}
}
if (!best_font.empty() &&
(best_font == current_font || ShapeRunWithFont(run, best_font))) {
return;
}
run->glyph_count = 0;
run->width = 0.0f;
}
bool RenderTextHarfBuzz::ShapeRunWithFont(internal::TextRunHarfBuzz* run,
const std::string& font_family) {
const base::string16& text = GetLayoutText();
skia::RefPtr<SkTypeface> skia_face =
internal::CreateSkiaTypeface(font_family, run->font_style);
if (skia_face == NULL)
return false;
run->skia_face = skia_face;
hb_font_t* harfbuzz_font = CreateHarfBuzzFont(run->skia_face.get(),
run->font_size);
// Create a HarfBuzz buffer and add the string to be shaped. The HarfBuzz
// buffer holds our text, run information to be used by the shaping engine,
// and the resulting glyph data.
hb_buffer_t* buffer = hb_buffer_create();
hb_buffer_add_utf16(buffer, reinterpret_cast<const uint16*>(text.c_str()),
text.length(), run->range.start(), run->range.length());
hb_buffer_set_script(buffer, ICUScriptToHBScript(run->script));
hb_buffer_set_direction(buffer,
run->is_rtl ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
// TODO(ckocagil): Should we determine the actual language?
hb_buffer_set_language(buffer, hb_language_get_default());
// Shape the text.
hb_shape(harfbuzz_font, buffer, NULL, 0);
// Populate the run fields with the resulting glyph data in the buffer.
unsigned int glyph_count = 0;
hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(buffer, &glyph_count);
run->glyph_count = glyph_count;
hb_glyph_position_t* hb_positions =
hb_buffer_get_glyph_positions(buffer, NULL);
run->glyphs.reset(new uint16[run->glyph_count]);
run->glyph_to_char.resize(run->glyph_count);
run->positions.reset(new SkPoint[run->glyph_count]);
run->width = 0.0f;
for (size_t i = 0; i < run->glyph_count; ++i) {
run->glyphs[i] = infos[i].codepoint;
run->glyph_to_char[i] = infos[i].cluster;
const int x_offset = SkFixedToScalar(hb_positions[i].x_offset);
const int y_offset = SkFixedToScalar(hb_positions[i].y_offset);
run->positions[i].set(run->width + x_offset, -y_offset);
run->width += SkFixedToScalar(hb_positions[i].x_advance);
}
hb_buffer_destroy(buffer);
hb_font_destroy(harfbuzz_font);
return true;
}
} // namespace gfx
| 7kbird/chrome | ui/gfx/render_text_harfbuzz.cc | C++ | bsd-3-clause | 41,809 |
package org.motechproject.dhis2.rest.domain;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.util.List;
/**
* Models the DHIS2 API's Data Set resource.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DataSetDto extends BaseDto {
private List<DataElementDto> dataElements;
public List<DataElementDto> getDataElements() {
return dataElements;
}
public void setDataElements(List<DataElementDto> dataElements) {
this.dataElements = dataElements;
}
}
| martokarski/modules | dhis2/src/main/java/org/motechproject/dhis2/rest/domain/DataSetDto.java | Java | bsd-3-clause | 640 |
---
id: 5a23c84252665b21eecc7eb0
title: I before E except after C
challengeType: 5
forumTopicId: 302288
dashedName: i-before-e-except-after-c
---
# --description--
The phrase ["I before E, except after C"](https://en.wikipedia.org/wiki/I before E except after C) is a widely known mnemonic which is supposed to help when spelling English words.
Using the words provided, check if the two sub-clauses of the phrase are plausible individually:
<ol>
<li>
<i>"I before E when not preceded by C".</i>
</li>
<li>
<i>"E before I when preceded by C".</i>
</li>
</ol>
If both sub-phrases are plausible then the original phrase can be said to be plausible.
# --instructions--
Write a function that accepts a word and check if the word follows this rule. The function should return true if the word follows the rule and false if it does not.
# --hints--
`IBeforeExceptC` should be a function.
```js
assert(typeof IBeforeExceptC == 'function');
```
`IBeforeExceptC("receive")` should return a boolean.
```js
assert(typeof IBeforeExceptC('receive') == 'boolean');
```
`IBeforeExceptC("receive")` should return `true`.
```js
assert.equal(IBeforeExceptC('receive'), true);
```
`IBeforeExceptC("science")` should return `false`.
```js
assert.equal(IBeforeExceptC('science'), false);
```
`IBeforeExceptC("imperceivable")` should return `true`.
```js
assert.equal(IBeforeExceptC('imperceivable'), true);
```
`IBeforeExceptC("inconceivable")` should return `true`.
```js
assert.equal(IBeforeExceptC('inconceivable'), true);
```
`IBeforeExceptC("insufficient")` should return `false`.
```js
assert.equal(IBeforeExceptC('insufficient'), false);
```
`IBeforeExceptC("omniscient")` should return `false`.
```js
assert.equal(IBeforeExceptC('omniscient'), false);
```
# --seed--
## --seed-contents--
```js
function IBeforeExceptC(word) {
}
```
# --solutions--
```js
function IBeforeExceptC(word)
{
if(word.indexOf("c")==-1 && word.indexOf("ie")!=-1)
return true;
else if(word.indexOf("cei")!=-1)
return true;
return false;
}
```
| FreeCodeCamp/FreeCodeCamp | curriculum/challenges/espanol/10-coding-interview-prep/rosetta-code/i-before-e-except-after-c.md | Markdown | bsd-3-clause | 2,078 |
module Spree
module TestingSupport
module Caching
def cache_writes
@cache_write_events
end
def assert_written_to_cache(key)
unless @cache_write_events.detect { |event| event[:key].starts_with?(key) }
raise %Q{Expected to find #{key} in the cache, but didn't.
Cache writes:
#{@cache_write_events.join("\n")}
}
end
end
def clear_cache_events
@cache_read_events = []
@cache_write_events = []
end
end
end
end
RSpec.configure do |config|
config.include Spree::TestingSupport::Caching, caching: true
config.before(:each, caching: true) do
ActionController::Base.perform_caching = true
ActiveSupport::Notifications.subscribe('read_fragment.action_controller') do |_event, _start_time, _finish_time, _, details|
@cache_read_events ||= []
@cache_read_events << details
end
ActiveSupport::Notifications.subscribe('write_fragment.action_controller') do |_event, _start_time, _finish_time, _, details|
@cache_write_events ||= []
@cache_write_events << details
end
end
config.after(:each, caching: true) do
ActionController::Base.perform_caching = false
Rails.cache.clear
end
end
| vinayvinsol/spree | core/lib/spree/testing_support/caching.rb | Ruby | bsd-3-clause | 1,249 |
project_slug = '{{ cookiecutter.project_slug }}'
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
elasticbeanstalk = '{{ cookiecutter.use_elasticbeanstalk_experimental }}'.lower()
heroku = '{{ cookiecutter.use_heroku }}'.lower()
docker = '{{ cookiecutter.use_docker }}'.lower()
if elasticbeanstalk == 'y' and (heroku == 'y' or docker == 'y'):
raise Exception("Cookiecutter Django's EXPERIMENTAL Elastic Beanstalk support is incompatible with Heroku and Docker setups.")
| schacki/cookiecutter-django | hooks/pre_gen_project.py | Python | bsd-3-clause | 560 |
describe('NgTableParams', function () {
var scope,
NgTableParams,
$rootScope;
beforeEach(module("ngTable"));
beforeEach(function(){
module(function($provide){
$provide.decorator('ngTableDefaultGetData', createSpy);
createSpy.$inject = ['$delegate'];
function createSpy(ngTableDefaultGetData){
return jasmine.createSpy('ngTableDefaultGetDataSpy',ngTableDefaultGetData).and.callThrough();
}
});
});
beforeEach(inject(function ($controller, _$rootScope_, _NgTableParams_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
NgTableParams = _NgTableParams_;
}));
function createNgTableParams(settings) {
var initialParams;
if (arguments.length === 2){
initialParams = arguments[0];
settings = arguments[1];
}
settings = angular.extend({}, settings);
settings.filterOptions = angular.extend({}, {
filterDelay: 0
}, settings.filterOptions);
var tableParams = new NgTableParams(initialParams, settings);
spyOn(tableParams.settings(), 'getData').and.callThrough();
return tableParams;
}
it('NgTableParams should be defined', function () {
expect(NgTableParams).toBeDefined();
});
describe('generatePagesArray', function(){
it('should generate pages array using arguments supplied', function(){
var params = new NgTableParams();
expect(params.generatePagesArray(1, 30, 10)).toEqual([
{ type: 'prev', number: 1, active: false },
{ type: 'first', number: 1, active: false, current: true },
{ type: 'page', number: 2, active: true, current: false },
{ type: 'last', number: 3, active: true, current: false },
{ type: 'next', number: 2, active: true }
]);
expect(params.generatePagesArray(2, 30, 10)).toEqual([
{ type: 'prev', number: 1, active: true },
{ type: 'first', number: 1, active: true, current: false },
{ type: 'page', number: 2, active: false, current: true },
{ type: 'last', number: 3, active: true, current: false },
{ type: 'next', number: 3, active: true }
]);
expect(params.generatePagesArray(2, 100, 10)).toEqual([
{ type: 'prev', number: 1, active: true },
{ type: 'first', number: 1, active: true, current: false },
{ type: 'page', number: 2, active: false, current: true },
{ type: 'page', number: 3, active: true, current: false },
{ type: 'page', number: 4, active: true, current: false },
{ type: 'page', number: 5, active: true, current: false },
{ type: 'page', number: 6, active: true, current: false },
{ type: 'page', number: 7, active: true, current: false },
{ type: 'more', active: false },
{ type: 'last', number: 10, active: true, current: false },
{ type: 'next', number: 3, active: true }
]);
});
it('should use own parameter values to generate pages when no arguments supplied', function(){
var params = new NgTableParams({ page: 2, count: 10 }, { total: 30 });
expect(params.generatePagesArray()).toEqual([
{ type: 'prev', number: 1, active: true },
{ type: 'first', number: 1, active: true, current: false },
{ type: 'page', number: 2, active: false, current: true },
{ type: 'last', number: 3, active: true, current: false },
{ type: 'next', number: 3, active: true }
]);
});
});
it('NgTableParams `page` parameter', function () {
var params = new NgTableParams();
expect(params.page()).toBe(1);
expect(params.page(2)).toEqual(params);
expect(params.page()).toBe(2);
params = new NgTableParams({
page: 3
});
expect(params.page()).toBe(3);
});
it('NgTableParams parse url parameters', function () {
var params = new NgTableParams({
'sorting[name]': 'asc',
'sorting[age]': 'desc',
'filter[name]': 'test',
'filter[age]': '20',
'group[name]' : 'asc',
'group[age]' : 'desc',
'group[surname]' : undefined
});
expect(params.filter()).toEqual({ 'name': 'test', 'age': 20 });
expect(params.sorting()).toEqual({ 'age': 'desc' }); // sorting only by one column - todo: remove restriction
expect(params.group()).toEqual({ 'name' : 'asc', 'age': 'desc', 'surname': undefined });
});
it('NgTableParams return url parameters', function () {
var params = new NgTableParams({
'sorting[name]': 'asc',
'sorting[age]': 'desc',
'filter[name]': 'test',
'filter[age]': '20',
'group[name]' : 'asc',
'group[age]' : 'desc',
'group[surname]' : ''
});
expect(params.url()).toEqual({
'page': '1',
'count': '10',
'filter[name]': 'test',
'filter[age]': '20',
'sorting[age]': 'desc', // sorting only by one column - todo: remove restriction
'group[name]' : 'asc',
'group[age]' : 'desc',
'group[surname]' : ''
});
expect(params.url(true)).toEqual([
'page=1',
'count=10',
'filter[name]=test',
'filter[age]=20',
'sorting[age]=desc', // sorting only by one column - todo: remove restriction
'group[name]=asc',
'group[age]=desc',
'group[surname]='
]);
});
it('orderBy', function () {
var params = new NgTableParams({
'sorting[name]': 'asc'
});
expect(params.orderBy()).toEqual([ '+name' ]); // for angular sorting function
params.sorting({ name: 'desc', age: 'asc' });
expect(params.orderBy()).toEqual([ '-name', '+age' ]);
});
describe('group', function(){
it('one group', function () {
var params = new NgTableParams({
group: 'role'
}, {
groupOptions: { defaultSort: 'desc' }
});
expect(params.hasGroup()).toBe(true);
expect(params.hasGroup('role')).toBe(true);
expect(params.hasGroup('role', 'desc')).toBe(true);
expect(params.group()).toEqual({ role: 'desc' });
params.group('age');
expect(params.hasGroup('age', 'desc')).toBe(true);
expect(params.group()).toEqual({ age: 'desc' });
params.group('age', 'asc');
expect(params.hasGroup('age', 'asc')).toBe(true);
expect(params.group()).toEqual({ age: 'asc' });
});
it('one group function', function () {
var params = new NgTableParams({
group: angular.identity
});
expect(params.hasGroup()).toBe(true);
expect(params.hasGroup(angular.identity)).toBe(true);
expect(params.hasGroup(angular.identity, params.settings().groupOptions.defaultSort)).toBe(true);
expect(params.group()).toEqual(angular.identity);
var fn = function(){ };
fn.sortDirection = 'desc';
params.group(fn);
expect(params.hasGroup(fn)).toBe(true);
expect(params.hasGroup(fn, 'desc')).toBe(true);
expect(params.group()).toEqual(fn);
});
it('can clear group', function () {
var params = new NgTableParams({
group: 'role'
});
expect(params.hasGroup()).toBe(true); // checking assumptions
params.group({});
expect(params.hasGroup()).toBe(false);
expect(params.group()).toEqual({});
});
it('multiple groups', function () {
var params = new NgTableParams({
group: 'role'
}, {
groupOptions: { defaultSort: 'desc' }
});
var newGroups = _.extend({}, params.group(), { age: 'desc'});
params.group(newGroups);
expect(params.hasGroup()).toBe(true);
expect(params.hasGroup('role')).toBe(true);
expect(params.hasGroup('role', 'desc')).toBe(true);
expect(params.hasGroup('age')).toBe(true);
expect(params.hasGroup('age', 'desc')).toBe(true);
expect(params.group()).toEqual({ role: 'desc', age: 'desc' });
params.group({ role: 'asc', age: 'asc'});
expect(params.hasGroup('age', 'desc')).toBe(false);
expect(params.hasGroup('age', 'asc')).toBe(true);
expect(params.group()).toEqual({ role: 'asc', age: 'asc' });
});
it('should apply current defaultSort from groupOptions', function(){
var params = new NgTableParams({
group: 'role'
}, {
groupOptions: { defaultSort: 'desc' }
});
params.settings({ groupOptions: { defaultSort: 'asc' }});
params.group('age');
expect(params.group()).toEqual({ age: 'asc' });
});
it('should not apply defaultSort from groupOptions when explicitly set to empty string', function(){
var params = new NgTableParams({
group: 'role'
}, {
groupOptions: { defaultSort: 'desc' }
});
expect(params.group()).toEqual({ role: 'desc' }); // checking assumptions
params.group({ role: ''});
expect(params.group()).toEqual({ role: '' });
params.group({ age: undefined});
expect(params.group()).toEqual({ age: 'desc' });
params.group({ role: null});
expect(params.group()).toEqual({ role: 'desc' });
});
});
describe('settings', function(){
it('defaults', function () {
var params = new NgTableParams();
var expectedSettings = {
$loading: false,
dataset: null,
total: 0,
defaultSort: 'desc',
counts: [10, 25, 50, 100],
interceptors: [],
paginationMaxBlocks: 11,
paginationMinBlocks: 5,
sortingIndicator: 'span',
filterOptions: {
filterComparator: undefined,
filterDelay: 500,
filterDelayThreshold: 10000,
filterFilterName: undefined,
filterFn: undefined,
filterLayout: 'stack'
},
groupOptions: { defaultSort: 'asc', isExpanded: true }
};
expect(params.settings()).toEqual(jasmine.objectContaining(expectedSettings));
expect(params.settings().getData).toEqual(jasmine.any(Function));
expect(params.settings().getGroups).toEqual(jasmine.any(Function));
params = new NgTableParams({}, {
total: 100,
counts: [1,2],
groupOptions: { isExpanded: false } });
expectedSettings.total = 100;
expectedSettings.counts = [1,2];
expectedSettings.groupOptions = { defaultSort: 'asc', isExpanded: false };
expect(params.settings()).toEqual(jasmine.objectContaining(expectedSettings));
});
it('changing settings().dataset should reset page to 1', function(){
// given
var tableParams = createNgTableParams({ count: 1, page: 2 }, { dataset: [1,2,3]});
tableParams.reload();
scope.$digest();
expect(tableParams.page()).toBe(2); // checking assumptions
// when
tableParams.settings({ dataset: [1,2,3, 4]});
// then
expect(tableParams.page()).toBe(1);
});
it('should not set filterDelay when working with synchronous dataset', function(){
// given
var tableParams = new NgTableParams({}, { dataset: [1,2,3]});
expect(tableParams.settings().filterOptions.filterDelay).toBe(0);
});
it('should not set filterDelay when working with synchronous dataset (empty dataset)', function(){
// given
var tableParams = new NgTableParams({}, { dataset: []});
expect(tableParams.settings().filterOptions.filterDelay).toBe(0);
});
it('should set filterDelay when not certain working with synchronous dataset', function(){
// given
var tableParams = new NgTableParams({}, { dataset: [1,2], getData: function(){
// am I sync or async?
}});
expect(tableParams.settings().filterOptions.filterDelay).toBe(500);
});
it('should set filterDelay when dataset exceeds filterDelayThreshold', function(){
// given
var tableParams = new NgTableParams({}, { filterOptions: { filterDelayThreshold: 5 }, dataset: [,2,3,4,5,6] });
expect(tableParams.settings().filterOptions.filterDelay).toBe(500);
});
it('should allow filterDelay to be set explicitly', function(){
// given
var tableParams = new NgTableParams({}, { filterOptions: { filterDelay: 100}, dataset: [1,2] });
expect(tableParams.settings().filterOptions.filterDelay).toBe(100);
});
});
describe('reload', function(){
it('should call getData to retrieve data', function(){
var tp = createNgTableParams();
tp.reload();
scope.$digest();
expect(tp.settings().getData.calls.count()).toBe(1);
});
it('should add the results returned by getData to the data field', function(){
var tp = createNgTableParams({ getData: function(){
return [1,2,3];
}});
tp.reload();
scope.$digest();
expect(tp.data).toEqual([1,2,3]);
});
it('should use ngTableDefaultGetData function when NgTableParams not supplied a getData function', inject(function(ngTableDefaultGetData){
// given
var tp = createNgTableParams();
// when
tp.reload();
scope.$digest();
// then
expect(ngTableDefaultGetData).toHaveBeenCalled();
}));
it('should propagate rejection reason from getData', inject(function($q){
// given
var tp = createNgTableParams({ getData: function(){
return $q.reject('bad response')
}});
// when
var actualRejection;
tp.reload().catch(function(reason){
actualRejection = reason;
});
scope.$digest();
// then
expect(actualRejection).toBe('bad response');
}));
});
describe('getGroups', function(){
var dataset;
beforeEach(function(){
dataset = [
{ 'name': 'Hanson', 'role': 'Accounting' },
{ 'name': 'Eaton', 'role': 'Customer Service' },
{ 'name': 'Perry', 'role': 'Customer Service' },
{ 'name': 'George', 'role': 'Accounting' },
{ 'name': 'Jennings', 'role': 'Asset Management' },
{ 'name': 'Whitney', 'role': 'Accounting' },
{ 'name': 'Weaver', 'role': 'Payroll' },
{ 'name': 'Gibson', 'role': 'Payroll' },
{ 'name': 'Wells', 'role': 'Media Relations' },
{ 'name': 'Willis', 'role': 'Finances' },
{ 'name': 'Donovan', 'role': 'Customer Relations' },
{ 'name': 'Mcdonald', 'role': 'Finances' },
{ 'name': 'Young', 'role': 'Asset Management' }
];
});
it('should group data then apply paging to groups', function () {
var tp = createNgTableParams({ count: 2, group: { role: '' } }, { dataset: dataset });
var actualRoleGroups;
tp.reload().then(function(groups){
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Accounting',
data: [
{ "name": 'Hanson', "role": 'Accounting' },
{ "name": 'George', "role": 'Accounting' },
{ "name": 'Whitney', "role": 'Accounting' }
]
},
{
$hideRows: false,
value: 'Customer Service',
data: [
{ "name": 'Eaton', "role": 'Customer Service' },
{ "name": 'Perry', "role": 'Customer Service' }
]
}
]);
});
it('should sort data, then group, then page groups', function () {
var tp = createNgTableParams({
count: 2,
sorting: { name: 'desc'},
group: { role: '' }
}, { dataset: dataset });
var actualRoleGroups;
tp.reload().then(function(groups){
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Asset Management',
data: [
{ "name": 'Young', "role": 'Asset Management' },
{ "name": 'Jennings', "role": 'Asset Management' }
]
},
{
$hideRows: false,
value: 'Finances',
data: [
{ "name": 'Willis', "role": 'Finances' },
{ "name": 'Mcdonald', "role": 'Finances' }
]
}
]);
});
it('should use group function to group data', function () {
var grouper = function (item) {
return item.name[0];
};
grouper.sortDirection = '';
var tp = createNgTableParams({
count: 2,
sorting: {name: 'desc'},
group: grouper
}, {dataset: dataset});
var actualRoleGroups;
tp.reload().then(function (groups) {
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Y',
data: [
{ "name": "Young", "role": "Asset Management" }
]
},
{
$hideRows: false,
value: 'W',
data: [
{ "name": "Willis", "role": "Finances" },
{ "name": "Whitney", "role": "Accounting" },
{ "name": "Wells", "role": "Media Relations" },
{ "name": "Weaver", "role": "Payroll" }
]
}
]);
});
it('should filter and sort data, then group, then page groups', function () {
var tp = createNgTableParams({
count: 2,
sorting: { name: 'desc' },
filter: { name: 'e' },
group: { role: '' }
}, {
dataset: dataset
});
var actualRoleGroups;
tp.reload().then(function(groups){
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Accounting',
data: [
{ 'name': 'Whitney', 'role': 'Accounting' },
{ 'name': 'George', 'role': 'Accounting' }
]
},
{
$hideRows: false,
value: 'Media Relations',
data: [
{ 'name': 'Wells', 'role': 'Media Relations' }
]
}
]);
});
it('should filter and sort data, then group, then apply group sortDirection, and finally page groups', function () {
var tp = createNgTableParams({
count: 3,
sorting: { name: 'desc' },
filter: { name: 'e' },
group: { role: 'desc' }
}, {
dataset: dataset,
groupOptions: {
// this value will be overridden by group: { role: 'desc' }
defaultSort: undefined
}
});
var actualRoleGroups;
tp.reload().then(function(groups){
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Payroll',
data: [
{ 'name': 'Weaver', 'role': 'Payroll' }
]
},
{
$hideRows: false,
value: 'Media Relations',
data: [
{ 'name': 'Wells', 'role': 'Media Relations' }
]
},
{
$hideRows: false,
value: 'Customer Service',
data: [
{ 'name': 'Perry', 'role': 'Customer Service' },
{ 'name': 'Eaton', 'role': 'Customer Service' }
]
}
]);
});
it('should use sortDirection defined on group function to sort groups', function () {
var groupFn = function(item){
return item.role;
};
groupFn.sortDirection = 'desc';
var tp = createNgTableParams({
count: 3,
sorting: { name: 'desc' },
filter: { name: 'e' },
group: groupFn
}, {
dataset: dataset,
groupOptions: {
// this value will be overridden by groupFn.sortDirection
defaultSort: undefined
}
});
var actualRoleGroups;
tp.reload().then(function(groups){
actualRoleGroups = groups;
});
$rootScope.$digest();
expect(actualRoleGroups).toEqual([
{
$hideRows: false,
value: 'Payroll',
data: [
{ 'name': 'Weaver', 'role': 'Payroll' }
]
},
{
$hideRows: false,
value: 'Media Relations',
data: [
{ 'name': 'Wells', 'role': 'Media Relations' }
]
},
{
$hideRows: false,
value: 'Customer Service',
data: [
{ 'name': 'Perry', 'role': 'Customer Service' },
{ 'name': 'Eaton', 'role': 'Customer Service' }
]
}
]);
});
});
it('ngTableParams test defaults', inject(function ($q, ngTableDefaults) {
ngTableDefaults.params.count = 2;
ngTableDefaults.settings.counts = [];
var tp = new NgTableParams();
expect(tp.count()).toEqual(2);
expect(tp.page()).toEqual(1);
var settings = tp.settings();
expect(settings.counts.length).toEqual(0);
expect(settings.interceptors.length).toEqual(0);
expect(settings.filterOptions.filterDelay).toEqual(500);
ngTableDefaults.settings.interceptors = [ { response: angular.identity }];
tp = new NgTableParams();
expect(tp.settings().interceptors.length).toEqual(1);
}));
describe('hasFilter', function(){
var tp;
beforeEach(inject(function(){
tp = new NgTableParams({}, {});
}));
it('should return false for an empty filter object', function(){
tp.filter({});
expect(tp.hasFilter()).toBe(false);
});
it('should return true for when filter has a field with a significant value', function(){
tp.filter({ a: 'b' });
expect(tp.hasFilter()).toBe(true);
tp.filter({ a: 0 });
expect(tp.hasFilter()).toBe(true);
});
it('should return false when filter only has insignificant field values', function(){
tp.filter({ a: '' });
expect(tp.hasFilter()).toBe(false);
tp.filter({ a: null });
expect(tp.hasFilter()).toBe(false);
tp.filter({ a: undefined });
expect(tp.hasFilter()).toBe(false);
tp.filter({ a: undefined, b: '', c: undefined });
expect(tp.hasFilter()).toBe(false);
//tp.filter({ a: NaN });
//expect(tp.hasFilter()).toBe(false);
});
});
describe('isDataReloadRequired', function(){
var tp;
beforeEach(inject(function(){
tp = createNgTableParams();
}));
it('should return true after construction', function(){
expect(tp.isDataReloadRequired()).toBe(true);
});
it('should return false once reload called after construction', function(){
tp.reload();
// note: we don't have to wait for the getData promise to be resolved before considering reload
// to be unnecessary - that's why we're not having to run a $digest
expect(tp.isDataReloadRequired()).toBe(false);
});
it('should return true when getData fails', inject(function($q){
tp.settings({ getData: function(){
return $q.reject('bad response');
}});
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(true);
}));
it('should detect direct changes to parameters', inject(function($q){
// given
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(false); // checking assumptions
// when
tp.filter().newField = 99;
expect(tp.isDataReloadRequired()).toBe(true);
}));
it('should return true until changed parameters have been reloaded', function(){
// given
tp.reload();
scope.$digest();
// when, then...
verifyIsDataReloadRequired(function(){
tp.filter({ age: 1});
});
verifyIsDataReloadRequired(function(){
tp.page(55);
});
verifyIsDataReloadRequired(function(){
tp.sorting({ age: 'desc'});
});
verifyIsDataReloadRequired(function(){
tp.count(100);
});
});
it('should return true when `$` field on `filter` changes', function(){
// given
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(false); // checking assumptions
// when
tp.filter().$ = 'cc';
expect(tp.isDataReloadRequired()).toBe(true);
});
it('should return true when group function sort direction changes', function(){
// given
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(false); // checking assumptions
// when, then...
var grouper = function(){ };
tp.group(grouper);
expect(tp.isDataReloadRequired()).toBe(true);
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(false);
grouper.sortDirection = 'desc';
expect(tp.isDataReloadRequired()).toBe(true);
});
it('should return false when parameters "touched" but not modified', function(){
// given
tp.filter({ age: 1});
tp.reload();
scope.$digest();
// when, then...
tp.filter({ age: 1});
expect(tp.isDataReloadRequired()).toBe(false);
});
it('should return true when new settings dataset array supplied', function(){
// given
tp.reload();
scope.$digest();
verifyIsDataReloadRequired(function(){
tp.settings({ dataset: [11,22,33]});
});
});
it('should return true when existing settings dataset array is unset', function(){
// given
tp = createNgTableParams({ dataset: [1,2,3]});
tp.reload();
scope.$digest();
verifyIsDataReloadRequired(function(){
tp.settings({ dataset: null});
});
});
it('status should not change when settings called without a dataset array', function(){
// given
tp = createNgTableParams({ dataset: [1,2,3]});
tp.reload();
scope.$digest();
// when, then...
tp.settings({ total : 100 });
expect(tp.isDataReloadRequired()).toBe(false);
});
function verifyIsDataReloadRequired(modifer){
modifer();
expect(tp.isDataReloadRequired()).toBe(true);
tp.reload();
scope.$digest();
expect(tp.isDataReloadRequired()).toBe(false);
}
});
describe('hasFilterChanges', function(){
var tp;
beforeEach(inject(function(){
tp = createNgTableParams();
}));
it('should return true after construction', function(){
expect(tp.hasFilterChanges()).toBe(true);
});
it('should return false once reload called after construction', function(){
tp.reload();
// note: we don't have to wait for the getData promise to be resolved before considering reload
// to be unnecessary - that's why we're not having to run a $digest
expect(tp.hasFilterChanges()).toBe(false);
});
it('should return true when getData fails', inject(function($q){
tp.settings({ getData: function(){
return $q.reject('bad response');
}});
tp.reload();
scope.$digest();
expect(tp.hasFilterChanges()).toBe(true);
}));
it('should detect direct changes to filters', inject(function($q){
// given
tp.reload();
scope.$digest();
expect(tp.hasFilterChanges()).toBe(false); // checking assumptions
// when
tp.filter().newField = 99;
expect(tp.hasFilterChanges()).toBe(true);
}));
it('should return true when `$` field on `filter` changes', function(){
// given
tp.reload();
scope.$digest();
expect(tp.hasFilterChanges()).toBe(false); // checking assumptions
// when
tp.filter().$ = 'cc';
expect(tp.hasFilterChanges()).toBe(true);
});
it('should return true until changed filters have been reloaded', function(){
// given
tp.reload();
scope.$digest();
// when, then...
tp.filter({ age: 1});
expect(tp.hasFilterChanges()).toBe(true);
tp.reload();
scope.$digest();
expect(tp.hasFilterChanges()).toBe(false);
});
it('should return false when filters "touched" but not modified', function(){
// given
tp.filter({ age: 1});
tp.reload();
scope.$digest();
// when, then...
tp.filter({ age: 1});
expect(tp.hasFilterChanges()).toBe(false);
});
it('status should not change just because new settings dataset array supplied', function(){
// given
tp.reload();
scope.$digest();
// when, then...
tp.settings({ dataset: [11,22,33]});
expect(tp.hasFilterChanges()).toBe(false);
});
});
describe('hasErrorState', function(){
var tp;
it('should return false until reload fails', inject(function($q){
// given
tp = createNgTableParams({ getData: function(){
if (tp.settings().getData.calls.count() > 2){
return $q.reject('bad response');
}
return [1,2];
}});
// when, then
tp.reload();
scope.$digest();
expect(tp.hasErrorState()).toBe(false);
tp.reload();
scope.$digest();
expect(tp.hasErrorState()).toBe(false);
tp.reload();
scope.$digest();
expect(tp.hasErrorState()).toBe(true);
}));
it('should return false once parameter values change', inject(function($q){
// given
tp = createNgTableParams({ getData: function(){
return $q.reject('bad response');
}});
// when, then
tp.reload();
scope.$digest();
expect(tp.hasErrorState()).toBe(true);
tp.filter({ age: 598});
expect(tp.hasErrorState()).toBe(false);
}));
});
describe('backwards compatibility shim', function(){
it('shim should supply getData original arguments', inject(function(ngTableGetDataBcShim){
// given
var callCount = 0;
var adaptedFn = ngTableGetDataBcShim(originalGetDataFn);
// when
var tableParams = new NgTableParams({}, {});
adaptedFn(tableParams);
// then
expect(callCount).toBe(1);
function originalGetDataFn($defer, params){
callCount++;
expect($defer).toBeDefined();
expect($defer.resolve).toBeDefined();
expect(params).toBeDefined();
expect(params).toEqual(jasmine.any(NgTableParams));
}
}));
it('shim should return the getData "$defer" promise', inject(function(ngTableGetDataBcShim){
// given
var callCount = 0;
var adaptedFn = ngTableGetDataBcShim(originalGetDataFn);
// when
var tableParams = new NgTableParams({}, {});
var results = adaptedFn(tableParams);
// then
expect(results).toBeDefined();
expect(results.then).toBeDefined();
results.then(function(data){
expect(data.length).toBe(3);
});
scope.$digest();
function originalGetDataFn($defer/*, params*/){
$defer.resolve([1,2,3]);
}
}));
it('shim should return the data', inject(function(ngTableGetDataBcShim){
// given
var callCount = 0;
var adaptedFn = ngTableGetDataBcShim(originalGetDataFn);
// when
var tableParams = new NgTableParams({}, {});
var results = adaptedFn(tableParams);
// then
expect(results).toBeDefined();
expect(results).toEqual([1,2,3]);
function originalGetDataFn(/*$defer, params*/){
return [1,2,3];
}
}));
it('shim should be applied when getData function supplied has more than one parameter', function(){
// given
var tp = createNgTableParams({ getData: originalGetDataFn});
// when
var dataFetched = tp.reload();
// then
var actualData;
dataFetched.then(function(data){
actualData = data;
});
scope.$digest();
expect(actualData).toEqual([1,2,3]);
function originalGetDataFn($defer, params){
params.total(3);
$defer.resolve([1,2,3]);
}
});
it('shim should NOT be applied when getData has new signature', function(){
// given
var tp = createNgTableParams({ getData: newGetDataFn});
// when
var dataFetched = tp.reload();
// then
var actualData;
dataFetched.then(function(data){
actualData = data;
});
scope.$digest();
expect(actualData).toEqual([1,2,3]);
function newGetDataFn(params){
params.total(3);
return [1,2,3];
}
});
});
describe('interceptors', function(){
it('can register interceptor', function(){
var interceptor = { response: angular.identity };
var tp = createNgTableParams({ interceptors: [interceptor]});
expect(tp.settings().interceptors).toEqual([interceptor]);
});
it('can register multiple interceptor', function(){
var interceptors = [{ response: angular.identity }, { response: angular.identity }];
var tp = createNgTableParams({ interceptors: interceptors});
expect(tp.settings().interceptors).toEqual(interceptors);
});
it('can register interceptors after NgTableParams created', function(){
var interceptor = { response: angular.identity };
var interceptor2 = { response: angular.identity };
var tp = createNgTableParams({ interceptors: [interceptor]});
var interceptors = tp.settings().interceptors.concat([interceptor2]);
tp.settings({ interceptors: interceptors});
expect(tp.settings().interceptors).toEqual(interceptors);
});
describe('one response interceptor', function(){
it('should receive response from call to getData', function(){
// given
var interceptor = {
response: function(/*data, params*/){
this.hasRun = true;
}
};
var tp = createNgTableParams({ interceptors: [interceptor]});
// when
tp.reload();
scope.$digest();
// then
expect(interceptor.hasRun).toBeTruthy();
});
it('should be able to modify data returned by getData', function(){
// given
var interceptor = {
response: function(data/*, params*/){
data.forEach(function(item){
item.modified = true;
});
return data;
}
};
var tp = createNgTableParams({ interceptors: [interceptor], getData: function(){
return [{}, {}];
}});
// when
var actualData;
tp.reload().then(function(data){
actualData = data;
});
scope.$digest();
// then
expect(actualData).toEqual([{ modified: true }, { modified: true }]);
});
it('should be able to replace data returned by getData', function(){
// given
var interceptor = {
response: function(data/*, params*/){
return data.map(function(item){
return item * 2;
});
}
};
var tp = createNgTableParams({ interceptors: [interceptor], getData: function(){
return [2, 3];
}});
// when
var actualData;
tp.reload().then(function(data){
actualData = data;
});
scope.$digest();
// then
expect(actualData).toEqual([4, 6]);
});
it('should be able to access tableParams supplied to getData', function(){
// given
var interceptor = {
response: function(data, params){
params.total(data.total);
return data.results;
}
};
var tp = createNgTableParams({ interceptors: [interceptor], getData: function(){
return { results: [1,2,3], total: 3};
}});
// when
var actualData;
tp.reload().then(function(data){
actualData = data;
});
scope.$digest();
// then
expect(actualData).toEqual([1,2,3]);
expect(tp.total()).toEqual(3);
});
});
describe('one responseError interceptor', function(){
it('should receive rejections from getData', inject(function($q){
// given
var interceptor = {
responseError: function(reason/*, params*/){
this.actualReason = reason;
}
};
var tp = createNgTableParams({
interceptors: [interceptor],
getData: function(/*params*/){
return $q.reject('BANG!');
}
});
// when
tp.reload();
scope.$digest();
// then
expect(interceptor.actualReason).toBe('BANG!');
}));
it('should NOT receive errors from getData', function(){
// given
var interceptor = {
responseError: function(/*reason, params*/){
this.hasRun = true;
}
};
var tp = createNgTableParams({
interceptors: [interceptor],
getData: function(/*params*/){
throw new Error('BANG!');
}
});
// when, then
expect(tp.reload).toThrow();
expect(interceptor.hasRun).toBeFalsy();
});
it('should be able to modify reason returned by getData', inject(function($q){
// given
var interceptor = {
responseError: function(reason/*, params*/){
reason.code = 400;
return $q.reject(reason);
}
};
var tp = createNgTableParams({
interceptors: [interceptor],
getData: function(/*params*/){
return $q.reject({ description: 'crappy data'});
}
});
// when
var actualReason;
tp.reload().catch(function(reason){
actualReason = reason;
});
scope.$digest();
// then
expect(actualReason.code).toBe(400);
expect(actualReason.description).toBe('crappy data');
}));
it('should be able to replace reason returned by getData', inject(function($q){
// given
var interceptor = {
responseError: function(/*reason, params*/){
return $q.reject('Cancelled by user');
}
};
var tp = createNgTableParams({
interceptors: [interceptor],
getData: function(/*params*/){
return $q.reject('BANG!');
}
});
// when
var actualReason;
tp.reload().catch(function(reason){
actualReason = reason;
});
scope.$digest();
// then
expect(actualReason).toBe('Cancelled by user');
}));
it('should be able to access tableParams supplied to getData', function(){
// given
var interceptor = {
response: function(reason, params){
this.actualParams = params;
}
};
var tp = createNgTableParams({ interceptors: [interceptor]});
// when
var actualData;
tp.reload();
scope.$digest();
// then
expect(interceptor.actualParams).toBe(tp);
});
});
describe('one response plus responseError interceptor', function(){
it('should NOT call responseError on same interceptor whose response method fails', inject(function($q){
// given
var interceptor = {
response: function(/*data, params*/){
return $q.reject('BANG!');
},
responseError: function(reason/*, params*/){
this.hasRun = true;
}
};
var tp = createNgTableParams({
interceptors: [interceptor],
getData: function(/*params*/){
return [1,2,3];
}
});
// when
tp.reload();
scope.$digest();
// then
expect(interceptor.hasRun).toBeFalsy();
}));
});
describe('multiple response interceptors', function(){
it('should run interceptors in the order they were registered', function(){
// given
var callCount = 0;
var interceptor = {
response: function(/*data, params*/){
this.sequence = callCount;
callCount++;
}
};
var interceptors = [interceptor, angular.copy(interceptor)];
var tp = createNgTableParams({ interceptors: interceptors});
// when
tp.reload();
scope.$digest();
// then
expect(interceptors[0].sequence).toBe(0);
expect(interceptors[1].sequence).toBe(1);
});
it('results of one interceptor should be piped to the next validator', function(){
// given
var interceptor = {
response: function(data/*, params*/){
return data.map(function(item){
return item * 2;
});
}
};
var interceptor2 = {
response: function(data/*, params*/){
return data.map(function(item){
return item.toString() + '0';
});
}
};
var tp = createNgTableParams({ interceptors: [interceptor, interceptor2], getData: function(){
return [2, 3];
}});
// when
var actualData;
tp.reload().then(function(data){
actualData = data;
});
scope.$digest();
// then
expect(actualData).toEqual(['40', '60']);
});
});
describe('multiple response and responseError interceptors', function(){
it('responseError of next interceptor should receive failures from previous interceptor', inject(function($q){
// given
var badInterceptor = {
response: function(/*data, params*/){
return $q.reject('BANG!');
}
};
var nextInterceptor = {
responseError: function(/*reason, params*/){
this.hasRun = true;
}
};
var tp = createNgTableParams({ interceptors: [badInterceptor, nextInterceptor]});
// when
tp.reload();
scope.$digest();
// then
expect(nextInterceptor.hasRun).toBe(true);
}));
it('should call next response interceptor when previous interceptor recovers from failure', inject(function($q){
// given
var badInterceptor = {
response: function(/*data, params*/){
return $q.reject('BANG!');
}
};
var recoveringInterceptor = {
responseError: function(/*reason, params*/){
return [8894,58];
}
};
var recoveredData;
var nextInterceptor = {
response: function(data/*, params*/){
this.hasRun = true;
recoveredData = data;
}
};
var tp = createNgTableParams({ interceptors: [badInterceptor, recoveringInterceptor, nextInterceptor]});
// when
tp.reload();
scope.$digest();
// then
expect(nextInterceptor.hasRun).toBe(true);
expect(recoveredData).toEqual([8894,58]);
}));
});
});
describe('events', function(){
var actualEventArgs,
actualPublisher,
fakeTableParams,
ngTableEventsChannel;
beforeEach(inject(function(_ngTableEventsChannel_){
ngTableEventsChannel = _ngTableEventsChannel_;
fakeTableParams = {};
actualPublisher = undefined;
actualEventArgs = undefined;
}));
function getSubscriberCount(){
var allEventNames = Object.keys($rootScope.$$listenerCount);
var ngTableEvents = allEventNames.filter(function(event){
return event.indexOf('ngTable:') === 0;
});
return ngTableEvents.reduce(function(result, event){
result += $rootScope.$$listenerCount[event];
return result;
}, 0);
}
describe('general pub/sub mechanics', function(){
var supportedEvents = ['DatasetChanged', 'AfterReloadData', 'PagesChanged', 'AfterCreated'];
it('should be safe to publish event when no subscribers', function () {
function test(event) {
ngTableEventsChannel['publish' + event](fakeTableParams);
}
supportedEvents.forEach(test);
});
it('publishing event should notify registered subscribers (one)', function(){
function test(event){
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function(){
cbCount++;
});
// when
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(cbCount).toBe(1);
}
supportedEvents.forEach(test);
});
it('publishing event should notify registered subscribers (multiple)', function(){
function test(event){
// given
var cb1Count = 0;
ngTableEventsChannel['on' + event](function(){
cb1Count++;
});
var cb2Count = 0;
ngTableEventsChannel['on' + event](function(){
cb2Count++;
});
// when
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(cb1Count).toBe(1);
expect(cb2Count).toBe(1);
}
supportedEvents.forEach(test);
});
it('subscriber should be able to unregister their callback', function(){
function test(event){
// given
var cbCount = 0;
var subscription = ngTableEventsChannel['on' + event](function(){
cbCount++;
});
ngTableEventsChannel['publish' + event](fakeTableParams);
expect(cbCount).toBe(1); // checking assumptions
expect(getSubscriberCount()).toBe(1); // checking assumptions
cbCount = 0; // reset
// when
subscription(); // unsubscribe
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(cbCount).toBe(0);
expect(getSubscriberCount()).toBe(0);
}
supportedEvents.forEach(test);
});
it('subscriber should be able specify the scope to receive events', function(){
// this is useful as it allows all subscriptions to be removed by calling $destroy on that scope
function test(event){
// given
var childScope = $rootScope.$new();
var cbCount = 0;
ngTableEventsChannel['on' + event](function(){
cbCount++;
}, childScope);
// when, then
ngTableEventsChannel['publish' + event](fakeTableParams);
expect(cbCount).toBe(1);
cbCount = 0; // reset
// when, then
childScope.$destroy();
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(cbCount).toBe(0);
}
supportedEvents.forEach(test);
});
it('should not notify subscribers who have filter out the publisher', function(){
function test(event){
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function(){
cbCount++;
}, function(publisher){
return publisher === fakeTableParams;
});
// when
ngTableEventsChannel['publish' + event](fakeTableParams);
var anoParams = {};
ngTableEventsChannel['publish' + event](anoParams);
// then
expect(cbCount).toBe(1);
}
supportedEvents.forEach(test);
});
it('should not notify subscribers who have filter not to receive event based on arg values', function(){
function test(event){
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function(){
cbCount++;
}, function(publisher, arg1){
return arg1 === 1;
});
// when
ngTableEventsChannel['publish' + event](fakeTableParams, 'cc');
ngTableEventsChannel['publish' + event](fakeTableParams, 1);
// then
expect(cbCount).toBe(1);
}
supportedEvents.forEach(test);
});
it('should support a shorthand for subscribers to receive events from specific NgTableParams instance', function () {
function test(event) {
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function () {
cbCount++;
}, fakeTableParams);
// when
ngTableEventsChannel['publish' + event](fakeTableParams);
var anoParams = {};
ngTableEventsChannel['publish' + event](anoParams);
// then
expect(cbCount).toBe(1);
}
supportedEvents.forEach(test);
});
it('publisher should be supplied to subscriber callback', function(){
function test(event){
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function(params){
actualPublisher = params;
});
// when
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(actualPublisher).toBe(fakeTableParams);
}
supportedEvents.forEach(test);
});
it('remaining event args should be supplied to subscriber callback', function(){
function test(event){
// given
ngTableEventsChannel['on' + event](function(params/*, ...args*/){
actualPublisher = params;
actualEventArgs = _.rest(arguments);
});
// when
var arg1 = [1, 2];
var arg2 = [1];
ngTableEventsChannel['publish' + event](fakeTableParams, arg1, arg2);
// then
expect(actualEventArgs).toEqual([arg1, arg2]);
}
supportedEvents.forEach(test);
});
it('subscribers should never receive events from null instance of tableParams', function(){
function test(event){
// given
var cbCount = 0;
ngTableEventsChannel['on' + event](function(params/*, ...args*/){
cbCount++;
});
// when
fakeTableParams.isNullInstance = true;
ngTableEventsChannel['publish' + event](fakeTableParams);
// then
expect(cbCount).toEqual(0);
}
supportedEvents.forEach(test);
});
});
describe('afterCreated', function(){
it('should fire when a new NgTableParams has been constructed', function(){
// given
ngTableEventsChannel.onAfterCreated(function(params){
actualPublisher = params;
});
// when
var params = createNgTableParams();
// then
expect(actualPublisher).toBe(params);
});
});
describe('afterReloadData', function(){
it('should fire when a reload completes', function(){
// given
ngTableEventsChannel.onAfterReloadData(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
var newDatapage = [1, 5, 6];
var params = createNgTableParams({ getData: function(){
return newDatapage;
}});
// when
params.reload();
scope.$digest();
// then
expect(actualPublisher).toBe(params);
expect(actualEventArgs).toEqual([newDatapage, []]);
});
it('should fire on reload even if datapage remains the same array', function(){
// given
var callCount = 0;
ngTableEventsChannel.onAfterReloadData(function(/*params, newVal, oldVal*/){
callCount++;
});
var dataPage = [1,2,3];
var params = createNgTableParams({ getData: function(){
return dataPage;
}});
// when
params.reload();
scope.$digest();
params.reload();
scope.$digest();
// then
expect(callCount).toBe(2);
});
it('should fire after afterCreated event', function(){
// given
var events = [];
ngTableEventsChannel.onAfterReloadData(function(/*params, newVal, oldVal*/){
events.push('afterReloadData');
});
ngTableEventsChannel.onAfterCreated(function(/*params*/){
events.push('afterCreated');
});
// when
var params = createNgTableParams({}, {dataset: [1,2,3,4,5,6]});
params.reload();
scope.$digest();
// then
expect(events[0]).toEqual('afterCreated');
expect(events[1]).toEqual('afterReloadData');
});
});
describe('pagesChanged', function(){
it('should fire when a reload completes', function(){
// given
ngTableEventsChannel.onPagesChanged(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
var params = createNgTableParams({ count: 5 }, { counts: [5,10], dataset: [1,2,3,4,5,6]});
// when
params.reload();
scope.$digest();
// then
var expectedPages = params.generatePagesArray(params.page(), params.total(), params.count());
expect(expectedPages.length).toBeGreaterThan(0); // checking assumptions
expect(actualEventArgs).toEqual([expectedPages, undefined]);
});
it('should fire when a reload completes - no data', function(){
// given
ngTableEventsChannel.onPagesChanged(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
var params = createNgTableParams({ count: 5 }, { counts: [5,10], dataset: []});
// when
params.reload();
scope.$digest();
// then
expect(actualEventArgs).toEqual([[], undefined]);
});
it('should fire when a reload completes (multiple)', function(){
// given
var callCount = 0;
ngTableEventsChannel.onPagesChanged(function(/*params, newVal, oldVal*/){
callCount++;
});
var params = createNgTableParams({ count: 5 }, { counts: [5,10], dataset: [1,2,3,4,5,6]});
// when
params.reload();
scope.$digest();
params.page(2); // trigger a change to pages data structure
params.reload();
scope.$digest();
// then
expect(callCount).toBe(2);
});
it('should not fire on reload when pages remain the same', function(){
// given
var callCount = 0;
ngTableEventsChannel.onPagesChanged(function(/*params, newVal, oldVal*/){
callCount++;
});
var params = createNgTableParams({ count: 5 }, { counts: [5,10], dataset: [1,2,3,4,5,6]});
params.reload();
scope.$digest();
// when
params.reload();
scope.$digest();
// then
expect(callCount).toBe(1);
});
it('should fire after afterCreated event', function(){
// given
var events = [];
ngTableEventsChannel.onPagesChanged(function(/*params, newVal, oldVal*/){
events.push('pagesChanged');
});
ngTableEventsChannel.onAfterCreated(function(/*params*/){
events.push('afterCreated');
});
// when
var params = createNgTableParams({ count: 5 }, { counts: [5,10], dataset: [1,2,3,4,5,6]});
params.reload();
scope.$digest();
// then
expect(events[0]).toEqual('afterCreated');
expect(events[1]).toEqual('pagesChanged');
});
});
describe('datasetChanged', function(){
it('should fire when a initial dataset is supplied as a settings value', function(){
// given
ngTableEventsChannel.onDatasetChanged(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
// when
var initialDs = [5, 10];
var params = createNgTableParams({ dataset: initialDs});
// then
expect(actualPublisher).toBe(params);
expect(actualEventArgs).toEqual([initialDs, null]);
});
it('should fire when a new dataset is supplied as a settings value', function(){
// given
var initialDs = [1, 2];
ngTableEventsChannel.onDatasetChanged(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
var params = createNgTableParams({ dataset: initialDs});
// when
var newDs = [5, 10];
params.settings({ dataset: newDs});
// then
expect(actualPublisher).toBe(params);
expect(actualEventArgs).toEqual([newDs, initialDs]);
});
it('should fire when a dataset is removed from settings value', function(){
// given
var initialDs = [1, 2];
ngTableEventsChannel.onDatasetChanged(function(params, newVal, oldVal){
actualPublisher = params;
actualEventArgs = [newVal, oldVal];
});
var params = createNgTableParams({ dataset: initialDs});
// when
var newDs = null;
params.settings({ dataset: newDs});
// then
expect(actualPublisher).toBe(params);
expect(actualEventArgs).toEqual([newDs, initialDs]);
});
it('should NOT fire when the same dataset array is supplied as a new settings value', function(){
// given
var callCount = 0;
var initialDs = [1, 2];
ngTableEventsChannel.onDatasetChanged(function(/*params, newVal, oldVal*/){
callCount++;
});
var params = createNgTableParams({ dataset: initialDs});
// when
params.settings({ dataset: initialDs});
// then
expect(callCount).toBe(1);
});
it('settings().dataset on publisher should reference the new dataset', function(){
var initialDs = [1, 2];
var newDs = [1, 2, 3];
var params = createNgTableParams({ dataset: initialDs});
ngTableEventsChannel.onDatasetChanged(function(params, newVal/*, oldVal*/){
expect(params.settings().dataset).toBe(newVal);
});
params.settings({ dataset: newDs});
});
it('should fire after afterCreated event', function(){
// given
var events = [];
var initialDs = [1, 2];
ngTableEventsChannel.onDatasetChanged(function(/*params, newVal, oldVal*/){
events.push('datasetChanged');
});
ngTableEventsChannel.onAfterCreated(function(/*params*/){
events.push('afterCreated');
});
// when
var params = createNgTableParams({ dataset: initialDs});
// then
expect(events[0]).toEqual('afterCreated');
expect(events[1]).toEqual('datasetChanged');
});
});
})
});
| amir-s/ng-table | test/tableParamsSpec.js | JavaScript | bsd-3-clause | 70,617 |
// Copyright 2013 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.
package org.chromium.content.browser;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;
import org.chromium.base.CpuFeatures;
import org.chromium.base.ThreadUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.library_loader.Linker;
import org.chromium.content.app.ChildProcessService;
import org.chromium.content.app.ChromiumLinkerParams;
import org.chromium.content.common.IChildProcessCallback;
import org.chromium.content.common.IChildProcessService;
import java.io.IOException;
/**
* Manages a connection between the browser activity and a child service.
*/
public class ChildProcessConnectionImpl implements ChildProcessConnection {
private final Context mContext;
private final int mServiceNumber;
private final boolean mInSandbox;
private final ChildProcessConnection.DeathCallback mDeathCallback;
private final Class<? extends ChildProcessService> mServiceClass;
// Synchronization: While most internal flow occurs on the UI thread, the public API
// (specifically start and stop) may be called from any thread, hence all entry point methods
// into the class are synchronized on the lock to protect access to these members.
private final Object mLock = new Object();
private IChildProcessService mService = null;
// Set to true when the service connected successfully.
private boolean mServiceConnectComplete = false;
// Set to true when the service disconnects, as opposed to being properly closed. This happens
// when the process crashes or gets killed by the system out-of-memory killer.
private boolean mServiceDisconnected = false;
// When the service disconnects (i.e. mServiceDisconnected is set to true), the status of the
// oom bindings is stashed here for future inspection.
private boolean mWasOomProtected = false;
private int mPid = 0; // Process ID of the corresponding child process.
// Initial binding protects the newly spawned process from being killed before it is put to use,
// it is maintained between calls to start() and removeInitialBinding().
private ChildServiceConnection mInitialBinding = null;
// Strong binding will make the service priority equal to the priority of the activity. We want
// the OS to be able to kill background renderers as it kills other background apps, so strong
// bindings are maintained only for services that are active at the moment (between
// addStrongBinding() and removeStrongBinding()).
private ChildServiceConnection mStrongBinding = null;
// Low priority binding maintained in the entire lifetime of the connection, i.e. between calls
// to start() and stop().
private ChildServiceConnection mWaivedBinding = null;
// Incremented on addStrongBinding(), decremented on removeStrongBinding().
private int mStrongBindingCount = 0;
// Linker-related parameters.
private ChromiumLinkerParams mLinkerParams = null;
private final boolean mAlwaysInForeground;
private static final String TAG = "ChildProcessConnection";
private static class ConnectionParams {
final String[] mCommandLine;
final FileDescriptorInfo[] mFilesToBeMapped;
final IChildProcessCallback mCallback;
final Bundle mSharedRelros;
ConnectionParams(String[] commandLine, FileDescriptorInfo[] filesToBeMapped,
IChildProcessCallback callback, Bundle sharedRelros) {
mCommandLine = commandLine;
mFilesToBeMapped = filesToBeMapped;
mCallback = callback;
mSharedRelros = sharedRelros;
}
}
// This is set in setupConnection() and is later used in doConnectionSetupLocked(), after which
// the variable is cleared. Therefore this is only valid while the connection is being set up.
private ConnectionParams mConnectionParams;
// Callback provided in setupConnection() that will communicate the result to the caller. This
// has to be called exactly once after setupConnection(), even if setup fails, so that the
// caller can free up resources associated with the setup attempt. This is set to null after the
// call.
private ChildProcessConnection.ConnectionCallback mConnectionCallback;
private class ChildServiceConnection implements ServiceConnection {
private boolean mBound = false;
private final int mBindFlags;
private Intent createServiceBindIntent() {
Intent intent = new Intent();
intent.setClassName(mContext, mServiceClass.getName() + mServiceNumber);
intent.setPackage(mContext.getPackageName());
return intent;
}
public ChildServiceConnection(int bindFlags) {
mBindFlags = bindFlags;
}
boolean bind(String[] commandLine) {
if (!mBound) {
try {
TraceEvent.begin("ChildProcessConnectionImpl.ChildServiceConnection.bind");
final Intent intent = createServiceBindIntent();
if (commandLine != null) {
intent.putExtra(EXTRA_COMMAND_LINE, commandLine);
}
if (mLinkerParams != null) {
mLinkerParams.addIntentExtras(intent);
}
mBound = mContext.bindService(intent, this, mBindFlags);
} finally {
TraceEvent.end("ChildProcessConnectionImpl.ChildServiceConnection.bind");
}
}
return mBound;
}
void unbind() {
if (mBound) {
mContext.unbindService(this);
mBound = false;
}
}
boolean isBound() {
return mBound;
}
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
synchronized (mLock) {
// A flag from the parent class ensures we run the post-connection logic only once
// (instead of once per each ChildServiceConnection).
if (mServiceConnectComplete) {
return;
}
try {
TraceEvent.begin(
"ChildProcessConnectionImpl.ChildServiceConnection.onServiceConnected");
mServiceConnectComplete = true;
mService = IChildProcessService.Stub.asInterface(service);
// Run the setup if the connection parameters have already been provided. If
// not, doConnectionSetupLocked() will be called from setupConnection().
if (mConnectionParams != null) {
doConnectionSetupLocked();
}
} finally {
TraceEvent.end(
"ChildProcessConnectionImpl.ChildServiceConnection.onServiceConnected");
}
}
}
// Called on the main thread to notify that the child service did not disconnect gracefully.
@Override
public void onServiceDisconnected(ComponentName className) {
synchronized (mLock) {
// Ensure that the disconnection logic runs only once (instead of once per each
// ChildServiceConnection).
if (mServiceDisconnected) {
return;
}
// Stash the status of the oom bindings, since stop() will release all bindings.
mWasOomProtected = isCurrentlyOomProtected();
mServiceDisconnected = true;
Log.w(TAG, "onServiceDisconnected (crash or killed by oom): pid=" + mPid);
stop(); // We don't want to auto-restart on crash. Let the browser do that.
mDeathCallback.onChildProcessDied(ChildProcessConnectionImpl.this);
// If we have a pending connection callback, we need to communicate the failure to
// the caller.
if (mConnectionCallback != null) {
mConnectionCallback.onConnected(0);
}
mConnectionCallback = null;
}
}
}
ChildProcessConnectionImpl(Context context, int number, boolean inSandbox,
ChildProcessConnection.DeathCallback deathCallback,
Class<? extends ChildProcessService> serviceClass,
ChromiumLinkerParams chromiumLinkerParams,
boolean alwaysInForeground) {
mContext = context;
mServiceNumber = number;
mInSandbox = inSandbox;
mDeathCallback = deathCallback;
mServiceClass = serviceClass;
mLinkerParams = chromiumLinkerParams;
mAlwaysInForeground = alwaysInForeground;
int initialFlags = Context.BIND_AUTO_CREATE;
if (mAlwaysInForeground) initialFlags |= Context.BIND_IMPORTANT;
mInitialBinding = new ChildServiceConnection(initialFlags);
mStrongBinding = new ChildServiceConnection(
Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);
mWaivedBinding = new ChildServiceConnection(
Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY);
}
@Override
public int getServiceNumber() {
return mServiceNumber;
}
@Override
public boolean isInSandbox() {
return mInSandbox;
}
@Override
public IChildProcessService getService() {
synchronized (mLock) {
return mService;
}
}
@Override
public int getPid() {
synchronized (mLock) {
return mPid;
}
}
@Override
public void start(String[] commandLine) {
try {
TraceEvent.begin("ChildProcessConnectionImpl.start");
synchronized (mLock) {
assert !ThreadUtils.runningOnUiThread();
assert mConnectionParams == null :
"setupConnection() called before start() in ChildProcessConnectionImpl.";
if (!mInitialBinding.bind(commandLine)) {
Log.e(TAG, "Failed to establish the service connection.");
// We have to notify the caller so that they can free-up associated resources.
// TODO(ppi): Can we hard-fail here?
mDeathCallback.onChildProcessDied(ChildProcessConnectionImpl.this);
} else {
mWaivedBinding.bind(null);
}
}
} finally {
TraceEvent.end("ChildProcessConnectionImpl.start");
}
}
@Override
public void setupConnection(
String[] commandLine,
FileDescriptorInfo[] filesToBeMapped,
IChildProcessCallback processCallback,
ConnectionCallback connectionCallback,
Bundle sharedRelros) {
synchronized (mLock) {
assert mConnectionParams == null;
if (mServiceDisconnected) {
Log.w(TAG, "Tried to setup a connection that already disconnected.");
connectionCallback.onConnected(0);
return;
}
try {
TraceEvent.begin("ChildProcessConnectionImpl.setupConnection");
mConnectionCallback = connectionCallback;
mConnectionParams = new ConnectionParams(
commandLine, filesToBeMapped, processCallback, sharedRelros);
// Run the setup if the service is already connected. If not,
// doConnectionSetupLocked() will be called from onServiceConnected().
if (mServiceConnectComplete) {
doConnectionSetupLocked();
}
} finally {
TraceEvent.end("ChildProcessConnectionImpl.setupConnection");
}
}
}
@Override
public void stop() {
synchronized (mLock) {
mInitialBinding.unbind();
mStrongBinding.unbind();
mWaivedBinding.unbind();
mStrongBindingCount = 0;
if (mService != null) {
mService = null;
}
mConnectionParams = null;
}
}
/**
* Called after the connection parameters have been set (in setupConnection()) *and* a
* connection has been established (as signaled by onServiceConnected()). These two events can
* happen in any order. Has to be called with mLock.
*/
private void doConnectionSetupLocked() {
try {
TraceEvent.begin("ChildProcessConnectionImpl.doConnectionSetupLocked");
assert mServiceConnectComplete && mService != null;
assert mConnectionParams != null;
Bundle bundle = new Bundle();
bundle.putStringArray(EXTRA_COMMAND_LINE, mConnectionParams.mCommandLine);
FileDescriptorInfo[] fileInfos = mConnectionParams.mFilesToBeMapped;
ParcelFileDescriptor[] parcelFiles = new ParcelFileDescriptor[fileInfos.length];
for (int i = 0; i < fileInfos.length; i++) {
if (fileInfos[i].mFd == -1) {
// If someone provided an invalid FD, they are doing something wrong.
Log.e(TAG, "Invalid FD (id=" + fileInfos[i].mId + ") for process connection, "
+ "aborting connection.");
return;
}
String idName = EXTRA_FILES_PREFIX + i + EXTRA_FILES_ID_SUFFIX;
String fdName = EXTRA_FILES_PREFIX + i + EXTRA_FILES_FD_SUFFIX;
if (fileInfos[i].mAutoClose) {
// Adopt the FD, it will be closed when we close the ParcelFileDescriptor.
parcelFiles[i] = ParcelFileDescriptor.adoptFd(fileInfos[i].mFd);
} else {
try {
parcelFiles[i] = ParcelFileDescriptor.fromFd(fileInfos[i].mFd);
} catch (IOException e) {
Log.e(TAG,
"Invalid FD provided for process connection, aborting connection.",
e);
return;
}
}
bundle.putParcelable(fdName, parcelFiles[i]);
bundle.putInt(idName, fileInfos[i].mId);
}
// Add the CPU properties now.
bundle.putInt(EXTRA_CPU_COUNT, CpuFeatures.getCount());
bundle.putLong(EXTRA_CPU_FEATURES, CpuFeatures.getMask());
bundle.putBundle(Linker.EXTRA_LINKER_SHARED_RELROS,
mConnectionParams.mSharedRelros);
try {
mPid = mService.setupConnection(bundle, mConnectionParams.mCallback);
assert mPid != 0 : "Child service claims to be run by a process of pid=0.";
} catch (android.os.RemoteException re) {
Log.e(TAG, "Failed to setup connection.", re);
}
// We proactively close the FDs rather than wait for GC & finalizer.
try {
for (ParcelFileDescriptor parcelFile : parcelFiles) {
if (parcelFile != null) parcelFile.close();
}
} catch (IOException ioe) {
Log.w(TAG, "Failed to close FD.", ioe);
}
mConnectionParams = null;
if (mConnectionCallback != null) {
mConnectionCallback.onConnected(mPid);
}
mConnectionCallback = null;
} finally {
TraceEvent.end("ChildProcessConnectionImpl.doConnectionSetupLocked");
}
}
@Override
public boolean isInitialBindingBound() {
synchronized (mLock) {
return mInitialBinding.isBound();
}
}
@Override
public boolean isStrongBindingBound() {
synchronized (mLock) {
return mStrongBinding.isBound();
}
}
@Override
public void removeInitialBinding() {
synchronized (mLock) {
assert !mAlwaysInForeground;
mInitialBinding.unbind();
}
}
@Override
public boolean isOomProtectedOrWasWhenDied() {
synchronized (mLock) {
if (mServiceDisconnected) {
return mWasOomProtected;
} else {
return isCurrentlyOomProtected();
}
}
}
private boolean isCurrentlyOomProtected() {
synchronized (mLock) {
assert !mServiceDisconnected;
if (mAlwaysInForeground) return ChildProcessLauncher.isApplicationInForeground();
return mInitialBinding.isBound() || mStrongBinding.isBound();
}
}
@Override
public void dropOomBindings() {
synchronized (mLock) {
assert !mAlwaysInForeground;
mInitialBinding.unbind();
mStrongBindingCount = 0;
mStrongBinding.unbind();
}
}
@Override
public void addStrongBinding() {
synchronized (mLock) {
if (mService == null) {
Log.w(TAG, "The connection is not bound for " + mPid);
return;
}
if (mStrongBindingCount == 0) {
mStrongBinding.bind(null);
}
mStrongBindingCount++;
}
}
@Override
public void removeStrongBinding() {
synchronized (mLock) {
if (mService == null) {
Log.w(TAG, "The connection is not bound for " + mPid);
return;
}
assert mStrongBindingCount > 0;
mStrongBindingCount--;
if (mStrongBindingCount == 0) {
mStrongBinding.unbind();
}
}
}
@VisibleForTesting
public boolean crashServiceForTesting() throws RemoteException {
try {
mService.crashIntentionallyForTesting();
} catch (DeadObjectException e) {
return true;
}
return false;
}
@VisibleForTesting
public boolean isConnected() {
return mService != null;
}
}
| guorendong/iridium-browser-ubuntu | content/public/android/java/src/org/chromium/content/browser/ChildProcessConnectionImpl.java | Java | bsd-3-clause | 18,767 |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>killerbee.dot154decode</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="killerbee-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="killerbee-module.html">Package killerbee</a> ::
Module dot154decode
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="killerbee.dot154decode-pysrc.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<h1 class="epydoc">Source Code for <a href="killerbee.dot154decode-module.html">Module killerbee.dot154decode</a></h1>
<pre class="py-src">
<a name="L1"></a><tt class="py-lineno"> 1</tt> <tt class="py-line"><tt class="py-keyword">import</tt> <tt class="py-name">struct</tt> </tt>
<a name="L2"></a><tt class="py-lineno"> 2</tt> <tt class="py-line"><tt class="py-keyword">from</tt> <tt class="py-name">Crypto</tt><tt class="py-op">.</tt><tt class="py-name">Cipher</tt> <tt class="py-keyword">import</tt> <tt class="py-name">AES</tt> </tt>
<a name="L3"></a><tt class="py-lineno"> 3</tt> <tt class="py-line"> </tt>
<a name="L4"></a><tt class="py-lineno"> 4</tt> <tt class="py-line"> </tt>
<a name="L5"></a><tt class="py-lineno"> 5</tt> <tt class="py-line"><tt class="py-comment">## Constants for packet decoding fields</tt> </tt>
<a name="L6"></a><tt class="py-lineno"> 6</tt> <tt class="py-line"><tt class="py-comment"># Frame Control Field</tt> </tt>
<a name="L7"></a><tt class="py-lineno"> 7</tt> <tt class="py-line"><tt id="link-0" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_MASK=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_MASK"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_MASK" class="py-name" href="#" onclick="return doclink('link-0', 'DOT154_FCF_TYPE_MASK', 'link-0');">DOT154_FCF_TYPE_MASK</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0007</tt> <tt class="py-comment">#: Frame type mask</tt> </tt>
<a name="L8"></a><tt class="py-lineno"> 8</tt> <tt class="py-line"><tt id="link-1" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_SEC_EN=killerbee.dot154decode-module.html#DOT154_FCF_SEC_EN"><a title="killerbee.dot154decode.DOT154_FCF_SEC_EN" class="py-name" href="#" onclick="return doclink('link-1', 'DOT154_FCF_SEC_EN', 'link-1');">DOT154_FCF_SEC_EN</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0008</tt> <tt class="py-comment">#: Set for encrypted payload</tt> </tt>
<a name="L9"></a><tt class="py-lineno"> 9</tt> <tt class="py-line"><tt id="link-2" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_FRAME_PND=killerbee.dot154decode-module.html#DOT154_FCF_FRAME_PND"><a title="killerbee.dot154decode.DOT154_FCF_FRAME_PND" class="py-name" href="#" onclick="return doclink('link-2', 'DOT154_FCF_FRAME_PND', 'link-2');">DOT154_FCF_FRAME_PND</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0010</tt> <tt class="py-comment">#: Frame pending</tt> </tt>
<a name="L10"></a><tt class="py-lineno"> 10</tt> <tt class="py-line"><tt id="link-3" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_ACK_REQ=killerbee.dot154decode-module.html#DOT154_FCF_ACK_REQ"><a title="killerbee.dot154decode.DOT154_FCF_ACK_REQ" class="py-name" href="#" onclick="return doclink('link-3', 'DOT154_FCF_ACK_REQ', 'link-3');">DOT154_FCF_ACK_REQ</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0020</tt> <tt class="py-comment">#: ACK request</tt> </tt>
<a name="L11"></a><tt class="py-lineno"> 11</tt> <tt class="py-line"><tt id="link-4" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_INTRA_PAN=killerbee.dot154decode-module.html#DOT154_FCF_INTRA_PAN"><a title="killerbee.dot154decode.DOT154_FCF_INTRA_PAN" class="py-name" href="#" onclick="return doclink('link-4', 'DOT154_FCF_INTRA_PAN', 'link-4');">DOT154_FCF_INTRA_PAN</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0040</tt> <tt class="py-comment">#: Intra-PAN activity</tt> </tt>
<a name="L12"></a><tt class="py-lineno"> 12</tt> <tt class="py-line"><tt id="link-5" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_DADDR_MASK=killerbee.dot154decode-module.html#DOT154_FCF_DADDR_MASK"><a title="killerbee.dot154decode.DOT154_FCF_DADDR_MASK" class="py-name" href="#" onclick="return doclink('link-5', 'DOT154_FCF_DADDR_MASK', 'link-5');">DOT154_FCF_DADDR_MASK</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0C00</tt> <tt class="py-comment">#: Destination addressing mode mask</tt> </tt>
<a name="L13"></a><tt class="py-lineno"> 13</tt> <tt class="py-line"><tt id="link-6" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_VERSION_MASK=killerbee.dot154decode-module.html#DOT154_FCF_VERSION_MASK"><a title="killerbee.dot154decode.DOT154_FCF_VERSION_MASK" class="py-name" href="#" onclick="return doclink('link-6', 'DOT154_FCF_VERSION_MASK', 'link-6');">DOT154_FCF_VERSION_MASK</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x3000</tt> <tt class="py-comment">#: Frame version</tt> </tt>
<a name="L14"></a><tt class="py-lineno"> 14</tt> <tt class="py-line"><tt id="link-7" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_SADDR_MASK=killerbee.dot154decode-module.html#DOT154_FCF_SADDR_MASK"><a title="killerbee.dot154decode.DOT154_FCF_SADDR_MASK" class="py-name" href="#" onclick="return doclink('link-7', 'DOT154_FCF_SADDR_MASK', 'link-7');">DOT154_FCF_SADDR_MASK</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0xC000</tt> <tt class="py-comment">#: Source addressing mask mode</tt> </tt>
<a name="L15"></a><tt class="py-lineno"> 15</tt> <tt class="py-line"> </tt>
<a name="L16"></a><tt class="py-lineno"> 16</tt> <tt class="py-line"><tt class="py-comment"># Frame Control Field Bit Shifts</tt> </tt>
<a name="L17"></a><tt class="py-lineno"> 17</tt> <tt class="py-line"><tt id="link-8" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_MASK_SHIFT=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_MASK_SHIFT"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_MASK_SHIFT" class="py-name" href="#" onclick="return doclink('link-8', 'DOT154_FCF_TYPE_MASK_SHIFT', 'link-8');">DOT154_FCF_TYPE_MASK_SHIFT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0</tt> <tt class="py-comment">#: Frame type mask mode shift</tt> </tt>
<a name="L18"></a><tt class="py-lineno"> 18</tt> <tt class="py-line"><tt id="link-9" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_DADDR_MASK_SHIFT=killerbee.dot154decode-module.html#DOT154_FCF_DADDR_MASK_SHIFT"><a title="killerbee.dot154decode.DOT154_FCF_DADDR_MASK_SHIFT" class="py-name" href="#" onclick="return doclink('link-9', 'DOT154_FCF_DADDR_MASK_SHIFT', 'link-9');">DOT154_FCF_DADDR_MASK_SHIFT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">10</tt> <tt class="py-comment">#: Destination addressing mode mask</tt> </tt>
<a name="L19"></a><tt class="py-lineno"> 19</tt> <tt class="py-line"><tt id="link-10" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_VERSION_MASK_SHIFT=killerbee.dot154decode-module.html#DOT154_FCF_VERSION_MASK_SHIFT"><a title="killerbee.dot154decode.DOT154_FCF_VERSION_MASK_SHIFT" class="py-name" href="#" onclick="return doclink('link-10', 'DOT154_FCF_VERSION_MASK_SHIFT', 'link-10');">DOT154_FCF_VERSION_MASK_SHIFT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">12</tt> <tt class="py-comment">#: Frame versions mask mode shift</tt> </tt>
<a name="L20"></a><tt class="py-lineno"> 20</tt> <tt class="py-line"><tt id="link-11" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_SADDR_MASK_SHIFT=killerbee.dot154decode-module.html#DOT154_FCF_SADDR_MASK_SHIFT"><a title="killerbee.dot154decode.DOT154_FCF_SADDR_MASK_SHIFT" class="py-name" href="#" onclick="return doclink('link-11', 'DOT154_FCF_SADDR_MASK_SHIFT', 'link-11');">DOT154_FCF_SADDR_MASK_SHIFT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">14</tt> <tt class="py-comment">#: Source addressing mask mode shift</tt> </tt>
<a name="L21"></a><tt class="py-lineno"> 21</tt> <tt class="py-line"> </tt>
<a name="L22"></a><tt class="py-lineno"> 22</tt> <tt class="py-line"><tt class="py-comment"># Address Mode Definitions</tt> </tt>
<a name="L23"></a><tt class="py-lineno"> 23</tt> <tt class="py-line"><tt id="link-12" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_ADDR_NONE=killerbee.dot154decode-module.html#DOT154_FCF_ADDR_NONE"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_NONE" class="py-name" href="#" onclick="return doclink('link-12', 'DOT154_FCF_ADDR_NONE', 'link-12');">DOT154_FCF_ADDR_NONE</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0000</tt> <tt class="py-comment">#: Not sure when this is used</tt> </tt>
<a name="L24"></a><tt class="py-lineno"> 24</tt> <tt class="py-line"><tt id="link-13" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_ADDR_SHORT=killerbee.dot154decode-module.html#DOT154_FCF_ADDR_SHORT"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_SHORT" class="py-name" href="#" onclick="return doclink('link-13', 'DOT154_FCF_ADDR_SHORT', 'link-13');">DOT154_FCF_ADDR_SHORT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0002</tt> <tt class="py-comment">#: 4-byte addressing</tt> </tt>
<a name="L25"></a><tt class="py-lineno"> 25</tt> <tt class="py-line"><tt id="link-14" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_ADDR_EXT=killerbee.dot154decode-module.html#DOT154_FCF_ADDR_EXT"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_EXT" class="py-name" href="#" onclick="return doclink('link-14', 'DOT154_FCF_ADDR_EXT', 'link-14');">DOT154_FCF_ADDR_EXT</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x0003</tt> <tt class="py-comment">#: 8-byte addressing</tt> </tt>
<a name="L26"></a><tt class="py-lineno"> 26</tt> <tt class="py-line"> </tt>
<a name="L27"></a><tt class="py-lineno"> 27</tt> <tt class="py-line"><tt id="link-15" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_BEACON=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_BEACON"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_BEACON" class="py-name" href="#" onclick="return doclink('link-15', 'DOT154_FCF_TYPE_BEACON', 'link-15');">DOT154_FCF_TYPE_BEACON</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0</tt> <tt class="py-comment">#: Beacon frame</tt> </tt>
<a name="L28"></a><tt class="py-lineno"> 28</tt> <tt class="py-line"><tt id="link-16" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_DATA=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_DATA"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_DATA" class="py-name" href="#" onclick="return doclink('link-16', 'DOT154_FCF_TYPE_DATA', 'link-16');">DOT154_FCF_TYPE_DATA</a></tt> <tt class="py-op">=</tt> <tt class="py-number">1</tt> <tt class="py-comment">#: Data frame</tt> </tt>
<a name="L29"></a><tt class="py-lineno"> 29</tt> <tt class="py-line"><tt id="link-17" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_ACK=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_ACK"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_ACK" class="py-name" href="#" onclick="return doclink('link-17', 'DOT154_FCF_TYPE_ACK', 'link-17');">DOT154_FCF_TYPE_ACK</a></tt> <tt class="py-op">=</tt> <tt class="py-number">2</tt> <tt class="py-comment">#: Acknowledgement frame</tt> </tt>
<a name="L30"></a><tt class="py-lineno"> 30</tt> <tt class="py-line"><tt id="link-18" class="py-name" targets="Variable killerbee.dot154decode.DOT154_FCF_TYPE_MACCMD=killerbee.dot154decode-module.html#DOT154_FCF_TYPE_MACCMD"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_MACCMD" class="py-name" href="#" onclick="return doclink('link-18', 'DOT154_FCF_TYPE_MACCMD', 'link-18');">DOT154_FCF_TYPE_MACCMD</a></tt> <tt class="py-op">=</tt> <tt class="py-number">3</tt> <tt class="py-comment">#: MAC Command frame</tt> </tt>
<a name="L31"></a><tt class="py-lineno"> 31</tt> <tt class="py-line"> </tt>
<a name="L32"></a><tt class="py-lineno"> 32</tt> <tt class="py-line"><tt id="link-19" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_NONE=killerbee.dot154decode-module.html#DOT154_CRYPT_NONE"><a title="killerbee.dot154decode.DOT154_CRYPT_NONE" class="py-name" href="#" onclick="return doclink('link-19', 'DOT154_CRYPT_NONE', 'link-19');">DOT154_CRYPT_NONE</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x00</tt> <tt class="py-comment">#: No encryption, no MIC</tt> </tt>
<a name="L33"></a><tt class="py-lineno"> 33</tt> <tt class="py-line"><tt id="link-20" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_MIC32=killerbee.dot154decode-module.html#DOT154_CRYPT_MIC32"><a title="killerbee.dot154decode.DOT154_CRYPT_MIC32" class="py-name" href="#" onclick="return doclink('link-20', 'DOT154_CRYPT_MIC32', 'link-20');">DOT154_CRYPT_MIC32</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x01</tt> <tt class="py-comment">#: No encryption, 32-bit MIC</tt> </tt>
<a name="L34"></a><tt class="py-lineno"> 34</tt> <tt class="py-line"><tt id="link-21" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_MIC64=killerbee.dot154decode-module.html#DOT154_CRYPT_MIC64"><a title="killerbee.dot154decode.DOT154_CRYPT_MIC64" class="py-name" href="#" onclick="return doclink('link-21', 'DOT154_CRYPT_MIC64', 'link-21');">DOT154_CRYPT_MIC64</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x02</tt> <tt class="py-comment">#: No encryption, 64-bit MIC</tt> </tt>
<a name="L35"></a><tt class="py-lineno"> 35</tt> <tt class="py-line"><tt id="link-22" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_MIC128=killerbee.dot154decode-module.html#DOT154_CRYPT_MIC128"><a title="killerbee.dot154decode.DOT154_CRYPT_MIC128" class="py-name" href="#" onclick="return doclink('link-22', 'DOT154_CRYPT_MIC128', 'link-22');">DOT154_CRYPT_MIC128</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x03</tt> <tt class="py-comment">#: No encryption, 128-bit MIC</tt> </tt>
<a name="L36"></a><tt class="py-lineno"> 36</tt> <tt class="py-line"><tt id="link-23" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_ENC=killerbee.dot154decode-module.html#DOT154_CRYPT_ENC"><a title="killerbee.dot154decode.DOT154_CRYPT_ENC" class="py-name" href="#" onclick="return doclink('link-23', 'DOT154_CRYPT_ENC', 'link-23');">DOT154_CRYPT_ENC</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x04</tt> <tt class="py-comment">#: Encryption, no MIC</tt> </tt>
<a name="L37"></a><tt class="py-lineno"> 37</tt> <tt class="py-line"><tt id="link-24" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_ENC_MIC32=killerbee.dot154decode-module.html#DOT154_CRYPT_ENC_MIC32"><a title="killerbee.dot154decode.DOT154_CRYPT_ENC_MIC32" class="py-name" href="#" onclick="return doclink('link-24', 'DOT154_CRYPT_ENC_MIC32', 'link-24');">DOT154_CRYPT_ENC_MIC32</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x05</tt> <tt class="py-comment">#: Encryption, 32-bit MIC</tt> </tt>
<a name="L38"></a><tt class="py-lineno"> 38</tt> <tt class="py-line"><tt id="link-25" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_ENC_MIC64=killerbee.dot154decode-module.html#DOT154_CRYPT_ENC_MIC64"><a title="killerbee.dot154decode.DOT154_CRYPT_ENC_MIC64" class="py-name" href="#" onclick="return doclink('link-25', 'DOT154_CRYPT_ENC_MIC64', 'link-25');">DOT154_CRYPT_ENC_MIC64</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x06</tt> <tt class="py-comment">#: Encryption, 64-bit MIC</tt> </tt>
<a name="L39"></a><tt class="py-lineno"> 39</tt> <tt class="py-line"><tt id="link-26" class="py-name" targets="Variable killerbee.dot154decode.DOT154_CRYPT_ENC_MIC128=killerbee.dot154decode-module.html#DOT154_CRYPT_ENC_MIC128"><a title="killerbee.dot154decode.DOT154_CRYPT_ENC_MIC128" class="py-name" href="#" onclick="return doclink('link-26', 'DOT154_CRYPT_ENC_MIC128', 'link-26');">DOT154_CRYPT_ENC_MIC128</a></tt> <tt class="py-op">=</tt> <tt class="py-number">0x07</tt> <tt class="py-comment">#: Encryption, 128-bit MIC</tt> </tt>
<a name="L40"></a><tt class="py-lineno"> 40</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser"></a><div id="Dot154PacketParser-def"><a name="L41"></a><tt class="py-lineno"> 41</tt> <a class="py-toggle" href="#" id="Dot154PacketParser-toggle" onclick="return toggle('Dot154PacketParser');">-</a><tt class="py-line"><tt class="py-keyword">class</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html">Dot154PacketParser</a><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser-collapsed" style="display:none;" pad="+++" indent="++++"></div><div id="Dot154PacketParser-expanded"><a name="Dot154PacketParser.__init__"></a><div id="Dot154PacketParser.__init__-def"><a name="L42"></a><tt class="py-lineno"> 42</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.__init__-toggle" onclick="return toggle('Dot154PacketParser.__init__');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#__init__">__init__</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.__init__-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.__init__-expanded"><a name="L43"></a><tt class="py-lineno"> 43</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L44"></a><tt class="py-lineno"> 44</tt> <tt class="py-line"><tt class="py-docstring"> Instantiates the Dot154PacketParser class.</tt> </tt>
<a name="L45"></a><tt class="py-lineno"> 45</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L46"></a><tt class="py-lineno"> 46</tt> <tt class="py-line"> </tt>
<a name="L47"></a><tt class="py-lineno"> 47</tt> <tt class="py-line"> <tt class="py-comment"># State values for AES-CTR mode</tt> </tt>
<a name="L48"></a><tt class="py-lineno"> 48</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_blockcntr</tt> <tt class="py-op">=</tt> <tt class="py-number">1</tt> </tt>
<a name="L49"></a><tt class="py-lineno"> 49</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_A_i</tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-op">]</tt> </tt>
<a name="L50"></a><tt class="py-lineno"> 50</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> </tt>
</div><a name="L51"></a><tt class="py-lineno"> 51</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.__crypt_counter"></a><div id="Dot154PacketParser.__crypt_counter-def"><a name="L52"></a><tt class="py-lineno"> 52</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.__crypt_counter-toggle" onclick="return toggle('Dot154PacketParser.__crypt_counter');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#__crypt_counter">__crypt_counter</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.__crypt_counter-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.__crypt_counter-expanded"><a name="L53"></a><tt class="py-lineno"> 53</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L54"></a><tt class="py-lineno"> 54</tt> <tt class="py-line"><tt class="py-docstring"> Used for AES-CTR mode after populating self.__crypt_A_i</tt> </tt>
<a name="L55"></a><tt class="py-lineno"> 55</tt> <tt class="py-line"><tt class="py-docstring"> Don't call this directly. Just don't.</tt> </tt>
<a name="L56"></a><tt class="py-lineno"> 56</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L57"></a><tt class="py-lineno"> 57</tt> <tt class="py-line"> <tt class="py-name">retindex</tt> <tt class="py-op">=</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_blockcntr</tt> </tt>
<a name="L58"></a><tt class="py-lineno"> 58</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_blockcntr</tt> <tt class="py-op">+=</tt> <tt class="py-number">1</tt> </tt>
<a name="L59"></a><tt class="py-lineno"> 59</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_A_i</tt><tt class="py-op">[</tt><tt class="py-name">retindex</tt><tt class="py-op">]</tt> </tt>
</div><a name="L60"></a><tt class="py-lineno"> 60</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.decrypt"></a><div id="Dot154PacketParser.decrypt-def"><a name="L61"></a><tt class="py-lineno"> 61</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.decrypt-toggle" onclick="return toggle('Dot154PacketParser.decrypt');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#decrypt">decrypt</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">,</tt> <tt class="py-param">packet</tt><tt class="py-op">,</tt> <tt class="py-param">key</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.decrypt-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.decrypt-expanded"><a name="L62"></a><tt class="py-lineno"> 62</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L63"></a><tt class="py-lineno"> 63</tt> <tt class="py-line"><tt class="py-docstring"> Decrypts the specified packet. Returns empty string if the packet is</tt> </tt>
<a name="L64"></a><tt class="py-lineno"> 64</tt> <tt class="py-line"><tt class="py-docstring"> not encrypted, or if decryption MIC validation fails.</tt> </tt>
<a name="L65"></a><tt class="py-lineno"> 65</tt> <tt class="py-line"><tt class="py-docstring"> </tt> </tt>
<a name="L66"></a><tt class="py-lineno"> 66</tt> <tt class="py-line"><tt class="py-docstring"> @type packet: String</tt> </tt>
<a name="L67"></a><tt class="py-lineno"> 67</tt> <tt class="py-line"><tt class="py-docstring"> @param packet: Packet contents.</tt> </tt>
<a name="L68"></a><tt class="py-lineno"> 68</tt> <tt class="py-line"><tt class="py-docstring"> @type key: String</tt> </tt>
<a name="L69"></a><tt class="py-lineno"> 69</tt> <tt class="py-line"><tt class="py-docstring"> @param key: Key contents.</tt> </tt>
<a name="L70"></a><tt class="py-lineno"> 70</tt> <tt class="py-line"><tt class="py-docstring"> @rtype: String</tt> </tt>
<a name="L71"></a><tt class="py-lineno"> 71</tt> <tt class="py-line"><tt class="py-docstring"> @return: Decrypted packet contents, empty string if not encrypted or if</tt> </tt>
<a name="L72"></a><tt class="py-lineno"> 72</tt> <tt class="py-line"><tt class="py-docstring"> decryped MIC fails validation.</tt> </tt>
<a name="L73"></a><tt class="py-lineno"> 73</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L74"></a><tt class="py-lineno"> 74</tt> <tt class="py-line"> </tt>
<a name="L75"></a><tt class="py-lineno"> 75</tt> <tt class="py-line"> <tt class="py-comment"># Retrieve the data payload from the packet contents</tt> </tt>
<a name="L76"></a><tt class="py-lineno"> 76</tt> <tt class="py-line"> <tt class="py-name">encpayload</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-op">-</tt><tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-27" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.payloadlen()=killerbee.dot154decode.Dot154PacketParser-class.html#payloadlen,Method killerbee.zigbeedecode.ZigBeeAPSPacketParser.payloadlen()=killerbee.zigbeedecode.ZigBeeAPSPacketParser-class.html#payloadlen,Method killerbee.zigbeedecode.ZigBeeNWKPacketParser.payloadlen()=killerbee.zigbeedecode.ZigBeeNWKPacketParser-class.html#payloadlen"><a title="killerbee.dot154decode.Dot154PacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.payloadlen" class="py-name" href="#" onclick="return doclink('link-27', 'payloadlen', 'link-27');">payloadlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt><tt class="py-op">]</tt> </tt>
<a name="L77"></a><tt class="py-lineno"> 77</tt> <tt class="py-line"> </tt>
<a name="L78"></a><tt class="py-lineno"> 78</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">ord</tt><tt class="py-op">(</tt><tt class="py-name">encpayload</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt><tt class="py-op">)</tt> <tt class="py-op">!=</tt> <tt id="link-28" class="py-name"><a title="killerbee.dot154decode.DOT154_CRYPT_ENC_MIC64" class="py-name" href="#" onclick="return doclink('link-28', 'DOT154_CRYPT_ENC_MIC64', 'link-25');">DOT154_CRYPT_ENC_MIC64</a></tt><tt class="py-op">:</tt> </tt>
<a name="L79"></a><tt class="py-lineno"> 79</tt> <tt class="py-line"> <tt class="py-keyword">raise</tt> <tt class="py-name">Exception</tt><tt class="py-op">(</tt><tt class="py-string">"Unsupported security level in packet: 0x%02x."</tt> <tt class="py-op">%</tt> <tt class="py-name">ord</tt><tt class="py-op">(</tt><tt class="py-name">encpayload</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L80"></a><tt class="py-lineno"> 80</tt> <tt class="py-line"> </tt>
<a name="L81"></a><tt class="py-lineno"> 81</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">key</tt><tt class="py-op">)</tt> <tt class="py-op">!=</tt> <tt class="py-number">16</tt><tt class="py-op">:</tt> </tt>
<a name="L82"></a><tt class="py-lineno"> 82</tt> <tt class="py-line"> <tt class="py-keyword">raise</tt> <tt class="py-name">Exception</tt><tt class="py-op">(</tt><tt class="py-string">"Invalid key length (%d)."</tt> <tt class="py-op">%</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">key</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L83"></a><tt class="py-lineno"> 83</tt> <tt class="py-line"> </tt>
<a name="L84"></a><tt class="py-lineno"> 84</tt> <tt class="py-line"> <tt class="py-comment"># Encrypted content is:</tt> </tt>
<a name="L85"></a><tt class="py-lineno"> 85</tt> <tt class="py-line"> <tt class="py-comment"># Sec Level | 4-byte counter | Flags | Ciphertext | Encrypted 8-byte MIC</tt> </tt>
<a name="L86"></a><tt class="py-lineno"> 86</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-29" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.payloadlen" class="py-name" href="#" onclick="return doclink('link-29', 'payloadlen', 'link-27');">payloadlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> <tt class="py-op"><</tt> <tt class="py-number">15</tt><tt class="py-op">:</tt> </tt>
<a name="L87"></a><tt class="py-lineno"> 87</tt> <tt class="py-line"> <tt class="py-keyword">raise</tt> <tt class="py-name">Exception</tt><tt class="py-op">(</tt><tt class="py-string">"Payload length too short (%d)."</tt> <tt class="py-op">%</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-30" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.payloadlen" class="py-name" href="#" onclick="return doclink('link-30', 'payloadlen', 'link-27');">payloadlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L88"></a><tt class="py-lineno"> 88</tt> <tt class="py-line"> </tt>
<a name="L89"></a><tt class="py-lineno"> 89</tt> <tt class="py-line"> <tt id="link-31" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.nonce()=killerbee.dot154decode.Dot154PacketParser-class.html#nonce"><a title="killerbee.dot154decode.Dot154PacketParser.nonce" class="py-name" href="#" onclick="return doclink('link-31', 'nonce', 'link-31');">nonce</a></tt> <tt class="py-op">=</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-32" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.nonce" class="py-name" href="#" onclick="return doclink('link-32', 'nonce', 'link-31');">nonce</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> </tt>
<a name="L90"></a><tt class="py-lineno"> 90</tt> <tt class="py-line"> </tt>
<a name="L91"></a><tt class="py-lineno"> 91</tt> <tt class="py-line"> <tt class="py-comment"># c = ciphertext payload including trailing 8-byte encrypted MIC</tt> </tt>
<a name="L92"></a><tt class="py-lineno"> 92</tt> <tt class="py-line"> <tt class="py-name">c</tt> <tt class="py-op">=</tt> <tt class="py-name">encpayload</tt><tt class="py-op">[</tt><tt class="py-op">-</tt><tt class="py-number">9</tt><tt class="py-op">:</tt><tt class="py-op">]</tt> </tt>
<a name="L93"></a><tt class="py-lineno"> 93</tt> <tt class="py-line"> </tt>
<a name="L94"></a><tt class="py-lineno"> 94</tt> <tt class="py-line"> </tt>
<a name="L95"></a><tt class="py-lineno"> 95</tt> <tt class="py-line"> <tt class="py-comment"># 1. Parse C||U where U is the right-most bytes for MIC and C is the</tt> </tt>
<a name="L96"></a><tt class="py-lineno"> 96</tt> <tt class="py-line"> <tt class="py-comment"># remaining bytes (representing encrypted packet payload content)</tt> </tt>
<a name="L97"></a><tt class="py-lineno"> 97</tt> <tt class="py-line"> <tt class="py-name">C</tt> <tt class="py-op">=</tt> <tt class="py-name">c</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-op">-</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> </tt>
<a name="L98"></a><tt class="py-lineno"> 98</tt> <tt class="py-line"> <tt class="py-name">U</tt> <tt class="py-op">=</tt> <tt class="py-name">c</tt><tt class="py-op">[</tt><tt class="py-op">-</tt><tt class="py-number">8</tt><tt class="py-op">:</tt><tt class="py-op">]</tt> </tt>
<a name="L99"></a><tt class="py-lineno"> 99</tt> <tt class="py-line"> </tt>
<a name="L100"></a><tt class="py-lineno">100</tt> <tt class="py-line"> <tt class="py-comment"># 2. Form cipherText by padding C to a block size</tt> </tt>
<a name="L101"></a><tt class="py-lineno">101</tt> <tt class="py-line"> <tt class="py-name">cipherText</tt> <tt class="py-op">=</tt> <tt class="py-name">C</tt> <tt class="py-op">+</tt> <tt class="py-op">(</tt><tt class="py-string">"\x00"</tt> <tt class="py-op">*</tt> <tt class="py-op">(</tt><tt class="py-number">16</tt> <tt class="py-op">-</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">C</tt><tt class="py-op">)</tt><tt class="py-op">%</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L102"></a><tt class="py-lineno">102</tt> <tt class="py-line"> </tt>
<a name="L103"></a><tt class="py-lineno">103</tt> <tt class="py-line"> <tt class="py-comment"># 3. Form 1-byte flags field = 01 </tt> </tt>
<a name="L104"></a><tt class="py-lineno">104</tt> <tt class="py-line"> <tt class="py-comment"># XXX will vary when L changes</tt> </tt>
<a name="L105"></a><tt class="py-lineno">105</tt> <tt class="py-line"> <tt class="py-name">flags</tt> <tt class="py-op">=</tt> <tt class="py-string">"\x01"</tt> </tt>
<a name="L106"></a><tt class="py-lineno">106</tt> <tt class="py-line"> </tt>
<a name="L107"></a><tt class="py-lineno">107</tt> <tt class="py-line"> <tt class="py-comment"># 4. Define 16-octet A_i consisting of:</tt> </tt>
<a name="L108"></a><tt class="py-lineno">108</tt> <tt class="py-line"> <tt class="py-comment"># Flags || Nonce || 2-byte counter i for i=0,1,2, ...</tt> </tt>
<a name="L109"></a><tt class="py-lineno">109</tt> <tt class="py-line"> <tt class="py-comment"># A[0] is for authenticity check, A[1] is for the first block of data,</tt> </tt>
<a name="L110"></a><tt class="py-lineno">110</tt> <tt class="py-line"> <tt class="py-comment"># A[2] is for the 2nd block of data, if C > 16</tt> </tt>
<a name="L111"></a><tt class="py-lineno">111</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_A_i</tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-op">]</tt> </tt>
<a name="L112"></a><tt class="py-lineno">112</tt> <tt class="py-line"> <tt class="py-keyword">for</tt> <tt class="py-name">i</tt> <tt class="py-keyword">in</tt> <tt class="py-name">xrange</tt><tt class="py-op">(</tt><tt class="py-number">0</tt><tt class="py-op">,</tt> <tt class="py-op">(</tt><tt class="py-number">1</tt><tt class="py-op">+</tt><tt class="py-number">1</tt><tt class="py-op">+</tt><tt class="py-op">(</tt><tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">C</tt><tt class="py-op">)</tt><tt class="py-op">/</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">)</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
<a name="L113"></a><tt class="py-lineno">113</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_A_i</tt><tt class="py-op">.</tt><tt class="py-name">append</tt><tt class="py-op">(</tt><tt class="py-name">flags</tt> <tt class="py-op">+</tt> <tt id="link-33" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.nonce" class="py-name" href="#" onclick="return doclink('link-33', 'nonce', 'link-31');">nonce</a></tt> <tt class="py-op">+</tt> <tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">pack</tt><tt class="py-op">(</tt><tt class="py-string">">H"</tt><tt class="py-op">,</tt><tt class="py-name">i</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L114"></a><tt class="py-lineno">114</tt> <tt class="py-line"> </tt>
<a name="L115"></a><tt class="py-lineno">115</tt> <tt class="py-line"> <tt class="py-comment"># 5. Decrypt cipherText producing plainText (observed)</tt> </tt>
<a name="L116"></a><tt class="py-lineno">116</tt> <tt class="py-line"> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_blockcntr</tt> <tt class="py-op">=</tt> <tt class="py-number">1</tt> <tt class="py-comment"># Start at A[1] to decrypt</tt> </tt>
<a name="L117"></a><tt class="py-lineno">117</tt> <tt class="py-line"> <tt class="py-name">crypt</tt> <tt class="py-op">=</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">new</tt><tt class="py-op">(</tt><tt class="py-name">key</tt><tt class="py-op">,</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">MODE_CTR</tt><tt class="py-op">,</tt> <tt class="py-name">counter</tt><tt class="py-op">=</tt><tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-34" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.__crypt_counter()=killerbee.dot154decode.Dot154PacketParser-class.html#__crypt_counter"><a title="killerbee.dot154decode.Dot154PacketParser.__crypt_counter" class="py-name" href="#" onclick="return doclink('link-34', '__crypt_counter', 'link-34');">__crypt_counter</a></tt><tt class="py-op">)</tt> </tt>
<a name="L118"></a><tt class="py-lineno">118</tt> <tt class="py-line"> <tt class="py-name">plainText</tt> <tt class="py-op">=</tt> <tt class="py-name">crypt</tt><tt class="py-op">.</tt><tt id="link-35" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.decrypt()=killerbee.dot154decode.Dot154PacketParser-class.html#decrypt"><a title="killerbee.dot154decode.Dot154PacketParser.decrypt" class="py-name" href="#" onclick="return doclink('link-35', 'decrypt', 'link-35');">decrypt</a></tt><tt class="py-op">(</tt><tt class="py-name">cipherText</tt><tt class="py-op">)</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">C</tt><tt class="py-op">)</tt><tt class="py-op">]</tt> </tt>
<a name="L119"></a><tt class="py-lineno">119</tt> <tt class="py-line"> </tt>
<a name="L120"></a><tt class="py-lineno">120</tt> <tt class="py-line"> <tt class="py-comment"># 6. Compute S_0 as E(Key, A[0])</tt> </tt>
<a name="L121"></a><tt class="py-lineno">121</tt> <tt class="py-line"> <tt class="py-name">crypt</tt> <tt class="py-op">=</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">new</tt><tt class="py-op">(</tt><tt class="py-name">key</tt><tt class="py-op">,</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">MODE_CBC</tt><tt class="py-op">)</tt> </tt>
<a name="L122"></a><tt class="py-lineno">122</tt> <tt class="py-line"> <tt class="py-name">S_0</tt> <tt class="py-op">=</tt> <tt class="py-name">crypt</tt><tt class="py-op">.</tt><tt class="py-name">encrypt</tt><tt class="py-op">(</tt><tt class="py-name">self</tt><tt class="py-op">.</tt><tt class="py-name">__crypt_A_i</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt><tt class="py-op">)</tt> </tt>
<a name="L123"></a><tt class="py-lineno">123</tt> <tt class="py-line"> </tt>
<a name="L124"></a><tt class="py-lineno">124</tt> <tt class="py-line"> <tt class="py-comment"># 7. Compute MIC (T) observed as S_0 XOR U</tt> </tt>
<a name="L125"></a><tt class="py-lineno">125</tt> <tt class="py-line"> <tt class="py-name">T_obs</tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-op">]</tt> </tt>
<a name="L126"></a><tt class="py-lineno">126</tt> <tt class="py-line"> <tt class="py-keyword">for</tt> <tt class="py-name">i</tt> <tt class="py-keyword">in</tt> <tt class="py-name">xrange</tt><tt class="py-op">(</tt><tt class="py-number">0</tt><tt class="py-op">,</tt><tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">S_0</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-number">8</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
<a name="L127"></a><tt class="py-lineno">127</tt> <tt class="py-line"> <tt class="py-name">T_obs</tt><tt class="py-op">.</tt><tt class="py-name">append</tt><tt class="py-op">(</tt><tt class="py-op">(</tt><tt class="py-name">ord</tt><tt class="py-op">(</tt><tt class="py-name">S_0</tt><tt class="py-op">[</tt><tt class="py-name">i</tt><tt class="py-op">]</tt><tt class="py-op">)</tt> <tt class="py-op">^</tt> <tt class="py-name">ord</tt><tt class="py-op">(</tt><tt class="py-name">U</tt><tt class="py-op">[</tt><tt class="py-name">i</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L128"></a><tt class="py-lineno">128</tt> <tt class="py-line"> </tt>
<a name="L129"></a><tt class="py-lineno">129</tt> <tt class="py-line"> <tt class="py-comment"># Convert T_obs back into a string (please, I need Python help)</tt> </tt>
<a name="L130"></a><tt class="py-lineno">130</tt> <tt class="py-line"> <tt class="py-name">T_obs</tt> <tt class="py-op">=</tt> <tt class="py-string">''</tt><tt class="py-op">.</tt><tt class="py-name">join</tt><tt class="py-op">(</tt><tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">pack</tt><tt class="py-op">(</tt><tt class="py-string">"B"</tt><tt class="py-op">,</tt><tt class="py-name">i</tt><tt class="py-op">)</tt> <tt class="py-keyword">for</tt> <tt class="py-name">i</tt> <tt class="py-keyword">in</tt> <tt class="py-name">T_obs</tt><tt class="py-op">)</tt> </tt>
<a name="L131"></a><tt class="py-lineno">131</tt> <tt class="py-line"> </tt>
<a name="L132"></a><tt class="py-lineno">132</tt> <tt class="py-line"> <tt class="py-comment"># 8. Compute a over packet contents before ciphertext payload</tt> </tt>
<a name="L133"></a><tt class="py-lineno">133</tt> <tt class="py-line"> <tt class="py-comment"># This is the 802.15.4 header,plus the security level, frame</tt> </tt>
<a name="L134"></a><tt class="py-lineno">134</tt> <tt class="py-line"> <tt class="py-comment"># counter and flags byte (01)</tt> </tt>
<a name="L135"></a><tt class="py-lineno">135</tt> <tt class="py-line"> <tt id="link-36" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.hdrlen()=killerbee.dot154decode.Dot154PacketParser-class.html#hdrlen,Method killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen()=killerbee.zigbeedecode.ZigBeeAPSPacketParser-class.html#hdrlen,Method killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen()=killerbee.zigbeedecode.ZigBeeNWKPacketParser-class.html#hdrlen"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-36', 'hdrlen', 'link-36');">hdrlen</a></tt> <tt class="py-op">=</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-37" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-37', 'hdrlen', 'link-36');">hdrlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> </tt>
<a name="L136"></a><tt class="py-lineno">136</tt> <tt class="py-line"> <tt class="py-name">a</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt id="link-38" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-38', 'hdrlen', 'link-36');">hdrlen</a></tt><tt class="py-op">]</tt> <tt class="py-op">+</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt id="link-39" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-39', 'hdrlen', 'link-36');">hdrlen</a></tt><tt class="py-op">:</tt><tt id="link-40" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-40', 'hdrlen', 'link-36');">hdrlen</a></tt><tt class="py-op">+</tt><tt class="py-number">6</tt><tt class="py-op">]</tt> </tt>
<a name="L137"></a><tt class="py-lineno">137</tt> <tt class="py-line"> </tt>
<a name="L138"></a><tt class="py-lineno">138</tt> <tt class="py-line"> <tt class="py-comment"># 9. Concatenate L(a) of 2-byte length a with a</tt> </tt>
<a name="L139"></a><tt class="py-lineno">139</tt> <tt class="py-line"> <tt class="py-name">addAuthData</tt> <tt class="py-op">=</tt> <tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">pack</tt><tt class="py-op">(</tt><tt class="py-string">">H"</tt><tt class="py-op">,</tt><tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">a</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> <tt class="py-op">+</tt> <tt class="py-name">a</tt> </tt>
<a name="L140"></a><tt class="py-lineno">140</tt> <tt class="py-line"> </tt>
<a name="L141"></a><tt class="py-lineno">141</tt> <tt class="py-line"> <tt class="py-comment"># 10. Pad addAuthData to an even block size</tt> </tt>
<a name="L142"></a><tt class="py-lineno">142</tt> <tt class="py-line"> <tt class="py-name">addAuthData</tt> <tt class="py-op">+=</tt> <tt class="py-op">(</tt><tt class="py-string">"\x00"</tt> <tt class="py-op">*</tt> <tt class="py-op">(</tt><tt class="py-number">16</tt> <tt class="py-op">-</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">addAuthData</tt><tt class="py-op">)</tt><tt class="py-op">%</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L143"></a><tt class="py-lineno">143</tt> <tt class="py-line"> </tt>
<a name="L144"></a><tt class="py-lineno">144</tt> <tt class="py-line"> <tt class="py-comment"># 11. Form AuthData by concatenating addAuthData and PlaintextData</tt> </tt>
<a name="L145"></a><tt class="py-lineno">145</tt> <tt class="py-line"> <tt class="py-comment"># Pad plainText to an even block size</tt> </tt>
<a name="L146"></a><tt class="py-lineno">146</tt> <tt class="py-line"> <tt class="py-name">plainTextPadded</tt> <tt class="py-op">=</tt> <tt class="py-name">plainText</tt> <tt class="py-op">+</tt> <tt class="py-op">(</tt><tt class="py-string">"\x00"</tt> <tt class="py-op">*</tt> <tt class="py-op">(</tt><tt class="py-number">16</tt> <tt class="py-op">-</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">plainText</tt><tt class="py-op">)</tt><tt class="py-op">%</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L147"></a><tt class="py-lineno">147</tt> <tt class="py-line"> </tt>
<a name="L148"></a><tt class="py-lineno">148</tt> <tt class="py-line"> <tt class="py-name">authData</tt> <tt class="py-op">=</tt> <tt class="py-name">addAuthData</tt> <tt class="py-op">+</tt> <tt class="py-name">plainTextPadded</tt> </tt>
<a name="L149"></a><tt class="py-lineno">149</tt> <tt class="py-line"> </tt>
<a name="L150"></a><tt class="py-lineno">150</tt> <tt class="py-line"> <tt class="py-comment"># 12. Perform authData transformation into B[0], B[1], ..., B[i]</tt> </tt>
<a name="L151"></a><tt class="py-lineno">151</tt> <tt class="py-line"> <tt class="py-name">B</tt> <tt class="py-op">=</tt> <tt class="py-string">"\x59"</tt> <tt class="py-op">+</tt> <tt id="link-41" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.nonce" class="py-name" href="#" onclick="return doclink('link-41', 'nonce', 'link-31');">nonce</a></tt> <tt class="py-op">+</tt> <tt class="py-string">"\x00\x01"</tt> <tt class="py-op">+</tt> <tt class="py-name">authData</tt> </tt>
<a name="L152"></a><tt class="py-lineno">152</tt> <tt class="py-line"> </tt>
<a name="L153"></a><tt class="py-lineno">153</tt> <tt class="py-line"> <tt class="py-comment"># 13. Calculate the MIC (T) calculated with CBC-MAC</tt> </tt>
<a name="L154"></a><tt class="py-lineno">154</tt> <tt class="py-line"> <tt class="py-name">iv</tt> <tt class="py-op">=</tt> <tt class="py-string">"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"</tt> </tt>
<a name="L155"></a><tt class="py-lineno">155</tt> <tt class="py-line"> <tt class="py-keyword">for</tt> <tt class="py-name">i</tt> <tt class="py-keyword">in</tt> <tt class="py-name">xrange</tt><tt class="py-op">(</tt><tt class="py-number">0</tt><tt class="py-op">,</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">B</tt><tt class="py-op">)</tt><tt class="py-op">/</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
<a name="L156"></a><tt class="py-lineno">156</tt> <tt class="py-line"> <tt class="py-name">crypt</tt> <tt class="py-op">=</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">new</tt><tt class="py-op">(</tt><tt class="py-name">key</tt><tt class="py-op">,</tt> <tt class="py-name">AES</tt><tt class="py-op">.</tt><tt class="py-name">MODE_CBC</tt><tt class="py-op">,</tt> <tt class="py-name">iv</tt><tt class="py-op">)</tt> </tt>
<a name="L157"></a><tt class="py-lineno">157</tt> <tt class="py-line"> <tt class="py-name">Bn</tt> <tt class="py-op">=</tt> <tt class="py-name">B</tt><tt class="py-op">[</tt><tt class="py-name">i</tt><tt class="py-op">*</tt><tt class="py-number">16</tt><tt class="py-op">:</tt><tt class="py-op">(</tt><tt class="py-name">i</tt><tt class="py-op">*</tt><tt class="py-number">16</tt><tt class="py-op">)</tt><tt class="py-op">+</tt><tt class="py-number">16</tt><tt class="py-op">]</tt> </tt>
<a name="L158"></a><tt class="py-lineno">158</tt> <tt class="py-line"> <tt class="py-name">iv</tt> <tt class="py-op">=</tt> <tt class="py-name">crypt</tt><tt class="py-op">.</tt><tt class="py-name">encrypt</tt><tt class="py-op">(</tt><tt class="py-name">Bn</tt><tt class="py-op">)</tt> </tt>
<a name="L159"></a><tt class="py-lineno">159</tt> <tt class="py-line"> <tt class="py-name">T_calc</tt> <tt class="py-op">=</tt> <tt class="py-name">iv</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> </tt>
<a name="L160"></a><tt class="py-lineno">160</tt> <tt class="py-line"> </tt>
<a name="L161"></a><tt class="py-lineno">161</tt> <tt class="py-line"> <tt class="py-comment"># 14. Compare </tt> </tt>
<a name="L162"></a><tt class="py-lineno">162</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">T_obs</tt> <tt class="py-op">==</tt> <tt class="py-name">T_calc</tt><tt class="py-op">:</tt> </tt>
<a name="L163"></a><tt class="py-lineno">163</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">plainText</tt> </tt>
<a name="L164"></a><tt class="py-lineno">164</tt> <tt class="py-line"> <tt class="py-keyword">else</tt><tt class="py-op">:</tt> </tt>
<a name="L165"></a><tt class="py-lineno">165</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-string">""</tt> </tt>
</div><a name="L166"></a><tt class="py-lineno">166</tt> <tt class="py-line"> </tt>
<a name="L167"></a><tt class="py-lineno">167</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.pktchop"></a><div id="Dot154PacketParser.pktchop-def"><a name="L168"></a><tt class="py-lineno">168</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.pktchop-toggle" onclick="return toggle('Dot154PacketParser.pktchop');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#pktchop">pktchop</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">,</tt> <tt class="py-param">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.pktchop-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.pktchop-expanded"><a name="L169"></a><tt class="py-lineno">169</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L170"></a><tt class="py-lineno">170</tt> <tt class="py-line"><tt class="py-docstring"> Chops up the specified packet contents into a list of fields. Does</tt> </tt>
<a name="L171"></a><tt class="py-lineno">171</tt> <tt class="py-line"><tt class="py-docstring"> not attempt to re-order the field values for parsing. ''.join(X) will</tt> </tt>
<a name="L172"></a><tt class="py-lineno">172</tt> <tt class="py-line"><tt class="py-docstring"> reassemble original packet string. Fields which may or may not be</tt> </tt>
<a name="L173"></a><tt class="py-lineno">173</tt> <tt class="py-line"><tt class="py-docstring"> present (such as the Source PAN field) are empty if they are not</tt> </tt>
<a name="L174"></a><tt class="py-lineno">174</tt> <tt class="py-line"><tt class="py-docstring"> present, keeping the list elements consistent, as follows:</tt> </tt>
<a name="L175"></a><tt class="py-lineno">175</tt> <tt class="py-line"><tt class="py-docstring"> FCF | Seq# | DPAN | DA | SPAN | SA | [Beacon Data] | PHY Payload</tt> </tt>
<a name="L176"></a><tt class="py-lineno">176</tt> <tt class="py-line"><tt class="py-docstring"></tt> </tt>
<a name="L177"></a><tt class="py-lineno">177</tt> <tt class="py-line"><tt class="py-docstring"> If the packet is a beacon frame, the Beacon Data field will be populated</tt> </tt>
<a name="L178"></a><tt class="py-lineno">178</tt> <tt class="py-line"><tt class="py-docstring"> as a list element in the format:</tt> </tt>
<a name="L179"></a><tt class="py-lineno">179</tt> <tt class="py-line"><tt class="py-docstring"> </tt> </tt>
<a name="L180"></a><tt class="py-lineno">180</tt> <tt class="py-line"><tt class="py-docstring"> Superframe Spec | GTS Fields | Pending Addr Counts | Proto ID | Stack Profile/Profile Version | Device Capabilities | Ext PAN ID | TX Offset | Update ID</tt> </tt>
<a name="L181"></a><tt class="py-lineno">181</tt> <tt class="py-line"><tt class="py-docstring"></tt> </tt>
<a name="L182"></a><tt class="py-lineno">182</tt> <tt class="py-line"><tt class="py-docstring"> An exception is raised if the packet contents are too short to</tt> </tt>
<a name="L183"></a><tt class="py-lineno">183</tt> <tt class="py-line"><tt class="py-docstring"> decode.</tt> </tt>
<a name="L184"></a><tt class="py-lineno">184</tt> <tt class="py-line"><tt class="py-docstring"></tt> </tt>
<a name="L185"></a><tt class="py-lineno">185</tt> <tt class="py-line"><tt class="py-docstring"> @type packet: String</tt> </tt>
<a name="L186"></a><tt class="py-lineno">186</tt> <tt class="py-line"><tt class="py-docstring"> @param packet: Packet contents.</tt> </tt>
<a name="L187"></a><tt class="py-lineno">187</tt> <tt class="py-line"><tt class="py-docstring"> @rtype: list</tt> </tt>
<a name="L188"></a><tt class="py-lineno">188</tt> <tt class="py-line"><tt class="py-docstring"> @return: Chopped contents of the 802.15.4 packet into list elements.</tt> </tt>
<a name="L189"></a><tt class="py-lineno">189</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L190"></a><tt class="py-lineno">190</tt> <tt class="py-line"> <tt id="link-42" class="py-name" targets="Method killerbee.dot154decode.Dot154PacketParser.pktchop()=killerbee.dot154decode.Dot154PacketParser-class.html#pktchop,Method killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop()=killerbee.zigbeedecode.ZigBeeAPSPacketParser-class.html#pktchop,Method killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop()=killerbee.zigbeedecode.ZigBeeNWKPacketParser-class.html#pktchop"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-42', 'pktchop', 'link-42');">pktchop</a></tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">,</tt> <tt class="py-op">[</tt><tt class="py-op">]</tt><tt class="py-op">,</tt> <tt class="py-string">''</tt><tt class="py-op">]</tt> </tt>
<a name="L191"></a><tt class="py-lineno">191</tt> <tt class="py-line"> </tt>
<a name="L192"></a><tt class="py-lineno">192</tt> <tt class="py-line"> <tt id="link-43" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-43', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L193"></a><tt class="py-lineno">193</tt> <tt class="py-line"> </tt>
<a name="L194"></a><tt class="py-lineno">194</tt> <tt class="py-line"> <tt class="py-comment"># Sequence number</tt> </tt>
<a name="L195"></a><tt class="py-lineno">195</tt> <tt class="py-line"> <tt id="link-44" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-44', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">1</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L196"></a><tt class="py-lineno">196</tt> <tt class="py-line"> </tt>
<a name="L197"></a><tt class="py-lineno">197</tt> <tt class="py-line"> <tt class="py-comment"># Byte swap</tt> </tt>
<a name="L198"></a><tt class="py-lineno">198</tt> <tt class="py-line"> <tt class="py-name">fcf</tt> <tt class="py-op">=</tt> <tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">unpack</tt><tt class="py-op">(</tt><tt class="py-string">"<H"</tt><tt class="py-op">,</tt><tt id="link-45" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-45', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> </tt>
<a name="L199"></a><tt class="py-lineno">199</tt> <tt class="py-line"> </tt>
<a name="L200"></a><tt class="py-lineno">200</tt> <tt class="py-line"> <tt class="py-comment"># Check if we are dealing with a beacon frame</tt> </tt>
<a name="L201"></a><tt class="py-lineno">201</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-46" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_MASK" class="py-name" href="#" onclick="return doclink('link-46', 'DOT154_FCF_TYPE_MASK', 'link-0');">DOT154_FCF_TYPE_MASK</a></tt><tt class="py-op">)</tt> <tt class="py-op">==</tt> <tt id="link-47" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_TYPE_BEACON" class="py-name" href="#" onclick="return doclink('link-47', 'DOT154_FCF_TYPE_BEACON', 'link-15');">DOT154_FCF_TYPE_BEACON</a></tt><tt class="py-op">:</tt> </tt>
<a name="L202"></a><tt class="py-lineno">202</tt> <tt class="py-line"> </tt>
<a name="L203"></a><tt class="py-lineno">203</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt> <tt class="py-op">=</tt> <tt class="py-op">[</tt><tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">,</tt> <tt class="py-string">""</tt><tt class="py-op">]</tt> </tt>
<a name="L204"></a><tt class="py-lineno">204</tt> <tt class="py-line"> </tt>
<a name="L205"></a><tt class="py-lineno">205</tt> <tt class="py-line"> <tt class="py-keyword">try</tt><tt class="py-op">:</tt> </tt>
<a name="L206"></a><tt class="py-lineno">206</tt> <tt class="py-line"> </tt>
<a name="L207"></a><tt class="py-lineno">207</tt> <tt class="py-line"> <tt class="py-comment"># 802.15.4 fields, SPAN and SA</tt> </tt>
<a name="L208"></a><tt class="py-lineno">208</tt> <tt class="py-line"> <tt id="link-48" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-48', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">4</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">3</tt><tt class="py-op">:</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> </tt>
<a name="L209"></a><tt class="py-lineno">209</tt> <tt class="py-line"> <tt id="link-49" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-49', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">:</tt><tt class="py-number">7</tt><tt class="py-op">]</tt> </tt>
<a name="L210"></a><tt class="py-lineno">210</tt> <tt class="py-line"> <tt class="py-name">offset</tt> <tt class="py-op">=</tt> <tt class="py-number">7</tt> </tt>
<a name="L211"></a><tt class="py-lineno">211</tt> <tt class="py-line"> </tt>
<a name="L212"></a><tt class="py-lineno">212</tt> <tt class="py-line"> <tt class="py-comment"># Superframe specification</tt> </tt>
<a name="L213"></a><tt class="py-lineno">213</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L214"></a><tt class="py-lineno">214</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">2</tt> </tt>
<a name="L215"></a><tt class="py-lineno">215</tt> <tt class="py-line"> </tt>
<a name="L216"></a><tt class="py-lineno">216</tt> <tt class="py-line"> <tt class="py-comment"># GTS data</tt> </tt>
<a name="L217"></a><tt class="py-lineno">217</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">1</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L218"></a><tt class="py-lineno">218</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L219"></a><tt class="py-lineno">219</tt> <tt class="py-line"> </tt>
<a name="L220"></a><tt class="py-lineno">220</tt> <tt class="py-line"> <tt class="py-comment"># Pending address count</tt> </tt>
<a name="L221"></a><tt class="py-lineno">221</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L222"></a><tt class="py-lineno">222</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L223"></a><tt class="py-lineno">223</tt> <tt class="py-line"> </tt>
<a name="L224"></a><tt class="py-lineno">224</tt> <tt class="py-line"> <tt class="py-comment"># Protocol ID</tt> </tt>
<a name="L225"></a><tt class="py-lineno">225</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">3</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L226"></a><tt class="py-lineno">226</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L227"></a><tt class="py-lineno">227</tt> <tt class="py-line"> </tt>
<a name="L228"></a><tt class="py-lineno">228</tt> <tt class="py-line"> <tt class="py-comment"># Stack Profile version</tt> </tt>
<a name="L229"></a><tt class="py-lineno">229</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">4</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L230"></a><tt class="py-lineno">230</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L231"></a><tt class="py-lineno">231</tt> <tt class="py-line"> </tt>
<a name="L232"></a><tt class="py-lineno">232</tt> <tt class="py-line"> <tt class="py-comment"># Capability information</tt> </tt>
<a name="L233"></a><tt class="py-lineno">233</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L234"></a><tt class="py-lineno">234</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L235"></a><tt class="py-lineno">235</tt> <tt class="py-line"> </tt>
<a name="L236"></a><tt class="py-lineno">236</tt> <tt class="py-line"> <tt class="py-comment"># Extended PAN ID</tt> </tt>
<a name="L237"></a><tt class="py-lineno">237</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">6</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> </tt>
<a name="L238"></a><tt class="py-lineno">238</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">8</tt> </tt>
<a name="L239"></a><tt class="py-lineno">239</tt> <tt class="py-line"> </tt>
<a name="L240"></a><tt class="py-lineno">240</tt> <tt class="py-line"> <tt class="py-comment"># TX Offset</tt> </tt>
<a name="L241"></a><tt class="py-lineno">241</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">7</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">3</tt><tt class="py-op">]</tt> </tt>
<a name="L242"></a><tt class="py-lineno">242</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">3</tt> </tt>
<a name="L243"></a><tt class="py-lineno">243</tt> <tt class="py-line"> </tt>
<a name="L244"></a><tt class="py-lineno">244</tt> <tt class="py-line"> <tt class="py-comment"># Update ID</tt> </tt>
<a name="L245"></a><tt class="py-lineno">245</tt> <tt class="py-line"> <tt class="py-name">beacondata</tt><tt class="py-op">[</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">]</tt> </tt>
<a name="L246"></a><tt class="py-lineno">246</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">1</tt> </tt>
<a name="L247"></a><tt class="py-lineno">247</tt> <tt class="py-line"> </tt>
<a name="L248"></a><tt class="py-lineno">248</tt> <tt class="py-line"> <tt class="py-keyword">except</tt><tt class="py-op">:</tt> </tt>
<a name="L249"></a><tt class="py-lineno">249</tt> <tt class="py-line"> <tt class="py-keyword">pass</tt> </tt>
<a name="L250"></a><tt class="py-lineno">250</tt> <tt class="py-line"> </tt>
<a name="L251"></a><tt class="py-lineno">251</tt> <tt class="py-line"> <tt id="link-50" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-50', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">6</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">beacondata</tt> </tt>
<a name="L252"></a><tt class="py-lineno">252</tt> <tt class="py-line"> </tt>
<a name="L253"></a><tt class="py-lineno">253</tt> <tt class="py-line"> <tt class="py-keyword">else</tt><tt class="py-op">:</tt> </tt>
<a name="L254"></a><tt class="py-lineno">254</tt> <tt class="py-line"> <tt class="py-comment"># Not a beacon frame</tt> </tt>
<a name="L255"></a><tt class="py-lineno">255</tt> <tt class="py-line"> </tt>
<a name="L256"></a><tt class="py-lineno">256</tt> <tt class="py-line"> <tt class="py-comment"># DPAN</tt> </tt>
<a name="L257"></a><tt class="py-lineno">257</tt> <tt class="py-line"> <tt id="link-51" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-51', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">3</tt><tt class="py-op">:</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> </tt>
<a name="L258"></a><tt class="py-lineno">258</tt> <tt class="py-line"> <tt class="py-name">offset</tt> <tt class="py-op">=</tt> <tt class="py-number">5</tt> </tt>
<a name="L259"></a><tt class="py-lineno">259</tt> <tt class="py-line"> </tt>
<a name="L260"></a><tt class="py-lineno">260</tt> <tt class="py-line"> <tt class="py-comment"># Examine the destination addressing mode</tt> </tt>
<a name="L261"></a><tt class="py-lineno">261</tt> <tt class="py-line"> <tt class="py-name">daddr_mask</tt> <tt class="py-op">=</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-52" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_DADDR_MASK" class="py-name" href="#" onclick="return doclink('link-52', 'DOT154_FCF_DADDR_MASK', 'link-5');">DOT154_FCF_DADDR_MASK</a></tt><tt class="py-op">)</tt> <tt class="py-op">>></tt> <tt class="py-number">10</tt> </tt>
<a name="L262"></a><tt class="py-lineno">262</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">daddr_mask</tt> <tt class="py-op">==</tt> <tt id="link-53" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_EXT" class="py-name" href="#" onclick="return doclink('link-53', 'DOT154_FCF_ADDR_EXT', 'link-14');">DOT154_FCF_ADDR_EXT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L263"></a><tt class="py-lineno">263</tt> <tt class="py-line"> <tt id="link-54" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-54', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">3</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> </tt>
<a name="L264"></a><tt class="py-lineno">264</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">8</tt> </tt>
<a name="L265"></a><tt class="py-lineno">265</tt> <tt class="py-line"> <tt class="py-keyword">elif</tt> <tt class="py-name">daddr_mask</tt> <tt class="py-op">==</tt> <tt id="link-55" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_SHORT" class="py-name" href="#" onclick="return doclink('link-55', 'DOT154_FCF_ADDR_SHORT', 'link-13');">DOT154_FCF_ADDR_SHORT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L266"></a><tt class="py-lineno">266</tt> <tt class="py-line"> <tt id="link-56" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-56', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">3</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L267"></a><tt class="py-lineno">267</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">2</tt> </tt>
<a name="L268"></a><tt class="py-lineno">268</tt> <tt class="py-line"> </tt>
<a name="L269"></a><tt class="py-lineno">269</tt> <tt class="py-line"> <tt class="py-comment"># Examine the Intra-PAN flag</tt> </tt>
<a name="L270"></a><tt class="py-lineno">270</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-57" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_INTRA_PAN" class="py-name" href="#" onclick="return doclink('link-57', 'DOT154_FCF_INTRA_PAN', 'link-4');">DOT154_FCF_INTRA_PAN</a></tt><tt class="py-op">)</tt> <tt class="py-op">==</tt> <tt class="py-number">0</tt><tt class="py-op">:</tt> </tt>
<a name="L271"></a><tt class="py-lineno">271</tt> <tt class="py-line"> <tt id="link-58" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-58', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">4</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L272"></a><tt class="py-lineno">272</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">2</tt> </tt>
<a name="L273"></a><tt class="py-lineno">273</tt> <tt class="py-line"> </tt>
<a name="L274"></a><tt class="py-lineno">274</tt> <tt class="py-line"> <tt class="py-comment"># Examine the source addressing mode</tt> </tt>
<a name="L275"></a><tt class="py-lineno">275</tt> <tt class="py-line"> <tt class="py-name">saddr_mask</tt> <tt class="py-op">=</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-59" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_SADDR_MASK" class="py-name" href="#" onclick="return doclink('link-59', 'DOT154_FCF_SADDR_MASK', 'link-7');">DOT154_FCF_SADDR_MASK</a></tt><tt class="py-op">)</tt> <tt class="py-op">>></tt> <tt class="py-number">14</tt> </tt>
<a name="L276"></a><tt class="py-lineno">276</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">daddr_mask</tt> <tt class="py-op">==</tt> <tt id="link-60" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_EXT" class="py-name" href="#" onclick="return doclink('link-60', 'DOT154_FCF_ADDR_EXT', 'link-14');">DOT154_FCF_ADDR_EXT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L277"></a><tt class="py-lineno">277</tt> <tt class="py-line"> <tt id="link-61" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-61', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">8</tt><tt class="py-op">]</tt> </tt>
<a name="L278"></a><tt class="py-lineno">278</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">8</tt> </tt>
<a name="L279"></a><tt class="py-lineno">279</tt> <tt class="py-line"> <tt class="py-keyword">elif</tt> <tt class="py-name">daddr_mask</tt> <tt class="py-op">==</tt> <tt id="link-62" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_SHORT" class="py-name" href="#" onclick="return doclink('link-62', 'DOT154_FCF_ADDR_SHORT', 'link-13');">DOT154_FCF_ADDR_SHORT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L280"></a><tt class="py-lineno">280</tt> <tt class="py-line"> <tt id="link-63" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-63', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-name">offset</tt><tt class="py-op">+</tt><tt class="py-number">2</tt><tt class="py-op">]</tt> </tt>
<a name="L281"></a><tt class="py-lineno">281</tt> <tt class="py-line"> <tt class="py-name">offset</tt><tt class="py-op">+=</tt><tt class="py-number">2</tt> </tt>
<a name="L282"></a><tt class="py-lineno">282</tt> <tt class="py-line"> </tt>
<a name="L283"></a><tt class="py-lineno">283</tt> <tt class="py-line"> <tt class="py-comment"># Append remaining payload</tt> </tt>
<a name="L284"></a><tt class="py-lineno">284</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-name">offset</tt> <tt class="py-op"><</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
<a name="L285"></a><tt class="py-lineno">285</tt> <tt class="py-line"> <tt id="link-64" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-64', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">[</tt><tt class="py-number">7</tt><tt class="py-op">]</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-name">offset</tt><tt class="py-op">:</tt><tt class="py-op">]</tt> </tt>
<a name="L286"></a><tt class="py-lineno">286</tt> <tt class="py-line"> </tt>
<a name="L287"></a><tt class="py-lineno">287</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt id="link-65" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-65', 'pktchop', 'link-42');">pktchop</a></tt> </tt>
</div><a name="L288"></a><tt class="py-lineno">288</tt> <tt class="py-line"> </tt>
<a name="L289"></a><tt class="py-lineno">289</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.hdrlen"></a><div id="Dot154PacketParser.hdrlen-def"><a name="L290"></a><tt class="py-lineno">290</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.hdrlen-toggle" onclick="return toggle('Dot154PacketParser.hdrlen');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#hdrlen">hdrlen</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">,</tt> <tt class="py-param">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.hdrlen-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.hdrlen-expanded"><a name="L291"></a><tt class="py-lineno">291</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L292"></a><tt class="py-lineno">292</tt> <tt class="py-line"><tt class="py-docstring"> Returns the length of the 802.15.4 header.</tt> </tt>
<a name="L293"></a><tt class="py-lineno">293</tt> <tt class="py-line"><tt class="py-docstring"> @type packet: String</tt> </tt>
<a name="L294"></a><tt class="py-lineno">294</tt> <tt class="py-line"><tt class="py-docstring"> @param packet: Packet contents to evaluate for header length.</tt> </tt>
<a name="L295"></a><tt class="py-lineno">295</tt> <tt class="py-line"><tt class="py-docstring"> @rtype: Int</tt> </tt>
<a name="L296"></a><tt class="py-lineno">296</tt> <tt class="py-line"><tt class="py-docstring"> @return: Length of the 802.15.4 header.</tt> </tt>
<a name="L297"></a><tt class="py-lineno">297</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L298"></a><tt class="py-lineno">298</tt> <tt class="py-line"> </tt>
<a name="L299"></a><tt class="py-lineno">299</tt> <tt class="py-line"> <tt class="py-comment"># Minimum size is 11 (2 bytes FCF + 1 byte SEQ + 2 bytes DPAN +</tt> </tt>
<a name="L300"></a><tt class="py-lineno">300</tt> <tt class="py-line"> <tt class="py-comment"># 2 bytes DstAddr + 2 bytes SPAN + 2 bytes SrcAddr)</tt> </tt>
<a name="L301"></a><tt class="py-lineno">301</tt> <tt class="py-line"> <tt class="py-comment"># XXX Need to validate this logic based on specification</tt> </tt>
<a name="L302"></a><tt class="py-lineno">302</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> <tt class="py-op"><</tt> <tt class="py-number">9</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
<a name="L303"></a><tt class="py-lineno">303</tt> <tt class="py-line"> <tt class="py-keyword">raise</tt> <tt class="py-name">Exception</tt><tt class="py-op">(</tt><tt class="py-string">"Packet too small, %d bytes."</tt> <tt class="py-op">%</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt><tt class="py-op">)</tt> </tt>
<a name="L304"></a><tt class="py-lineno">304</tt> <tt class="py-line"> </tt>
<a name="L305"></a><tt class="py-lineno">305</tt> <tt class="py-line"> <tt class="py-comment"># Start with minimum size, increase as needed based on FCF flags</tt> </tt>
<a name="L306"></a><tt class="py-lineno">306</tt> <tt class="py-line"> <tt class="py-name">plen</tt> <tt class="py-op">=</tt> <tt class="py-number">9</tt> </tt>
<a name="L307"></a><tt class="py-lineno">307</tt> <tt class="py-line"> </tt>
<a name="L308"></a><tt class="py-lineno">308</tt> <tt class="py-line"> <tt class="py-comment"># Byte swap</tt> </tt>
<a name="L309"></a><tt class="py-lineno">309</tt> <tt class="py-line"> <tt class="py-name">fcf</tt> <tt class="py-op">=</tt> <tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">unpack</tt><tt class="py-op">(</tt><tt class="py-string">"<H"</tt><tt class="py-op">,</tt><tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-number">2</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> </tt>
<a name="L310"></a><tt class="py-lineno">310</tt> <tt class="py-line"> </tt>
<a name="L311"></a><tt class="py-lineno">311</tt> <tt class="py-line"> <tt class="py-comment"># Examine the destination addressing mode</tt> </tt>
<a name="L312"></a><tt class="py-lineno">312</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-66" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_DADDR_MASK" class="py-name" href="#" onclick="return doclink('link-66', 'DOT154_FCF_DADDR_MASK', 'link-5');">DOT154_FCF_DADDR_MASK</a></tt><tt class="py-op">)</tt> <tt class="py-op">>></tt> <tt class="py-number">10</tt> <tt class="py-op">==</tt> <tt id="link-67" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_EXT" class="py-name" href="#" onclick="return doclink('link-67', 'DOT154_FCF_ADDR_EXT', 'link-14');">DOT154_FCF_ADDR_EXT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L313"></a><tt class="py-lineno">313</tt> <tt class="py-line"> <tt class="py-name">plen</tt> <tt class="py-op">+=</tt> <tt class="py-number">6</tt> <tt class="py-comment"># 8-byte addressing is in use, increasing addr 6 bytes</tt> </tt>
<a name="L314"></a><tt class="py-lineno">314</tt> <tt class="py-line"> </tt>
<a name="L315"></a><tt class="py-lineno">315</tt> <tt class="py-line"> <tt class="py-comment"># Examine the source addressing mode</tt> </tt>
<a name="L316"></a><tt class="py-lineno">316</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-68" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_SADDR_MASK" class="py-name" href="#" onclick="return doclink('link-68', 'DOT154_FCF_SADDR_MASK', 'link-7');">DOT154_FCF_SADDR_MASK</a></tt><tt class="py-op">)</tt> <tt class="py-op">>></tt> <tt class="py-number">14</tt> <tt class="py-op">==</tt> <tt id="link-69" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_ADDR_EXT" class="py-name" href="#" onclick="return doclink('link-69', 'DOT154_FCF_ADDR_EXT', 'link-14');">DOT154_FCF_ADDR_EXT</a></tt><tt class="py-op">:</tt> </tt>
<a name="L317"></a><tt class="py-lineno">317</tt> <tt class="py-line"> <tt class="py-name">plen</tt> <tt class="py-op">+=</tt> <tt class="py-number">6</tt> <tt class="py-comment"># 8-byte addressing is in use, increasing addr 6 bytes</tt> </tt>
<a name="L318"></a><tt class="py-lineno">318</tt> <tt class="py-line"> </tt>
<a name="L319"></a><tt class="py-lineno">319</tt> <tt class="py-line"> <tt class="py-comment"># Examine the Intra-PAN flag</tt> </tt>
<a name="L320"></a><tt class="py-lineno">320</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-70" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_INTRA_PAN" class="py-name" href="#" onclick="return doclink('link-70', 'DOT154_FCF_INTRA_PAN', 'link-4');">DOT154_FCF_INTRA_PAN</a></tt><tt class="py-op">)</tt> <tt class="py-op">==</tt> <tt class="py-number">0</tt><tt class="py-op">:</tt> </tt>
<a name="L321"></a><tt class="py-lineno">321</tt> <tt class="py-line"> <tt class="py-name">plen</tt> <tt class="py-op">+=</tt> <tt class="py-number">2</tt> <tt class="py-comment"># Intra-PAN is false, source PAN 2-bytes is present</tt> </tt>
<a name="L322"></a><tt class="py-lineno">322</tt> <tt class="py-line"> </tt>
<a name="L323"></a><tt class="py-lineno">323</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">plen</tt> </tt>
</div><a name="L324"></a><tt class="py-lineno">324</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.payloadlen"></a><div id="Dot154PacketParser.payloadlen-def"><a name="L325"></a><tt class="py-lineno">325</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.payloadlen-toggle" onclick="return toggle('Dot154PacketParser.payloadlen');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#payloadlen">payloadlen</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">,</tt> <tt class="py-param">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.payloadlen-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.payloadlen-expanded"><a name="L326"></a><tt class="py-lineno">326</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L327"></a><tt class="py-lineno">327</tt> <tt class="py-line"><tt class="py-docstring"> Returns the length of the 802.15.4 payload.</tt> </tt>
<a name="L328"></a><tt class="py-lineno">328</tt> <tt class="py-line"><tt class="py-docstring"> @type packet: String</tt> </tt>
<a name="L329"></a><tt class="py-lineno">329</tt> <tt class="py-line"><tt class="py-docstring"> @param packet: Packet contents to evaluate for header length.</tt> </tt>
<a name="L330"></a><tt class="py-lineno">330</tt> <tt class="py-line"><tt class="py-docstring"> @rtype: Int</tt> </tt>
<a name="L331"></a><tt class="py-lineno">331</tt> <tt class="py-line"><tt class="py-docstring"> @return: Length of the 802.15.4 payload.</tt> </tt>
<a name="L332"></a><tt class="py-lineno">332</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L333"></a><tt class="py-lineno">333</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">len</tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> <tt class="py-op">-</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-71" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.hdrlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.hdrlen" class="py-name" href="#" onclick="return doclink('link-71', 'hdrlen', 'link-36');">hdrlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> </tt>
</div><a name="L334"></a><tt class="py-lineno">334</tt> <tt class="py-line"> </tt>
<a name="Dot154PacketParser.nonce"></a><div id="Dot154PacketParser.nonce-def"><a name="L335"></a><tt class="py-lineno">335</tt> <a class="py-toggle" href="#" id="Dot154PacketParser.nonce-toggle" onclick="return toggle('Dot154PacketParser.nonce');">-</a><tt class="py-line"> <tt class="py-keyword">def</tt> <a class="py-def-name" href="killerbee.dot154decode.Dot154PacketParser-class.html#nonce">nonce</a><tt class="py-op">(</tt><tt class="py-param">self</tt><tt class="py-op">,</tt> <tt class="py-param">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt> </tt>
</div><div id="Dot154PacketParser.nonce-collapsed" style="display:none;" pad="+++" indent="++++++++"></div><div id="Dot154PacketParser.nonce-expanded"><a name="L336"></a><tt class="py-lineno">336</tt> <tt class="py-line"> <tt class="py-docstring">'''</tt> </tt>
<a name="L337"></a><tt class="py-lineno">337</tt> <tt class="py-line"><tt class="py-docstring"> Returns the nonce of the 802.15.4 packet. Returns empty string for</tt> </tt>
<a name="L338"></a><tt class="py-lineno">338</tt> <tt class="py-line"><tt class="py-docstring"> unencrypted frames.</tt> </tt>
<a name="L339"></a><tt class="py-lineno">339</tt> <tt class="py-line"><tt class="py-docstring"> @type packet: String</tt> </tt>
<a name="L340"></a><tt class="py-lineno">340</tt> <tt class="py-line"><tt class="py-docstring"> @param packet: Packet contents to evaluate for nonce.</tt> </tt>
<a name="L341"></a><tt class="py-lineno">341</tt> <tt class="py-line"><tt class="py-docstring"> @rtype: String</tt> </tt>
<a name="L342"></a><tt class="py-lineno">342</tt> <tt class="py-line"><tt class="py-docstring"> @return: Nonce, empty when the frame is not encrypted.</tt> </tt>
<a name="L343"></a><tt class="py-lineno">343</tt> <tt class="py-line"><tt class="py-docstring"> '''</tt> </tt>
<a name="L344"></a><tt class="py-lineno">344</tt> <tt class="py-line"> </tt>
<a name="L345"></a><tt class="py-lineno">345</tt> <tt class="py-line"> <tt class="py-comment"># Byte swap</tt> </tt>
<a name="L346"></a><tt class="py-lineno">346</tt> <tt class="py-line"> <tt class="py-name">fcf</tt> <tt class="py-op">=</tt> <tt class="py-name">struct</tt><tt class="py-op">.</tt><tt class="py-name">unpack</tt><tt class="py-op">(</tt><tt class="py-string">"<H"</tt><tt class="py-op">,</tt><tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">:</tt><tt class="py-number">2</tt><tt class="py-op">]</tt><tt class="py-op">)</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> </tt>
<a name="L347"></a><tt class="py-lineno">347</tt> <tt class="py-line"> </tt>
<a name="L348"></a><tt class="py-lineno">348</tt> <tt class="py-line"> <tt class="py-keyword">if</tt> <tt class="py-op">(</tt><tt class="py-name">fcf</tt> <tt class="py-op">&</tt> <tt id="link-72" class="py-name"><a title="killerbee.dot154decode.DOT154_FCF_SEC_EN" class="py-name" href="#" onclick="return doclink('link-72', 'DOT154_FCF_SEC_EN', 'link-1');">DOT154_FCF_SEC_EN</a></tt><tt class="py-op">)</tt> <tt class="py-op">==</tt> <tt class="py-number">0</tt><tt class="py-op">:</tt> </tt>
<a name="L349"></a><tt class="py-lineno">349</tt> <tt class="py-line"> <tt class="py-comment"># Packet is not encrypted</tt> </tt>
<a name="L350"></a><tt class="py-lineno">350</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-string">""</tt> </tt>
<a name="L351"></a><tt class="py-lineno">351</tt> <tt class="py-line"> </tt>
<a name="L352"></a><tt class="py-lineno">352</tt> <tt class="py-line"> <tt class="py-comment"># Nonce formation is Src Addr || Frame Counter || Security Level</tt> </tt>
<a name="L353"></a><tt class="py-lineno">353</tt> <tt class="py-line"> <tt class="py-name">pchop</tt> <tt class="py-op">=</tt> <tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-73" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.pktchop
killerbee.zigbeedecode.ZigBeeAPSPacketParser.pktchop
killerbee.zigbeedecode.ZigBeeNWKPacketParser.pktchop" class="py-name" href="#" onclick="return doclink('link-73', 'pktchop', 'link-42');">pktchop</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt> </tt>
<a name="L354"></a><tt class="py-lineno">354</tt> <tt class="py-line"> </tt>
<a name="L355"></a><tt class="py-lineno">355</tt> <tt class="py-line"> <tt class="py-comment"># SA is the 5th list element, reverse it</tt> </tt>
<a name="L356"></a><tt class="py-lineno">356</tt> <tt class="py-line"> <tt class="py-name">noncep1</tt> <tt class="py-op">=</tt> <tt class="py-name">pchop</tt><tt class="py-op">[</tt><tt class="py-number">5</tt><tt class="py-op">]</tt><tt class="py-op">[</tt><tt class="py-op">:</tt><tt class="py-op">:</tt><tt class="py-op">-</tt><tt class="py-number">1</tt><tt class="py-op">]</tt> </tt>
<a name="L357"></a><tt class="py-lineno">357</tt> <tt class="py-line"> </tt>
<a name="L358"></a><tt class="py-lineno">358</tt> <tt class="py-line"> <tt class="py-comment"># Retrieve the data payload from the packet contents</tt> </tt>
<a name="L359"></a><tt class="py-lineno">359</tt> <tt class="py-line"> <tt class="py-name">encpayload</tt> <tt class="py-op">=</tt> <tt class="py-name">packet</tt><tt class="py-op">[</tt><tt class="py-op">-</tt><tt class="py-name">self</tt><tt class="py-op">.</tt><tt id="link-74" class="py-name"><a title="killerbee.dot154decode.Dot154PacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeAPSPacketParser.payloadlen
killerbee.zigbeedecode.ZigBeeNWKPacketParser.payloadlen" class="py-name" href="#" onclick="return doclink('link-74', 'payloadlen', 'link-27');">payloadlen</a></tt><tt class="py-op">(</tt><tt class="py-name">packet</tt><tt class="py-op">)</tt><tt class="py-op">:</tt><tt class="py-op">]</tt> </tt>
<a name="L360"></a><tt class="py-lineno">360</tt> <tt class="py-line"> </tt>
<a name="L361"></a><tt class="py-lineno">361</tt> <tt class="py-line"> <tt class="py-comment"># First byte of encrypted payload is the security level</tt> </tt>
<a name="L362"></a><tt class="py-lineno">362</tt> <tt class="py-line"> <tt class="py-name">noncep3</tt> <tt class="py-op">=</tt> <tt class="py-name">encpayload</tt><tt class="py-op">[</tt><tt class="py-number">0</tt><tt class="py-op">]</tt> </tt>
<a name="L363"></a><tt class="py-lineno">363</tt> <tt class="py-line"> </tt>
<a name="L364"></a><tt class="py-lineno">364</tt> <tt class="py-line"> <tt class="py-comment"># The next 4 bytes of the encrypted payload is the frame counter, rev</tt> </tt>
<a name="L365"></a><tt class="py-lineno">365</tt> <tt class="py-line"> <tt class="py-name">noncep2</tt> <tt class="py-op">=</tt> <tt class="py-name">encpayload</tt><tt class="py-op">[</tt><tt class="py-number">1</tt><tt class="py-op">:</tt><tt class="py-number">5</tt><tt class="py-op">]</tt><tt class="py-op">[</tt><tt class="py-op">:</tt><tt class="py-op">:</tt><tt class="py-op">-</tt><tt class="py-number">1</tt><tt class="py-op">]</tt> </tt>
<a name="L366"></a><tt class="py-lineno">366</tt> <tt class="py-line"> </tt>
<a name="L367"></a><tt class="py-lineno">367</tt> <tt class="py-line"> <tt class="py-keyword">return</tt> <tt class="py-name">noncep1</tt> <tt class="py-op">+</tt> <tt class="py-name">noncep2</tt> <tt class="py-op">+</tt> <tt class="py-name">noncep3</tt> </tt>
</div></div><a name="L368"></a><tt class="py-lineno">368</tt> <tt class="py-line"> </tt><script type="text/javascript">
<!--
expandto(location.href);
// -->
</script>
</pre>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="killerbee-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Mon Dec 30 17:49:14 2013
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| rfmcpherson/killerbee | doc/killerbee.dot154decode-pysrc.html | HTML | bsd-3-clause | 104,201 |
""" Non-negative matrix factorization
"""
# Author: Vlad Niculae
# Lars Buitinck <[email protected]>
# Mathieu Blondel <[email protected]>
# Tom Dupre la Tour
# Author: Chih-Jen Lin, National Taiwan University (original projected gradient
# NMF implementation)
# Author: Anthony Di Franco (Projected gradient, Python and NumPy port)
# License: BSD 3 clause
from __future__ import division, print_function
from math import sqrt
import warnings
import numbers
import numpy as np
import scipy.sparse as sp
from ..externals import six
from ..base import BaseEstimator, TransformerMixin
from ..utils import check_random_state, check_array
from ..utils.extmath import randomized_svd, safe_sparse_dot, squared_norm
from ..utils.extmath import fast_dot
from ..utils.validation import check_is_fitted, check_non_negative
from ..utils import deprecated
from ..exceptions import ConvergenceWarning
from .cdnmf_fast import _update_cdnmf_fast
def safe_vstack(Xs):
if any(sp.issparse(X) for X in Xs):
return sp.vstack(Xs)
else:
return np.vstack(Xs)
def norm(x):
"""Dot product-based Euclidean norm implementation
See: http://fseoane.net/blog/2011/computing-the-vector-norm/
"""
return sqrt(squared_norm(x))
def trace_dot(X, Y):
"""Trace of np.dot(X, Y.T)."""
return np.dot(X.ravel(), Y.ravel())
def _sparseness(x):
"""Hoyer's measure of sparsity for a vector"""
sqrt_n = np.sqrt(len(x))
return (sqrt_n - np.linalg.norm(x, 1) / norm(x)) / (sqrt_n - 1)
def _check_init(A, shape, whom):
A = check_array(A)
if np.shape(A) != shape:
raise ValueError('Array with wrong shape passed to %s. Expected %s, '
'but got %s ' % (whom, shape, np.shape(A)))
check_non_negative(A, whom)
if np.max(A) == 0:
raise ValueError('Array passed to %s is full of zeros.' % whom)
def _safe_compute_error(X, W, H):
"""Frobenius norm between X and WH, safe for sparse array"""
if not sp.issparse(X):
error = norm(X - np.dot(W, H))
else:
norm_X = np.dot(X.data, X.data)
norm_WH = trace_dot(np.dot(np.dot(W.T, W), H), H)
cross_prod = trace_dot((X * H.T), W)
error = sqrt(norm_X + norm_WH - 2. * cross_prod)
return error
def _check_string_param(sparseness, solver):
allowed_sparseness = (None, 'data', 'components')
if sparseness not in allowed_sparseness:
raise ValueError(
'Invalid sparseness parameter: got %r instead of one of %r' %
(sparseness, allowed_sparseness))
allowed_solver = ('pg', 'cd')
if solver not in allowed_solver:
raise ValueError(
'Invalid solver parameter: got %r instead of one of %r' %
(solver, allowed_solver))
def _initialize_nmf(X, n_components, init=None, eps=1e-6,
random_state=None):
"""Algorithms for NMF initialization.
Computes an initial guess for the non-negative
rank k matrix approximation for X: X = WH
Parameters
----------
X : array-like, shape (n_samples, n_features)
The data matrix to be decomposed.
n_components : integer
The number of components desired in the approximation.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise 'random'.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
eps : float
Truncate all values less then this in output to zero.
random_state : int seed, RandomState instance, or None (default)
Random number generator seed control, used in 'nndsvdar' and
'random' modes.
Returns
-------
W : array-like, shape (n_samples, n_components)
Initial guesses for solving X ~= WH
H : array-like, shape (n_components, n_features)
Initial guesses for solving X ~= WH
References
----------
C. Boutsidis, E. Gallopoulos: SVD based initialization: A head start for
nonnegative matrix factorization - Pattern Recognition, 2008
http://tinyurl.com/nndsvd
"""
check_non_negative(X, "NMF initialization")
n_samples, n_features = X.shape
if init is None:
if n_components < n_features:
init = 'nndsvd'
else:
init = 'random'
# Random initialization
if init == 'random':
avg = np.sqrt(X.mean() / n_components)
rng = check_random_state(random_state)
H = avg * rng.randn(n_components, n_features)
W = avg * rng.randn(n_samples, n_components)
# we do not write np.abs(H, out=H) to stay compatible with
# numpy 1.5 and earlier where the 'out' keyword is not
# supported as a kwarg on ufuncs
np.abs(H, H)
np.abs(W, W)
return W, H
# NNDSVD initialization
U, S, V = randomized_svd(X, n_components, random_state=random_state)
W, H = np.zeros(U.shape), np.zeros(V.shape)
# The leading singular triplet is non-negative
# so it can be used as is for initialization.
W[:, 0] = np.sqrt(S[0]) * np.abs(U[:, 0])
H[0, :] = np.sqrt(S[0]) * np.abs(V[0, :])
for j in range(1, n_components):
x, y = U[:, j], V[j, :]
# extract positive and negative parts of column vectors
x_p, y_p = np.maximum(x, 0), np.maximum(y, 0)
x_n, y_n = np.abs(np.minimum(x, 0)), np.abs(np.minimum(y, 0))
# and their norms
x_p_nrm, y_p_nrm = norm(x_p), norm(y_p)
x_n_nrm, y_n_nrm = norm(x_n), norm(y_n)
m_p, m_n = x_p_nrm * y_p_nrm, x_n_nrm * y_n_nrm
# choose update
if m_p > m_n:
u = x_p / x_p_nrm
v = y_p / y_p_nrm
sigma = m_p
else:
u = x_n / x_n_nrm
v = y_n / y_n_nrm
sigma = m_n
lbd = np.sqrt(S[j] * sigma)
W[:, j] = lbd * u
H[j, :] = lbd * v
W[W < eps] = 0
H[H < eps] = 0
if init == "nndsvd":
pass
elif init == "nndsvda":
avg = X.mean()
W[W == 0] = avg
H[H == 0] = avg
elif init == "nndsvdar":
rng = check_random_state(random_state)
avg = X.mean()
W[W == 0] = abs(avg * rng.randn(len(W[W == 0])) / 100)
H[H == 0] = abs(avg * rng.randn(len(H[H == 0])) / 100)
else:
raise ValueError(
'Invalid init parameter: got %r instead of one of %r' %
(init, (None, 'random', 'nndsvd', 'nndsvda', 'nndsvdar')))
return W, H
def _nls_subproblem(V, W, H, tol, max_iter, alpha=0., l1_ratio=0.,
sigma=0.01, beta=0.1):
"""Non-negative least square solver
Solves a non-negative least squares subproblem using the projected
gradient descent algorithm.
Parameters
----------
V : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Constant matrix.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float
Tolerance of the stopping condition.
max_iter : int
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
sigma : float
Constant used in the sufficient decrease condition checked by the line
search. Smaller values lead to a looser sufficient decrease condition,
thus reducing the time taken by the line search, but potentially
increasing the number of iterations of the projected gradient
procedure. 0.01 is a commonly used value in the optimization
literature.
beta : float
Factor by which the step size is decreased (resp. increased) until
(resp. as long as) the sufficient decrease condition is satisfied.
Larger values allow to find a better step size but lead to longer line
search. 0.1 is a commonly used value in the optimization literature.
Returns
-------
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
grad : array-like, shape (n_components, n_features)
The gradient.
n_iter : int
The number of iterations done by the algorithm.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
"""
WtV = safe_sparse_dot(W.T, V)
WtW = fast_dot(W.T, W)
# values justified in the paper (alpha is renamed gamma)
gamma = 1
for n_iter in range(1, max_iter + 1):
grad = np.dot(WtW, H) - WtV
if alpha > 0 and l1_ratio == 1.:
grad += alpha
elif alpha > 0:
grad += alpha * (l1_ratio + (1 - l1_ratio) * H)
# The following multiplication with a boolean array is more than twice
# as fast as indexing into grad.
if norm(grad * np.logical_or(grad < 0, H > 0)) < tol:
break
Hp = H
for inner_iter in range(20):
# Gradient step.
Hn = H - gamma * grad
# Projection step.
Hn *= Hn > 0
d = Hn - H
gradd = np.dot(grad.ravel(), d.ravel())
dQd = np.dot(np.dot(WtW, d).ravel(), d.ravel())
suff_decr = (1 - sigma) * gradd + 0.5 * dQd < 0
if inner_iter == 0:
decr_gamma = not suff_decr
if decr_gamma:
if suff_decr:
H = Hn
break
else:
gamma *= beta
elif not suff_decr or (Hp == Hn).all():
H = Hp
break
else:
gamma /= beta
Hp = Hn
if n_iter == max_iter:
warnings.warn("Iteration limit reached in nls subproblem.")
return H, grad, n_iter
def _update_projected_gradient_w(X, W, H, tolW, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = H.shape[0]
if sparseness is None:
Wt, gradW, iterW = _nls_subproblem(X.T, H.T, W.T, tolW, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T, np.zeros((1, n_samples))]),
safe_vstack([H.T, np.sqrt(beta) * np.ones((1,
n_components_))]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
Wt, gradW, iterW = _nls_subproblem(
safe_vstack([X.T,
np.zeros((n_components_, n_samples))]),
safe_vstack([H.T,
np.sqrt(eta) * np.eye(n_components_)]),
W.T, tolW, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return Wt.T, gradW.T, iterW
def _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Helper function for _fit_projected_gradient"""
n_samples, n_features = X.shape
n_components_ = W.shape[1]
if sparseness is None:
H, gradH, iterH = _nls_subproblem(X, W, H, tolH, nls_max_iter,
alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'data':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((n_components_, n_features))]),
safe_vstack([W,
np.sqrt(eta) * np.eye(n_components_)]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
elif sparseness == 'components':
H, gradH, iterH = _nls_subproblem(
safe_vstack([X, np.zeros((1, n_features))]),
safe_vstack([W,
np.sqrt(beta)
* np.ones((1, n_components_))]),
H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio)
return H, gradH, iterH
def _fit_projected_gradient(X, W, H, tol, max_iter,
nls_max_iter, alpha, l1_ratio,
sparseness, beta, eta):
"""Compute Non-negative Matrix Factorization (NMF) with Projected Gradient
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
P. Hoyer. Non-negative Matrix Factorization with Sparseness Constraints.
Journal of Machine Learning Research 2004.
"""
gradW = (np.dot(W, np.dot(H, H.T))
- safe_sparse_dot(X, H.T, dense_output=True))
gradH = (np.dot(np.dot(W.T, W), H)
- safe_sparse_dot(W.T, X, dense_output=True))
init_grad = squared_norm(gradW) + squared_norm(gradH.T)
# max(0.001, tol) to force alternating minimizations of W and H
tolW = max(0.001, tol) * np.sqrt(init_grad)
tolH = tolW
for n_iter in range(1, max_iter + 1):
# stopping condition
# as discussed in paper
proj_grad_W = squared_norm(gradW * np.logical_or(gradW < 0, W > 0))
proj_grad_H = squared_norm(gradH * np.logical_or(gradH < 0, H > 0))
if (proj_grad_W + proj_grad_H) / init_grad < tol ** 2:
break
# update W
W, gradW, iterW = _update_projected_gradient_w(X, W, H, tolW,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterW == 1:
tolW = 0.1 * tolW
# update H
H, gradH, iterH = _update_projected_gradient_h(X, W, H, tolH,
nls_max_iter,
alpha, l1_ratio,
sparseness, beta, eta)
if iterH == 1:
tolH = 0.1 * tolH
H[H == 0] = 0 # fix up negative zeros
if n_iter == max_iter:
W, _, _ = _update_projected_gradient_w(X, W, H, tol, nls_max_iter,
alpha, l1_ratio, sparseness,
beta, eta)
return W, H, n_iter
def _update_coordinate_descent(X, W, Ht, l1_reg, l2_reg, shuffle,
random_state):
"""Helper function for _fit_coordinate_descent
Update W to minimize the objective function, iterating once over all
coordinates. By symmetry, to update H, one can call
_update_coordinate_descent(X.T, Ht, W, ...)
"""
n_components = Ht.shape[1]
HHt = fast_dot(Ht.T, Ht)
XHt = safe_sparse_dot(X, Ht)
# L2 regularization corresponds to increase the diagonal of HHt
if l2_reg != 0.:
# adds l2_reg only on the diagonal
HHt.flat[::n_components + 1] += l2_reg
# L1 regularization correponds to decrease each element of XHt
if l1_reg != 0.:
XHt -= l1_reg
if shuffle:
permutation = random_state.permutation(n_components)
else:
permutation = np.arange(n_components)
# The following seems to be required on 64-bit Windows w/ Python 3.5.
permutation = np.asarray(permutation, dtype=np.intp)
return _update_cdnmf_fast(W, HHt, XHt, permutation)
def _fit_coordinate_descent(X, W, H, tol=1e-4, max_iter=200, alpha=0.001,
l1_ratio=0., regularization=None, update_H=True,
verbose=0, shuffle=False, random_state=None):
"""Compute Non-negative Matrix Factorization (NMF) with Coordinate Descent
The objective function is minimized with an alternating minimization of W
and H. Each minimization is done with a cyclic (up to a permutation of the
features) Coordinate Descent.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Initial guess for the solution.
H : array-like, shape (n_components, n_features)
Initial guess for the solution.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an L2 penalty.
For l1_ratio = 1 it is an L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
The number of iterations done by the algorithm.
References
----------
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
# so W and Ht are both in C order in memory
Ht = check_array(H.T, order='C')
X = check_array(X, accept_sparse='csr')
# L1 and L2 regularization
l1_H, l2_H, l1_W, l2_W = 0, 0, 0, 0
if regularization in ('both', 'components'):
alpha = float(alpha)
l1_H = l1_ratio * alpha
l2_H = (1. - l1_ratio) * alpha
if regularization in ('both', 'transformation'):
alpha = float(alpha)
l1_W = l1_ratio * alpha
l2_W = (1. - l1_ratio) * alpha
rng = check_random_state(random_state)
for n_iter in range(max_iter):
violation = 0.
# Update W
violation += _update_coordinate_descent(X, W, Ht, l1_W, l2_W,
shuffle, rng)
# Update H
if update_H:
violation += _update_coordinate_descent(X.T, Ht, W, l1_H, l2_H,
shuffle, rng)
if n_iter == 0:
violation_init = violation
if violation_init == 0:
break
if verbose:
print("violation:", violation / violation_init)
if violation / violation_init <= tol:
if verbose:
print("Converged at iteration", n_iter + 1)
break
return W, Ht.T, n_iter
def non_negative_factorization(X, W=None, H=None, n_components=None,
init='random', update_H=True, solver='cd',
tol=1e-4, max_iter=200, alpha=0., l1_ratio=0.,
regularization=None, random_state=None,
verbose=0, shuffle=False, nls_max_iter=2000,
sparseness=None, beta=1, eta=0.1):
"""Compute Non-negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H. If H is given and update_H=False, it solves for W only.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
If update_H=False, it is used as a constant, to solve for W only.
n_components : integer
Number of components, if n_components is not set all features
are kept.
init : None | 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvd' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
update_H : boolean, default: True
Set to True, both W and H will be estimated from initial guesses.
Set to False, only W will be estimated.
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a (deprecated) Projected Gradient solver.
'cd' is a Coordinate Descent solver.
tol : float, default: 1e-4
Tolerance of the stopping condition.
max_iter : integer, default: 200
Maximum number of iterations before timing out.
alpha : double, default: 0.
Constant that multiplies the regularization terms.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
regularization : 'both' | 'components' | 'transformation' | None
Select whether the regularization affects the components (H), the
transformation (W), both or none of them.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
verbose : integer, default: 0
The verbosity level.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
Returns
-------
W : array-like, shape (n_samples, n_components)
Solution to the non-negative least squares problem.
H : array-like, shape (n_components, n_features)
Solution to the non-negative least squares problem.
n_iter : int
Actual number of iterations.
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
check_non_negative(X, "NMF (input X)")
_check_string_param(sparseness, solver)
n_samples, n_features = X.shape
if n_components is None:
n_components = n_features
if not isinstance(n_components, six.integer_types) or n_components <= 0:
raise ValueError("Number of components must be positive;"
" got (n_components=%r)" % n_components)
if not isinstance(max_iter, numbers.Number) or max_iter < 0:
raise ValueError("Maximum number of iteration must be positive;"
" got (max_iter=%r)" % max_iter)
if not isinstance(tol, numbers.Number) or tol < 0:
raise ValueError("Tolerance for stopping criteria must be "
"positive; got (tol=%r)" % tol)
# check W and H, or initialize them
if init == 'custom':
_check_init(H, (n_components, n_features), "NMF (input H)")
_check_init(W, (n_samples, n_components), "NMF (input W)")
elif not update_H:
_check_init(H, (n_components, n_features), "NMF (input H)")
W = np.zeros((n_samples, n_components))
else:
W, H = _initialize_nmf(X, n_components, init=init,
random_state=random_state)
if solver == 'pg':
warnings.warn("'pg' solver will be removed in release 0.19."
" Use 'cd' solver instead.", DeprecationWarning)
if update_H: # fit_transform
W, H, n_iter = _fit_projected_gradient(X, W, H, tol,
max_iter,
nls_max_iter,
alpha, l1_ratio,
sparseness,
beta, eta)
else: # transform
W, H, n_iter = _update_projected_gradient_w(X, W, H,
tol, nls_max_iter,
alpha, l1_ratio,
sparseness, beta,
eta)
elif solver == 'cd':
W, H, n_iter = _fit_coordinate_descent(X, W, H, tol,
max_iter,
alpha, l1_ratio,
regularization,
update_H=update_H,
verbose=verbose,
shuffle=shuffle,
random_state=random_state)
else:
raise ValueError("Invalid solver parameter '%s'." % solver)
if n_iter == max_iter:
warnings.warn("Maximum number of iteration %d reached. Increase it to"
" improve convergence." % max_iter, ConvergenceWarning)
return W, H, n_iter
class NMF(BaseEstimator, TransformerMixin):
"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a Projected Gradient solver (deprecated).
'cd' is a Coordinate Descent solver (recommended).
.. versionadded:: 0.17
Coordinate Descent solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver.
tol : double, default: 1e-4
Tolerance value used in stopping conditions.
max_iter : integer, default: 200
Number of iterations to compute.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
.. versionadded:: 0.17
*alpha* used in the Coordinate Descent solver.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
.. versionadded:: 0.17
Regularization parameter *l1_ratio* used in the Coordinate Descent solver.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
.. versionadded:: 0.17
*shuffle* parameter used in the Coordinate Descent solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
Attributes
----------
components_ : array, [n_components, n_features]
Non-negative components of the data.
reconstruction_err_ : number
Frobenius norm of the matrix difference between
the training data and the reconstructed data from
the fit produced by the model. ``|| X - WH ||_2``
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200,
n_components=2, nls_max_iter=2000, random_state=0, shuffle=False,
solver='cd', sparseness=None, tol=0.0001, verbose=0)
>>> model.components_
array([[ 2.09783018, 0.30560234],
[ 2.13443044, 2.13171694]])
>>> model.reconstruction_err_ #doctest: +ELLIPSIS
0.00115993...
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
def __init__(self, n_components=None, init=None, solver='cd',
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0, shuffle=False,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
self.n_components = n_components
self.init = init
self.solver = solver
self.tol = tol
self.max_iter = max_iter
self.random_state = random_state
self.alpha = alpha
self.l1_ratio = l1_ratio
self.verbose = verbose
self.shuffle = shuffle
if sparseness is not None:
warnings.warn("Controlling regularization through the sparseness,"
" beta and eta arguments is only available"
" for 'pg' solver, which will be removed"
" in release 0.19. Use another solver with L1 or L2"
" regularization instead.", DeprecationWarning)
self.nls_max_iter = nls_max_iter
self.sparseness = sparseness
self.beta = beta
self.eta = eta
def fit_transform(self, X, y=None, W=None, H=None):
"""Learn a NMF model for the data X and returns the transformed data.
This is more efficient than calling fit followed by transform.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
W : array-like, shape (n_samples, n_components)
If init='custom', it is used as initial guess for the solution.
H : array-like, shape (n_components, n_features)
If init='custom', it is used as initial guess for the solution.
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data.
"""
X = check_array(X, accept_sparse=('csr', 'csc'))
W, H, n_iter_ = non_negative_factorization(
X=X, W=W, H=H, n_components=self.n_components,
init=self.init, update_H=True, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
if self.solver == 'pg':
self.comp_sparseness_ = _sparseness(H.ravel())
self.data_sparseness_ = _sparseness(W.ravel())
self.reconstruction_err_ = _safe_compute_error(X, W, H)
self.n_components_ = H.shape[0]
self.components_ = H
self.n_iter_ = n_iter_
return W
def fit(self, X, y=None, **params):
"""Learn a NMF model for the data X.
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be decomposed
Attributes
----------
components_ : array-like, shape (n_components, n_features)
Factorization matrix, sometimes called 'dictionary'.
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
self
"""
self.fit_transform(X, **params)
return self
def transform(self, X):
"""Transform the data X according to the fitted NMF model
Parameters
----------
X: {array-like, sparse matrix}, shape (n_samples, n_features)
Data matrix to be transformed by the model
Attributes
----------
n_iter_ : int
Actual number of iterations for the transform.
Returns
-------
W: array, shape (n_samples, n_components)
Transformed data
"""
check_is_fitted(self, 'n_components_')
W, _, n_iter_ = non_negative_factorization(
X=X, W=None, H=self.components_, n_components=self.n_components_,
init=self.init, update_H=False, solver=self.solver,
tol=self.tol, max_iter=self.max_iter, alpha=self.alpha,
l1_ratio=self.l1_ratio, regularization='both',
random_state=self.random_state, verbose=self.verbose,
shuffle=self.shuffle,
nls_max_iter=self.nls_max_iter, sparseness=self.sparseness,
beta=self.beta, eta=self.eta)
self.n_iter_ = n_iter_
return W
@deprecated("It will be removed in release 0.19. Use NMF instead."
"'pg' solver is still available until release 0.19.")
class ProjectedGradientNMF(NMF):
"""Non-Negative Matrix Factorization (NMF)
Find two non-negative matrices (W, H) whose product approximates the non-
negative matrix X. This factorization can be used for example for
dimensionality reduction, source separation or topic extraction.
The objective function is::
0.5 * ||X - WH||_Fro^2
+ alpha * l1_ratio * ||vec(W)||_1
+ alpha * l1_ratio * ||vec(H)||_1
+ 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2
+ 0.5 * alpha * (1 - l1_ratio) * ||H||_Fro^2
Where::
||A||_Fro^2 = \sum_{i,j} A_{ij}^2 (Frobenius norm)
||vec(A)||_1 = \sum_{i,j} abs(A_{ij}) (Elementwise L1 norm)
The objective function is minimized with an alternating minimization of W
and H.
Read more in the :ref:`User Guide <NMF>`.
Parameters
----------
n_components : int or None
Number of components, if n_components is not set all features
are kept.
init : 'random' | 'nndsvd' | 'nndsvda' | 'nndsvdar' | 'custom'
Method used to initialize the procedure.
Default: 'nndsvdar' if n_components < n_features, otherwise random.
Valid options:
- 'random': non-negative random matrices, scaled with:
sqrt(X.mean() / n_components)
- 'nndsvd': Nonnegative Double Singular Value Decomposition (NNDSVD)
initialization (better for sparseness)
- 'nndsvda': NNDSVD with zeros filled with the average of X
(better when sparsity is not desired)
- 'nndsvdar': NNDSVD with zeros filled with small random values
(generally faster, less accurate alternative to NNDSVDa
for when sparsity is not desired)
- 'custom': use custom matrices W and H
solver : 'pg' | 'cd'
Numerical solver to use:
'pg' is a Projected Gradient solver (deprecated).
'cd' is a Coordinate Descent solver (recommended).
.. versionadded:: 0.17
Coordinate Descent solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver.
tol : double, default: 1e-4
Tolerance value used in stopping conditions.
max_iter : integer, default: 200
Number of iterations to compute.
random_state : integer seed, RandomState instance, or None (default)
Random number generator seed control.
alpha : double, default: 0.
Constant that multiplies the regularization terms. Set it to zero to
have no regularization.
.. versionadded:: 0.17
*alpha* used in the Coordinate Descent solver.
l1_ratio : double, default: 0.
The regularization mixing parameter, with 0 <= l1_ratio <= 1.
For l1_ratio = 0 the penalty is an elementwise L2 penalty
(aka Frobenius Norm).
For l1_ratio = 1 it is an elementwise L1 penalty.
For 0 < l1_ratio < 1, the penalty is a combination of L1 and L2.
.. versionadded:: 0.17
Regularization parameter *l1_ratio* used in the Coordinate Descent solver.
shuffle : boolean, default: False
If true, randomize the order of coordinates in the CD solver.
.. versionadded:: 0.17
*shuffle* parameter used in the Coordinate Descent solver.
nls_max_iter : integer, default: 2000
Number of iterations in NLS subproblem.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
sparseness : 'data' | 'components' | None, default: None
Where to enforce sparsity in the model.
Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
beta : double, default: 1
Degree of sparseness, if sparseness is not None. Larger values mean
more sparseness. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
eta : double, default: 0.1
Degree of correctness to maintain, if sparsity is not None. Smaller
values mean larger error. Used only in the deprecated 'pg' solver.
.. versionchanged:: 0.17
Deprecated Projected Gradient solver. Use Coordinate Descent solver
instead.
Attributes
----------
components_ : array, [n_components, n_features]
Non-negative components of the data.
reconstruction_err_ : number
Frobenius norm of the matrix difference between
the training data and the reconstructed data from
the fit produced by the model. ``|| X - WH ||_2``
n_iter_ : int
Actual number of iterations.
Examples
--------
>>> import numpy as np
>>> X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
>>> from sklearn.decomposition import NMF
>>> model = NMF(n_components=2, init='random', random_state=0)
>>> model.fit(X) #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
NMF(alpha=0.0, beta=1, eta=0.1, init='random', l1_ratio=0.0, max_iter=200,
n_components=2, nls_max_iter=2000, random_state=0, shuffle=False,
solver='cd', sparseness=None, tol=0.0001, verbose=0)
>>> model.components_
array([[ 2.09783018, 0.30560234],
[ 2.13443044, 2.13171694]])
>>> model.reconstruction_err_ #doctest: +ELLIPSIS
0.00115993...
References
----------
C.-J. Lin. Projected gradient methods for non-negative matrix
factorization. Neural Computation, 19(2007), 2756-2779.
http://www.csie.ntu.edu.tw/~cjlin/nmf/
Cichocki, Andrzej, and P. H. A. N. Anh-Huy. "Fast local algorithms for
large scale nonnegative matrix and tensor factorizations."
IEICE transactions on fundamentals of electronics, communications and
computer sciences 92.3: 708-721, 2009.
"""
def __init__(self, n_components=None, solver='pg', init=None,
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., verbose=0,
nls_max_iter=2000, sparseness=None, beta=1, eta=0.1):
super(ProjectedGradientNMF, self).__init__(
n_components=n_components, init=init, solver='pg', tol=tol,
max_iter=max_iter, random_state=random_state, alpha=alpha,
l1_ratio=l1_ratio, verbose=verbose, nls_max_iter=nls_max_iter,
sparseness=sparseness, beta=beta, eta=eta)
| f3r/scikit-learn | sklearn/decomposition/nmf.py | Python | bsd-3-clause | 46,549 |
// Copyright (c) 2011 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 "base/process_util.h"
#include <ctype.h>
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "base/logging.h"
#include "base/string_tokenizer.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/sys_info.h"
namespace base {
ProcessId GetParentProcessId(ProcessHandle process) {
struct kinfo_proc info;
size_t length;
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process };
if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
return -1;
return info.ki_ppid;
}
FilePath GetProcessExecutablePath(ProcessHandle process) {
char pathname[PATH_MAX];
size_t length;
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, process };
length = sizeof(pathname);
if (sysctl(mib, arraysize(mib), pathname, &length, NULL, 0) < 0 ||
length == 0) {
return FilePath();
}
return FilePath(std::string(pathname));
}
void EnableTerminationOnOutOfMemory() {
DLOG(WARNING) << "Not feasible.";
}
void EnableTerminationOnHeapCorruption() {
// Nothing to do.
}
bool AdjustOOMScore(ProcessId process, int score) {
NOTIMPLEMENTED();
return false;
}
} // namespace base
| espadrine/opera | chromium/src/base/process_util_freebsd.cc | C++ | bsd-3-clause | 1,575 |
-----------------------------------------------------------------------------
-- |
-- Module : Window
-- Copyright : (c) 2011-15 Jose A. Ortega Ruiz
-- : (c) 2012 Jochen Keil
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Window manipulation functions
--
-----------------------------------------------------------------------------
module Window where
import Prelude
import Control.Applicative ((<$>))
import Control.Monad (when, unless)
import Graphics.X11.Xlib hiding (textExtents, textWidth)
import Graphics.X11.Xlib.Extras
import Graphics.X11.Xinerama
import Foreign.C.Types (CLong)
import Data.Function (on)
import Data.List (maximumBy)
import Data.Maybe (fromMaybe)
import System.Posix.Process (getProcessID)
import Config
import XUtil
-- $window
-- | The function to create the initial window
createWin :: Display -> XFont -> Config -> IO (Rectangle,Window)
createWin d fs c = do
let dflt = defaultScreen d
srs <- getScreenInfo d
rootw <- rootWindow d dflt
(as,ds) <- textExtents fs "0"
let ht = as + ds + 4
r = setPosition c (position c) srs (fi ht)
win <- newWindow d (defaultScreenOfDisplay d) rootw r (overrideRedirect c)
setProperties c d win
setStruts r c d win srs
when (lowerOnStart c) $ lowerWindow d win
unless (hideOnStart c) $ showWindow r c d win
return (r,win)
-- | Updates the size and position of the window
repositionWin :: Display -> Window -> XFont -> Config -> IO Rectangle
repositionWin d win fs c = do
srs <- getScreenInfo d
(as,ds) <- textExtents fs "0"
let ht = as + ds + 4
r = setPosition c (position c) srs (fi ht)
moveResizeWindow d win (rect_x r) (rect_y r) (rect_width r) (rect_height r)
setStruts r c d win srs
return r
setPosition :: Config -> XPosition -> [Rectangle] -> Dimension -> Rectangle
setPosition c p rs ht =
case p' of
Top -> Rectangle rx ry rw h
TopP l r -> Rectangle (rx + fi l) ry (rw - fi l - fi r) h
TopW a i -> Rectangle (ax a i) ry (nw i) h
TopSize a i ch -> Rectangle (ax a i) ry (nw i) (mh ch)
Bottom -> Rectangle rx ny rw h
BottomW a i -> Rectangle (ax a i) ny (nw i) h
BottomP l r -> Rectangle (rx + fi l) ny (rw - fi l - fi r) h
BottomSize a i ch -> Rectangle (ax a i) (ny' ch) (nw i) (mh ch)
Static cx cy cw ch -> Rectangle (fi cx) (fi cy) (fi cw) (fi ch)
OnScreen _ p'' -> setPosition c p'' [scr] ht
where
(scr@(Rectangle rx ry rw rh), p') =
case p of OnScreen i x -> (fromMaybe (picker rs) $ safeIndex i rs, x)
_ -> (picker rs, p)
ny = ry + fi (rh - ht)
center i = rx + fi (div (remwid i) 2)
right i = rx + fi (remwid i)
remwid i = rw - pw (fi i)
ax L = const rx
ax R = right
ax C = center
pw i = rw * min 100 i `div` 100
nw = fi . pw . fi
h = fi ht
mh h' = max (fi h') h
ny' h' = ry + fi (rh - mh h')
safeIndex i = lookup i . zip [0..]
picker = if pickBroadest c
then maximumBy (compare `on` rect_width)
else head
setProperties :: Config -> Display -> Window -> IO ()
setProperties c d w = do
let mkatom n = internAtom d n False
card <- mkatom "CARDINAL"
atom <- mkatom "ATOM"
setTextProperty d w "xmobar" wM_CLASS
setTextProperty d w "xmobar" wM_NAME
wtype <- mkatom "_NET_WM_WINDOW_TYPE"
dock <- mkatom "_NET_WM_WINDOW_TYPE_DOCK"
changeProperty32 d w wtype atom propModeReplace [fi dock]
when (allDesktops c) $ do
desktop <- mkatom "_NET_WM_DESKTOP"
changeProperty32 d w desktop card propModeReplace [0xffffffff]
pid <- mkatom "_NET_WM_PID"
getProcessID >>= changeProperty32 d w pid card propModeReplace . return . fi
setStruts' :: Display -> Window -> [Foreign.C.Types.CLong] -> IO ()
setStruts' d w svs = do
let mkatom n = internAtom d n False
card <- mkatom "CARDINAL"
pstrut <- mkatom "_NET_WM_STRUT_PARTIAL"
strut <- mkatom "_NET_WM_STRUT"
changeProperty32 d w pstrut card propModeReplace svs
changeProperty32 d w strut card propModeReplace (take 4 svs)
setStruts :: Rectangle -> Config -> Display -> Window -> [Rectangle] -> IO ()
setStruts r c d w rs = do
let svs = map fi $ getStrutValues r (position c) (getRootWindowHeight rs)
setStruts' d w svs
getRootWindowHeight :: [Rectangle] -> Int
getRootWindowHeight srs = maximum (map getMaxScreenYCoord srs)
where
getMaxScreenYCoord sr = fi (rect_y sr) + fi (rect_height sr)
getStrutValues :: Rectangle -> XPosition -> Int -> [Int]
getStrutValues r@(Rectangle x y w h) p rwh =
case p of
OnScreen _ p' -> getStrutValues r p' rwh
Top -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopP _ _ -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopW _ _ -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
TopSize {} -> [0, 0, st, 0, 0, 0, 0, 0, nx, nw, 0, 0]
Bottom -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomP _ _ -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomW _ _ -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
BottomSize {} -> [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, nx, nw]
Static {} -> getStaticStrutValues p rwh
where st = fi y + fi h
sb = rwh - fi y
nx = fi x
nw = fi (x + fi w - 1)
-- get some reaonable strut values for static placement.
getStaticStrutValues :: XPosition -> Int -> [Int]
getStaticStrutValues (Static cx cy cw ch) rwh
-- if the yPos is in the top half of the screen, then assume a Top
-- placement, otherwise, it's a Bottom placement
| cy < (rwh `div` 2) = [0, 0, st, 0, 0, 0, 0, 0, xs, xe, 0, 0]
| otherwise = [0, 0, 0, sb, 0, 0, 0, 0, 0, 0, xs, xe]
where st = cy + ch
sb = rwh - cy
xs = cx -- a simple calculation for horizontal (x) placement
xe = xs + cw
getStaticStrutValues _ _ = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
drawBorder :: Border -> Int -> Display -> Drawable -> GC -> Pixel
-> Dimension -> Dimension -> IO ()
drawBorder b lw d p gc c wi ht = case b of
NoBorder -> return ()
TopB -> drawBorder (TopBM 0) lw d p gc c wi ht
BottomB -> drawBorder (BottomBM 0) lw d p gc c wi ht
FullB -> drawBorder (FullBM 0) lw d p gc c wi ht
TopBM m -> sf >> sla >>
drawLine d p gc 0 (fi m + boff) (fi wi) (fi m + boff)
BottomBM m -> let rw = fi ht - fi m + boff in
sf >> sla >> drawLine d p gc 0 rw (fi wi) rw
FullBM m -> let mp = fi m
pad = 2 * fi mp + fi lw
in sf >> sla >>
drawRectangle d p gc mp mp (wi - pad + 1) (ht - pad)
where sf = setForeground d gc c
sla = setLineAttributes d gc (fi lw) lineSolid capNotLast joinMiter
boff = borderOffset b lw
-- boff' = calcBorderOffset lw :: Int
hideWindow :: Display -> Window -> IO ()
hideWindow d w = do
setStruts' d w (replicate 12 0)
unmapWindow d w >> sync d False
showWindow :: Rectangle -> Config -> Display -> Window -> IO ()
showWindow r c d w = do
mapWindow d w
getScreenInfo d >>= setStruts r c d w
sync d False
isMapped :: Display -> Window -> IO Bool
isMapped d w = ism <$> getWindowAttributes d w
where ism (WindowAttributes { wa_map_state = wms }) = wms /= waIsUnmapped
borderOffset :: (Integral a) => Border -> Int -> a
borderOffset b lw =
case b of
BottomB -> negate boffs
BottomBM _ -> negate boffs
TopB -> boffs
TopBM _ -> boffs
_ -> 0
where boffs = calcBorderOffset lw
calcBorderOffset :: (Integral a) => Int -> a
calcBorderOffset = ceiling . (/2) . toDouble
where toDouble = fi :: (Integral a) => a -> Double
| dsalisbury/xmobar | src/Window.hs | Haskell | bsd-3-clause | 7,751 |
#ifndef _ROS_SERVICE_SetCameraInfo_h
#define _ROS_SERVICE_SetCameraInfo_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "sensor_msgs/CameraInfo.h"
namespace sensor_msgs
{
static const char SETCAMERAINFO[] = "sensor_msgs/SetCameraInfo";
class SetCameraInfoRequest : public ros::Msg
{
public:
sensor_msgs::CameraInfo camera_info;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->camera_info.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->camera_info.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return SETCAMERAINFO; };
const char * getMD5(){ return "ee34be01fdeee563d0d99cd594d5581d"; };
};
class SetCameraInfoResponse : public ros::Msg
{
public:
bool success;
const char* status_message;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
bool real;
uint8_t base;
} u_success;
u_success.real = this->success;
*(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->success);
uint32_t length_status_message = strlen(this->status_message);
memcpy(outbuffer + offset, &length_status_message, sizeof(uint32_t));
offset += 4;
memcpy(outbuffer + offset, this->status_message, length_status_message);
offset += length_status_message;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
bool real;
uint8_t base;
} u_success;
u_success.base = 0;
u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->success = u_success.real;
offset += sizeof(this->success);
uint32_t length_status_message;
memcpy(&length_status_message, (inbuffer + offset), sizeof(uint32_t));
offset += 4;
for(unsigned int k= offset; k< offset+length_status_message; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_status_message-1]=0;
this->status_message = (char *)(inbuffer + offset-1);
offset += length_status_message;
return offset;
}
const char * getType(){ return SETCAMERAINFO; };
const char * getMD5(){ return "2ec6f3eff0161f4257b808b12bc830c2"; };
};
class SetCameraInfo {
public:
typedef SetCameraInfoRequest Request;
typedef SetCameraInfoResponse Response;
};
}
#endif
| davidx3601/ric | ric_mc/Arduino/libraries/ros_lib/sensor_msgs/SetCameraInfo.h | C | bsd-3-clause | 2,643 |
<!DOCTYPE html>
<script>
if (window.internals) {
internals.settings.setOverlayScrollbarsEnabled(true);
internals.settings.setMockScrollbarsEnabled(true);
}
</script>
<div style="position: absolute; width: 2000px; height: 2000px; background-color: blue">
<div style="width: 20%; height: 20%; background-color: yellow">
</div>
</div>
| danakj/chromium | third_party/WebKit/LayoutTests/fast/repaint/window-resize-no-layout-change2-expected.html | HTML | bsd-3-clause | 348 |
// 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.
#ifndef NET_SPDY_SPDY_STREAM_TEST_UTIL_H_
#define NET_SPDY_SPDY_STREAM_TEST_UTIL_H_
#include <memory>
#include <string>
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/strings/string_piece.h"
#include "net/base/io_buffer.h"
#include "net/base/load_timing_info.h"
#include "net/base/test_completion_callback.h"
#include "net/log/net_log_source.h"
#include "net/spdy/spdy_read_queue.h"
#include "net/spdy/spdy_stream.h"
namespace net {
namespace test {
// Delegate that calls Close() on |stream_| on OnClose. Used by tests
// to make sure that such an action is harmless.
class ClosingDelegate : public SpdyStream::Delegate {
public:
explicit ClosingDelegate(const base::WeakPtr<SpdyStream>& stream);
~ClosingDelegate() override;
// SpdyStream::Delegate implementation.
void OnEarlyHintsReceived(const spdy::Http2HeaderBlock& headers) override;
void OnHeadersSent() override;
void OnHeadersReceived(
const spdy::Http2HeaderBlock& response_headers,
const spdy::Http2HeaderBlock* pushed_request_headers) override;
void OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) override;
void OnDataSent() override;
void OnTrailers(const spdy::Http2HeaderBlock& trailers) override;
void OnClose(int status) override;
bool CanGreaseFrameType() const override;
NetLogSource source_dependency() const override;
// Returns whether or not the stream is closed.
bool StreamIsClosed() const { return !stream_.get(); }
private:
base::WeakPtr<SpdyStream> stream_;
};
// Base class with shared functionality for test delegate
// implementations below.
class StreamDelegateBase : public SpdyStream::Delegate {
public:
explicit StreamDelegateBase(const base::WeakPtr<SpdyStream>& stream);
~StreamDelegateBase() override;
void OnHeadersSent() override;
void OnEarlyHintsReceived(const spdy::Http2HeaderBlock& headers) override;
void OnHeadersReceived(
const spdy::Http2HeaderBlock& response_headers,
const spdy::Http2HeaderBlock* pushed_request_headers) override;
void OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) override;
void OnDataSent() override;
void OnTrailers(const spdy::Http2HeaderBlock& trailers) override;
void OnClose(int status) override;
bool CanGreaseFrameType() const override;
NetLogSource source_dependency() const override;
// Waits for the stream to be closed and returns the status passed
// to OnClose().
int WaitForClose();
// Drains all data from the underlying read queue and returns it as
// a string.
std::string TakeReceivedData();
// Returns whether or not the stream is closed.
bool StreamIsClosed() const { return !stream_.get(); }
// Returns the stream's ID. If called when the stream is closed,
// returns the stream's ID when it was open.
spdy::SpdyStreamId stream_id() const { return stream_id_; }
// Returns 103 Early Hints response headers.
const std::vector<spdy::Http2HeaderBlock>& early_hints() const {
return early_hints_;
}
std::string GetResponseHeaderValue(const std::string& name) const;
bool send_headers_completed() const { return send_headers_completed_; }
// Returns the load timing info on the stream. This must be called after the
// stream is closed in order to get the up-to-date information.
const LoadTimingInfo& GetLoadTimingInfo();
protected:
const base::WeakPtr<SpdyStream>& stream() { return stream_; }
private:
base::WeakPtr<SpdyStream> stream_;
spdy::SpdyStreamId stream_id_;
TestCompletionCallback callback_;
bool send_headers_completed_;
std::vector<spdy::Http2HeaderBlock> early_hints_;
spdy::Http2HeaderBlock response_headers_;
SpdyReadQueue received_data_queue_;
LoadTimingInfo load_timing_info_;
};
// Test delegate that does nothing. Used to capture data about the
// stream, e.g. its id when it was open.
class StreamDelegateDoNothing : public StreamDelegateBase {
public:
explicit StreamDelegateDoNothing(const base::WeakPtr<SpdyStream>& stream);
~StreamDelegateDoNothing() override;
};
// Test delegate that consumes data as it arrives.
class StreamDelegateConsumeData : public StreamDelegateBase {
public:
explicit StreamDelegateConsumeData(const base::WeakPtr<SpdyStream>& stream);
~StreamDelegateConsumeData() override;
void OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) override;
};
// Test delegate that sends data immediately in OnHeadersReceived().
class StreamDelegateSendImmediate : public StreamDelegateBase {
public:
// |data| can be NULL.
StreamDelegateSendImmediate(const base::WeakPtr<SpdyStream>& stream,
base::StringPiece data);
~StreamDelegateSendImmediate() override;
void OnHeadersReceived(
const spdy::Http2HeaderBlock& response_headers,
const spdy::Http2HeaderBlock* pushed_request_headers) override;
private:
base::StringPiece data_;
};
// Test delegate that sends body data.
class StreamDelegateWithBody : public StreamDelegateBase {
public:
StreamDelegateWithBody(const base::WeakPtr<SpdyStream>& stream,
base::StringPiece data);
~StreamDelegateWithBody() override;
void OnHeadersSent() override;
private:
scoped_refptr<StringIOBuffer> buf_;
};
// Test delegate that closes stream in OnHeadersReceived().
class StreamDelegateCloseOnHeaders : public StreamDelegateBase {
public:
explicit StreamDelegateCloseOnHeaders(
const base::WeakPtr<SpdyStream>& stream);
~StreamDelegateCloseOnHeaders() override;
void OnHeadersReceived(
const spdy::Http2HeaderBlock& response_headers,
const spdy::Http2HeaderBlock* pushed_request_headers) override;
};
// Test delegate that sets a flag when EOF is detected.
class StreamDelegateDetectEOF : public StreamDelegateBase {
public:
explicit StreamDelegateDetectEOF(const base::WeakPtr<SpdyStream>& stream);
~StreamDelegateDetectEOF() override;
void OnDataReceived(std::unique_ptr<SpdyBuffer> buffer) override;
bool eof_detected() const { return eof_detected_; }
private:
bool eof_detected_ = false;
};
} // namespace test
} // namespace net
#endif // NET_SPDY_SPDY_STREAM_TEST_UTIL_H_
| chromium/chromium | net/spdy/spdy_stream_test_util.h | C | bsd-3-clause | 6,328 |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Lucene.Net.Documents;
using Kooboo.CMS.Search.Models;
using System.Collections.Specialized;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using Kooboo.Web.Mvc.Paging;
using Kooboo.CMS.Content.Models;
using System.Threading;
using Kooboo.CMS.Common.Runtime;
using Lucene.Net.Search.Highlight;
namespace Kooboo.CMS.Search
{
public class DocumentConverter
{
public DocumentConverter(Analyzer analyzer)
{
this.TitleFieldName = "_TitleIndex_";
this.BodyFieldName = "_BodyIndex_";
this.NativeTypeNameField = "_NativeType_";
this.Analyzer = analyzer;
}
public virtual string TitleFieldName { get; set; }
public virtual string BodyFieldName { get; set; }
public virtual string NativeTypeNameField { get; set; }
public virtual Analyzer Analyzer { get; set; }
protected virtual bool IsReservedField(string fieldName)
{
return fieldName.EqualsOrNullEmpty(TitleFieldName, StringComparison.OrdinalIgnoreCase)
|| fieldName.EqualsOrNullEmpty(BodyFieldName, StringComparison.OrdinalIgnoreCase)
|| fieldName.EqualsOrNullEmpty(NativeTypeNameField, StringComparison.OrdinalIgnoreCase);
}
public virtual Document ToDocument(object o)
{
Document doc = null;
var converter = ObjectConverters.GetConverter(o.GetType());
if (converter != null)
{
var indexObject = converter.GetIndexObject(o);
if (indexObject != null)
{
doc = new Document();
var key = converter.GetKeyField(o);
doc.Add(new Field(key.Key, key.Value.ToLower(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.Add(new Field(TitleFieldName, indexObject.Title, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field(BodyFieldName, indexObject.Body, Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new Field(NativeTypeNameField, indexObject.NativeType, Field.Store.YES, Field.Index.NO));
if (indexObject.StoreFields != null)
{
foreach (var item in indexObject.StoreFields.AllKeys)
{
if (!item.EqualsOrNullEmpty(key.Key, StringComparison.OrdinalIgnoreCase))
{
doc.Add(new Field(item, indexObject.StoreFields[item], Field.Store.YES, Field.Index.NO));
}
}
}
if (indexObject.SystemFields != null)
{
foreach (var item in indexObject.SystemFields.AllKeys)
{
if (!item.EqualsOrNullEmpty(key.Key, StringComparison.OrdinalIgnoreCase))
{
doc.Add(new Field(item, indexObject.SystemFields[item], Field.Store.YES, Field.Index.NOT_ANALYZED));
}
}
}
}
}
return doc;
}
public virtual ResultObject ToResultObject(Highlighter highlighter, Document doc)
{
var nativeTypeName = doc.GetField(NativeTypeNameField).StringValue;
var nativeType = Type.GetType(nativeTypeName);
var converter = ObjectConverters.GetConverter(nativeType);
if (converter != null)
{
ResultObject result = new ResultObject();
result.Title = doc.GetField(TitleFieldName).StringValue;
result.HighlightedTitle = highlighter.GetBestFragment(this.Analyzer, TitleFieldName, result.Title);
if (string.IsNullOrEmpty(result.HighlightedTitle))
{
result.HighlightedTitle = result.Title;
}
result.Body = doc.GetField(BodyFieldName).StringValue;
result.HighlightedBody = string.Join("...", highlighter.GetBestFragments(Analyzer, BodyFieldName, result.Body, 5));
if (string.IsNullOrEmpty(result.HighlightedBody))
{
result.HighlightedBody = result.Body;
}
NameValueCollection fields = new NameValueCollection();
foreach (Field field in doc.GetFields())
{
if (!IsReservedField(field.Name))
{
fields[field.Name] = field.StringValue;
}
}
result.NativeObject = converter.GetNativeObject(fields);
result.Url = converter.GetUrl(result.NativeObject);
return result;
}
return null;
}
public virtual Term GetKeyTerm(object o)
{
var converter = ObjectConverters.GetConverter(o.GetType());
if (converter != null)
{
var key = converter.GetKeyField(o);
return new Term(key.Key, key.Value.ToLower());
}
return null;
}
}
public class SearchService : ISearchService
{
public string IndexName { get; private set; }
private string indexDir = null;
public SearchService(Repository repository)
{
this.IndexName = repository.Name;
indexDir = Path.Combine(SearchDir.GetBasePhysicalPath(repository), "Index");
Analyzer = new StandardAnalyzer(global::Lucene.Net.Util.Version.LUCENE_30);
Converter = new DocumentConverter(Analyzer);
}
public virtual Analyzer Analyzer { get; set; }
public virtual DocumentConverter Converter { get; set; }
#region Build index
public virtual void Add<T>(T o)
{
BatchAdd(new[] { o });
}
public virtual void Update<T>(T o)
{
BatchUpdate(new[] { o });
}
public virtual void Delete<T>(T o)
{
BatchDelete(new[] { o });
}
private IndexWriter CreateIndexWriter()
{
var writer = new IndexWriter(FSDirectory.Open(new DirectoryInfo(indexDir)), Analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
return writer;
}
public virtual void BatchAdd<T>(IEnumerable<T> list)
{
var writer = CreateIndexWriter();
try
{
foreach (var item in list)
{
var doc = Converter.ToDocument(item);
if (doc != null)
{
writer.AddDocument(doc);
}
LogLastAction(item, ContentAction.Add);
}
}
finally
{
writer.Optimize();
writer.Close();
}
}
public virtual void BatchUpdate<T>(IEnumerable<T> list)
{
var writer = CreateIndexWriter();
try
{
foreach (var item in list)
{
var doc = Converter.ToDocument(item);
var keyTerm = Converter.GetKeyTerm(item);
if (doc != null && keyTerm != null)
{
writer.UpdateDocument(keyTerm, doc);
}
LogLastAction(item, ContentAction.Update);
}
}
finally
{
writer.Optimize();
writer.Close();
}
}
public virtual void BatchDelete<T>(IEnumerable<T> list)
{
var writer = CreateIndexWriter();
try
{
var keyTerms = list.Select(it => Converter.GetKeyTerm(it)).Where(it => it != null).ToArray();
writer.DeleteDocuments(keyTerms);
foreach (var item in list)
{
LogLastAction(item, ContentAction.Delete);
}
}
finally
{
writer.Optimize();
writer.Close();
}
}
public void BatchDelete(string folderName)
{
var writer = CreateIndexWriter();
try
{
writer.DeleteDocuments(new Lucene.Net.Index.Term("FolderName", folderName));
}
finally
{
writer.Optimize();
writer.Close();
}
}
#endregion
protected virtual void LogLastAction(object o, ContentAction action)
{
Thread thread = new Thread(() =>
{
try
{
if (o is TextContent)
{
var textContent = (TextContent)o;
var repository = textContent.GetRepository();
var folderName = textContent.FolderName;
var contentSummary = textContent.GetSummary();
LastAction lastAction = new LastAction()
{
Repository = repository,
FolderName = folderName,
ContentSummary = contentSummary,
Action = action,
UtcActionDate = DateTime.UtcNow
};
EngineContext.Current.Resolve<Kooboo.CMS.Search.Persistence.ILastActionProvider>().Add(lastAction);
}
}
catch (Exception e)
{
Kooboo.HealthMonitoring.Log.LogException(e);
}
});
thread.Start();
}
public virtual PagedList<Models.ResultObject> Search(string key, int pageIndex, int pageSize, params string[] folders)
{
var indexDirectory = FSDirectory.Open(new DirectoryInfo(indexDir));
if (!IndexReader.IndexExists(indexDirectory) || string.IsNullOrEmpty(key) && (folders == null || folders.Length == 0))
{
return new PagedList<ResultObject>(new ResultObject[0], pageIndex, pageSize, 0);
}
var query = new BooleanQuery();
key = QueryParser.Escape(key.Trim().ToLower());
if (string.IsNullOrEmpty(key))
{
key = "*:*";
}
QueryParser titleParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, Converter.TitleFieldName, this.Analyzer);
var titleQuery = titleParser.Parse(key);
titleQuery.Boost = 2;
query.Add(new BooleanClause(titleQuery, Occur.SHOULD));
QueryParser bodyParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_30, Converter.BodyFieldName, this.Analyzer);
var bodyQuery = bodyParser.Parse(key);
bodyQuery.Boost = 1;
query.Add(new BooleanClause(bodyQuery, Occur.SHOULD));
QueryWrapperFilter filter = null;
if (folders != null && folders.Length > 0)
{
var folderQuery = new BooleanQuery();
//QueryParser folderParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "FolderName", this.Analyzer);
foreach (var folder in folders)
{
var termQuery = new TermQuery(new Term("FolderName", folder));
termQuery.Boost = 3;
folderQuery.Add(new BooleanClause(termQuery, Occur.SHOULD));
}
filter = new QueryWrapperFilter(folderQuery);
}
var searcher = new IndexSearcher(indexDirectory, true);
var collecltor = TopScoreDocCollector.Create(searcher.MaxDoc, false);
if (filter == null)
{
searcher.Search(query, collecltor);
}
else
{
searcher.Search(query, filter, collecltor);
}
var lighter =
new Highlighter(new SimpleHTMLFormatter("<strong class='highlight'>", "</strong>"), new Lucene.Net.Search.Highlight.QueryScorer((Query)query));
var startIndex = (pageIndex - 1) * pageSize;
List<ResultObject> results = new List<ResultObject>();
foreach (var doc in collecltor.TopDocs(startIndex, pageSize).ScoreDocs)
{
var document = searcher.Doc(doc.Doc);
ResultObject result = Converter.ToResultObject(lighter, document);
if (result != null)
{
results.Add(result);
}
}
return new PagedList<ResultObject>(results, pageIndex, pageSize, collecltor.TotalHits);
}
}
}
| lingxyd/CMS | Kooboo.CMS/Kooboo.CMS.Search/SearchService.cs | C# | bsd-3-clause | 13,623 |
// 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.
#ifndef ASH_APP_LIST_MODEL_APP_LIST_MODEL_OBSERVER_H_
#define ASH_APP_LIST_MODEL_APP_LIST_MODEL_OBSERVER_H_
#include "ash/app_list/model/app_list_model_export.h"
#include "base/observer_list_types.h"
namespace ash {
class AppListItem;
enum class AppListState;
class APP_LIST_MODEL_EXPORT AppListModelObserver
: public base::CheckedObserver {
public:
// Triggered after AppListModel's status has changed.
virtual void OnAppListModelStatusChanged() {}
// Triggered after |item| has been added to the model.
virtual void OnAppListItemAdded(AppListItem* item) {}
// Triggered just before an item is deleted from the model.
virtual void OnAppListItemWillBeDeleted(AppListItem* item) {}
// Triggered after |item| has moved, changed folders, or changed properties.
virtual void OnAppListItemUpdated(AppListItem* item) {}
// Triggered when the custom launcher page enabled state is changed.
virtual void OnCustomLauncherPageEnabledStateChanged(bool enabled) {}
protected:
~AppListModelObserver() override;
};
} // namespace ash
#endif // ASH_APP_LIST_MODEL_APP_LIST_MODEL_OBSERVER_H_
| ric2b/Vivaldi-browser | chromium/ash/app_list/model/app_list_model_observer.h | C | bsd-3-clause | 1,287 |
/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <af/dim4.hpp>
#include <af/defines.h>
#include <ArrayInfo.hpp>
#include <Array.hpp>
#include <morph.hpp>
#include <algorithm>
using af::dim4;
namespace cpu
{
static inline unsigned getIdx(const dim4 &strides,
int i, int j = 0, int k = 0, int l = 0)
{
return (l * strides[3] +
k * strides[2] +
j * strides[1] +
i * strides[0]);
}
template<typename T, bool isDilation>
Array<T> morph(const Array<T> &in, const Array<T> &mask)
{
const dim4 dims = in.dims();
const dim4 window = mask.dims();
const dim_t R0 = window[0]/2;
const dim_t R1 = window[1]/2;
const dim4 istrides = in.strides();
const dim4 fstrides = mask.strides();
Array<T> out = createEmptyArray<T>(dims);
const dim4 ostrides = out.strides();
T* outData = out.get();
const T* inData = in.get();
const T* filter = mask.get();
for(dim_t b3=0; b3<dims[3]; ++b3) {
for(dim_t b2=0; b2<dims[2]; ++b2) {
// either channels or batch is handled by outer most loop
for(dim_t j=0; j<dims[1]; ++j) {
// j steps along 2nd dimension
for(dim_t i=0; i<dims[0]; ++i) {
// i steps along 1st dimension
T filterResult = inData[ getIdx(istrides, i, j) ];
// wj,wi steps along 2nd & 1st dimensions of filter window respectively
for(dim_t wj=0; wj<window[1]; wj++) {
for(dim_t wi=0; wi<window[0]; wi++) {
dim_t offj = j+wj-R1;
dim_t offi = i+wi-R0;
T maskValue = filter[ getIdx(fstrides, wi, wj) ];
if ((maskValue > (T)0) && offi>=0 && offj>=0 && offi<dims[0] && offj<dims[1]) {
T inValue = inData[ getIdx(istrides, offi, offj) ];
if (isDilation)
filterResult = std::max(filterResult, inValue);
else
filterResult = std::min(filterResult, inValue);
}
} // window 1st dimension loop ends here
} // filter window loop ends here
outData[ getIdx(ostrides, i, j) ] = filterResult;
} //1st dimension loop ends here
} // 2nd dimension loop ends here
// next iteration will be next batch if any
outData += ostrides[2];
inData += istrides[2];
}
}
return out;
}
template<typename T, bool isDilation>
Array<T> morph3d(const Array<T> &in, const Array<T> &mask)
{
const dim4 dims = in.dims();
const dim4 window = mask.dims();
const dim_t R0 = window[0]/2;
const dim_t R1 = window[1]/2;
const dim_t R2 = window[2]/2;
const dim4 istrides = in.strides();
const dim4 fstrides = mask.strides();
const dim_t bCount = dims[3];
Array<T> out = createEmptyArray<T>(dims);
const dim4 ostrides = out.strides();
T* outData = out.get();
const T* inData = in.get();
const T* filter = mask.get();
for(dim_t batchId=0; batchId<bCount; ++batchId) {
// either channels or batch is handled by outer most loop
for(dim_t k=0; k<dims[2]; ++k) {
// k steps along 3rd dimension
for(dim_t j=0; j<dims[1]; ++j) {
// j steps along 2nd dimension
for(dim_t i=0; i<dims[0]; ++i) {
// i steps along 1st dimension
T filterResult = inData[ getIdx(istrides, i, j, k) ];
// wk, wj,wi steps along 2nd & 1st dimensions of filter window respectively
for(dim_t wk=0; wk<window[2]; wk++) {
for(dim_t wj=0; wj<window[1]; wj++) {
for(dim_t wi=0; wi<window[0]; wi++) {
dim_t offk = k+wk-R2;
dim_t offj = j+wj-R1;
dim_t offi = i+wi-R0;
T maskValue = filter[ getIdx(fstrides, wi, wj, wk) ];
if ((maskValue > (T)0) && offi>=0 && offj>=0 && offk>=0 &&
offi<dims[0] && offj<dims[1] && offk<dims[2]) {
T inValue = inData[ getIdx(istrides, offi, offj, offk) ];
if (isDilation)
filterResult = std::max(filterResult, inValue);
else
filterResult = std::min(filterResult, inValue);
}
} // window 1st dimension loop ends here
} // window 1st dimension loop ends here
}// filter window loop ends here
outData[ getIdx(ostrides, i, j, k) ] = filterResult;
} //1st dimension loop ends here
} // 2nd dimension loop ends here
} // 3rd dimension loop ends here
// next iteration will be next batch if any
outData += ostrides[3];
inData += istrides[3];
}
return out;
}
#define INSTANTIATE(T)\
template Array<T> morph <T, true >(const Array<T> &in, const Array<T> &mask);\
template Array<T> morph <T, false>(const Array<T> &in, const Array<T> &mask);\
template Array<T> morph3d<T, true >(const Array<T> &in, const Array<T> &mask);\
template Array<T> morph3d<T, false>(const Array<T> &in, const Array<T> &mask);
INSTANTIATE(float )
INSTANTIATE(double)
INSTANTIATE(char )
INSTANTIATE(int )
INSTANTIATE(uint )
INSTANTIATE(uchar )
}
| asifmadnan/arrayfire | src/backend/cpu/morph.cpp | C++ | bsd-3-clause | 6,259 |
// 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 "mojo/runner/android/android_handler.h"
#include <stddef.h>
#include <utility>
#include "base/android/context_utils.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/scoped_native_library.h"
#include "jni/AndroidHandler_jni.h"
#include "mojo/common/data_pipe_utils.h"
#include "mojo/public/c/system/main.h"
#include "mojo/runner/android/run_android_application_function.h"
#include "mojo/runner/host/native_application_support.h"
#include "mojo/shell/public/cpp/application_impl.h"
#include "mojo/util/filename_util.h"
#include "url/gurl.h"
using base::android::AttachCurrentThread;
using base::android::ScopedJavaLocalRef;
using base::android::ConvertJavaStringToUTF8;
using base::android::ConvertUTF8ToJavaString;
using base::android::GetApplicationContext;
namespace mojo {
namespace runner {
namespace {
// This function loads the application library, sets the application context and
// thunks and calls into the application MojoMain. To ensure that the thunks are
// set correctly we keep it in the Mojo shell .so and pass the function pointer
// to the helper libbootstrap.so.
void RunAndroidApplication(JNIEnv* env,
jobject j_context,
const base::FilePath& app_path,
jint j_handle) {
InterfaceRequest<Application> application_request =
MakeRequest<Application>(MakeScopedHandle(MessagePipeHandle(j_handle)));
// Load the library, so that we can set the application context there if
// needed.
// TODO(vtl): We'd use a ScopedNativeLibrary, but it doesn't have .get()!
base::NativeLibrary app_library = LoadNativeApplication(app_path);
if (!app_library)
return;
// Set the application context if needed. Most applications will need to
// access the Android ApplicationContext in which they are run. If the
// application library exports the InitApplicationContext function, we will
// set it there.
const char* init_application_context_name = "InitApplicationContext";
typedef void (*InitApplicationContextFn)(
const base::android::JavaRef<jobject>&);
InitApplicationContextFn init_application_context =
reinterpret_cast<InitApplicationContextFn>(
base::GetFunctionPointerFromNativeLibrary(
app_library, init_application_context_name));
if (init_application_context) {
base::android::ScopedJavaLocalRef<jobject> scoped_context(env, j_context);
init_application_context(scoped_context);
}
// Run the application.
RunNativeApplication(app_library, std::move(application_request));
// TODO(vtl): See note about unloading and thread-local destructors above
// declaration of |LoadNativeApplication()|.
base::UnloadNativeLibrary(app_library);
}
// Returns true if |url| denotes a cached app. If true |app_dir| is set to the
// path of the directory for the app and |path_to_mojo| the path of the app's
// .mojo file.
bool IsCachedApp(JNIEnv* env,
const GURL& url,
base::FilePath* app_dir,
base::FilePath* path_to_mojo) {
ScopedJavaLocalRef<jstring> j_cached_apps_dir =
Java_AndroidHandler_getCachedAppsDir(env, GetApplicationContext());
const base::FilePath cached_apps_fp(
ConvertJavaStringToUTF8(env, j_cached_apps_dir.obj()));
const std::string cached_apps(util::FilePathToFileURL(cached_apps_fp).spec());
const std::string response_url(GURL(url).spec());
if (response_url.size() <= cached_apps.size() ||
cached_apps.compare(0u, cached_apps.size(), response_url, 0u,
cached_apps.size()) != 0) {
return false;
}
const std::string mojo_suffix(".mojo");
// app_rel_path is either something like html_viewer/html_viewer.mojo, or
// html_viewer.mojo, depending upon whether the app has a package.
const std::string app_rel_path(response_url.substr(cached_apps.size() + 1));
const size_t slash_index = app_rel_path.find('/');
if (slash_index != std::string::npos) {
const std::string tail =
app_rel_path.substr(slash_index + 1, std::string::npos);
const std::string head = app_rel_path.substr(0, slash_index);
if (head.find('/') != std::string::npos ||
tail.size() <= mojo_suffix.size() ||
tail.compare(tail.size() - mojo_suffix.size(), tail.size(),
mojo_suffix) != 0) {
return false;
}
*app_dir = cached_apps_fp.Append(head);
*path_to_mojo = app_dir->Append(tail);
return true;
}
if (app_rel_path.find('/') != std::string::npos ||
app_rel_path.size() <= mojo_suffix.size() ||
app_rel_path.compare(app_rel_path.size() - mojo_suffix.size(),
mojo_suffix.size(), mojo_suffix) != 0) {
return false;
}
*app_dir = cached_apps_fp.Append(
app_rel_path.substr(0, app_rel_path.size() - mojo_suffix.size()));
*path_to_mojo = cached_apps_fp.Append(app_rel_path);
return true;
}
} // namespace
AndroidHandler::AndroidHandler() : content_handler_factory_(this) {
}
AndroidHandler::~AndroidHandler() {
}
void AndroidHandler::RunApplication(
InterfaceRequest<Application> application_request,
URLResponsePtr response) {
JNIEnv* env = AttachCurrentThread();
RunAndroidApplicationFn run_android_application_fn = &RunAndroidApplication;
if (!response->url.is_null()) {
base::FilePath internal_app_path;
base::FilePath path_to_mojo;
if (IsCachedApp(env, GURL(response->url), &internal_app_path,
&path_to_mojo)) {
ScopedJavaLocalRef<jstring> j_internal_app_path(
ConvertUTF8ToJavaString(env, internal_app_path.value()));
ScopedJavaLocalRef<jstring> j_path_to_mojo(
ConvertUTF8ToJavaString(env, path_to_mojo.value()));
Java_AndroidHandler_bootstrapCachedApp(
env, GetApplicationContext(), j_path_to_mojo.obj(),
j_internal_app_path.obj(),
application_request.PassMessagePipe().release().value(),
reinterpret_cast<jlong>(run_android_application_fn));
return;
}
}
ScopedJavaLocalRef<jstring> j_archive_path =
Java_AndroidHandler_getNewTempArchivePath(env, GetApplicationContext());
base::FilePath archive_path(
ConvertJavaStringToUTF8(env, j_archive_path.obj()));
common::BlockingCopyToFile(std::move(response->body), archive_path);
Java_AndroidHandler_bootstrap(
env, GetApplicationContext(), j_archive_path.obj(),
application_request.PassMessagePipe().release().value(),
reinterpret_cast<jlong>(run_android_application_fn));
}
void AndroidHandler::Initialize(ApplicationImpl* app) {
}
bool AndroidHandler::ConfigureIncomingConnection(
ApplicationConnection* connection) {
connection->AddService(&content_handler_factory_);
return true;
}
bool RegisterAndroidHandlerJni(JNIEnv* env) {
return RegisterNativesImpl(env);
}
} // namespace runner
} // namespace mojo
| js0701/chromium-crosswalk | mojo/runner/android/android_handler.cc | C++ | bsd-3-clause | 7,160 |
/*
* Copyright (c) 2016, 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:
*
* 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 Salesforce.com 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.
*/
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.system.SystemException;
/**
* Make a map of datapoints that aggregates points from originalDatapoints and baseDatapoints, if for some timestamp in originalDatapoints, there is
* no point value in the baseDatapoints corresponding to that timestamp, the aggregation result is subtraction of point value in originalDatapoints
* and ZERO.
*
* @author Ruofan Zhang ([email protected])
*/
public class DiffValueZipper implements ValueZipper {
//~ Methods **************************************************************************************************************************************
@Override
public Double zip(Double originalDp, Double baseDp) {
try {
Double original = (originalDp == null) ? 0.0 : originalDp;
Double base = (baseDp == null) ? 0.0 : baseDp;
return (original - base);
} catch (Exception e) {
throw new SystemException("Fail to parse the double value of original Datapoint or base Datapoint!", e);
}
}
@Override
public String name() {
return TransformFactory.Function.DIFF_V.name();
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
| SalesforceEng/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/DiffValueZipper.java | Java | bsd-3-clause | 2,863 |
<!--
/*
** Copyright (c) 2016 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are 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 Materials.
**
** THE MATERIALS ARE 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
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebGL BlitFramebuffer Tests</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../js/js-test-pre.js"></script>
<script src="../../js/webgl-test-utils.js"></script>
<script src="../../js/glsl-conformance-test.js"></script>
</head>
<body>
<canvas id="canvas" width="8" height="8"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
var wtu = WebGLTestUtils;
description("This test verifies the functionality of blitFramebuffer with multiple draw buffers (srgb image and linear image).");
var gl = wtu.create3DContext("canvas", undefined, 2);
var linearMask = 1;
var srgbMask = 2;
if (!gl) {
testFailed("WebGL context does not exist");
} else {
testPassed("WebGL context exists");
var filters = [gl.LINEAR, gl.NEAREST];
var drawbuffersFormats = [linearMask, srgbMask, linearMask | srgbMask];
for (var ii = 0; ii < filters.length; ++ii) {
for (var jj = 0; jj < drawbuffersFormats.length; ++jj) {
blitframebuffer_srgb_and_linear_drawbuffers(gl.SRGB8_ALPHA8, drawbuffersFormats[jj], filters[ii]);
blitframebuffer_srgb_and_linear_drawbuffers(gl.RGBA8, drawbuffersFormats[jj], filters[ii]);
}
}
}
function blitframebuffer_srgb_and_linear_drawbuffers(readbufferFormat, drawbuffersFormatMask, filter) {
debug("");
debug("The filter is: " + wtu.glEnumToString(gl, filter));
debug("Read buffer format is: " + wtu.glEnumToString(gl, readbufferFormat));
var drawbuffersFormat = "\0";
if (drawbuffersFormatMask & linearMask) {
drawbuffersFormat += " linear ";
}
if (drawbuffersFormatMask & srgbMask) {
drawbuffersFormat += " srgb ";
}
debug("The test have multiple draw buffers, the images are: " + drawbuffersFormat);
var tex_srgb0 = gl.createTexture();
var tex_srgb1 = gl.createTexture();
var tex_linear0 = gl.createTexture();
var tex_linear1 = gl.createTexture();
var tex_read = gl.createTexture();
var fbo_read = gl.createFramebuffer();
var fbo_draw = gl.createFramebuffer();
// Create read buffer and feed data to the read buffer
var size = 8;
var data = new Uint8Array(size * size * 4);
var color = [250, 100, 15, 255];
for (var ii = 0; ii < size * size * 4; ii += 4) {
for (var jj = 0; jj < 4; ++jj) {
data[ii + jj] = color[jj];
}
}
gl.bindTexture(gl.TEXTURE_2D, tex_read);
gl.texImage2D(gl.TEXTURE_2D, 0, readbufferFormat, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_read);
gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex_read, 0);
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "setup read framebuffer should succeed");
// Create multiple textures. Attach them as fbo's draw buffers.
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo_draw);
var drawbuffers = [gl.NONE, gl.NONE, gl.NONE, gl.NONE];
if (drawbuffersFormatMask & srgbMask) {
gl.bindTexture(gl.TEXTURE_2D, tex_srgb0);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.SRGB8_ALPHA8, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex_srgb0, 0);
gl.bindTexture(gl.TEXTURE_2D, tex_srgb1);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.SRGB8_ALPHA8, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT2, gl.TEXTURE_2D, tex_srgb1, 0);
drawbuffers[0] = gl.COLOR_ATTACHMENT0;
drawbuffers[2] = gl.COLOR_ATTACHMENT2;
}
if (drawbuffersFormatMask & linearMask) {
gl.bindTexture(gl.TEXTURE_2D, tex_linear0);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.TEXTURE_2D, tex_linear0, 0);
gl.bindTexture(gl.TEXTURE_2D, tex_linear1);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT3, gl.TEXTURE_2D, tex_linear1, 0);
drawbuffers[1] = gl.COLOR_ATTACHMENT1;
drawbuffers[3] = gl.COLOR_ATTACHMENT3;
}
gl.drawBuffers(drawbuffers);
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "setup draw framebuffer should succeed");
if (gl.checkFramebufferStatus(gl.DRAW_FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE ||
gl.checkFramebufferStatus(gl.READ_FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) {
testFailed("Framebuffer incomplete when setup draw framebuffer.");
return;
}
// Blit to multiple draw buffers with srgb images and linear images
var dstSize = size - 1;
gl.blitFramebuffer(0, 0, size, size, 0, 0, dstSize, dstSize, gl.COLOR_BUFFER_BIT, filter);
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "blitframebuffer should succeed");
// Read pixels from srgb images and linear images
var srgbPixels0 = new Uint8Array(dstSize * dstSize * 4);
var srgbPixels1 = new Uint8Array(dstSize * dstSize * 4);
var linearPixels0 = new Uint8Array(dstSize * dstSize * 4);
var linearPixels1 = new Uint8Array(dstSize * dstSize * 4);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo_draw);
if (drawbuffersFormatMask & srgbMask) {
gl.readBuffer(gl.COLOR_ATTACHMENT0);
gl.readPixels(0, 0, dstSize, dstSize, gl.RGBA, gl.UNSIGNED_BYTE, srgbPixels0);
gl.readBuffer(gl.COLOR_ATTACHMENT2);
gl.readPixels(0, 0, dstSize, dstSize, gl.RGBA, gl.UNSIGNED_BYTE, srgbPixels1);
}
if (drawbuffersFormatMask & linearMask) {
gl.readBuffer(gl.COLOR_ATTACHMENT1);
gl.readPixels(0, 0, dstSize, dstSize, gl.RGBA, gl.UNSIGNED_BYTE, linearPixels0);
gl.readBuffer(gl.COLOR_ATTACHMENT3);
gl.readPixels(0, 0, dstSize, dstSize, gl.RGBA, gl.UNSIGNED_BYTE, linearPixels1);
}
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "readpixels should succeed");
// Compare
var expectedSRGBColor = (readbufferFormat == gl.SRGB8_ALPHA8) ? color : wtu.linearToSRGB(color);
var expectedLinearColor = (readbufferFormat == gl.SRGB8_ALPHA8) ? wtu.sRGBToLinear(color) : color;
var failed = false;
for (var ii = 0; ii < dstSize; ++ii) {
for (var jj = 0; jj < dstSize; ++jj) {
var index = (ii * dstSize + jj) * 4;
if (drawbuffersFormatMask & srgbMask) {
var srgbColor0 = [srgbPixels0[index], srgbPixels0[index + 1], srgbPixels0[index + 2], srgbPixels0[index + 3]];
if (checkPixel(srgbColor0, expectedSRGBColor) == false) {
failed = true;
debug("Pixels comparison failed for the 1st sRGB image. Pixel at [" + jj + ", " + ii + "] should be (" + expectedSRGBColor + "), but the actual color is (" + srgbColor0 + ")");
}
var srgbColor1 = [srgbPixels1[index], srgbPixels1[index + 1], srgbPixels1[index + 2], srgbPixels1[index + 3]];
if (checkPixel(srgbColor1, expectedSRGBColor) == false) {
failed = true;
debug("Pixels comparison failed for the 2nd sRGB image. Pixel at [" + jj + ", " + ii + "] should be (" + expectedSRGBColor + "), but the actual color is (" + srgbColor1 + ")");
}
}
if (drawbuffersFormatMask & linearMask) {
var linearColor0 = [linearPixels0[index], linearPixels0[index + 1], linearPixels0[index + 2], linearPixels0[index + 3]];
if (checkPixel(linearColor0, expectedLinearColor) == false) {
failed = true;
debug("Pixel comparison failed for the 1st linear image. Pixel at [" + jj + ", " + ii + "] should be (" + color + "), but the actual color is (" + linearColor0 + ")");
}
var linearColor1 = [linearPixels1[index], linearPixels1[index + 1], linearPixels1[index + 2], linearPixels1[index + 3]];
if (checkPixel(linearColor1, expectedLinearColor) == false) {
failed = true;
debug("Pixel comparison failed for the 2nd linear image. Pixel at [" + jj + ", " + ii + "] should be (" + color + "), but the actual color is (" + linearColor1 + ")");
}
}
}
}
if (failed == false) {
testPassed("All pixels comparision passed!");
}
// deinit
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
gl.deleteTexture(tex_srgb0);
gl.deleteTexture(tex_linear0);
gl.deleteTexture(tex_srgb1);
gl.deleteTexture(tex_linear1);
gl.deleteTexture(tex_read);
gl.deleteFramebuffer(fbo_read);
gl.deleteFramebuffer(fbo_draw);
}
function checkPixel(color, expectedColor) {
var tolerance = 3;
return (Math.abs(color[0] - expectedColor[0]) <= tolerance &&
Math.abs(color[1] - expectedColor[1]) <= tolerance &&
Math.abs(color[2] - expectedColor[2]) <= tolerance &&
Math.abs(color[3] - expectedColor[3]) <= tolerance);
}
var successfullyParsed = true;
</script>
<script src="../../js/js-test-post.js"></script>
</body>
</html>
| endlessm/chromium-browser | third_party/webgl/src/conformance-suites/2.0.0/conformance2/rendering/blitframebuffer-srgb-and-linear-drawbuffers.html | HTML | bsd-3-clause | 10,502 |
package scala.scalajs.js.typedarray
import scala.scalajs.js
/** <span class="badge badge-ecma6" style="float: right;">ECMAScript 6</span>
* A [[TypedArray]] of unsigned 8-bit integers whose values are clamped to
* their max/min rather than wrapped around if they overflow.
*/
class Uint8ClampedArray private extends TypedArray[Int, Uint8ClampedArray] {
/** Constructs a Uint8ClampedArray with the given length. Initialized to all 0 */
def this(length: Int) = this()
/** Creates a new Uint8ClampedArray with the same elements than the given TypedArray
*
* The elements are converted before being stored in the new Int8Array.
*/
def this(typedArray: TypedArray[_, _]) = this()
/** Creates a new Uint8ClampedArray with the elements in the given array */
def this(array: js.Array[_]) = this()
/** Creates a Uint8ClampedArray view on the given ArrayBuffer */
def this(buffer: ArrayBuffer, byteOffset: Int = 0, length: Int = ???) = this()
}
/** <span class="badge badge-ecma6" style="float: right;">ECMAScript 6</span>
* [[Uint8ClampedArray]] companion
*/
object Uint8ClampedArray extends TypedArrayStatic
| jmnarloch/scala-js | library/src/main/scala/scala/scalajs/js/typedarray/Uint8ClampedArray.scala | Scala | bsd-3-clause | 1,142 |
// Copyright 2018 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.
#ifndef ASH_COMPONENTS_ARC_APPFUSE_ARC_APPFUSE_BRIDGE_H_
#define ASH_COMPONENTS_ARC_APPFUSE_ARC_APPFUSE_BRIDGE_H_
#include <stdint.h>
#include "ash/components/arc/mojom/appfuse.mojom.h"
#include "components/keyed_service/core/keyed_service.h"
namespace content {
class BrowserContext;
} // namespace content
namespace arc {
class ArcBridgeService;
// This class handles Appfuse mount/unmount requests from the ARC container.
class ArcAppfuseBridge : public KeyedService, public mojom::AppfuseHost {
public:
// Returns singleton instance for the given BrowserContext,
// or nullptr if the browser |context| is not allowed to use ARC.
static ArcAppfuseBridge* GetForBrowserContext(
content::BrowserContext* context);
static ArcAppfuseBridge* GetForBrowserContextForTesting(
content::BrowserContext* context);
ArcAppfuseBridge(content::BrowserContext* context,
ArcBridgeService* bridge_service);
ArcAppfuseBridge(const ArcAppfuseBridge&) = delete;
ArcAppfuseBridge& operator=(const ArcAppfuseBridge&) = delete;
~ArcAppfuseBridge() override;
// mojom::AppfuseHost overrides:
void Mount(uint32_t uid, int32_t mount_id, MountCallback callback) override;
void Unmount(uint32_t uid,
int32_t mount_id,
UnmountCallback callback) override;
void OpenFile(uint32_t uid,
int32_t mount_id,
int32_t file_id,
int32_t flags,
OpenFileCallback callback) override;
private:
ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager.
};
} // namespace arc
#endif // ASH_COMPONENTS_ARC_APPFUSE_ARC_APPFUSE_BRIDGE_H_
| ric2b/Vivaldi-browser | chromium/ash/components/arc/appfuse/arc_appfuse_bridge.h | C | bsd-3-clause | 1,846 |
<!DOCTYPE html>
<!--
Copyright (c) 2012 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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.
Authors:
Yan,Changci <[email protected]>
Xie,Yunxiao <[email protected]>
-->
<meta charset="utf-8">
<title>WebStorage Test: window_localStorage_setItem_null</title>
<link rel="author" title="Intel" href="http://www.intel.com" >
<link rel="help" href="http://www.w3.org/TR/2011/CR-webstorage-20111208/#dom-localStorage-setItem" >
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<div id="log"></div>
<script>
test(function () {
assert_true("localStorage" in window);
var store=window.localStorage;
store.setItem("test", null);
assert_equals(store.getItem("test"), "null");
}, "Check if the localStorage.setItem value is null");
</script>
| haoxli/web-testing-service | wts/tests/webstorage/window_localStorage_setItem_null.html | HTML | bsd-3-clause | 2,192 |
<?php
namespace Drupal\Tests\Core\Access;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Access\RouteProcessorCsrf;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\Core\Access\RouteProcessorCsrf
* @group Access
*/
class RouteProcessorCsrfTest extends UnitTestCase {
/**
* The mock CSRF token generator.
*
* @var \Drupal\Core\Access\CsrfTokenGenerator|\PHPUnit_Framework_MockObject_MockObject
*/
protected $csrfToken;
/**
* The route processor.
*
* @var \Drupal\Core\Access\RouteProcessorCsrf
*/
protected $processor;
protected function setUp() {
$this->csrfToken = $this->getMockBuilder('Drupal\Core\Access\CsrfTokenGenerator')
->disableOriginalConstructor()
->getMock();
$this->processor = new RouteProcessorCsrf($this->csrfToken);
}
/**
* Tests the processOutbound() method with no _csrf_token route requirement.
*/
public function testProcessOutboundNoRequirement() {
$this->csrfToken->expects($this->never())
->method('get');
$route = new Route('/test-path');
$parameters = [];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// No parameters should be added to the parameters array.
$this->assertEmpty($parameters);
// Cacheability of routes without a _csrf_token route requirement is
// unaffected.
$this->assertEquals((new BubbleableMetadata()), $bubbleable_metadata);
}
/**
* Tests the processOutbound() method with a _csrf_token route requirement.
*/
public function testProcessOutbound() {
$route = new Route('/test-path', [], ['_csrf_token' => 'TRUE']);
$parameters = [];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// 'token' should be added to the parameters array.
$this->assertArrayHasKey('token', $parameters);
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = 'test-path';
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];
$this->assertSame($parameters['token'], $placeholder);
$this->assertEquals((new BubbleableMetadata())->setAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]), $bubbleable_metadata);
}
/**
* Tests the processOutbound() method with a dynamic path and one replacement.
*/
public function testProcessOutboundDynamicOne() {
$route = new Route('/test-path/{slug}', [], ['_csrf_token' => 'TRUE']);
$parameters = ['slug' => 100];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = 'test-path/100';
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];
$this->assertEquals((new BubbleableMetadata())->setAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]), $bubbleable_metadata);
}
/**
* Tests the processOutbound() method with two parameter replacements.
*/
public function testProcessOutboundDynamicTwo() {
$route = new Route('{slug_1}/test-path/{slug_2}', [], ['_csrf_token' => 'TRUE']);
$parameters = ['slug_1' => 100, 'slug_2' => 'test'];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = '100/test-path/test';
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];
$this->assertEquals((new BubbleableMetadata())->setAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]), $bubbleable_metadata);
}
}
| JeramyK/training | web/core/tests/Drupal/Tests/Core/Access/RouteProcessorCsrfTest.php | PHP | gpl-2.0 | 4,338 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.tomcat.util.net;
import java.io.EOFException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
*
* Thread safe non blocking selector pool
* @version 1.0
* @since 6.0
*/
public class NioSelectorPool {
public NioSelectorPool() {
}
private static final Log log = LogFactory.getLog(NioSelectorPool.class);
protected static final boolean SHARED =
Boolean.valueOf(System.getProperty("org.apache.tomcat.util.net.NioSelectorShared", "true")).booleanValue();
protected NioBlockingSelector blockingSelector;
protected volatile Selector SHARED_SELECTOR;
protected int maxSelectors = 200;
protected long sharedSelectorTimeout = 30000;
protected int maxSpareSelectors = -1;
protected boolean enabled = true;
protected AtomicInteger active = new AtomicInteger(0);
protected AtomicInteger spare = new AtomicInteger(0);
protected ConcurrentLinkedQueue<Selector> selectors =
new ConcurrentLinkedQueue<>();
protected Selector getSharedSelector() throws IOException {
if (SHARED && SHARED_SELECTOR == null) {
synchronized ( NioSelectorPool.class ) {
if ( SHARED_SELECTOR == null ) {
synchronized (Selector.class) {
// Selector.open() isn't thread safe
// http://bugs.sun.com/view_bug.do?bug_id=6427854
// Affects 1.6.0_29, fixed in 1.7.0_01
SHARED_SELECTOR = Selector.open();
}
log.info("Using a shared selector for servlet write/read");
}
}
}
return SHARED_SELECTOR;
}
@SuppressWarnings("resource") // s is closed in put()
public Selector get() throws IOException{
if ( SHARED ) {
return getSharedSelector();
}
if ( (!enabled) || active.incrementAndGet() >= maxSelectors ) {
if ( enabled ) active.decrementAndGet();
return null;
}
Selector s = null;
try {
s = selectors.size()>0?selectors.poll():null;
if (s == null) {
synchronized (Selector.class) {
// Selector.open() isn't thread safe
// http://bugs.sun.com/view_bug.do?bug_id=6427854
// Affects 1.6.0_29, fixed in 1.7.0_01
s = Selector.open();
}
}
else spare.decrementAndGet();
}catch (NoSuchElementException x ) {
try {
synchronized (Selector.class) {
// Selector.open() isn't thread safe
// http://bugs.sun.com/view_bug.do?bug_id=6427854
// Affects 1.6.0_29, fixed in 1.7.0_01
s = Selector.open();
}
} catch (IOException iox) {
}
} finally {
if ( s == null ) active.decrementAndGet();//we were unable to find a selector
}
return s;
}
public void put(Selector s) throws IOException {
if ( SHARED ) return;
if ( enabled ) active.decrementAndGet();
if ( enabled && (maxSpareSelectors==-1 || spare.get() < Math.min(maxSpareSelectors,maxSelectors)) ) {
spare.incrementAndGet();
selectors.offer(s);
}
else s.close();
}
public void close() throws IOException {
enabled = false;
Selector s;
while ( (s = selectors.poll()) != null ) s.close();
spare.set(0);
active.set(0);
if (blockingSelector!=null) {
blockingSelector.close();
}
if ( SHARED && getSharedSelector()!=null ) {
getSharedSelector().close();
SHARED_SELECTOR = null;
}
}
public void open() throws IOException {
enabled = true;
getSharedSelector();
if (SHARED) {
blockingSelector = new NioBlockingSelector();
blockingSelector.open(getSharedSelector());
}
}
/**
* Performs a write using the bytebuffer for data to be written and a
* selector to block (if blocking is requested). If the
* <code>selector</code> parameter is null, and blocking is requested then
* it will perform a busy write that could take up a lot of CPU cycles.
* @param buf The buffer containing the data, we will write as long as <code>(buf.hasRemaining()==true)</code>
* @param socket The socket to write data to
* @param selector The selector to use for blocking, if null then a busy write will be initiated
* @param writeTimeout The timeout for this write operation in milliseconds, -1 means no timeout
* @param block <code>true</code> to perform a blocking write
* otherwise a non-blocking write will be performed
* @return int - returns the number of bytes written
* @throws EOFException if write returns -1
* @throws SocketTimeoutException if the write times out
* @throws IOException if an IO Exception occurs in the underlying socket logic
*/
public int write(ByteBuffer buf, NioChannel socket, Selector selector,
long writeTimeout, boolean block) throws IOException {
if ( SHARED && block ) {
return blockingSelector.write(buf,socket,writeTimeout);
}
SelectionKey key = null;
int written = 0;
boolean timedout = false;
int keycount = 1; //assume we can write
long time = System.currentTimeMillis(); //start the timeout timer
try {
while ( (!timedout) && buf.hasRemaining() ) {
int cnt = 0;
if ( keycount > 0 ) { //only write if we were registered for a write
cnt = socket.write(buf); //write the data
if (cnt == -1) throw new EOFException();
written += cnt;
if (cnt > 0) {
time = System.currentTimeMillis(); //reset our timeout timer
continue; //we successfully wrote, try again without a selector
}
if (cnt==0 && (!block)) break; //don't block
}
if ( selector != null ) {
//register OP_WRITE to the selector
if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE);
else key.interestOps(SelectionKey.OP_WRITE);
if (writeTimeout==0) {
timedout = buf.hasRemaining();
} else if (writeTimeout<0) {
keycount = selector.select();
} else {
keycount = selector.select(writeTimeout);
}
}
if (writeTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=writeTimeout;
}//while
if ( timedout ) throw new SocketTimeoutException();
} finally {
if (key != null) {
key.cancel();
if (selector != null) selector.selectNow();//removes the key from this selector
}
}
return written;
}
/**
* Performs a blocking read using the bytebuffer for data to be read and a selector to block.
* If the <code>selector</code> parameter is null, then it will perform a busy read that could
* take up a lot of CPU cycles.
* @param buf ByteBuffer - the buffer containing the data, we will read as until we have read at least one byte or we timed out
* @param socket SocketChannel - the socket to write data to
* @param selector Selector - the selector to use for blocking, if null then a busy read will be initiated
* @param readTimeout long - the timeout for this read operation in milliseconds, -1 means no timeout
* @return int - returns the number of bytes read
* @throws EOFException if read returns -1
* @throws SocketTimeoutException if the read times out
* @throws IOException if an IO Exception occurs in the underlying socket logic
*/
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout) throws IOException {
return read(buf,socket,selector,readTimeout,true);
}
/**
* Performs a read using the bytebuffer for data to be read and a selector to register for events should
* you have the block=true.
* If the <code>selector</code> parameter is null, then it will perform a busy read that could
* take up a lot of CPU cycles.
* @param buf ByteBuffer - the buffer containing the data, we will read as until we have read at least one byte or we timed out
* @param socket SocketChannel - the socket to write data to
* @param selector Selector - the selector to use for blocking, if null then a busy read will be initiated
* @param readTimeout long - the timeout for this read operation in milliseconds, -1 means no timeout
* @param block - true if you want to block until data becomes available or timeout time has been reached
* @return int - returns the number of bytes read
* @throws EOFException if read returns -1
* @throws SocketTimeoutException if the read times out
* @throws IOException if an IO Exception occurs in the underlying socket logic
*/
public int read(ByteBuffer buf, NioChannel socket, Selector selector, long readTimeout, boolean block) throws IOException {
if ( SHARED && block ) {
return blockingSelector.read(buf,socket,readTimeout);
}
SelectionKey key = null;
int read = 0;
boolean timedout = false;
int keycount = 1; //assume we can write
long time = System.currentTimeMillis(); //start the timeout timer
try {
while ( (!timedout) ) {
int cnt = 0;
if ( keycount > 0 ) { //only read if we were registered for a read
cnt = socket.read(buf);
if (cnt == -1) throw new EOFException();
read += cnt;
if (cnt > 0) continue; //read some more
if (cnt==0 && (read>0 || (!block) ) ) break; //we are done reading
}
if ( selector != null ) {//perform a blocking read
//register OP_WRITE to the selector
if (key==null) key = socket.getIOChannel().register(selector, SelectionKey.OP_READ);
else key.interestOps(SelectionKey.OP_READ);
if (readTimeout==0) {
timedout = (read==0);
} else if (readTimeout<0) {
keycount = selector.select();
} else {
keycount = selector.select(readTimeout);
}
}
if (readTimeout > 0 && (selector == null || keycount == 0) ) timedout = (System.currentTimeMillis()-time)>=readTimeout;
}//while
if ( timedout ) throw new SocketTimeoutException();
} finally {
if (key != null) {
key.cancel();
if (selector != null) selector.selectNow();//removes the key from this selector
}
}
return read;
}
public void setMaxSelectors(int maxSelectors) {
this.maxSelectors = maxSelectors;
}
public void setMaxSpareSelectors(int maxSpareSelectors) {
this.maxSpareSelectors = maxSpareSelectors;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setSharedSelectorTimeout(long sharedSelectorTimeout) {
this.sharedSelectorTimeout = sharedSelectorTimeout;
}
public int getMaxSelectors() {
return maxSelectors;
}
public int getMaxSpareSelectors() {
return maxSpareSelectors;
}
public boolean isEnabled() {
return enabled;
}
public long getSharedSelectorTimeout() {
return sharedSelectorTimeout;
}
public ConcurrentLinkedQueue<Selector> getSelectors() {
return selectors;
}
public AtomicInteger getSpare() {
return spare;
}
} | plumer/codana | tomcat_files/8.0.22/NioSelectorPool.java | Java | mit | 13,585 |
// 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.
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.VisualStudio.Imaging.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
/// <summary>
/// Represents a view model for <see cref="NotificationOption"/>
/// </summary>
internal class NotificationOptionViewModel
{
public NotificationOptionViewModel(NotificationOption notification, ImageMoniker moniker)
{
Notification = notification;
Name = notification.Name;
Moniker = moniker;
}
public ImageMoniker Moniker { get; }
public string Name { get; }
public NotificationOption Notification { get; }
}
}
| jmarolf/roslyn | src/VisualStudio/Core/Impl/Options/NotificationOptionViewModel.cs | C# | mit | 904 |
require 'spec_helper'
describe "article_pages", dbscope: :example do
let(:site) { cms_site }
let(:item) { create(:article_page, cur_node: node) }
let(:index_path) { article_pages_path site.id, node }
let(:new_path) { new_article_page_path site.id, node }
let(:show_path) { article_page_path site.id, node, item }
let(:edit_path) { edit_article_page_path site.id, node, item }
let(:delete_path) { delete_article_page_path site.id, node, item }
let(:move_path) { move_article_page_path site.id, node, item }
let(:copy_path) { copy_article_page_path site.id, node, item }
context "basic crud in category_node_node" do
let(:node) { create_once :category_node_node, filename: "category", name: "category" }
before { login_cms_user }
it "#index" do
visit index_path
expect(current_path).not_to eq sns_login_path
end
it "#new" do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
fill_in "item[basename]", with: "sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).to have_no_css("form#item-form")
end
it "#show" do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).to have_no_css("form#item-form")
end
it "#move" do
visit move_path
within "form" do
fill_in "destination", with: "category/destination"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "category/destination.html")
within "form" do
fill_in "destination", with: "category/sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "category/sample.html")
end
it "#copy" do
visit copy_path
within "form" do
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
expect(page).to have_css("a", text: "[複製] #{item.name}")
expect(page).to have_css(".state", text: "非公開")
end
it "#delete" do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
context "basic crud in category_node_page" do
let(:node) { create_once :category_node_page, filename: "category", name: "category" }
before { login_cms_user }
it "#index" do
visit index_path
expect(current_path).not_to eq sns_login_path
end
it "#new" do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
fill_in "item[basename]", with: "sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).to have_no_css("form#item-form")
end
it "#show" do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).to have_no_css("form#item-form")
end
it "#move" do
visit move_path
within "form" do
fill_in "destination", with: "category/destination"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "category/destination.html")
within "form" do
fill_in "destination", with: "category/sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "category/sample.html")
end
it "#copy" do
visit copy_path
within "form" do
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
expect(page).to have_css("a", text: "[複製] #{item.name}")
expect(page).to have_css(".state", text: "非公開")
end
it "#delete" do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
end
| itowtips/shirasagi | spec/features/article/pages/basic_crud_in_category_nodes.rb | Ruby | mit | 4,856 |
#--
# Copyright (c) 2004-2017 David Heinemeier Hansson
#
# 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.
#++
require "active_support"
require "active_support/rails"
require "active_model/version"
module ActiveModel
extend ActiveSupport::Autoload
autoload :AttributeAssignment
autoload :AttributeMethods
autoload :BlockValidator, "active_model/validator"
autoload :Callbacks
autoload :Conversion
autoload :Dirty
autoload :EachValidator, "active_model/validator"
autoload :ForbiddenAttributesProtection
autoload :Lint
autoload :Model
autoload :Name, "active_model/naming"
autoload :Naming
autoload :SecurePassword
autoload :Serialization
autoload :TestCase
autoload :Translation
autoload :Validations
autoload :Validator
eager_autoload do
autoload :Errors
autoload :RangeError, "active_model/errors"
autoload :StrictValidationFailed, "active_model/errors"
autoload :UnknownAttributeError, "active_model/errors"
end
module Serializers
extend ActiveSupport::Autoload
eager_autoload do
autoload :JSON
end
end
def self.eager_load!
super
ActiveModel::Serializers.eager_load!
end
end
ActiveSupport.on_load(:i18n) do
I18n.load_path << File.dirname(__FILE__) + "/active_model/locale/en.yml"
end
| rbhitchcock/rails | activemodel/lib/active_model.rb | Ruby | mit | 2,296 |
/*Basic RBC model with full depreciation
*
* Jesus Fernandez-Villaverde
*Haverford, July 3, 2013
*/
//package rbc_java;
public class RBC_Java {
public static void main(String[] args) {
/////////////////////////////////////////////////////////////////////
// 0. Housekeeping
/////////////////////////////////////////////////////////////////////
long start = System.nanoTime();
/////////////////////////////////////////////////////////////////////
// 1. Calibration
/////////////////////////////////////////////////////////////////////
double aalpha = 0.33333333333; //Elasticity of output w.r.t. capital
double bbeta = 0.95; //Discount factor
//Productivity values
double[] vProductivity = {0.9792, 0.9896, 1.0000, 1.0106, 1.0212};
//Transition matrix
double[][] mTransition = {
{0.9727, 0.0273, 0.0000, 0.0000, 0.0000},
{0.0041, 0.9806, 0.0153, 0.0000, 0.0000},
{0.0000, 0.0082, 0.9837, 0.0082, 0.0000},
{0.0000, 0.0000, 0.0153, 0.9806, 0.0041},
{0.0000, 0.0000, 0.0000, 0.0273, 0.9727}
};
/////////////////////////////////////////////////////////////////////
// 2. Steady State
/////////////////////////////////////////////////////////////////////
double capitalSteadyState = Math.pow(aalpha*bbeta,1/(1-aalpha));
double outputSteadyState = Math.pow(capitalSteadyState,aalpha);
double consumptionSteadyState = outputSteadyState-capitalSteadyState;
System.out.println("Output = " + outputSteadyState + ", Capital = " +
capitalSteadyState + ", Consumption = " + consumptionSteadyState
+ "\n");
//We generate the grid of capital
int nCapital, nCapitalNextPeriod, gridCapitalNextPeriod, nProductivity,
nProductivityNextPeriod;
int nGridCapital = 17820, nGridProductivity = 5;
double[] vGridCapital = new double[nGridCapital];
for (nCapital = 0; nCapital < nGridCapital; nCapital++){
vGridCapital[nCapital] = 0.5*capitalSteadyState+0.00001*nCapital;
}
/////////////////////////////////////////////////////////////////////
// 3. Required matrices and vectors
/////////////////////////////////////////////////////////////////////
double[][] mOutput = new double[nGridCapital][nGridProductivity];
double[][] mValueFunction = new double[nGridCapital][nGridProductivity];
double[][] mValueFunctionNew = new double[nGridCapital][nGridProductivity];
double[][] mPolicyFunction = new double[nGridCapital][nGridProductivity];
double[][] expectedValueFunction = new double[nGridCapital][nGridProductivity];
/////////////////////////////////////////////////////////////////////
// 4. We pre-build output for each point in the grid
/////////////////////////////////////////////////////////////////////
for(nProductivity = 0; nProductivity < nGridProductivity; nProductivity++){
for(nCapital = 0; nCapital < nGridCapital; nCapital++){
mOutput[nCapital][nProductivity] =
vProductivity[nProductivity]*Math.pow(vGridCapital[nCapital],aalpha);
}
}
/////////////////////////////////////////////////////////////////////
// 5. Main iteration
/////////////////////////////////////////////////////////////////////
double maxDifference = 10.0, diff, diffHighSoFar;
double tolerance = 0.0000001;
double valueHighSoFar, valueProvisional, consumption, capitalChoice;
int iteration = 0;
while(maxDifference > tolerance){
for(nProductivity = 0; nProductivity < nGridProductivity; nProductivity++){
for(nCapital = 0; nCapital < nGridCapital; nCapital++){
expectedValueFunction[nCapital][nProductivity] = 0.0;
for(nProductivityNextPeriod = 0; nProductivityNextPeriod < nGridProductivity; nProductivityNextPeriod++){
expectedValueFunction[nCapital][nProductivity] +=
mTransition[nProductivity][nProductivityNextPeriod]*
mValueFunction[nCapital][nProductivityNextPeriod];
}
}
}
for(nProductivity = 0; nProductivity < nGridProductivity; nProductivity++){
//We start from previous choice (monotonicity of policy function)
gridCapitalNextPeriod = 0;
for(nCapital = 0; nCapital < nGridCapital; nCapital++){
valueHighSoFar = -100000.0;
capitalChoice = vGridCapital[0];
for(nCapitalNextPeriod = gridCapitalNextPeriod; nCapitalNextPeriod < nGridCapital; nCapitalNextPeriod++){
consumption = mOutput[nCapital][nProductivity] - vGridCapital[nCapitalNextPeriod];
valueProvisional = (1 - bbeta)*Math.log(consumption)+bbeta*expectedValueFunction[nCapitalNextPeriod][nProductivity];
if(valueProvisional > valueHighSoFar){
valueHighSoFar = valueProvisional;
capitalChoice = vGridCapital[nCapitalNextPeriod];
gridCapitalNextPeriod = nCapitalNextPeriod;
}
else{
break; //We break when we have achieved the max
}
mValueFunctionNew[nCapital][nProductivity] = valueHighSoFar;
mPolicyFunction[nCapital][nProductivity] = capitalChoice;
}
}
}
diffHighSoFar = -100000.0;
for(nProductivity = 0; nProductivity < nGridProductivity; nProductivity++){
for(nCapital = 0; nCapital < nGridCapital; nCapital++){
diff = Math.abs(mValueFunction[nCapital][nProductivity] -
mValueFunctionNew[nCapital][nProductivity]);
if(diff > diffHighSoFar){
diffHighSoFar = diff;
}
mValueFunction[nCapital][nProductivity] = mValueFunctionNew[nCapital][nProductivity];
}
}
maxDifference = diffHighSoFar;
iteration = iteration + 1;
if(iteration % 10 == 0 || iteration == 1){
System.out.println("Iteration = " + iteration + ", Sup Diff = " + maxDifference);
}
}
System.out.println("Iteration = " + iteration + ", Sup Diff = " + maxDifference + "\n");
System.out.println("My check = " + mPolicyFunction[999][2] + "\n");
long end = System.nanoTime();
long timeDifference = end - start;
double nanoSecs = 1000000000;
System.out.println("Elapsed time is " + timeDifference/nanoSecs + " seconds.");
}
}
| Ryman/Comparison-Programming-Languages-Economics | RBC_Java.java | Java | mit | 7,535 |
using System;
using System.Globalization;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Routing;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Services;
using Umbraco.Web.Models.Trees;
using Umbraco.Web.Mvc;
using Umbraco.Web.WebApi;
using Umbraco.Web.WebApi.Filters;
using umbraco.cms.presentation.Trees;
namespace Umbraco.Web.Trees
{
/// <summary>
/// This is used to output JSON from legacy trees
/// </summary>
[PluginController("UmbracoTrees")]
//public class LegacyTreeController : UmbracoAuthorizedApiController
public class LegacyTreeController : TreeControllerBase
{
private readonly XmlTreeNode _xmlTreeNode;
private readonly string _treeAlias;
private readonly string _currentSection;
private readonly string _rootDisplay;
public LegacyTreeController()
{
}
public LegacyTreeController(XmlTreeNode xmlTreeNode, string treeAlias, string currentSection, UrlHelper urlHelper)
{
_xmlTreeNode = xmlTreeNode;
_treeAlias = treeAlias;
_currentSection = currentSection;
_rootDisplay = xmlTreeNode.Text;
Url = urlHelper;
}
protected override TreeNode CreateRootNode(FormDataCollection queryStrings)
{
return LegacyTreeDataConverter.ConvertFromLegacy(
_xmlTreeNode.NodeID,
_xmlTreeNode,
Url,
_currentSection,
queryStrings,
isRoot: true);
}
protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings)
{
var tree = GetTree(queryStrings);
var attempt = tree.TryLoadFromLegacyTree(id, queryStrings, Url, tree.ApplicationAlias);
if (attempt.Success == false)
{
var msg = "Could not render tree " + queryStrings.GetRequiredString("treeType") + " for node id " + id;
LogHelper.Error<LegacyTreeController>(msg, attempt.Exception);
throw new ApplicationException(msg);
}
return attempt.Result;
}
protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings)
{
//get the parent id from the query strings
var parentId = queryStrings.GetRequiredString("parentId");
var tree = GetTree(queryStrings);
var rootIds = new[]
{
Core.Constants.System.Root.ToString(CultureInfo.InvariantCulture),
Core.Constants.System.RecycleBinContent.ToString(CultureInfo.InvariantCulture),
Core.Constants.System.RecycleBinMedia.ToString(CultureInfo.InvariantCulture)
};
//if the id and the parentId are both -1 then we need to get the menu for the root node
if (rootIds.Contains(id) && parentId == "-1")
{
var attempt = tree.TryGetMenuFromLegacyTreeRootNode(queryStrings, Url);
if (attempt.Success == false)
{
var msg = "Could not render menu for root node for treeType " + queryStrings.GetRequiredString("treeType");
LogHelper.Error<LegacyTreeController>(msg, attempt.Exception);
throw new ApplicationException(msg);
}
foreach (var menuItem in attempt.Result.Items)
{
menuItem.Name = global::umbraco.ui.Text("actions", menuItem.Alias);
}
return attempt.Result;
}
else
{
var attempt = tree.TryGetMenuFromLegacyTreeNode(parentId, id, queryStrings, Url);
if (attempt.Success == false)
{
var msg = "Could not render menu for treeType " + queryStrings.GetRequiredString("treeType") + " for node id " + parentId;
LogHelper.Error<LegacyTreeController>(msg, attempt.Exception);
throw new ApplicationException(msg);
}
foreach (var menuItem in attempt.Result.Items)
{
menuItem.Name = global::umbraco.ui.Text("actions", menuItem.Alias);
}
return attempt.Result;
}
}
public override string RootNodeDisplayName
{
get { return _rootDisplay; }
}
public override string TreeAlias
{
get { return _treeAlias; }
}
private ApplicationTree GetTree(FormDataCollection queryStrings)
{
//need to ensure we have a tree type
var treeType = queryStrings.GetRequiredString("treeType");
//now we'll look up that tree
var tree = Services.ApplicationTreeService.GetByAlias(treeType);
if (tree == null)
throw new InvalidOperationException("No tree found with alias " + treeType);
return tree;
}
}
} | Shazwazza/Umbraco-CMS | src/Umbraco.Web/Trees/LegacyTreeController.cs | C# | mit | 5,328 |
using Stratis.SmartContracts;
[Deploy]
public class TransferTestPos : SmartContract
{
public TransferTestPos(ISmartContractState state)
: base(state)
{
}
public void Test()
{
Transfer(Serializer.ToAddress("SZUEJ7EkPWGC2W1jyMZXVNnYx76vWdyB2a"), 100);
}
public void Test2()
{
Transfer(Serializer.ToAddress("SZUEJ7EkPWGC2W1jyMZXVNnYx76vWdyB2a"), 100);
Transfer(Serializer.ToAddress("n2hyJZj9m8jorD21Nss1tbUtR1NthNHEzg"), 100);
}
public void P2KTest()
{
Transfer(Serializer.ToAddress("mxKorCkWmtrPoekfWiMzERJPhaT13nnkMy"), 100);
}
public bool DoNothing()
{
return true;
}
} | stratisproject/StratisBitcoinFullNode | src/Stratis.SmartContracts.IntegrationTests/SmartContracts/TransferTestPos.cs | C# | mit | 685 |
# coding=utf-8
# pylint: disable-msg=E1101,W0612
import pytest
import numpy as np
import pandas as pd
from pandas import (Index, Series, _np_version_under1p9)
from pandas.core.indexes.datetimes import Timestamp
from pandas.core.dtypes.common import is_integer
import pandas.util.testing as tm
from .common import TestData
class TestSeriesQuantile(TestData):
def test_quantile(self):
q = self.ts.quantile(0.1)
assert q == np.percentile(self.ts.valid(), 10)
q = self.ts.quantile(0.9)
assert q == np.percentile(self.ts.valid(), 90)
# object dtype
q = Series(self.ts, dtype=object).quantile(0.9)
assert q == np.percentile(self.ts.valid(), 90)
# datetime64[ns] dtype
dts = self.ts.index.to_series()
q = dts.quantile(.2)
assert q == Timestamp('2000-01-10 19:12:00')
# timedelta64[ns] dtype
tds = dts.diff()
q = tds.quantile(.25)
assert q == pd.to_timedelta('24:00:00')
# GH7661
result = Series([np.timedelta64('NaT')]).sum()
assert result is pd.NaT
msg = 'percentiles should all be in the interval \\[0, 1\\]'
for invalid in [-1, 2, [0.5, -1], [0.5, 2]]:
with tm.assert_raises_regex(ValueError, msg):
self.ts.quantile(invalid)
def test_quantile_multi(self):
qs = [.1, .9]
result = self.ts.quantile(qs)
expected = pd.Series([np.percentile(self.ts.valid(), 10),
np.percentile(self.ts.valid(), 90)],
index=qs, name=self.ts.name)
tm.assert_series_equal(result, expected)
dts = self.ts.index.to_series()
dts.name = 'xxx'
result = dts.quantile((.2, .2))
expected = Series([Timestamp('2000-01-10 19:12:00'),
Timestamp('2000-01-10 19:12:00')],
index=[.2, .2], name='xxx')
tm.assert_series_equal(result, expected)
result = self.ts.quantile([])
expected = pd.Series([], name=self.ts.name, index=Index(
[], dtype=float))
tm.assert_series_equal(result, expected)
@pytest.mark.skipif(_np_version_under1p9,
reason="Numpy version is under 1.9")
def test_quantile_interpolation(self):
# see gh-10174
# interpolation = linear (default case)
q = self.ts.quantile(0.1, interpolation='linear')
assert q == np.percentile(self.ts.valid(), 10)
q1 = self.ts.quantile(0.1)
assert q1 == np.percentile(self.ts.valid(), 10)
# test with and without interpolation keyword
assert q == q1
@pytest.mark.skipif(_np_version_under1p9,
reason="Numpy version is under 1.9")
def test_quantile_interpolation_dtype(self):
# GH #10174
# interpolation = linear (default case)
q = pd.Series([1, 3, 4]).quantile(0.5, interpolation='lower')
assert q == np.percentile(np.array([1, 3, 4]), 50)
assert is_integer(q)
q = pd.Series([1, 3, 4]).quantile(0.5, interpolation='higher')
assert q == np.percentile(np.array([1, 3, 4]), 50)
assert is_integer(q)
@pytest.mark.skipif(not _np_version_under1p9,
reason="Numpy version is greater 1.9")
def test_quantile_interpolation_np_lt_1p9(self):
# GH #10174
# interpolation = linear (default case)
q = self.ts.quantile(0.1, interpolation='linear')
assert q == np.percentile(self.ts.valid(), 10)
q1 = self.ts.quantile(0.1)
assert q1 == np.percentile(self.ts.valid(), 10)
# interpolation other than linear
msg = "Interpolation methods other than "
with tm.assert_raises_regex(ValueError, msg):
self.ts.quantile(0.9, interpolation='nearest')
# object dtype
with tm.assert_raises_regex(ValueError, msg):
Series(self.ts, dtype=object).quantile(0.7, interpolation='higher')
def test_quantile_nan(self):
# GH 13098
s = pd.Series([1, 2, 3, 4, np.nan])
result = s.quantile(0.5)
expected = 2.5
assert result == expected
# all nan/empty
cases = [Series([]), Series([np.nan, np.nan])]
for s in cases:
res = s.quantile(0.5)
assert np.isnan(res)
res = s.quantile([0.5])
tm.assert_series_equal(res, pd.Series([np.nan], index=[0.5]))
res = s.quantile([0.2, 0.3])
tm.assert_series_equal(res, pd.Series([np.nan, np.nan],
index=[0.2, 0.3]))
def test_quantile_box(self):
cases = [[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'),
pd.Timestamp('2011-01-03')],
[pd.Timestamp('2011-01-01', tz='US/Eastern'),
pd.Timestamp('2011-01-02', tz='US/Eastern'),
pd.Timestamp('2011-01-03', tz='US/Eastern')],
[pd.Timedelta('1 days'), pd.Timedelta('2 days'),
pd.Timedelta('3 days')],
# NaT
[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'),
pd.Timestamp('2011-01-03'), pd.NaT],
[pd.Timestamp('2011-01-01', tz='US/Eastern'),
pd.Timestamp('2011-01-02', tz='US/Eastern'),
pd.Timestamp('2011-01-03', tz='US/Eastern'), pd.NaT],
[pd.Timedelta('1 days'), pd.Timedelta('2 days'),
pd.Timedelta('3 days'), pd.NaT]]
for case in cases:
s = pd.Series(case, name='XXX')
res = s.quantile(0.5)
assert res == case[1]
res = s.quantile([0.5])
exp = pd.Series([case[1]], index=[0.5], name='XXX')
tm.assert_series_equal(res, exp)
def test_datetime_timedelta_quantiles(self):
# covers #9694
assert pd.isnull(Series([], dtype='M8[ns]').quantile(.5))
assert pd.isnull(Series([], dtype='m8[ns]').quantile(.5))
def test_quantile_nat(self):
res = Series([pd.NaT, pd.NaT]).quantile(0.5)
assert res is pd.NaT
res = Series([pd.NaT, pd.NaT]).quantile([0.5])
tm.assert_series_equal(res, pd.Series([pd.NaT], index=[0.5]))
def test_quantile_empty(self):
# floats
s = Series([], dtype='float64')
res = s.quantile(0.5)
assert np.isnan(res)
res = s.quantile([0.5])
exp = Series([np.nan], index=[0.5])
tm.assert_series_equal(res, exp)
# int
s = Series([], dtype='int64')
res = s.quantile(0.5)
assert np.isnan(res)
res = s.quantile([0.5])
exp = Series([np.nan], index=[0.5])
tm.assert_series_equal(res, exp)
# datetime
s = Series([], dtype='datetime64[ns]')
res = s.quantile(0.5)
assert res is pd.NaT
res = s.quantile([0.5])
exp = Series([pd.NaT], index=[0.5])
tm.assert_series_equal(res, exp)
| mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/pandas/tests/series/test_quantile.py | Python | mit | 7,083 |
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga 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.
****************************************************************************/
namespace CocosSharp
{
public class CCTransitionZoomFlipX : CCTransitionSceneOriented
{
float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ;
#region Properties
protected override CCFiniteTimeAction InSceneAction
{
get
{
return new CCSequence
(
new CCDelayTime (Duration / 2),
new CCSpawn
(
new CCOrbitCamera(Duration / 2, 1, 0, inAngleZ, inDeltaZ, 0, 0),
new CCScaleTo(Duration / 2, 1),
new CCShow()
)
);
}
}
protected override CCFiniteTimeAction OutSceneAction
{
get
{
return new CCSequence(
new CCSpawn
(
new CCOrbitCamera(Duration / 2, 1, 0, outAngleZ, outDeltaZ, 0, 0),
new CCScaleTo(Duration / 2, 0.5f)
),
new CCHide(),
new CCDelayTime (Duration / 2)
);
}
}
#endregion Properties
#region Constructors
public CCTransitionZoomFlipX (float duration, CCScene scene, CCTransitionOrientation orientation)
: base(duration, scene, orientation)
{
}
#endregion Constructors
protected override void InitialiseScenes()
{
base.InitialiseScenes();
InSceneNodeContainer.Visible = false;
InSceneNodeContainer.Scale = 0.5f;
InSceneNodeContainer.IgnoreAnchorPointForPosition = true;
OutSceneNodeContainer.IgnoreAnchorPointForPosition = true;
InSceneNodeContainer.AnchorPoint = new CCPoint(0.5f, 0.5f);
OutSceneNodeContainer.AnchorPoint = new CCPoint(0.5f, 0.5f);
if (Orientation == CCTransitionOrientation.RightOver)
{
inDeltaZ = 90;
inAngleZ = 270;
outDeltaZ = 90;
outAngleZ = 0;
}
else
{
inDeltaZ = -90;
inAngleZ = 90;
outDeltaZ = -90;
outAngleZ = 0;
}
}
}
} | hig-ag/CocosSharp | src/layers_scenes_transitions_nodes/transition/CCTransitionZoomFlipX.cs | C# | mit | 3,698 |
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_MODULES_AUDIO_PROCESSING_CHANNEL_BUFFER_H_
#define WEBRTC_MODULES_AUDIO_PROCESSING_CHANNEL_BUFFER_H_
#include <string.h>
#include "webrtc/base/checks.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/common_audio/include/audio_util.h"
#include "webrtc/test/testsupport/gtest_prod_util.h"
namespace webrtc {
// Helper to encapsulate a contiguous data buffer, full or split into frequency
// bands, with access to a pointer arrays of the deinterleaved channels and
// bands. The buffer is zero initialized at creation.
//
// The buffer structure is showed below for a 2 channel and 2 bands case:
//
// |data_|:
// { [ --- b1ch1 --- ] [ --- b2ch1 --- ] [ --- b1ch2 --- ] [ --- b2ch2 --- ] }
//
// The pointer arrays for the same example are as follows:
//
// |channels_|:
// { [ b1ch1* ] [ b1ch2* ] [ b2ch1* ] [ b2ch2* ] }
//
// |bands_|:
// { [ b1ch1* ] [ b2ch1* ] [ b1ch2* ] [ b2ch2* ] }
template <typename T>
class ChannelBuffer {
public:
ChannelBuffer(size_t num_frames,
int num_channels,
size_t num_bands = 1)
: data_(new T[num_frames * num_channels]()),
channels_(new T*[num_channels * num_bands]),
bands_(new T*[num_channels * num_bands]),
num_frames_(num_frames),
num_frames_per_band_(num_frames / num_bands),
num_channels_(num_channels),
num_bands_(num_bands) {
for (int i = 0; i < num_channels_; ++i) {
for (size_t j = 0; j < num_bands_; ++j) {
channels_[j * num_channels_ + i] =
&data_[i * num_frames_ + j * num_frames_per_band_];
bands_[i * num_bands_ + j] = channels_[j * num_channels_ + i];
}
}
}
// Returns a pointer array to the full-band channels (or lower band channels).
// Usage:
// channels()[channel][sample].
// Where:
// 0 <= channel < |num_channels_|
// 0 <= sample < |num_frames_|
T* const* channels() { return channels(0); }
const T* const* channels() const { return channels(0); }
// Returns a pointer array to the channels for a specific band.
// Usage:
// channels(band)[channel][sample].
// Where:
// 0 <= band < |num_bands_|
// 0 <= channel < |num_channels_|
// 0 <= sample < |num_frames_per_band_|
const T* const* channels(size_t band) const {
RTC_DCHECK_LT(band, num_bands_);
return &channels_[band * num_channels_];
}
T* const* channels(size_t band) {
const ChannelBuffer<T>* t = this;
return const_cast<T* const*>(t->channels(band));
}
// Returns a pointer array to the bands for a specific channel.
// Usage:
// bands(channel)[band][sample].
// Where:
// 0 <= channel < |num_channels_|
// 0 <= band < |num_bands_|
// 0 <= sample < |num_frames_per_band_|
const T* const* bands(int channel) const {
RTC_DCHECK_LT(channel, num_channels_);
RTC_DCHECK_GE(channel, 0);
return &bands_[channel * num_bands_];
}
T* const* bands(int channel) {
const ChannelBuffer<T>* t = this;
return const_cast<T* const*>(t->bands(channel));
}
// Sets the |slice| pointers to the |start_frame| position for each channel.
// Returns |slice| for convenience.
const T* const* Slice(T** slice, size_t start_frame) const {
RTC_DCHECK_LT(start_frame, num_frames_);
for (int i = 0; i < num_channels_; ++i)
slice[i] = &channels_[i][start_frame];
return slice;
}
T** Slice(T** slice, size_t start_frame) {
const ChannelBuffer<T>* t = this;
return const_cast<T**>(t->Slice(slice, start_frame));
}
size_t num_frames() const { return num_frames_; }
size_t num_frames_per_band() const { return num_frames_per_band_; }
int num_channels() const { return num_channels_; }
size_t num_bands() const { return num_bands_; }
size_t size() const {return num_frames_ * num_channels_; }
void SetDataForTesting(const T* data, size_t size) {
RTC_CHECK_EQ(size, this->size());
memcpy(data_.get(), data, size * sizeof(*data));
}
private:
rtc::scoped_ptr<T[]> data_;
rtc::scoped_ptr<T* []> channels_;
rtc::scoped_ptr<T* []> bands_;
const size_t num_frames_;
const size_t num_frames_per_band_;
const int num_channels_;
const size_t num_bands_;
};
// One int16_t and one float ChannelBuffer that are kept in sync. The sync is
// broken when someone requests write access to either ChannelBuffer, and
// reestablished when someone requests the outdated ChannelBuffer. It is
// therefore safe to use the return value of ibuf_const() and fbuf_const()
// until the next call to ibuf() or fbuf(), and the return value of ibuf() and
// fbuf() until the next call to any of the other functions.
class IFChannelBuffer {
public:
IFChannelBuffer(size_t num_frames, int num_channels, size_t num_bands = 1);
ChannelBuffer<int16_t>* ibuf();
ChannelBuffer<float>* fbuf();
const ChannelBuffer<int16_t>* ibuf_const() const;
const ChannelBuffer<float>* fbuf_const() const;
size_t num_frames() const { return ibuf_.num_frames(); }
size_t num_frames_per_band() const { return ibuf_.num_frames_per_band(); }
int num_channels() const { return ibuf_.num_channels(); }
size_t num_bands() const { return ibuf_.num_bands(); }
private:
void RefreshF() const;
void RefreshI() const;
mutable bool ivalid_;
mutable ChannelBuffer<int16_t> ibuf_;
mutable bool fvalid_;
mutable ChannelBuffer<float> fbuf_;
};
} // namespace webrtc
#endif // WEBRTC_MODULES_AUDIO_PROCESSING_CHANNEL_BUFFER_H_
| Teamxrtc/webrtc-streaming-node | third_party/webrtc/src/webrtc/common_audio/channel_buffer.h | C | mit | 5,834 |
/**
* @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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
if (n === 1) return 1;
return 5;
}
global.ng.common.locales['es-gt'] = [
'es-GT',
[['a. m.', 'p. m.'], u, u],
u,
[
['d', 'l', 'm', 'm', 'j', 'v', 's'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],
['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA']
],
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],
['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA']
],
[
['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'
],
[
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre',
'octubre', 'noviembre', 'diciembre'
]
],
u,
[['a. C.', 'd. C.'], u, ['antes de Cristo', 'después de Cristo']],
0,
[6, 0],
['d/MM/yy', 'd/MM/y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, '{1} \'a\' \'las\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '¤#,##0.00', '#E0'],
'GTQ',
'Q',
'quetzal',
{
'AUD': [u, '$'],
'BRL': [u, 'R$'],
'CAD': [u, '$'],
'CNY': [u, '¥'],
'ESP': ['₧'],
'EUR': [u, '€'],
'FKP': [u, 'FK£'],
'GBP': [u, '£'],
'GTQ': ['Q'],
'HKD': [u, '$'],
'ILS': [u, '₪'],
'INR': [u, '₹'],
'JPY': [u, '¥'],
'KRW': [u, '₩'],
'MXN': [u, '$'],
'NZD': [u, '$'],
'RON': [u, 'L'],
'SSP': [u, 'SD£'],
'SYP': [u, 'S£'],
'TWD': [u, 'NT$'],
'USD': [u, '$'],
'VEF': [u, 'BsF'],
'VND': [u, '₫'],
'XAF': [],
'XCD': [u, '$'],
'XOF': []
},
'ltr',
plural,
[
[['del mediodía', 'de la madrugada', 'de la mañana', 'de la tarde', 'de la noche'], u, u],
[['mediodía', 'madrugada', 'mañana', 'tarde', 'noche'], u, u],
['12:00', ['00:00', '06:00'], ['06:00', '12:00'], ['12:00', '20:00'], ['20:00', '24:00']]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
| wKoza/angular | packages/common/locales/global/es-GT.js | JavaScript | mit | 2,848 |
define(
[
'dojo/_base/declare', 'dgrid/OnDemandGrid', 'dojo/store/JsonRest', 'dgrid/extensions/DijitRegistry',
'dgrid/Keyboard', 'dgrid/Selection', './formatter', 'dgrid/extensions/ColumnResizer',
'dgrid/extensions/ColumnHider', 'dgrid/extensions/DnD', 'dojo/dnd/Source',
'dojo/_base/Deferred', 'dojo/aspect', 'dojo/_base/lang', '../util/PathJoin'
],
function (
declare, Grid, Store, DijitRegistry,
Keyboard, Selection, formatter, ColumnResizer,
ColumnHider, DnD, DnDSource,
Deferred, aspect, lang, PathJoin
) {
return declare([Grid, ColumnHider, Keyboard, ColumnResizer, DijitRegistry, Selection], {
constructor: function () {
this.dndParams.creator = lang.hitch(this, function (item, hint) {
// console.log("item: ", item, " hint:", hint, "dataType: ", this.dndDataType);
var avatar = dojo.create('div', {
innerHTML: item.organism_name || item.ncbi_taxon_id || item.id
});
avatar.data = item;
if (hint == 'avatar') {
// create your avatar if you want
}
return {
node: avatar,
data: item,
type: this.dndDataType
};
});
},
store: null,
selectionMode: 'extended',
allowTextSelection: false,
allowSelectAll: true,
deselectOnRefresh: false,
minRowsPerPage: 50,
bufferRows: 100,
maxRowsPerPage: 1000,
pagingDelay: 250,
farOffRemoval: 2000,
keepScrollPosition: true,
rowHeight: 24,
loadingMessage: 'Loading...',
dndDataType: 'genome',
dndParams: {
accept: 'none',
selfAccept: false,
copyOnly: true
},
apiServer: window.App.dataServiceURL,
_setApiServer: function (server) {
console.log('_setApiServer ', server);
this.apiServer = server;
this.set('store', this.createStore(this.dataModel), this.buildQuery());
},
_setTotalRows: function (rows) {
this.totalRows = rows;
console.log('Total Rows: ', rows);
if (this.controlButton) {
console.log('this.controlButton: ', this.controlButton);
if (!this._originalTitle) {
this._originalTitle = this.controlButton.get('label');
}
this.controlButton.set('label', this._originalTitle + ' (' + rows + ')');
console.log(this.controlButton);
}
},
startup: function () {
if (this._started) {
return;
}
var _self = this;
// console.log("this.hiderToggleNode: ", this.hiderToggleNode);
// add hint for the show/hide column button
this.hiderToggleNode.title = 'Click to show or hide columns';
aspect.before(_self, 'renderArray', function (results) {
Deferred.when(results.total || results.length, function (x) {
_self.set('totalRows', x);
});
});
if (!this.store && this.dataModel) {
this.store = this.createStore(this.dataModel);
}
this.inherited(arguments);
this._started = true;
},
_setActiveFilter: function (filter) {
console.log('Set Active Filter: ', filter, 'started:', this._started);
this.activeFilter = filter;
this.set('query', this.buildQuery());
},
buildQuery: function (table, extra) {
var q = '?' + (this.activeFilter ? ('in(gid,query(genomesummary,and(' + this.activeFilter + ',limit(Infinity),values(genome_info_id))))') : '') + (this.extra || '');
return q;
},
createStore: function (dataModel) {
console.log('Create Store for ', dataModel, ' at ', this.apiServer);
var store = new Store({
target: PathJoin((this.apiServer ? (this.apiServer) : ''), dataModel) + '/',
idProperty: 'rownum',
headers: {
accept: 'application/json',
'content-type': 'application/json',
Authorization: (window.App.authorizationToken || ''),
'X-Requested-With': null
}
});
console.log('store: ', store);
return store;
}
// getFilterPanel: function () {
// console.log('getFilterPanel()');
// return FilterPanel;
// }
});
}
);
| dawenx/p3_web | public/js/p3/widget/Grid.js | JavaScript | mit | 4,339 |
export function getTypeOf(instance: any /** TODO #9100 */) {
return instance.constructor;
}
export function instantiateType(type: Function, params: any[] = []) {
var instance = Object.create(type.prototype);
instance.constructor.apply(instance, params);
return instance;
}
| zhura/angular | modules/@angular/core/testing/lang_utils.ts | TypeScript | mit | 282 |
<?php
namespace Zotlabs\Module;
require_once('include/security.php');
require_once('include/bbcode.php');
require_once('include/items.php');
class Filer extends \Zotlabs\Web\Controller {
function get() {
if(! local_channel()) {
killme();
}
$term = unxmlify(trim($_GET['term']));
$item_id = ((\App::$argc > 1) ? intval(\App::$argv[1]) : 0);
logger('filer: tag ' . $term . ' item ' . $item_id);
if($item_id && strlen($term)){
// file item
store_item_tag(local_channel(),$item_id,TERM_OBJ_POST,TERM_FILE,$term,'');
// protect the entire conversation from periodic expiration
$r = q("select parent from item where id = %d and uid = %d limit 1",
intval($item_id),
intval(local_channel())
);
if($r) {
$x = q("update item set item_retained = 1 where id = %d and uid = %d",
intval($r[0]['parent']),
intval(local_channel())
);
}
}
else {
$filetags = array();
$r = q("select distinct(term) from term where uid = %d and ttype = %d order by term asc",
intval(local_channel()),
intval(TERM_FILE)
);
if(count($r)) {
foreach($r as $rr)
$filetags[] = $rr['term'];
}
$tpl = get_markup_template("filer_dialog.tpl");
$o = replace_macros($tpl, array(
'$field' => array('term', t('Enter a folder name'), '', '', $filetags, 'placeholder="' . t('or select an existing folder (doubleclick)') . '"'),
'$submit' => t('Save'),
'$title' => t('Save to Folder'),
'$cancel' => t('Cancel')
));
echo $o;
}
killme();
}
}
| anaqreon/hubzilla | Zotlabs/Module/Filer.php | PHP | mit | 1,543 |
<?php
App::uses('FileManagerAppController', 'FileManager.Controller');
App::uses('FileManager', 'FileManager.Model');
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
/**
* FileManager Controller
*
* @category FileManager.Controller
* @package Croogo.FileManager.Controller
* @version 1.0
* @author Fahad Ibnay Heylaal <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @link http://www.croogo.org
*/
class FileManagerController extends FileManagerAppController {
/**
* Models used by the Controller
*
* @var array
* @access public
*/
public $uses = array('Settings.Setting', 'Users.User', 'FileManager.FileManager');
/**
* Helpers used by the Controller
*
* @var array
* @access public
*/
public $helpers = array('Html', 'Form', 'FileManager.FileManager');
/**
* Deletable Paths
*
* @var array
* @access public
*/
public $deletablePaths = array();
/**
* beforeFilter
*
* @return void
* @access public
*/
public function beforeFilter() {
parent::beforeFilter();
$this->deletablePaths = array(
APP . 'View' . DS . 'Themed' . DS,
WWW_ROOT,
);
$this->set('deletablePaths', $this->deletablePaths);
}
/**
* Checks wether given $path is editable.
* A file is editable when it resides under the APP directory
*
* @param string $path Path to check
* @return boolean true if file is editable
* @deprecated Use FileManager::isEditable()
*/
protected function _isEditable($path) {
$path = realpath($path);
$regex = '/^' . preg_quote(realpath(APP), '/') . '/';
return preg_match($regex, $path) > 0;
}
/**
* Checks wether given $path is editable.
* A file is deleteable when it resides under directories registered in
* FileManagerController::deletablePaths
*
* @param string $path Path to check
* @return boolean true when file is deletable
* @deprecated Use FileManager::isDeletable()
*/
protected function _isDeletable($path) {
$path = realpath($path);
$regex = array();
for ($i = 0, $ii = count($this->deletablePaths); $i < $ii; $i++) {
$regex[] = '(^' . preg_quote(realpath($this->deletablePaths[$i]), '/') . ')';
}
$regex = '/' . join($regex, '|') . '/';
return preg_match($regex, $path) > 0;
}
/**
* Admin index
*
* @return void
* @access public
*/
public function admin_index() {
return $this->redirect(array('action' => 'browse'));
}
/**
* Admin browse
*
* @return void
* @access public
*/
public function admin_browse() {
$this->folder = new Folder;
if (isset($this->request->query['path'])) {
$path = $this->request->query['path'];
} else {
$path = APP;
}
$this->set('title_for_layout', __d('croogo', 'File Manager'));
$path = realpath($path) . DS;
$regex = '/^' . preg_quote(realpath(APP), '/') . '/';
if (preg_match($regex, $path) == false) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
$path = APP;
}
$blacklist = array('.git', '.svn', '.CVS');
$regex = '/(' . preg_quote(implode('|', $blacklist), '.') . ')/';
if (in_array(basename($path), $blacklist) || preg_match($regex, $path)) {
$this->Session->setFlash(__d('croogo', sprintf('Path %s is restricted', $path)), 'flash', array('class' => 'error'));
$path = dirname($path);
}
$this->folder->path = $path;
$content = $this->folder->read();
$this->set(compact('content'));
$this->set('path', $path);
}
/**
* Admin editfile
*
* @return void
* @access public
*/
public function admin_editfile() {
if (isset($this->request->query['path'])) {
$path = $this->request->query['path'];
$absolutefilepath = $path;
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (!$this->FileManager->isEditable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
$this->set('title_for_layout', __d('croogo', 'Edit file: %s', $path));
$pathE = explode(DS, $path);
$n = count($pathE) - 1;
unset($pathE[$n]);
$path = implode(DS, $pathE);
$this->file = new File($absolutefilepath, true);
if (!empty($this->request->data) ) {
if ($this->file->write($this->request->data['FileManager']['content'])) {
$this->Session->setFlash(__d('croogo', 'File saved successfully'), 'flash', array('class' => 'success'));
}
}
$content = $this->file->read();
$this->set(compact('content', 'path', 'absolutefilepath'));
}
/**
* Admin upload
*
* @return void
* @access public
*/
public function admin_upload() {
$this->set('title_for_layout', __d('croogo', 'Upload'));
if (isset($this->request->query['path'])) {
$path = $this->request->query['path'];
} else {
$path = APP;
}
$this->set(compact('path'));
if (isset($path) && !$this->_isDeletable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect($this->referer());
}
if (isset($this->request->data['FileManager']['file']['tmp_name']) &&
is_uploaded_file($this->request->data['FileManager']['file']['tmp_name'])) {
$destination = $path . $this->request->data['FileManager']['file']['name'];
move_uploaded_file($this->request->data['FileManager']['file']['tmp_name'], $destination);
$this->Session->setFlash(__d('croogo', 'File uploaded successfully.'), 'flash', array('class' => 'success'));
$redirectUrl = Router::url(array('controller' => 'file_manager', 'action' => 'browse'), true) . '?path=' . urlencode($path);
return $this->redirect($redirectUrl);
}
}
/**
* Admin Delete File
*
* @return void
* @access public
*/
public function admin_delete_file() {
if (!empty($this->request->data['path'])) {
$path = $this->request->data['path'];
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (!$this->_isDeletable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (file_exists($path) && unlink($path)) {
$this->Session->setFlash(__d('croogo', 'File deleted'), 'flash', array('class' => 'success'));
} else {
$this->Session->setFlash(__d('croogo', 'An error occured'), 'flash', array('class' => 'error'));
}
if (isset($_SERVER['HTTP_REFERER'])) {
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'index'));
}
exit();
}
/**
* Admin Delete Directory
*
* @return void
* @access public
*/
public function admin_delete_directory() {
if (!empty($this->request->data['path'])) {
$path = $this->request->data['path'];
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (isset($path) && !$this->_isDeletable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (is_dir($path) && rmdir($path)) {
$this->Session->setFlash(__d('croogo', 'Directory deleted'), 'flash', array('class' => 'success'));
} else {
$this->Session->setFlash(__d('croogo', 'An error occured'), 'flash', array('class' => 'error'));
}
if (isset($_SERVER['HTTP_REFERER'])) {
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'index'));
}
exit;
}
/**
* Rename a file or directory
*
* @return void
* @access public
*/
public function admin_rename() {
$path = $this->request->query('path');
$pathFragments = array_filter(explode(DIRECTORY_SEPARATOR, $path));
if (!$this->FileManager->isEditable($path)) {
$this->Session->setFlash(__d('croogo', 'Path "%s" cannot be renamed', $path), 'flash', array('class' => 'error'));
$this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if (!is_null($this->request->data('FileManager.name')) && !empty($this->request->data['FileManager']['name'])) {
$newName = trim($this->request->data['FileManager']['name']);
$oldName = array_pop($pathFragments);
$newPath = DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $pathFragments) . DIRECTORY_SEPARATOR . $newName;
$fileExists = file_exists($newPath);
if ($oldName !== $newName) {
if ($fileExists) {
$message = __d('croogo', '%s already exists', $newName);
$alertType = 'error';
} else {
if ($this->FileManager->rename($path, $newPath)) {
$message = __d('croogo', '"%s" has been renamed to "%s"', $oldName, $newName);
$alertType = 'success';
} else {
$message = __d('croogo', 'Could not rename "%s" to "%s"', $oldName,$newName);
$alertType = 'error';
}
}
} else {
$message = __d('croogo', 'Name has not changed');
$alertType = 'alert';
}
$this->Session->setFlash($message, 'flash', array('class' => $alertType));
}
return $this->Croogo->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
} else {
$this->Croogo->setReferer();
}
$this->request->data('FileManager.name', array_pop($pathFragments));
$this->set('path', $path);
}
/**
* Admin Create Directory
*
* @return void
* @access public
*/
public function admin_create_directory() {
$this->set('title_for_layout', __d('croogo', 'Create Directory'));
if (isset($this->request->query['path'])) {
$path = $this->request->query['path'];
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (isset($path) && !$this->_isDeletable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect($this->referer());
}
if (!empty($this->request->data)) {
$this->folder = new Folder;
if ($this->folder->create($path . $this->request->data['FileManager']['name'])) {
$this->Session->setFlash(__d('croogo', 'Directory created successfully.'), 'flash', array('class' => 'success'));
$redirectUrl = Router::url(array('controller' => 'file_manager', 'action' => 'browse'), true) . '?path=' . urlencode($path);
return $this->redirect($redirectUrl);
} else {
$this->Session->setFlash(__d('croogo', 'An error occured'), 'flash', array('class' => 'error'));
}
}
$this->set(compact('path'));
}
/**
* Admin Create File
*
* @return void
* @access public
*/
public function admin_create_file() {
$this->set('title_for_layout', __d('croogo', 'Create File'));
if (isset($this->request->query['path'])) {
$path = $this->request->query['path'];
} else {
return $this->redirect(array('controller' => 'file_manager', 'action' => 'browse'));
}
if (isset($path) && !$this->_isEditable($path)) {
$this->Session->setFlash(__d('croogo', 'Path %s is restricted', $path), 'flash', array('class' => 'error'));
return $this->redirect($this->referer());
}
if (!empty($this->request->data)) {
if (touch($path . $this->request->data['FileManager']['name'])) {
$this->Session->setFlash(__d('croogo', 'File created successfully.'), 'flash', array('class' => 'success'));
$redirectUrl = Router::url(array('controller' => 'file_manager', 'action' => 'browse'), true) . '?path=' . urlencode($path);
return $this->redirect($redirectUrl);
} else {
$this->Session->setFlash(__d('croogo', 'An error occured'), 'flash', array('class' => 'error'));
}
}
$this->set(compact('path'));
}
/**
* Admin chmod
*
* @return void
* @access public
*/
public function admin_chmod() {
}
}
| calsoftware/kampecars | Vendor/croogo/croogo/FileManager/Controller/FileManagerController.php | PHP | mit | 12,035 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S7.8.3_A4.2_T1;
* @section: 7.8.3;
* @assertion: ExponentPart :: ExponentIndicator ( /+/-) 0 DecimalDigits is allowed;
* @description: ExponentIndicator :: e;
*/
//CHECK#0
if (0e01 !== 0) {
$ERROR('#0: 0e01 === 0');
}
//CHECK#1
if (1e01 !== 10) {
$ERROR('#1: 1e01 === 10');
}
//CHECK#2
if (2e01 !== 20) {
$ERROR('#2: 2e01 === 20');
}
//CHECK#3
if (3e01 !== 30) {
$ERROR('#3: 3e01 === 30');
}
//CHECK#4
if (4e01 !== 40) {
$ERROR('#4: 4e01 === 40');
}
//CHECK#5
if (5e01 !== 50) {
$ERROR('#5: 5e01 === 50');
}
//CHECK#6
if (6e01 !== 60) {
$ERROR('#6: 6e01 === 60');
}
//CHECK#7
if (7e01 !== 70) {
$ERROR('#7: 7e01 === 70');
}
//CHECK#8
if (8e01 !== 80) {
$ERROR('#8: 8e01 === 80');
}
//CHECK#9
if (9e01 !== 90) {
$ERROR('#9: 9e01 === 90');
}
| seraum/nectarjs | tests/ES3/Conformance/07_Lexical_Conventions/7.8_Literals/7.8.3_Numeric_Literals/S7.8.3_A4.2_T1.js | JavaScript | mit | 922 |
util_log = "util"
| georgestarcher/TA-SyncKVStore | bin/ta_synckvstore/cloudconnectlib/splunktalib/common/consts.py | Python | mit | 18 |
//
// LazyPDFPopoverController.h
//
// Created by Palanisamy Easwaramoorthy on 23/2/15.
// Copyright (c) 2015 Lazyprogram. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "ARCMacros.h"
#import "LazyPDFPopoverView.h"
#import "LazyPDFTouchView.h"
@class LazyPDFPopoverController;
@protocol LazyPDFPopoverControllerDelegate <NSObject>
@optional
- (void)popoverControllerDidDismissPopover:(LazyPDFPopoverController *)popoverController;
- (void)presentedNewPopoverController:(LazyPDFPopoverController *)newPopoverController
shouldDismissVisiblePopover:(LazyPDFPopoverController*)visiblePopoverController;
@end
@interface LazyPDFPopoverController : UIViewController
{
UIView *_parentView;
}
//ARC-enable and disable support
#if __has_feature(objc_arc)
@property(nonatomic,weak) id<LazyPDFPopoverControllerDelegate> delegate;
#else
@property(nonatomic,assign) id<LazyPDFPopoverControllerDelegate> delegate;
#endif
/** @brief LazyPDFPopoverArrowDirectionAny, LazyPDFPopoverArrowDirectionVertical or LazyPDFPopoverArrowDirectionHorizontal for automatic arrow direction.
**/
/** @brief allow reading in order to integrate other open-source **/
@property(nonatomic,readonly) LazyPDFTouchView* touchView;
@property(nonatomic,readonly) LazyPDFPopoverView* contentView;
@property(nonatomic,assign) LazyPDFPopoverArrowDirection arrowDirection;
@property(nonatomic,assign) CGSize contentSize;
@property(nonatomic,assign) CGPoint origin;
@property(nonatomic,assign) CGFloat alpha;
/** @brief The tint of the popover. **/
@property(nonatomic,assign) LazyPDFPopoverTint tint;
/** @brief Popover border, default is YES **/
@property(nonatomic, assign) BOOL border;
/** @brief Initialize the popover with the content view controller
**/
-(id)initWithViewController:(UIViewController*)viewController;
-(id)initWithViewController:(UIViewController*)viewController
delegate:(id<LazyPDFPopoverControllerDelegate>)delegate;
/** @brief Presenting the popover from a specified view **/
-(void)presentPopoverFromView:(UIView*)fromView;
/** @brief Presenting the popover from a specified point **/
-(void)presentPopoverFromPoint:(CGPoint)fromPoint;
/** @brief Dismiss the popover **/
-(void)dismissPopoverAnimated:(BOOL)animated;
/** @brief Dismiss the popover with completion block for post-animation cleanup **/
typedef void (^LazyPDFPopoverCompletion)();
-(void)dismissPopoverAnimated:(BOOL)animated completion:(LazyPDFPopoverCompletion)completionBlock;
/** @brief Hide the shadows to get better performances **/
-(void)setShadowsHidden:(BOOL)hidden;
/** @brief Refresh popover **/
-(void)setupView;
@end
| worgock/LazyPDFKit | LazyPDFKit/LazyPDFPopoverController.h | C | mit | 3,751 |
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react-unstable-shared-subset.production.min.js');
} else {
module.exports = require('./cjs/react-unstable-shared-subset.development.js');
}
| cpojer/react | packages/react/npm/unstable-shared-subset.js | JavaScript | mit | 236 |
(function (testFns) {
if (testFns.DEBUG_SEQUELIZE || testFns.DEBUG_HIBERNATE) {
module("query - raw odata", {});
QUnit.skip("Skipping tests for Sequelize/Hibernate - these servers do no support OData syntax", function () {
});
return;
};
var breeze = testFns.breeze;
var core = breeze.core;
var MetadataStore = breeze.MetadataStore;
var Enum = core.Enum;
var EntityManager = breeze.EntityManager;
var EntityQuery = breeze.EntityQuery;
var EntityType = breeze.EntityType;
var newEm = testFns.newEm;
module("query - raw odata", {
beforeEach: function (assert) {
testFns.setup(assert);
},
afterEach: function (assert) {
}
});
//// for now returns an OData message "$count is not supported"
//test("$count operator", function () {
//
// var em = newEm(testFns.newMs());
// ok(em, "no em found");
// var query = "Customers?$filter=startswith(CompanyName, 'A') eq true&$count";
// em.executeQuery(query).then(function (data) {
// ok(!em.metadataStore.isEmpty(), "metadata should not be empty");
// ok(data, "no data");
// }).fail(testFns.handleFail).fin(done);
//});
testFns.skipIf("mongo", "does not support 'expand'").
test("filter and order by", function (assert) {
var done = assert.async();
var em = newEm(testFns.newMs());
ok(em, "no em found");
var query = "Customers?$filter=startswith(CompanyName, 'A') eq true&$orderby=CompanyName desc&$expand=Orders";
em.executeQuery(query).then(function (data) {
ok(!em.metadataStore.isEmpty(), "metadata should not be empty");
ok(data, "no data");
ok(data.results.length > 0, "empty data");
var customers = data.results;
customers.forEach(function (c) {
ok(c.getProperty("companyName"), "missing companyName property");
var key = c.entityAspect.getKey();
ok(key, "missing key");
});
}).fail(testFns.handleFail).fin(done);
});
testFns.skipIf("mongo", "does not support 'expand'").
test("select", function (assert) {
var done = assert.async();
var em = newEm(testFns.newMs());
ok(em, "no em found");
var query = "Customers?$filter=startswith(CompanyName, 'A') eq true&$select=CompanyName, Orders";
if (testFns.DEBUG_ODATA) {
query = query + "&$expand=Orders";
}
em.executeQuery(query).then(function (data) {
ok(!em.metadataStore.isEmpty(), "metadata should not be empty");
var orderType = em.metadataStore.getEntityType("Order");
ok(data, "no data");
ok(data.results.length > 0, "empty data");
var anons = data.results;
anons.forEach(function (a) {
ok(a.companyName);
ok(Array.isArray(a.orders));
a.orders.forEach(function (order) {
ok(order.entityType === orderType);
});
});
}).fail(testFns.handleFail).fin(done);
});
test("bad expr", function (assert) {
var done = assert.async();
var em = newEm();
var query = "Customers?$filter=starxtswith(CompanyName, 'A') eq true&$orderby=CompanyName desc";
em.executeQuery(query).fail(function (error) {
ok(error instanceof Error, "should be an error");
ok(error.message.indexOf("starxtswith") > -1, "error message has wrong text");
}).fail(testFns.handleFail).fin(done);
});
testFns.skipIf("mongo,odata", "does not implement the 'CustomersAndOrders' endpoint'").
test("raw ajax to web api - server side include many - customer and orders", function (assert) {
var done = assert.async();
try {
$.getJSON(testFns.defaultServiceName + "/CustomersAndOrders?&$top=3").success(function (data, status) {
ok(data);
var str = JSON.stringify(data, undefined, 4);
testFns.output("Customers with orders");
testFns.output(str);
start();
}).error(function (e) {
testFns.handleFail(e);
});
} catch (e) {
testFns.handleFail(e);
}
});
})(breezeTestFns); | edigitalresearch/breeze.js | test/internal/queryRawOdataTests.js | JavaScript | mit | 4,033 |
'use strict';
//This file contains the ES6 extensions to the core Promises/A+ API
var Promise = require('./core.js');
var asap = require('asap');
module.exports = Promise;
/* Static Functions */
var TRUE = valuePromise(true);
var FALSE = valuePromise(false);
var NULL = valuePromise(null);
var UNDEFINED = valuePromise(undefined);
var ZERO = valuePromise(0);
var EMPTYSTRING = valuePromise('');
function valuePromise(value) {
var p = new Promise(Promise._1);
p._41 = 1;
p._86 = value;
return p;
}
Promise.resolve = function (value) {
if (value instanceof Promise) return value;
if (value === null) return NULL;
if (value === undefined) return UNDEFINED;
if (value === true) return TRUE;
if (value === false) return FALSE;
if (value === 0) return ZERO;
if (value === '') return EMPTYSTRING;
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then;
if (typeof then === 'function') {
return new Promise(then.bind(value));
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex);
});
}
}
return valuePromise(value);
};
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
if (val && (typeof val === 'object' || typeof val === 'function')) {
if (val instanceof Promise && val.then === Promise.prototype.then) {
while (val._41 === 3) {
val = val._86;
}
if (val._41 === 1) return res(i, val._86);
if (val._41 === 2) reject(val._86);
val.then(function (val) {
res(i, val);
}, reject);
return;
} else {
var then = val.then;
if (typeof then === 'function') {
var p = new Promise(then.bind(val));
p.then(function (val) {
res(i, val);
}, reject);
return;
}
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
});
});
};
/* Prototype Methods */
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
| xiekw2010/WeInstagram | node_modules/react-native/node_modules/promise/domains/es6-extensions.js | JavaScript | mit | 2,701 |
package net.sf.jabref.gui.exporter;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
class RtfSelection implements Transferable {
private static final Log LOGGER = LogFactory.getLog(RtfSelection.class);
private DataFlavor rtfFlavor;
private DataFlavor[] supportedFlavors;
private final String content;
public RtfSelection(String s) {
content = s;
try {
rtfFlavor = new DataFlavor("text/rtf; class=java.io.InputStream");
supportedFlavors = new DataFlavor[] {rtfFlavor, DataFlavor.stringFlavor};
} catch (ClassNotFoundException ex) {
LOGGER.warn("Cannot find class", ex);
}
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(rtfFlavor) ||
flavor.equals(DataFlavor.stringFlavor);
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return supportedFlavors;
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(DataFlavor.stringFlavor)) {
return content;
} else if (flavor.equals(rtfFlavor)) {
byte[] byteArray = content.getBytes();
return new ByteArrayInputStream(byteArray);
}
throw new UnsupportedFlavorException(flavor);
}
}
| mairdl/jabref | src/main/java/net/sf/jabref/gui/exporter/RtfSelection.java | Java | mit | 1,640 |
define(['mout/random/choice', './helper-mockRandom'], function (choice, mockRandom) {
describe('random/choice()', function () {
beforeEach(function(){
mockRandom.start();
});
afterEach(function() {
mockRandom.end();
});
it('should pick a random argument', function(){
var choices = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var a = choice.apply(null, choices),
b = choice.apply(null, choices);
expect( choices ).toContain( a );
expect( choices ).toContain( b );
expect( a ).not.toEqual( b );
});
it('should work with array', function(){
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var a = choice(arr),
b = choice(arr);
expect( arr ).toContain( a );
expect( arr ).toContain( b );
expect( a ).not.toEqual( b );
});
});
});
| moklick/mout | tests/spec/random/spec-choice.js | JavaScript | mit | 972 |
/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with the
terms contained in a written agreement between you and Sencha.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1)
*/
Ext.define('ExtThemeNeptune.panel.Tool', {
override: 'Ext.panel.Tool',
height: 16,
width: 16
});
| rch/flask-openshift | wsgi/container/pkgs/sencha/static/ext-4.2.2.1144/packages/ext-theme-neptune/overrides/panel/Tool.js | JavaScript | mit | 705 |
require "pathname"
require "log4r"
module Vagrant
module Config
# This class is responsible for loading Vagrant configuration,
# usually in the form of Vagrantfiles.
#
# Loading works by specifying the sources for the configuration
# as well as the order the sources should be loaded. Configuration
# set later always overrides those set earlier; this is how
# configuration "scoping" is implemented.
class Loader
# Initializes a configuration loader.
#
# @param [Registry] versions A registry of the available versions and
# their associated loaders.
# @param [Array] version_order An array of the order of the versions
# in the registry. This is used to determine if upgrades are
# necessary. Additionally, the last version in this order is always
# considered the "current" version.
def initialize(versions, version_order)
@logger = Log4r::Logger.new("vagrant::config::loader")
@config_cache = {}
@proc_cache = {}
@sources = {}
@versions = versions
@version_order = version_order
end
# Set the configuration data for the given name.
#
# The `name` should be a symbol and must uniquely identify the data
# being given.
#
# `data` can either be a path to a Ruby Vagrantfile or a `Proc` directly.
# `data` can also be an array of such values.
#
# At this point, no configuration is actually loaded. Note that calling
# `set` multiple times with the same name will override any previously
# set values. In this way, the last set data for a given name wins.
def set(name, sources)
@logger.info("Set #{name.inspect} = #{sources.inspect}")
# Sources should be an array
sources = [sources] if !sources.kind_of?(Array)
# Gather the procs for every source, since that is what we care about.
procs = []
sources.each do |source|
if !@proc_cache.has_key?(source)
# Load the procs for this source and cache them. This caching
# avoids the issue where a file may have side effects when loading
# and loading it multiple times causes unexpected behavior.
@logger.debug("Populating proc cache for #{source.inspect}")
@proc_cache[source] = procs_for_source(source)
end
# Add on to the array of procs we're going to use
procs.concat(@proc_cache[source])
end
# Set this source by name.
@sources[name] = procs
end
# This loads the configuration sources in the given order and returns
# an actual configuration object that is ready to be used.
#
# @param [Array<Symbol>] order The order of configuration to load.
# @return [Object] The configuration object. This is different for
# each configuration version.
def load(order)
@logger.info("Loading configuration in order: #{order.inspect}")
unknown_sources = @sources.keys - order
if !unknown_sources.empty?
# TODO: Raise exception here perhaps.
@logger.error("Unknown config sources: #{unknown_sources.inspect}")
end
# Get the current version config class to use
current_version = @version_order.last
current_config_klass = @versions.get(current_version)
# This will hold our result
result = current_config_klass.init
# Keep track of the warnings and errors that may come from
# upgrading the Vagrantfiles
warnings = []
errors = []
order.each do |key|
next if [email protected]_key?(key)
@sources[key].each do |version, proc|
if !@config_cache.has_key?(proc)
@logger.debug("Loading from: #{key} (evaluating)")
# Get the proper version loader for this version and load
version_loader = @versions.get(version)
version_config = version_loader.load(proc)
# Store the errors/warnings associated with loading this
# configuration. We'll store these for later.
version_warnings = []
version_errors = []
# If this version is not the current version, then we need
# to upgrade to the latest version.
if version != current_version
@logger.debug("Upgrading config from version #{version} to #{current_version}")
version_index = @version_order.index(version)
current_index = @version_order.index(current_version)
(version_index + 1).upto(current_index) do |index|
next_version = @version_order[index]
@logger.debug("Upgrading config to version #{next_version}")
# Get the loader of this version and ask it to upgrade
loader = @versions.get(next_version)
upgrade_result = loader.upgrade(version_config)
this_warnings = upgrade_result[1]
this_errors = upgrade_result[2]
@logger.debug("Upgraded to version #{next_version} with " +
"#{this_warnings.length} warnings and " +
"#{this_errors.length} errors")
# Append loading this to the version warnings and errors
version_warnings += this_warnings
version_errors += this_errors
# Store the new upgraded version
version_config = upgrade_result[0]
end
end
# Cache the loaded configuration along with any warnings
# or errors so that they can be retrieved later.
@config_cache[proc] = [version_config, version_warnings, version_errors]
else
@logger.debug("Loading from: #{key} (cache)")
end
# Merge the configurations
cache_data = @config_cache[proc]
result = current_config_klass.merge(result, cache_data[0])
# Append the total warnings/errors
warnings += cache_data[1]
errors += cache_data[2]
end
end
@logger.debug("Configuration loaded successfully, finalizing and returning")
[current_config_klass.finalize(result), warnings, errors]
end
protected
# This returns an array of `Proc` objects for the given source.
# The `Proc` objects returned will expect a single argument for
# the configuration object and are expected to mutate this
# configuration object.
def procs_for_source(source)
# Convert all pathnames to strings so we just have their path
source = source.to_s if source.is_a?(Pathname)
if source.is_a?(Array)
# An array must be formatted as [version, proc], so verify
# that and then return it
raise ArgumentError, "String source must have format [version, proc]" if source.length != 2
# Return it as an array since we're expected to return an array
# of [version, proc] pairs, but an array source only has one.
return [source]
elsif source.is_a?(String)
# Strings are considered paths, so load them
return procs_for_path(source)
else
raise ArgumentError, "Unknown configuration source: #{source.inspect}"
end
end
# This returns an array of `Proc` objects for the given path source.
#
# @param [String] path Path to the file which contains the proper
# `Vagrant.configure` calls.
# @return [Array<Proc>]
def procs_for_path(path)
@logger.debug("Load procs for pathname: #{path}")
return Config.capture_configures do
begin
Kernel.load path
rescue SyntaxError => e
# Report syntax errors in a nice way.
raise Errors::VagrantfileSyntaxError, :file => e.message
rescue SystemExit
# Continue raising that exception...
raise
rescue Vagrant::Errors::VagrantError
# Continue raising known Vagrant errors since they already
# contain well worded error messages and context.
raise
rescue Exception => e
@logger.error("Vagrantfile load error: #{e.message}")
@logger.error(e.backtrace.join("\n"))
# Report the generic exception
raise Errors::VagrantfileLoadError,
:path => path,
:message => e.message
end
end
end
end
end
end
| derickr/vagrant | lib/vagrant/config/loader.rb | Ruby | mit | 8,787 |
<?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.
*/
namespace spec\Sylius\Bundle\ResourceBundle\Doctrine\ORM\Form\Builder;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\Form\Builder\DefaultFormBuilder;
use Sylius\Bundle\ResourceBundle\Form\Builder\DefaultFormBuilderInterface;
use Sylius\Component\Resource\Metadata\MetadataInterface;
use Symfony\Component\Form\FormBuilderInterface;
/**
* @mixin DefaultFormBuilder
*
* @author Paweł Jędrzejewski <[email protected]>
*/
final class DefaultFormBuilderSpec extends ObjectBehavior
{
function let(EntityManagerInterface $entityManager)
{
$this->beConstructedWith($entityManager);
}
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\ResourceBundle\Doctrine\ORM\Form\Builder\DefaultFormBuilder');
}
function it_is_a_default_form_builder()
{
$this->shouldImplement(DefaultFormBuilderInterface::class);
}
function it_does_not_support_entities_with_multiple_primary_keys(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->identifier = ['id', 'slug'];
$this
->shouldThrow(\RuntimeException::class)
->during('build', [$metadata, $formBuilder, []])
;
}
function it_excludes_non_natural_identifier_from_the_field_list(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['id', 'name', 'description', 'enabled'];
$classMetadataInfo->identifier = ['id'];
$classMetadataInfo->isIdentifierNatural()->willReturn(false);
$classMetadataInfo->getAssociationMappings()->willReturn([]);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$formBuilder->add('id', Argument::cetera())->shouldNotBeCalled();
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$this->build($metadata, $formBuilder, []);
}
function it_does_not_exclude_natural_identifier_from_the_field_list(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['id', 'name', 'description', 'enabled'];
$classMetadataInfo->identifier = ['id'];
$classMetadataInfo->isIdentifierNatural()->willReturn(true);
$classMetadataInfo->getAssociationMappings()->willReturn([]);
$classMetadataInfo->getTypeOfField('id')->willReturn(Type::INTEGER);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$formBuilder->add('id', null, [])->shouldBeCalled();
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$this->build($metadata, $formBuilder, []);
}
function it_uses_metadata_to_create_appropriate_fields(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['name', 'description', 'enabled'];
$classMetadataInfo->isIdentifierNatural()->willReturn(true);
$classMetadataInfo->getAssociationMappings()->willReturn([]);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$this->build($metadata, $formBuilder, []);
}
function it_uses_single_text_widget_for_datetime_field(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['name', 'description', 'enabled', 'publishedAt'];
$classMetadataInfo->isIdentifierNatural()->willReturn(true);
$classMetadataInfo->getAssociationMappings()->willReturn([]);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$classMetadataInfo->getTypeOfField('publishedAt')->willReturn(Type::DATETIME);
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$formBuilder->add('publishedAt', null, ['widget' => 'single_text'])->shouldBeCalled();
$this->build($metadata, $formBuilder, []);
}
function it_also_creates_fields_for_relations_other_than_one_to_many(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['name', 'description', 'enabled', 'publishedAt'];
$classMetadataInfo->isIdentifierNatural()->willReturn(true);
$classMetadataInfo->getAssociationMappings()->willReturn([
'category' => ['type' => ClassMetadataInfo::MANY_TO_ONE],
'users' => ['type' => ClassMetadataInfo::ONE_TO_MANY],
]);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$classMetadataInfo->getTypeOfField('publishedAt')->willReturn(Type::DATETIME);
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$formBuilder->add('publishedAt', null, ['widget' => 'single_text'])->shouldBeCalled();
$formBuilder->add('category', null, ['property' => 'id'])->shouldBeCalled();
$formBuilder->add('users', Argument::cetera())->shouldNotBeCalled();
$this->build($metadata, $formBuilder, []);
}
function it_excludes_common_fields_like_createdAt_and_updatedAt(
MetadataInterface $metadata,
FormBuilderInterface $formBuilder,
EntityManagerInterface $entityManager,
ClassMetadataInfo $classMetadataInfo
) {
$metadata->getClass('model')->willReturn('AppBundle\Entity\Book');
$entityManager->getClassMetadata('AppBundle\Entity\Book')->willReturn($classMetadataInfo);
$classMetadataInfo->fieldNames = ['name', 'description', 'enabled', 'createdAt', 'updatedAt'];
$classMetadataInfo->isIdentifierNatural()->willReturn(true);
$classMetadataInfo->getAssociationMappings()->willReturn([]);
$classMetadataInfo->getTypeOfField('name')->willReturn(Type::STRING);
$classMetadataInfo->getTypeOfField('description')->willReturn(Type::TEXT);
$classMetadataInfo->getTypeOfField('enabled')->willReturn(Type::BOOLEAN);
$classMetadataInfo->getTypeOfField('createdAt')->willReturn(Type::DATETIME);
$classMetadataInfo->getTypeOfField('updatedAt')->willReturn(Type::DATETIME);
$formBuilder->add('name', null, [])->shouldBeCalled();
$formBuilder->add('description', null, [])->shouldBeCalled();
$formBuilder->add('enabled', null, [])->shouldBeCalled();
$formBuilder->add('createdAt', Argument::cetera())->shouldNotBeCalled();
$formBuilder->add('updatedAt', Argument::cetera())->shouldNotBeCalled();
$this->build($metadata, $formBuilder, []);
}
}
| steffenbrem/Sylius | src/Sylius/Bundle/ResourceBundle/spec/Doctrine/ORM/Form/Builder/DefaultFormBuilderSpec.php | PHP | mit | 10,124 |
/**
* @license
* Copyright Google Inc. 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 {CompileDirectiveMetadata, CompileStylesheetMetadata, CompileTemplateMetadata, CompileTypeMetadata} from '@angular/compiler/src/compile_metadata';
import {CompilerConfig} from '@angular/compiler/src/config';
import {DirectiveNormalizer} from '@angular/compiler/src/directive_normalizer';
import {ResourceLoader} from '@angular/compiler/src/resource_loader';
import {MockResourceLoader} from '@angular/compiler/testing/resource_loader_mock';
import {TEST_COMPILER_PROVIDERS} from '@angular/compiler/testing/test_bindings';
import {ViewEncapsulation} from '@angular/core/src/metadata/view';
import {TestBed} from '@angular/core/testing';
import {AsyncTestCompleter, beforeEach, beforeEachProviders, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {SpyResourceLoader} from './spies';
export function main() {
describe('DirectiveNormalizer', () => {
var dirType: CompileTypeMetadata;
var dirTypeWithHttpUrl: CompileTypeMetadata;
beforeEach(() => { TestBed.configureCompiler({providers: TEST_COMPILER_PROVIDERS}); });
beforeEach(() => {
dirType = new CompileTypeMetadata({moduleUrl: 'package:some/module/a.js', name: 'SomeComp'});
dirTypeWithHttpUrl =
new CompileTypeMetadata({moduleUrl: 'http://some/module/a.js', name: 'SomeComp'});
});
describe('normalizeDirective', () => {
it('should throw if no template was specified',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
expect(() => normalizer.normalizeDirective(new CompileDirectiveMetadata({
type: dirType,
isComponent: true,
template:
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []})
}))).toThrowError('No template specified for component SomeComp');
}));
});
describe('normalizeTemplateSync', () => {
it('should store the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: 'a',
templateUrl: null,
styles: [],
styleUrls: []
}));
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/a.js');
}));
it('should resolve styles on the annotation against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should resolve styles in the template against the moduleUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template =
normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '<style>@import test.css</style>',
templateUrl: null,
styles: [],
styleUrls: []
}));
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should use ViewEncapsulation.Emulated by default',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
let template = normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.encapsulation).toEqual(ViewEncapsulation.Emulated);
}));
it('should use default encapsulation provided by CompilerConfig',
inject(
[CompilerConfig, DirectiveNormalizer],
(config: CompilerConfig, normalizer: DirectiveNormalizer) => {
config.defaultEncapsulation = ViewEncapsulation.None;
let template =
normalizer.normalizeTemplateSync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: '',
templateUrl: null,
styles: [],
styleUrls: ['test.css']
}));
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
}));
});
describe('templateUrl', () => {
it('should load a template from a url that is resolved against moduleUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/sometplurl.html', 'a');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'sometplurl.html',
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.template).toEqual('a');
expect(template.templateUrl).toEqual('package:some/module/sometplurl.html');
async.done();
});
resourceLoader.flush();
}));
it('should resolve styles on the annotation against the moduleUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/tpl/sometplurl.html', '');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: ['test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
async.done();
});
resourceLoader.flush();
}));
it('should resolve styles in the template against the templateUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect(
'package:some/module/tpl/sometplurl.html', '<style>@import test.css</style>');
normalizer
.normalizeTemplateAsync(dirType, new CompileTemplateMetadata({
encapsulation: null,
template: null,
templateUrl: 'tpl/sometplurl.html',
styles: [],
styleUrls: []
}))
.then((template: CompileTemplateMetadata) => {
expect(template.styleUrls).toEqual(['package:some/module/tpl/test.css']);
async.done();
});
resourceLoader.flush();
}));
});
describe('normalizeExternalStylesheets', () => {
beforeEach(() => {
TestBed.configureCompiler(
{providers: [{provide: ResourceLoader, useClass: SpyResourceLoader}]});
});
it('should load an external stylesheet',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: SpyResourceLoader) => {
programResourceLoaderSpy(resourceLoader, {'package:some/module/test.css': 'a'});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.externalStylesheets.length).toBe(1);
expect(template.externalStylesheets[0]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test.css',
styles: ['a'],
styleUrls: []
}));
async.done();
});
}));
it('should load stylesheets referenced by external stylesheets',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: SpyResourceLoader) => {
programResourceLoaderSpy(resourceLoader, {
'package:some/module/test.css': 'a@import "test2.css"',
'package:some/module/test2.css': 'b'
});
normalizer
.normalizeExternalStylesheets(new CompileTemplateMetadata({
template: '',
templateUrl: '',
styleUrls: ['package:some/module/test.css']
}))
.then((template: CompileTemplateMetadata) => {
expect(template.externalStylesheets.length).toBe(2);
expect(template.externalStylesheets[0]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test.css',
styles: ['a'],
styleUrls: ['package:some/module/test2.css']
}));
expect(template.externalStylesheets[1]).toEqual(new CompileStylesheetMetadata({
moduleUrl: 'package:some/module/test2.css',
styles: ['b'],
styleUrls: []
}));
async.done();
});
}));
});
describe('caching', () => {
it('should work for templateUrl',
inject(
[AsyncTestCompleter, DirectiveNormalizer, ResourceLoader],
(async: AsyncTestCompleter, normalizer: DirectiveNormalizer,
resourceLoader: MockResourceLoader) => {
resourceLoader.expect('package:some/module/cmp.html', 'a');
var templateMeta = new CompileTemplateMetadata({
templateUrl: 'cmp.html',
});
Promise
.all([
normalizer.normalizeTemplateAsync(dirType, templateMeta),
normalizer.normalizeTemplateAsync(dirType, templateMeta)
])
.then((templates: CompileTemplateMetadata[]) => {
expect(templates[0].template).toEqual('a');
expect(templates[1].template).toEqual('a');
async.done();
});
resourceLoader.flush();
}));
});
describe('normalizeLoadedTemplate', () => {
it('should store the viewEncapsulationin the result',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var viewEncapsulation = ViewEncapsulation.Native;
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: viewEncapsulation, styles: [], styleUrls: []}),
'', 'package:some/module/');
expect(template.encapsulation).toBe(viewEncapsulation);
}));
it('should keep the template as html',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}), 'a',
'package:some/module/');
expect(template.template).toEqual('a');
}));
it('should collect ngContent',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<ng-content select="a"></ng-content>', 'package:some/module/');
expect(template.ngContentSelectors).toEqual(['a']);
}));
it('should normalize ngContent wildcard selector',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<ng-content></ng-content><ng-content select></ng-content><ng-content select="*"></ng-content>',
'package:some/module/');
expect(template.ngContentSelectors).toEqual(['*', '*', '*']);
}));
it('should collect top level styles in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<style>a</style>', 'package:some/module/');
expect(template.styles).toEqual(['a']);
}));
it('should collect styles inside in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div><style>a</style></div>', 'package:some/module/');
expect(template.styles).toEqual(['a']);
}));
it('should collect styleUrls in the template',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link rel="stylesheet" href="aUrl">', 'package:some/module/');
expect(template.styleUrls).toEqual(['package:some/module/aUrl']);
}));
it('should collect styleUrls in elements',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div><link rel="stylesheet" href="aUrl"></div>', 'package:some/module/');
expect(template.styleUrls).toEqual(['package:some/module/aUrl']);
}));
it('should ignore link elements with non stylesheet rel attribute',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link href="b" rel="a">', 'package:some/module/');
expect(template.styleUrls).toEqual([]);
}));
it('should ignore link elements with absolute urls but non package: scheme',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<link href="http://some/external.css" rel="stylesheet">', 'package:some/module/');
expect(template.styleUrls).toEqual([]);
}));
it('should extract @import style urls into styleAbsUrl',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: null, styles: ['@import "test.css";'], styleUrls: []}),
'', 'package:some/module/id');
expect(template.styles).toEqual(['']);
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should not resolve relative urls in inline styles',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata({
encapsulation: null,
styles: ['.foo{background-image: url(\'double.jpg\');'],
styleUrls: []
}),
'', 'package:some/module/id');
expect(template.styles).toEqual(['.foo{background-image: url(\'double.jpg\');']);
}));
it('should resolve relative style urls in styleUrls',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: null, styles: [], styleUrls: ['test.css']}),
'', 'package:some/module/id');
expect(template.styles).toEqual([]);
expect(template.styleUrls).toEqual(['package:some/module/test.css']);
}));
it('should resolve relative style urls in styleUrls with http directive url',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirTypeWithHttpUrl, new CompileTemplateMetadata(
{encapsulation: null, styles: [], styleUrls: ['test.css']}),
'', 'http://some/module/id');
expect(template.styles).toEqual([]);
expect(template.styleUrls).toEqual(['http://some/module/test.css']);
}));
it('should normalize ViewEncapsulation.Emulated to ViewEncapsulation.None if there are no styles nor stylesheets',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType, new CompileTemplateMetadata(
{encapsulation: ViewEncapsulation.Emulated, styles: [], styleUrls: []}),
'', 'package:some/module/id');
expect(template.encapsulation).toEqual(ViewEncapsulation.None);
}));
it('should ignore ng-content in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div ngNonBindable><ng-content select="a"></ng-content></div>',
'package:some/module/');
expect(template.ngContentSelectors).toEqual([]);
}));
it('should still collect <style> in elements with ngNonBindable',
inject([DirectiveNormalizer], (normalizer: DirectiveNormalizer) => {
var template = normalizer.normalizeLoadedTemplate(
dirType,
new CompileTemplateMetadata({encapsulation: null, styles: [], styleUrls: []}),
'<div ngNonBindable><style>div {color:red}</style></div>', 'package:some/module/');
expect(template.styles).toEqual(['div {color:red}']);
}));
});
});
}
function programResourceLoaderSpy(spy: SpyResourceLoader, results: {[key: string]: string}) {
spy.spy('get').andCallFake((url: string): Promise<any> => {
var result = results[url];
if (result) {
return Promise.resolve(result);
} else {
return Promise.reject(`Unknown mock url ${url}`);
}
});
}
| alamgird/angular | modules/@angular/compiler/test/directive_normalizer_spec.ts | TypeScript | mit | 22,718 |
// 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 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault.Models
{
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization;
/// <summary>
/// Defines values for KeyUsageType.
/// </summary>
public static class KeyUsageType
{
public const string DigitalSignature = "digitalSignature";
public const string NonRepudiation = "nonRepudiation";
public const string KeyEncipherment = "keyEncipherment";
public const string DataEncipherment = "dataEncipherment";
public const string KeyAgreement = "keyAgreement";
public const string KeyCertSign = "keyCertSign";
public const string CRLSign = "cRLSign";
public const string EncipherOnly = "encipherOnly";
public const string DecipherOnly = "decipherOnly";
}
}
| ahosnyms/azure-sdk-for-net | src/KeyVault/Microsoft.Azure.KeyVault/Generated/Models/KeyUsageType.cs | C# | mit | 1,145 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Operator ++x returns x = ToNumber(x) + 1
es5id: 11.4.4_A3_T5
description: Type(x) is Object object or Function object
---*/
//CHECK#1
var x = {};
++x;
if (isNaN(x) !== true) {
$ERROR('#1: var x = {}; ++x; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
var x = function(){return 1};
++x;
if (isNaN(x) !== true) {
$ERROR('#2: var x = function(){return 1}; ++x; x === Not-a-Number. Actual: ' + (x));
}
| PiotrDabkowski/Js2Py | tests/test_cases/language/expressions/prefix-increment/S11.4.4_A3_T5.js | JavaScript | mit | 557 |
using System.Collections.Generic;
using NUnit.Framework;
using SIL.DictionaryServices.Model;
using SIL.Lift;
using SIL.TestUtilities;
using SIL.Text;
namespace SIL.DictionaryServices.Tests.Model
{
[TestFixture]
public class LexPhoneticCloneableTests:CloneableTests<IPalasoDataObjectProperty>
{
public override IPalasoDataObjectProperty CreateNewCloneable()
{
return new LexPhonetic();
}
public override string ExceptionList
{
//PropertyChanged: No good way to clone eventhandlers
//_parent: We are doing top down clones. Children shouldn't make clones of their parents, but parents of their children.
get { return "|_parent|PropertyChanged|"; }
}
protected override List<ValuesToSet> DefaultValuesForTypes
{
get
{
return new List<ValuesToSet>
{
new ValuesToSet(
new List<LexTrait> { new LexTrait("one", "eins"), new LexTrait("two", "zwei") },
new List<LexTrait> { new LexTrait("three", "drei"), new LexTrait("four", "vier") }),
new ValuesToSet(
new List<LexField> { new LexField("one"), new LexField("two") },
new List<LexField> { new LexField("three"), new LexField("four") }),
new ValuesToSet(new List<string>{"to", "be"}, new List<string>{"!","to","be"}),
new ValuesToSet(new []{new LanguageForm("en", "en_form", null)}, new []{new LanguageForm("de", "de_form", null)})
};
}
}
}
}
| tombogle/libpalaso | SIL.DictionaryServices.Tests/Model/LexPhoneticTests.cs | C# | mit | 1,421 |
import got = require('got');
import cookie = require('cookie');
import FormData = require('form-data');
import Keyv = require('keyv');
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as url from 'url';
import QuickLRU = require('quick-lru');
let str: string;
let buf: Buffer;
got('todomvc.com')
.then(response => {
str = response.body;
})
.catch((error: got.GotError) => {
console.log(error.response.body);
});
got('todomvc.com').cancel();
got('todomvc.com', {json: true}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {json: true, body: {}}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {json: true, body: [{}]}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {json: true, form: true}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {json: true, form: true, encoding: null}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {json: true, form: true, encoding: null, hostname: 'todomvc'}).then((response) => {
response.body; // $ExpectType any
});
got('todomvc.com', {form: true}).then(response => str = response.body);
got('todomvc.com', {form: true, body: {}}).then(response => str = response.body);
got('todomvc.com', {form: true, body: [{}]}).then(response => str = response.body);
got('todomvc.com', {form: true, body: [{}], encoding: null}).then(response => buf = response.body);
got('todomvc.com', {form: true, body: [{}], encoding: 'utf8'}).then(response => str = response.body);
got('todomvc.com', {
form: true,
body: [{}],
encoding: 'utf8',
hostname: 'todomvc'
}).then(response => str = response.body);
got('todomvc.com', {
form: true,
body: [{}],
encoding: 'utf8',
hostname: 'todomvc',
timeout: 2000
}).then(response => str = response.body);
got('todomvc.com', {
form: true,
body: [{}],
encoding: 'utf8',
hostname: 'todomvc',
timeout: {connect: 20, request: 20, socket: 20}
}).then(response => str = response.body);
// following must lead to type checking error: got('todomvc.com', {form: true, body: ''}).then(response => str = response.body);
got('todomvc.com', {encoding: null, hostname: 'todomvc'}).then(response => buf = response.body);
got('todomvc.com', {encoding: 'utf8', hostname: 'todomvc'}).then(response => str = response.body);
got('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.get('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.post('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.put('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.patch('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.head('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.delete('todomvc.com', {hostname: 'todomvc'}).then(response => str = response.body);
got.stream('todomvc.com').pipe(fs.createWriteStream('index.html'));
fs.createReadStream('index.html').pipe(got.stream.get('todomvc.com'));
fs.createReadStream('index.html').pipe(got.stream.post('todomvc.com'));
fs.createReadStream('index.html').pipe(got.stream.put('todomvc.com'));
fs.createReadStream('index.html').pipe(got.stream.patch('todomvc.com'));
fs.createReadStream('index.html').pipe(got.stream.head('todomvc.com'));
fs.createReadStream('index.html').pipe(got.stream.delete('todomvc.com'));
let req: http.ClientRequest;
let res: http.IncomingMessage | undefined;
let opts: got.GotOptions<string | null>;
let err: got.GotError;
let href: string | undefined;
let progress: got.Progress;
const stream = got.stream('todomvc.com');
stream.addListener('request', (r) => req = r);
stream.addListener('response', (r) => res = r);
stream.addListener('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.addListener('error', (e, b, r) => {
err = e;
res = r;
});
stream.addListener('downloadProgress', (p) => {
progress = p;
});
stream.addListener('uploadProgress', (p) => {
progress = p;
});
stream.on('request', (r) => req = r);
stream.on('response', (r) => res = r);
stream.on('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.on('error', (e, b, r) => {
err = e;
res = r;
});
stream.on('downloadProgress', (p) => {
progress = p;
});
stream.on('uploadProgress', (p) => {
progress = p;
});
stream.once('request', (r) => req = r);
stream.once('response', (r) => res = r);
stream.once('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.once('error', (e, b, r) => {
err = e;
res = r;
});
stream.once('downloadProgress', (p) => {
progress = p;
});
stream.once('uploadProgress', (p) => {
progress = p;
});
stream.prependListener('request', (r) => req = r);
stream.prependListener('response', (r) => res = r);
stream.prependListener('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.prependListener('error', (e, b, r) => {
err = e;
res = r;
});
stream.prependListener('downloadProgress', (p) => {
progress = p;
});
stream.prependListener('uploadProgress', (p) => {
progress = p;
});
stream.prependOnceListener('request', (r) => req = r);
stream.prependOnceListener('response', (r) => res = r);
stream.prependOnceListener('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.prependOnceListener('error', (e, b, r) => {
err = e;
res = r;
});
stream.prependOnceListener('downloadProgress', (p) => {
progress = p;
});
stream.prependOnceListener('uploadProgress', (p) => {
progress = p;
});
stream.removeListener('request', (r) => req = r);
stream.removeListener('response', (r) => res = r);
stream.removeListener('redirect', (r, o) => {
res = r;
opts = o;
href = o.href;
});
stream.removeListener('error', (e, b, r) => {
err = e;
res = r;
});
stream.removeListener('downloadProgress', (p) => {
progress = p;
});
stream.removeListener('uploadProgress', (p) => {
progress = p;
});
got('google.com', {
headers: {
cookie: cookie.serialize('foo', 'bar')
}
});
const form = new FormData();
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
got.post('google.com', {
body: form
});
got('todomvc.com', {
headers: {
'user-agent': `my-module/ (https://github.com/username/my-module)`
}
});
got('https://httpbin.org/404')
.catch(err => err instanceof got.HTTPError && err.statusCode === 404);
got('todomvc', {
throwHttpErrors: false
});
got('todomvc', {
agent: {
http: new http.Agent(),
https: new https.Agent()
}
});
got('todomvc', {
cache: new Map(),
}).then(res => res.fromCache);
got('todomvc', {
cache: new Keyv(),
}).then(res => res.fromCache);
got('todomvc', {
cache: new QuickLRU({maxSize: 10}),
}).then(res => res.fromCache);
got(new url.URL('http://todomvc.com'));
got(url.parse('http://todomvc.com'));
got('https://todomvc.com', { rejectUnauthorized: false });
| magny/DefinitelyTyped | types/got/v8/got-tests.ts | TypeScript | mit | 7,199 |
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Sets up the tasks for default AI.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "stringregistry.h"
#include "ai_basenpc.h"
#include "ai_task.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
const char * g_ppszTaskFailureText[] =
{
"No failure", // NO_TASK_FAILURE
"No Target", // FAIL_NO_TARGET
"Weapon owned by someone else", // FAIL_WEAPON_OWNED
"Weapon/Item doesn't exist", // FAIL_ITEM_NO_FIND
"No hint node", // FAIL_NO_HINT_NODE
"Schedule not found", // FAIL_SCHEDULE_NOT_FOUND
"Don't have an enemy", // FAIL_NO_ENEMY
"Found no backaway node", // FAIL_NO_BACKAWAY_NODE
"Couldn't find cover", // FAIL_NO_COVER
"Couldn't find flank", // FAIL_NO_FLANK
"Couldn't find shoot position", // FAIL_NO_SHOOT
"Don't have a route", // FAIL_NO_ROUTE
"Don't have a route: no goal", // FAIL_NO_ROUTE_GOAL
"Don't have a route: blocked", // FAIL_NO_ROUTE_BLOCKED
"Don't have a route: illegal move", // FAIL_NO_ROUTE_ILLEGAL
"Couldn't walk to target", // FAIL_NO_WALK
"Node already locked", // FAIL_ALREADY_LOCKED
"No sound present", // FAIL_NO_SOUND
"No scent present", // FAIL_NO_SCENT
"Bad activity", // FAIL_BAD_ACTIVITY
"No goal entity", // FAIL_NO_GOAL
"No player", // FAIL_NO_PLAYER
"Can't reach any nodes", // FAIL_NO_REACHABLE_NODE
"No AI Network to Use", // FAIL_NO_AI_NETWORK
"Bad position to Target", // FAIL_BAD_POSITION
"Route Destination No Longer Valid", // FAIL_BAD_PATH_GOAL
"Stuck on top of something", // FAIL_STUCK_ONTOP
"Item has been taken", // FAIL_ITEM_TAKEN
};
const char *TaskFailureToString( AI_TaskFailureCode_t code )
{
const char *pszResult;
if ( code < 0 || code >= NUM_FAIL_CODES )
pszResult = (const char *)code;
else
pszResult = g_ppszTaskFailureText[code];
return pszResult;
}
//-----------------------------------------------------------------------------
// Purpose: Given and task name, return the task ID
//-----------------------------------------------------------------------------
int CAI_BaseNPC::GetTaskID(const char* taskName)
{
return GetSchedulingSymbols()->TaskSymbolToId( taskName );
}
//-----------------------------------------------------------------------------
// Purpose: Initialize the task name string registry
// Input :
// Output :
//-----------------------------------------------------------------------------
void CAI_BaseNPC::InitDefaultTaskSR(void)
{
#define ADD_DEF_TASK( name ) idSpace.AddTask(#name, name, "CAI_BaseNPC" )
CAI_ClassScheduleIdSpace &idSpace = CAI_BaseNPC::AccessClassScheduleIdSpaceDirect();
ADD_DEF_TASK( TASK_INVALID );
ADD_DEF_TASK( TASK_ANNOUNCE_ATTACK );
ADD_DEF_TASK( TASK_RESET_ACTIVITY );
ADD_DEF_TASK( TASK_WAIT );
ADD_DEF_TASK( TASK_WAIT_FACE_ENEMY );
ADD_DEF_TASK( TASK_WAIT_FACE_ENEMY_RANDOM );
ADD_DEF_TASK( TASK_WAIT_PVS );
ADD_DEF_TASK( TASK_SUGGEST_STATE );
ADD_DEF_TASK( TASK_TARGET_PLAYER );
ADD_DEF_TASK( TASK_SCRIPT_WALK_TO_TARGET );
ADD_DEF_TASK( TASK_SCRIPT_RUN_TO_TARGET );
ADD_DEF_TASK( TASK_SCRIPT_CUSTOM_MOVE_TO_TARGET );
ADD_DEF_TASK( TASK_MOVE_TO_TARGET_RANGE );
ADD_DEF_TASK( TASK_MOVE_TO_GOAL_RANGE );
ADD_DEF_TASK( TASK_MOVE_AWAY_PATH );
ADD_DEF_TASK( TASK_GET_PATH_AWAY_FROM_BEST_SOUND );
ADD_DEF_TASK( TASK_SET_GOAL );
ADD_DEF_TASK( TASK_GET_PATH_TO_GOAL );
ADD_DEF_TASK( TASK_GET_PATH_TO_ENEMY );
ADD_DEF_TASK( TASK_GET_PATH_TO_ENEMY_LKP );
ADD_DEF_TASK( TASK_GET_CHASE_PATH_TO_ENEMY );
ADD_DEF_TASK( TASK_GET_PATH_TO_ENEMY_LKP_LOS );
ADD_DEF_TASK( TASK_GET_PATH_TO_RANGE_ENEMY_LKP_LOS );
ADD_DEF_TASK( TASK_GET_PATH_TO_ENEMY_CORPSE );
ADD_DEF_TASK( TASK_GET_PATH_TO_PLAYER );
ADD_DEF_TASK( TASK_GET_PATH_TO_ENEMY_LOS );
ADD_DEF_TASK( TASK_GET_FLANK_ARC_PATH_TO_ENEMY_LOS );
ADD_DEF_TASK( TASK_GET_FLANK_RADIUS_PATH_TO_ENEMY_LOS );
ADD_DEF_TASK( TASK_GET_PATH_TO_TARGET );
ADD_DEF_TASK( TASK_GET_PATH_TO_TARGET_WEAPON );
ADD_DEF_TASK( TASK_CREATE_PENDING_WEAPON );
ADD_DEF_TASK( TASK_GET_PATH_TO_HINTNODE );
ADD_DEF_TASK( TASK_STORE_LASTPOSITION );
ADD_DEF_TASK( TASK_CLEAR_LASTPOSITION );
ADD_DEF_TASK( TASK_STORE_POSITION_IN_SAVEPOSITION );
ADD_DEF_TASK( TASK_STORE_BESTSOUND_IN_SAVEPOSITION );
ADD_DEF_TASK( TASK_STORE_BESTSOUND_REACTORIGIN_IN_SAVEPOSITION );
ADD_DEF_TASK( TASK_REACT_TO_COMBAT_SOUND );
ADD_DEF_TASK( TASK_STORE_ENEMY_POSITION_IN_SAVEPOSITION );
ADD_DEF_TASK( TASK_GET_PATH_TO_COMMAND_GOAL );
ADD_DEF_TASK( TASK_MARK_COMMAND_GOAL_POS );
ADD_DEF_TASK( TASK_CLEAR_COMMAND_GOAL );
ADD_DEF_TASK( TASK_GET_PATH_TO_LASTPOSITION );
ADD_DEF_TASK( TASK_GET_PATH_TO_SAVEPOSITION );
ADD_DEF_TASK( TASK_GET_PATH_TO_SAVEPOSITION_LOS );
ADD_DEF_TASK( TASK_GET_PATH_TO_BESTSOUND );
ADD_DEF_TASK( TASK_GET_PATH_TO_BESTSCENT );
ADD_DEF_TASK( TASK_GET_PATH_TO_RANDOM_NODE );
ADD_DEF_TASK( TASK_RUN_PATH );
ADD_DEF_TASK( TASK_WALK_PATH );
ADD_DEF_TASK( TASK_WALK_PATH_TIMED );
ADD_DEF_TASK( TASK_WALK_PATH_WITHIN_DIST );
ADD_DEF_TASK( TASK_RUN_PATH_WITHIN_DIST );
ADD_DEF_TASK( TASK_WALK_PATH_FOR_UNITS );
ADD_DEF_TASK( TASK_RUN_PATH_FOR_UNITS );
ADD_DEF_TASK( TASK_RUN_PATH_FLEE );
ADD_DEF_TASK( TASK_RUN_PATH_TIMED );
ADD_DEF_TASK( TASK_STRAFE_PATH );
ADD_DEF_TASK( TASK_CLEAR_MOVE_WAIT );
ADD_DEF_TASK( TASK_SMALL_FLINCH );
ADD_DEF_TASK( TASK_BIG_FLINCH );
ADD_DEF_TASK( TASK_DEFER_DODGE );
ADD_DEF_TASK( TASK_FACE_IDEAL );
ADD_DEF_TASK( TASK_FACE_REASONABLE );
ADD_DEF_TASK( TASK_FACE_PATH );
ADD_DEF_TASK( TASK_FACE_PLAYER );
ADD_DEF_TASK( TASK_FACE_ENEMY );
ADD_DEF_TASK( TASK_FACE_HINTNODE );
ADD_DEF_TASK( TASK_PLAY_HINT_ACTIVITY );
ADD_DEF_TASK( TASK_FACE_TARGET );
ADD_DEF_TASK( TASK_FACE_LASTPOSITION );
ADD_DEF_TASK( TASK_FACE_SAVEPOSITION );
ADD_DEF_TASK( TASK_FACE_AWAY_FROM_SAVEPOSITION );
ADD_DEF_TASK( TASK_SET_IDEAL_YAW_TO_CURRENT );
ADD_DEF_TASK( TASK_RANGE_ATTACK1 );
ADD_DEF_TASK( TASK_RANGE_ATTACK2 );
ADD_DEF_TASK( TASK_MELEE_ATTACK1 );
ADD_DEF_TASK( TASK_MELEE_ATTACK2 );
ADD_DEF_TASK( TASK_RELOAD );
ADD_DEF_TASK( TASK_SPECIAL_ATTACK1 );
ADD_DEF_TASK( TASK_SPECIAL_ATTACK2 );
ADD_DEF_TASK( TASK_FIND_HINTNODE );
ADD_DEF_TASK( TASK_CLEAR_HINTNODE );
ADD_DEF_TASK( TASK_FIND_LOCK_HINTNODE );
ADD_DEF_TASK( TASK_LOCK_HINTNODE );
ADD_DEF_TASK( TASK_SOUND_ANGRY );
ADD_DEF_TASK( TASK_SOUND_DEATH );
ADD_DEF_TASK( TASK_SOUND_IDLE );
ADD_DEF_TASK( TASK_SOUND_WAKE );
ADD_DEF_TASK( TASK_SOUND_PAIN );
ADD_DEF_TASK( TASK_SOUND_DIE );
ADD_DEF_TASK( TASK_SPEAK_SENTENCE );
ADD_DEF_TASK( TASK_WAIT_FOR_SPEAK_FINISH );
ADD_DEF_TASK( TASK_SET_ACTIVITY );
ADD_DEF_TASK( TASK_RANDOMIZE_FRAMERATE );
ADD_DEF_TASK( TASK_SET_SCHEDULE );
ADD_DEF_TASK( TASK_SET_FAIL_SCHEDULE );
ADD_DEF_TASK( TASK_SET_TOLERANCE_DISTANCE );
ADD_DEF_TASK( TASK_SET_ROUTE_SEARCH_TIME );
ADD_DEF_TASK( TASK_CLEAR_FAIL_SCHEDULE );
ADD_DEF_TASK( TASK_PLAY_SEQUENCE );
ADD_DEF_TASK( TASK_PLAY_PRIVATE_SEQUENCE );
ADD_DEF_TASK( TASK_PLAY_PRIVATE_SEQUENCE_FACE_ENEMY );
ADD_DEF_TASK( TASK_PLAY_SEQUENCE_FACE_ENEMY );
ADD_DEF_TASK( TASK_PLAY_SEQUENCE_FACE_TARGET );
ADD_DEF_TASK( TASK_FIND_COVER_FROM_BEST_SOUND );
ADD_DEF_TASK( TASK_FIND_COVER_FROM_ENEMY );
ADD_DEF_TASK( TASK_FIND_LATERAL_COVER_FROM_ENEMY );
ADD_DEF_TASK( TASK_FIND_BACKAWAY_FROM_SAVEPOSITION );
ADD_DEF_TASK( TASK_FIND_NODE_COVER_FROM_ENEMY );
ADD_DEF_TASK( TASK_FIND_NEAR_NODE_COVER_FROM_ENEMY );
ADD_DEF_TASK( TASK_FIND_FAR_NODE_COVER_FROM_ENEMY );
ADD_DEF_TASK( TASK_FIND_COVER_FROM_ORIGIN );
ADD_DEF_TASK( TASK_DIE );
ADD_DEF_TASK( TASK_WAIT_FOR_SCRIPT );
ADD_DEF_TASK( TASK_PUSH_SCRIPT_ARRIVAL_ACTIVITY );
ADD_DEF_TASK( TASK_PLAY_SCRIPT );
ADD_DEF_TASK( TASK_PLAY_SCRIPT_POST_IDLE );
ADD_DEF_TASK( TASK_ENABLE_SCRIPT );
ADD_DEF_TASK( TASK_PLANT_ON_SCRIPT );
ADD_DEF_TASK( TASK_FACE_SCRIPT );
ADD_DEF_TASK( TASK_PLAY_SCENE );
ADD_DEF_TASK( TASK_WAIT_RANDOM );
ADD_DEF_TASK( TASK_WAIT_INDEFINITE );
ADD_DEF_TASK( TASK_STOP_MOVING );
ADD_DEF_TASK( TASK_TURN_LEFT );
ADD_DEF_TASK( TASK_TURN_RIGHT );
ADD_DEF_TASK( TASK_REMEMBER );
ADD_DEF_TASK( TASK_FORGET );
ADD_DEF_TASK( TASK_WAIT_FOR_MOVEMENT );
ADD_DEF_TASK( TASK_WAIT_FOR_MOVEMENT_STEP );
ADD_DEF_TASK( TASK_WAIT_UNTIL_NO_DANGER_SOUND );
ADD_DEF_TASK( TASK_WEAPON_FIND );
ADD_DEF_TASK( TASK_WEAPON_PICKUP );
ADD_DEF_TASK( TASK_WEAPON_RUN_PATH );
ADD_DEF_TASK( TASK_WEAPON_CREATE );
ADD_DEF_TASK( TASK_ITEM_RUN_PATH );
ADD_DEF_TASK( TASK_ITEM_PICKUP );
ADD_DEF_TASK( TASK_USE_SMALL_HULL );
ADD_DEF_TASK( TASK_FALL_TO_GROUND );
ADD_DEF_TASK( TASK_WANDER );
ADD_DEF_TASK( TASK_FREEZE );
ADD_DEF_TASK( TASK_GATHER_CONDITIONS );
ADD_DEF_TASK( TASK_IGNORE_OLD_ENEMIES );
ADD_DEF_TASK( TASK_DEBUG_BREAK );
ADD_DEF_TASK( TASK_ADD_HEALTH );
ADD_DEF_TASK( TASK_GET_PATH_TO_INTERACTION_PARTNER );
ADD_DEF_TASK( TASK_PRE_SCRIPT );
}
| scen/ionlib | src/sdk/hl2_ob/game/server/ai_task.cpp | C++ | mit | 9,557 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_22) on Mon Dec 20 13:46:23 EST 2010 -->
<TITLE>
FileProvider (Apache Ant API)
</TITLE>
<META NAME="keywords" CONTENT="org.apache.tools.ant.types.resources.FileProvider interface">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="FileProvider (Apache Ant API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/tools/ant/types/resources/Difference.html" title="class in org.apache.tools.ant.types.resources"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/apache/tools/ant/types/resources/FileResource.html" title="class in org.apache.tools.ant.types.resources"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/tools/ant/types/resources/FileProvider.html" target="_top"><B>FRAMES</B></A>
<A HREF="FileProvider.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.tools.ant.types.resources</FONT>
<BR>
Interface FileProvider</H2>
<DL>
<DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../../../../org/apache/tools/ant/types/resources/FileResource.html" title="class in org.apache.tools.ant.types.resources">FileResource</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public interface <B>FileProvider</B></DL>
</PRE>
<P>
This is an interface that resources that can provide a file should implement.
This is a refactoring of <A HREF="../../../../../../org/apache/tools/ant/types/resources/FileResource.html" title="class in org.apache.tools.ant.types.resources"><CODE>FileResource</CODE></A>, to allow other resources
to act as sources of files (and to make components that only support
file-based resources from only support FileResource resources.
<P>
<P>
<DL>
<DT><B>Since:</B></DT>
<DD>Ant 1.8</DD>
</DL>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.io.File</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../org/apache/tools/ant/types/resources/FileProvider.html#getFile()">getFile</A></B>()</CODE>
<BR>
Get the file represented by this Resource.</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getFile()"><!-- --></A><H3>
getFile</H3>
<PRE>
java.io.File <B>getFile</B>()</PRE>
<DL>
<DD>Get the file represented by this Resource.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the file.</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../org/apache/tools/ant/types/resources/Difference.html" title="class in org.apache.tools.ant.types.resources"><B>PREV CLASS</B></A>
<A HREF="../../../../../../org/apache/tools/ant/types/resources/FileResource.html" title="class in org.apache.tools.ant.types.resources"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/tools/ant/types/resources/FileProvider.html" target="_top"><B>FRAMES</B></A>
<A HREF="FileProvider.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| jeroendesloovere/PhotoSwipe | tools/apache-ant-1.8.2/docs/manual/api/org/apache/tools/ant/types/resources/FileProvider.html | HTML | mit | 8,788 |
/* BFD backend for local host's a.out binaries
Copyright (C) 1990-2019 Free Software Foundation, Inc.
Written by Cygnus Support. Probably John Gilmore's fault.
This file is part of BFD, the Binary File Descriptor library.
This program 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 3 of the License, or
(at your option) any later version.
This program 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 program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#define ARCH_SIZE 32
/* When porting to a new system, you must supply:
HOST_PAGE_SIZE (optional)
HOST_SEGMENT_SIZE (optional -- defaults to page size)
HOST_MACHINE_ARCH (optional)
HOST_MACHINE_MACHINE (optional)
HOST_TEXT_START_ADDR (optional)
HOST_STACK_END_ADDR (not used, except by trad-core ???)
HOST_BIG_ENDIAN_P (required -- define if big-endian)
in the ./hosts/h-systemname.h file. */
#ifdef TRAD_HEADER
#include TRAD_HEADER
#endif
#ifdef HOST_PAGE_SIZE
#define TARGET_PAGE_SIZE HOST_PAGE_SIZE
#endif
#ifdef HOST_SEGMENT_SIZE
#define SEGMENT_SIZE HOST_SEGMENT_SIZE
#else
#define SEGMENT_SIZE TARGET_PAGE_SIZE
#endif
#ifdef HOST_TEXT_START_ADDR
#define TEXT_START_ADDR HOST_TEXT_START_ADDR
#endif
#ifdef HOST_STACK_END_ADDR
#define STACK_END_ADDR HOST_STACK_END_ADDR
#endif
#ifdef HOST_BIG_ENDIAN_P
#define TARGET_IS_BIG_ENDIAN_P
#else
#undef TARGET_IS_BIG_ENDIAN_P
#endif
#include "libaout.h" /* BFD a.out internal data structures */
#include "aout/aout64.h"
#ifdef HOST_MACHINE_ARCH
#ifdef HOST_MACHINE_MACHINE
#define SET_ARCH_MACH(abfd, execp) \
bfd_default_set_arch_mach(abfd, HOST_MACHINE_ARCH, HOST_MACHINE_MACHINE)
#else
#define SET_ARCH_MACH(abfd, execp) \
bfd_default_set_arch_mach(abfd, HOST_MACHINE_ARCH, 0)
#endif
#endif /* HOST_MACHINE_ARCH */
/* Do not "beautify" the CONCAT* macro args. Traditional C will not
remove whitespace added here, and thus will fail to concatenate
the tokens. */
#define MY(OP) CONCAT2 (host_aout_,OP)
#define TARGETNAME "a.out"
#include "aout-target.h"
| OpenSmalltalk/vm | processors/ARM/gdb-8.3.1/bfd/host-aout.c | C | mit | 2,572 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://genshi.edgewall.org/log/.
"""Basic support for evaluating XPath expressions against streams.
>>> from genshi.input import XML
>>> doc = XML('''<doc>
... <items count="4">
... <item status="new">
... <summary>Foo</summary>
... </item>
... <item status="closed">
... <summary>Bar</summary>
... </item>
... <item status="closed" resolution="invalid">
... <summary>Baz</summary>
... </item>
... <item status="closed" resolution="fixed">
... <summary>Waz</summary>
... </item>
... </items>
... </doc>''')
>>> print doc.select('items/item[@status="closed" and '
... '(@resolution="invalid" or not(@resolution))]/summary/text()')
BarBaz
Because the XPath engine operates on markup streams (as opposed to tree
structures), it only implements a subset of the full XPath 1.0 language.
"""
from math import ceil, floor
import operator
import re
from genshi.core import Stream, Attrs, Namespace, QName
from genshi.core import START, END, TEXT, START_NS, END_NS, COMMENT, PI, \
START_CDATA, END_CDATA
__all__ = ['Path', 'PathSyntaxError']
__docformat__ = 'restructuredtext en'
class Axis(object):
"""Defines constants for the various supported XPath axes."""
ATTRIBUTE = 'attribute'
CHILD = 'child'
DESCENDANT = 'descendant'
DESCENDANT_OR_SELF = 'descendant-or-self'
SELF = 'self'
def forname(cls, name):
"""Return the axis constant for the given name, or `None` if no such
axis was defined.
"""
return getattr(cls, name.upper().replace('-', '_'), None)
forname = classmethod(forname)
ATTRIBUTE = Axis.ATTRIBUTE
CHILD = Axis.CHILD
DESCENDANT = Axis.DESCENDANT
DESCENDANT_OR_SELF = Axis.DESCENDANT_OR_SELF
SELF = Axis.SELF
class Path(object):
"""Implements basic XPath support on streams.
Instances of this class represent a "compiled" XPath expression, and provide
methods for testing the path against a stream, as well as extracting a
substream matching that path.
"""
def __init__(self, text, filename=None, lineno=-1):
"""Create the path object from a string.
:param text: the path expression
:param filename: the name of the file in which the path expression was
found (used in error messages)
:param lineno: the line on which the expression was found
"""
self.source = text
self.paths = PathParser(text, filename, lineno).parse()
def __repr__(self):
paths = []
for path in self.paths:
steps = []
for axis, nodetest, predicates in path:
steps.append('%s::%s' % (axis, nodetest))
for predicate in predicates:
steps[-1] += '[%s]' % predicate
paths.append('/'.join(steps))
return '<%s "%s">' % (self.__class__.__name__, '|'.join(paths))
def select(self, stream, namespaces=None, variables=None):
"""Returns a substream of the given stream that matches the path.
If there are no matches, this method returns an empty stream.
>>> from genshi.input import XML
>>> xml = XML('<root><elem><child>Text</child></elem></root>')
>>> print Path('.//child').select(xml)
<child>Text</child>
>>> print Path('.//child/text()').select(xml)
Text
:param stream: the stream to select from
:param namespaces: (optional) a mapping of namespace prefixes to URIs
:param variables: (optional) a mapping of variable names to values
:return: the substream matching the path, or an empty stream
:rtype: `Stream`
"""
if namespaces is None:
namespaces = {}
if variables is None:
variables = {}
stream = iter(stream)
def _generate():
test = self.test()
for event in stream:
result = test(event, namespaces, variables)
if result is True:
yield event
if event[0] is START:
depth = 1
while depth > 0:
subevent = stream.next()
if subevent[0] is START:
depth += 1
elif subevent[0] is END:
depth -= 1
yield subevent
test(subevent, namespaces, variables,
updateonly=True)
elif result:
yield result
return Stream(_generate(),
serializer=getattr(stream, 'serializer', None))
def test(self, ignore_context=False):
"""Returns a function that can be used to track whether the path matches
a specific stream event.
The function returned expects the positional arguments ``event``,
``namespaces`` and ``variables``. The first is a stream event, while the
latter two are a mapping of namespace prefixes to URIs, and a mapping
of variable names to values, respectively. In addition, the function
accepts an ``updateonly`` keyword argument that default to ``False``. If
it is set to ``True``, the function only updates its internal state,
but does not perform any tests or return a result.
If the path matches the event, the function returns the match (for
example, a `START` or `TEXT` event.) Otherwise, it returns ``None``.
>>> from genshi.input import XML
>>> xml = XML('<root><elem><child id="1"/></elem><child id="2"/></root>')
>>> test = Path('child').test()
>>> for event in xml:
... if test(event, {}, {}):
... print event[0], repr(event[1])
START (QName(u'child'), Attrs([(QName(u'id'), u'2')]))
:param ignore_context: if `True`, the path is interpreted like a pattern
in XSLT, meaning for example that it will match
at any depth
:return: a function that can be used to test individual events in a
stream against the path
:rtype: ``function``
"""
paths = [(p, len(p), [0], [], [0] * len(p)) for p in [
(ignore_context and [_DOTSLASHSLASH] or []) + p for p in self.paths
]]
def _test(event, namespaces, variables, updateonly=False):
kind, data, pos = event[:3]
retval = None
for steps, size, cursors, cutoff, counter in paths:
# Manage the stack that tells us "where we are" in the stream
if kind is END:
if cursors:
cursors.pop()
continue
elif kind is START:
cursors.append(cursors and cursors[-1] or 0)
elif kind is START_NS or kind is END_NS \
or kind is START_CDATA or kind is END_CDATA:
continue
if updateonly or retval or not cursors:
continue
cursor = cursors[-1]
depth = len(cursors)
if cutoff and depth + int(kind is not START) > cutoff[0]:
continue
ctxtnode = not ignore_context and kind is START \
and depth == 2
matched = None
while 1:
# Fetch the next location step
axis, nodetest, predicates = steps[cursor]
# If this is the start event for the context node, and the
# axis of the location step doesn't include the current
# element, skip the test
if ctxtnode and (axis is CHILD or axis is DESCENDANT):
break
# Is this the last step of the location path?
last_step = cursor + 1 == size
# Perform the actual node test
matched = nodetest(kind, data, pos, namespaces, variables)
# The node test matched
if matched:
# Check all the predicates for this step
if predicates:
for predicate in predicates:
pretval = predicate(kind, data, pos, namespaces,
variables)
if type(pretval) is float: # FIXME <- need to
# check this for
# other types that
# can be coerced to
# float
counter[cursor] += 1
if counter[cursor] != int(pretval):
pretval = False
if not pretval:
matched = None
break
# Both the node test and the predicates matched
if matched:
if last_step:
if not ctxtnode or kind is not START \
or axis is ATTRIBUTE or axis is SELF:
retval = matched
elif not ctxtnode or axis is SELF \
or axis is DESCENDANT_OR_SELF:
cursor += 1
cursors[-1] = cursor
cutoff[:] = []
if kind is START:
if last_step and not (axis is DESCENDANT or
axis is DESCENDANT_OR_SELF):
cutoff[:] = [depth]
elif steps[cursor][0] is ATTRIBUTE:
# If the axis of the next location step is the
# attribute axis, we need to move on to processing
# that step without waiting for the next markup
# event
continue
# We're done with this step if it's the last step or the
# axis isn't "self"
if not matched or last_step or not (
axis is SELF or axis is DESCENDANT_OR_SELF):
break
if ctxtnode and axis is DESCENDANT_OR_SELF:
ctxtnode = False
if (retval or not matched) and kind is START and \
not (axis is DESCENDANT or axis is DESCENDANT_OR_SELF):
# If this step is not a closure, it cannot be matched until
# the current element is closed... so we need to move the
# cursor back to the previous closure and retest that
# against the current element
backsteps = [(i, k, d, p) for i, (k, d, p)
in enumerate(steps[:cursor])
if k is DESCENDANT or k is DESCENDANT_OR_SELF]
backsteps.reverse()
for cursor, axis, nodetest, predicates in backsteps:
if nodetest(kind, data, pos, namespaces, variables):
cutoff[:] = []
break
cursors[-1] = cursor
return retval
return _test
class PathSyntaxError(Exception):
"""Exception raised when an XPath expression is syntactically incorrect."""
def __init__(self, message, filename=None, lineno=-1, offset=-1):
if filename:
message = '%s (%s, line %d)' % (message, filename, lineno)
Exception.__init__(self, message)
self.filename = filename
self.lineno = lineno
self.offset = offset
class PathParser(object):
"""Tokenizes and parses an XPath expression."""
_QUOTES = (("'", "'"), ('"', '"'))
_TOKENS = ('::', ':', '..', '.', '//', '/', '[', ']', '()', '(', ')', '@',
'=', '!=', '!', '|', ',', '>=', '>', '<=', '<', '$')
_tokenize = re.compile('("[^"]*")|(\'[^\']*\')|((?:\d+)?\.\d+)|(%s)|([^%s\s]+)|\s+' % (
'|'.join([re.escape(t) for t in _TOKENS]),
''.join([re.escape(t[0]) for t in _TOKENS]))).findall
def __init__(self, text, filename=None, lineno=-1):
self.filename = filename
self.lineno = lineno
self.tokens = filter(None, [dqstr or sqstr or number or token or name
for dqstr, sqstr, number, token, name in
self._tokenize(text)])
self.pos = 0
# Tokenizer
at_end = property(lambda self: self.pos == len(self.tokens) - 1)
cur_token = property(lambda self: self.tokens[self.pos])
def next_token(self):
self.pos += 1
return self.tokens[self.pos]
def peek_token(self):
if not self.at_end:
return self.tokens[self.pos + 1]
return None
# Recursive descent parser
def parse(self):
"""Parses the XPath expression and returns a list of location path
tests.
For union expressions (such as `*|text()`), this function returns one
test for each operand in the union. For patch expressions that don't
use the union operator, the function always returns a list of size 1.
Each path test in turn is a sequence of tests that correspond to the
location steps, each tuples of the form `(axis, testfunc, predicates)`
"""
paths = [self._location_path()]
while self.cur_token == '|':
self.next_token()
paths.append(self._location_path())
if not self.at_end:
raise PathSyntaxError('Unexpected token %r after end of expression'
% self.cur_token, self.filename, self.lineno)
return paths
def _location_path(self):
steps = []
while True:
if self.cur_token.startswith('/'):
if self.cur_token == '//':
steps.append((DESCENDANT_OR_SELF, NodeTest(), []))
elif not steps:
raise PathSyntaxError('Absolute location paths not '
'supported', self.filename,
self.lineno)
self.next_token()
axis, nodetest, predicates = self._location_step()
if not axis:
axis = CHILD
steps.append((axis, nodetest, predicates))
if self.at_end or not self.cur_token.startswith('/'):
break
return steps
def _location_step(self):
if self.cur_token == '@':
axis = ATTRIBUTE
self.next_token()
elif self.cur_token == '.':
axis = SELF
elif self.cur_token == '..':
raise PathSyntaxError('Unsupported axis "parent"', self.filename,
self.lineno)
elif self.peek_token() == '::':
axis = Axis.forname(self.cur_token)
if axis is None:
raise PathSyntaxError('Unsupport axis "%s"' % axis,
self.filename, self.lineno)
self.next_token()
self.next_token()
else:
axis = None
nodetest = self._node_test(axis or CHILD)
predicates = []
while self.cur_token == '[':
predicates.append(self._predicate())
return axis, nodetest, predicates
def _node_test(self, axis=None):
test = prefix = None
next_token = self.peek_token()
if next_token in ('(', '()'): # Node type test
test = self._node_type()
elif next_token == ':': # Namespace prefix
prefix = self.cur_token
self.next_token()
localname = self.next_token()
if localname == '*':
test = QualifiedPrincipalTypeTest(axis, prefix)
else:
test = QualifiedNameTest(axis, prefix, localname)
else: # Name test
if self.cur_token == '*':
test = PrincipalTypeTest(axis)
elif self.cur_token == '.':
test = NodeTest()
else:
test = LocalNameTest(axis, self.cur_token)
if not self.at_end:
self.next_token()
return test
def _node_type(self):
name = self.cur_token
self.next_token()
args = []
if self.cur_token != '()':
# The processing-instruction() function optionally accepts the
# name of the PI as argument, which must be a literal string
self.next_token() # (
if self.cur_token != ')':
string = self.cur_token
if (string[0], string[-1]) in self._QUOTES:
string = string[1:-1]
args.append(string)
cls = _nodetest_map.get(name)
if not cls:
raise PathSyntaxError('%s() not allowed here' % name, self.filename,
self.lineno)
return cls(*args)
def _predicate(self):
assert self.cur_token == '['
self.next_token()
expr = self._or_expr()
if self.cur_token != ']':
raise PathSyntaxError('Expected "]" to close predicate, '
'but found "%s"' % self.cur_token,
self.filename, self.lineno)
if not self.at_end:
self.next_token()
return expr
def _or_expr(self):
expr = self._and_expr()
while self.cur_token == 'or':
self.next_token()
expr = OrOperator(expr, self._and_expr())
return expr
def _and_expr(self):
expr = self._equality_expr()
while self.cur_token == 'and':
self.next_token()
expr = AndOperator(expr, self._equality_expr())
return expr
def _equality_expr(self):
expr = self._relational_expr()
while self.cur_token in ('=', '!='):
op = _operator_map[self.cur_token]
self.next_token()
expr = op(expr, self._relational_expr())
return expr
def _relational_expr(self):
expr = self._sub_expr()
while self.cur_token in ('>', '>=', '<', '>='):
op = _operator_map[self.cur_token]
self.next_token()
expr = op(expr, self._sub_expr())
return expr
def _sub_expr(self):
token = self.cur_token
if token != '(':
return self._primary_expr()
self.next_token()
expr = self._or_expr()
if self.cur_token != ')':
raise PathSyntaxError('Expected ")" to close sub-expression, '
'but found "%s"' % self.cur_token,
self.filename, self.lineno)
self.next_token()
return expr
def _primary_expr(self):
token = self.cur_token
if len(token) > 1 and (token[0], token[-1]) in self._QUOTES:
self.next_token()
return StringLiteral(token[1:-1])
elif token[0].isdigit() or token[0] == '.':
self.next_token()
return NumberLiteral(as_float(token))
elif token == '$':
token = self.next_token()
self.next_token()
return VariableReference(token)
elif not self.at_end and self.peek_token().startswith('('):
return self._function_call()
else:
axis = None
if token == '@':
axis = ATTRIBUTE
self.next_token()
return self._node_test(axis)
def _function_call(self):
name = self.cur_token
if self.next_token() == '()':
args = []
else:
assert self.cur_token == '('
self.next_token()
args = [self._or_expr()]
while self.cur_token == ',':
self.next_token()
args.append(self._or_expr())
if not self.cur_token == ')':
raise PathSyntaxError('Expected ")" to close function argument '
'list, but found "%s"' % self.cur_token,
self.filename, self.lineno)
self.next_token()
cls = _function_map.get(name)
if not cls:
raise PathSyntaxError('Unsupported function "%s"' % name,
self.filename, self.lineno)
return cls(*args)
# Type coercion
def as_scalar(value):
"""Convert value to a scalar. If a single element Attrs() object is passed
the value of the single attribute will be returned."""
if isinstance(value, Attrs):
assert len(value) == 1
return value[0][1]
else:
return value
def as_float(value):
# FIXME - if value is a bool it will be coerced to 0.0 and consequently
# compared as a float. This is probably not ideal.
return float(as_scalar(value))
def as_long(value):
return long(as_scalar(value))
def as_string(value):
value = as_scalar(value)
if value is False:
return u''
return unicode(value)
def as_bool(value):
return bool(as_scalar(value))
# Node tests
class PrincipalTypeTest(object):
"""Node test that matches any event with the given principal type."""
__slots__ = ['principal_type']
def __init__(self, principal_type):
self.principal_type = principal_type
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
if self.principal_type is ATTRIBUTE:
return data[1] or None
else:
return True
def __repr__(self):
return '*'
class QualifiedPrincipalTypeTest(object):
"""Node test that matches any event with the given principal type in a
specific namespace."""
__slots__ = ['principal_type', 'prefix']
def __init__(self, principal_type, prefix):
self.principal_type = principal_type
self.prefix = prefix
def __call__(self, kind, data, pos, namespaces, variables):
namespace = Namespace(namespaces.get(self.prefix))
if kind is START:
if self.principal_type is ATTRIBUTE and data[1]:
return Attrs([(name, value) for name, value in data[1]
if name in namespace]) or None
else:
return data[0] in namespace
def __repr__(self):
return '%s:*' % self.prefix
class LocalNameTest(object):
"""Node test that matches any event with the given principal type and
local name.
"""
__slots__ = ['principal_type', 'name']
def __init__(self, principal_type, name):
self.principal_type = principal_type
self.name = name
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
if self.principal_type is ATTRIBUTE and self.name in data[1]:
return Attrs([(self.name, data[1].get(self.name))])
else:
return data[0].localname == self.name
def __repr__(self):
return self.name
class QualifiedNameTest(object):
"""Node test that matches any event with the given principal type and
qualified name.
"""
__slots__ = ['principal_type', 'prefix', 'name']
def __init__(self, principal_type, prefix, name):
self.principal_type = principal_type
self.prefix = prefix
self.name = name
def __call__(self, kind, data, pos, namespaces, variables):
qname = QName('%s}%s' % (namespaces.get(self.prefix), self.name))
if kind is START:
if self.principal_type is ATTRIBUTE and qname in data[1]:
return Attrs([(self.name, data[1].get(self.name))])
else:
return data[0] == qname
def __repr__(self):
return '%s:%s' % (self.prefix, self.name)
class CommentNodeTest(object):
"""Node test that matches any comment events."""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
return kind is COMMENT
def __repr__(self):
return 'comment()'
class NodeTest(object):
"""Node test that matches any node."""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
return True
return kind, data, pos
def __repr__(self):
return 'node()'
class ProcessingInstructionNodeTest(object):
"""Node test that matches any processing instruction event."""
__slots__ = ['target']
def __init__(self, target=None):
self.target = target
def __call__(self, kind, data, pos, namespaces, variables):
return kind is PI and (not self.target or data[0] == self.target)
def __repr__(self):
arg = ''
if self.target:
arg = '"' + self.target + '"'
return 'processing-instruction(%s)' % arg
class TextNodeTest(object):
"""Node test that matches any text event."""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
return kind is TEXT
def __repr__(self):
return 'text()'
_nodetest_map = {'comment': CommentNodeTest, 'node': NodeTest,
'processing-instruction': ProcessingInstructionNodeTest,
'text': TextNodeTest}
# Functions
class Function(object):
"""Base class for function nodes in XPath expressions."""
class BooleanFunction(Function):
"""The `boolean` function, which converts its argument to a boolean
value.
"""
__slots__ = ['expr']
def __init__(self, expr):
self.expr = expr
def __call__(self, kind, data, pos, namespaces, variables):
val = self.expr(kind, data, pos, namespaces, variables)
return as_bool(val)
def __repr__(self):
return 'boolean(%r)' % self.expr
class CeilingFunction(Function):
"""The `ceiling` function, which returns the nearest lower integer number
for the given number.
"""
__slots__ = ['number']
def __init__(self, number):
self.number = number
def __call__(self, kind, data, pos, namespaces, variables):
number = self.number(kind, data, pos, namespaces, variables)
return ceil(as_float(number))
def __repr__(self):
return 'ceiling(%r)' % self.number
class ConcatFunction(Function):
"""The `concat` function, which concatenates (joins) the variable number of
strings it gets as arguments.
"""
__slots__ = ['exprs']
def __init__(self, *exprs):
self.exprs = exprs
def __call__(self, kind, data, pos, namespaces, variables):
strings = []
for item in [expr(kind, data, pos, namespaces, variables)
for expr in self.exprs]:
strings.append(as_string(item))
return u''.join(strings)
def __repr__(self):
return 'concat(%s)' % ', '.join([repr(expr) for expr in self.exprs])
class ContainsFunction(Function):
"""The `contains` function, which returns whether a string contains a given
substring.
"""
__slots__ = ['string1', 'string2']
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def __call__(self, kind, data, pos, namespaces, variables):
string1 = self.string1(kind, data, pos, namespaces, variables)
string2 = self.string2(kind, data, pos, namespaces, variables)
return as_string(string2) in as_string(string1)
def __repr__(self):
return 'contains(%r, %r)' % (self.string1, self.string2)
class MatchesFunction(Function):
"""The `matches` function, which returns whether a string matches a regular
expression.
"""
__slots__ = ['string1', 'string2']
flag_mapping = {'s': re.S, 'm': re.M, 'i': re.I, 'x': re.X}
def __init__(self, string1, string2, flags=''):
self.string1 = string1
self.string2 = string2
self.flags = self._map_flags(flags)
def __call__(self, kind, data, pos, namespaces, variables):
string1 = as_string(self.string1(kind, data, pos, namespaces, variables))
string2 = as_string(self.string2(kind, data, pos, namespaces, variables))
return re.search(string2, string1, self.flags)
def _map_flags(self, flags):
return reduce(operator.or_,
[self.flag_map[flag] for flag in flags], re.U)
def __repr__(self):
return 'contains(%r, %r)' % (self.string1, self.string2)
class FalseFunction(Function):
"""The `false` function, which always returns the boolean `false` value."""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
return False
def __repr__(self):
return 'false()'
class FloorFunction(Function):
"""The `ceiling` function, which returns the nearest higher integer number
for the given number.
"""
__slots__ = ['number']
def __init__(self, number):
self.number = number
def __call__(self, kind, data, pos, namespaces, variables):
number = self.number(kind, data, pos, namespaces, variables)
return floor(as_float(number))
def __repr__(self):
return 'floor(%r)' % self.number
class LocalNameFunction(Function):
"""The `local-name` function, which returns the local name of the current
element.
"""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
return data[0].localname
def __repr__(self):
return 'local-name()'
class NameFunction(Function):
"""The `name` function, which returns the qualified name of the current
element.
"""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
return data[0]
def __repr__(self):
return 'name()'
class NamespaceUriFunction(Function):
"""The `namespace-uri` function, which returns the namespace URI of the
current element.
"""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
if kind is START:
return data[0].namespace
def __repr__(self):
return 'namespace-uri()'
class NotFunction(Function):
"""The `not` function, which returns the negated boolean value of its
argument.
"""
__slots__ = ['expr']
def __init__(self, expr):
self.expr = expr
def __call__(self, kind, data, pos, namespaces, variables):
return not as_bool(self.expr(kind, data, pos, namespaces, variables))
def __repr__(self):
return 'not(%s)' % self.expr
class NormalizeSpaceFunction(Function):
"""The `normalize-space` function, which removes leading and trailing
whitespace in the given string, and replaces multiple adjacent whitespace
characters inside the string with a single space.
"""
__slots__ = ['expr']
_normalize = re.compile(r'\s{2,}').sub
def __init__(self, expr):
self.expr = expr
def __call__(self, kind, data, pos, namespaces, variables):
string = self.expr(kind, data, pos, namespaces, variables)
return self._normalize(' ', as_string(string).strip())
def __repr__(self):
return 'normalize-space(%s)' % repr(self.expr)
class NumberFunction(Function):
"""The `number` function that converts its argument to a number."""
__slots__ = ['expr']
def __init__(self, expr):
self.expr = expr
def __call__(self, kind, data, pos, namespaces, variables):
val = self.expr(kind, data, pos, namespaces, variables)
return as_float(val)
def __repr__(self):
return 'number(%r)' % self.expr
class RoundFunction(Function):
"""The `round` function, which returns the nearest integer number for the
given number.
"""
__slots__ = ['number']
def __init__(self, number):
self.number = number
def __call__(self, kind, data, pos, namespaces, variables):
number = self.number(kind, data, pos, namespaces, variables)
return round(as_float(number))
def __repr__(self):
return 'round(%r)' % self.number
class StartsWithFunction(Function):
"""The `starts-with` function that returns whether one string starts with
a given substring.
"""
__slots__ = ['string1', 'string2']
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def __call__(self, kind, data, pos, namespaces, variables):
string1 = self.string1(kind, data, pos, namespaces, variables)
string2 = self.string2(kind, data, pos, namespaces, variables)
return as_string(string1).startswith(as_string(string2))
def __repr__(self):
return 'starts-with(%r, %r)' % (self.string1, self.string2)
class StringLengthFunction(Function):
"""The `string-length` function that returns the length of the given
string.
"""
__slots__ = ['expr']
def __init__(self, expr):
self.expr = expr
def __call__(self, kind, data, pos, namespaces, variables):
string = self.expr(kind, data, pos, namespaces, variables)
return len(as_string(string))
def __repr__(self):
return 'string-length(%r)' % self.expr
class SubstringFunction(Function):
"""The `substring` function that returns the part of a string that starts
at the given offset, and optionally limited to the given length.
"""
__slots__ = ['string', 'start', 'length']
def __init__(self, string, start, length=None):
self.string = string
self.start = start
self.length = length
def __call__(self, kind, data, pos, namespaces, variables):
string = self.string(kind, data, pos, namespaces, variables)
start = self.start(kind, data, pos, namespaces, variables)
length = 0
if self.length is not None:
length = self.length(kind, data, pos, namespaces, variables)
return string[as_long(start):len(as_string(string)) - as_long(length)]
def __repr__(self):
if self.length is not None:
return 'substring(%r, %r, %r)' % (self.string, self.start,
self.length)
else:
return 'substring(%r, %r)' % (self.string, self.start)
class SubstringAfterFunction(Function):
"""The `substring-after` function that returns the part of a string that
is found after the given substring.
"""
__slots__ = ['string1', 'string2']
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def __call__(self, kind, data, pos, namespaces, variables):
string1 = as_string(self.string1(kind, data, pos, namespaces, variables))
string2 = as_string(self.string2(kind, data, pos, namespaces, variables))
index = string1.find(string2)
if index >= 0:
return string1[index + len(string2):]
return u''
def __repr__(self):
return 'substring-after(%r, %r)' % (self.string1, self.string2)
class SubstringBeforeFunction(Function):
"""The `substring-before` function that returns the part of a string that
is found before the given substring.
"""
__slots__ = ['string1', 'string2']
def __init__(self, string1, string2):
self.string1 = string1
self.string2 = string2
def __call__(self, kind, data, pos, namespaces, variables):
string1 = as_string(self.string1(kind, data, pos, namespaces, variables))
string2 = as_string(self.string2(kind, data, pos, namespaces, variables))
index = string1.find(string2)
if index >= 0:
return string1[:index]
return u''
def __repr__(self):
return 'substring-after(%r, %r)' % (self.string1, self.string2)
class TranslateFunction(Function):
"""The `translate` function that translates a set of characters in a
string to target set of characters.
"""
__slots__ = ['string', 'fromchars', 'tochars']
def __init__(self, string, fromchars, tochars):
self.string = string
self.fromchars = fromchars
self.tochars = tochars
def __call__(self, kind, data, pos, namespaces, variables):
string = as_string(self.string(kind, data, pos, namespaces, variables))
fromchars = as_string(self.fromchars(kind, data, pos, namespaces, variables))
tochars = as_string(self.tochars(kind, data, pos, namespaces, variables))
table = dict(zip([ord(c) for c in fromchars],
[ord(c) for c in tochars]))
return string.translate(table)
def __repr__(self):
return 'translate(%r, %r, %r)' % (self.string, self.fromchars,
self.tochars)
class TrueFunction(Function):
"""The `true` function, which always returns the boolean `true` value."""
__slots__ = []
def __call__(self, kind, data, pos, namespaces, variables):
return True
def __repr__(self):
return 'true()'
_function_map = {'boolean': BooleanFunction, 'ceiling': CeilingFunction,
'concat': ConcatFunction, 'contains': ContainsFunction,
'matches': MatchesFunction, 'false': FalseFunction, 'floor':
FloorFunction, 'local-name': LocalNameFunction, 'name':
NameFunction, 'namespace-uri': NamespaceUriFunction,
'normalize-space': NormalizeSpaceFunction, 'not': NotFunction,
'number': NumberFunction, 'round': RoundFunction,
'starts-with': StartsWithFunction, 'string-length':
StringLengthFunction, 'substring': SubstringFunction,
'substring-after': SubstringAfterFunction, 'substring-before':
SubstringBeforeFunction, 'translate': TranslateFunction,
'true': TrueFunction}
# Literals & Variables
class Literal(object):
"""Abstract base class for literal nodes."""
class StringLiteral(Literal):
"""A string literal node."""
__slots__ = ['text']
def __init__(self, text):
self.text = text
def __call__(self, kind, data, pos, namespaces, variables):
return self.text
def __repr__(self):
return '"%s"' % self.text
class NumberLiteral(Literal):
"""A number literal node."""
__slots__ = ['number']
def __init__(self, number):
self.number = number
def __call__(self, kind, data, pos, namespaces, variables):
return self.number
def __repr__(self):
return str(self.number)
class VariableReference(Literal):
"""A variable reference node."""
__slots__ = ['name']
def __init__(self, name):
self.name = name
def __call__(self, kind, data, pos, namespaces, variables):
return variables.get(self.name)
def __repr__(self):
return str(self.name)
# Operators
class AndOperator(object):
"""The boolean operator `and`."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = as_bool(self.lval(kind, data, pos, namespaces, variables))
if not lval:
return False
rval = self.rval(kind, data, pos, namespaces, variables)
return as_bool(rval)
def __repr__(self):
return '%s and %s' % (self.lval, self.rval)
class EqualsOperator(object):
"""The equality operator `=`."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = as_scalar(self.lval(kind, data, pos, namespaces, variables))
rval = as_scalar(self.rval(kind, data, pos, namespaces, variables))
return lval == rval
def __repr__(self):
return '%s=%s' % (self.lval, self.rval)
class NotEqualsOperator(object):
"""The equality operator `!=`."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = as_scalar(self.lval(kind, data, pos, namespaces, variables))
rval = as_scalar(self.rval(kind, data, pos, namespaces, variables))
return lval != rval
def __repr__(self):
return '%s!=%s' % (self.lval, self.rval)
class OrOperator(object):
"""The boolean operator `or`."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = as_bool(self.lval(kind, data, pos, namespaces, variables))
if lval:
return True
rval = self.rval(kind, data, pos, namespaces, variables)
return as_bool(rval)
def __repr__(self):
return '%s or %s' % (self.lval, self.rval)
class GreaterThanOperator(object):
"""The relational operator `>` (greater than)."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = self.lval(kind, data, pos, namespaces, variables)
rval = self.rval(kind, data, pos, namespaces, variables)
return as_float(lval) > as_float(rval)
def __repr__(self):
return '%s>%s' % (self.lval, self.rval)
class GreaterThanOrEqualOperator(object):
"""The relational operator `>=` (greater than or equal)."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = self.lval(kind, data, pos, namespaces, variables)
rval = self.rval(kind, data, pos, namespaces, variables)
return as_float(lval) >= as_float(rval)
def __repr__(self):
return '%s>=%s' % (self.lval, self.rval)
class LessThanOperator(object):
"""The relational operator `<` (less than)."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = self.lval(kind, data, pos, namespaces, variables)
rval = self.rval(kind, data, pos, namespaces, variables)
return as_float(lval) < as_float(rval)
def __repr__(self):
return '%s<%s' % (self.lval, self.rval)
class LessThanOrEqualOperator(object):
"""The relational operator `<=` (less than or equal)."""
__slots__ = ['lval', 'rval']
def __init__(self, lval, rval):
self.lval = lval
self.rval = rval
def __call__(self, kind, data, pos, namespaces, variables):
lval = self.lval(kind, data, pos, namespaces, variables)
rval = self.rval(kind, data, pos, namespaces, variables)
return as_float(lval) <= as_float(rval)
def __repr__(self):
return '%s<=%s' % (self.lval, self.rval)
_operator_map = {'=': EqualsOperator, '!=': NotEqualsOperator,
'>': GreaterThanOperator, '>=': GreaterThanOrEqualOperator,
'<': LessThanOperator, '>=': LessThanOrEqualOperator}
_DOTSLASHSLASH = (DESCENDANT_OR_SELF, PrincipalTypeTest(None), ())
| pombreda/django-hotclub | libs/external_libs/Genshi-0.5.1/genshi/path.py | Python | mit | 44,732 |
<?php
/*
* @package s9e\TextFormatter
* @copyright Copyright (c) 2010-2016 The s9e Authors
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
namespace s9e\TextFormatter\Plugins\Escaper;
use s9e\TextFormatter\Plugins\ConfiguratorBase;
class Configurator extends ConfiguratorBase
{
protected $quickMatch = '\\';
protected $regexp;
protected $tagName = 'ESC';
public function escapeAll($bool = \true)
{
$this->regexp = ($bool) ? '/\\\\./su' : '/\\\\[-!#()*+.:<>@[\\\\\\]^_`{}]/';
}
protected function setUp()
{
$this->escapeAll(\false);
$tag = $this->configurator->tags->add($this->tagName);
$tag->rules->disableAutoLineBreaks();
$tag->rules->ignoreTags();
$tag->rules->preventLineBreaks();
$tag->template = '<xsl:apply-templates/>';
}
} | namjoker/flarumfull | vendor/s9e/text-formatter/src/Plugins/Escaper/Configurator.php | PHP | mit | 793 |
package org.knowm.xchange.examples.anx.v2.trade;
import java.io.IOException;
import java.math.BigDecimal;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.trade.LimitOrder;
import org.knowm.xchange.dto.trade.OpenOrders;
import org.knowm.xchange.examples.anx.v2.ANXExamplesUtils;
import org.knowm.xchange.service.trade.TradeService;
/** Test placing a limit order at ANX */
public class LimitOrderDemo {
public static void main(String[] args) throws IOException {
Exchange anx = ANXExamplesUtils.createExchange();
// Interested in the private trading functionality (authentication)
TradeService tradeService = anx.getTradeService();
// place a limit order for a random amount of BTC at USD 1.25
OrderType orderType = (OrderType.ASK);
BigDecimal tradeableAmount = new BigDecimal("2");
BigDecimal limitPrice = new BigDecimal("921");
LimitOrder limitOrder =
new LimitOrder(orderType, tradeableAmount, CurrencyPair.BTC_USD, "", null, limitPrice);
String orderID = tradeService.placeLimitOrder(limitOrder);
System.out.println("Limit Order ID: " + orderID);
// get open orders
OpenOrders openOrders = tradeService.getOpenOrders();
for (LimitOrder openOrder : openOrders.getOpenOrders()) {
System.out.println(openOrder.toString());
}
}
}
| TSavo/XChange | xchange-examples/src/main/java/org/knowm/xchange/examples/anx/v2/trade/LimitOrderDemo.java | Java | mit | 1,422 |
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'vendor/angular/angular.js',
'vendor/angular-mocks/angular-mocks.js',
'src/**/*.js',
'tests/**/*.spec.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
| balderdashy/angularSails | karma.conf.js | JavaScript | mit | 1,218 |
package gateway
import (
"net"
"time"
"github.com/NebulousLabs/Sia/modules"
)
// peerConn is a simple type that implements the modules.PeerConn interface.
type peerConn struct {
net.Conn
dialbackAddr modules.NetAddress
}
// RPCAddr implements the RPCAddr method of the modules.PeerConn interface. It
// is the address that identifies a peer.
func (pc peerConn) RPCAddr() modules.NetAddress {
return pc.dialbackAddr
}
// dial will dial the input address and return a connection. dial appropriately
// handles things like clean shutdown, fast shutdown, and chooses the correct
// communication protocol.
func (g *Gateway) dial(addr modules.NetAddress) (net.Conn, error) {
dialer := &net.Dialer{
Cancel: g.threads.StopChan(),
Timeout: dialTimeout,
}
conn, err := dialer.Dial("tcp", string(addr))
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(connStdDeadline))
return conn, nil
}
| MrStrong/Sia | modules/gateway/conn.go | GO | mit | 921 |
from coalib.bears.GlobalBear import GlobalBear
from coalib.results.Result import Result
from dependency_management.requirements.PipRequirement import PipRequirement
from vulture import Vulture
def _find_unused_code(filenames):
"""
:param filenames: List of filenames to check.
:return: Generator of Result objects.
"""
vulture = Vulture()
vulture.scavenge(filenames)
for item in vulture.get_unused_code():
yield Result.from_values(origin='VultureBear',
message=item.message,
file=item.filename,
line=item.first_lineno,
end_line=item.last_lineno,
confidence=item.confidence)
class VultureBear(GlobalBear):
LANGUAGES = {'Python', 'Python 3'}
REQUIREMENTS = {PipRequirement('vulture', '0.25.0')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'[email protected]'}
LICENSE = 'AGPL-3.0'
ASCIINEMA_URL = 'https://asciinema.org/a/82256'
CAN_DETECT = {'Unused Code'}
SEE_MORE = 'https://github.com/jendrikseipp/vulture'
def run(self):
"""
Check Python code for unused variables and functions using `vulture`.
"""
filenames = list(self.file_dict.keys())
return _find_unused_code(filenames)
| IPMITMO/statan | coala-bears/bears/python/VultureBear.py | Python | mit | 1,380 |
/*
* Copyright 2011 Red Hat, Inc. and/or its affiliates.
*
* 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 org.drools.workbench.models.guided.dtable.shared.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.drools.workbench.models.datamodel.workitems.PortableParameterDefinition;
import org.drools.workbench.models.datamodel.workitems.PortableWorkDefinition;
/**
* A column representing the execution of a Work Item.
*/
public class ActionWorkItemCol52 extends ActionCol52 {
private static final long serialVersionUID = 540l;
private PortableWorkDefinition workItemDefinition;
/**
* Available fields for this type of column.
*/
public static final String FIELD_WORKITEM_DEFINITION_NAME = "workItemDefinitionName";
public static final String FIELD_WORKITEM_DEFINITION_PARAMETER_NAME = "workItemDefinitionParameterName";
public static final String FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE = "workItemDefinitionParameterValue";
@Override
public List<BaseColumnFieldDiff> diff( BaseColumn otherColumn ) {
if ( otherColumn == null ) {
return null;
}
List<BaseColumnFieldDiff> result = super.diff( otherColumn );
ActionWorkItemCol52 other = (ActionWorkItemCol52) otherColumn;
// Field: Work Item definition.
final PortableWorkDefinition thisDefinition = this.getWorkItemDefinition();
final PortableWorkDefinition otherDefinition = other.getWorkItemDefinition();
//Determine diffs between "this" WorkItemDefinition and the "other" WorkItemDefinition
//If both are null there are no changes; if however one is null and the other is not
//then the WorkItemDefinition has effectively been added or deleted. Otherwise look
//for differences between the two WorkItemDefinitions
if ( thisDefinition == null && otherDefinition == null ) {
return result;
} else if ( thisDefinition != null && otherDefinition == null ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_NAME,
thisDefinition.getName(),
null ) );
for ( PortableParameterDefinition parameter : thisDefinition.getParameters() ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_NAME,
parameter.getName(),
null ) );
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
parameter.asString(),
null ) );
}
} else if ( thisDefinition == null && otherDefinition != null ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_NAME,
null,
otherDefinition.getName() ) );
for ( PortableParameterDefinition parameter : otherDefinition.getParameters() ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_NAME,
null,
parameter.getName() ) );
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
null,
parameter.asString() ) );
}
} else {
if ( !thisDefinition.getName().equals( otherDefinition.getName() ) ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_NAME,
thisDefinition.getName(),
otherDefinition.getName() ) );
}
final List<String> thisDefinitionParameterNames = Arrays.asList( thisDefinition.getParameterNames() );
final List<String> otherDefinitionParameterNames = Arrays.asList( otherDefinition.getParameterNames() );
//Some Parameters have been deleted
final List<String> parameterNamesDeleted = new ArrayList<String>( thisDefinitionParameterNames );
parameterNamesDeleted.removeAll( otherDefinitionParameterNames );
for ( String parameterName : parameterNamesDeleted ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_NAME,
thisDefinition.getParameter( parameterName ).getName(),
null ) );
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
thisDefinition.getParameter( parameterName ).asString(),
null ) );
}
//Some Parameters have been added
final List<String> parameterNamesAdded = new ArrayList<String>( otherDefinitionParameterNames );
parameterNamesAdded.removeAll( thisDefinitionParameterNames );
for ( String parameterName : parameterNamesAdded ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_NAME,
null,
otherDefinition.getParameter( parameterName ).getName() ) );
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
null,
otherDefinition.getParameter( parameterName ).asString() ) );
}
//Some Parameters have been updated
final List<String> parameterNamesUpdated = new ArrayList<String>( thisDefinitionParameterNames );
parameterNamesUpdated.retainAll( otherDefinitionParameterNames );
for ( String parameterName : parameterNamesUpdated ) {
boolean parameterNamesDiffer = false;
if ( !isEqualOrNull( thisDefinition.getParameter( parameterName ).getName(),
otherDefinition.getParameter( parameterName ).getName() ) ) {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_NAME,
thisDefinition.getParameter( parameterName ).getName(),
otherDefinition.getParameter( parameterName ).getName() ) );
parameterNamesDiffer = true;
}
if ( !isEqualOrNull( thisDefinition.getParameter( parameterName ).asString(),
otherDefinition.getParameter( parameterName ).asString() ) ) {
if ( !parameterNamesDiffer ) {
result.add( new WorkItemColumnParameterValueDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
thisDefinition.getParameter( parameterName ).getName(),
thisDefinition.getParameter( parameterName ).asString(),
otherDefinition.getParameter( parameterName ).asString() ) );
} else {
result.add( new BaseColumnFieldDiffImpl( FIELD_WORKITEM_DEFINITION_PARAMETER_VALUE,
thisDefinition.getParameter( parameterName ).asString(),
otherDefinition.getParameter( parameterName ).asString() ) );
}
}
}
}
return result;
}
public PortableWorkDefinition getWorkItemDefinition() {
return workItemDefinition;
}
public void setWorkItemDefinition( PortableWorkDefinition workItemDefinition ) {
this.workItemDefinition = workItemDefinition;
}
}
| rokn/Count_Words_2015 | testing/drools-master/drools-workbench-models/drools-workbench-models-guided-dtable/src/main/java/org/drools/workbench/models/guided/dtable/shared/model/ActionWorkItemCol52.java | Java | mit | 9,102 |
# Getting Started
This is a getting started guide. | polmiro/raml-ruby-parser | spec/fixtures/gettingstarted.md | Markdown | mit | 51 |
import './baseWidget.html';
import './baseWidget';
import './oembedImageWidget.html';
import './oembedImageWidget';
import './oembedAudioWidget.html';
import './oembedVideoWidget.html';
import './oembedVideoWidget';
import './oembedYoutubeWidget.html';
import './oembedUrlWidget.html';
import './oembedUrlWidget';
import './oembedFrameWidget.html';
| Sing-Li/Rocket.Chat | app/oembed/client/index.js | JavaScript | mit | 349 |
/**
* @license Highcharts JS v6.1.0 (2018-04-13)
*
* Bullet graph series type for Highcharts
*
* (c) 2010-2017 Kacper Madej
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function (Highcharts) {
(function (H) {
/**
* (c) 2010-2017 Kacper Madej
*
* License: www.highcharts.com/license
*/
var each = H.each,
pick = H.pick,
isNumber = H.isNumber,
relativeLength = H.relativeLength,
seriesType = H.seriesType,
columnProto = H.seriesTypes.column.prototype;
/**
* The bullet series type.
*
* @constructor seriesTypes.bullet
* @augments seriesTypes.column
*/
seriesType('bullet', 'column',
/**
* A bullet graph is a variation of a bar graph. The bullet graph features
* a single measure, compares it to a target, and displays it in the context
* of qualitative ranges of performance that could be set using
* [plotBands](#yAxis.plotBands) on [yAxis](#yAxis).
*
* @extends {plotOptions.column}
* @product highcharts
* @sample {highcharts} highcharts/demo/bullet-graph/ Bullet graph
* @since 6.0.0
* @excluding allAreas,boostThreshold,colorAxis,compare,compareBase
* @optionparent plotOptions.bullet
*/
{
/**
* All options related with look and positiong of targets.
*
* @sample {highcharts} highcharts/plotoptions/bullet-targetoptions/
* Target options
*
* @type {Object}
* @since 6.0.0
* @product highcharts
*/
targetOptions: {
/**
* The width of the rectangle representing the target. Could be set
* as a pixel value or as a percentage of a column width.
*
* @type {Number|String}
* @since 6.0.0
* @product highcharts
*/
width: '140%',
/**
* The height of the rectangle representing the target.
*
* @since 6.0.0
* @product highcharts
*/
height: 3
},
tooltip: {
pointFormat: '' + // eslint-disable-line no-dupe-keys
'<span class="highcharts-color-{point.colorIndex}">' +
'\u25CF</span> {series.name}: ' +
'<span class="highcharts-strong">{point.y}</span>. ' +
'Target: <span class="highcharts-strong">' +
'{point.target}</span><br/>'
}
}, {
pointArrayMap: ['y', 'target'],
parallelArrays: ['x', 'y', 'target'],
/**
* Draws the targets. For inverted chart, the `series.group` is rotated,
* so the same coordinates apply. This method is based on
* column series drawPoints function.
*/
drawPoints: function () {
var series = this,
chart = series.chart,
options = series.options,
animationLimit = options.animationLimit || 250;
columnProto.drawPoints.apply(this);
each(series.points, function (point) {
var pointOptions = point.options,
shapeArgs,
targetGraphic = point.targetGraphic,
targetShapeArgs,
targetVal = point.target,
pointVal = point.y,
width,
height,
targetOptions,
y;
if (isNumber(targetVal) && targetVal !== null) {
targetOptions = H.merge(
options.targetOptions,
pointOptions.targetOptions
);
height = targetOptions.height;
shapeArgs = point.shapeArgs;
width = relativeLength(
targetOptions.width,
shapeArgs.width
);
y = series.yAxis.translate(
targetVal,
false,
true,
false,
true
) - targetOptions.height / 2 - 0.5;
targetShapeArgs = series.crispCol.apply({
// Use fake series object to set borderWidth of target
chart: chart,
borderWidth: targetOptions.borderWidth,
options: {
crisp: options.crisp
}
}, [
shapeArgs.x + shapeArgs.width / 2 - width / 2,
y,
width,
height
]);
if (targetGraphic) {
// Update
targetGraphic[
chart.pointCount < animationLimit ?
'animate' :
'attr'
](targetShapeArgs);
// Add or remove tooltip reference
if (isNumber(pointVal) && pointVal !== null) {
targetGraphic.element.point = point;
} else {
targetGraphic.element.point = undefined;
}
} else {
point.targetGraphic = targetGraphic = chart.renderer
.rect()
.attr(targetShapeArgs)
.add(series.group);
}
// Add tooltip reference
if (isNumber(pointVal) && pointVal !== null) {
targetGraphic.element.point = point;
}
targetGraphic.addClass(point.getClassName() +
' highcharts-bullet-target', true);
} else if (targetGraphic) {
point.targetGraphic = targetGraphic.destroy(); // #1269
}
});
},
/**
* Includes target values to extend extremes from y values.
*/
getExtremes: function (yData) {
var series = this,
targetData = series.targetData,
yMax,
yMin;
columnProto.getExtremes.call(this, yData);
if (targetData && targetData.length) {
yMax = series.dataMax;
yMin = series.dataMin;
columnProto.getExtremes.call(this, targetData);
series.dataMax = Math.max(series.dataMax, yMax);
series.dataMin = Math.min(series.dataMin, yMin);
}
}
}, /** @lends seriesTypes.ohlc.prototype.pointClass.prototype */ {
/**
* Destroys target graphic.
*/
destroy: function () {
if (this.targetGraphic) {
this.targetGraphic = this.targetGraphic.destroy();
}
columnProto.pointClass.prototype.destroy.apply(this, arguments);
}
});
/**
* A `bullet` series. If the [type](#series.bullet.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @type {Object}
* @since 6.0.0
* @extends series,plotOptions.bullet
* @excluding dataParser,dataURL,marker
* @product highcharts
* @apioption series.bullet
*/
/**
* An array of data points for the series. For the `bullet` series type,
* points can be given in the following ways:
*
* 1. An array of arrays with 3 or 2 values. In this case, the values
* correspond to `x,y,target`. If the first value is a string,
* it is applied as the name of the point, and the `x` value is inferred.
* The `x` value can also be omitted, in which case the inner arrays
* should be of length 2\. Then the `x` value is automatically calculated,
* either starting at 0 and incremented by 1, or from `pointStart`
* and `pointInterval` given in the series options.
*
* ```js
* data: [
* [0, 40, 75],
* [1, 50, 50],
* [2, 60, 40]
* ]
* ```
*
* 2. An array of objects with named values. The objects are point
* configuration objects as seen below. If the total number of data
* points exceeds the series' [turboThreshold](#series.bullet.turboThreshold),
* this option is not available.
*
* ```js
* data: [{
* x: 0,
* y: 40,
* target: 75,
* name: "Point1",
* color: "#00FF00"
* }, {
* x: 1,
* y: 60,
* target: 40,
* name: "Point2",
* color: "#FF00FF"
* }]
* ```
*
* @type {Array<Object|Array>}
* @since 6.0.0
* @extends series.column.data
* @product highcharts
* @apioption series.bullet.data
*/
/**
* The target value of a point.
*
* @type {Number}
* @since 6.0.0
* @product highcharts
* @apioption series.bullet.data.target
*/
/**
* Individual target options for each point.
*
* @extends plotOptions.bullet.targetOptions
* @product highcharts
* @apioption series.bullet.data.targetOptions
*/
/**
* @excluding halo,lineWidth,lineWidthPlus,marker
* @product highcharts highstock
* @apioption series.bullet.states.hover
*/
/**
* @excluding halo,lineWidth,lineWidthPlus,marker
* @product highcharts highstock
* @apioption series.bullet.states.select
*/
}(Highcharts));
}));
| jonobr1/cdnjs | ajax/libs/highcharts/6.1.0/js/modules/bullet.src.js | JavaScript | mit | 10,355 |
<!DOCTYPE html>
<!--Reference:
SSAO algo: http://devlog-martinsh.blogspot.tw/2011/12/ssao-shader-update-v12.html?showComment=1398158188712#c1563204765906693531
log depth http://outerra.blogspot.tw/2013/07/logarithmic-depth-buffer-optimizations.html
convert the exponential depth to a linear value: http://www.ozone3d.net/blogs/lab/20090206/how-to-linearize-the-depth-value/
Spiral sampling http://web.archive.org/web/20120421191837/http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere-->
<html lang="en">
<head>
<title>three.js webgl - postprocessing - Screen Space Ambient Occlusion</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
background-color: #000000;
margin: 0px;
overflow: hidden;
font-family:Monospace;
font-size:13px;
text-align:center;
font-weight: bold;
}
a {
color:#00ff78;
}
#info {
color: #fff;
position: absolute;
top: 0px;
width: 100%;
padding: 5px;
}
.dg.ac {
z-index: 1 !important; /* FIX DAT.GUI */
}
</style>
</head>
<body>
<script src="../build/three.js"></script>
<script src="js/shaders/SSAOShader.js"></script>
<script src="js/shaders/CopyShader.js"></script>
<script src="js/postprocessing/EffectComposer.js"></script>
<script src="js/postprocessing/RenderPass.js"></script>
<script src="js/postprocessing/ShaderPass.js"></script>
<script src="js/postprocessing/MaskPass.js"></script>
<script src="js/postprocessing/SSAOPass.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src='js/libs/dat.gui.min.js'></script>
<div id="info">
<a href="http://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl screen space ambient occlusion example<br/>
shader by <a href="http://alteredqualia.com">alteredq</a>
</div>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer;
var effectComposer;
var ssaoPass;
var group;
var postprocessing = { enabled: true, onlyAO: false, radius: 32, aoClamp: 0.25, lumInfluence: 0.7 };
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 100, 700 );
camera.position.z = 500;
scene = new THREE.Scene();
scene.background = new THREE.Color( 0xa0a0a0 );
group = new THREE.Object3D();
scene.add( group );
var geometry = new THREE.BoxGeometry( 10, 10, 10 );
for ( var i = 0; i < 200; i ++ ) {
var material = new THREE.MeshBasicMaterial();
material.color.r = Math.random();
material.color.g = Math.random();
material.color.b = Math.random();
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = Math.random() * 400 - 200;
mesh.position.y = Math.random() * 400 - 200;
mesh.position.z = Math.random() * 400 - 200;
mesh.rotation.x = Math.random();
mesh.rotation.y = Math.random();
mesh.rotation.z = Math.random();
mesh.scale.x = mesh.scale.y = mesh.scale.z = Math.random() * 10 + 1;
group.add( mesh );
}
stats = new Stats();
container.appendChild( stats.dom );
// Init postprocessing
initPostprocessing();
// Init gui
var gui = new dat.GUI();
gui.add( postprocessing, 'enabled' );
gui.add( postprocessing, 'onlyAO', false ).onChange( function( value ) { ssaoPass.onlyAO = value; } );
gui.add( postprocessing, 'radius' ).min( 0 ).max( 64 ).onChange( function( value ) { ssaoPass.radius = value; } );
gui.add( postprocessing, 'aoClamp' ).min( 0 ).max( 1 ).onChange( function( value ) { ssaoPass.aoClamp = value; } );
gui.add( postprocessing, 'lumInfluence' ).min( 0 ).max( 1 ).onChange( function( value ) { ssaoPass.lumInfluence = value; } );
window.addEventListener( 'resize', onWindowResize, false );
onWindowResize();
}
function onWindowResize() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
// Resize renderTargets
ssaoPass.setSize( width, height );
var pixelRatio = renderer.getPixelRatio();
var newWidth = Math.floor( width / pixelRatio ) || 1;
var newHeight = Math.floor( height / pixelRatio ) || 1;
effectComposer.setSize( newWidth, newHeight );
}
function initPostprocessing() {
// Setup render pass
var renderPass = new THREE.RenderPass( scene, camera );
// Setup SSAO pass
ssaoPass = new THREE.SSAOPass( scene, camera );
ssaoPass.renderToScreen = true;
// Add pass to effect composer
effectComposer = new THREE.EffectComposer( renderer );
effectComposer.addPass( renderPass );
effectComposer.addPass( ssaoPass );
}
function animate() {
requestAnimationFrame( animate );
stats.begin();
render();
stats.end();
}
function render() {
var timer = performance.now();
group.rotation.x = timer * 0.0002;
group.rotation.y = timer * 0.0001;
if ( postprocessing.enabled ) {
effectComposer.render();
} else {
renderer.render( scene, camera );
}
}
</script>
</body>
</html>
| googlecreativelab/three.js | examples/webgl_postprocessing_ssao.html | HTML | mit | 5,672 |
require 'librarian/dsl'
require 'librarian/chef/source'
module Librarian
module Chef
class Dsl < Librarian::Dsl
dependency :cookbook
source :site => Source::Site
source :git => Source::Git
source :github => Source::Github
source :path => Source::Path
end
end
end
| outsmartin/ispconfig3 | vendor/bundler/ruby/2.0.0/gems/librarian-0.0.26/lib/librarian/chef/dsl.rb | Ruby | mit | 308 |
import express = require('express');
import expressEnforcesSsl = require('express-enforces-ssl');
let app: express.Express = express();
app.use(expressEnforcesSsl());
| isman-usoh/DefinitelyTyped | types/express-enforces-ssl/express-enforces-ssl-tests.ts | TypeScript | mit | 169 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import copy
import os
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.staticfiles.storage import staticfiles_storage
import mistune
from .utils.emoji import emojis
User = get_user_model()
class InlineGrammar(mistune.InlineGrammar):
emoji = re.compile(
r'^:(?P<emoji>[A-Za-z0-9_\-\+]+?):'
)
mention = re.compile(
r'^@(?P<username>[\w.@+-]+)',
flags=re.UNICODE
)
# Override
def hard_wrap(self):
# Adds ":" and "@" as a valid text character, so we can match emojis and mentions.
self.linebreak = re.compile(r'^ *\n(?!\s*$)')
self.text = re.compile(
r'^[\s\S]+?(?=[\\<!\[_*`:@~]|https?://| *\n|$)'
)
class InlineLexer(mistune.InlineLexer):
default_features = copy.copy(mistune.InlineLexer.default_features)
default_features.insert(0, 'emoji')
default_features.insert(0, 'mention')
def __init__(self, renderer, rules=None, **kwargs):
if rules is None:
rules = InlineGrammar()
super(InlineLexer, self).__init__(renderer, rules, **kwargs)
self.mentions = {}
self._mention_count = 0
def output_emoji(self, m):
emoji = m.group('emoji')
if emoji not in emojis:
return m.group(0)
image = emoji + '.png'
rel_path = os.path.join('spirit', 'emojis', image).replace('\\', '/')
path = staticfiles_storage.url(rel_path)
return self.renderer.emoji(path)
def output_mention(self, m):
username = m.group('username')
# Already mentioned?
if username in self.mentions:
user = self.mentions[username]
return self.renderer.mention(username, user.st.get_absolute_url())
# Mentions limiter
if self._mention_count >= settings.ST_MENTIONS_PER_COMMENT:
return m.group(0)
# We increase this before doing the query to avoid abuses
self._mention_count += 1
# New mention
try:
user = User.objects\
.select_related('st')\
.get(username=username)
except User.DoesNotExist:
return m.group(0)
self.mentions[username] = user
return self.renderer.mention(username, user.st.get_absolute_url())
| dvreed/Spirit | spirit/core/utils/markdown/inline.py | Python | mit | 2,414 |
.CodeMirror-search-match {
background: gold;
border: 1px solid orange;
-moz-box-sizing: border-box;
box-sizing: border-box;
opacity: .5;
}
| Rory80Hz/hackmd | public/vendor/codemirror/addon/search/matchesonscrollbar.css | CSS | mit | 149 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace Microsoft.Azure.Services.AppAuthentication
{
/// <summary>
/// Creates an access token provider based on the connection string.
/// </summary>
internal class AzureServiceTokenProviderFactory
{
private const string RunAs = "RunAs";
private const string Developer = "Developer";
private const string AzureCli = "AzureCLI";
private const string VisualStudio = "VisualStudio";
private const string DeveloperTool = "DeveloperTool";
private const string CurrentUser = "CurrentUser";
private const string App = "App";
private const string AppId = "AppId";
private const string AppKey = "AppKey";
private const string TenantId = "TenantId";
private const string CertificateSubjectName = "CertificateSubjectName";
private const string CertificateThumbprint = "CertificateThumbprint";
private const string KeyVaultCertificateSecretIdentifier = "KeyVaultCertificateSecretIdentifier";
private const string KeyVaultUserAssignedManagedIdentityId = "KeyVaultUserAssignedManagedIdentityId";
private const string CertificateStoreLocation = "CertificateStoreLocation";
private const string MsiRetryTimeout = "MsiRetryTimeout";
// taken from https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Data/Common/DbConnectionOptions.Common.cs
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon
+ "(?<key>([^=\\s\\p{Cc}]|\\s+[^=\\s\\p{Cc}]|\\s+==|==)+)" // allow any visible character for keyname except '=' which must quoted as '=='
+ "\\s*=(?!=)\\s*" // the equal sign divides the key and value parts
+ "(?<value>"
+ "(\"([^\"\u0000]|\"\")*\")" // double quoted string, " must be quoted as ""
+ "|"
+ "('([^'\u0000]|'')*')" // single quoted string, ' must be quoted as ''
+ "|"
+ "((?![\"'\\s])" // unquoted value must not start with " or ' or space, would also like = but too late to change
+ "([^;\\s\\p{Cc}]|\\s+[^;\\s\\p{Cc}])*" // control characters must be quoted
+ "(?<![\"']))" // unquoted value must not stop with " or '
+ ")(\\s*)(;|[\u0000\\s]*$)" // whitespace after value up to semicolon or end-of-line
+ ")*" // repeat the key-value pair
+ "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
;
private static readonly Regex ConnectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
/// <summary>
/// Returns a specific token provider based on authentication option specified in the connection string.
/// </summary>
/// <param name="connectionString">Connection string with authentication option and related parameters.</param>
/// <param name="azureAdInstance"></param>
/// <returns></returns>
internal static NonInteractiveAzureServiceTokenProviderBase Create(string connectionString, string azureAdInstance, IHttpClientFactory httpClientFactory = default)
{
Dictionary<string, string> connectionSettings = ParseConnectionString(connectionString);
NonInteractiveAzureServiceTokenProviderBase azureServiceTokenProvider;
ValidateAttribute(connectionSettings, RunAs, connectionString);
string runAs = connectionSettings[RunAs];
if (string.Equals(runAs, Developer, StringComparison.OrdinalIgnoreCase))
{
// If RunAs=Developer
ValidateAttribute(connectionSettings, DeveloperTool, connectionString);
// And Dev Tool equals AzureCLI or VisualStudio
if (string.Equals(connectionSettings[DeveloperTool], AzureCli,
StringComparison.OrdinalIgnoreCase))
{
azureServiceTokenProvider = new AzureCliAccessTokenProvider(new ProcessManager());
}
else if (string.Equals(connectionSettings[DeveloperTool], VisualStudio,
StringComparison.OrdinalIgnoreCase))
{
azureServiceTokenProvider = new VisualStudioAccessTokenProvider(new ProcessManager());
}
else
{
throw new ArgumentException($"Connection string {connectionString} is not valid. {DeveloperTool} '{connectionSettings[DeveloperTool]}' is not valid. " +
$"Allowed values are {AzureCli} or {VisualStudio}");
}
}
else if (string.Equals(runAs, CurrentUser, StringComparison.OrdinalIgnoreCase))
{
// If RunAs=CurrentUser
#if FullNetFx
azureServiceTokenProvider = new WindowsAuthenticationAzureServiceTokenProvider(new AdalAuthenticationContext(httpClientFactory), azureAdInstance);
#else
throw new ArgumentException($"Connection string {connectionString} is not supported for .NET Core.");
#endif
}
else if (string.Equals(runAs, App, StringComparison.OrdinalIgnoreCase))
{
// If RunAs=App
// If AppId key is present, use certificate, client secret, or MSI (with user assigned identity) based token provider
if (connectionSettings.ContainsKey(AppId))
{
ValidateAttribute(connectionSettings, AppId, connectionString);
if (connectionSettings.ContainsKey(CertificateStoreLocation))
{
ValidateAttributes(connectionSettings, new List<string> { CertificateSubjectName, CertificateThumbprint }, connectionString);
ValidateAttribute(connectionSettings, CertificateStoreLocation, connectionString);
ValidateStoreLocation(connectionSettings, connectionString);
ValidateAttribute(connectionSettings, TenantId, connectionString);
azureServiceTokenProvider =
new ClientCertificateAzureServiceTokenProvider(
connectionSettings[AppId],
connectionSettings.ContainsKey(CertificateThumbprint)
? connectionSettings[CertificateThumbprint]
: connectionSettings[CertificateSubjectName],
connectionSettings.ContainsKey(CertificateThumbprint)
? ClientCertificateAzureServiceTokenProvider.CertificateIdentifierType.Thumbprint
: ClientCertificateAzureServiceTokenProvider.CertificateIdentifierType.SubjectName,
connectionSettings[CertificateStoreLocation],
azureAdInstance,
connectionSettings[TenantId],
0,
authenticationContext: new AdalAuthenticationContext(httpClientFactory));
}
else if (connectionSettings.ContainsKey(CertificateThumbprint) ||
connectionSettings.ContainsKey(CertificateSubjectName))
{
// if certificate thumbprint or subject name are specified but certificate store location is not, throw error
throw new ArgumentException($"Connection string {connectionString} is not valid. Must contain '{CertificateStoreLocation}' attribute and it must not be empty " +
$"when using '{CertificateThumbprint}' and '{CertificateSubjectName}' attributes");
}
else if (connectionSettings.ContainsKey(KeyVaultCertificateSecretIdentifier))
{
ValidateMsiRetryTimeout(connectionSettings, connectionString);
var msiRetryTimeout = connectionSettings.ContainsKey(MsiRetryTimeout)
? int.Parse(connectionSettings[MsiRetryTimeout])
: 0;
connectionSettings.TryGetValue(KeyVaultUserAssignedManagedIdentityId, out var keyVaultUserAssignedManagedIdentityId);
azureServiceTokenProvider =
new ClientCertificateAzureServiceTokenProvider(
connectionSettings[AppId],
connectionSettings[KeyVaultCertificateSecretIdentifier],
ClientCertificateAzureServiceTokenProvider.CertificateIdentifierType.KeyVaultCertificateSecretIdentifier,
null, // storeLocation unused
azureAdInstance,
connectionSettings.ContainsKey(TenantId) // tenantId can be specified in connection string or retrieved from Key Vault access token later
? connectionSettings[TenantId]
: default,
msiRetryTimeout,
keyVaultUserAssignedManagedIdentityId,
new AdalAuthenticationContext(httpClientFactory));
}
else if (connectionSettings.ContainsKey(AppKey))
{
ValidateAttribute(connectionSettings, AppKey, connectionString);
ValidateAttribute(connectionSettings, TenantId, connectionString);
azureServiceTokenProvider =
new ClientSecretAccessTokenProvider(
connectionSettings[AppId],
connectionSettings[AppKey],
connectionSettings[TenantId],
azureAdInstance,
new AdalAuthenticationContext(httpClientFactory));
}
else
{
ValidateMsiRetryTimeout(connectionSettings, connectionString);
// If certificate or client secret are not specified, use the specified managed identity
azureServiceTokenProvider = new MsiAccessTokenProvider(
connectionSettings.ContainsKey(MsiRetryTimeout)
? int.Parse(connectionSettings[MsiRetryTimeout])
: 0,
connectionSettings[AppId]);
}
}
else
{
ValidateMsiRetryTimeout(connectionSettings, connectionString);
// If AppId is not specified, use Managed Service Identity
azureServiceTokenProvider = new MsiAccessTokenProvider(
connectionSettings.ContainsKey(MsiRetryTimeout)
? int.Parse(connectionSettings[MsiRetryTimeout])
: 0);
}
}
else
{
throw new ArgumentException($"Connection string {connectionString} is not valid. RunAs value '{connectionSettings[RunAs]}' is not valid. " +
$"Allowed values are {Developer}, {CurrentUser}, or {App}");
}
azureServiceTokenProvider.ConnectionString = connectionString;
return azureServiceTokenProvider;
}
private static void ValidateAttribute(Dictionary<string, string> connectionSettings, string attribute,
string connectionString)
{
if (connectionSettings != null &&
(!connectionSettings.ContainsKey(attribute) || string.IsNullOrWhiteSpace(connectionSettings[attribute])))
{
throw new ArgumentException($"Connection string {connectionString} is not valid. Must contain '{attribute}' attribute and it must not be empty.");
}
}
/// <summary>
/// Throws an exception if none of the attributes are in the connection string
/// </summary>
/// <param name="connectionSettings">List of key value pairs in the connection string</param>
/// <param name="attributes">List of attributes to test</param>
/// <param name="connectionString">The connection string specified</param>
private static void ValidateAttributes(Dictionary<string, string> connectionSettings, List<string> attributes,
string connectionString)
{
if (connectionSettings != null)
{
foreach (string attribute in attributes)
{
if (connectionSettings.ContainsKey(attribute))
{
return;
}
}
throw new ArgumentException($"Connection string {connectionString} is not valid. Must contain at least one of {string.Join(" or ", attributes)} attributes.");
}
}
private static void ValidateStoreLocation(Dictionary<string, string> connectionSettings, string connectionString)
{
if (connectionSettings != null && connectionSettings.ContainsKey(CertificateStoreLocation))
{
if (!string.IsNullOrEmpty(connectionSettings[CertificateStoreLocation]))
{
StoreLocation location;
string storeLocation = connectionSettings[CertificateStoreLocation];
bool parseSucceeded = Enum.TryParse(storeLocation, true, out location);
if (!parseSucceeded)
{
throw new ArgumentException(
$"Connection string {connectionString} is not valid. StoreLocation {storeLocation} is not valid. Valid values are CurrentUser and LocalMachine.");
}
}
}
}
private static void ValidateMsiRetryTimeout(Dictionary<string, string> connectionSettings, string connectionString)
{
if (connectionSettings != null && connectionSettings.ContainsKey(MsiRetryTimeout))
{
if (!string.IsNullOrEmpty(connectionSettings[MsiRetryTimeout]))
{
int timeoutInt;
string timeoutString = connectionSettings[MsiRetryTimeout];
bool parseSucceeded = int.TryParse(timeoutString, out timeoutInt);
if (!parseSucceeded)
{
throw new ArgumentException(
$"Connection string {connectionString} is not valid. MsiRetryTimeout {timeoutString} is not valid. Valid values are integers greater than or equal to 0.");
}
}
}
}
// adapted from https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Data/Common/DbConnectionOptions.Common.cs
internal static Dictionary<string, string> ParseConnectionString(string connectionString)
{
Dictionary<string, string> connectionSettings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
const int KeyIndex = 1, ValueIndex = 2;
if (!string.IsNullOrWhiteSpace(connectionString))
{
Match match = ConnectionStringRegex.Match(connectionString);
if (!match.Success || (match.Length != connectionString.Length))
{
throw new ArgumentException(
$"Connection string {connectionString} is not in a proper format. Expected format is Key1=Value1;Key2=Value2;");
}
int indexValue = 0;
CaptureCollection keyValues = match.Groups[ValueIndex].Captures;
foreach (Capture keyNames in match.Groups[KeyIndex].Captures)
{
string key = keyNames.Value.Replace("==", "=");
string value = keyValues[indexValue++].Value;
if (value.Length > 0)
{
switch (value[0])
{
case '\"':
value = value.Substring(1, value.Length - 2).Replace("\"\"", "\"");
break;
case '\'':
value = value.Substring(1, value.Length - 2).Replace("\'\'", "\'");
break;
default:
break;
}
}
if (!string.IsNullOrWhiteSpace(key))
{
if (!connectionSettings.ContainsKey(key))
{
connectionSettings[key] = value;
}
else
{
throw new ArgumentException(
$"Connection string {connectionString} is not in a proper format. Key '{key}' is repeated.");
}
}
}
}
else
{
throw new ArgumentException("Connection string is empty.");
}
return connectionSettings;
}
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/mgmtcommon/AppAuthentication/Azure.Services.AppAuthentication/AzureServiceTokenProviderFactory.cs | C# | mit | 18,879 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>DbMpoolFile::get()</title>
<link rel="stylesheet" href="apiReference.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB C++ API Reference" />
<link rel="up" href="memp.html" title="Chapter 9. The DbMpoolFile Handle" />
<link rel="prev" href="mempfclose.html" title="DbMpoolFile::close()" />
<link rel="next" href="mempfopen.html" title="DbMpoolFile::open()" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">DbMpoolFile::get()</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="mempfclose.html">Prev</a> </td>
<th width="60%" align="center">Chapter 9.
The DbMpoolFile Handle
</th>
<td width="20%" align="right"> <a accesskey="n" href="mempfopen.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="mempfget"></a>DbMpoolFile::get()</h2>
</div>
</div>
</div>
<pre class="programlisting">#include <db_cxx.h>
int
DbMpoolFile::get(db_pgno_t *pgnoaddr,
DbTxn *txnid, u_int32_t flags, void **pagep);</pre>
<p>
The <code class="methodname">DbMpoolFile::get()</code> method returns pages from the cache.
</p>
<p>
All pages returned by <code class="methodname">DbMpoolFile::get()</code> will be retained (that is,
<span class="emphasis"><em>latched</em></span>) in the cache until a subsequent call to
<a class="xref" href="mempput.html" title="DbMpoolFile::put()">DbMpoolFile::put()</a>.
There is no deadlock detection amoung latches so care must be taken in the application if the DB_MPOOL_DIRTY
or DB_MPOOL_EDIT flags are used as these get exlusive latches on the pages.
</p>
<p>
The returned page is <span class="bold"><strong>size_t</strong></span> type
aligned.
</p>
<p>
Fully or partially created pages have all their bytes set to a nul
byte, unless the
<a class="xref" href="mempset_clear_len.html" title="DbMpoolFile::set_clear_len()">DbMpoolFile::set_clear_len()</a>
method was called to specify other behavior before the file was
opened.
</p>
<p><a id="fget_DB_PAGE_NOTFOUND"></a>
The <code class="methodname">DbMpoolFile::get()</code> method will return
<code class="literal">DB_PAGE_NOTFOUND</code> if the requested page does not exist and DB_MPOOL_CREATE
was not set. Unless otherwise specified, the <code class="methodname">DbMpoolFile::get()</code>
<span>
<span>
method either returns a non-zero error value or throws an
exception that encapsulates a non-zero error value on
failure, and returns 0 on success.
</span>
</span>
</p>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id1693956"></a>Parameters</h3>
</div>
</div>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1693846"></a>flags</h4>
</div>
</div>
</div>
<p>
The <span class="bold"><strong>flags</strong></span> parameter must be set to 0
or by bitwise inclusively <span class="bold"><strong>OR</strong></span>'ing
together one or more of the following values:
</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><a id="mpoolfget_DB_MPOOL_CREATE"></a>
<code class="literal">DB_MPOOL_CREATE</code>
</p>
<p>
If the specified page does not exist, create it. In this case, the
<a class="link" href="mempregister.html" title="DbEnv::memp_register()">pgin</a> method, if
specified, is called.
</p>
</li>
<li>
<p><a id="fget_DB_MPOOL_DIRTY"></a>
<code class="literal">DB_MPOOL_DIRTY</code>
</p>
<p>
The page will be modified and must be written to the source file
before being evicted from the cache. For files open with the
<a class="link" href="dbopen.html#dbopen_DB_MULTIVERSION">DB_MULTIVERSION</a>
flag set, a new copy of the page will be made if this is the first
time the specified transaction is modifying it.
A page fetched with the <code class="literal">DB_MPOOL_DIRTY</code> flag will be
<span class="bold"><strong>excluively latched</strong></span> until
a subsequent call to <a class="xref" href="mempput.html" title="DbMpoolFile::put()">DbMpoolFile::put()</a>.
</p>
</li>
<li>
<p><a id="fget_DB_MPOOL_EDIT"></a>
<code class="literal">DB_MPOOL_EDIT</code>
</p>
<p>
The page will be modified and must be written to the source file
before being evicted from the cache. No copy of the page will be made,
regardless of the
<a class="link" href="dbopen.html#dbopen_DB_MULTIVERSION">DB_MULTIVERSION</a>
setting. This flag is only intended for use in situations where a
transaction handle is not available, such as during aborts or
recovery.
A page fetched with the <code class="literal">DB_MPOOL_EDIT</code> flag will be
<span class="bold"><strong>excluively latched</strong></span> until
a subsequent call to <a class="xref" href="mempput.html" title="DbMpoolFile::put()">DbMpoolFile::put()</a>.
</p>
</li>
<li>
<p><a id="fget_DB_MPOOL_LAST"></a>
<code class="literal">DB_MPOOL_LAST</code>
</p>
<p>
Return the last page of the source file, and copy its page number into
the memory location to which <span class="bold"><strong>pgnoaddr</strong></span>
refers.
</p>
</li>
<li>
<p><a id="mpoolfget_DB_MPOOL_NEW"></a>
<code class="literal">DB_MPOOL_NEW</code>
</p>
<p>
Create a new page in the file, and copy its page number into the
memory location to which <span class="bold"><strong>pgnoaddr</strong></span>
refers. In this case, the <code class="literal">pgin_fcn</code> callback, if specified on
<a class="xref" href="mempregister.html" title="DbEnv::memp_register()">DbEnv::memp_register()</a>, is
<span class="bold"><strong>not</strong></span> called.
</p>
</li>
</ul>
</div>
<p>
The <code class="literal">DB_MPOOL_CREATE</code>, <code class="literal">DB_MPOOL_LAST</code>, and
<code class="literal">DB_MPOOL_NEW</code> flags are mutually exclusive.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694300"></a>pagep</h4>
</div>
</div>
</div>
<p>
The <span class="bold"><strong>pagep</strong></span> parameter references memory
into which a pointer to the returned page is copied.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694153"></a>pgnoaddr</h4>
</div>
</div>
</div>
<p>
If the <span class="bold"><strong>flags</strong></span> parameter is set to
<code class="literal">DB_MPOOL_LAST</code> or <code class="literal">DB_MPOOL_NEW</code>, the
page number of the created page is copied into the memory location to
which the <span class="bold"><strong>pgnoaddr</strong></span> parameter refers.
Otherwise, the <span class="bold"><strong>pgnoaddr</strong></span> parameter is the
page to create or retrieve.
</p>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Page numbers begin at 0; that is, the first page in the file is page number 0,
not page number 1.
</p>
</div>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694424"></a>txnid</h4>
</div>
</div>
</div>
<p>
If the operation is part of an application-specified transaction, the
<span class="bold"><strong>txnid</strong></span> parameter is a transaction
handle returned from <a class="xref" href="txnbegin.html" title="DbEnv::txn_begin()">DbEnv::txn_begin()</a>;
otherwise NULL. A transaction is required if the file is open for multiversion
concurrency control by passing
<a class="link" href="dbopen.html#dbopen_DB_MULTIVERSION">DB_MULTIVERSION</a>
to
<a class="xref" href="mempfopen.html" title="DbMpoolFile::open()">DbMpoolFile::open()</a>
and the DB_MPOOL_DIRTY, DB_MPOOL_CREATE or DB_MPOOL_NEW flags were
specified. Otherwise it is ignored.
</p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id1694406"></a>Errors</h3>
</div>
</div>
</div>
<p>
The <code class="methodname">DbMpoolFile::get()</code> <span>
<span>
method may fail and throw a <a class="link" href="dbexception.html" title="Chapter 6. The DbException Class">DbException</a>
exception, encapsulating one of the following non-zero errors, or return one
of the following non-zero errors:
</span>
</span>
</p>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694141"></a>EACCES</h4>
</div>
</div>
</div>
<p>
The <code class="literal">DB_MPOOL_DIRTY</code> or
<code class="literal">DB_MPOOL_EDIT</code> flag was set and the source file was
not opened for writing.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694229"></a>EAGAIN</h4>
</div>
</div>
</div>
<p>
The page reference count has overflowed. (This should never happen
unless there is a bug in the application.)
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694344"></a>EINVAL</h4>
</div>
</div>
</div>
<p>
If the <code class="literal">DB_MPOOL_NEW</code> flag was set, and the source
file was not opened for writing; more than one of
<code class="literal">DB_MPOOL_CREATE</code>, <code class="literal">DB_MPOOL_LAST</code>,
and <code class="literal">DB_MPOOL_NEW</code> was set; or if an invalid flag
value or parameter was specified.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694007"></a>DB_LOCK_DEADLOCK</h4>
</div>
</div>
</div>
<p>
For transactions configured with
<a class="link" href="txnbegin.html#txnbegin_DB_TXN_SNAPSHOT">DB_TXN_SNAPSHOT</a>,
the page has been modified since the transaction began.
</p>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="id1694510"></a>ENOMEM</h4>
</div>
</div>
</div>
<p>
The cache is full, and no more pages will fit in the cache.
</p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id1694265"></a>Class</h3>
</div>
</div>
</div>
<p>
<a class="link" href="env.html" title="Chapter 5. The DbEnv Handle">DbEnv</a>, <a class="link" href="memp.html" title="Chapter 9. The DbMpoolFile Handle">DbMpoolFile</a>
</p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="id1693932"></a>See Also</h3>
</div>
</div>
</div>
<p>
<a class="xref" href="memp.html#memplist" title="Memory Pools and Related Methods">Memory Pools and Related Methods</a>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="mempfclose.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="memp.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="mempfopen.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">DbMpoolFile::close() </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> DbMpoolFile::open()</td>
</tr>
</table>
</div>
</body>
</html>
| egoitzro/poedit | deps/db/docs/api_reference/CXX/mempfget.html | HTML | mit | 16,157 |
# Markdown #
This extension provides Markdown formatting for fields.
It is part of the Symphony core download package.
- Version: 1.14
- Date: 21st May 2012
- Requirements: Symphony 2.0.7+
- Author: Alistair Kearney, [email protected]
- Constributors: [A list of contributors can be found in the commit history](http://github.com/pointybeard/markdown/commits/master)
- GitHub Repository: <http://github.com/pointybeard/markdown>
## Synopsis
Format text using [Markdown](http://daringfireball.net/projects/markdown/) syntax. This release also passes any output through the [HTML Purifier](http://htmlpurifier.org/) library.
## Installation & Updating
Although the update should address this, fields that used a previous version (< 1.10) may appear to have no formatter specified and will need to be set manually.
Information about [installing and updating extensions](http://symphony-cms.com/learn/tasks/view/install-an-extension/) can be found in the Symphony documentation at <http://symphony-cms.com/learn/>.
| jdsimcoe/briansimcoe | extensions/markdown/README.markdown | Markdown | mit | 1,027 |
// 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.
using Microsoft.CodeAnalysis.Elfie.Model;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
internal interface IDatabaseFactoryService
{
AddReferenceDatabase CreateDatabaseFromBytes(byte[] bytes);
}
}
| diryboy/roslyn | src/EditorFeatures/Core/SymbolSearch/IDatabaseFactoryService.cs | C# | mit | 427 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Consul;
using Orleans.Messaging;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.Runtime.Membership
{
public class ConsulGatewayListProvider : IGatewayListProvider
{
private ConsulClient consulClient;
private string clusterId;
private ILogger logger;
private readonly ConsulClusteringClientOptions options;
private readonly TimeSpan maxStaleness;
private readonly string kvRootFolder;
public ConsulGatewayListProvider(
ILogger<ConsulGatewayListProvider> logger,
IOptions<ConsulClusteringClientOptions> options,
IOptions<GatewayOptions> gatewayOptions,
IOptions<ClusterOptions> clusterOptions)
{
this.logger = logger;
this.clusterId = clusterOptions.Value.ClusterId;
this.maxStaleness = gatewayOptions.Value.GatewayListRefreshPeriod;
this.options = options.Value;
this.kvRootFolder = options.Value.KvRootFolder;
}
public TimeSpan MaxStaleness
{
get { return this.maxStaleness; }
}
public bool IsUpdatable
{
get { return true; }
}
public Task InitializeGatewayListProvider()
{
consulClient =
new ConsulClient(config =>
{
config.Address = options.Address;
config.Token = options.AclClientToken;
});
return Task.CompletedTask;
}
public async Task<IList<Uri>> GetGateways()
{
var membershipTableData = await ConsulBasedMembershipTable.ReadAll(this.consulClient, this.clusterId, this.kvRootFolder, this.logger, null);
if (membershipTableData == null) return new List<Uri>();
return membershipTableData.Members.Select(e => e.Item1).
Where(m => m.Status == SiloStatus.Active && m.ProxyPort != 0).
Select(m =>
{
var endpoint = new IPEndPoint(m.SiloAddress.Endpoint.Address, m.ProxyPort);
var gatewayAddress = SiloAddress.New(endpoint, m.SiloAddress.Generation);
return gatewayAddress.ToGatewayUri();
}).ToList();
}
}
}
| galvesribeiro/orleans | src/Orleans.Clustering.Consul/ConsulGatewayListProvider.cs | C# | mit | 2,498 |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import 'vs/editor/standalone-languages/all';
import './standaloneSchemas';
import Colorizer = require('vs/editor/browser/standalone/colorizer');
import standaloneCodeEditor = require('vs/editor/browser/standalone/standaloneCodeEditor');
import EditorCommon = require('vs/editor/common/editorCommon');
import EditorBrowser = require('vs/editor/browser/editorBrowser');
import {ILanguageDef} from 'vs/editor/standalone-languages/types';
import {IJSONSchema} from 'vs/base/common/jsonSchema';
var global:any = self;
if (!global.Monaco) {
global.Monaco = {};
}
var Monaco = global.Monaco;
if (!Monaco.Editor) {
Monaco.Editor = {};
}
Monaco.Editor.setupServices = standaloneCodeEditor.setupServices;
Monaco.Editor.getAPI = standaloneCodeEditor.getAPI;
Monaco.Editor.create = standaloneCodeEditor.create;
Monaco.Editor.createModel = standaloneCodeEditor.createModel;
Monaco.Editor.createDiffEditor = standaloneCodeEditor.createDiffEditor;
Monaco.Editor.configureMode = standaloneCodeEditor.configureMode;
Monaco.Editor.registerWorkerParticipant = standaloneCodeEditor.registerWorkerParticipant;
Monaco.Editor.getOrCreateMode = standaloneCodeEditor.getOrCreateMode;
Monaco.Editor.createCustomMode = standaloneCodeEditor.createCustomMode;
Monaco.Editor.colorize = standaloneCodeEditor.colorize;
Monaco.Editor.colorizeElement = standaloneCodeEditor.colorizeElement;
Monaco.Editor.colorizeLine = Colorizer.colorizeLine;
Monaco.Editor.colorizeModelLine = Colorizer.colorizeModelLine;
// -- export common constants
Monaco.Editor.SelectionDirection = EditorCommon.SelectionDirection;
Monaco.Editor.WrappingIndent = EditorCommon.WrappingIndent;
Monaco.Editor.wrappingIndentFromString = EditorCommon.wrappingIndentFromString;
Monaco.Editor.OverviewRulerLane = EditorCommon.OverviewRulerLane;
Monaco.Editor.EndOfLinePreference = EditorCommon.EndOfLinePreference;
Monaco.Editor.EndOfLineSequence = EditorCommon.EndOfLineSequence;
Monaco.Editor.LineTokensBinaryEncoding = EditorCommon.LineTokensBinaryEncoding;
Monaco.Editor.TrackedRangeStickiness = EditorCommon.TrackedRangeStickiness;
Monaco.Editor.VerticalRevealType = EditorCommon.VerticalRevealType;
Monaco.Editor.MouseTargetType = EditorCommon.MouseTargetType;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_TEXT_FOCUS;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_FOCUS;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_TAB_MOVES_FOCUS;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS = EditorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_MULTIPLE_SELECTIONS;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION = EditorCommon.KEYBINDING_CONTEXT_EDITOR_HAS_NON_EMPTY_SELECTION;
Monaco.Editor.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID = EditorCommon.KEYBINDING_CONTEXT_EDITOR_LANGUAGE_ID;
Monaco.Editor.ViewEventNames = EditorCommon.ViewEventNames;
Monaco.Editor.CodeEditorStateFlag = EditorCommon.CodeEditorStateFlag;
Monaco.Editor.EditorType = EditorCommon.EditorType;
Monaco.Editor.ClassName = EditorCommon.ClassName;
Monaco.Editor.EventType = EditorCommon.EventType;
Monaco.Editor.Handler = EditorCommon.Handler;
// -- export browser constants
Monaco.Editor.ClassNames = EditorBrowser.ClassNames;
Monaco.Editor.ContentWidgetPositionPreference = EditorBrowser.ContentWidgetPositionPreference;
Monaco.Editor.OverlayWidgetPositionPreference = EditorBrowser.OverlayWidgetPositionPreference;
// Register all built-in standalone languages
let MonacoEditorLanguages: ILanguageDef[] = this.MonacoEditorLanguages || [];
MonacoEditorLanguages.forEach((language) => {
standaloneCodeEditor.registerStandaloneLanguage(language, language.defModule);
});
// Register all built-in standalone JSON schemas
let MonacoEditorSchemas: { [url:string]: IJSONSchema } = this.MonacoEditorSchemas || {};
for (var uri in MonacoEditorSchemas) {
standaloneCodeEditor.registerStandaloneSchema(uri, MonacoEditorSchemas[uri]);
}; | start/vscode | src/vs/editor/browser/standalone/standaloneEditor.ts | TypeScript | mit | 4,366 |
/*
[The "BSD license"]
Copyright (c) 2005-2009 Terence Parr
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. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
package org.antlr.runtime3_4_0;
public interface Token {
public static final int EOR_TOKEN_TYPE = 1;
/** imaginary tree navigation type; traverse "get child" link */
public static final int DOWN = 2;
/** imaginary tree navigation type; finish with a child list */
public static final int UP = 3;
public static final int MIN_TOKEN_TYPE = UP+1;
public static final int EOF = CharStream.EOF;
// TODO: remove once we go ANTLR v3.3
public static final Token EOF_TOKEN = new CommonToken(EOF);
public static final int INVALID_TOKEN_TYPE = 0;
public static final Token INVALID_TOKEN = new CommonToken(INVALID_TOKEN_TYPE);
/** In an action, a lexer rule can set token to this SKIP_TOKEN and ANTLR
* will avoid creating a token for this symbol and try to fetch another.
*/
public static final Token SKIP_TOKEN = new CommonToken(INVALID_TOKEN_TYPE);
/** All tokens go to the parser (unless skip() is called in that rule)
* on a particular "channel". The parser tunes to a particular channel
* so that whitespace etc... can go to the parser on a "hidden" channel.
*/
public static final int DEFAULT_CHANNEL = 0;
/** Anything on different channel than DEFAULT_CHANNEL is not parsed
* by parser.
*/
public static final int HIDDEN_CHANNEL = 99;
/** Get the text of the token */
public String getText();
public void setText(String text);
public int getType();
public void setType(int ttype);
/** The line number on which this token was matched; line=1..n */
public int getLine();
public void setLine(int line);
/** The index of the first character relative to the beginning of the line 0..n-1 */
public int getCharPositionInLine();
public void setCharPositionInLine(int pos);
public int getChannel();
public void setChannel(int channel);
/** An index from 0..n-1 of the token object in the input stream.
* This must be valid in order to use the ANTLRWorks debugger.
*/
public int getTokenIndex();
public void setTokenIndex(int index);
/** From what character stream was this token created? You don't have to
* implement but it's nice to know where a Token comes from if you have
* include files etc... on the input.
*/
public CharStream getInputStream();
public void setInputStream(CharStream input);
}
| jesusc/bento | plugins/org.emftext.commons.antlr3_4_0/src/org/antlr/runtime3_4_0/Token.java | Java | epl-1.0 | 3,734 |
/**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.shared_interactive_console.console.ui.internal.actions;
/**
* @author fabioz
*
*/
public interface IInteractiveConsoleConstants {
static final String EVALUATE_ACTION_ID = "org.python.pydev.interactiveconsole.evaluateActionSetter";
}
| bobwalker99/Pydev | plugins/org.python.pydev.shared_interactive_console/src/org/python/pydev/shared_interactive_console/console/ui/internal/actions/IInteractiveConsoleConstants.java | Java | epl-1.0 | 557 |
/* Copyright (C) 2007-2010 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Anoop Saldanha <[email protected]>
*/
#include "suricata-common.h"
#include "threads.h"
#include "decode.h"
#include "detect.h"
#include "detect-parse.h"
#include "detect-engine.h"
#include "detect-engine-mpm.h"
#include "detect-engine-state.h"
#include "detect-content.h"
#include "detect-pcre.h"
#include "detect-bytejump.h"
#include "detect-bytetest.h"
#include "detect-byte-extract.h"
#include "detect-isdataat.h"
#include "app-layer-protos.h"
#include "flow.h"
#include "flow-var.h"
#include "flow-util.h"
#include "util-byte.h"
#include "util-debug.h"
#include "util-unittest.h"
#include "util-unittest-helper.h"
#include "util-spm.h"
/* the default value of endianess to be used, if none's specified */
#define DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT DETECT_BYTE_EXTRACT_ENDIAN_BIG
/* the base to be used if string mode is specified. These options would be
* specified in DetectByteParseData->base */
#define DETECT_BYTE_EXTRACT_BASE_NONE 0
#define DETECT_BYTE_EXTRACT_BASE_HEX 16
#define DETECT_BYTE_EXTRACT_BASE_DEC 10
#define DETECT_BYTE_EXTRACT_BASE_OCT 8
/* the default value for multiplier. Either ways we always store a
* multiplier, 1 or otherwise, so that we can always multiply the extracted
* value and store it, instead of checking if a multiplier is set or not */
#define DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT 1
/* the min/max limit for multiplier */
#define DETECT_BYTE_EXTRACT_MULTIPLIER_MIN_LIMIT 1
#define DETECT_BYTE_EXTRACT_MULTIPLIER_MAX_LIMIT 65535
/* the max no of bytes that can be extracted in string mode - (string, hex)
* (string, oct) or (string, dec) */
#define STRING_MAX_BYTES_TO_EXTRACT_FOR_OCT 23
#define STRING_MAX_BYTES_TO_EXTRACT_FOR_DEC 20
#define STRING_MAX_BYTES_TO_EXTRACT_FOR_HEX 14
/* the max no of bytes that can be extraced in non-string mode */
#define NO_STRING_MAX_BYTES_TO_EXTRACT 8
#define PARSE_REGEX "^" \
"\\s*([0-9]+)\\s*" \
",\\s*(-?[0-9]+)\\s*" \
",\\s*([^\\s,]+)\\s*" \
"(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \
"(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \
"(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \
"(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \
"(?:(?:,\\s*([^\\s,]+)\\s*)|(?:,\\s*([^\\s,]+)\\s+([^\\s,]+)\\s*))?" \
"$"
static pcre *parse_regex;
static pcre_extra *parse_regex_study;
int DetectByteExtractMatch(ThreadVars *, DetectEngineThreadCtx *,
Packet *, Signature *, SigMatch *);
int DetectByteExtractSetup(DetectEngineCtx *, Signature *, char *);
void DetectByteExtractRegisterTests(void);
void DetectByteExtractFree(void *);
/**
* \brief Registers the keyword handlers for the "byte_extract" keyword.
*/
void DetectByteExtractRegister(void)
{
const char *eb;
int eo;
int opts = 0;
sigmatch_table[DETECT_BYTE_EXTRACT].name = "byte_extract";
sigmatch_table[DETECT_BYTE_EXTRACT].Match = NULL;
sigmatch_table[DETECT_BYTE_EXTRACT].AppLayerMatch = NULL;
sigmatch_table[DETECT_BYTE_EXTRACT].Setup = DetectByteExtractSetup;
sigmatch_table[DETECT_BYTE_EXTRACT].Free = DetectByteExtractFree;
sigmatch_table[DETECT_BYTE_EXTRACT].RegisterTests = DetectByteExtractRegisterTests;
sigmatch_table[DETECT_BYTE_EXTRACT].flags |= SIGMATCH_PAYLOAD;
parse_regex = pcre_compile(PARSE_REGEX, opts, &eb, &eo, NULL);
if (parse_regex == NULL) {
SCLogError(SC_ERR_PCRE_COMPILE, "pcre compile of \"%s\" failed "
"at offset %" PRId32 ": %s", PARSE_REGEX, eo, eb);
goto error;
}
parse_regex_study = pcre_study(parse_regex, 0, &eb);
if (eb != NULL) {
SCLogError(SC_ERR_PCRE_STUDY, "pcre study failed: %s", eb);
goto error;
}
return;
error:
return;
}
int DetectByteExtractDoMatch(DetectEngineThreadCtx *det_ctx, SigMatch *sm,
Signature *s, uint8_t *payload,
uint16_t payload_len, uint64_t *value,
uint8_t endian)
{
DetectByteExtractData *data = (DetectByteExtractData *)sm->ctx;
uint8_t *ptr = NULL;
int32_t len = 0;
uint64_t val = 0;
int extbytes;
if (payload_len == 0) {
return 0;
}
/* Calculate the ptr value for the bytetest and length remaining in
* the packet from that point.
*/
if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) {
SCLogDebug("relative, working with det_ctx->buffer_offset %"PRIu32", "
"data->offset %"PRIu32"", det_ctx->buffer_offset, data->offset);
ptr = payload + det_ctx->buffer_offset;
len = payload_len - det_ctx->buffer_offset;
ptr += data->offset;
len -= data->offset;
/* No match if there is no relative base */
if (len <= 0) {
return 0;
}
//PrintRawDataFp(stdout,ptr,len);
} else {
SCLogDebug("absolute, data->offset %"PRIu32"", data->offset);
ptr = payload + data->offset;
len = payload_len - data->offset;
}
/* Validate that the to-be-extracted is within the packet */
if (ptr < payload || data->nbytes > len) {
SCLogDebug("Data not within payload pkt=%p, ptr=%p, len=%"PRIu32", nbytes=%d",
payload, ptr, len, data->nbytes);
return 0;
}
/* Extract the byte data */
if (data->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) {
extbytes = ByteExtractStringUint64(&val, data->base,
data->nbytes, (const char *)ptr);
if (extbytes <= 0) {
/* strtoull() return 0 if there is no numeric value in data string */
if (val == 0) {
SCLogDebug("No Numeric value");
return 0;
} else {
SCLogError(SC_ERR_INVALID_NUM_BYTES, "Error extracting %d "
"bytes of string data: %d", data->nbytes, extbytes);
return -1;
}
}
} else {
int endianness = (endian == DETECT_BYTE_EXTRACT_ENDIAN_BIG) ?
BYTE_BIG_ENDIAN : BYTE_LITTLE_ENDIAN;
extbytes = ByteExtractUint64(&val, endianness, data->nbytes, ptr);
if (extbytes != data->nbytes) {
SCLogError(SC_ERR_INVALID_NUM_BYTES, "Error extracting %d bytes "
"of numeric data: %d\n", data->nbytes, extbytes);
return 0;
}
}
/* Adjust the jump value based on flags */
val *= data->multiplier_value;
if (data->flags & DETECT_BYTE_EXTRACT_FLAG_ALIGN) {
if ((val % data->align_value) != 0) {
val += data->align_value - (val % data->align_value);
}
}
ptr += extbytes;
det_ctx->buffer_offset = ptr - payload;
*value = val;
return 1;
}
int DetectByteExtractMatch(ThreadVars *tv, DetectEngineThreadCtx *det_ctx,
Packet *p, Signature *s, SigMatch *m)
{
goto end;
end:
return 1;
}
/**
* \internal
* \brief Used to parse byte_extract arg.
*
* \arg The argument to parse.
*
* \param bed On success an instance containing the parsed data.
* On failure, NULL.
*/
static inline DetectByteExtractData *DetectByteExtractParse(char *arg)
{
DetectByteExtractData *bed = NULL;
#define MAX_SUBSTRINGS 100
int ret = 0, res = 0;
int ov[MAX_SUBSTRINGS];
int i = 0;
ret = pcre_exec(parse_regex, parse_regex_study, arg,
strlen(arg), 0, 0, ov, MAX_SUBSTRINGS);
if (ret < 3 || ret > 19) {
SCLogError(SC_ERR_PCRE_PARSE, "parse error, ret %" PRId32
", string \"%s\"", ret, arg);
SCLogError(SC_ERR_INVALID_SIGNATURE, "Invalid arg to byte_extract : %s "
"for byte_extract", arg);
goto error;
}
bed = SCMalloc(sizeof(DetectByteExtractData));
if (unlikely(bed == NULL))
goto error;
memset(bed, 0, sizeof(DetectByteExtractData));
/* no of bytes to extract */
char nbytes_str[64] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, 1, nbytes_str, sizeof(nbytes_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg 1 for byte_extract");
goto error;
}
bed->nbytes = atoi(nbytes_str);
/* offset */
char offset_str[64] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, 2, offset_str, sizeof(offset_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg 2 for byte_extract");
goto error;
}
int offset = atoi(offset_str);
if (offset < -65535 || offset > 65535) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract offset invalid - %d. "
"The right offset range is -65535 to 65535", offset);
goto error;
}
bed->offset = offset;
/* var name */
char varname_str[256] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, 3, varname_str, sizeof(varname_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg 3 for byte_extract");
goto error;
}
bed->name = SCStrdup(varname_str);
if (bed->name == NULL)
goto error;
/* check out other optional args */
for (i = 4; i < ret; i++) {
char opt_str[64] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, i, opt_str, sizeof(opt_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg %d for byte_extract", i);
goto error;
}
if (strcmp("relative", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "relative specified more "
"than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_RELATIVE;
} else if (strcmp("multiplier", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "multiplier specified more "
"than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER;
i++;
char multiplier_str[16] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, i, multiplier_str, sizeof(multiplier_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg %d for byte_extract", i);
goto error;
}
int multiplier = atoi(multiplier_str);
if (multiplier < DETECT_BYTE_EXTRACT_MULTIPLIER_MIN_LIMIT ||
multiplier > DETECT_BYTE_EXTRACT_MULTIPLIER_MAX_LIMIT) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "multipiler_value invalid "
"- %d. The range is %d-%d",
multiplier,
DETECT_BYTE_EXTRACT_MULTIPLIER_MIN_LIMIT,
DETECT_BYTE_EXTRACT_MULTIPLIER_MAX_LIMIT);
goto error;
}
bed->multiplier_value = multiplier;
} else if (strcmp("big", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "endian option specified "
"more than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_ENDIAN;
bed->endian = DETECT_BYTE_EXTRACT_ENDIAN_BIG;
} else if (strcmp("little", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "endian option specified "
"more than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_ENDIAN;
bed->endian = DETECT_BYTE_EXTRACT_ENDIAN_LITTLE;
} else if (strcmp("dce", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "endian option specified "
"more than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_ENDIAN;
bed->endian = DETECT_BYTE_EXTRACT_ENDIAN_DCE;
} else if (strcmp("string", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "string specified more "
"than once for byte_extract");
goto error;
}
if (bed->base != DETECT_BYTE_EXTRACT_BASE_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "The right way to specify "
"base is (string, base) and not (base, string) "
"for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_STRING;
} else if (strcmp("hex", opt_str) == 0) {
if (!(bed->flags & DETECT_BYTE_EXTRACT_FLAG_STRING)) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Base(hex) specified "
"without specifying string. The right way is "
"(string, base) and not (base, string)");
goto error;
}
if (bed->base != DETECT_BYTE_EXTRACT_BASE_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "More than one base "
"specified for byte_extract");
goto error;
}
bed->base = DETECT_BYTE_EXTRACT_BASE_HEX;
} else if (strcmp("oct", opt_str) == 0) {
if (!(bed->flags & DETECT_BYTE_EXTRACT_FLAG_STRING)) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Base(oct) specified "
"without specifying string. The right way is "
"(string, base) and not (base, string)");
goto error;
}
if (bed->base != DETECT_BYTE_EXTRACT_BASE_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "More than one base "
"specified for byte_extract");
goto error;
}
bed->base = DETECT_BYTE_EXTRACT_BASE_OCT;
} else if (strcmp("dec", opt_str) == 0) {
if (!(bed->flags & DETECT_BYTE_EXTRACT_FLAG_STRING)) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Base(dec) specified "
"without specifying string. The right way is "
"(string, base) and not (base, string)");
goto error;
}
if (bed->base != DETECT_BYTE_EXTRACT_BASE_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "More than one base "
"specified for byte_extract");
goto error;
}
bed->base = DETECT_BYTE_EXTRACT_BASE_DEC;
} else if (strcmp("align", opt_str) == 0) {
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_ALIGN) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Align specified more "
"than once for byte_extract");
goto error;
}
bed->flags |= DETECT_BYTE_EXTRACT_FLAG_ALIGN;
i++;
char align_str[16] = "";
res = pcre_copy_substring((char *)arg, ov,
MAX_SUBSTRINGS, i, align_str, sizeof(align_str));
if (res < 0) {
SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring failed "
"for arg %d in byte_extract", i);
goto error;
}
bed->align_value = atoi(align_str);
if (!(bed->align_value == 2 || bed->align_value == 4)) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Invalid align_value for "
"byte_extract - \"%d\"", bed->align_value);
goto error;
}
} else if (strcmp("", opt_str) == 0) {
;
} else {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Invalid option - \"%s\" "
"specified in byte_extract", opt_str);
goto error;
}
} /* for (i = 4; i < ret; i++) */
/* validation */
if (!(bed->flags & DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER)) {
/* default value */
bed->multiplier_value = DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT;
}
if (bed->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) {
if (bed->base == DETECT_BYTE_EXTRACT_BASE_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Base not specified for "
"byte_extract, though string was specified. "
"The right options are (string, hex), (string, oct) "
"or (string, dec)");
goto error;
}
if (bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract can't have "
"endian \"big\" or \"little\" specified along with "
"\"string\"");
goto error;
}
if (bed->base == DETECT_BYTE_EXTRACT_BASE_OCT) {
/* if are dealing with octal nos, the max no that can fit in a 8
* byte value is 01777777777777777777777 */
if (bed->nbytes > STRING_MAX_BYTES_TO_EXTRACT_FOR_OCT) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract can't process "
"more than %d bytes in \"string\" extraction",
STRING_MAX_BYTES_TO_EXTRACT_FOR_OCT);
goto error;
}
} else if (bed->base == DETECT_BYTE_EXTRACT_BASE_DEC) {
/* if are dealing with decimal nos, the max no that can fit in a 8
* byte value is 18446744073709551615 */
if (bed->nbytes > STRING_MAX_BYTES_TO_EXTRACT_FOR_DEC) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract can't process "
"more than %d bytes in \"string\" extraction",
STRING_MAX_BYTES_TO_EXTRACT_FOR_DEC);
goto error;
}
} else if (bed->base == DETECT_BYTE_EXTRACT_BASE_HEX) {
/* if are dealing with hex nos, the max no that can fit in a 8
* byte value is 0xFFFFFFFFFFFFFFFF */
if (bed->nbytes > STRING_MAX_BYTES_TO_EXTRACT_FOR_HEX) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract can't process "
"more than %d bytes in \"string\" extraction",
STRING_MAX_BYTES_TO_EXTRACT_FOR_HEX);
goto error;
}
} else {
; // just a placeholder. we won't reach here.
}
} else {
if (bed->nbytes > NO_STRING_MAX_BYTES_TO_EXTRACT) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "byte_extract can't process "
"more than %d bytes in \"non-string\" extraction",
NO_STRING_MAX_BYTES_TO_EXTRACT);
goto error;
}
/* if string has not been specified and no endian option has been
* specified, then set the default endian level of BIG */
if (!(bed->flags & DETECT_BYTE_EXTRACT_FLAG_ENDIAN))
bed->endian = DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT;
}
return bed;
error:
if (bed != NULL)
DetectByteExtractFree(bed);
return NULL;
}
/**
* \brief The setup function for the byte_extract keyword for a signature.
*
* \param de_ctx Pointer to the detection engine context.
* \param s Pointer to signature for the current Signature being parsed
* from the rules.
* \param m Pointer to the head of the SigMatch for the current rule
* being parsed.
* \param arg Pointer to the string holding the keyword value.
*
* \retval 0 On success.
* \retval -1 On failure.
*/
int DetectByteExtractSetup(DetectEngineCtx *de_ctx, Signature *s, char *arg)
{
SigMatch *sm = NULL;
SigMatch *prev_pm = NULL;
DetectByteExtractData *data = NULL;
int ret = -1;
data = DetectByteExtractParse(arg);
if (data == NULL)
goto error;
int sm_list;
if (s->list != DETECT_SM_LIST_NOTSET) {
if (s->list == DETECT_SM_LIST_FILEDATA) {
if (data->endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "dce byte_extract specified "
"with file_data option set.");
goto error;
}
AppLayerHtpEnableResponseBodyCallback();
}
sm_list = s->list;
s->flags |= SIG_FLAG_APPLAYER;
if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) {
prev_pm = SigMatchGetLastSMFromLists(s, 4,
DETECT_CONTENT, s->sm_lists_tail[sm_list],
DETECT_PCRE, s->sm_lists_tail[sm_list]);
}
} else if (data->endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE) {
if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) {
prev_pm = SigMatchGetLastSMFromLists(s, 12,
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH]);
if (prev_pm == NULL) {
sm_list = DETECT_SM_LIST_PMATCH;
} else {
sm_list = SigMatchListSMBelongsTo(s, prev_pm);
if (sm_list < 0)
goto error;
}
} else {
sm_list = DETECT_SM_LIST_PMATCH;
}
s->alproto = ALPROTO_DCERPC;
s->flags |= SIG_FLAG_APPLAYER;
} else if (data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE) {
prev_pm = SigMatchGetLastSMFromLists(s, 168,
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_CONTENT, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_PCRE, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_BYTETEST, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_BYTEJUMP, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_BYTE_EXTRACT, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_PMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_UMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HCBDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_FILEDATA],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HHDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HRHDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HMDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HCDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HRUDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HSMDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HSCDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HUADMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HHHDMATCH],
DETECT_ISDATAAT, s->sm_lists_tail[DETECT_SM_LIST_HRHHDMATCH]);
if (prev_pm == NULL) {
sm_list = DETECT_SM_LIST_PMATCH;
} else {
sm_list = SigMatchListSMBelongsTo(s, prev_pm);
if (sm_list < 0)
goto error;
if (sm_list != DETECT_SM_LIST_PMATCH)
s->flags |= SIG_FLAG_APPLAYER;
}
} else {
sm_list = DETECT_SM_LIST_PMATCH;
}
if (data->endian == DETECT_BYTE_EXTRACT_ENDIAN_DCE) {
if (s->alproto != ALPROTO_UNKNOWN && s->alproto != ALPROTO_DCERPC) {
SCLogError(SC_ERR_INVALID_SIGNATURE, "Non dce alproto sig has "
"byte_extract with dce enabled");
goto error;
}
s->alproto = ALPROTO_DCERPC;
if ((data->flags & DETECT_BYTE_EXTRACT_FLAG_STRING) ||
(data->base == DETECT_BYTE_EXTRACT_BASE_DEC) ||
(data->base == DETECT_BYTE_EXTRACT_BASE_HEX) ||
(data->base == DETECT_BYTE_EXTRACT_BASE_OCT) ) {
SCLogError(SC_ERR_CONFLICTING_RULE_KEYWORDS, "Invalid option. "
"A byte_jump keyword with dce holds other invalid modifiers.");
goto error;
}
}
SigMatch *prev_bed_sm = SigMatchGetLastSMFromLists(s, 2,
DETECT_BYTE_EXTRACT, s->sm_lists_tail[sm_list]);
if (prev_bed_sm == NULL)
data->local_id = 0;
else
data->local_id = ((DetectByteExtractData *)prev_bed_sm->ctx)->local_id + 1;
if (data->local_id > de_ctx->byte_extract_max_local_id)
de_ctx->byte_extract_max_local_id = data->local_id;
sm = SigMatchAlloc();
if (sm == NULL)
goto error;
sm->type = DETECT_BYTE_EXTRACT;
sm->ctx = (void *)data;
SigMatchAppendSMToList(s, sm, sm_list);
if (!(data->flags & DETECT_BYTE_EXTRACT_FLAG_RELATIVE))
goto okay;
if (prev_pm == NULL)
goto okay;
if (prev_pm->type == DETECT_CONTENT) {
DetectContentData *cd = (DetectContentData *)prev_pm->ctx;
cd->flags |= DETECT_CONTENT_RELATIVE_NEXT;
} else if (prev_pm->type == DETECT_PCRE) {
DetectPcreData *pd = (DetectPcreData *)prev_pm->ctx;
pd->flags |= DETECT_PCRE_RELATIVE_NEXT;
}
okay:
ret = 0;
return ret;
error:
DetectByteExtractFree(data);
return ret;
}
/**
* \brief Used to free instances of DetectByteExtractData.
*
* \param ptr Instance of DetectByteExtractData to be freed.
*/
void DetectByteExtractFree(void *ptr)
{
if (ptr != NULL) {
DetectByteExtractData *bed = ptr;
if (bed->name != NULL)
SCFree((void *)bed->name);
SCFree(bed);
}
return;
}
/**
* \brief Lookup the SigMatch for a named byte_extract variable.
*
* \param arg The name of the byte_extract variable to lookup.
* \param s Pointer the signature to look in.
*
* \retval A pointer to the SigMatch if found, otherwise NULL.
*/
SigMatch *DetectByteExtractRetrieveSMVar(const char *arg, Signature *s)
{
DetectByteExtractData *bed = NULL;
int list;
for (list = 0; list < DETECT_SM_LIST_MAX; list++) {
SigMatch *sm = s->sm_lists[list];
while (sm != NULL) {
if (sm->type == DETECT_BYTE_EXTRACT) {
bed = (DetectByteExtractData *)sm->ctx;
if (strcmp(bed->name, arg) == 0) {
return sm;
}
}
sm = sm->next;
}
}
return NULL;
}
/*************************************Unittests********************************/
#ifdef UNITTESTS
int DetectByteExtractTest01(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != 0 ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest02(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, relative");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_RELATIVE ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest03(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, multiplier 10");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != 10) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest04(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, relative, multiplier 10");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != 10) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest05(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, big");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest06(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, little");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest07(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, dce");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_ENDIAN ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest08(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, string, hex");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest09(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, string, oct");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_OCT ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest10(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, string, dec");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_DEC ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest11(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_ALIGN ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest12(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, relative");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest13(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, relative, big");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN |
DETECT_BYTE_EXTRACT_FLAG_ENDIAN |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_BIG ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest14(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, relative, dce");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN |
DETECT_BYTE_EXTRACT_FLAG_ENDIAN |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DCE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest15(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, relative, little");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN |
DETECT_BYTE_EXTRACT_FLAG_ENDIAN |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest16(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, relative, little, multiplier 2");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_ALIGN |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_ENDIAN |
DETECT_BYTE_EXTRACT_FLAG_MULTIPLIER) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_LITTLE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 4 ||
bed->multiplier_value != 2) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest17(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"relative, little, "
"multiplier 2, string hex");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest18(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"relative, little, "
"multiplier 2, "
"relative");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest19(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"relative, little, "
"multiplier 2, "
"little");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest20(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"relative, "
"multiplier 2, "
"align 2");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest21(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"multiplier 2, "
"relative, "
"multiplier 2");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest22(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"string hex, "
"relative, "
"string hex");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest23(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"string hex, "
"relative, "
"string oct");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest24(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("24, 2, one, align 4, "
"string hex, "
"relative");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest25(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("9, 2, one, align 4, "
"little, "
"relative");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest26(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"little, "
"relative, "
"multiplier 65536");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest27(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, 2, one, align 4, "
"little, "
"relative, "
"multiplier 0");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest28(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("23, 2, one, string, oct");
if (bed == NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest29(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("24, 2, one, string, oct");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest30(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("20, 2, one, string, dec");
if (bed == NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest31(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("21, 2, one, string, dec");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest32(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("14, 2, one, string, hex");
if (bed == NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest33(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("15, 2, one, string, hex");
if (bed != NULL)
goto end;
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
int DetectByteExtractTest34(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,2,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strncmp(bed->name, "two", cd->content_len) != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest35(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectPcreData *pd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; pcre:/asf/; "
"byte_extract:4,0,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_PCRE) {
result = 0;
goto end;
}
pd = (DetectPcreData *)sm->ctx;
if (pd->flags != DETECT_PCRE_RELATIVE_NEXT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest36(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectBytejumpData *bjd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; byte_jump:1,13; "
"byte_extract:4,0,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest37(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectContentData *ud = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; uricontent:\"two\"; "
"byte_extract:4,0,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
ud = (DetectContentData *)sm->ctx;
if (ud->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)ud->content, "two", cd->content_len) != 0 ||
ud->flags & DETECT_CONTENT_NOCASE ||
ud->flags & DETECT_CONTENT_WITHIN ||
ud->flags & DETECT_CONTENT_DISTANCE ||
ud->flags & DETECT_CONTENT_FAST_PATTERN ||
!(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
ud->flags & DETECT_CONTENT_NEGATED ) {
printf("two failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest38(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectContentData *ud = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; uricontent:\"two\"; "
"byte_extract:4,0,two,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags !=DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
ud = (DetectContentData *)sm->ctx;
if (ud->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)ud->content, "two", cd->content_len) != 0 ||
ud->flags & DETECT_CONTENT_NOCASE ||
ud->flags & DETECT_CONTENT_WITHIN ||
ud->flags & DETECT_CONTENT_DISTANCE ||
ud->flags & DETECT_CONTENT_FAST_PATTERN ||
ud->flags & DETECT_CONTENT_RELATIVE_NEXT ||
ud->flags & DETECT_CONTENT_NEGATED ) {
printf("two failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
result = 0;
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest39(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectContentData *ud = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; content:\"two\"; http_uri; "
"byte_extract:4,0,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
ud = (DetectContentData *)sm->ctx;
if (ud->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)ud->content, "two", cd->content_len) != 0 ||
ud->flags & DETECT_CONTENT_NOCASE ||
ud->flags & DETECT_CONTENT_WITHIN ||
ud->flags & DETECT_CONTENT_DISTANCE ||
ud->flags & DETECT_CONTENT_FAST_PATTERN ||
!(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
ud->flags & DETECT_CONTENT_NEGATED ) {
printf("two failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest40(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectContentData *ud = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; content:\"two\"; http_uri; "
"byte_extract:4,0,two,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags !=DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
ud = (DetectContentData *)sm->ctx;
if (ud->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)ud->content, "two", cd->content_len) != 0 ||
ud->flags & DETECT_CONTENT_NOCASE ||
ud->flags & DETECT_CONTENT_WITHIN ||
ud->flags & DETECT_CONTENT_DISTANCE ||
ud->flags & DETECT_CONTENT_FAST_PATTERN ||
ud->flags & DETECT_CONTENT_RELATIVE_NEXT ||
ud->flags & DETECT_CONTENT_NEGATED ) {
printf("two failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
result = 0;
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest41(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "three") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 1) {
result = 0;
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest42(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectContentData *ud = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"uricontent: \"three\"; "
"byte_extract:4,0,four,string,hex,relative; "
"byte_extract:4,0,five,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "five") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 1) {
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
ud = (DetectContentData *)sm->ctx;
if (ud->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)ud->content, "three", cd->content_len) != 0 ||
ud->flags & DETECT_CONTENT_NOCASE ||
ud->flags & DETECT_CONTENT_WITHIN ||
ud->flags & DETECT_CONTENT_DISTANCE ||
ud->flags & DETECT_CONTENT_FAST_PATTERN ||
!(ud->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
ud->flags & DETECT_CONTENT_NEGATED ) {
printf("two failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "four") != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_RELATIVE |
DETECT_BYTE_EXTRACT_FLAG_STRING) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest43(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"content: \"three\"; offset:two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "three", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_OFFSET_BE |
DETECT_CONTENT_OFFSET) ||
cd->offset != bed->local_id) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest44(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"content: \"four\"; offset:two; "
"content: \"five\"; offset:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_OFFSET_BE |
DETECT_CONTENT_OFFSET) ||
cd->offset != bed1->local_id) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "five", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_OFFSET_BE |
DETECT_CONTENT_OFFSET) ||
cd->offset != bed2->local_id) {
printf("five failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest45(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"content: \"three\"; depth:two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "three", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DEPTH_BE |
DETECT_CONTENT_DEPTH) ||
cd->depth != bed->local_id ||
cd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest46(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"content: \"four\"; depth:two; "
"content: \"five\"; depth:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DEPTH_BE |
DETECT_CONTENT_DEPTH) ||
cd->depth != bed1->local_id) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "five", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DEPTH_BE |
DETECT_CONTENT_DEPTH) ||
cd->depth != bed2->local_id) {
printf("five failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest47(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"content: \"three\"; distance:two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "three", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_DISTANCE) ||
cd->distance != bed->local_id ||
cd->offset != 0 ||
cd->depth != 0) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest48(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"content: \"four\"; distance:two; "
"content: \"five\"; distance:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_DISTANCE |
DETECT_CONTENT_RELATIVE_NEXT) ||
cd->distance != bed1->local_id ||
cd->depth != 0 ||
cd->offset != 0) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "five", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_DISTANCE) ||
cd->distance != bed2->local_id ||
cd->depth != 0 ||
cd->offset != 0) {
printf("five failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest49(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"content: \"three\"; within:two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "three", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_WITHIN) ||
cd->within != bed->local_id ||
cd->offset != 0 ||
cd->depth != 0 ||
cd->distance != 0) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest50(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"content: \"four\"; within:two; "
"content: \"five\"; within:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_WITHIN|
DETECT_CONTENT_RELATIVE_NEXT) ||
cd->within != bed1->local_id ||
cd->depth != 0 ||
cd->offset != 0 ||
cd->distance != 0) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "five", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_WITHIN) ||
cd->within != bed2->local_id ||
cd->depth != 0 ||
cd->offset != 0 ||
cd->distance != 0) {
printf("five failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest51(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
DetectBytetestData *btd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_test: 2,=,10, two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTETEST) {
result = 0;
goto end;
}
btd = (DetectBytetestData *)sm->ctx;
if (btd->flags != DETECT_BYTETEST_OFFSET_BE ||
btd->value != 10 ||
btd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest52(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectBytetestData *btd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_test: 2,=,two,three; "
"byte_test: 3,=,10,three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTETEST) {
result = 0;
goto end;
}
btd = (DetectBytetestData *)sm->ctx;
if (btd->flags != (DETECT_BYTETEST_OFFSET_BE |
DETECT_BYTETEST_VALUE_BE) ||
btd->value != 0 ||
btd->offset != 1) {
printf("three failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTETEST) {
result = 0;
goto end;
}
btd = (DetectBytetestData *)sm->ctx;
if (btd->flags != DETECT_BYTETEST_OFFSET_BE ||
btd->value != 10 ||
btd->offset != 1) {
printf("four failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest53(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed = NULL;
DetectBytejumpData *bjd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_jump: 2,two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 0 ||
strcmp(bed->name, "two") != 0 ||
bed->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest54(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectBytejumpData *bjd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_jump: 2,two; "
"byte_jump: 3,three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 1) {
printf("four failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest55(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing byte_extract\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_extract:4,0,four,string,hex; "
"byte_extract:4,0,five,string,hex; "
"content: \"four\"; within:two; distance:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed: ");
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_DISTANCE |
DETECT_CONTENT_WITHIN) ||
cd->within != bed1->local_id ||
cd->distance != bed2->local_id) {
printf("four failed: ");
goto end;
}
if (sm->next != NULL) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest56(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"uricontent:\"urione\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_extract:4,0,four,string,hex; "
"byte_extract:4,0,five,string,hex; "
"content: \"four\"; within:two; distance:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "urione", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_DISTANCE |
DETECT_CONTENT_WITHIN) ||
cd->within != bed1->local_id ||
cd->distance != bed2->local_id ) {
printf("four failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest57(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectByteExtractData *bed2 = NULL;
DetectByteExtractData *bed3 = NULL;
DetectByteExtractData *bed4 = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"uricontent: \"urione\"; "
"byte_extract:4,0,two,string,hex,relative; "
"byte_extract:4,0,three,string,hex,relative; "
"byte_extract:4,0,four,string,hex,relative; "
"byte_extract:4,0,five,string,hex,relative; "
"uricontent: \"four\"; within:two; distance:three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "urione", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed2 = (DetectByteExtractData *)sm->ctx;
if (bed2->local_id != 1) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed3 = (DetectByteExtractData *)sm->ctx;
if (bed3->local_id != 2) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed4 = (DetectByteExtractData *)sm->ctx;
if (bed4->local_id != 3) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (strncmp((char *)cd->content, "four", cd->content_len) != 0 ||
cd->flags != (DETECT_CONTENT_DISTANCE_BE |
DETECT_CONTENT_WITHIN_BE |
DETECT_CONTENT_DISTANCE |
DETECT_CONTENT_WITHIN) ||
cd->within != bed1->local_id ||
cd->distance != bed2->local_id) {
printf("four failed\n");
result = 0;
goto end;
}
if (sm->next != NULL) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest58(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectBytejumpData *bjd = NULL;
DetectIsdataatData *isdd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_jump: 2,two; "
"byte_jump: 3,three; "
"isdataat: three; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 1) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_ISDATAAT) {
result = 0;
goto end;
}
isdd = (DetectIsdataatData *)sm->ctx;
if (isdd->flags != ISDATAAT_OFFSET_BE ||
isdd->dataat != 1) {
printf("isdataat failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest59(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectBytejumpData *bjd = NULL;
DetectIsdataatData *isdd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex; "
"byte_extract:4,0,three,string,hex; "
"byte_jump: 2,two; "
"byte_jump: 3,three; "
"isdataat: three,relative; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
cd->flags & DETECT_CONTENT_RELATIVE_NEXT ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != DETECT_BYTE_EXTRACT_FLAG_STRING ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 0) {
printf("three failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTEJUMP) {
result = 0;
goto end;
}
bjd = (DetectBytejumpData *)sm->ctx;
if (bjd->flags != DETECT_BYTEJUMP_OFFSET_BE ||
bjd->offset != 1) {
printf("four failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_ISDATAAT) {
result = 0;
goto end;
}
isdd = (DetectIsdataatData *)sm->ctx;
if (isdd->flags != (ISDATAAT_OFFSET_BE |
ISDATAAT_RELATIVE) ||
isdd->dataat != 1) {
printf("isdataat failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest60(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectIsdataatData *isdd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex,relative; "
"uricontent: \"three\"; "
"byte_extract:4,0,four,string,hex,relative; "
"isdataat: two; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_ISDATAAT) {
result = 0;
goto end;
}
isdd = (DetectIsdataatData *)sm->ctx;
if (isdd->flags != (ISDATAAT_OFFSET_BE) ||
isdd->dataat != bed1->local_id) {
printf("isdataat failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
if (s->sm_lists_tail[DETECT_SM_LIST_UMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags != DETECT_CONTENT_RELATIVE_NEXT ||
strncmp((char *)cd->content, "three", cd->content_len) != 0) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "four") != 0 ||
bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest61(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectContentData *cd = NULL;
DetectByteExtractData *bed1 = NULL;
DetectIsdataatData *isdd = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(msg:\"Testing bytejump_body\"; "
"content:\"one\"; "
"byte_extract:4,0,two,string,hex,relative; "
"uricontent: \"three\"; "
"byte_extract:4,0,four,string,hex,relative; "
"isdataat: four, relative; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
result = 0;
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_PMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_PMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags & DETECT_CONTENT_RAWBYTES ||
strncmp((char *)cd->content, "one", cd->content_len) != 0 ||
cd->flags & DETECT_CONTENT_NOCASE ||
cd->flags & DETECT_CONTENT_WITHIN ||
cd->flags & DETECT_CONTENT_DISTANCE ||
cd->flags & DETECT_CONTENT_FAST_PATTERN ||
!(cd->flags & DETECT_CONTENT_RELATIVE_NEXT) ||
cd->flags & DETECT_CONTENT_NEGATED ) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "two") != 0 ||
bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
if (s->sm_lists_tail[DETECT_SM_LIST_UMATCH] == NULL) {
result = 0;
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_UMATCH];
if (sm->type != DETECT_CONTENT) {
result = 0;
goto end;
}
cd = (DetectContentData *)sm->ctx;
if (cd->flags != DETECT_CONTENT_RELATIVE_NEXT ||
strncmp((char *)cd->content, "three", cd->content_len) != 0) {
printf("one failed\n");
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed1 = (DetectByteExtractData *)sm->ctx;
if (bed1->nbytes != 4 ||
bed1->offset != 0 ||
strcmp(bed1->name, "four") != 0 ||
bed1->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING |
DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed1->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed1->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed1->align_value != 0 ||
bed1->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
if (bed1->local_id != 0) {
result = 0;
goto end;
}
sm = sm->next;
if (sm->type != DETECT_ISDATAAT) {
result = 0;
goto end;
}
isdd = (DetectIsdataatData *)sm->ctx;
if (isdd->flags != (ISDATAAT_OFFSET_BE |
ISDATAAT_RELATIVE) ||
isdd->dataat != bed1->local_id) {
printf("isdataat failed\n");
result = 0;
goto end;
}
if (sm->next != NULL)
goto end;
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
static int DetectByteExtractTest62(void)
{
DetectEngineCtx *de_ctx = NULL;
int result = 0;
Signature *s = NULL;
SigMatch *sm = NULL;
DetectByteExtractData *bed = NULL;
de_ctx = DetectEngineCtxInit();
if (de_ctx == NULL)
goto end;
de_ctx->flags |= DE_QUIET;
s = de_ctx->sig_list = SigInit(de_ctx, "alert tcp any any -> any any "
"(file_data; byte_extract:4,2,two,relative,string,hex; "
"sid:1;)");
if (de_ctx->sig_list == NULL) {
goto end;
}
if (s->sm_lists_tail[DETECT_SM_LIST_FILEDATA] == NULL) {
goto end;
}
sm = s->sm_lists[DETECT_SM_LIST_FILEDATA];
if (sm->type != DETECT_BYTE_EXTRACT) {
result = 0;
goto end;
}
bed = (DetectByteExtractData *)sm->ctx;
if (bed->nbytes != 4 ||
bed->offset != 2 ||
strncmp(bed->name, "two", 3) != 0 ||
bed->flags != (DETECT_BYTE_EXTRACT_FLAG_STRING | DETECT_BYTE_EXTRACT_FLAG_RELATIVE) ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_NONE ||
bed->base != DETECT_BYTE_EXTRACT_BASE_HEX ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
SigGroupCleanup(de_ctx);
SigCleanSignatures(de_ctx);
DetectEngineCtxFree(de_ctx);
return result;
}
int DetectByteExtractTest63(void)
{
int result = 0;
DetectByteExtractData *bed = DetectByteExtractParse("4, -2, one");
if (bed == NULL)
goto end;
if (bed->nbytes != 4 ||
bed->offset != -2 ||
strcmp(bed->name, "one") != 0 ||
bed->flags != 0 ||
bed->endian != DETECT_BYTE_EXTRACT_ENDIAN_DEFAULT ||
bed->base != DETECT_BYTE_EXTRACT_BASE_NONE ||
bed->align_value != 0 ||
bed->multiplier_value != DETECT_BYTE_EXTRACT_MULTIPLIER_DEFAULT) {
goto end;
}
result = 1;
end:
if (bed != NULL)
DetectByteExtractFree(bed);
return result;
}
#endif /* UNITTESTS */
void DetectByteExtractRegisterTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("DetectByteExtractTest01", DetectByteExtractTest01, 1);
UtRegisterTest("DetectByteExtractTest02", DetectByteExtractTest02, 1);
UtRegisterTest("DetectByteExtractTest03", DetectByteExtractTest03, 1);
UtRegisterTest("DetectByteExtractTest04", DetectByteExtractTest04, 1);
UtRegisterTest("DetectByteExtractTest05", DetectByteExtractTest05, 1);
UtRegisterTest("DetectByteExtractTest06", DetectByteExtractTest06, 1);
UtRegisterTest("DetectByteExtractTest07", DetectByteExtractTest07, 1);
UtRegisterTest("DetectByteExtractTest08", DetectByteExtractTest08, 1);
UtRegisterTest("DetectByteExtractTest09", DetectByteExtractTest09, 1);
UtRegisterTest("DetectByteExtractTest10", DetectByteExtractTest10, 1);
UtRegisterTest("DetectByteExtractTest11", DetectByteExtractTest11, 1);
UtRegisterTest("DetectByteExtractTest12", DetectByteExtractTest12, 1);
UtRegisterTest("DetectByteExtractTest13", DetectByteExtractTest13, 1);
UtRegisterTest("DetectByteExtractTest14", DetectByteExtractTest14, 1);
UtRegisterTest("DetectByteExtractTest15", DetectByteExtractTest15, 1);
UtRegisterTest("DetectByteExtractTest16", DetectByteExtractTest16, 1);
UtRegisterTest("DetectByteExtractTest17", DetectByteExtractTest17, 1);
UtRegisterTest("DetectByteExtractTest18", DetectByteExtractTest18, 1);
UtRegisterTest("DetectByteExtractTest19", DetectByteExtractTest19, 1);
UtRegisterTest("DetectByteExtractTest20", DetectByteExtractTest20, 1);
UtRegisterTest("DetectByteExtractTest21", DetectByteExtractTest21, 1);
UtRegisterTest("DetectByteExtractTest22", DetectByteExtractTest22, 1);
UtRegisterTest("DetectByteExtractTest23", DetectByteExtractTest23, 1);
UtRegisterTest("DetectByteExtractTest24", DetectByteExtractTest24, 1);
UtRegisterTest("DetectByteExtractTest25", DetectByteExtractTest25, 1);
UtRegisterTest("DetectByteExtractTest26", DetectByteExtractTest26, 1);
UtRegisterTest("DetectByteExtractTest27", DetectByteExtractTest27, 1);
UtRegisterTest("DetectByteExtractTest28", DetectByteExtractTest28, 1);
UtRegisterTest("DetectByteExtractTest29", DetectByteExtractTest29, 1);
UtRegisterTest("DetectByteExtractTest30", DetectByteExtractTest30, 1);
UtRegisterTest("DetectByteExtractTest31", DetectByteExtractTest31, 1);
UtRegisterTest("DetectByteExtractTest32", DetectByteExtractTest32, 1);
UtRegisterTest("DetectByteExtractTest33", DetectByteExtractTest33, 1);
UtRegisterTest("DetectByteExtractTest34", DetectByteExtractTest34, 1);
UtRegisterTest("DetectByteExtractTest35", DetectByteExtractTest35, 1);
UtRegisterTest("DetectByteExtractTest36", DetectByteExtractTest36, 1);
UtRegisterTest("DetectByteExtractTest37", DetectByteExtractTest37, 1);
UtRegisterTest("DetectByteExtractTest38", DetectByteExtractTest38, 1);
UtRegisterTest("DetectByteExtractTest39", DetectByteExtractTest39, 1);
UtRegisterTest("DetectByteExtractTest40", DetectByteExtractTest40, 1);
UtRegisterTest("DetectByteExtractTest41", DetectByteExtractTest41, 1);
UtRegisterTest("DetectByteExtractTest42", DetectByteExtractTest42, 1);
UtRegisterTest("DetectByteExtractTest43", DetectByteExtractTest43, 1);
UtRegisterTest("DetectByteExtractTest44", DetectByteExtractTest44, 1);
UtRegisterTest("DetectByteExtractTest45", DetectByteExtractTest45, 1);
UtRegisterTest("DetectByteExtractTest46", DetectByteExtractTest46, 1);
UtRegisterTest("DetectByteExtractTest47", DetectByteExtractTest47, 1);
UtRegisterTest("DetectByteExtractTest48", DetectByteExtractTest48, 1);
UtRegisterTest("DetectByteExtractTest49", DetectByteExtractTest49, 1);
UtRegisterTest("DetectByteExtractTest50", DetectByteExtractTest50, 1);
UtRegisterTest("DetectByteExtractTest51", DetectByteExtractTest51, 1);
UtRegisterTest("DetectByteExtractTest52", DetectByteExtractTest52, 1);
UtRegisterTest("DetectByteExtractTest53", DetectByteExtractTest53, 1);
UtRegisterTest("DetectByteExtractTest54", DetectByteExtractTest54, 1);
UtRegisterTest("DetectByteExtractTest55", DetectByteExtractTest55, 1);
UtRegisterTest("DetectByteExtractTest56", DetectByteExtractTest56, 1);
UtRegisterTest("DetectByteExtractTest57", DetectByteExtractTest57, 1);
UtRegisterTest("DetectByteExtractTest58", DetectByteExtractTest58, 1);
UtRegisterTest("DetectByteExtractTest59", DetectByteExtractTest59, 1);
UtRegisterTest("DetectByteExtractTest60", DetectByteExtractTest60, 1);
UtRegisterTest("DetectByteExtractTest61", DetectByteExtractTest61, 1);
UtRegisterTest("DetectByteExtractTest62", DetectByteExtractTest62, 1);
UtRegisterTest("DetectByteExtractTest63", DetectByteExtractTest63, 1);
#endif /* UNITTESTS */
return;
}
| vsol75/suricata | src/detect-byte-extract.c | C | gpl-2.0 | 154,251 |
// license:BSD-3-Clause
// copyright-holders:F.Ulivi
/***************************************************************************
dipty.h
Device PTY interface
***************************************************************************/
#ifndef MAME_EMU_DIPTY_H
#define MAME_EMU_DIPTY_H
class device_pty_interface : public device_interface
{
public:
// construction/destruction
device_pty_interface(const machine_config &mconfig, device_t &device);
virtual ~device_pty_interface();
bool open();
void close();
bool is_open() const;
ssize_t read(u8 *rx_chars , size_t count) const;
void write(u8 tx_char) const;
bool is_slave_connected() const;
const char *slave_name() const;
protected:
osd_file::ptr m_pty_master;
std::string m_slave_name;
bool m_opened;
};
// iterator
typedef device_interface_enumerator<device_pty_interface> pty_interface_enumerator;
#endif // MAME_EMU_DIPTY_H
| johnparker007/mame | src/emu/dipty.h | C | gpl-2.0 | 914 |
/*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* This program 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
* of the License, or (at your option) any later version.
*
* This program 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 program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
using System;
using DOL.Database;
using DOL.GS.PacketHandler;
using DOL.Events;
using DOL.GS.ServerRules;
namespace DOL.GS.GameEvents
{
/// <summary>
/// Handles Tutorial Jump Point Exits
/// </summary>
public class TutorialJumpPointHandler : IJumpPointHandler
{
/// <summary>
/// Decides whether player can jump to the target point.
/// All messages with reasons must be sent here.
/// Can change destination too.
/// </summary>
/// <param name="targetPoint">The jump destination</param>
/// <param name="player">The jumping player</param>
/// <returns>True if allowed</returns>
public bool IsAllowedToJump(ZonePoint targetPoint, GamePlayer player)
{
StartupLocation loc = StartupLocations.GetNonTutorialLocation(player);
if (loc != null)
{
targetPoint.TargetX = loc.XPos;
targetPoint.TargetY = loc.YPos;
targetPoint.TargetZ = loc.ZPos;
targetPoint.TargetHeading = (ushort)loc.Heading;
targetPoint.TargetRegion = (ushort)loc.Region;
return true;
}
return false;
}
}
}
| Dawn-of-Light/DOLSharp | GameServerScripts/gameevents/TutorialJumpPointHandler.cs | C# | gpl-2.0 | 1,894 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.