repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
reaction1989/roslyn | src/Compilers/Core/Portable/InternalUtilities/ThreadSafeFlagOperations.cs | 1280 | // 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.
#nullable enable
using System.Threading;
namespace Roslyn.Utilities
{
internal static class ThreadSafeFlagOperations
{
public static bool Set(ref int flags, int toSet)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState | toSet;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
public static bool Clear(ref int flags, int toClear)
{
int oldState, newState;
do
{
oldState = flags;
newState = oldState & ~toClear;
if (newState == oldState)
{
return false;
}
}
while (Interlocked.CompareExchange(ref flags, newState, oldState) != oldState);
return true;
}
}
}
| apache-2.0 |
jackgr/kubernetes | pkg/client/unversioned/testclient/fake_limit_ranges.go | 2345 | /*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package testclient
import (
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/watch"
)
// FakeLimitRanges implements PodsInterface. Meant to be embedded into a struct to get a default
// implementation. This makes faking out just the methods you want to test easier.
type FakeLimitRanges struct {
Fake *Fake
Namespace string
}
func (c *FakeLimitRanges) Get(name string) (*api.LimitRange, error) {
obj, err := c.Fake.Invokes(NewGetAction("limitranges", c.Namespace, name), &api.LimitRange{})
if obj == nil {
return nil, err
}
return obj.(*api.LimitRange), err
}
func (c *FakeLimitRanges) List(opts unversioned.ListOptions) (*api.LimitRangeList, error) {
obj, err := c.Fake.Invokes(NewListAction("limitranges", c.Namespace, opts), &api.LimitRangeList{})
if obj == nil {
return nil, err
}
return obj.(*api.LimitRangeList), err
}
func (c *FakeLimitRanges) Create(limitRange *api.LimitRange) (*api.LimitRange, error) {
obj, err := c.Fake.Invokes(NewCreateAction("limitranges", c.Namespace, limitRange), limitRange)
if obj == nil {
return nil, err
}
return obj.(*api.LimitRange), err
}
func (c *FakeLimitRanges) Update(limitRange *api.LimitRange) (*api.LimitRange, error) {
obj, err := c.Fake.Invokes(NewUpdateAction("limitranges", c.Namespace, limitRange), limitRange)
if obj == nil {
return nil, err
}
return obj.(*api.LimitRange), err
}
func (c *FakeLimitRanges) Delete(name string) error {
_, err := c.Fake.Invokes(NewDeleteAction("limitranges", c.Namespace, name), &api.LimitRange{})
return err
}
func (c *FakeLimitRanges) Watch(opts unversioned.ListOptions) (watch.Interface, error) {
return c.Fake.InvokesWatch(NewWatchAction("limitranges", c.Namespace, opts))
}
| apache-2.0 |
rahulunair/nova | nova/virt/powervm/tasks/image.py | 3270 | # Copyright 2015, 2018 IBM Corp.
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from taskflow import task
from nova.virt.powervm import image
LOG = logging.getLogger(__name__)
class UpdateTaskState(task.Task):
def __init__(self, update_task_state, task_state, expected_state=None):
"""Invoke the update_task_state callback with the desired arguments.
:param update_task_state: update_task_state callable passed into
snapshot.
:param task_state: The new task state (from nova.compute.task_states)
to set.
:param expected_state: Optional. The expected state of the task prior
to this request.
"""
self.update_task_state = update_task_state
self.task_state = task_state
self.kwargs = {}
if expected_state is not None:
# We only want to pass expected state if it's not None! That's so
# we take the update_task_state method's default.
self.kwargs['expected_state'] = expected_state
super(UpdateTaskState, self).__init__(
name='update_task_state_%s' % task_state)
def execute(self):
self.update_task_state(self.task_state, **self.kwargs)
class StreamToGlance(task.Task):
"""Task around streaming a block device to glance."""
def __init__(self, context, image_api, image_id, instance):
"""Initialize the flow for streaming a block device to glance.
Requires: disk_path: Path to the block device file for the instance's
boot disk.
:param context: Nova security context.
:param image_api: Handle to the glance API.
:param image_id: UUID of the prepared glance image.
:param instance: Instance whose backing device is being captured.
"""
self.context = context
self.image_api = image_api
self.image_id = image_id
self.instance = instance
super(StreamToGlance, self).__init__(name='stream_to_glance',
requires='disk_path')
def execute(self, disk_path):
metadata = image.generate_snapshot_metadata(
self.context, self.image_api, self.image_id, self.instance)
LOG.info("Starting stream of boot device (local blockdev %(devpath)s) "
"to glance image %(img_id)s.",
{'devpath': disk_path, 'img_id': self.image_id},
instance=self.instance)
image.stream_blockdev_to_glance(self.context, self.image_api,
self.image_id, metadata, disk_path)
| apache-2.0 |
nigbubski/f1livetiming | F1/Data/Packets/SimplePacket.cs | 1229 | /*
* f1livetiming - Part of the Live Timing Library for .NET
* Copyright (C) 2009 Liam Lowey
*
* http://livetiming.turnitin.co.uk/
*
* 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.
*/
using System.IO;
namespace F1.Data.Packets
{
/// <summary>
/// This packet allows the calling message type decide how much data to receive as
/// it is not included in the Header.
/// </summary>
public class SimplePacket : Packet
{
public SimplePacket(int readSize, Stream input)
: base(input)
{
AcquirePayload(readSize);
}
public byte[] Data { get { return Payload; } }
}
} | apache-2.0 |
kuali/rice-playground | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/uif/freemarker/FreeMarkerOpenGroupWrapAdaptor.java | 1622 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.uif.freemarker;
import java.io.IOException;
import java.io.Serializable;
import org.kuali.rice.krad.uif.container.Group;
import freemarker.core.Environment;
import freemarker.core.InlineTemplateAdaptor;
import freemarker.template.TemplateException;
/**
* Inline FreeMarker template adaptor for supporting groupWrap.ftl
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class FreeMarkerOpenGroupWrapAdaptor implements InlineTemplateAdaptor, Serializable {
private static final long serialVersionUID = 2727212194328393817L;
/**
* Render a opening elements for wrapping a group component inline.
*
* {@inheritDoc}
*/
@Override
public void accept(Environment env) throws TemplateException, IOException {
Group group = FreeMarkerInlineRenderUtils.resolve(env, "group", Group.class);
FreeMarkerInlineRenderUtils.renderOpenGroupWrap(env, group);
}
}
| apache-2.0 |
cstroe/yajsw | src/hessian/src/main/java/com/caucho/hessian4/HessianException.java | 2827 | /*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* 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 end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 CAUCHO TECHNOLOGY OR ITS 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.
*
* @author Scott Ferguson
*/
package com.caucho.hessian4;
/**
* Base runtime exception for Hessian exceptions.
*/
public class HessianException extends RuntimeException {
/**
* Zero-arg constructor.
*/
public HessianException()
{
}
/**
* Create the exception.
*/
public HessianException(String message)
{
super(message);
}
/**
* Create the exception.
*/
public HessianException(String message, Throwable rootCause)
{
super(message, rootCause);
}
/**
* Create the exception.
*/
public HessianException(Throwable rootCause)
{
super(rootCause);
}
}
| apache-2.0 |
phinexus/jenkins-job-builder | jenkins_jobs/modules/reporters.py | 5779 | # Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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.
"""
Reporters are like publishers but only applicable to Maven projects.
**Component**: reporters
:Macro: reporter
:Entry Point: jenkins_jobs.reporters
Example::
job:
name: test_job
project-type: maven
reporters:
- email:
recipients: breakage@example.com
"""
import xml.etree.ElementTree as XML
from jenkins_jobs.errors import JenkinsJobsException
import jenkins_jobs.modules.base
from jenkins_jobs.modules.helpers import build_trends_publisher
from jenkins_jobs.modules.helpers import findbugs_settings
def email(registry, xml_parent, data):
"""yaml: email
Email notifications on build failure.
:arg str recipients: Recipient email addresses
:arg bool notify-every-unstable-build: Send an email for every
unstable build (default true)
:arg bool send-to-individuals: Send an email to the individual
who broke the build (default false)
:arg bool notify-for-each-module: Send an email for each module
(e.g. failed, unstable). (default true)
Example::
reporters:
- email:
recipients: breakage@example.com
"""
mailer = XML.SubElement(xml_parent,
'hudson.maven.reporters.MavenMailer')
XML.SubElement(mailer, 'recipients').text = data['recipients']
# Note the logic reversal (included here to match the GUI
if data.get('notify-every-unstable-build', True):
XML.SubElement(mailer, 'dontNotifyEveryUnstableBuild').text = 'false'
else:
XML.SubElement(mailer, 'dontNotifyEveryUnstableBuild').text = 'true'
XML.SubElement(mailer, 'sendToIndividuals').text = str(
data.get('send-to-individuals', False)).lower()
XML.SubElement(mailer, 'perModuleEmail').text = str(
data.get('notify-for-every-module', True)).lower()
def findbugs(registry, xml_parent, data):
"""yaml: findbugs
FindBugs reporting for builds
Requires the Jenkins :jenkins-wiki:`FindBugs Plugin
<FindBugs+Plugin>`.
:arg bool rank-priority: Use rank as priority (default false)
:arg str include-files: Comma separated list of files to include.
(Optional)
:arg str exclude-files: Comma separated list of files to exclude.
(Optional)
:arg bool can-run-on-failed: Weather or not to run plug-in on failed builds
(default false)
:arg int healthy: Sunny threshold (optional)
:arg int unhealthy: Stormy threshold (optional)
:arg str health-threshold: Threshold priority for health status
('low', 'normal' or 'high', defaulted to 'low')
:arg bool dont-compute-new: If set to false, computes new warnings based on
the reference build (default true)
:arg bool use-delta-values: Use delta for new warnings. (default false)
:arg bool use-previous-build-as-reference: If set then the number of new
warnings will always be calculated based on the previous build.
Otherwise the reference build. (default false)
:arg bool use-stable-build-as-reference: The number of new warnings will be
calculated based on the last stable build, allowing reverts of unstable
builds where the number of warnings was decreased. (default false)
:arg dict thresholds:
:thresholds:
* **unstable** (`dict`)
:unstable: * **total-all** (`int`)
* **total-high** (`int`)
* **total-normal** (`int`)
* **total-low** (`int`)
* **new-all** (`int`)
* **new-high** (`int`)
* **new-normal** (`int`)
* **new-low** (`int`)
* **failed** (`dict`)
:failed: * **total-all** (`int`)
* **total-high** (`int`)
* **total-normal** (`int`)
* **total-low** (`int`)
* **new-all** (`int`)
* **new-high** (`int`)
* **new-normal** (`int`)
* **new-low** (`int`)
Minimal Example:
.. literalinclude:: /../../tests/reporters/fixtures/findbugs-minimal.yaml
Full Example:
.. literalinclude:: /../../tests/reporters/fixtures/findbugs01.yaml
"""
findbugs = XML.SubElement(xml_parent,
'hudson.plugins.findbugs.FindBugsReporter')
findbugs.set('plugin', 'findbugs')
findbugs_settings(findbugs, data)
build_trends_publisher('[FINDBUGS] ', findbugs, data)
class Reporters(jenkins_jobs.modules.base.Base):
sequence = 55
component_type = 'reporter'
component_list_type = 'reporters'
def gen_xml(self, xml_parent, data):
if 'reporters' not in data:
return
if xml_parent.tag != 'maven2-moduleset':
raise JenkinsJobsException("Reporters may only be used for Maven "
"modules.")
reporters = XML.SubElement(xml_parent, 'reporters')
for action in data.get('reporters', []):
self.registry.dispatch('reporter', reporters, action)
| apache-2.0 |
enj/origin | pkg/monitor/operator.go | 8960 | package monitor
import (
"context"
"fmt"
"strings"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
configv1 "github.com/openshift/api/config/v1"
configclientset "github.com/openshift/client-go/config/clientset/versioned"
)
func startClusterOperatorMonitoring(ctx context.Context, m Recorder, client configclientset.Interface) {
coInformer := cache.NewSharedIndexInformer(
NewErrorRecordingListWatcher(m, &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
return client.ConfigV1().ClusterOperators().List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return client.ConfigV1().ClusterOperators().Watch(options)
},
}),
&configv1.ClusterOperator{},
time.Hour,
nil,
)
coChangeFns := []func(co, oldCO *configv1.ClusterOperator) []Condition{
func(co, oldCO *configv1.ClusterOperator) []Condition {
var conditions []Condition
for i := range co.Status.Conditions {
s := &co.Status.Conditions[i]
previous := findOperatorStatusCondition(oldCO.Status.Conditions, s.Type)
if previous == nil {
continue
}
if s.Status != previous.Status {
var msg string
switch {
case len(s.Reason) > 0 && len(s.Message) > 0:
msg = fmt.Sprintf("changed %s to %s: %s: %s", s.Type, s.Status, s.Reason, s.Message)
case len(s.Message) > 0:
msg = fmt.Sprintf("changed %s to %s: %s", s.Type, s.Status, s.Message)
default:
msg = fmt.Sprintf("changed %s to %s", s.Type, s.Status)
}
level := Warning
if s.Type == configv1.OperatorDegraded && s.Status == configv1.ConditionTrue {
level = Error
}
if s.Type == configv1.ClusterStatusConditionType("Failing") && s.Status == configv1.ConditionTrue {
level = Error
}
conditions = append(conditions, Condition{
Level: level,
Locator: locateClusterOperator(co),
Message: msg,
})
}
}
if changes := findOperatorVersionChange(oldCO.Status.Versions, co.Status.Versions); len(changes) > 0 {
conditions = append(conditions, Condition{
Level: Info,
Locator: locateClusterOperator(co),
Message: fmt.Sprintf("versions: %v", strings.Join(changes, ", ")),
})
}
return conditions
},
}
startTime := time.Now().Add(-time.Minute)
coInformer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
co, ok := obj.(*configv1.ClusterOperator)
if !ok {
return
}
// filter out old pods so our monitor doesn't send a big chunk
// of co creations
if co.CreationTimestamp.Time.Before(startTime) {
return
}
m.Record(Condition{
Level: Info,
Locator: locateClusterOperator(co),
Message: "created",
})
},
DeleteFunc: func(obj interface{}) {
co, ok := obj.(*configv1.ClusterOperator)
if !ok {
return
}
m.Record(Condition{
Level: Warning,
Locator: locateClusterOperator(co),
Message: "deleted",
})
},
UpdateFunc: func(old, obj interface{}) {
co, ok := obj.(*configv1.ClusterOperator)
if !ok {
return
}
oldCO, ok := old.(*configv1.ClusterOperator)
if !ok {
return
}
if co.UID != oldCO.UID {
return
}
for _, fn := range coChangeFns {
m.Record(fn(co, oldCO)...)
}
},
},
)
go coInformer.Run(ctx.Done())
cvInformer := cache.NewSharedIndexInformer(
NewErrorRecordingListWatcher(m, &cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = "metadata.name=version"
return client.ConfigV1().ClusterVersions().List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = "metadata.name=version"
return client.ConfigV1().ClusterVersions().Watch(options)
},
}),
&configv1.ClusterVersion{},
time.Hour,
nil,
)
cvChangeFns := []func(cv, oldCV *configv1.ClusterVersion) []Condition{
func(cv, oldCV *configv1.ClusterVersion) []Condition {
var conditions []Condition
if len(cv.Status.History) == 0 {
return nil
}
if len(oldCV.Status.History) == 0 {
conditions = append(conditions, Condition{
Level: Warning,
Locator: locateClusterVersion(cv),
Message: fmt.Sprintf("cluster converging to %s", cv.Status.History[0].Version),
})
return conditions
}
cvNew, cvOld := cv.Status.History[0], oldCV.Status.History[0]
switch {
case cvNew.State == configv1.CompletedUpdate && cvOld.State != cvNew.State:
conditions = append(conditions, Condition{
Level: Warning,
Locator: locateClusterVersion(cv),
Message: fmt.Sprintf("cluster reached %s", cvNew.Version),
})
case cvNew.State == configv1.PartialUpdate && cvOld.State == cvNew.State && cvOld.Image != cvNew.Image:
conditions = append(conditions, Condition{
Level: Warning,
Locator: locateClusterVersion(cv),
Message: fmt.Sprintf("cluster upgrading to %s without completing %s", cvNew.Version, cvOld.Version),
})
}
return conditions
},
func(cv, oldCV *configv1.ClusterVersion) []Condition {
var conditions []Condition
for i := range cv.Status.Conditions {
s := &cv.Status.Conditions[i]
previous := findOperatorStatusCondition(oldCV.Status.Conditions, s.Type)
if previous == nil {
continue
}
if s.Status != previous.Status {
var msg string
switch {
case len(s.Reason) > 0 && len(s.Message) > 0:
msg = fmt.Sprintf("changed %s to %s: %s: %s", s.Type, s.Status, s.Reason, s.Message)
case len(s.Message) > 0:
msg = fmt.Sprintf("changed %s to %s: %s", s.Type, s.Status, s.Message)
default:
msg = fmt.Sprintf("changed %s to %s", s.Type, s.Status)
}
level := Warning
if s.Type == configv1.OperatorDegraded && s.Status == configv1.ConditionTrue {
level = Error
}
if s.Type == configv1.ClusterStatusConditionType("Failing") && s.Status == configv1.ConditionTrue {
level = Error
}
conditions = append(conditions, Condition{
Level: level,
Locator: locateClusterVersion(cv),
Message: msg,
})
}
}
return conditions
},
}
cvInformer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
cv, ok := obj.(*configv1.ClusterVersion)
if !ok {
return
}
// filter out old pods so our monitor doesn't send a big chunk
// of co creations
if cv.CreationTimestamp.Time.Before(startTime) {
return
}
m.Record(Condition{
Level: Info,
Locator: locateClusterVersion(cv),
Message: "created",
})
},
DeleteFunc: func(obj interface{}) {
cv, ok := obj.(*configv1.ClusterVersion)
if !ok {
return
}
m.Record(Condition{
Level: Warning,
Locator: locateClusterVersion(cv),
Message: "deleted",
})
},
UpdateFunc: func(old, obj interface{}) {
cv, ok := obj.(*configv1.ClusterVersion)
if !ok {
return
}
oldCV, ok := old.(*configv1.ClusterVersion)
if !ok {
return
}
if cv.UID != oldCV.UID {
return
}
for _, fn := range cvChangeFns {
m.Record(fn(cv, oldCV)...)
}
},
},
)
m.AddSampler(func(now time.Time) []*Condition {
var conditions []*Condition
for _, obj := range cvInformer.GetStore().List() {
cv, ok := obj.(*configv1.ClusterVersion)
if !ok {
continue
}
if len(cv.Status.History) > 0 {
if cv.Status.History[0].State != configv1.CompletedUpdate {
conditions = append(conditions, &Condition{
Level: Warning,
Locator: locateClusterVersion(cv),
Message: fmt.Sprintf("cluster is updating to %s", cv.Status.History[0].Version),
})
}
}
}
return conditions
})
go cvInformer.Run(ctx.Done())
}
func locateClusterOperator(co *configv1.ClusterOperator) string {
return fmt.Sprintf("clusteroperator/%s", co.Name)
}
func locateClusterVersion(cv *configv1.ClusterVersion) string {
return fmt.Sprintf("clusterversion/%s", cv.Name)
}
func findOperatorVersionChange(old, new []configv1.OperandVersion) []string {
var changed []string
for i := 0; i < len(new); i++ {
for j := 0; j < len(old); j++ {
p := (j + i) % len(old)
if old[p].Name != new[i].Name {
continue
}
if old[p].Version == new[i].Version {
break
}
changed = append(changed, fmt.Sprintf("%s %s -> %s", new[i].Name, old[p].Version, new[i].Version))
break
}
}
return changed
}
func findOperatorStatusCondition(conditions []configv1.ClusterOperatorStatusCondition, conditionType configv1.ClusterStatusConditionType) *configv1.ClusterOperatorStatusCondition {
for i := range conditions {
if conditions[i].Type == conditionType {
return &conditions[i]
}
}
return nil
}
| apache-2.0 |
nevali/shindig | java/gadgets/src/main/java/org/apache/shindig/gadgets/spec/LinkSpec.java | 2227 | /*
* 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.shindig.gadgets.spec;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.common.xml.XmlUtil;
import org.apache.shindig.gadgets.variables.Substitutions;
import org.w3c.dom.Element;
/**
* Represents /ModulePrefs/Link elements.
*/
public class LinkSpec {
private final Uri base;
public LinkSpec(Element element, Uri base) throws SpecParserException {
this.base = base;
rel = XmlUtil.getAttribute(element, "rel");
if (rel == null) {
throw new SpecParserException("Link/@rel is required!");
}
href = XmlUtil.getUriAttribute(element, "href");
if (href == null) {
throw new SpecParserException("Link/@href is required!");
}
}
private LinkSpec(LinkSpec rhs, Substitutions substitutions) {
rel = substitutions.substituteString(rhs.rel);
base = rhs.base;
href = base.resolve(substitutions.substituteUri(rhs.href));
}
/**
* Link/@rel
*/
private final String rel;
public String getRel() {
return rel;
}
/**
* Link/@href
*/
private final Uri href;
public Uri getHref() {
return href;
}
/**
* Performs variable substitution on all visible elements.
*/
public LinkSpec substitute(Substitutions substitutions) {
return new LinkSpec(this, substitutions);
}
@Override
public String toString() {
return "<Link rel='" + rel + "' href='" + href.toString() + "'/>";
}
}
| apache-2.0 |
ibek/droolsjbpm-integration | kie-spring/src/test/java/org/kie/spring/tests/KieSpringScopeTest.java | 3375 | /*
* Copyright 2013 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.kie.spring.tests;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.spring.beans.Person;
import org.kie.spring.beans.SampleBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class KieSpringScopeTest {
static ApplicationContext context = null;
@BeforeClass
public static void setup() {
context = new ClassPathXmlApplicationContext("org/kie/spring/beans-with-scope.xml");
}
@Test
public void testContext() throws Exception {
assertNotNull(context);
}
@Test
public void testStatelessPrototypeKieSession() throws Exception {
StatelessKieSession ksession = (StatelessKieSession) context.getBean("statelessPrototypeSession");
assertNotNull(ksession);
StatelessKieSession anotherKsession = (StatelessKieSession) context.getBean("statelessPrototypeSession");
assertNotNull(anotherKsession);
assertNotEquals(ksession.hashCode(), anotherKsession.hashCode());
}
@Test
public void testStatelessSingletonKieSession() throws Exception {
StatelessKieSession ksession = (StatelessKieSession) context.getBean("statelessSingletonSession");
assertNotNull(ksession);
StatelessKieSession anotherKsession = (StatelessKieSession) context.getBean("statelessSingletonSession");
assertNotNull(anotherKsession);
assertEquals(ksession.hashCode(), anotherKsession.hashCode());
}
@Test
public void testStatefulSingletonKieSession() throws Exception {
KieSession ksession = (KieSession) context.getBean("statefulSingletonSession");
assertNotNull(ksession);
KieSession anotherKsession = (KieSession) context.getBean("statefulSingletonSession");
assertNotNull(anotherKsession);
assertEquals(ksession.hashCode(), anotherKsession.hashCode());
}
@Test
public void testStatefulPrototypeKieSession() throws Exception {
KieSession ksession = (KieSession) context.getBean("statefulPrototypeSession");
assertNotNull(ksession);
KieSession anotherKsession = (KieSession) context.getBean("statefulPrototypeSession");
assertNotNull(anotherKsession);
assertNotEquals(ksession.hashCode(), anotherKsession.hashCode());
}
@AfterClass
public static void tearDown() {
}
}
| apache-2.0 |
azkaban/azkaban | azkaban-common/src/test/java/azkaban/executor/ExecutorDaoTest.java | 6608 | /*
* Copyright 2017 LinkedIn Corp.
*
* 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 azkaban.executor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import azkaban.db.DatabaseOperator;
import azkaban.test.Utils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ExecutorDaoTest {
private static DatabaseOperator dbOperator;
private ExecutorDao executorDao;
@BeforeClass
public static void setUp() throws Exception {
dbOperator = Utils.initTestDB();
}
@AfterClass
public static void destroyDB() throws Exception {
try {
dbOperator.update("DROP ALL OBJECTS");
dbOperator.update("SHUTDOWN");
} catch (final SQLException e) {
e.printStackTrace();
}
}
@Before
public void setup() {
this.executorDao = new ExecutorDao(dbOperator);
}
@After
public void clearDB() {
try {
dbOperator.update("delete from executors");
} catch (final SQLException e) {
e.printStackTrace();
}
}
/* Test all executors fetch from empty executors */
@Test
public void testFetchEmptyExecutors() throws Exception {
final List<Executor> executors = this.executorDao.fetchAllExecutors();
assertThat(executors.size()).isEqualTo(0);
}
/* Test active executors fetch from empty executors */
@Test
public void testFetchEmptyActiveExecutors() throws Exception {
final List<Executor> executors = this.executorDao.fetchActiveExecutors();
assertThat(executors.size()).isEqualTo(0);
}
/* Test missing executor fetch with search by executor id */
@Test
public void testFetchMissingExecutorId() throws Exception {
final Executor executor = this.executorDao.fetchExecutor(0);
assertThat(executor).isEqualTo(null);
}
/* Test missing executor fetch with search by host:port */
@Test
public void testFetchMissingExecutorHostPort() throws Exception {
final Executor executor = this.executorDao.fetchExecutor("localhost", 12345);
assertThat(executor).isEqualTo(null);
}
/* Test to add duplicate executors */
@Test
public void testDuplicateAddExecutor() throws Exception {
final String host = "localhost";
final int port = 12345;
this.executorDao.addExecutor(host, port);
assertThatThrownBy(() -> this.executorDao.addExecutor(host, port))
.isInstanceOf(ExecutorManagerException.class)
.hasMessageContaining("already exist");
}
/* Test to try update a non-existent executor */
@Test
public void testMissingExecutorUpdate() throws Exception {
final Executor executor = new Executor(1, "localhost", 1234, true);
assertThatThrownBy(() -> this.executorDao.updateExecutor(executor))
.isInstanceOf(ExecutorManagerException.class)
.hasMessageContaining("No executor with id");
}
/* Test add & fetch by Id Executors */
@Test
public void testSingleExecutorFetchById() throws Exception {
final List<Executor> executors = addTestExecutors();
for (final Executor executor : executors) {
final Executor fetchedExecutor = this.executorDao.fetchExecutor(executor.getId());
assertThat(executor).isEqualTo(fetchedExecutor);
}
}
/* Test fetch all executors */
@Test
public void testFetchAllExecutors() throws Exception {
final List<Executor> executors = addTestExecutors();
executors.get(0).setActive(false);
this.executorDao.updateExecutor(executors.get(0));
final List<Executor> fetchedExecutors = this.executorDao.fetchAllExecutors();
assertThat(executors.size()).isEqualTo(fetchedExecutors.size());
assertThat(executors.toArray()).isEqualTo(fetchedExecutors.toArray());
}
/* Test fetch only active executors */
@Test
public void testFetchActiveExecutors() throws Exception {
final List<Executor> executors = addTestExecutors();
executors.get(0).setActive(true);
this.executorDao.updateExecutor(executors.get(0));
final List<Executor> fetchedExecutors = this.executorDao.fetchActiveExecutors();
assertThat(executors.size()).isEqualTo(fetchedExecutors.size() + 2);
assertThat(executors.get(0)).isEqualTo(fetchedExecutors.get(0));
}
/* Test add & fetch by host:port Executors */
@Test
public void testSingleExecutorFetchHostPort() throws Exception {
final List<Executor> executors = addTestExecutors();
for (final Executor executor : executors) {
final Executor fetchedExecutor =
this.executorDao.fetchExecutor(executor.getHost(), executor.getPort());
assertThat(executor).isEqualTo(fetchedExecutor);
}
}
/* Helper method used in methods testing jdbc interface for executors table */
private List<Executor> addTestExecutors()
throws ExecutorManagerException {
final List<Executor> executors = new ArrayList<>();
executors.add(this.executorDao.addExecutor("localhost1", 12345));
executors.add(this.executorDao.addExecutor("localhost2", 12346));
executors.add(this.executorDao.addExecutor("localhost1", 12347));
return executors;
}
/* Test Removing Executor */
@Test
public void testRemovingExecutor() throws Exception {
final Executor executor = this.executorDao.addExecutor("localhost1", 12345);
assertThat(executor).isNotNull();
this.executorDao.removeExecutor("localhost1", 12345);
final Executor fetchedExecutor = this.executorDao.fetchExecutor("localhost1", 12345);
assertThat(fetchedExecutor).isNull();
}
/* Test Executor reactivation */
@Test
public void testExecutorActivation() throws Exception {
final Executor executor = this.executorDao.addExecutor("localhost1", 12345);
assertThat(executor.isActive()).isFalse();
executor.setActive(true);
this.executorDao.updateExecutor(executor);
final Executor fetchedExecutor = this.executorDao.fetchExecutor(executor.getId());
assertThat(fetchedExecutor.isActive()).isTrue();
}
}
| apache-2.0 |
baslr/ArangoDB | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/expressions/unary-plus/S11.4.6_A3_T3.js | 557 | // 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 ToNumber(x)
es5id: 11.4.6_A3_T3
description: Type(x) is string primitive or String object
---*/
//CHECK#1
if (+"1" !== 1) {
$ERROR('#1: +"1" === 1. Actual: ' + (+"1"));
}
//CHECK#2
if (isNaN(+"x") !== true) {
$ERROR('#2: +"x" === Not-a-Number. Actual: ' + (+"x"));
}
//CHECK#3
if (+new Number("-1") !== -1) {
$ERROR('#3: +new String("-1") === -1. Actual: ' + (+new String("-1")));
}
| apache-2.0 |
yiaslu/qbpDemo | ManageUI/Demos/lib/ligerUI/js/plugins/ligerRadioList.js | 11226 | /**
* jQuery ligerUI 1.3.3
*
* http://ligerui.com
*
* Author daomi 2015 [ gd_star@163.com ]
*
*/
(function ($)
{
$.fn.ligerRadioList = function (options)
{
return $.ligerui.run.call(this, "ligerRadioList", arguments);
};
$.ligerDefaults.RadioList = {
rowSize: 3, //每行显示元素数
valueField: 'id', //值成员
textField: 'text', //显示成员
valueFieldID: null, //隐藏域
name: null, //表单名
data: null, //数据
parms: null, //ajax提交表单
url: null, //数据源URL(需返回JSON)
urlParms: null, //url带参数
ajaxContentType: null,
ajaxType: 'post',
onSuccess: null,
onError: null,
onSelect: null,
css: null, //附加css
value: null, //值
valueFieldCssClass: null
};
//扩展方法
$.ligerMethos.RadioList = $.ligerMethos.RadioList || {};
$.ligerui.controls.RadioList = function (element, options)
{
$.ligerui.controls.RadioList.base.constructor.call(this, element, options);
};
$.ligerui.controls.RadioList.ligerExtend($.ligerui.controls.Input, {
__getType: function ()
{
return 'RadioList';
},
_extendMethods: function ()
{
return $.ligerMethos.RadioList;
},
_init: function ()
{
$.ligerui.controls.RadioList.base._init.call(this);
},
_render: function ()
{
var g = this, p = this.options;
g.data = p.data;
g.valueField = null; //隐藏域(保存值)
if ($(this.element).is(":hidden") || $(this.element).is(":text"))
{
g.valueField = $(this.element);
if ($(this.element).is(":text"))
{
g.valueField.hide();
}
}
else if (p.valueFieldID)
{
g.valueField = $("#" + p.valueFieldID + ":input,[name=" + p.valueFieldID + "]:input");
if (g.valueField.length == 0) g.valueField = $('<input type="hidden"/>');
g.valueField[0].id = g.valueField[0].name = p.valueFieldID;
}
else
{
g.valueField = $('<input type="hidden"/>');
g.valueField[0].id = g.valueField[0].name = g.id + "_val";
}
if (g.valueField[0].name == null) g.valueField[0].name = g.valueField[0].id;
if (p.valueFieldCssClass)
{
g.valueField.addClass(p.valueFieldCssClass);
}
g.valueField.attr("data-ligerid", g.id);
if ($(this.element).is(":hidden") || $(this.element).is(":text"))
{
g.radioList = $('<div></div>').insertBefore(this.element);
} else
{
g.radioList = $(this.element);
}
g.radioList.html('<div class="l-radiolist-inner"><table cellpadding="0" cellspacing="0" border="0" class="l-radiolist-table"></table></div>').addClass("l-radiolist").append(g.valueField);
g.radioList.table = $("table:first", g.radioList);
p.value = g.valueField.val() || p.value;
g.set(p);
g._addClickEven();
},
destroy: function ()
{
if (this.radioList) this.radioList.remove();
this.options = null;
$.ligerui.remove(this);
},
clear: function ()
{
this._changeValue("");
this.trigger('clear');
},
_setCss: function (css)
{
if (css)
{
this.radioList.addClass(css);
}
},
_setDisabled: function (value)
{
//禁用样式
if (value)
{
this.radioList.addClass('l-radiolist-disabled');
$("input:radio", this.radioList).attr("disabled", true);
} else
{
this.radioList.removeClass('l-radiolist-disabled');
$("input:radio", this.radioList).removeAttr("disabled");
}
},
_setWidth: function (value)
{
this.radioList.width(value);
},
_setHeight: function (value)
{
this.radioList.height(value);
},
indexOf: function (item)
{
var g = this, p = this.options;
if (!g.data) return -1;
for (var i = 0, l = g.data.length; i < l; i++)
{
if (typeof (item) == "object")
{
if (g.data[i] == item) return i;
} else
{
if (g.data[i][p.valueField].toString() == item.toString()) return i;
}
}
return -1;
},
removeItems: function (items)
{
var g = this;
if (!g.data) return;
$(items).each(function (i, item)
{
var index = g.indexOf(item);
if (index == -1) return;
g.data.splice(index, 1);
});
g.refresh();
},
removeItem: function (item)
{
if (!this.data) return;
var index = this.indexOf(item);
if (index == -1) return;
this.data.splice(index, 1);
this.refresh();
},
insertItem: function (item, index)
{
var g = this;
if (!g.data) g.data = [];
g.data.splice(index, 0, item);
g.refresh();
},
addItems: function (items)
{
var g = this;
if (!g.data) g.data = [];
$(items).each(function (i, item)
{
g.data.push(item);
});
g.refresh();
},
addItem: function (item)
{
var g = this;
if (!g.data) g.data = [];
g.data.push(item);
g.refresh();
},
_setValue: function (value)
{
var g = this, p = this.options;
g.valueField.val(value);
p.value = value;
this._dataInit();
},
setValue: function (value)
{
this._setValue(value);
},
_setUrl: function (url)
{
var g = this, p = this.options;
if (!url) return;
var urlParms = $.isFunction(p.urlParms) ? p.urlParms.call(g) : p.urlParms;
if (urlParms)
{
for (name in urlParms)
{
url += url.indexOf('?') == -1 ? "?" : "&";
url += name + "=" + urlParms[name];
}
}
var parms = $.isFunction(p.parms) ? p.parms() : p.parms;
if (p.ajaxContentType == "application/json" && typeof (parms) != "string")
{
parms = liger.toJSON(parms);
}
$.ajax({
type: 'post',
url: url,
data: parms,
cache: false,
dataType: 'json',
contentType: p.ajaxContentType,
success: function (data)
{
g.setData(data);
g.trigger('success', [data]);
},
error: function (XMLHttpRequest, textStatus)
{
g.trigger('error', [XMLHttpRequest, textStatus]);
}
});
},
setUrl: function (url)
{
return this._setUrl(url);
},
setParm: function (name, value)
{
if (!name) return;
var g = this;
var parms = g.get('parms');
if (!parms) parms = {};
parms[name] = value;
g.set('parms', parms);
},
clearContent: function ()
{
var g = this, p = this.options;
$("table", g.radioList).html("");
},
_setData: function (data)
{
this.setData(data);
},
setData: function (data)
{
var g = this, p = this.options;
if (!data || !data.length) return;
g.data = data;
g.refresh();
g.updateStyle();
},
refresh: function ()
{
var g = this, p = this.options, data = this.data;
this.clearContent();
if (!data) return;
var out = [], rowSize = p.rowSize, appendRowStart = false, name = p.name || g.id;
for (var i = 0; i < data.length; i++)
{
var val = data[i][p.valueField], txt = data[i][p.textField], id = g.id + "-" + i;
var newRow = i % rowSize == 0;
//0,5,10
if (newRow)
{
if (appendRowStart) out.push('</tr>');
out.push("<tr>");
appendRowStart = true;
}
out.push("<td><input type='radio' name='" + name + "' value='" + val + "' id='" + id + "'/><label for='" + id + "'>" + txt + "</label></td>");
}
if (appendRowStart) out.push('</tr>');
g.radioList.table.append(out.join(''));
},
_getValue: function ()
{
var g = this, p = this.options, name = p.name || g.id;
return $('input:radio[name="' + name + '"]:checked').val();
},
getValue: function ()
{
//获取值
return this._getValue();
},
updateStyle: function ()
{
var g = this, p = this.options;
g._dataInit();
$(":radio", g.element).change(function ()
{
var value = g.getValue();
g.trigger('select', [{
value: value
}]);
});
},
_dataInit: function ()
{
var g = this, p = this.options;
var value = g.valueField.val() || g._getValue() || p.value;
g._changeValue(value);
},
//设置值到 隐藏域
_changeValue: function (newValue)
{
var g = this, p = this.options, name = p.name || g.id;
$("input:radio[name='" + name + "']", g.radioList).each(function ()
{
this.checked = this.value == newValue;
});
g.valueField.val(newValue);
g.selectedValue = newValue;
},
_addClickEven: function ()
{
var g = this, p = this.options;
//选项点击
g.radioList.click(function (e)
{
var value = g.getValue();
if (value) g.valueField.val(value);
});
}
});
})(jQuery); | apache-2.0 |
prateekbh/amphtml | extensions/amp-subscriptions-google/0.1/test-e2e/test-amp-subscriptions-google.js | 2307 | /**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
describes.endtoend(
'amp-subscriptions-google',
{
fixture: 'amp-subscriptions-google/swg.amp.html',
environments: ['single'],
},
(env) => {
let controller;
beforeEach(() => {
controller = env.controller;
});
it('Subscription offers should render correctly', async () => {
const btn = await controller.findElement('#swg_button');
// Wait for button to be rendered and ready to click
await expect(controller.getElementRect(btn)).to.include({
width: 240,
height: 40,
});
await controller.click(btn);
// Switch to SwG's outer iFrame
const outerFrame = await controller.findElement('iframe.swg-dialog');
await controller.switchToFrame(outerFrame);
// Switch to SwG's inner iFrame
const innerFrame = await controller.findElement('iframe');
await controller.switchToFrame(innerFrame);
const text = await controller.findElement('.K2Fgzb');
await expect(text).to.exist;
await expect(controller.getElementText(text)).to.equal(
'Subscribe with your Google Account'
);
const basicAccessText = await controller.findElement('.amekj');
await expect(controller.getElementText(basicAccessText)).to.equal(
'Basic Access!'
);
const basicAccessDesc = await controller.findElement('.a02uaf');
await expect(controller.getElementText(basicAccessDesc)).to.equal(
'Basic access charged weekly..'
);
const basicAccessPrice = await controller.findElement('.mojnzf');
await expect(controller.getElementText(basicAccessPrice)).to.equal(
'$1.99/week*'
);
});
}
);
| apache-2.0 |
mdanielwork/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/conversion/EclipseUserLibrariesHelper.java | 5241 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse.conversion;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class EclipseUserLibrariesHelper {
//private static final String ORG_ECLIPSE_JDT_CORE_PREFS = "org.eclipse.jdt.core.prefs";
//private static final String ORG_ECLIPSE_JDT_CORE_USER_LIBRARY = "org.eclipse.jdt.core.userLibrary.";
private EclipseUserLibrariesHelper() {
}
private static void writeUserLibrary(final Library library, final Element libElement) {
final VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
for (VirtualFile file : files) {
Element archElement = new Element("archive");
if (file.getFileSystem() instanceof JarFileSystem) {
final VirtualFile localFile = JarFileSystem.getInstance().getVirtualFileForJar(file);
if (localFile != null) {
file = localFile;
}
}
archElement.setAttribute("path", file.getPath());
libElement.addContent(archElement);
}
}
public static void appendProjectLibraries(final Project project, @Nullable final File userLibrariesFile) throws IOException {
if (userLibrariesFile == null) return;
if (userLibrariesFile.exists() && !userLibrariesFile.isFile()) return;
final File parentFile = userLibrariesFile.getParentFile();
if (parentFile == null) return;
if (!parentFile.isDirectory()) {
if (!parentFile.mkdir()) return;
}
final Element userLibsElement = new Element("eclipse-userlibraries");
final List<Library> libraries = new ArrayList<>(Arrays.asList(ProjectLibraryTable.getInstance(project).getLibraries()));
ContainerUtil.addAll(libraries, LibraryTablesRegistrar.getInstance().getLibraryTable().getLibraries());
for (Library library : libraries) {
Element libElement = new Element("library");
libElement.setAttribute("name", library.getName());
writeUserLibrary(library, libElement);
userLibsElement.addContent(libElement);
}
JDOMUtil.writeDocument(new Document(userLibsElement), userLibrariesFile, "\n");
}
public static void readProjectLibrariesContent(@NotNull VirtualFile exportedFile, Project project, Collection<String> unknownLibraries)
throws IOException, JDOMException {
if (!exportedFile.isValid()) {
return;
}
LibraryTable libraryTable = ProjectLibraryTable.getInstance(project);
Element element = JDOMUtil.load(exportedFile.getInputStream());
WriteAction.run(() -> {
for (Element libElement : element.getChildren("library")) {
String libName = libElement.getAttributeValue("name");
Library libraryByName = libraryTable.getLibraryByName(libName);
if (libraryByName == null) {
LibraryTable.ModifiableModel model = libraryTable.getModifiableModel();
libraryByName = model.createLibrary(libName);
model.commit();
}
if (libraryByName != null) {
Library.ModifiableModel model = libraryByName.getModifiableModel();
for (Element a : libElement.getChildren("archive")) {
String rootPath = a.getAttributeValue("path");
// IDEA-138039 Eclipse import: Unix file system: user library gets wrong paths
LocalFileSystem fileSystem = LocalFileSystem.getInstance();
VirtualFile localFile = fileSystem.findFileByPath(rootPath);
if (rootPath.startsWith("/") && (localFile == null || !localFile.isValid())) {
// relative to workspace root
rootPath = project.getBasePath() + rootPath;
localFile = fileSystem.findFileByPath(rootPath);
}
String url = localFile == null ? VfsUtilCore.pathToUrl(rootPath) : localFile.getUrl();
if (localFile != null) {
VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(localFile);
if (jarFile != null) {
url = jarFile.getUrl();
}
}
model.addRoot(url, OrderRootType.CLASSES);
}
model.commit();
}
unknownLibraries.remove(libName); //ignore finally found libraries
}
});
}
}
| apache-2.0 |
clebeg/mylinuxbackup | src/main/java/com/manning/hip/ch3/binary/CustomBinaryRecordReader.java | 2750 | package com.manning.hip.ch3.binary;
import com.manning.hip.common.HadoopCompat;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import java.io.DataInputStream;
import java.io.IOException;
public class CustomBinaryRecordReader
extends RecordReader<LongWritable, BytesWritable> {
private DataInputStream in;
private LongWritable key;
private BytesWritable value;
private long start;
private long end;
private long pos;
@Override
public void initialize(InputSplit genericSplit,
TaskAttemptContext context)
throws IOException, InterruptedException {
FileSplit split = (FileSplit) genericSplit;
Configuration job = HadoopCompat.getConfiguration(context);
System.out.println("Start = " + split.getStart());
System.out.println("Length = " + split.getLength());
start = split.getStart();
end = start + split.getLength();
final Path file = split.getPath();
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIn = fs.open(split.getPath());
fileIn.seek(start);
in = new DataInputStream(fileIn);
this.pos = start;
}
@Override
public boolean nextKeyValue()
throws IOException, InterruptedException {
System.out.println("nextKeyValue with pos " + pos);
if(pos >= end) {
key = null;
value = null;
return false;
}
if (key == null) {
key = new LongWritable();
}
key.set(pos);
if (value == null) {
value = new BytesWritable();
}
int len = in.readInt();
System.out.println("len = " + len);
byte[] data = new byte[len];
int read = in.read(data);
System.out.println("read = " + read);
value.set(data, 0, data.length);
pos += 4 + len;
return true;
}
@Override
public LongWritable getCurrentKey()
throws IOException, InterruptedException {
return key;
}
@Override
public BytesWritable getCurrentValue()
throws IOException, InterruptedException {
return value;
}
@Override
public float getProgress()
throws IOException, InterruptedException {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float)(end - start));
}
}
@Override
public void close() throws IOException {
if (in != null) {
in.close();
}
}
}
| apache-2.0 |
kuali/rice-playground | rice-middleware/core/api/src/main/java/org/kuali/rice/krad/keyvalues/KeyValuesFinder.java | 1925 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.keyvalues;
import java.util.List;
import java.util.Map;
import org.kuali.rice.core.api.util.KeyValue;
/**
* Defines basic methods value finders
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public interface KeyValuesFinder {
/**
* Builds a list of key values representations for valid value selections.
*
* @return List of KeyValue objects
*/
public List<KeyValue> getKeyValues();
/**
* Builds a list of key values representations for valid value selections.
*
* @param includeActiveOnly whether to only include active values in the list
*
* @return List of KeyValue objects.
*/
public List<KeyValue> getKeyValues(boolean includeActiveOnly);
/**
* Returns a map with the key as the key of the map and the label as the value. Used to render the label instead of the code in
* the jsp when the field is readonly.
*
* @return
*/
public Map<String, String> getKeyLabelMap();
/**
* Returns the label for the associated key.
*
* @param key
* @return
*/
public String getKeyLabel(String key);
/**
* Clears any internal cache that is being maintained by the value finder
*/
public void clearInternalCache();
}
| apache-2.0 |
trashkalmar/omim | android/src/com/mapswithme/util/StorageUtils.java | 2459 | package com.mapswithme.util;
import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import com.mapswithme.maps.MwmApplication;
import java.io.File;
public class StorageUtils
{
private final static String LOGS_FOLDER = "logs";
/**
* Checks if external storage is available for read and write
*
* @return true if external storage is mounted and ready for reading/writing
*/
private static boolean isExternalStorageWritable()
{
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
/**
* Safely returns the external files directory path with the preliminary
* checking the availability of the mentioned directory
*
* @return the absolute path of external files directory or null if directory can not be obtained
* @see Context#getExternalFilesDir(String)
*/
@Nullable
private static String getExternalFilesDir()
{
if (!isExternalStorageWritable())
return null;
File dir = MwmApplication.get().getExternalFilesDir(null);
if (dir != null)
return dir.getAbsolutePath();
Log.e(StorageUtils.class.getSimpleName(),
"Cannot get the external files directory for some reasons", new Throwable());
return null;
}
/**
* Check existence of the folder for writing the logs. If that folder is absent this method will
* try to create it and all missed parent folders.
* @return true - if folder exists, otherwise - false
*/
public static boolean ensureLogsFolderExistence()
{
String externalDir = StorageUtils.getExternalFilesDir();
if (TextUtils.isEmpty(externalDir))
return false;
File folder = new File(externalDir + File.separator + LOGS_FOLDER);
boolean success = true;
if (!folder.exists())
success = folder.mkdirs();
return success;
}
@Nullable
public static String getLogsFolder()
{
if (!ensureLogsFolderExistence())
return null;
String externalDir = StorageUtils.getExternalFilesDir();
return externalDir + File.separator + LOGS_FOLDER;
}
@Nullable
static String getLogsZipPath()
{
String zipFile = getExternalFilesDir() + File.separator + LOGS_FOLDER + ".zip";
File file = new File(zipFile);
return file.isFile() && file.exists() ? zipFile : null;
}
}
| apache-2.0 |
baslr/ArangoDB | 3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/types/reference/S8.7_A7.js | 1014 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Passing arguments by reference do change values of reference to be passed
es5id: 8.7_A7
description: Add new property to original variable inside function
---*/
var n = {};
var m = n;
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (typeof m !== "object") {
$ERROR('#1: var n = {}; var m = n; typeof m === "object". Actual: ' + (typeof m));
}
//
//////////////////////////////////////////////////////////////////////////////
function populateAge(person){person.age = 50;}
populateAge(m);
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (n.age !== 50) {
$ERROR('#2: var n = {}; var m = n; function populateAge(person){person.age = 50;} populateAge(m); n.age === 50. Actual: ' + (n.age));
}
//
//////////////////////////////////////////////////////////////////////////////
| apache-2.0 |
chetanmeh/jackrabbit-oak | oak-segment-tar/src/main/java/org/apache/jackrabbit/oak/segment/Record.java | 2832 | /*
* 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.jackrabbit.oak.segment;
import javax.annotation.Nonnull;
/**
* Record within a segment.
*/
class Record {
static boolean fastEquals(Object a, Object b) {
return a instanceof Record && fastEquals((Record) a, b);
}
private static boolean fastEquals(@Nonnull Record a, Object b) {
return b instanceof Record && fastEquals(a, (Record) b);
}
private static boolean fastEquals(@Nonnull Record a, @Nonnull Record b) {
return a == b || (a.recordNumber == b.recordNumber && a.segmentId.equals(b.segmentId));
}
/**
* Identifier of the segment that contains this record.
*/
private final SegmentId segmentId;
/**
* Segment recordNumber of this record.
*/
private final int recordNumber;
/**
* Creates a new object for the identified record.
*
* @param id record identified
*/
protected Record(@Nonnull RecordId id) {
this(id.getSegmentId(), id.getRecordNumber());
}
protected Record(@Nonnull SegmentId segmentId, int recordNumber) {
this.segmentId = segmentId;
this.recordNumber = recordNumber;
}
/**
* Returns the segment that contains this record.
*
* @return segment that contains this record
*/
protected Segment getSegment() {
return segmentId.getSegment();
}
protected int getRecordNumber() {
return recordNumber;
}
/**
* Returns the identifier of this record.
*
* @return record identifier
*/
public RecordId getRecordId() {
return new RecordId(segmentId, recordNumber);
}
//------------------------------------------------------------< Object >--
@Override
public boolean equals(Object that) {
return fastEquals(this, that);
}
@Override
public int hashCode() {
return segmentId.hashCode() ^ recordNumber;
}
@Override
public String toString() {
return getRecordId().toString();
}
}
| apache-2.0 |
davebarnes97/geode | geode-core/src/distributedTest/java/org/apache/geode/internal/cache/partitioned/BucketRebalanceStatRegressionTest.java | 11124 | /*
* 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.geode.internal.cache.partitioned;
import static org.apache.geode.cache.EvictionAction.OVERFLOW_TO_DISK;
import static org.apache.geode.cache.EvictionAttributes.createLRUEntryAttributes;
import static org.apache.geode.test.dunit.Disconnect.disconnectAllFromDS;
import static org.apache.geode.test.dunit.VM.getVM;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.control.RebalanceFactory;
import org.apache.geode.cache.control.RebalanceOperation;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.internal.cache.BucketRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.rules.CacheRule;
import org.apache.geode.test.dunit.rules.DistributedRule;
import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
/**
* Moving a bucket during rebalancing should update overflow stats (numEntriesInVM and
* numOverflowOnDisk).
*
* <p>
* GEODE-3566: Moving a bucket during rebalancing does not update overflow stats
*/
@SuppressWarnings("serial")
public class BucketRebalanceStatRegressionTest implements Serializable {
private static final String REGION_NAME = "TestRegion";
private static final int TOTAL_NUMBER_BUCKETS = 2;
private static final int LRU_ENTRY_COUNT = 4;
private static final int ENTRIES_IN_REGION = 20;
private static final int BYTES_SIZE = 100;
private VM vm0;
private VM vm1;
@ClassRule
public static DistributedRule distributedRule = new DistributedRule();
@Rule
public CacheRule cacheRule = new CacheRule();
@Rule
public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
@Rule
public SerializableTestName testName = new SerializableTestName();
@Before
public void setUp() throws Exception {
vm0 = getVM(0);
vm1 = getVM(1);
}
@After
public void tearDown() throws Exception {
disconnectAllFromDS();
}
@Test
public void statsUpdatedAfterRebalancePersistentOverflowPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION_PERSISTENT, true);
validateInitialOverflowStats();
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
@Test
public void statsUpdatedAfterRebalanceOverflowPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION, true);
validateInitialOverflowStats();
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
@Test
public void statsUpdatedAfterRebalancePersistentPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION_PERSISTENT, false);
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
/**
* Verify that overflow stats are updated when a bucket moves due to rebalancing.
*/
private void validateStatsUpdatedAfterRebalance() {
vm0.invoke(() -> rebalance());
assertThat(vm0.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm1.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS / 2);
assertThat(vm1.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS / 2);
validateOverflowStats(vm0, "vm0");
validateOverflowStats(vm1, "vm1");
}
/**
* Initialize region on the distributed members.
*
* @param shortcut The region shortcut to use to create the region.
* @param overflow If true, use overflow on the region, false otherwise.
*/
private void initializeRegions(final RegionShortcut shortcut, final boolean overflow) {
// arrange: create regions and data
vm0.invoke(() -> createRegion(shortcut, overflow));
vm0.invoke(() -> loadRegion());
vm1.invoke(() -> createRegion(shortcut, overflow));
}
/**
* Do validation on the initial region before rebalancing. It is expected that all buckets and
* data live on vm0; vm1 does not host any buckets.
*/
private void validateInitialRegion() {
assertThat(vm0.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm1.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS);
assertThat(vm1.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(0);
}
/**
* Do validation the initial region for the member containing all the data
*/
private void validateInitialOverflowStats() {
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getDiskRegionStats().getNumEntriesInVM())).isEqualTo(LRU_ENTRY_COUNT);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getDiskRegionStats().getNumOverflowOnDisk()))
.isEqualTo(ENTRIES_IN_REGION - LRU_ENTRY_COUNT);
}
/**
* Validate that the overflow stats are as expected on the given member.
*/
private void validateOverflowStats(final VM vm, final String vmName) {
long[] overflowStats = vm.invoke(() -> getOverflowStats());
long[] overflowEntries = vm.invoke(() -> getActualOverflowEntries());
long statEntriesInVM = overflowStats[0];
long statEntriesOnDisk = overflowStats[1];
long actualEntriesInVM = overflowEntries[0];
long actualEntriesOnDisk = overflowEntries[1];
assertThat(actualEntriesInVM).as("entriesInVM for " + vmName).isEqualTo(statEntriesInVM);
assertThat(actualEntriesOnDisk).as("entriesOnDisk for " + vmName).isEqualTo(statEntriesOnDisk);
}
/**
* Rebalance the region, waiting for the rebalance operation to complete
*/
private void rebalance() throws Exception {
ResourceManager resourceManager = cacheRule.getCache().getResourceManager();
RebalanceFactory rebalanceFactory = resourceManager.createRebalanceFactory();
RebalanceOperation rebalanceOperation = rebalanceFactory.start();
// wait for rebalance to complete
assertThat(rebalanceOperation.getResults()).isNotNull();
}
/**
* Load the region with some data
*
*/
private void loadRegion() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
for (int i = 1; i <= ENTRIES_IN_REGION; i++) {
region.put(i, new byte[BYTES_SIZE]);
}
}
/**
* Return stats from the region's disk statistics, specifically the numEntriesInVM stat and the
* numOverflowOnDisk stat.
*
* @return [0] numEntriesInVM stat [1] numOverflowOnDisk stat
*/
private long[] getOverflowStats() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
PartitionedRegion partitionedRegion = (PartitionedRegion) region;
long numEntriesInVM = partitionedRegion.getDiskRegionStats().getNumEntriesInVM();
long numOverflowOnDisk = partitionedRegion.getDiskRegionStats().getNumOverflowOnDisk();
return new long[] {numEntriesInVM, numOverflowOnDisk};
}
/**
* Return the actual values for entries in the jvm (in memory) and entries on disk. These values
* are the sum of all buckets in the current member.
*
* @return [0] total entries in VM [1] total entries on disk
*/
private long[] getActualOverflowEntries() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
PartitionedRegion partitionedRegion = (PartitionedRegion) region;
int totalBucketEntriesInVM = 0;
int totalBucketEntriesOnDisk = 0;
Set<Entry<Integer, BucketRegion>> buckets =
partitionedRegion.getDataStore().getAllLocalBuckets();
for (Map.Entry<Integer, BucketRegion> entry : buckets) {
BucketRegion bucket = entry.getValue();
if (bucket != null) {
totalBucketEntriesInVM += bucket.testHookGetValuesInVM();
totalBucketEntriesOnDisk += bucket.testHookGetValuesOnDisk();
}
}
return new long[] {totalBucketEntriesInVM, totalBucketEntriesOnDisk};
}
private void createRegion(final RegionShortcut shortcut, final boolean overflow)
throws IOException {
Cache cache = cacheRule.getOrCreateCache();
DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
diskStoreFactory.setDiskDirs(getDiskDirs());
DiskStore diskStore = diskStoreFactory.create(testName.getMethodName());
RegionFactory<Integer, byte[]> regionFactory = cache.createRegionFactory(shortcut);
regionFactory.setDiskStoreName(diskStore.getName());
regionFactory.setDiskSynchronous(true);
if (overflow) {
regionFactory
.setEvictionAttributes(createLRUEntryAttributes(LRU_ENTRY_COUNT, OVERFLOW_TO_DISK));
}
PartitionAttributesFactory<Integer, byte[]> paf = new PartitionAttributesFactory<>();
paf.setRedundantCopies(0);
paf.setTotalNumBuckets(TOTAL_NUMBER_BUCKETS);
regionFactory.setPartitionAttributes(paf.create());
regionFactory.create(REGION_NAME);
}
private File[] getDiskDirs() throws IOException {
File dir = temporaryFolder.newFolder("disk" + VM.getCurrentVMNum()).getAbsoluteFile();
return new File[] {dir};
}
}
| apache-2.0 |
tgraf/cilium | vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go | 2268 | package restjson
import (
"encoding/json"
"io"
"strings"
"github.com/aws/smithy-go"
)
// GetErrorInfo util looks for code, __type, and message members in the
// json body. These members are optionally available, and the function
// returns the value of member if it is available. This function is useful to
// identify the error code, msg in a REST JSON error response.
func GetErrorInfo(decoder *json.Decoder) (errorType string, message string, err error) {
var errInfo struct {
Code string
Type string `json:"__type"`
Message string
}
err = decoder.Decode(&errInfo)
if err != nil {
if err == io.EOF {
return errorType, message, nil
}
return errorType, message, err
}
// assign error type
if len(errInfo.Code) != 0 {
errorType = errInfo.Code
} else if len(errInfo.Type) != 0 {
errorType = errInfo.Type
}
// assign error message
if len(errInfo.Message) != 0 {
message = errInfo.Message
}
// sanitize error
if len(errorType) != 0 {
errorType = SanitizeErrorCode(errorType)
}
return errorType, message, nil
}
// SanitizeErrorCode sanitizes the errorCode string .
// The rule for sanitizing is if a `:` character is present, then take only the
// contents before the first : character in the value.
// If a # character is present, then take only the contents after the
// first # character in the value.
func SanitizeErrorCode(errorCode string) string {
if strings.ContainsAny(errorCode, ":") {
errorCode = strings.SplitN(errorCode, ":", 2)[0]
}
if strings.ContainsAny(errorCode, "#") {
errorCode = strings.SplitN(errorCode, "#", 2)[1]
}
return errorCode
}
// GetSmithyGenericAPIError returns smithy generic api error and an error interface.
// Takes in json decoder, and error Code string as args. The function retrieves error message
// and error code from the decoder body. If errorCode of length greater than 0 is passed in as
// an argument, it is used instead.
func GetSmithyGenericAPIError(decoder *json.Decoder, errorCode string) (*smithy.GenericAPIError, error) {
errorType, message, err := GetErrorInfo(decoder)
if err != nil {
return nil, err
}
if len(errorCode) == 0 {
errorCode = errorType
}
return &smithy.GenericAPIError{
Code: errorCode,
Message: message,
}, nil
}
| apache-2.0 |
sjohnr/elasticsearch | src/test/java/org/elasticsearch/test/ExternalNode.java | 9880 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.test;
import com.google.common.base.Predicate;
import org.apache.lucene.util.Constants;
import org.elasticsearch.Version;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.discovery.DiscoveryModule;
import org.elasticsearch.transport.TransportModule;
import java.io.Closeable;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertFalse;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
/**
* Simple helper class to start external nodes to be used within a test cluster
*/
final class ExternalNode implements Closeable {
public static final Settings REQUIRED_SETTINGS = ImmutableSettings.builder()
.put("config.ignore_system_properties", true)
.put(DiscoveryModule.DISCOVERY_TYPE_KEY, "zen")
.put("node.mode", "network").build(); // we need network mode for this
private final Path path;
private final Random random;
private final SettingsSource settingsSource;
private Process process;
private NodeInfo nodeInfo;
private final String clusterName;
private TransportClient client;
private final ESLogger logger = Loggers.getLogger(getClass());
private Settings externalNodeSettings;
ExternalNode(Path path, long seed, SettingsSource settingsSource) {
this(path, null, seed, settingsSource);
}
ExternalNode(Path path, String clusterName, long seed, SettingsSource settingsSource) {
if (!Files.isDirectory(path)) {
throw new IllegalArgumentException("path must be a directory");
}
this.path = path;
this.clusterName = clusterName;
this.random = new Random(seed);
this.settingsSource = settingsSource;
}
synchronized ExternalNode start(Client localNode, Settings defaultSettings, String nodeName, String clusterName, int nodeOrdinal) throws IOException, InterruptedException {
ExternalNode externalNode = new ExternalNode(path, clusterName, random.nextLong(), settingsSource);
Settings settings = ImmutableSettings.builder().put(defaultSettings).put(settingsSource.node(nodeOrdinal)).build();
externalNode.startInternal(localNode, settings, nodeName, clusterName);
return externalNode;
}
synchronized void startInternal(Client client, Settings settings, String nodeName, String clusterName) throws IOException, InterruptedException {
if (process != null) {
throw new IllegalStateException("Already started");
}
List<String> params = new ArrayList<>();
if (!Constants.WINDOWS) {
params.add("bin/elasticsearch");
} else {
params.add("bin/elasticsearch.bat");
}
params.add("-Des.cluster.name=" + clusterName);
params.add("-Des.node.name=" + nodeName);
ImmutableSettings.Builder externaNodeSettingsBuilder = ImmutableSettings.builder();
for (Map.Entry<String, String> entry : settings.getAsMap().entrySet()) {
switch (entry.getKey()) {
case "cluster.name":
case "node.name":
case "path.home":
case "node.mode":
case "node.local":
case TransportModule.TRANSPORT_TYPE_KEY:
case DiscoveryModule.DISCOVERY_TYPE_KEY:
case TransportModule.TRANSPORT_SERVICE_TYPE_KEY:
case "config.ignore_system_properties":
continue;
default:
externaNodeSettingsBuilder.put(entry.getKey(), entry.getValue());
}
}
this.externalNodeSettings = externaNodeSettingsBuilder.put(REQUIRED_SETTINGS).build();
for (Map.Entry<String, String> entry : externalNodeSettings.getAsMap().entrySet()) {
params.add("-Des." + entry.getKey() + "=" + entry.getValue());
}
params.add("-Des.path.home=" + Paths.get(".").toAbsolutePath());
params.add("-Des.path.conf=" + path + "/config");
ProcessBuilder builder = new ProcessBuilder(params);
builder.directory(path.toFile());
builder.inheritIO();
boolean success = false;
try {
logger.debug("starting external node [{}] with: {}", nodeName, builder.command());
process = builder.start();
this.nodeInfo = null;
if (waitForNode(client, nodeName)) {
nodeInfo = nodeInfo(client, nodeName);
assert nodeInfo != null;
} else {
throw new IllegalStateException("Node [" + nodeName + "] didn't join the cluster");
}
success = true;
} finally {
if (!success) {
stop();
}
}
}
static boolean waitForNode(final Client client, final String name) throws InterruptedException {
return ElasticsearchTestCase.awaitBusy(new Predicate<Object>() {
@Override
public boolean apply(java.lang.Object input) {
final NodesInfoResponse nodeInfos = client.admin().cluster().prepareNodesInfo().get();
final NodeInfo[] nodes = nodeInfos.getNodes();
for (NodeInfo info : nodes) {
if (name.equals(info.getNode().getName())) {
return true;
}
}
return false;
}
}, 30, TimeUnit.SECONDS);
}
static NodeInfo nodeInfo(final Client client, final String nodeName) {
final NodesInfoResponse nodeInfos = client.admin().cluster().prepareNodesInfo().get();
final NodeInfo[] nodes = nodeInfos.getNodes();
for (NodeInfo info : nodes) {
if (nodeName.equals(info.getNode().getName())) {
return info;
}
}
return null;
}
synchronized TransportAddress getTransportAddress() {
if (nodeInfo == null) {
throw new IllegalStateException("Node has not started yet");
}
return nodeInfo.getTransport().getAddress().publishAddress();
}
synchronized Client getClient() {
if (nodeInfo == null) {
throw new IllegalStateException("Node has not started yet");
}
if (client == null) {
TransportAddress addr = nodeInfo.getTransport().getAddress().publishAddress();
// verify that the end node setting will have network enabled.
Settings clientSettings = settingsBuilder().put(externalNodeSettings)
.put("client.transport.nodes_sampler_interval", "1s")
.put("name", "transport_client_" + nodeInfo.getNode().name())
.put(ClusterName.SETTING, clusterName).put("client.transport.sniff", false).build();
TransportClient client = new TransportClient(clientSettings);
client.addTransportAddress(addr);
this.client = client;
}
return client;
}
synchronized void reset(long seed) {
this.random.setSeed(seed);
}
synchronized void stop() {
stop(false);
}
synchronized void stop(boolean forceKill) {
if (running()) {
try {
if (forceKill == false && nodeInfo != null && random.nextBoolean()) {
// sometimes shut down gracefully
getClient().admin().cluster().prepareNodesShutdown(this.nodeInfo.getNode().id()).setExit(random.nextBoolean()).setDelay("0s").get();
}
if (this.client != null) {
client.close();
}
} finally {
process.destroy();
try {
process.waitFor();
} catch (InterruptedException e) {
Thread.interrupted();
}
process = null;
nodeInfo = null;
}
}
}
synchronized boolean running() {
return process != null;
}
@Override
public void close() {
stop();
}
synchronized String getName() {
if (nodeInfo == null) {
throw new IllegalStateException("Node has not started yet");
}
return nodeInfo.getNode().getName();
}
}
| apache-2.0 |
thiliniish/developer-studio | common/org.wso2.developerstudio.eclipse.artifact.qos/src/org/wso2/developerstudio/eclipse/qos/project/model/TransformType.java | 3456 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.11 at 12:17:22 PM IST
//
package org.wso2.developerstudio.eclipse.qos.project.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
/**
* <p>Java class for TransformType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TransformType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded" minOccurs="0">
* <any processContents='lax' namespace='##other'/>
* <element name="XPath" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </choice>
* <attribute name="Algorithm" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TransformType", propOrder = {
"content"
})
public class TransformType {
@XmlElementRef(name = "XPath", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false)
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute(name = "Algorithm", required = true)
@XmlSchemaType(name = "anyURI")
protected String algorithm;
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
* {@link String }
* {@link Object }
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the algorithm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlgorithm() {
return algorithm;
}
/**
* Sets the value of the algorithm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlgorithm(String value) {
this.algorithm = value;
}
}
| apache-2.0 |
vipullakhani/mi-instrument | mi/dataset/driver/dpc/dpc_driver.py | 834 | #!/usr/local/bin/python2.7
##
# OOIPLACEHOLDER
#
# Copyright 2014 Raytheon Co.
##
from mi.dataset.dataset_driver import DataSetDriver
from mi.dataset.parser.dpc import DeepProfilerParser
from mi.core.log import get_logger
from mi.logging import config
from mi.core.versioning import version
import os
log = get_logger()
@version("15.6.1")
def parse(unused, source_file_path, particle_data_handler):
with open(source_file_path, "r") as stream_handle:
def exception_callback(exception):
log.debug("Exception: %s", exception)
particle_data_handler.setParticleDataCaptureFailure()
parser = DeepProfilerParser({}, stream_handle, exception_callback)
driver = DataSetDriver(parser, particle_data_handler)
driver.processFileStream()
return particle_data_handler
| bsd-2-clause |
bcg62/homebrew-core | Formula/peg.rb | 1199 | class Peg < Formula
desc "Program to perform pattern matching on text"
homepage "http://piumarta.com/software/peg/"
url "http://piumarta.com/software/peg/peg-0.1.18.tar.gz"
sha256 "20193bdd673fc7487a38937e297fff08aa73751b633a086ac28c3b34890f9084"
bottle do
cellar :any_skip_relocation
sha256 "335fda7dd0c4cbd0a2c929daf19693729b3e1592f1880f5a1cb2ebd5ae587c3c" => :mojave
sha256 "622cd7695294bcac63049e45e934ea1936dfc0f9373046dd028f63a3fe6fa2a4" => :high_sierra
sha256 "15dfb147f388a8a486714d17d519a1ad1195f79bad5843d37726e8efaab1ae79" => :sierra
sha256 "44d0ab83d1bc3ee71294d328dc70dd14206b8d8ddf05a195f2cdf354d746d5dc" => :el_capitan
sha256 "9abe69e43c8e2672aa7b5b26df5c80976c2d0365b5d85d672e8948cebe88646f" => :yosemite
sha256 "bbe71ecc8acb17bdf2538f41ae56472bc104a69e310cfd533565507c3468c53c" => :mavericks
end
def install
system "make", "all"
bin.install %w[peg leg]
man1.install gzip("src/peg.1")
end
test do
(testpath/"username.peg").write <<~EOS
start <- "username"
EOS
system "#{bin}/peg", "-o", "username.c", "username.peg"
assert_match /yymatchString\(yy, "username"\)/, File.read("username.c")
end
end
| bsd-2-clause |
ahocevar/ol3 | test/browser/spec/ol/webgl/helper.test.js | 12382 | import WebGLArrayBuffer from '../../../../../src/ol/webgl/Buffer.js';
import WebGLHelper, {
DefaultUniform,
} from '../../../../../src/ol/webgl/Helper.js';
import {ARRAY_BUFFER, FLOAT, STATIC_DRAW} from '../../../../../src/ol/webgl.js';
import {
create as createTransform,
rotate as rotateTransform,
scale as scaleTransform,
translate as translateTransform,
} from '../../../../../src/ol/transform.js';
import {getUid} from '../../../../../src/ol/util.js';
const VERTEX_SHADER = `
precision mediump float;
uniform mat4 u_offsetScaleMatrix;
uniform mat4 u_offsetRotateMatrix;
uniform float u_time;
uniform float u_zoom;
uniform float u_resolution;
attribute float a_test;
uniform float u_test;
void main(void) {
gl_Position = vec4(u_test, a_test, 0.0, 1.0);
}`;
const INVALID_VERTEX_SHADER = `
precision mediump float;
uniform mat4 u_offsetScaleMatrix;
uniform mat4 u_offsetRotateMatrix;
uniform float u_time;
uniform float u_zoom;
uniform float u_resolution;
bla
uniform float u_test;
void main(void) {
gl_Position = vec4(u_test, a_test, 0.0, 1.0);
}`;
const FRAGMENT_SHADER = `
precision mediump float;
void main(void) {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}`;
const INVALID_FRAGMENT_SHADER = `
precision mediump float;
void main(void) {
gl_FragColor = vec4(oops, 1.0, 1.0, 1.0);
}`;
describe('ol/webgl/WebGLHelper', function () {
describe('constructor', function () {
describe('without an argument', function () {
let h;
beforeEach(function () {
h = new WebGLHelper();
});
it('initialized WebGL context & canvas', function () {
expect(h.getGL() instanceof WebGLRenderingContext).to.eql(true);
expect(h.getCanvas() instanceof HTMLCanvasElement).to.eql(true);
});
it('has a default rendering pass', function () {
expect(h.postProcessPasses_.length).to.eql(1);
});
});
describe('with post process passes', function () {
let h;
beforeEach(function () {
h = new WebGLHelper({
postProcesses: [
{
scaleRatio: 0.5,
},
{
uniforms: {
u_test: 4,
},
},
],
});
});
it('has instantiated post-processing passes', function () {
expect(h.postProcessPasses_.length).to.eql(2);
expect(h.postProcessPasses_[0].scaleRatio_).to.eql(0.5);
expect(h.postProcessPasses_[0].uniforms_.length).to.eql(0);
expect(h.postProcessPasses_[1].scaleRatio_).to.eql(1);
expect(h.postProcessPasses_[1].uniforms_.length).to.eql(1);
expect(h.postProcessPasses_[1].uniforms_[0].value).to.eql(4);
});
});
});
describe('operations', function () {
describe('prepare draw', function () {
let h;
beforeEach(function () {
h = new WebGLHelper({
uniforms: {
u_test1: 42,
u_test2: [1, 3],
u_test3: document.createElement('canvas'),
u_test4: createTransform(),
},
});
h.useProgram(h.getProgram(FRAGMENT_SHADER, VERTEX_SHADER));
h.prepareDraw({
pixelRatio: 2,
size: [50, 80],
viewState: {
rotation: 10,
resolution: 10,
center: [0, 0],
},
});
});
it('has resized the canvas', function () {
expect(h.getCanvas().width).to.eql(100);
expect(h.getCanvas().height).to.eql(160);
});
it('has processed default uniforms', function () {
expect(
h.uniformLocations_[DefaultUniform.OFFSET_ROTATION_MATRIX]
).not.to.eql(undefined);
expect(
h.uniformLocations_[DefaultUniform.OFFSET_SCALE_MATRIX]
).not.to.eql(undefined);
expect(h.uniformLocations_[DefaultUniform.TIME]).not.to.eql(undefined);
});
it('has processed uniforms', function () {
expect(h.uniforms_.length).to.eql(4);
expect(h.uniforms_[0].name).to.eql('u_test1');
expect(h.uniforms_[1].name).to.eql('u_test2');
expect(h.uniforms_[2].name).to.eql('u_test3');
expect(h.uniforms_[3].name).to.eql('u_test4');
expect(h.uniforms_[0].location).to.not.eql(-1);
expect(h.uniforms_[1].location).to.not.eql(-1);
expect(h.uniforms_[2].location).to.not.eql(-1);
expect(h.uniforms_[3].location).to.not.eql(-1);
expect(h.uniforms_[2].texture).to.not.eql(undefined);
});
});
describe('valid shader compiling', function () {
let h;
let p;
beforeEach(function () {
h = new WebGLHelper();
p = h.getProgram(FRAGMENT_SHADER, VERTEX_SHADER);
h.useProgram(p);
});
it('has saved the program', function () {
expect(h.currentProgram_).to.eql(p);
});
it('has no shader compilation error', function () {
expect(h.shaderCompileErrors_).to.eql(null);
});
it('can find the uniform location', function () {
expect(h.getUniformLocation('u_test')).to.not.eql(null);
});
it('can find the attribute location', function () {
expect(h.getAttributeLocation('a_test')).to.not.eql(-1);
});
it('cannot find an unknown attribute location', function () {
expect(h.getAttributeLocation('a_test_missing')).to.eql(-1);
});
});
describe('invalid shader compiling', function () {
it('throws for an invalid vertex shader', function () {
const helper = new WebGLHelper();
expect(() =>
helper.getProgram(FRAGMENT_SHADER, INVALID_VERTEX_SHADER)
).to.throwException(
/Vertex shader compilation failed: ERROR: 0:10: 'bla' : syntax error/
);
});
it('throws for an invalid fragment shader', function () {
const helper = new WebGLHelper();
expect(() =>
helper.getProgram(INVALID_FRAGMENT_SHADER, VERTEX_SHADER)
).to.throwException(
/Fragment shader compliation failed: ERROR: 0:5: 'oops' : undeclared identifier/
);
});
});
describe('#makeProjectionTransform', function () {
let h;
let frameState;
beforeEach(function () {
h = new WebGLHelper();
frameState = {
size: [100, 150],
viewState: {
rotation: 0.4,
resolution: 2,
center: [10, 20],
},
};
});
it('gives out the correct transform', function () {
const scaleX = 2 / frameState.size[0] / frameState.viewState.resolution;
const scaleY = 2 / frameState.size[1] / frameState.viewState.resolution;
const given = createTransform();
const expected = createTransform();
scaleTransform(expected, scaleX, scaleY);
rotateTransform(expected, -frameState.viewState.rotation);
translateTransform(
expected,
-frameState.viewState.center[0],
-frameState.viewState.center[1]
);
h.makeProjectionTransform(frameState, given);
expect(given.map((val) => val.toFixed(15))).to.eql(
expected.map((val) => val.toFixed(15))
);
});
});
describe('deleteBuffer()', function () {
it('can be called to free up buffer resources', function () {
const helper = new WebGLHelper();
const buffer = new WebGLArrayBuffer(ARRAY_BUFFER, STATIC_DRAW);
buffer.fromArray([0, 1, 2, 3]);
helper.flushBufferData(buffer);
const bufferKey = getUid(buffer);
expect(helper.bufferCache_).to.have.property(bufferKey);
helper.deleteBuffer(buffer);
expect(helper.bufferCache_).to.not.have.property(bufferKey);
});
});
describe('#createTexture', function () {
let h;
beforeEach(function () {
h = new WebGLHelper();
});
it('creates an empty texture from scratch', function () {
const width = 4;
const height = 4;
const t = h.createTexture([width, height]);
const gl = h.getGL();
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
t,
0
);
const data = new Uint8Array(width * height * 4);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.deleteFramebuffer(fb);
expect(data[0]).to.eql(0);
expect(data[1]).to.eql(0);
expect(data[2]).to.eql(0);
expect(data[3]).to.eql(0);
expect(data[4]).to.eql(0);
expect(data[5]).to.eql(0);
expect(data[6]).to.eql(0);
expect(data[7]).to.eql(0);
});
it('creates a texture from image data', function () {
const width = 4;
const height = 4;
const canvas = document.createElement('canvas');
const image = canvas.getContext('2d').createImageData(width, height);
for (let i = 0; i < image.data.length; i += 4) {
image.data[i] = 100;
image.data[i + 1] = 150;
image.data[i + 2] = 200;
image.data[i + 3] = 250;
}
const t = h.createTexture([width, height], image);
const gl = h.getGL();
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
t,
0
);
const data = new Uint8Array(width * height * 4);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.deleteFramebuffer(fb);
expect(data[0]).to.eql(100);
expect(data[1]).to.eql(150);
expect(data[2]).to.eql(200);
expect(data[3]).to.eql(250);
expect(data[4]).to.eql(100);
expect(data[5]).to.eql(150);
expect(data[6]).to.eql(200);
expect(data[7]).to.eql(250);
});
it('reuses a given texture', function () {
const width = 4;
const height = 4;
const gl = h.getGL();
const t1 = gl.createTexture();
const t2 = h.createTexture([width, height], undefined, t1);
expect(t1).to.be(t2);
});
});
});
describe('#enableAttributes', function () {
let baseAttrs, h;
beforeEach(function () {
h = new WebGLHelper();
baseAttrs = [
{
name: 'attr1',
size: 3,
},
{
name: 'attr2',
size: 2,
},
{
name: 'attr3',
size: 1,
},
];
h.useProgram(
h.getProgram(
FRAGMENT_SHADER,
`
precision mediump float;
uniform mat4 u_projectionMatrix;
uniform mat4 u_offsetScaleMatrix;
uniform mat4 u_offsetRotateMatrix;
attribute vec3 attr1;
attribute vec2 attr2;
attribute float attr3;
uniform float u_test;
void main(void) {
gl_Position = vec4(u_test, attr3, 0.0, 1.0);
}`
)
);
});
it('enables attributes based on the given array (FLOAT)', function () {
const spy = sinon.spy(h, 'enableAttributeArray_');
h.enableAttributes(baseAttrs);
const bytesPerFloat = Float32Array.BYTES_PER_ELEMENT;
expect(spy.callCount).to.eql(3);
expect(spy.getCall(0).args[0]).to.eql('attr1');
expect(spy.getCall(0).args[1]).to.eql(3);
expect(spy.getCall(0).args[2]).to.eql(FLOAT);
expect(spy.getCall(0).args[3]).to.eql(6 * bytesPerFloat);
expect(spy.getCall(0).args[4]).to.eql(0);
expect(spy.getCall(1).args[0]).to.eql('attr2');
expect(spy.getCall(1).args[1]).to.eql(2);
expect(spy.getCall(1).args[2]).to.eql(FLOAT);
expect(spy.getCall(1).args[3]).to.eql(6 * bytesPerFloat);
expect(spy.getCall(1).args[4]).to.eql(3 * bytesPerFloat);
expect(spy.getCall(2).args[0]).to.eql('attr3');
expect(spy.getCall(2).args[1]).to.eql(1);
expect(spy.getCall(2).args[2]).to.eql(FLOAT);
expect(spy.getCall(2).args[3]).to.eql(6 * bytesPerFloat);
expect(spy.getCall(2).args[4]).to.eql(5 * bytesPerFloat);
});
});
});
| bsd-2-clause |
sjackman/homebrew-core | Formula/sd.rb | 1724 | class Sd < Formula
desc "Intuitive find & replace CLI"
homepage "https://github.com/chmln/sd"
url "https://github.com/chmln/sd/archive/v0.7.6.tar.gz"
sha256 "faf33a97797b95097c08ebb7c2451ac9835907254d89863b10ab5e0813b5fe5f"
license "MIT"
revision 1
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "b13fb7360bf22415291f9567ecbdd73be518370ed0d586b126f4799235346e50"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "18c80fe2725f822518e07c67d37f410ba97387ad956d83e57caf33ac29e80d25"
sha256 cellar: :any_skip_relocation, monterey: "9d7ced5db7e35961bc033feefd5ccac3e2a92aab40639b6551e7025917c010ff"
sha256 cellar: :any_skip_relocation, big_sur: "954897383d176858ae3756214f1cd328813aca21c8a1680e28574b75d60f176c"
sha256 cellar: :any_skip_relocation, catalina: "7a596311c78da626809ba278bd318499d9552ee8ada8ae302abe4b3481b2245e"
sha256 cellar: :any_skip_relocation, mojave: "779ae77105d505f8532438b83acb54f915b5a917c66aecfc21ecdd86cf550b5d"
sha256 cellar: :any_skip_relocation, x86_64_linux: "3cc1bd3d85302acebc3f77b87d9251cafa625c84cf6f3cc0f675af9db0e4c016"
end
depends_on "rust" => :build
def install
system "cargo", "install", *std_cargo_args
# Completion scripts and manpage are generated in the crate's build
# directory, which includes a fingerprint hash. Try to locate it first
out_dir = Dir["target/release/build/sd-*/out"].first
man1.install "#{out_dir}/sd.1"
bash_completion.install "#{out_dir}/sd.bash"
fish_completion.install "#{out_dir}/sd.fish"
zsh_completion.install "#{out_dir}/_sd"
end
test do
assert_equal "after", pipe_output("#{bin}/sd before after", "before")
end
end
| bsd-2-clause |
chromium/chromium | chrome/browser/extensions/api/idltest/idltest_apitest.cc | 990 | // 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/extensions/extension_apitest.h"
#include "components/version_info/version_info.h"
#include "content/public/test/browser_test.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/switches.h"
class ExtensionIdltestApiTest : public extensions::ExtensionApiTest {
public:
// Set the channel to "trunk" since idltest is restricted to trunk.
ExtensionIdltestApiTest() : trunk_(version_info::Channel::UNKNOWN) {}
~ExtensionIdltestApiTest() override {}
private:
extensions::ScopedCurrentChannel trunk_;
};
IN_PROC_BROWSER_TEST_F(ExtensionIdltestApiTest, IdlCompiler) {
EXPECT_TRUE(
RunExtensionTest("idltest/binary_data", {.page_url = "binary.html"}));
EXPECT_TRUE(
RunExtensionTest("idltest/nocompile", {.page_url = "nocompile.html"}));
}
| bsd-3-clause |
nwjs/chromium.src | services/device/hid/hid_connection_unittest.cc | 6789 | // Copyright (c) 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 "services/device/hid/hid_connection.h"
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/callback.h"
#include "base/memory/ref_counted_memory.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/task_environment.h"
#include "base/test/test_io_thread.h"
#include "services/device/hid/hid_service.h"
#include "services/device/public/mojom/hid.mojom.h"
#include "services/device/test/usb_test_gadget.h"
#include "services/device/usb/usb_device.h"
#include "services/device/usb/usb_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace device {
namespace {
// Helper class that can be used to block until a HID device with a particular
// serial number is available. Example usage:
//
// DeviceCatcher device_catcher("ABC123");
// std::string device_guid = device_catcher.WaitForDevice();
// /* Call HidService::Connect(device_guid) to open the device. */
//
class DeviceCatcher : HidService::Observer {
public:
DeviceCatcher(HidService* hid_service, const std::u16string& serial_number)
: serial_number_(base::UTF16ToUTF8(serial_number)) {
hid_service->GetDevices(
base::BindOnce(&DeviceCatcher::OnEnumerationComplete,
base::Unretained(this), hid_service));
}
DeviceCatcher(DeviceCatcher&) = delete;
DeviceCatcher& operator=(DeviceCatcher&) = delete;
const std::string& WaitForDevice() {
run_loop_.Run();
observation_.Reset();
return device_guid_;
}
private:
void OnEnumerationComplete(HidService* hid_service,
std::vector<mojom::HidDeviceInfoPtr> devices) {
for (auto& device_info : devices) {
if (device_info->serial_number == serial_number_) {
device_guid_ = device_info->guid;
run_loop_.Quit();
break;
}
}
observation_.Observe(hid_service);
}
void OnDeviceAdded(mojom::HidDeviceInfoPtr device_info) override {
if (device_info->serial_number == serial_number_) {
device_guid_ = device_info->guid;
run_loop_.Quit();
}
}
std::string serial_number_;
base::ScopedObservation<HidService, HidService::Observer> observation_{this};
base::RunLoop run_loop_;
std::string device_guid_;
};
class TestConnectCallback {
public:
TestConnectCallback() = default;
TestConnectCallback(TestConnectCallback&) = delete;
TestConnectCallback& operator=(TestConnectCallback&) = delete;
~TestConnectCallback() = default;
void SetConnection(scoped_refptr<HidConnection> connection) {
connection_ = connection;
run_loop_.Quit();
}
scoped_refptr<HidConnection> WaitForConnection() {
run_loop_.Run();
return connection_;
}
HidService::ConnectCallback GetCallback() {
return base::BindOnce(&TestConnectCallback::SetConnection,
base::Unretained(this));
}
private:
base::RunLoop run_loop_;
scoped_refptr<HidConnection> connection_;
};
class TestIoCallback {
public:
TestIoCallback() = default;
TestIoCallback(TestIoCallback&) = delete;
TestIoCallback& operator=(TestIoCallback&) = delete;
~TestIoCallback() = default;
void SetReadResult(bool success,
scoped_refptr<base::RefCountedBytes> buffer,
size_t size) {
result_ = success;
buffer_ = buffer;
size_ = size;
run_loop_.Quit();
}
void SetWriteResult(bool success) {
result_ = success;
run_loop_.Quit();
}
bool WaitForResult() {
run_loop_.Run();
return result_;
}
HidConnection::ReadCallback GetReadCallback() {
return base::BindOnce(&TestIoCallback::SetReadResult,
base::Unretained(this));
}
HidConnection::WriteCallback GetWriteCallback() {
return base::BindOnce(&TestIoCallback::SetWriteResult,
base::Unretained(this));
}
scoped_refptr<base::RefCountedBytes> buffer() const { return buffer_; }
size_t size() const { return size_; }
private:
base::RunLoop run_loop_;
bool result_;
size_t size_;
scoped_refptr<base::RefCountedBytes> buffer_;
};
} // namespace
class HidConnectionTest : public testing::Test {
public:
HidConnectionTest()
: task_environment_(base::test::TaskEnvironment::MainThreadType::UI),
io_thread_(base::TestIOThread::kAutoStart) {}
HidConnectionTest(HidConnectionTest&) = delete;
HidConnectionTest& operator=(HidConnectionTest&) = delete;
protected:
void SetUp() override {
if (!UsbTestGadget::IsTestEnabled() || !usb_service_)
return;
service_ = HidService::Create();
ASSERT_TRUE(service_);
usb_service_ = UsbService::Create();
test_gadget_ =
UsbTestGadget::Claim(usb_service_.get(), io_thread_.task_runner());
ASSERT_TRUE(test_gadget_);
ASSERT_TRUE(test_gadget_->SetType(UsbTestGadget::HID_ECHO));
DeviceCatcher device_catcher(service_.get(),
test_gadget_->GetDevice()->serial_number());
device_guid_ = device_catcher.WaitForDevice();
ASSERT_FALSE(device_guid_.empty());
}
base::test::TaskEnvironment task_environment_;
base::TestIOThread io_thread_;
std::unique_ptr<HidService> service_;
std::unique_ptr<UsbTestGadget> test_gadget_;
std::unique_ptr<UsbService> usb_service_;
std::string device_guid_;
};
TEST_F(HidConnectionTest, ReadWrite) {
if (!UsbTestGadget::IsTestEnabled())
return;
TestConnectCallback connect_callback;
service_->Connect(device_guid_, /*allow_protected_reports=*/false,
/*allow_fido_reports=*/false,
connect_callback.GetCallback());
scoped_refptr<HidConnection> conn = connect_callback.WaitForConnection();
ASSERT_TRUE(conn.get());
const char kBufferSize = 9;
for (char i = 0; i < 8; ++i) {
auto buffer = base::MakeRefCounted<base::RefCountedBytes>(kBufferSize);
buffer->data()[0] = 0;
for (unsigned char j = 1; j < kBufferSize; ++j) {
buffer->data()[j] = i + j - 1;
}
TestIoCallback write_callback;
conn->Write(buffer, write_callback.GetWriteCallback());
ASSERT_TRUE(write_callback.WaitForResult());
TestIoCallback read_callback;
conn->Read(read_callback.GetReadCallback());
ASSERT_TRUE(read_callback.WaitForResult());
ASSERT_EQ(9UL, read_callback.size());
ASSERT_EQ(0, read_callback.buffer()->data()[0]);
for (unsigned char j = 1; j < kBufferSize; ++j) {
ASSERT_EQ(i + j - 1, read_callback.buffer()->data()[j]);
}
}
conn->Close();
}
} // namespace device
| bsd-3-clause |
endlessm/chromium-browser | third_party/angle/third_party/VK-GL-CTS/src/external/openglcts/modules/gl/gl4cES31CompatibilityTests.hpp | 7180 | #ifndef _GL4CES31COMPATIBILITYTESTS_HPP
#define _GL4CES31COMPATIBILITYTESTS_HPP
/*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2015-2016 The Khronos Group Inc.
*
* 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.
*
*/ /*!
* \file
* \brief
*/ /*-------------------------------------------------------------------*/
/**
*/ /*!
* \file gl4cES31CompatibilityTests.hpp
* \brief Conformance tests for ES3.1 Compatibility feature functionality.
*/ /*------------------------------------------------------------------------------*/
/* Includes. */
#include "glcTestCase.hpp"
#include "glcTestSubcase.hpp"
#include "gluShaderUtil.hpp"
#include "glwDefs.hpp"
#include "tcuDefs.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
/* Interface. */
namespace gl4cts
{
namespace es31compatibility
{
/** @class Tests
*
* @brief OpenGL ES 3.1 Compatibility Tests Suite.
*/
class Tests : public deqp::TestCaseGroup
{
public:
/* Public member functions. */
Tests(deqp::Context& context);
void init();
private:
/* Private member functions. */
Tests(const Tests& other);
Tests& operator=(const Tests& other);
};
/* Tests class */
/** @class ShaderCompilationCompatibilityTests
*
* @brief Test verifies that vertex, fragment and compute shaders
* containing line "#version 310 es" compile without
* error.
*
* Test verifies that fragment shader using gl_HelperInvocation
* variable compiles without errors.
*/
class ShaderCompilationCompatibilityTests : public deqp::TestCase
{
public:
/* Public member functions. */
ShaderCompilationCompatibilityTests(deqp::Context& context);
virtual tcu::TestNode::IterateResult iterate();
private:
/* Private member functions */
ShaderCompilationCompatibilityTests(const ShaderCompilationCompatibilityTests& other);
ShaderCompilationCompatibilityTests& operator=(const ShaderCompilationCompatibilityTests& other);
/* Static member constants. */
static const struct TestShader
{
glw::GLenum type;
const glw::GLchar* type_name;
const glw::GLchar* source;
} s_shaders[]; //!< Test cases shaders.
static const glw::GLsizei s_shaders_count; //!< Test cases shaders count.
};
/* ShaderCompilationCompatibilityTests */
/** @class ShaderFunctionalCompatibilityTests
*
* @brief Test veryifies that GLSL mix(T, T, Tboolean) function
* works with int, uint and boolean types. Test is performed
* for highp, mediump and lowp precision qualifiers.
*/
class ShaderFunctionalCompatibilityTest : public deqp::TestCase
{
public:
/* Public member functions. */
ShaderFunctionalCompatibilityTest(deqp::Context& context);
virtual tcu::TestNode::IterateResult iterate();
private:
/* Private member variables. */
glw::GLuint m_po_id; //!< Program object name.
glw::GLuint m_fbo_id; //!< Framebuffer object name.
glw::GLuint m_rbo_id; //!< Renderbuffer object name.
glw::GLuint m_vao_id; //!< Vertex Array Object name.
/* Static member constants. */
static const glw::GLchar* s_shader_version; //!< Shader version string.
static const glw::GLchar* s_vertex_shader_body; //!< Vertex shader body template.
static const glw::GLchar* s_fragment_shader_body; //!< Fragment shader body template.
static const struct Shader
{
const glw::GLchar* vertex[3];
const glw::GLchar* fragment[3];
} s_shaders[]; //!< Template parameter cases.
static const glw::GLsizei s_shaders_count; //!< Number of template parameter cases.
/* Private member functions */
ShaderFunctionalCompatibilityTest(const ShaderFunctionalCompatibilityTest& other);
ShaderFunctionalCompatibilityTest& operator=(const ShaderFunctionalCompatibilityTest& other);
bool createProgram(const struct Shader shader_source);
void createFramebufferAndVertexArrayObject();
bool test();
void cleanProgram();
void cleanFramebufferAndVertexArrayObject();
};
/* ShaderFunctionalCompatibilityTests */
/** @class SampleVariablesTests
*
* @breif This class groups adjusted OpenGL ES 3.1 Sample Variables Tests.
* Those tests cover a new GLSL built-in constant for the maximum supported
* samples (gl_MaxSamples) which is available in OpenGL ES 3.1 and in new
* compatibility feature of OpenGL 4.5.
*/
class SampleVariablesTests : public deqp::TestCaseGroup
{
public:
SampleVariablesTests(deqp::Context& context, glu::GLSLVersion glslVersion);
~SampleVariablesTests();
void init();
private:
SampleVariablesTests(const SampleVariablesTests& other);
SampleVariablesTests& operator=(const SampleVariablesTests& other);
enum
{
SAMPLE_MASKS = 8
};
glu::GLSLVersion m_glslVersion;
};
/* SampleVariablesTests class */
/** @class ShaderImageLoadStoreTests
*
* @brief This class groups adjusted OpenGL ES 3.1 Shader Image Load
* Store Tests. These tests cover following features of OpenGL
* ES 3.1 which were included to OpenGL 4.5 as a compatibility
* enhancement:
*
* - a MemoryBarrierByRegion API,
* - a GLSL built-in function imageAtomicExchange,
* - a set of new GLSL built-in constants (gl_Max*ImageUniforms,
* gl_MaxCombinedShaderOutputResources)
* - a "coherent" qualifier related to variables taken by the GLSL atomic*
* and imageAtomic* functions.
*/
class ShaderImageLoadStoreTests : public deqp::TestCaseGroup
{
public:
ShaderImageLoadStoreTests(deqp::Context& context);
~ShaderImageLoadStoreTests(void);
void init(void);
private:
ShaderImageLoadStoreTests(const ShaderImageLoadStoreTests& other);
ShaderImageLoadStoreTests& operator=(const ShaderImageLoadStoreTests& other);
};
/* ShaderImageLoadStoreTests class */
/** @class ShaderStorageBufferObjectTests
*
* @brief This class contains adjusted OpenGL ES 3.1 Shader Storage
* Buffer Object Tests. These tests cover minimum required
* size of SSBOs to 2^27 (128 MB) and its general functionality
* included in OpenGL ES 3.1 and in new compatibility feature
* of OpenGL 4.5.
*/
class ShaderStorageBufferObjectTests : public deqp::TestCaseGroup
{
public:
ShaderStorageBufferObjectTests(deqp::Context& context);
~ShaderStorageBufferObjectTests(void);
void init(void);
private:
ShaderStorageBufferObjectTests(const ShaderStorageBufferObjectTests& other);
ShaderStorageBufferObjectTests& operator=(const ShaderStorageBufferObjectTests& other);
};
/* ShaderStorageBufferObjectTests class */
} /* es31compatibility namespace */
} /* gl4cts namespace */
#endif // _GL4CES31COMPATIBILITYTESTS_HPP
| bsd-3-clause |
robinpowered/php-ews | EWSType/PlayOnPhoneType.php | 692 | <?php
/**
* Contains EWSType_PlayOnPhoneType.
*/
/**
* Represents a request to read an item on a phone.
*
* @package php-ews\Types
*
* @todo Extend EWSType_BaseRequestType.
*/
class EWSType_PlayOnPhoneType extends EWSType
{
/**
* Represents the dial string of the phone number that is called to play an
* item by phone.
*
* This element is required.
*
* @since Exchange 2010
*
* @var string
*/
public $DialString;
/**
* Represents the identifier of an item to play on a phone.
*
* This element is required.
*
* @since Exchange 2010
*
* @var EWSType_ItemIdType
*/
public $ItemId;
}
| bsd-3-clause |
moklick/odyssey.js | index.js | 417 |
var e = require('./lib/odyssey/story');
e.Actions = require('./lib/odyssey/actions');
e.Triggers = require('./lib/odyssey/triggers');
e.Core = require('./lib/odyssey/core');
e.Template = require('./lib/odyssey/template');
e.UI = require('./lib/odyssey/ui');
require('./lib/odyssey/util');
for (var k in e.Actions) {
e[k] = e.Actions[k];
}
for (var k in e.Triggers) {
e[k] = e.Triggers[k];
}
module.exports = e;
| bsd-3-clause |
nwjs/chromium.src | chrome/common/extensions/manifest_tests/extension_manifests_manifest_version_unittest.cc | 3437 | // 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 <memory>
#include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h"
#include "extensions/common/error_utils.h"
#include "extensions/common/manifest_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using extensions::Extension;
namespace errors = extensions::manifest_errors;
TEST_F(ChromeManifestTest, ManifestVersionError) {
base::Value mv_missing(base::Value::Type::DICTIONARY);
mv_missing.SetStringKey("name", "Miles");
mv_missing.SetStringKey("version", "0.55");
base::Value mv0 = mv_missing.Clone();
mv0.SetIntKey("manifest_version", 0);
base::Value mv1 = mv_missing.Clone();
mv1.SetIntKey("manifest_version", 1);
base::Value mv2 = mv_missing.Clone();
mv2.SetIntKey("manifest_version", 2);
base::Value mv3 = mv_missing.Clone();
mv3.SetIntKey("manifest_version", 3);
base::Value mv4 = mv_missing.Clone();
mv4.SetIntKey("manifest_version", 4);
base::Value mv_string = mv_missing.Clone();
mv_string.SetStringKey("manifest_version", "2");
struct {
const char* test_name;
bool require_modern_manifest_version;
base::Value manifest;
std::string expected_error;
} test_data[] = {
{"require_modern_with_default", true, mv_missing.Clone(),
errors::kInvalidManifestVersionMissingKey},
{"require_modern_with_invalid_version", true, mv0.Clone(),
errors::kInvalidManifestVersionUnsupported},
{"require_modern_with_old_version", true, mv1.Clone(),
errors::kInvalidManifestVersionUnsupported},
{"require_modern_with_v2", true, mv2.Clone(), ""},
{"require_modern_with_v3", true, mv3.Clone(), ""},
{"require_modern_with_future_version", true, mv4.Clone(), ""},
{"require_modern_with_string", true, mv_string.Clone(),
errors::kInvalidManifestVersionUnsupported},
{"dont_require_modern_with_default", false, mv_missing.Clone(),
errors::kInvalidManifestVersionMissingKey},
{"dont_require_modern_with_invalid_version", false, mv0.Clone(),
errors::kInvalidManifestVersionUnsupported},
{"dont_require_modern_with_old_version", false, mv1.Clone(),
errors::kInvalidManifestVersionUnsupported},
{"dont_require_modern_with_v2", false, mv2.Clone(), ""},
{"dont_require_modern_with_v3", false, mv3.Clone(), ""},
{"dont_require_modern_with_future_version", false, mv4.Clone(), ""},
{"dont_require_modern_with_string", false, mv_string.Clone(),
errors::kInvalidManifestVersionUnsupported},
};
for (auto& entry : test_data) {
int create_flags = Extension::NO_FLAGS;
if (entry.require_modern_manifest_version)
create_flags |= Extension::REQUIRE_MODERN_MANIFEST_VERSION;
if (!entry.expected_error.empty()) {
LoadAndExpectError(
ManifestData(std::move(entry.manifest), entry.test_name),
extensions::ErrorUtils::FormatErrorMessage(
entry.expected_error, "either 2 or 3", "extensions"),
extensions::mojom::ManifestLocation::kUnpacked, create_flags);
} else {
LoadAndExpectSuccess(
ManifestData(std::move(entry.manifest), entry.test_name),
extensions::mojom::ManifestLocation::kUnpacked, create_flags);
}
}
}
| bsd-3-clause |
kageiit/infer | infer/tests/codetoanalyze/cpp/shared/types/type_trait_expr.cpp | 421 | /*
* Copyright (c) 2016 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
int is_trivial_example() { return __is_trivial(int); }
int is_pointer_example() { return __is_pointer(int); }
| bsd-3-clause |
chuan9/chromium-crosswalk | chrome/browser/sync/test/integration/two_client_typed_urls_sync_test.cc | 22905 | // 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 "base/guid.h"
#include "base/i18n/number_formatting.h"
#include "base/memory/scoped_vector.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/sessions/session_service.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_integration_test_util.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/browser/sync/test/integration/typed_urls_helper.h"
#include "components/history/core/browser/history_types.h"
using base::ASCIIToUTF16;
using bookmarks::BookmarkNode;
using sync_integration_test_util::AwaitCommitActivityCompletion;
using typed_urls_helper::AddUrlToHistory;
using typed_urls_helper::AddUrlToHistoryWithTimestamp;
using typed_urls_helper::AddUrlToHistoryWithTransition;
using typed_urls_helper::AreVisitsEqual;
using typed_urls_helper::AreVisitsUnique;
using typed_urls_helper::AwaitCheckAllProfilesHaveSameURLs;
using typed_urls_helper::CheckURLRowVectorsAreEqual;
using typed_urls_helper::DeleteUrlFromHistory;
using typed_urls_helper::GetTypedUrlsFromClient;
using typed_urls_helper::GetUrlFromClient;
using typed_urls_helper::GetVisitsFromClient;
using typed_urls_helper::RemoveVisitsFromClient;
class TwoClientTypedUrlsSyncTest : public SyncTest {
public:
TwoClientTypedUrlsSyncTest() : SyncTest(TWO_CLIENT) {}
~TwoClientTypedUrlsSyncTest() override {}
::testing::AssertionResult CheckClientsEqual() {
history::URLRows urls = GetTypedUrlsFromClient(0);
history::URLRows urls2 = GetTypedUrlsFromClient(1);
if (!CheckURLRowVectorsAreEqual(urls, urls2))
return ::testing::AssertionFailure() << "URLVectors are not equal";
// Now check the visits.
for (size_t i = 0; i < urls.size() && i < urls2.size(); i++) {
history::VisitVector visit1 = GetVisitsFromClient(0, urls[i].id());
history::VisitVector visit2 = GetVisitsFromClient(1, urls2[i].id());
if (!AreVisitsEqual(visit1, visit2))
return ::testing::AssertionFailure() << "Visits are not equal";
}
return ::testing::AssertionSuccess();
}
bool CheckNoDuplicateVisits() {
for (int i = 0; i < num_clients(); ++i) {
history::URLRows urls = GetTypedUrlsFromClient(i);
for (size_t j = 0; j < urls.size(); ++j) {
history::VisitVector visits = GetVisitsFromClient(i, urls[j].id());
if (!AreVisitsUnique(visits))
return false;
}
}
return true;
}
int GetVisitCountForFirstURL(int index) {
history::URLRows urls = GetTypedUrlsFromClient(index);
if (urls.size() == 0)
return 0;
else
return urls[0].visit_count();
}
private:
DISALLOW_COPY_AND_ASSIGN(TwoClientTypedUrlsSyncTest);
};
// TCM: 3728323
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, E2ETestAdd) {
// Use a randomized URL to prevent test collisions.
const base::string16 kHistoryUrl = ASCIIToUTF16(base::StringPrintf(
"http://www.add-history.google.com/%s", base::GenerateGUID().c_str()));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
unsigned long initial_count = GetTypedUrlsFromClient(0).size();
// Populate one client with a URL, wait for it to sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Assert that the second client has the correct new URL.
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(initial_count + 1, urls.size());
ASSERT_EQ(new_url, urls[urls.size() - 1].url());
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, AddExpired) {
const base::string16 kHistoryUrl(
ASCIIToUTF16("http://www.add-one-history.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
// Create a URL with a timestamp 1 year before today.
base::Time timestamp = base::Time::Now() - base::TimeDelta::FromDays(365);
AddUrlToHistoryWithTimestamp(0,
new_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Let sync finish.
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
// Second client should still have no URLs since this one is expired.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(0U, urls.size());
}
// Flake on mac: http://crbug/115526
#if defined(OS_MACOSX)
#define MAYBE_AddExpiredThenUpdate DISABLED_AddExpiredThenUpdate
#else
#define MAYBE_AddExpiredThenUpdate AddExpiredThenUpdate
#endif
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, MAYBE_AddExpiredThenUpdate) {
const base::string16 kHistoryUrl(
ASCIIToUTF16("http://www.add-one-history.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
// Create a URL with a timestamp 1 year before today.
base::Time timestamp = base::Time::Now() - base::TimeDelta::FromDays(365);
AddUrlToHistoryWithTimestamp(0,
new_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp);
std::vector<history::URLRow> urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Let sync finish.
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
// Second client should still have no URLs since this one is expired.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(0U, urls.size());
// Now drive an update on the first client.
AddUrlToHistory(0, new_url);
// Let sync finish again.
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
// Second client should have the URL now.
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
}
// TCM: 3705291
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, E2ETestAddThenDelete) {
// Use a randomized URL to prevent test collisions.
const base::string16 kHistoryUrl = ASCIIToUTF16(base::StringPrintf(
"http://www.add-history.google.com/%s", base::GenerateGUID().c_str()));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
unsigned long initial_count = GetTypedUrlsFromClient(0).size();
// Populate one client with a URL, wait for it to sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Assert that the second client has the correct new URL.
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(initial_count + 1, urls.size());
ASSERT_EQ(new_url, urls[urls.size() - 1].url());
// Delete from first client, and wait for them to sync.
DeleteUrlFromHistory(0, new_url);
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Assert that it's deleted from the second client.
ASSERT_EQ(initial_count, GetTypedUrlsFromClient(1).size());
}
// TCM: 3643277
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, DisableEnableSync) {
const base::string16 kUrl1(ASCIIToUTF16("http://history1.google.com/"));
const base::string16 kUrl2(ASCIIToUTF16("http://history2.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Disable typed url sync for one client, leave it active for the other.
GetClient(0)->DisableSyncForDatatype(syncer::TYPED_URLS);
// Add one URL to non-syncing client, add a different URL to the other,
// wait for sync cycle to complete. No data should be exchanged.
GURL url1(kUrl1);
GURL url2(kUrl2);
AddUrlToHistory(0, url1);
AddUrlToHistory(1, url2);
ASSERT_TRUE(AwaitCommitActivityCompletion(GetSyncService((1))));
// Make sure that no data was exchanged.
history::URLRows post_sync_urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, post_sync_urls.size());
ASSERT_EQ(url1, post_sync_urls[0].url());
post_sync_urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, post_sync_urls.size());
ASSERT_EQ(url2, post_sync_urls[0].url());
// Enable typed url sync, make both URLs are synced to each client.
GetClient(0)->EnableSyncForDatatype(syncer::TYPED_URLS);
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
}
// flaky, see crbug.com/108511
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, DISABLED_AddOneDeleteOther) {
const base::string16 kHistoryUrl(
ASCIIToUTF16("http://www.add-one-delete-history.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Both clients should have this URL.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Now, delete the URL from the second client.
DeleteUrlFromHistory(1, new_url);
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
// Both clients should have this URL removed.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
}
// flaky, see crbug.com/108511
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
DISABLED_AddOneDeleteOtherAddAgain) {
const base::string16 kHistoryUrl(
ASCIIToUTF16("http://www.add-delete-add-history.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a URL, should sync to the other.
GURL new_url(kHistoryUrl);
AddUrlToHistory(0, new_url);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
// Both clients should have this URL.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Now, delete the URL from the second client.
DeleteUrlFromHistory(1, new_url);
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
// Both clients should have this URL removed.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
// Add it to the first client again, should succeed (tests that the deletion
// properly disassociates that URL).
AddUrlToHistory(0, new_url);
// Both clients should have this URL added again.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
MergeTypedWithNonTypedDuringAssociation) {
ASSERT_TRUE(SetupClients());
GURL new_url("http://history.com");
base::Time timestamp = base::Time::Now();
// Put a non-typed URL in both clients with an identical timestamp.
// Then add a typed URL to the second client - this test makes sure that
// we properly merge both sets of visits together to end up with the same
// set of visits on both ends.
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp + base::TimeDelta::FromSeconds(1));
// Now start up sync - URLs should get merged. Fully sync client 1 first,
// before syncing client 0, so we have both of client 1's URLs in the sync DB
// at the time that client 0 does model association.
ASSERT_TRUE(GetClient(1)->SetupSync()) << "SetupSync() failed";
AwaitCommitActivityCompletion(GetSyncService((1)));
ASSERT_TRUE(GetClient(0)->SetupSync()) << "SetupSync() failed";
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
ASSERT_TRUE(CheckClientsEqual());
// At this point, we should have no duplicates (total visit count should be
// 2). We only need to check client 0 since we already verified that both
// clients are identical above.
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
ASSERT_TRUE(CheckNoDuplicateVisits());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
}
// Tests transitioning a URL from non-typed to typed when both clients
// have already seen that URL (so a merge is required).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
MergeTypedWithNonTypedDuringChangeProcessing) {
ASSERT_TRUE(SetupClients());
GURL new_url("http://history.com");
base::Time timestamp = base::Time::Now();
// Setup both clients with the identical typed URL visit. This means we can't
// use the verifier in this test, because this will show up as two distinct
// visits in the verifier.
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
AddUrlToHistoryWithTimestamp(1, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED, timestamp);
// Now start up sync. Neither URL should get synced as they do not look like
// typed URLs.
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
ASSERT_TRUE(CheckClientsEqual());
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Now, add a typed visit to the first client.
AddUrlToHistoryWithTimestamp(0, new_url, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED,
timestamp + base::TimeDelta::FromSeconds(1));
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
ASSERT_TRUE(CheckClientsEqual());
ASSERT_TRUE(CheckNoDuplicateVisits());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
ASSERT_EQ(2, GetVisitCountForFirstURL(1));
}
// Tests transitioning a URL from non-typed to typed when one of the clients
// has never seen that URL before (so no merge is necessary).
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, UpdateToNonTypedURL) {
const base::string16 kHistoryUrl(
ASCIIToUTF16("http://www.add-delete-add-history.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Populate one client with a non-typed URL, should not be synced.
GURL new_url(kHistoryUrl);
AddUrlToHistoryWithTransition(0, new_url, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED);
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Both clients should have 0 typed URLs.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(0U, urls.size());
// Now, add a typed visit to this URL.
AddUrlToHistory(0, new_url);
// Let sync finish.
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
// Both clients should have this URL as typed and have two visits synced up.
ASSERT_TRUE(CheckClientsEqual());
urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(new_url, urls[0].url());
ASSERT_EQ(2, GetVisitCountForFirstURL(0));
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
DontSyncUpdatedNonTypedURLs) {
// Checks if a non-typed URL that has been updated (modified) doesn't get
// synced. This is a regression test after fixing a bug where adding a
// non-typed URL was guarded against but later modifying it was not. Since
// "update" is "update or create if missing", non-typed URLs were being
// created.
const GURL kNonTypedURL("http://link.google.com/");
const GURL kTypedURL("http://typed.google.com/");
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
AddUrlToHistoryWithTransition(0, kNonTypedURL, ui::PAGE_TRANSITION_LINK,
history::SOURCE_BROWSED);
AddUrlToHistoryWithTransition(0, kTypedURL, ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
// Modify the non-typed URL. It should not get synced.
typed_urls_helper::SetPageTitle(0, kNonTypedURL, "Welcome to Non-Typed URL");
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
history::VisitVector visits;
// First client has both visits.
visits = typed_urls_helper::GetVisitsForURLFromClient(0, kNonTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_LINK));
visits = typed_urls_helper::GetVisitsForURLFromClient(0, kTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
// Second client has only the typed visit.
visits = typed_urls_helper::GetVisitsForURLFromClient(1, kNonTypedURL);
ASSERT_EQ(0U, visits.size());
visits = typed_urls_helper::GetVisitsForURLFromClient(1, kTypedURL);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, SyncTypedRedirects) {
const base::string16 kHistoryUrl(ASCIIToUTF16("http://typed.google.com/"));
const base::string16 kRedirectedHistoryUrl(
ASCIIToUTF16("http://www.typed.google.com/"));
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
// Simulate a typed address that gets redirected by the server to a different
// address.
GURL initial_url(kHistoryUrl);
const ui::PageTransition initial_transition = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_CHAIN_START);
AddUrlToHistoryWithTransition(0, initial_url, initial_transition,
history::SOURCE_BROWSED);
GURL redirected_url(kRedirectedHistoryUrl);
const ui::PageTransition redirected_transition = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_CHAIN_END |
ui::PAGE_TRANSITION_SERVER_REDIRECT);
// This address will have a typed_count == 0 because it's a redirection.
// It should still be synced.
AddUrlToHistoryWithTransition(0, redirected_url, redirected_transition,
history::SOURCE_BROWSED);
// Both clients should have both URLs.
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
history::VisitVector visits =
typed_urls_helper::GetVisitsForURLFromClient(0, initial_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(0, redirected_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(1, initial_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
visits = typed_urls_helper::GetVisitsForURLFromClient(1, redirected_url);
ASSERT_EQ(1U, visits.size());
EXPECT_TRUE(ui::PageTransitionCoreTypeIs(visits[0].transition,
ui::PAGE_TRANSITION_TYPED));
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest,
SkipImportedVisits) {
GURL imported_url("http://imported_url.com");
GURL browsed_url("http://browsed_url.com");
GURL browsed_and_imported_url("http://browsed_and_imported_url.com");
ASSERT_TRUE(SetupClients());
// Create 3 items in our first client - 1 imported, one browsed, one with
// both imported and browsed entries.
AddUrlToHistoryWithTransition(0, imported_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_FIREFOX_IMPORTED);
AddUrlToHistoryWithTransition(0, browsed_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
AddUrlToHistoryWithTransition(0, browsed_and_imported_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_FIREFOX_IMPORTED);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
history::URLRows urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(browsed_url, urls[0].url());
// Now browse to 3rd URL - this should cause it to be synced, even though it
// was initially imported.
AddUrlToHistoryWithTransition(0, browsed_and_imported_url,
ui::PAGE_TRANSITION_TYPED,
history::SOURCE_BROWSED);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
urls = GetTypedUrlsFromClient(1);
ASSERT_EQ(2U, urls.size());
// Make sure the imported URL didn't make it over.
for (size_t i = 0; i < urls.size(); ++i) {
ASSERT_NE(imported_url, urls[i].url());
}
}
IN_PROC_BROWSER_TEST_F(TwoClientTypedUrlsSyncTest, BookmarksWithTypedVisit) {
GURL bookmark_url("http://www.bookmark.google.com/");
GURL bookmark_icon_url("http://www.bookmark.google.com/favicon.ico");
ASSERT_TRUE(SetupClients());
// Create a bookmark.
const BookmarkNode* node = bookmarks_helper::AddURL(
0, bookmarks_helper::IndexedURLTitle(0), bookmark_url);
bookmarks_helper::SetFavicon(0, node, bookmark_icon_url,
bookmarks_helper::CreateFavicon(SK_ColorWHITE),
bookmarks_helper::FROM_UI);
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
// A row in the DB for client 1 should have been created as a result of the
// sync.
history::URLRow row;
ASSERT_TRUE(GetUrlFromClient(1, bookmark_url, &row));
// Now, add a typed visit for client 0 to the bookmark URL and sync it over
// - this should not cause a crash.
AddUrlToHistory(0, bookmark_url);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
ASSERT_TRUE(AwaitCheckAllProfilesHaveSameURLs());
history::URLRows urls = GetTypedUrlsFromClient(0);
ASSERT_EQ(1U, urls.size());
ASSERT_EQ(bookmark_url, urls[0].url());
ASSERT_EQ(1, GetVisitCountForFirstURL(0));
}
| bsd-3-clause |
mythmon/kitsune | kitsune/search/urls.py | 359 | from django.conf.urls import patterns, url
urlpatterns = patterns(
'kitsune.search.views',
url(r'^$', 'simple_search', name='search'),
url(r'^/advanced$', 'advanced_search', name='search.advanced'),
url(r'^/xml$', 'opensearch_plugin', name='search.plugin'),
url(r'^/suggestions$', 'opensearch_suggestions', name='search.suggestions'),
)
| bsd-3-clause |
atul-bhouraskar/django | tests/prefetch_related/tests.py | 69028 | from unittest import mock
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection
from django.db.models import Prefetch, QuerySet, prefetch_related_objects
from django.db.models.query import get_prefetcher
from django.db.models.sql import Query
from django.test import TestCase, override_settings
from django.test.utils import CaptureQueriesContext
from .models import (
Article, Author, Author2, AuthorAddress, AuthorWithAge, Bio, Book,
Bookmark, BookReview, BookWithYear, Comment, Department, Employee,
FavoriteAuthors, House, LessonEntry, ModelIterableSubclass, Person,
Qualification, Reader, Room, TaggedItem, Teacher, WordEntry,
)
class TestDataMixin:
@classmethod
def setUpTestData(cls):
cls.book1 = Book.objects.create(title='Poems')
cls.book2 = Book.objects.create(title='Jane Eyre')
cls.book3 = Book.objects.create(title='Wuthering Heights')
cls.book4 = Book.objects.create(title='Sense and Sensibility')
cls.author1 = Author.objects.create(name='Charlotte', first_book=cls.book1)
cls.author2 = Author.objects.create(name='Anne', first_book=cls.book1)
cls.author3 = Author.objects.create(name='Emily', first_book=cls.book1)
cls.author4 = Author.objects.create(name='Jane', first_book=cls.book4)
cls.book1.authors.add(cls.author1, cls.author2, cls.author3)
cls.book2.authors.add(cls.author1)
cls.book3.authors.add(cls.author3)
cls.book4.authors.add(cls.author4)
cls.reader1 = Reader.objects.create(name='Amy')
cls.reader2 = Reader.objects.create(name='Belinda')
cls.reader1.books_read.add(cls.book1, cls.book4)
cls.reader2.books_read.add(cls.book2, cls.book4)
class PrefetchRelatedTests(TestDataMixin, TestCase):
def assertWhereContains(self, sql, needle):
where_idx = sql.index('WHERE')
self.assertEqual(
sql.count(str(needle), where_idx), 1,
msg="WHERE clause doesn't contain %s, actual SQL: %s" % (needle, sql[where_idx:])
)
def test_m2m_forward(self):
with self.assertNumQueries(2):
lists = [list(b.authors.all()) for b in Book.objects.prefetch_related('authors')]
normal_lists = [list(b.authors.all()) for b in Book.objects.all()]
self.assertEqual(lists, normal_lists)
def test_m2m_reverse(self):
with self.assertNumQueries(2):
lists = [list(a.books.all()) for a in Author.objects.prefetch_related('books')]
normal_lists = [list(a.books.all()) for a in Author.objects.all()]
self.assertEqual(lists, normal_lists)
def test_foreignkey_forward(self):
with self.assertNumQueries(2):
books = [a.first_book for a in Author.objects.prefetch_related('first_book')]
normal_books = [a.first_book for a in Author.objects.all()]
self.assertEqual(books, normal_books)
def test_foreignkey_reverse(self):
with self.assertNumQueries(2):
[list(b.first_time_authors.all())
for b in Book.objects.prefetch_related('first_time_authors')]
self.assertSequenceEqual(self.book2.authors.all(), [self.author1])
def test_onetoone_reverse_no_match(self):
# Regression for #17439
with self.assertNumQueries(2):
book = Book.objects.prefetch_related('bookwithyear').all()[0]
with self.assertNumQueries(0):
with self.assertRaises(BookWithYear.DoesNotExist):
book.bookwithyear
def test_onetoone_reverse_with_to_field_pk(self):
"""
A model (Bio) with a OneToOneField primary key (author) that references
a non-pk field (name) on the related model (Author) is prefetchable.
"""
Bio.objects.bulk_create([
Bio(author=self.author1),
Bio(author=self.author2),
Bio(author=self.author3),
])
authors = Author.objects.filter(
name__in=[self.author1, self.author2, self.author3],
).prefetch_related('bio')
with self.assertNumQueries(2):
for author in authors:
self.assertEqual(author.name, author.bio.author.name)
def test_survives_clone(self):
with self.assertNumQueries(2):
[list(b.first_time_authors.all())
for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)]
def test_len(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors')
len(qs)
[list(b.first_time_authors.all()) for b in qs]
def test_bool(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors')
bool(qs)
[list(b.first_time_authors.all()) for b in qs]
def test_count(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors')
[b.first_time_authors.count() for b in qs]
def test_exists(self):
with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors')
[b.first_time_authors.exists() for b in qs]
def test_in_and_prefetch_related(self):
"""
Regression test for #20242 - QuerySet "in" didn't work the first time
when using prefetch_related. This was fixed by the removal of chunked
reads from QuerySet iteration in
70679243d1786e03557c28929f9762a119e3ac14.
"""
qs = Book.objects.prefetch_related('first_time_authors')
self.assertIn(qs[0], qs)
def test_clear(self):
with self.assertNumQueries(5):
with_prefetch = Author.objects.prefetch_related('books')
without_prefetch = with_prefetch.prefetch_related(None)
[list(a.books.all()) for a in without_prefetch]
def test_m2m_then_m2m(self):
"""A m2m can be followed through another m2m."""
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by')
lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
])
def test_overriding_prefetch(self):
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books', 'books__read_by')
lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
])
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by', 'books')
lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights
[["Amy", "Belinda"]], # Jane - Sense and Sense
])
def test_get(self):
"""
Objects retrieved with .get() get the prefetch behavior.
"""
# Need a double
with self.assertNumQueries(3):
author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte")
lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()]
self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
def test_foreign_key_then_m2m(self):
"""
A m2m relation can be followed after a relation like ForeignKey that
doesn't have many objects.
"""
with self.assertNumQueries(2):
qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
lists = [[str(r) for r in a.first_book.read_by.all()]
for a in qs]
self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
def test_reverse_one_to_one_then_m2m(self):
"""
A m2m relation can be followed after going through the select_related
reverse of an o2o.
"""
qs = Author.objects.prefetch_related('bio__books').select_related('bio')
with self.assertNumQueries(1):
list(qs.all())
Bio.objects.create(author=self.author1)
with self.assertNumQueries(2):
list(qs.all())
def test_attribute_error(self):
qs = Reader.objects.all().prefetch_related('books_read__xyz')
msg = (
"Cannot find 'xyz' on Book object, 'books_read__xyz' "
"is an invalid parameter to prefetch_related()"
)
with self.assertRaisesMessage(AttributeError, msg) as cm:
list(qs)
self.assertIn('prefetch_related', str(cm.exception))
def test_invalid_final_lookup(self):
qs = Book.objects.prefetch_related('authors__name')
msg = (
"'authors__name' does not resolve to an item that supports "
"prefetching - this is an invalid parameter to prefetch_related()."
)
with self.assertRaisesMessage(ValueError, msg) as cm:
list(qs)
self.assertIn('prefetch_related', str(cm.exception))
self.assertIn("name", str(cm.exception))
def test_prefetch_eq(self):
prefetch_1 = Prefetch('authors', queryset=Author.objects.all())
prefetch_2 = Prefetch('books', queryset=Book.objects.all())
self.assertEqual(prefetch_1, prefetch_1)
self.assertEqual(prefetch_1, mock.ANY)
self.assertNotEqual(prefetch_1, prefetch_2)
def test_forward_m2m_to_attr_conflict(self):
msg = 'to_attr=authors conflicts with a field on the Book model.'
authors = Author.objects.all()
with self.assertRaisesMessage(ValueError, msg):
list(Book.objects.prefetch_related(
Prefetch('authors', queryset=authors, to_attr='authors'),
))
# Without the ValueError, an author was deleted due to the implicit
# save of the relation assignment.
self.assertEqual(self.book1.authors.count(), 3)
def test_reverse_m2m_to_attr_conflict(self):
msg = 'to_attr=books conflicts with a field on the Author model.'
poems = Book.objects.filter(title='Poems')
with self.assertRaisesMessage(ValueError, msg):
list(Author.objects.prefetch_related(
Prefetch('books', queryset=poems, to_attr='books'),
))
# Without the ValueError, a book was deleted due to the implicit
# save of reverse relation assignment.
self.assertEqual(self.author1.books.count(), 2)
def test_m2m_then_reverse_fk_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related('authors__addresses'))
sql = queries[-1]['sql']
self.assertWhereContains(sql, self.author1.name)
def test_m2m_then_m2m_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related('authors__favorite_authors'))
sql = queries[-1]['sql']
self.assertWhereContains(sql, self.author1.name)
def test_m2m_then_reverse_one_to_one_object_ids(self):
with CaptureQueriesContext(connection) as queries:
list(Book.objects.prefetch_related('authors__authorwithage'))
sql = queries[-1]['sql']
self.assertWhereContains(sql, self.author1.id)
def test_filter_deferred(self):
"""
Related filtering of prefetched querysets is deferred on m2m and
reverse m2o relations until necessary.
"""
add_q = Query.add_q
for relation in ['authors', 'first_time_authors']:
with self.subTest(relation=relation):
with mock.patch.object(
Query,
'add_q',
autospec=True,
side_effect=lambda self, q: add_q(self, q),
) as add_q_mock:
list(Book.objects.prefetch_related(relation))
self.assertEqual(add_q_mock.call_count, 1)
def test_named_values_list(self):
qs = Author.objects.prefetch_related('books')
self.assertCountEqual(
[value.name for value in qs.values_list('name', named=True)],
['Anne', 'Charlotte', 'Emily', 'Jane'],
)
class RawQuerySetTests(TestDataMixin, TestCase):
def test_basic(self):
with self.assertNumQueries(2):
books = Book.objects.raw(
"SELECT * FROM prefetch_related_book WHERE id = %s",
(self.book1.id,)
).prefetch_related('authors')
book1 = list(books)[0]
with self.assertNumQueries(0):
self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3])
def test_prefetch_before_raw(self):
with self.assertNumQueries(2):
books = Book.objects.prefetch_related('authors').raw(
"SELECT * FROM prefetch_related_book WHERE id = %s",
(self.book1.id,)
)
book1 = list(books)[0]
with self.assertNumQueries(0):
self.assertCountEqual(book1.authors.all(), [self.author1, self.author2, self.author3])
def test_clear(self):
with self.assertNumQueries(5):
with_prefetch = Author.objects.raw(
"SELECT * FROM prefetch_related_author"
).prefetch_related('books')
without_prefetch = with_prefetch.prefetch_related(None)
[list(a.books.all()) for a in without_prefetch]
class CustomPrefetchTests(TestCase):
@classmethod
def traverse_qs(cls, obj_iter, path):
"""
Helper method that returns a list containing a list of the objects in the
obj_iter. Then for each object in the obj_iter, the path will be
recursively travelled and the found objects are added to the return value.
"""
ret_val = []
if hasattr(obj_iter, 'all'):
obj_iter = obj_iter.all()
try:
iter(obj_iter)
except TypeError:
obj_iter = [obj_iter]
for obj in obj_iter:
rel_objs = []
for part in path:
if not part:
continue
try:
related = getattr(obj, part[0])
except ObjectDoesNotExist:
continue
if related is not None:
rel_objs.extend(cls.traverse_qs(related, [part[1:]]))
ret_val.append((obj, rel_objs))
return ret_val
@classmethod
def setUpTestData(cls):
cls.person1 = Person.objects.create(name='Joe')
cls.person2 = Person.objects.create(name='Mary')
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
cls.house1 = House.objects.create(name='House 1', address='123 Main St', owner=cls.person1)
cls.room1_1 = Room.objects.create(name='Dining room', house=cls.house1)
cls.room1_2 = Room.objects.create(name='Lounge', house=cls.house1)
cls.room1_3 = Room.objects.create(name='Kitchen', house=cls.house1)
cls.house1.main_room = cls.room1_1
cls.house1.save()
cls.person1.houses.add(cls.house1)
cls.house2 = House.objects.create(name='House 2', address='45 Side St', owner=cls.person1)
cls.room2_1 = Room.objects.create(name='Dining room', house=cls.house2)
cls.room2_2 = Room.objects.create(name='Lounge', house=cls.house2)
cls.room2_3 = Room.objects.create(name='Kitchen', house=cls.house2)
cls.house2.main_room = cls.room2_1
cls.house2.save()
cls.person1.houses.add(cls.house2)
cls.house3 = House.objects.create(name='House 3', address='6 Downing St', owner=cls.person2)
cls.room3_1 = Room.objects.create(name='Dining room', house=cls.house3)
cls.room3_2 = Room.objects.create(name='Lounge', house=cls.house3)
cls.room3_3 = Room.objects.create(name='Kitchen', house=cls.house3)
cls.house3.main_room = cls.room3_1
cls.house3.save()
cls.person2.houses.add(cls.house3)
cls.house4 = House.objects.create(name='house 4', address="7 Regents St", owner=cls.person2)
cls.room4_1 = Room.objects.create(name='Dining room', house=cls.house4)
cls.room4_2 = Room.objects.create(name='Lounge', house=cls.house4)
cls.room4_3 = Room.objects.create(name='Kitchen', house=cls.house4)
cls.house4.main_room = cls.room4_1
cls.house4.save()
cls.person2.houses.add(cls.house4)
def test_traverse_qs(self):
qs = Person.objects.prefetch_related('houses')
related_objs_normal = [list(p.houses.all()) for p in qs],
related_objs_from_traverse = [[inner[0] for inner in o[1]]
for o in self.traverse_qs(qs, [['houses']])]
self.assertEqual(related_objs_normal, (related_objs_from_traverse,))
def test_ambiguous(self):
# Ambiguous: Lookup was already seen with a different queryset.
msg = (
"'houses' lookup was already seen with a different queryset. You "
"may need to adjust the ordering of your lookups."
)
# lookup.queryset shouldn't be evaluated.
with self.assertNumQueries(3):
with self.assertRaisesMessage(ValueError, msg):
self.traverse_qs(
Person.objects.prefetch_related(
'houses__rooms',
Prefetch('houses', queryset=House.objects.all()),
),
[['houses', 'rooms']],
)
# Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms.
msg = (
"Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is "
"an invalid parameter to prefetch_related()"
)
with self.assertRaisesMessage(AttributeError, msg):
self.traverse_qs(
Person.objects.prefetch_related(
'houses_lst__rooms',
Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')
),
[['houses', 'rooms']]
)
# Not ambiguous.
self.traverse_qs(
Person.objects.prefetch_related('houses__rooms', 'houses'),
[['houses', 'rooms']]
)
self.traverse_qs(
Person.objects.prefetch_related(
'houses__rooms',
Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')
),
[['houses', 'rooms']]
)
def test_m2m(self):
# Control lookups.
with self.assertNumQueries(2):
lst1 = self.traverse_qs(
Person.objects.prefetch_related('houses'),
[['houses']]
)
# Test lookups.
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch('houses')),
[['houses']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst')),
[['houses_lst']]
)
self.assertEqual(lst1, lst2)
def test_reverse_m2m(self):
# Control lookups.
with self.assertNumQueries(2):
lst1 = self.traverse_qs(
House.objects.prefetch_related('occupants'),
[['occupants']]
)
# Test lookups.
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
House.objects.prefetch_related(Prefetch('occupants')),
[['occupants']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
lst2 = self.traverse_qs(
House.objects.prefetch_related(Prefetch('occupants', to_attr='occupants_lst')),
[['occupants_lst']]
)
self.assertEqual(lst1, lst2)
def test_m2m_through_fk(self):
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
Room.objects.prefetch_related('house__occupants'),
[['house', 'occupants']]
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Room.objects.prefetch_related(Prefetch('house__occupants')),
[['house', 'occupants']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Room.objects.prefetch_related(Prefetch('house__occupants', to_attr='occupants_lst')),
[['house', 'occupants_lst']]
)
self.assertEqual(lst1, lst2)
def test_m2m_through_gfk(self):
TaggedItem.objects.create(tag="houses", content_object=self.house1)
TaggedItem.objects.create(tag="houses", content_object=self.house2)
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
TaggedItem.objects.filter(tag='houses').prefetch_related('content_object__rooms'),
[['content_object', 'rooms']]
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
TaggedItem.objects.prefetch_related(
Prefetch('content_object'),
Prefetch('content_object__rooms', to_attr='rooms_lst')
),
[['content_object', 'rooms_lst']]
)
self.assertEqual(lst1, lst2)
def test_o2m_through_m2m(self):
# Control lookups.
with self.assertNumQueries(3):
lst1 = self.traverse_qs(
Person.objects.prefetch_related('houses', 'houses__rooms'),
[['houses', 'rooms']]
)
# Test lookups.
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch('houses'), 'houses__rooms'),
[['houses', 'rooms']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch('houses'), Prefetch('houses__rooms')),
[['houses', 'rooms']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(Prefetch('houses', to_attr='houses_lst'), 'houses_lst__rooms'),
[['houses_lst', 'rooms']]
)
self.assertEqual(lst1, lst2)
with self.assertNumQueries(3):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
Prefetch('houses', to_attr='houses_lst'),
Prefetch('houses_lst__rooms', to_attr='rooms_lst')
),
[['houses_lst', 'rooms_lst']]
)
self.assertEqual(lst1, lst2)
def test_generic_rel(self):
bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
TaggedItem.objects.create(content_object=bookmark, tag='django')
TaggedItem.objects.create(content_object=bookmark, favorite=bookmark, tag='python')
# Control lookups.
with self.assertNumQueries(4):
lst1 = self.traverse_qs(
Bookmark.objects.prefetch_related('tags', 'tags__content_object', 'favorite_tags'),
[['tags', 'content_object'], ['favorite_tags']]
)
# Test lookups.
with self.assertNumQueries(4):
lst2 = self.traverse_qs(
Bookmark.objects.prefetch_related(
Prefetch('tags', to_attr='tags_lst'),
Prefetch('tags_lst__content_object'),
Prefetch('favorite_tags'),
),
[['tags_lst', 'content_object'], ['favorite_tags']]
)
self.assertEqual(lst1, lst2)
def test_traverse_single_item_property(self):
# Control lookups.
with self.assertNumQueries(5):
lst1 = self.traverse_qs(
Person.objects.prefetch_related(
'houses__rooms',
'primary_house__occupants__houses',
),
[['primary_house', 'occupants', 'houses']]
)
# Test lookups.
with self.assertNumQueries(5):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
'houses__rooms',
Prefetch('primary_house__occupants', to_attr='occupants_lst'),
'primary_house__occupants_lst__houses',
),
[['primary_house', 'occupants_lst', 'houses']]
)
self.assertEqual(lst1, lst2)
def test_traverse_multiple_items_property(self):
# Control lookups.
with self.assertNumQueries(4):
lst1 = self.traverse_qs(
Person.objects.prefetch_related(
'houses',
'all_houses__occupants__houses',
),
[['all_houses', 'occupants', 'houses']]
)
# Test lookups.
with self.assertNumQueries(4):
lst2 = self.traverse_qs(
Person.objects.prefetch_related(
'houses',
Prefetch('all_houses__occupants', to_attr='occupants_lst'),
'all_houses__occupants_lst__houses',
),
[['all_houses', 'occupants_lst', 'houses']]
)
self.assertEqual(lst1, lst2)
def test_custom_qs(self):
# Test basic.
with self.assertNumQueries(2):
lst1 = list(Person.objects.prefetch_related('houses'))
with self.assertNumQueries(2):
lst2 = list(Person.objects.prefetch_related(
Prefetch('houses', queryset=House.objects.all(), to_attr='houses_lst')))
self.assertEqual(
self.traverse_qs(lst1, [['houses']]),
self.traverse_qs(lst2, [['houses_lst']])
)
# Test queryset filtering.
with self.assertNumQueries(2):
lst2 = list(
Person.objects.prefetch_related(
Prefetch(
'houses',
queryset=House.objects.filter(pk__in=[self.house1.pk, self.house3.pk]),
to_attr='houses_lst',
)
)
)
self.assertEqual(len(lst2[0].houses_lst), 1)
self.assertEqual(lst2[0].houses_lst[0], self.house1)
self.assertEqual(len(lst2[1].houses_lst), 1)
self.assertEqual(lst2[1].houses_lst[0], self.house3)
# Test flattened.
with self.assertNumQueries(3):
lst1 = list(Person.objects.prefetch_related('houses__rooms'))
with self.assertNumQueries(3):
lst2 = list(Person.objects.prefetch_related(
Prefetch('houses__rooms', queryset=Room.objects.all(), to_attr='rooms_lst')))
self.assertEqual(
self.traverse_qs(lst1, [['houses', 'rooms']]),
self.traverse_qs(lst2, [['houses', 'rooms_lst']])
)
# Test inner select_related.
with self.assertNumQueries(3):
lst1 = list(Person.objects.prefetch_related('houses__owner'))
with self.assertNumQueries(2):
lst2 = list(Person.objects.prefetch_related(
Prefetch('houses', queryset=House.objects.select_related('owner'))))
self.assertEqual(
self.traverse_qs(lst1, [['houses', 'owner']]),
self.traverse_qs(lst2, [['houses', 'owner']])
)
# Test inner prefetch.
inner_rooms_qs = Room.objects.filter(pk__in=[self.room1_1.pk, self.room1_2.pk])
houses_qs_prf = House.objects.prefetch_related(
Prefetch('rooms', queryset=inner_rooms_qs, to_attr='rooms_lst'))
with self.assertNumQueries(4):
lst2 = list(Person.objects.prefetch_related(
Prefetch('houses', queryset=houses_qs_prf.filter(pk=self.house1.pk), to_attr='houses_lst'),
Prefetch('houses_lst__rooms_lst__main_room_of')
))
self.assertEqual(len(lst2[0].houses_lst[0].rooms_lst), 2)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0], self.room1_1)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[1], self.room1_2)
self.assertEqual(lst2[0].houses_lst[0].rooms_lst[0].main_room_of, self.house1)
self.assertEqual(len(lst2[1].houses_lst), 0)
# Test ForwardManyToOneDescriptor.
houses = House.objects.select_related('owner')
with self.assertNumQueries(6):
rooms = Room.objects.all().prefetch_related('house')
lst1 = self.traverse_qs(rooms, [['house', 'owner']])
with self.assertNumQueries(2):
rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all()))
lst2 = self.traverse_qs(rooms, [['house', 'owner']])
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
houses = House.objects.select_related('owner')
rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=houses.all(), to_attr='house_attr'))
lst2 = self.traverse_qs(rooms, [['house_attr', 'owner']])
self.assertEqual(lst1, lst2)
room = Room.objects.all().prefetch_related(
Prefetch('house', queryset=houses.filter(address='DoesNotExist'))
).first()
with self.assertRaises(ObjectDoesNotExist):
getattr(room, 'house')
room = Room.objects.all().prefetch_related(
Prefetch('house', queryset=houses.filter(address='DoesNotExist'), to_attr='house_attr')
).first()
self.assertIsNone(room.house_attr)
rooms = Room.objects.all().prefetch_related(Prefetch('house', queryset=House.objects.only('name')))
with self.assertNumQueries(2):
getattr(rooms.first().house, 'name')
with self.assertNumQueries(3):
getattr(rooms.first().house, 'address')
# Test ReverseOneToOneDescriptor.
houses = House.objects.select_related('owner')
with self.assertNumQueries(6):
rooms = Room.objects.all().prefetch_related('main_room_of')
lst1 = self.traverse_qs(rooms, [['main_room_of', 'owner']])
with self.assertNumQueries(2):
rooms = Room.objects.all().prefetch_related(Prefetch('main_room_of', queryset=houses.all()))
lst2 = self.traverse_qs(rooms, [['main_room_of', 'owner']])
self.assertEqual(lst1, lst2)
with self.assertNumQueries(2):
rooms = list(
Room.objects.all().prefetch_related(
Prefetch('main_room_of', queryset=houses.all(), to_attr='main_room_of_attr')
)
)
lst2 = self.traverse_qs(rooms, [['main_room_of_attr', 'owner']])
self.assertEqual(lst1, lst2)
room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(
Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'))
).first()
with self.assertRaises(ObjectDoesNotExist):
getattr(room, 'main_room_of')
room = Room.objects.filter(main_room_of__isnull=False).prefetch_related(
Prefetch('main_room_of', queryset=houses.filter(address='DoesNotExist'), to_attr='main_room_of_attr')
).first()
self.assertIsNone(room.main_room_of_attr)
# The custom queryset filters should be applied to the queryset
# instance returned by the manager.
person = Person.objects.prefetch_related(
Prefetch('houses', queryset=House.objects.filter(name='House 1')),
).get(pk=self.person1.pk)
self.assertEqual(
list(person.houses.all()),
list(person.houses.all().all()),
)
def test_nested_prefetch_related_are_not_overwritten(self):
# Regression test for #24873
houses_2 = House.objects.prefetch_related(Prefetch('rooms'))
persons = Person.objects.prefetch_related(Prefetch('houses', queryset=houses_2))
houses = House.objects.prefetch_related(Prefetch('occupants', queryset=persons))
list(houses) # queryset must be evaluated once to reproduce the bug.
self.assertEqual(
houses.all()[0].occupants.all()[0].houses.all()[1].rooms.all()[0],
self.room2_1
)
def test_nested_prefetch_related_with_duplicate_prefetcher(self):
"""
Nested prefetches whose name clashes with descriptor names
(Person.houses here) are allowed.
"""
occupants = Person.objects.prefetch_related(
Prefetch('houses', to_attr='some_attr_name'),
Prefetch('houses', queryset=House.objects.prefetch_related('main_room')),
)
houses = House.objects.prefetch_related(Prefetch('occupants', queryset=occupants))
with self.assertNumQueries(5):
self.traverse_qs(list(houses), [['occupants', 'houses', 'main_room']])
def test_values_queryset(self):
msg = 'Prefetch querysets cannot use raw(), values(), and values_list().'
with self.assertRaisesMessage(ValueError, msg):
Prefetch('houses', House.objects.values('pk'))
with self.assertRaisesMessage(ValueError, msg):
Prefetch('houses', House.objects.values_list('pk'))
# That error doesn't affect managers with custom ModelIterable subclasses
self.assertIs(Teacher.objects_custom.all()._iterable_class, ModelIterableSubclass)
Prefetch('teachers', Teacher.objects_custom.all())
def test_raw_queryset(self):
msg = 'Prefetch querysets cannot use raw(), values(), and values_list().'
with self.assertRaisesMessage(ValueError, msg):
Prefetch('houses', House.objects.raw('select pk from house'))
def test_to_attr_doesnt_cache_through_attr_as_list(self):
house = House.objects.prefetch_related(
Prefetch('rooms', queryset=Room.objects.all(), to_attr='to_rooms'),
).get(pk=self.house3.pk)
self.assertIsInstance(house.rooms.all(), QuerySet)
def test_to_attr_cached_property(self):
persons = Person.objects.prefetch_related(
Prefetch('houses', House.objects.all(), to_attr='cached_all_houses'),
)
for person in persons:
# To bypass caching at the related descriptor level, don't use
# person.houses.all() here.
all_houses = list(House.objects.filter(occupants=person))
with self.assertNumQueries(0):
self.assertEqual(person.cached_all_houses, all_houses)
def test_filter_deferred(self):
"""
Related filtering of prefetched querysets is deferred until necessary.
"""
add_q = Query.add_q
with mock.patch.object(
Query,
'add_q',
autospec=True,
side_effect=lambda self, q: add_q(self, q),
) as add_q_mock:
list(House.objects.prefetch_related(
Prefetch('occupants', queryset=Person.objects.all())
))
self.assertEqual(add_q_mock.call_count, 1)
class DefaultManagerTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.qual1 = Qualification.objects.create(name='BA')
cls.qual2 = Qualification.objects.create(name='BSci')
cls.qual3 = Qualification.objects.create(name='MA')
cls.qual4 = Qualification.objects.create(name='PhD')
cls.teacher1 = Teacher.objects.create(name='Mr Cleese')
cls.teacher2 = Teacher.objects.create(name='Mr Idle')
cls.teacher3 = Teacher.objects.create(name='Mr Chapman')
cls.teacher1.qualifications.add(cls.qual1, cls.qual2, cls.qual3, cls.qual4)
cls.teacher2.qualifications.add(cls.qual1)
cls.teacher3.qualifications.add(cls.qual2)
cls.dept1 = Department.objects.create(name='English')
cls.dept2 = Department.objects.create(name='Physics')
cls.dept1.teachers.add(cls.teacher1, cls.teacher2)
cls.dept2.teachers.add(cls.teacher1, cls.teacher3)
def test_m2m_then_m2m(self):
with self.assertNumQueries(3):
# When we prefetch the teachers, and force the query, we don't want
# the default manager on teachers to immediately get all the related
# qualifications, since this will do one query per teacher.
qs = Department.objects.prefetch_related('teachers')
depts = "".join("%s department: %s\n" %
(dept.name, ", ".join(str(t) for t in dept.teachers.all()))
for dept in qs)
self.assertEqual(depts,
"English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
"Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman (BSci)\n")
class GenericRelationTests(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title="Winnie the Pooh")
book2 = Book.objects.create(title="Do you like green eggs and spam?")
book3 = Book.objects.create(title="Three Men In A Boat")
reader1 = Reader.objects.create(name="me")
reader2 = Reader.objects.create(name="you")
reader3 = Reader.objects.create(name="someone")
book1.read_by.add(reader1, reader2)
book2.read_by.add(reader2)
book3.read_by.add(reader3)
cls.book1, cls.book2, cls.book3 = book1, book2, book3
cls.reader1, cls.reader2, cls.reader3 = reader1, reader2, reader3
def test_prefetch_GFK(self):
TaggedItem.objects.create(tag="awesome", content_object=self.book1)
TaggedItem.objects.create(tag="great", content_object=self.reader1)
TaggedItem.objects.create(tag="outstanding", content_object=self.book2)
TaggedItem.objects.create(tag="amazing", content_object=self.reader3)
# 1 for TaggedItem table, 1 for Book table, 1 for Reader table
with self.assertNumQueries(3):
qs = TaggedItem.objects.prefetch_related('content_object')
list(qs)
def test_prefetch_GFK_nonint_pk(self):
Comment.objects.create(comment="awesome", content_object=self.book1)
# 1 for Comment table, 1 for Book table
with self.assertNumQueries(2):
qs = Comment.objects.prefetch_related('content_object')
[c.content_object for c in qs]
def test_prefetch_GFK_uuid_pk(self):
article = Article.objects.create(name='Django')
Comment.objects.create(comment='awesome', content_object_uuid=article)
qs = Comment.objects.prefetch_related('content_object_uuid')
self.assertEqual([c.content_object_uuid for c in qs], [article])
def test_prefetch_GFK_fk_pk(self):
book = Book.objects.create(title='Poems')
book_with_year = BookWithYear.objects.create(book=book, published_year=2019)
Comment.objects.create(comment='awesome', content_object=book_with_year)
qs = Comment.objects.prefetch_related('content_object')
self.assertEqual([c.content_object for c in qs], [book_with_year])
def test_traverse_GFK(self):
"""
A 'content_object' can be traversed with prefetch_related() and
get to related objects on the other side (assuming it is suitably
filtered)
"""
TaggedItem.objects.create(tag="awesome", content_object=self.book1)
TaggedItem.objects.create(tag="awesome", content_object=self.book2)
TaggedItem.objects.create(tag="awesome", content_object=self.book3)
TaggedItem.objects.create(tag="awesome", content_object=self.reader1)
TaggedItem.objects.create(tag="awesome", content_object=self.reader2)
ct = ContentType.objects.get_for_model(Book)
# We get 3 queries - 1 for main query, 1 for content_objects since they
# all use the same table, and 1 for the 'read_by' relation.
with self.assertNumQueries(3):
# If we limit to books, we know that they will have 'read_by'
# attributes, so the following makes sense:
qs = TaggedItem.objects.filter(content_type=ct, tag='awesome').prefetch_related('content_object__read_by')
readers_of_awesome_books = {r.name for tag in qs
for r in tag.content_object.read_by.all()}
self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"})
def test_nullable_GFK(self):
TaggedItem.objects.create(tag="awesome", content_object=self.book1,
created_by=self.reader1)
TaggedItem.objects.create(tag="great", content_object=self.book2)
TaggedItem.objects.create(tag="rubbish", content_object=self.book3)
with self.assertNumQueries(2):
result = [t.created_by for t in TaggedItem.objects.prefetch_related('created_by')]
self.assertEqual(result,
[t.created_by for t in TaggedItem.objects.all()])
def test_generic_relation(self):
bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
TaggedItem.objects.create(content_object=bookmark, tag='django')
TaggedItem.objects.create(content_object=bookmark, tag='python')
with self.assertNumQueries(2):
tags = [t.tag for b in Bookmark.objects.prefetch_related('tags')
for t in b.tags.all()]
self.assertEqual(sorted(tags), ["django", "python"])
def test_charfield_GFK(self):
b = Bookmark.objects.create(url='http://www.djangoproject.com/')
TaggedItem.objects.create(content_object=b, tag='django')
TaggedItem.objects.create(content_object=b, favorite=b, tag='python')
with self.assertNumQueries(3):
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
self.assertEqual(sorted(i.tag for i in bookmark.tags.all()), ["django", "python"])
self.assertEqual([i.tag for i in bookmark.favorite_tags.all()], ["python"])
def test_custom_queryset(self):
bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
django_tag = TaggedItem.objects.create(content_object=bookmark, tag='django')
TaggedItem.objects.create(content_object=bookmark, tag='python')
with self.assertNumQueries(2):
bookmark = Bookmark.objects.prefetch_related(
Prefetch('tags', TaggedItem.objects.filter(tag='django')),
).get()
with self.assertNumQueries(0):
self.assertEqual(list(bookmark.tags.all()), [django_tag])
# The custom queryset filters should be applied to the queryset
# instance returned by the manager.
self.assertEqual(list(bookmark.tags.all()), list(bookmark.tags.all().all()))
class MultiTableInheritanceTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.book1 = BookWithYear.objects.create(title='Poems', published_year=2010)
cls.book2 = BookWithYear.objects.create(title='More poems', published_year=2011)
cls.author1 = AuthorWithAge.objects.create(name='Jane', first_book=cls.book1, age=50)
cls.author2 = AuthorWithAge.objects.create(name='Tom', first_book=cls.book1, age=49)
cls.author3 = AuthorWithAge.objects.create(name='Robert', first_book=cls.book2, age=48)
cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1')
cls.book2.aged_authors.add(cls.author2, cls.author3)
cls.br1 = BookReview.objects.create(book=cls.book1, notes='review book1')
cls.br2 = BookReview.objects.create(book=cls.book2, notes='review book2')
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = AuthorWithAge.objects.prefetch_related('addresses')
addresses = [[str(address) for address in obj.addresses.all()] for obj in qs]
self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_foreignkey_to_inherited(self):
with self.assertNumQueries(2):
qs = BookReview.objects.prefetch_related('book')
titles = [obj.book.title for obj in qs]
self.assertEqual(titles, ["Poems", "More poems"])
def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related('books_with_year')
with self.assertNumQueries(2):
lst = [[str(book) for book in author.books_with_year.all()] for author in qs]
qs = AuthorWithAge.objects.all()
lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs]
self.assertEqual(lst, lst2)
qs = BookWithYear.objects.prefetch_related('aged_authors')
with self.assertNumQueries(2):
lst = [[str(author) for author in book.aged_authors.all()] for book in qs]
qs = BookWithYear.objects.all()
lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs]
self.assertEqual(lst, lst2)
def test_parent_link_prefetch(self):
with self.assertNumQueries(2):
[a.author for a in AuthorWithAge.objects.prefetch_related('author')]
@override_settings(DEBUG=True)
def test_child_link_prefetch(self):
with self.assertNumQueries(2):
authors = [a.authorwithage for a in Author.objects.prefetch_related('authorwithage')]
# Regression for #18090: the prefetching query must include an IN clause.
# Note that on Oracle the table name is upper case in the generated SQL,
# thus the .lower() call.
self.assertIn('authorwithage', connection.queries[-1]['sql'].lower())
self.assertIn(' IN ', connection.queries[-1]['sql'])
self.assertEqual(authors, [a.authorwithage for a in Author.objects.all()])
class ForeignKeyToFieldTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.book = Book.objects.create(title='Poems')
cls.author1 = Author.objects.create(name='Jane', first_book=cls.book)
cls.author2 = Author.objects.create(name='Tom', first_book=cls.book)
cls.author3 = Author.objects.create(name='Robert', first_book=cls.book)
cls.author_address = AuthorAddress.objects.create(author=cls.author1, address='SomeStreet 1')
FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
FavoriteAuthors.objects.create(author=cls.author2, likes_author=cls.author3)
FavoriteAuthors.objects.create(author=cls.author3, likes_author=cls.author1)
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = Author.objects.prefetch_related('addresses')
addresses = [[str(address) for address in obj.addresses.all()]
for obj in qs]
self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_m2m(self):
with self.assertNumQueries(3):
qs = Author.objects.all().prefetch_related('favorite_authors', 'favors_me')
favorites = [(
[str(i_like) for i_like in author.favorite_authors.all()],
[str(likes_me) for likes_me in author.favors_me.all()]
) for author in qs]
self.assertEqual(
favorites,
[
([str(self.author2)], [str(self.author3)]),
([str(self.author3)], [str(self.author1)]),
([str(self.author1)], [str(self.author2)])
]
)
class LookupOrderingTest(TestCase):
"""
Test cases that demonstrate that ordering of lookups is important, and
ensure it is preserved.
"""
@classmethod
def setUpTestData(cls):
person1 = Person.objects.create(name='Joe')
person2 = Person.objects.create(name='Mary')
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
house1 = House.objects.create(address='123 Main St')
room1_1 = Room.objects.create(name='Dining room', house=house1)
Room.objects.create(name='Lounge', house=house1)
Room.objects.create(name='Kitchen', house=house1)
house1.main_room = room1_1
house1.save()
person1.houses.add(house1)
house2 = House.objects.create(address='45 Side St')
room2_1 = Room.objects.create(name='Dining room', house=house2)
Room.objects.create(name='Lounge', house=house2)
house2.main_room = room2_1
house2.save()
person1.houses.add(house2)
house3 = House.objects.create(address='6 Downing St')
room3_1 = Room.objects.create(name='Dining room', house=house3)
Room.objects.create(name='Lounge', house=house3)
Room.objects.create(name='Kitchen', house=house3)
house3.main_room = room3_1
house3.save()
person2.houses.add(house3)
house4 = House.objects.create(address='7 Regents St')
room4_1 = Room.objects.create(name='Dining room', house=house4)
Room.objects.create(name='Lounge', house=house4)
house4.main_room = room4_1
house4.save()
person2.houses.add(house4)
def test_order(self):
with self.assertNumQueries(4):
# The following two queries must be done in the same order as written,
# otherwise 'primary_house' will cause non-prefetched lookups
qs = Person.objects.prefetch_related('houses__rooms',
'primary_house__occupants')
[list(p.primary_house.occupants.all()) for p in qs]
class NullableTest(TestCase):
@classmethod
def setUpTestData(cls):
boss = Employee.objects.create(name="Peter")
Employee.objects.create(name="Joe", boss=boss)
Employee.objects.create(name="Angela", boss=boss)
def test_traverse_nullable(self):
# Because we use select_related() for 'boss', it doesn't need to be
# prefetched, but we can still traverse it although it contains some nulls
with self.assertNumQueries(2):
qs = Employee.objects.select_related('boss').prefetch_related('boss__serfs')
co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else []
for e in qs]
qs2 = Employee.objects.select_related('boss')
co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2]
self.assertEqual(co_serfs, co_serfs2)
def test_prefetch_nullable(self):
# One for main employee, one for boss, one for serfs
with self.assertNumQueries(3):
qs = Employee.objects.prefetch_related('boss__serfs')
co_serfs = [list(e.boss.serfs.all()) if e.boss is not None else []
for e in qs]
qs2 = Employee.objects.all()
co_serfs2 = [list(e.boss.serfs.all()) if e.boss is not None else [] for e in qs2]
self.assertEqual(co_serfs, co_serfs2)
def test_in_bulk(self):
"""
In-bulk does correctly prefetch objects by not using .iterator()
directly.
"""
boss1 = Employee.objects.create(name="Peter")
boss2 = Employee.objects.create(name="Jack")
with self.assertNumQueries(2):
# Prefetch is done and it does not cause any errors.
bulk = Employee.objects.prefetch_related('serfs').in_bulk([boss1.pk, boss2.pk])
for b in bulk.values():
list(b.serfs.all())
class MultiDbTests(TestCase):
databases = {'default', 'other'}
def test_using_is_honored_m2m(self):
B = Book.objects.using('other')
A = Author.objects.using('other')
book1 = B.create(title="Poems")
book2 = B.create(title="Jane Eyre")
book3 = B.create(title="Wuthering Heights")
book4 = B.create(title="Sense and Sensibility")
author1 = A.create(name="Charlotte", first_book=book1)
author2 = A.create(name="Anne", first_book=book1)
author3 = A.create(name="Emily", first_book=book1)
author4 = A.create(name="Jane", first_book=book4)
book1.authors.add(author1, author2, author3)
book2.authors.add(author1)
book3.authors.add(author3)
book4.authors.add(author4)
# Forward
qs1 = B.prefetch_related('authors')
with self.assertNumQueries(2, using='other'):
books = "".join("%s (%s)\n" %
(book.title, ", ".join(a.name for a in book.authors.all()))
for book in qs1)
self.assertEqual(books,
"Poems (Charlotte, Anne, Emily)\n"
"Jane Eyre (Charlotte)\n"
"Wuthering Heights (Emily)\n"
"Sense and Sensibility (Jane)\n")
# Reverse
qs2 = A.prefetch_related('books')
with self.assertNumQueries(2, using='other'):
authors = "".join("%s: %s\n" %
(author.name, ", ".join(b.title for b in author.books.all()))
for author in qs2)
self.assertEqual(authors,
"Charlotte: Poems, Jane Eyre\n"
"Anne: Poems\n"
"Emily: Poems, Wuthering Heights\n"
"Jane: Sense and Sensibility\n")
def test_using_is_honored_fkey(self):
B = Book.objects.using('other')
A = Author.objects.using('other')
book1 = B.create(title="Poems")
book2 = B.create(title="Sense and Sensibility")
A.create(name="Charlotte Bronte", first_book=book1)
A.create(name="Jane Austen", first_book=book2)
# Forward
with self.assertNumQueries(2, using='other'):
books = ", ".join(a.first_book.title for a in A.prefetch_related('first_book'))
self.assertEqual("Poems, Sense and Sensibility", books)
# Reverse
with self.assertNumQueries(2, using='other'):
books = "".join("%s (%s)\n" %
(b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related('first_time_authors'))
self.assertEqual(books,
"Poems (Charlotte Bronte)\n"
"Sense and Sensibility (Jane Austen)\n")
def test_using_is_honored_inheritance(self):
B = BookWithYear.objects.using('other')
A = AuthorWithAge.objects.using('other')
book1 = B.create(title="Poems", published_year=2010)
B.create(title="More poems", published_year=2011)
A.create(name='Jane', first_book=book1, age=50)
A.create(name='Tom', first_book=book1, age=49)
# parent link
with self.assertNumQueries(2, using='other'):
authors = ", ".join(a.author.name for a in A.prefetch_related('author'))
self.assertEqual(authors, "Jane, Tom")
# child link
with self.assertNumQueries(2, using='other'):
ages = ", ".join(str(a.authorwithage.age) for a in A.prefetch_related('authorwithage'))
self.assertEqual(ages, "50, 49")
def test_using_is_honored_custom_qs(self):
B = Book.objects.using('other')
A = Author.objects.using('other')
book1 = B.create(title="Poems")
book2 = B.create(title="Sense and Sensibility")
A.create(name="Charlotte Bronte", first_book=book1)
A.create(name="Jane Austen", first_book=book2)
# Implicit hinting
with self.assertNumQueries(2, using='other'):
prefetch = Prefetch('first_time_authors', queryset=Author.objects.all())
books = "".join("%s (%s)\n" %
(b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch))
self.assertEqual(books,
"Poems (Charlotte Bronte)\n"
"Sense and Sensibility (Jane Austen)\n")
# Explicit using on the same db.
with self.assertNumQueries(2, using='other'):
prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('other'))
books = "".join("%s (%s)\n" %
(b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch))
self.assertEqual(books,
"Poems (Charlotte Bronte)\n"
"Sense and Sensibility (Jane Austen)\n")
# Explicit using on a different db.
with self.assertNumQueries(1, using='default'), self.assertNumQueries(1, using='other'):
prefetch = Prefetch('first_time_authors', queryset=Author.objects.using('default'))
books = "".join("%s (%s)\n" %
(b.title, ", ".join(a.name for a in b.first_time_authors.all()))
for b in B.prefetch_related(prefetch))
self.assertEqual(books,
"Poems ()\n"
"Sense and Sensibility ()\n")
class Ticket19607Tests(TestCase):
@classmethod
def setUpTestData(cls):
LessonEntry.objects.bulk_create(
LessonEntry(id=id_, name1=name1, name2=name2)
for id_, name1, name2 in [
(1, 'einfach', 'simple'),
(2, 'schwierig', 'difficult'),
]
)
WordEntry.objects.bulk_create(
WordEntry(id=id_, lesson_entry_id=lesson_entry_id, name=name)
for id_, lesson_entry_id, name in [
(1, 1, 'einfach'),
(2, 1, 'simple'),
(3, 2, 'schwierig'),
(4, 2, 'difficult'),
]
)
def test_bug(self):
list(WordEntry.objects.prefetch_related('lesson_entry', 'lesson_entry__wordentry_set'))
class Ticket21410Tests(TestCase):
@classmethod
def setUpTestData(cls):
book1 = Book.objects.create(title='Poems')
book2 = Book.objects.create(title='Jane Eyre')
book3 = Book.objects.create(title='Wuthering Heights')
book4 = Book.objects.create(title='Sense and Sensibility')
author1 = Author2.objects.create(name='Charlotte', first_book=book1)
author2 = Author2.objects.create(name='Anne', first_book=book1)
author3 = Author2.objects.create(name='Emily', first_book=book1)
author4 = Author2.objects.create(name='Jane', first_book=book4)
author1.favorite_books.add(book1, book2, book3)
author2.favorite_books.add(book1)
author3.favorite_books.add(book2)
author4.favorite_books.add(book3)
def test_bug(self):
list(Author2.objects.prefetch_related('first_book', 'favorite_books'))
class Ticket21760Tests(TestCase):
@classmethod
def setUpTestData(cls):
cls.rooms = []
for _ in range(3):
house = House.objects.create()
for _ in range(3):
cls.rooms.append(Room.objects.create(house=house))
# Set main_room for each house before creating the next one for
# databases where supports_nullable_unique_constraints is False.
house.main_room = cls.rooms[-3]
house.save()
def test_bug(self):
prefetcher = get_prefetcher(self.rooms[0], 'house', 'house')[0]
queryset = prefetcher.get_prefetch_queryset(list(Room.objects.all()))[0]
self.assertNotIn(' JOIN ', str(queryset.query))
class DirectPrefetchedObjectCacheReuseTests(TestCase):
"""
prefetch_related() reuses objects fetched in _prefetched_objects_cache.
When objects are prefetched and not stored as an instance attribute (often
intermediary relationships), they are saved to the
_prefetched_objects_cache attribute. prefetch_related() takes
_prefetched_objects_cache into account when determining whether an object
has been fetched[1] and retrieves results from it when it is populated [2].
[1]: #25546 (duplicate queries on nested Prefetch)
[2]: #27554 (queryset evaluation fails with a mix of nested and flattened
prefetches)
"""
@classmethod
def setUpTestData(cls):
cls.book1, cls.book2 = [
Book.objects.create(title='book1'),
Book.objects.create(title='book2'),
]
cls.author11, cls.author12, cls.author21 = [
Author.objects.create(first_book=cls.book1, name='Author11'),
Author.objects.create(first_book=cls.book1, name='Author12'),
Author.objects.create(first_book=cls.book2, name='Author21'),
]
cls.author1_address1, cls.author1_address2, cls.author2_address1 = [
AuthorAddress.objects.create(author=cls.author11, address='Happy place'),
AuthorAddress.objects.create(author=cls.author12, address='Haunted house'),
AuthorAddress.objects.create(author=cls.author21, address='Happy place'),
]
cls.bookwithyear1 = BookWithYear.objects.create(title='Poems', published_year=2010)
cls.bookreview1 = BookReview.objects.create(book=cls.bookwithyear1)
def test_detect_is_fetched(self):
"""
Nested prefetch_related() shouldn't trigger duplicate queries for the same
lookup.
"""
with self.assertNumQueries(3):
books = Book.objects.filter(
title__in=['book1', 'book2'],
).prefetch_related(
Prefetch(
'first_time_authors',
Author.objects.prefetch_related(
Prefetch(
'addresses',
AuthorAddress.objects.filter(address='Happy place'),
)
),
),
)
book1, book2 = list(books)
with self.assertNumQueries(0):
self.assertSequenceEqual(book1.first_time_authors.all(), [self.author11, self.author12])
self.assertSequenceEqual(book2.first_time_authors.all(), [self.author21])
self.assertSequenceEqual(book1.first_time_authors.all()[0].addresses.all(), [self.author1_address1])
self.assertSequenceEqual(book1.first_time_authors.all()[1].addresses.all(), [])
self.assertSequenceEqual(book2.first_time_authors.all()[0].addresses.all(), [self.author2_address1])
self.assertEqual(
list(book1.first_time_authors.all()), list(book1.first_time_authors.all().all())
)
self.assertEqual(
list(book2.first_time_authors.all()), list(book2.first_time_authors.all().all())
)
self.assertEqual(
list(book1.first_time_authors.all()[0].addresses.all()),
list(book1.first_time_authors.all()[0].addresses.all().all())
)
self.assertEqual(
list(book1.first_time_authors.all()[1].addresses.all()),
list(book1.first_time_authors.all()[1].addresses.all().all())
)
self.assertEqual(
list(book2.first_time_authors.all()[0].addresses.all()),
list(book2.first_time_authors.all()[0].addresses.all().all())
)
def test_detect_is_fetched_with_to_attr(self):
with self.assertNumQueries(3):
books = Book.objects.filter(
title__in=['book1', 'book2'],
).prefetch_related(
Prefetch(
'first_time_authors',
Author.objects.prefetch_related(
Prefetch(
'addresses',
AuthorAddress.objects.filter(address='Happy place'),
to_attr='happy_place',
)
),
to_attr='first_authors',
),
)
book1, book2 = list(books)
with self.assertNumQueries(0):
self.assertEqual(book1.first_authors, [self.author11, self.author12])
self.assertEqual(book2.first_authors, [self.author21])
self.assertEqual(book1.first_authors[0].happy_place, [self.author1_address1])
self.assertEqual(book1.first_authors[1].happy_place, [])
self.assertEqual(book2.first_authors[0].happy_place, [self.author2_address1])
def test_prefetch_reverse_foreign_key(self):
with self.assertNumQueries(2):
bookwithyear1, = BookWithYear.objects.prefetch_related('bookreview_set')
with self.assertNumQueries(0):
self.assertCountEqual(bookwithyear1.bookreview_set.all(), [self.bookreview1])
with self.assertNumQueries(0):
prefetch_related_objects([bookwithyear1], 'bookreview_set')
def test_add_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], 'bookreview_set')
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
new_review = BookReview.objects.create()
bookwithyear.bookreview_set.add(new_review)
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1, new_review])
def test_remove_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], 'bookreview_set')
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
bookwithyear.bookreview_set.remove(self.bookreview1)
self.assertCountEqual(bookwithyear.bookreview_set.all(), [])
class ReadPrefetchedObjectsCacheTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.book1 = Book.objects.create(title='Les confessions Volume I')
cls.book2 = Book.objects.create(title='Candide')
cls.author1 = AuthorWithAge.objects.create(name='Rousseau', first_book=cls.book1, age=70)
cls.author2 = AuthorWithAge.objects.create(name='Voltaire', first_book=cls.book2, age=65)
cls.book1.authors.add(cls.author1)
cls.book2.authors.add(cls.author2)
FavoriteAuthors.objects.create(author=cls.author1, likes_author=cls.author2)
def test_retrieves_results_from_prefetched_objects_cache(self):
"""
When intermediary results are prefetched without a destination
attribute, they are saved in the RelatedManager's cache
(_prefetched_objects_cache). prefetch_related() uses this cache
(#27554).
"""
authors = AuthorWithAge.objects.prefetch_related(
Prefetch(
'author',
queryset=Author.objects.prefetch_related(
# Results are saved in the RelatedManager's cache
# (_prefetched_objects_cache) and do not replace the
# RelatedManager on Author instances (favorite_authors)
Prefetch('favorite_authors__first_book'),
),
),
)
with self.assertNumQueries(4):
# AuthorWithAge -> Author -> FavoriteAuthors, Book
self.assertSequenceEqual(authors, [self.author1, self.author2])
| bsd-3-clause |
bunyip/django-authority | example/users/admin.py | 125 | from django.contrib.auth.admin import UserAdmin
from example.users.models import User
admin.site.register(User, UserAdmin)
| bsd-3-clause |
NunoEdgarGub1/figaro | Figaro/src/main/scala/com/cra/figaro/language/Inject.scala | 1302 | /*
* Inject.scala
* Element that converts a sequence of elements into an element over sequences.
*
* Created By: Avi Pfeffer (apfeffer@cra.com)
* Creation Date: Jan 1, 2009
*
* Copyright 2013 Avrom J. Pfeffer and Charles River Analytics, Inc.
* See http://www.cra.com or email figaro@cra.com for information.
*
* See http://www.github.com/p2t2/figaro for a copy of the software license.
*/
package com.cra.figaro.language
import com.cra.figaro.algorithm._
import com.cra.figaro.util._
/**
* Element that converts a sequence of elements into an element over sequences.
*
* @param xs The sequence of elements to be converted.
*/
class Inject[T](name: Name[List[T]], val xs: Seq[Element[T]], collection: ElementCollection)
extends Deterministic[List[T]](name, collection) with IfArgsCacheable[List[T]] {
/**
* The type over which the sequence is defined.
*/
type BaseType = T
def args = xs.toList
def generateValue() = (xs map (_.value)).toList
override def toString = "Inject(" + xs.mkString(", ") + ")"
}
object Inject {
/**
* Element that converts a sequence of elements into an element over sequences.
*/
def apply[T](xs: Element[T]*)(implicit name: Name[List[T]], collection: ElementCollection) =
new Inject(name, xs.toList, collection)
}
| bsd-3-clause |
gxxjjj/QuantEcon.py | examples/ar1_cycles.py | 1095 | """
Helps to illustrate the spectral density for AR(1) X' = phi X + epsilon
"""
import numpy as np
import matplotlib.pyplot as plt
phi = -0.8
times = list(range(16))
y1 = [phi**k / (1 - phi**2) for k in times]
y2 = [np.cos(np.pi * k) for k in times]
y3 = [a * b for a, b in zip(y1, y2)]
num_rows, num_cols = 3, 1
fig, axes = plt.subplots(num_rows, num_cols, figsize=(10, 8))
plt.subplots_adjust(hspace=0.25)
# Autocovariance when phi = -0.8
ax = axes[0]
ax.plot(times, y1, 'bo-', alpha=0.6, label=r'$\gamma(k)$')
ax.legend(loc='upper right')
ax.set_xlim(0, 15)
ax.set_yticks((-2, 0, 2))
ax.hlines(0, 0, 15, linestyle='--', alpha=0.5)
# Cycles at frequence pi
ax = axes[1]
ax.plot(times, y2, 'bo-', alpha=0.6, label=r'$\cos(\pi k)$')
ax.legend(loc='upper right')
ax.set_xlim(0, 15)
ax.set_yticks((-1, 0, 1))
ax.hlines(0, 0, 15, linestyle='--', alpha=0.5)
# Product
ax = axes[2]
ax.stem(times, y3, label=r'$\gamma(k) \cos(\pi k)$')
ax.legend(loc='upper right')
ax.set_xlim((0, 15))
ax.set_ylim(-3, 3)
ax.set_yticks((-1, 0, 1, 2, 3))
ax.hlines(0, 0, 15, linestyle='--', alpha=0.5)
plt.show()
| bsd-3-clause |
garvitr/sympy | sympy/polys/tests/test_ring_series.py | 21485 | from sympy.polys.domains import QQ, EX, RR
from sympy.polys.rings import ring
from sympy.polys.ring_series import (_invert_monoms, rs_integrate,
rs_trunc, rs_mul, rs_square, rs_pow, _has_constant_term, rs_hadamard_exp,
rs_series_from_list, rs_exp, rs_log, rs_newton, rs_series_inversion,
rs_compose_add, rs_asin, rs_atan, rs_atanh, rs_tan, rs_cot, rs_sin, rs_cos,
rs_cos_sin, rs_sinh, rs_cosh, rs_tanh, _tan1, rs_fun, rs_nth_root,
rs_LambertW, rs_series_reversion, rs_is_puiseux)
from sympy.utilities.pytest import raises
from sympy.core.compatibility import range
from sympy.core.symbol import symbols
from sympy.functions import (sin, cos, exp, tan, cot, atan, asin, atanh,
tanh, log, sqrt)
def is_close(a, b):
tol = 10**(-10)
assert abs(a - b) < tol
def test_ring_series1():
R, x = ring('x', QQ)
p = x**4 + 2*x**3 + 3*x + 4
assert _invert_monoms(p) == 4*x**4 + 3*x**3 + 2*x + 1
assert rs_hadamard_exp(p) == x**4/24 + x**3/3 + 3*x + 4
R, x = ring('x', QQ)
p = x**4 + 2*x**3 + 3*x + 4
assert rs_integrate(p, x) == x**5/5 + x**4/2 + 3*x**2/2 + 4*x
R, x, y = ring('x, y', QQ)
p = x**2*y**2 + x + 1
assert rs_integrate(p, x) == x**3*y**2/3 + x**2/2 + x
assert rs_integrate(p, y) == x**2*y**3/3 + x*y + y
def test_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = (y + t*x)**4
p1 = rs_trunc(p, x, 3)
assert p1 == y**4 + 4*y**3*t*x + 6*y**2*t**2*x**2
def test_mul_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = 1 + t*x + t*y
for i in range(2):
p = rs_mul(p, p, t, 3)
assert p == 6*x**2*t**2 + 12*x*y*t**2 + 6*y**2*t**2 + 4*x*t + 4*y*t + 1
p = 1 + t*x + t*y + t**2*x*y
p1 = rs_mul(p, p, t, 2)
assert p1 == 1 + 2*t*x + 2*t*y
R1, z = ring('z', QQ)
def test1(p):
p2 = rs_mul(p, z, x, 2)
raises(ValueError, lambda: test1(p))
p1 = 2 + 2*x + 3*x**2
p2 = 3 + x**2
assert rs_mul(p1, p2, x, 4) == 2*x**3 + 11*x**2 + 6*x + 6
def test_square_trunc():
R, x, y, t = ring('x, y, t', QQ)
p = (1 + t*x + t*y)*2
p1 = rs_mul(p, p, x, 3)
p2 = rs_square(p, x, 3)
assert p1 == p2
p = 1 + x + x**2 + x**3
assert rs_square(p, x, 4) == 4*x**3 + 3*x**2 + 2*x + 1
def test_pow_trunc():
R, x, y, z = ring('x, y, z', QQ)
p0 = y + x*z
p = p0**16
for xx in (x, y, z):
p1 = rs_trunc(p, xx, 8)
p2 = rs_pow(p0, 16, xx, 8)
assert p1 == p2
p = 1 + x
p1 = rs_pow(p, 3, x, 2)
assert p1 == 1 + 3*x
assert rs_pow(p, 0, x, 2) == 1
assert rs_pow(p, -2, x, 2) == 1 - 2*x
p = x + y
assert rs_pow(p, 3, y, 3) == x**3 + 3*x**2*y + 3*x*y**2
def test_has_constant_term():
R, x, y, z = ring('x, y, z', QQ)
p = y + x*z
assert _has_constant_term(p, x)
p = x + x**4
assert not _has_constant_term(p, x)
p = 1 + x + x**4
assert _has_constant_term(p, x)
p = x + y + x*z
def test_inversion():
R, x = ring('x', QQ)
p = 2 + x + 2*x**2
n = 5
p1 = rs_series_inversion(p, x, n)
assert rs_trunc(p*p1, x, n) == 1
R, x, y = ring('x, y', QQ)
p = 2 + x + 2*x**2 + y*x + x**2*y
p1 = rs_series_inversion(p, x, n)
assert rs_trunc(p*p1, x, n) == 1
R, x, y = ring('x, y', QQ)
p = 1 + x + y
def test2(p):
p1 = rs_series_inversion(p, x, 4)
raises(NotImplementedError, lambda: test2(p))
def test_series_reversion():
R, x, y = ring('x, y', QQ)
p = rs_tan(x, x, 10)
r1 = rs_series_reversion(p, x, 8, y)
r2 = rs_atan(y, y, 8)
assert rs_series_reversion(p, x, 8, y) == rs_atan(y, y, 8)
p = rs_sin(x, x, 10)
assert rs_series_reversion(p, x, 8, y) == 5*y**7/112 + 3*y**5/40 + \
y**3/6 + y
def test_series_from_list():
R, x = ring('x', QQ)
p = 1 + 2*x + x**2 + 3*x**3
c = [1, 2, 0, 4, 4]
r = rs_series_from_list(p, c, x, 5)
pc = R.from_list(list(reversed(c)))
r1 = rs_trunc(pc.compose(x, p), x, 5)
assert r == r1
R, x, y = ring('x, y', QQ)
c = [1, 3, 5, 7]
p1 = rs_series_from_list(x + y, c, x, 3, concur=0)
p2 = rs_trunc((1 + 3*(x+y) + 5*(x+y)**2 + 7*(x+y)**3), x, 3)
assert p1 == p2
R, x = ring('x', QQ)
h = 25
p = rs_exp(x, x, h) - 1
p1 = rs_series_from_list(p, c, x, h)
p2 = 0
for i, cx in enumerate(c):
p2 += cx*rs_pow(p, i, x, h)
assert p1 == p2
def test_log():
R, x = ring('x', QQ)
p = 1 + x
p1 = rs_log(p, x, 4)
assert p1 == x - x**2/2 + x**3/3
p = 1 + x +2*x**2/3
p1 = rs_log(p, x, 9)
assert p1 == -17*x**8/648 + 13*x**7/189 - 11*x**6/162 - x**5/45 + \
7*x**4/36 - x**3/3 + x**2/6 + x
p2 = rs_series_inversion(p, x, 9)
p3 = rs_log(p2, x, 9)
assert p3 == -p1
R, x, y = ring('x, y', QQ)
p = 1 + x + 2*y*x**2
p1 = rs_log(p, x, 6)
assert p1 == (4*x**5*y**2 - 2*x**5*y - 2*x**4*y**2 + x**5/5 + 2*x**4*y -
x**4/4 - 2*x**3*y + x**3/3 + 2*x**2*y - x**2/2 + x)
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_log(x + a, x, 5) == -EX(1/(4*a**4))*x**4 + EX(1/(3*a**3))*x**3 \
- EX(1/(2*a**2))*x**2 + EX(1/a)*x + EX(log(a))
assert rs_log(x + x**2*y + a, x, 4) == -EX(a**(-2))*x**3*y + \
EX(1/(3*a**3))*x**3 + EX(1/a)*x**2*y - EX(1/(2*a**2))*x**2 + \
EX(1/a)*x + EX(log(a))
p = x + x**2 + 3
assert rs_log(p, x, 10).compose(x, 5) == EX(log(3) + 19281291595/9920232)
def test_exp():
R, x = ring('x', QQ)
p = x + x**4
for h in [10, 30]:
q = rs_series_inversion(1 + p, x, h) - 1
p1 = rs_exp(q, x, h)
q1 = rs_log(p1, x, h)
assert q1 == q
p1 = rs_exp(p, x, 30)
assert p1.coeff(x**29) == QQ(74274246775059676726972369, 353670479749588078181744640000)
prec = 21
p = rs_log(1 + x, x, prec)
p1 = rs_exp(p, x, prec)
assert p1 == x + 1
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[exp(a), a])
assert rs_exp(x + a, x, 5) == exp(a)*x**4/24 + exp(a)*x**3/6 + \
exp(a)*x**2/2 + exp(a)*x + exp(a)
assert rs_exp(x + x**2*y + a, x, 5) == exp(a)*x**4*y**2/2 + \
exp(a)*x**4*y/2 + exp(a)*x**4/24 + exp(a)*x**3*y + \
exp(a)*x**3/6 + exp(a)*x**2*y + exp(a)*x**2/2 + exp(a)*x + exp(a)
R, x, y = ring('x, y', EX)
assert rs_exp(x + a, x, 5) == EX(exp(a)/24)*x**4 + EX(exp(a)/6)*x**3 + \
EX(exp(a)/2)*x**2 + EX(exp(a))*x + EX(exp(a))
assert rs_exp(x + x**2*y + a, x, 5) == EX(exp(a)/2)*x**4*y**2 + \
EX(exp(a)/2)*x**4*y + EX(exp(a)/24)*x**4 + EX(exp(a))*x**3*y + \
EX(exp(a)/6)*x**3 + EX(exp(a))*x**2*y + EX(exp(a)/2)*x**2 + \
EX(exp(a))*x + EX(exp(a))
def test_newton():
R, x = ring('x', QQ)
p = x**2 - 2
r = rs_newton(p, x, 4)
f = [1, 0, -2]
assert r == 8*x**4 + 4*x**2 + 2
def test_compose_add():
R, x = ring('x', QQ)
p1 = x**3 - 1
p2 = x**2 - 2
assert rs_compose_add(p1, p2) == x**6 - 6*x**4 - 2*x**3 + 12*x**2 - 12*x - 7
def test_fun():
R, x, y = ring('x, y', QQ)
p = x*y + x**2*y**3 + x**5*y
assert rs_fun(p, rs_tan, x, 10) == rs_tan(p, x, 10)
assert rs_fun(p, _tan1, x, 10) == _tan1(p, x, 10)
def test_nth_root():
R, x, y = ring('x, y', QQ)
r1 = rs_nth_root(1 + x**2*y, 4, x, 10)
assert rs_nth_root(1 + x**2*y, 4, x, 10) == -77*x**8*y**4/2048 + \
7*x**6*y**3/128 - 3*x**4*y**2/32 + x**2*y/4 + 1
assert rs_nth_root(1 + x*y + x**2*y**3, 3, x, 5) == -x**4*y**6/9 + \
5*x**4*y**5/27 - 10*x**4*y**4/243 - 2*x**3*y**4/9 + 5*x**3*y**3/81 + \
x**2*y**3/3 - x**2*y**2/9 + x*y/3 + 1
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_nth_root(x + a, 3, x, 4) == EX(5/(81*a**QQ(8, 3)))*x**3 - \
EX(1/(9*a**QQ(5, 3)))*x**2 + EX(1/(3*a**QQ(2, 3)))*x + EX(a**QQ(1, 3))
assert rs_nth_root(x**QQ(2, 3) + x**2*y + 5, 2, x, 3) == -EX(sqrt(5)/100)*\
x**QQ(8, 3)*y - EX(sqrt(5)/16000)*x**QQ(8, 3) + EX(sqrt(5)/10)*x**2*y + \
EX(sqrt(5)/2000)*x**2 - EX(sqrt(5)/200)*x**QQ(4, 3) + \
EX(sqrt(5)/10)*x**QQ(2, 3) + EX(sqrt(5))
def test_atan():
R, x, y = ring('x, y', QQ)
assert rs_atan(x, x, 9) == -x**7/7 + x**5/5 - x**3/3 + x
assert rs_atan(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 - x**8*y**9 + \
2*x**7*y**9 - x**7*y**7/7 - x**6*y**9/3 + x**6*y**7 - x**5*y**7 + \
x**5*y**5/5 - x**4*y**5 - x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_atan(x + a, x, 5) == -EX((a**3 - a)/(a**8 + 4*a**6 + 6*a**4 + \
4*a**2 + 1))*x**4 + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + \
9*a**2 + 3))*x**3 - EX(a/(a**4 + 2*a**2 + 1))*x**2 + \
EX(1/(a**2 + 1))*x + EX(atan(a))
assert rs_atan(x + x**2*y + a, x, 4) == -EX(2*a/(a**4 + 2*a**2 + 1)) \
*x**3*y + EX((3*a**2 - 1)/(3*a**6 + 9*a**4 + 9*a**2 + 3))*x**3 + \
EX(1/(a**2 + 1))*x**2*y - EX(a/(a**4 + 2*a**2 + 1))*x**2 + EX(1/(a**2 \
+ 1))*x + EX(atan(a))
def test_asin():
R, x, y = ring('x, y', QQ)
assert rs_asin(x + x*y, x, 5) == x**3*y**3/6 + x**3*y**2/2 + x**3*y/2 + \
x**3/6 + x*y + x
assert rs_asin(x*y + x**2*y**3, x, 6) == x**5*y**7/2 + 3*x**5*y**5/40 + \
x**4*y**5/2 + x**3*y**3/6 + x**2*y**3 + x*y
def test_tan():
R, x, y = ring('x, y', QQ)
assert rs_tan(x, x, 9) == \
x + x**3/3 + 2*x**5/15 + 17*x**7/315
assert rs_tan(x*y + x**2*y**3, x, 9) == 4*x**8*y**11/3 + 17*x**8*y**9/45 + \
4*x**7*y**9/3 + 17*x**7*y**7/315 + x**6*y**9/3 + 2*x**6*y**7/3 + \
x**5*y**7 + 2*x**5*y**5/15 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[tan(a), a])
assert rs_tan(x + a, x, 5) == (tan(a)**5 + 5*tan(a)**3/3 + \
2*tan(a)/3)*x**4 + (tan(a)**4 + 4*tan(a)**2/3 + 1/3)*x**3 + \
(tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
assert rs_tan(x + x**2*y + a, x, 4) == (2*tan(a)**3 + 2*tan(a))*x**3*y + \
(tan(a)**4 + 4/3*tan(a)**2 + 1/3)*x**3 + (tan(a)**2 + 1)*x**2*y + \
(tan(a)**3 + tan(a))*x**2 + (tan(a)**2 + 1)*x + tan(a)
R, x, y = ring('x, y', EX)
assert rs_tan(x + a, x, 5) == EX(tan(a)**5 + 5*tan(a)**3/3 + \
2*tan(a)/3)*x**4 + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
EX(tan(a)**3 + tan(a))*x**2 + EX(tan(a)**2 + 1)*x + EX(tan(a))
assert rs_tan(x + x**2*y + a, x, 4) == EX(2*tan(a)**3 + \
2*tan(a))*x**3*y + EX(tan(a)**4 + 4*tan(a)**2/3 + EX(1)/3)*x**3 + \
EX(tan(a)**2 + 1)*x**2*y + EX(tan(a)**3 + tan(a))*x**2 + \
EX(tan(a)**2 + 1)*x + EX(tan(a))
p = x + x**2 + 5
assert rs_atan(p, x, 10).compose(x, 10) == EX(atan(5) + 67701870330562640/ \
668083460499)
def test_cot():
R, x, y = ring('x, y', QQ)
assert rs_cot(x**6 + x**7, x, 8) == x**-6 - x**-5 + x**-4 - x**-3 + \
x**-2 - x**-1 + 1 - x + x**2 - x**3 + x**4 - x**5 + 2*x**6/3 - 4*x**7/3
assert rs_cot(x + x**2*y, x, 5) == -x**4*y**5 - x**4*y/15 + x**3*y**4 - \
x**3/45 - x**2*y**3 - x**2*y/3 + x*y**2 - x/3 - y + x**-1
def test_sin():
R, x, y = ring('x, y', QQ)
assert rs_sin(x, x, 9) == \
x - x**3/6 + x**5/120 - x**7/5040
assert rs_sin(x*y + x**2*y**3, x, 9) == x**8*y**11/12 - \
x**8*y**9/720 + x**7*y**9/12 - x**7*y**7/5040 - x**6*y**9/6 + \
x**6*y**7/24 - x**5*y**7/2 + x**5*y**5/120 - x**4*y**5/2 - \
x**3*y**3/6 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
assert rs_sin(x + a, x, 5) == sin(a)*x**4/24 - cos(a)*x**3/6 - \
sin(a)*x**2/2 + cos(a)*x + sin(a)
assert rs_sin(x + x**2*y + a, x, 5) == -sin(a)*x**4*y**2/2 - \
cos(a)*x**4*y/2 + sin(a)*x**4/24 - sin(a)*x**3*y - cos(a)*x**3/6 + \
cos(a)*x**2*y - sin(a)*x**2/2 + cos(a)*x + sin(a)
R, x, y = ring('x, y', EX)
assert rs_sin(x + a, x, 5) == EX(sin(a)/24)*x**4 - EX(cos(a)/6)*x**3 - \
EX(sin(a)/2)*x**2 + EX(cos(a))*x + EX(sin(a))
assert rs_sin(x + x**2*y + a, x, 5) == -EX(sin(a)/2)*x**4*y**2 - \
EX(cos(a)/2)*x**4*y + EX(sin(a)/24)*x**4 - EX(sin(a))*x**3*y - \
EX(cos(a)/6)*x**3 + EX(cos(a))*x**2*y - EX(sin(a)/2)*x**2 + \
EX(cos(a))*x + EX(sin(a))
def test_cos():
R, x, y = ring('x, y', QQ)
assert rs_cos(x, x, 9) == \
x**8/40320 - x**6/720 + x**4/24 - x**2/2 + 1
assert rs_cos(x*y + x**2*y**3, x, 9) == x**8*y**12/24 - \
x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 - \
x**7*y**8/120 + x**6*y**8/4 - x**6*y**6/720 + x**5*y**6/6 - \
x**4*y**6/2 + x**4*y**4/24 - x**3*y**4 - x**2*y**2/2 + 1
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', QQ[sin(a), cos(a), a])
assert rs_cos(x + a, x, 5) == cos(a)*x**4/24 + sin(a)*x**3/6 - \
cos(a)*x**2/2 - sin(a)*x + cos(a)
assert rs_cos(x + x**2*y + a, x, 5) == -cos(a)*x**4*y**2/2 + \
sin(a)*x**4*y/2 + cos(a)*x**4/24 - cos(a)*x**3*y + sin(a)*x**3/6 - \
sin(a)*x**2*y - cos(a)*x**2/2 - sin(a)*x + cos(a)
R, x, y = ring('x, y', EX)
assert rs_cos(x + a, x, 5) == EX(cos(a)/24)*x**4 + EX(sin(a)/6)*x**3 - \
EX(cos(a)/2)*x**2 - EX(sin(a))*x + EX(cos(a))
assert rs_cos(x + x**2*y + a, x, 5) == -EX(cos(a)/2)*x**4*y**2 + \
EX(sin(a)/2)*x**4*y + EX(cos(a)/24)*x**4 - EX(cos(a))*x**3*y + \
EX(sin(a)/6)*x**3 - EX(sin(a))*x**2*y - EX(cos(a)/2)*x**2 - \
EX(sin(a))*x + EX(cos(a))
def test_cos_sin():
R, x, y = ring('x, y', QQ)
cos, sin = rs_cos_sin(x, x, 9)
assert cos == rs_cos(x, x, 9)
assert sin == rs_sin(x, x, 9)
cos, sin = rs_cos_sin(x + x*y, x, 5)
assert cos == rs_cos(x + x*y, x, 5)
assert sin == rs_sin(x + x*y, x, 5)
def test_atanh():
R, x, y = ring('x, y', QQ)
assert rs_atanh(x, x, 9) == x**7/7 + x**5/5 + x**3/3 + x
assert rs_atanh(x*y + x**2*y**3, x, 9) == 2*x**8*y**11 + x**8*y**9 + \
2*x**7*y**9 + x**7*y**7/7 + x**6*y**9/3 + x**6*y**7 + x**5*y**7 + \
x**5*y**5/5 + x**4*y**5 + x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_atanh(x + a, x, 5) == EX((a**3 + a)/(a**8 - 4*a**6 + 6*a**4 - \
4*a**2 + 1))*x**4 - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + \
9*a**2 - 3))*x**3 + EX(a/(a**4 - 2*a**2 + 1))*x**2 - EX(1/(a**2 - \
1))*x + EX(atanh(a))
assert rs_atanh(x + x**2*y + a, x, 4) == EX(2*a/(a**4 - 2*a**2 + \
1))*x**3*y - EX((3*a**2 + 1)/(3*a**6 - 9*a**4 + 9*a**2 - 3))*x**3 - \
EX(1/(a**2 - 1))*x**2*y + EX(a/(a**4 - 2*a**2 + 1))*x**2 - \
EX(1/(a**2 - 1))*x + EX(atanh(a))
p = x + x**2 + 5
assert rs_atanh(p, x, 10).compose(x, 10) == EX(-733442653682135/5079158784 \
+ atanh(5))
def test_sinh():
R, x, y = ring('x, y', QQ)
assert rs_sinh(x, x, 9) == x**7/5040 + x**5/120 + x**3/6 + x
assert rs_sinh(x*y + x**2*y**3, x, 9) == x**8*y**11/12 + \
x**8*y**9/720 + x**7*y**9/12 + x**7*y**7/5040 + x**6*y**9/6 + \
x**6*y**7/24 + x**5*y**7/2 + x**5*y**5/120 + x**4*y**5/2 + \
x**3*y**3/6 + x**2*y**3 + x*y
def test_cosh():
R, x, y = ring('x, y', QQ)
assert rs_cosh(x, x, 9) == x**8/40320 + x**6/720 + x**4/24 + \
x**2/2 + 1
assert rs_cosh(x*y + x**2*y**3, x, 9) == x**8*y**12/24 + \
x**8*y**10/48 + x**8*y**8/40320 + x**7*y**10/6 + \
x**7*y**8/120 + x**6*y**8/4 + x**6*y**6/720 + x**5*y**6/6 + \
x**4*y**6/2 + x**4*y**4/24 + x**3*y**4 + x**2*y**2/2 + 1
def test_tanh():
R, x, y = ring('x, y', QQ)
assert rs_tanh(x, x, 9) == -17*x**7/315 + 2*x**5/15 - x**3/3 + x
assert rs_tanh(x*y + x**2*y**3 , x, 9) == 4*x**8*y**11/3 - \
17*x**8*y**9/45 + 4*x**7*y**9/3 - 17*x**7*y**7/315 - x**6*y**9/3 + \
2*x**6*y**7/3 - x**5*y**7 + 2*x**5*y**5/15 - x**4*y**5 - \
x**3*y**3/3 + x**2*y**3 + x*y
# Constant term in series
a = symbols('a')
R, x, y = ring('x, y', EX)
assert rs_tanh(x + a, x, 5) == EX(tanh(a)**5 - 5*tanh(a)**3/3 + \
2*tanh(a)/3)*x**4 + EX(-tanh(a)**4 + 4*tanh(a)**2/3 - QQ(1, 3))*x**3 + \
EX(tanh(a)**3 - tanh(a))*x**2 + EX(-tanh(a)**2 + 1)*x + EX(tanh(a))
p = rs_tanh(x + x**2*y + a, x, 4)
assert (p.compose(x, 10)).compose(y, 5) == EX(-1000*tanh(a)**4 + \
10100*tanh(a)**3 + 2470*tanh(a)**2/3 - 10099*tanh(a) + QQ(530, 3))
def test_RR():
rs_funcs = [rs_sin, rs_cos, rs_tan, rs_cot, rs_atan, rs_tanh]
sympy_funcs = [sin, cos, tan, cot, atan, tanh]
R, x, y = ring('x, y', RR)
a = symbols('a')
for rs_func, sympy_func in zip(rs_funcs, sympy_funcs):
p = rs_func(2 + x, x, 5).compose(x, 5)
q = sympy_func(2 + a).series(a, 0, 5).removeO()
is_close(p.as_expr(), q.subs(a, 5).n())
p = rs_nth_root(2 + x, 5, x, 5).compose(x, 5)
q = ((2 + a)**QQ(1, 5)).series(a, 0, 5).removeO()
is_close(p.as_expr(), q.subs(a, 5).n())
def test_is_regular():
R, x, y = ring('x, y', QQ)
p = 1 + 2*x + x**2 + 3*x**3
assert not rs_is_puiseux(p, x)
p = x + x**QQ(1,5)*y
assert rs_is_puiseux(p, x)
assert not rs_is_puiseux(p, y)
p = x + x**2*y**QQ(1,5)*y
assert not rs_is_puiseux(p, x)
def test_puiseux():
R, x, y = ring('x, y', QQ)
p = x**QQ(2,5) + x**QQ(2,3) + x
r = rs_series_inversion(p, x, 1)
r1 = -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + x**QQ(2,3) + \
2*x**QQ(7,15) - x**QQ(2,5) - x**QQ(1,5) + x**QQ(2,15) - x**QQ(-2,15) \
+ x**QQ(-2,5)
assert r == r1
r = rs_nth_root(1 + p, 3, x, 1)
assert r == -x**QQ(4,5)/9 + x**QQ(2,3)/3 + x**QQ(2,5)/3 + 1
r = rs_log(1 + p, x, 1)
assert r == -x**QQ(4,5)/2 + x**QQ(2,3) + x**QQ(2,5)
r = rs_LambertW(p, x, 1)
assert r == -x**QQ(4,5) + x**QQ(2,3) + x**QQ(2,5)
r = rs_exp(p, x, 1)
assert r == x**QQ(4,5)/2 + x**QQ(2,3) + x**QQ(2,5) + 1
p1 = x + x**QQ(1,5)*y
r = rs_exp(p1, x, 1)
assert r == x**QQ(4,5)*y**4/24 + x**QQ(3,5)*y**3/6 + x**QQ(2,5)*y**2/2 + \
x**QQ(1,5)*y + 1
r = rs_atan(p, x, 2)
assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \
x + x**QQ(2,3) + x**QQ(2,5)
r = rs_atan(p1, x, 2)
assert r == x**QQ(9,5)*y**9/9 + x**QQ(9,5)*y**4 - x**QQ(7,5)*y**7/7 - \
x**QQ(7,5)*y**2 + x*y**5/5 + x - x**QQ(3,5)*y**3/3 + x**QQ(1,5)*y
r = rs_asin(p, x, 2)
assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_tan(p, x, 2)
assert r == x**QQ(9,5) + x**QQ(26,15) + x**QQ(22,15) + x**QQ(6,5)/3 + \
x + x**QQ(2,3) + x**QQ(2,5)
r = rs_cot(p, x, 1)
assert r == -x**QQ(14,15) + x**QQ(4,5) - 3*x**QQ(11,15) + \
2*x**QQ(2,3)/3 + 2*x**QQ(7,15) - 4*x**QQ(2,5)/3 - x**QQ(1,5) + \
x**QQ(2,15) - x**QQ(-2,15) + x**QQ(-2,5)
r = rs_sin(p, x, 2)
assert r == -x**QQ(9,5)/2 - x**QQ(26,15)/2 - x**QQ(22,15)/2 - \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_cos(p, x, 2)
assert r == x**QQ(28,15)/6 - x**QQ(5,3) + x**QQ(8,5)/24 - x**QQ(7,5) - \
x**QQ(4,3)/2 - x**QQ(16,15) - x**QQ(4,5)/2 + 1
r = rs_cos_sin(p, x, 2)
assert r[0] == x**QQ(28,15)/6 - x**QQ(5,3) + x**QQ(8,5)/24 - x**QQ(7,5) - \
x**QQ(4,3)/2 - x**QQ(16,15) - x**QQ(4,5)/2 + 1
assert r[1] == -x**QQ(9,5)/2 - x**QQ(26,15)/2 - x**QQ(22,15)/2 - \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_atanh(p, x, 2)
assert r == x**QQ(9,5) + x**QQ(26,15) + x**QQ(22,15) + x**QQ(6,5)/3 + x + \
x**QQ(2,3) + x**QQ(2,5)
r = rs_sinh(p, x, 2)
assert r == x**QQ(9,5)/2 + x**QQ(26,15)/2 + x**QQ(22,15)/2 + \
x**QQ(6,5)/6 + x + x**QQ(2,3) + x**QQ(2,5)
r = rs_cosh(p, x, 2)
assert r == x**QQ(28,15)/6 + x**QQ(5,3) + x**QQ(8,5)/24 + x**QQ(7,5) + \
x**QQ(4,3)/2 + x**QQ(16,15) + x**QQ(4,5)/2 + 1
r = rs_tanh(p, x, 2)
assert r == -x**QQ(9,5) - x**QQ(26,15) - x**QQ(22,15) - x**QQ(6,5)/3 + \
x + x**QQ(2,3) + x**QQ(2,5)
def test1():
R, x = ring('x', QQ)
r = rs_sin(x, x, 15)*x**(-5)
assert r == x**8/6227020800 - x**6/39916800 + x**4/362880 - x**2/5040 + \
QQ(1,120) - x**-2/6 + x**-4
p = rs_sin(x, x, 10)
r = rs_nth_root(p, 2, x, 10)
assert r == -67*x**QQ(17,2)/29030400 - x**QQ(13,2)/24192 + \
x**QQ(9,2)/1440 - x**QQ(5,2)/12 + x**QQ(1,2)
p = rs_sin(x, x, 10)
r = rs_nth_root(p, 7, x, 10)
r = rs_pow(r, 5, x, 10)
assert r == -97*x**QQ(61,7)/124467840 - x**QQ(47,7)/16464 + \
11*x**QQ(33,7)/3528 - 5*x**QQ(19,7)/42 + x**QQ(5,7)
r = rs_exp(x**QQ(1,2), x, 10)
assert r == x**QQ(19,2)/121645100408832000 + x**9/6402373705728000 + \
x**QQ(17,2)/355687428096000 + x**8/20922789888000 + \
x**QQ(15,2)/1307674368000 + x**7/87178291200 + \
x**QQ(13,2)/6227020800 + x**6/479001600 + x**QQ(11,2)/39916800 + \
x**5/3628800 + x**QQ(9,2)/362880 + x**4/40320 + x**QQ(7,2)/5040 + \
x**3/720 + x**QQ(5,2)/120 + x**2/24 + x**QQ(3,2)/6 + x/2 + \
x**QQ(1,2) + 1
def test_puiseux2():
R, y = ring('y', QQ)
S, x = ring('x', R)
p = x + x**QQ(1,5)*y
r = rs_atan(p, x, 3)
assert r == (y**13/13 + y**8 + 2*y**3)*x**QQ(13,5) - (y**11/11 + y**6 +
y)*x**QQ(11,5) + (y**9/9 + y**4)*x**QQ(9,5) - (y**7/7 +
y**2)*x**QQ(7,5) + (y**5/5 + 1)*x - y**3*x**QQ(3,5)/3 + y*x**QQ(1,5)
| bsd-3-clause |
felixbuenemann/sentry | api-docs/generator.py | 6419 | import os
import zlib
import json
import click
import urlparse
import logging
from datetime import datetime
from subprocess import Popen, PIPE
from contextlib import contextmanager
HERE = os.path.abspath(os.path.dirname(__file__))
SENTRY_CONFIG = os.path.join(HERE, 'sentry.conf.py')
# No sentry or django imports before that point
from sentry.utils import runner
runner.configure(config_path=SENTRY_CONFIG, skip_backend_validation=True)
from django.conf import settings
# Fair game from here
from django.core.management import call_command
from sentry.utils.apidocs import Runner, MockUtils, iter_scenarios, \
iter_endpoints, get_sections
OUTPUT_PATH = os.path.join(HERE, 'cache')
HOST = urlparse.urlparse(settings.SENTRY_URL_PREFIX).netloc
# We don't care about you, go away
_logger = logging.getLogger('sentry.events')
_logger.disabled = True
def color_for_string(s):
colors = ('red', 'green', 'yellow', 'blue', 'cyan', 'magenta')
return colors[zlib.crc32(s) % len(colors)]
def report(category, message, fg=None):
if fg is None:
fg = color_for_string(category)
click.echo('[%s] %s: %s' % (
str(datetime.utcnow()).split('.')[0],
click.style(category, fg=fg),
message
))
def launch_redis():
report('redis', 'Launching redis server')
cl = Popen(['redis-server', '-'], stdin=PIPE, stdout=open(os.devnull, 'r+'))
cl.stdin.write('''
port %(port)s
databases %(databases)d
save ""
''' % {
'port': str(settings.SENTRY_APIDOCS_REDIS_PORT),
'databases': 4,
})
cl.stdin.flush()
cl.stdin.close()
return cl
def spawn_sentry():
report('sentry', 'Launching sentry server')
cl = Popen(['sentry', '--config=' + SENTRY_CONFIG, 'runserver',
'-v', '0', '--noreload', '--nothreading',
'--no-watchers', '--traceback',
'127.0.0.1:%s' % settings.SENTRY_APIDOCS_WEB_PORT])
return cl
@contextmanager
def management_connection():
from sqlite3 import connect
cfg = settings.DATABASES['default']
con = connect(cfg['NAME'])
try:
con.cursor()
yield con
finally:
con.close()
def init_db():
drop_db()
report('db', 'Migrating database (this can time some time)')
call_command('syncdb', migrate=True, interactive=False,
traceback=True, verbosity=0)
def drop_db():
report('db', 'Dropping database')
try:
os.remove(settings.DATABASES['default']['NAME'])
except (OSError, IOError):
pass
class SentryBox(object):
def __init__(self):
self.redis = None
self.sentry = None
self.task_runner = None
def __enter__(self):
self.redis = launch_redis()
self.sentry = spawn_sentry()
init_db()
return self
def __exit__(self, exc_type, exc_value, tb):
drop_db()
if self.redis is not None:
report('redis', 'Stopping redis server')
self.redis.kill()
self.redis.wait()
if self.sentry is not None:
report('sentry', 'Shutting down sentry server')
self.sentry.kill()
self.sentry.wait()
def dump_json(path, data):
path = os.path.join(OUTPUT_PATH, path)
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass
with open(path, 'w') as f:
for line in json.dumps(data, indent=2, sort_keys=True).splitlines():
f.write(line.rstrip() + '\n')
def run_scenario(vars, scenario_ident, func):
runner = Runner(scenario_ident, func, **vars)
report('scenario', 'Running scenario "%s"' % scenario_ident)
func(runner)
dump_json('scenarios/%s.json' % scenario_ident, runner.to_json())
@click.command()
@click.option('--output-path', type=click.Path())
def cli(output_path):
"""API docs dummy generator."""
global OUTPUT_PATH
if output_path is not None:
OUTPUT_PATH = os.path.abspath(output_path)
with SentryBox():
utils = MockUtils()
report('org', 'Creating user and organization')
user = utils.create_user('john@interstellar.invalid')
org = utils.create_org('The Interstellar Jurisdiction',
owner=user)
api_key = utils.create_api_key(org)
report('org', 'Creating team')
team = utils.create_team('Powerful Abolitionist',
org=org)
projects = []
for project_name in 'Pump Station', 'Prime Mover':
report('project', 'Creating project "%s"' % project_name)
project = utils.create_project(project_name, team=team, org=org)
release = utils.create_release(project=project, user=user)
report('event', 'Creating event for "%s"' % project_name)
event1 = utils.create_event(project=project, release=release,
platform='python')
event2 = utils.create_event(project=project, release=release,
platform='java')
projects.append({
'project': project,
'release': release,
'events': [event1, event2],
})
vars = {
'org': org,
'api_key': api_key,
'me': user,
'api_key': api_key,
'teams': [{
'team': team,
'projects': projects,
}],
}
for scenario_ident, func in iter_scenarios():
run_scenario(vars, scenario_ident, func)
section_mapping = {}
report('docs', 'Exporting endpoint documentation')
for endpoint in iter_endpoints():
report('endpoint', 'Exporting docs for "%s"' %
endpoint['endpoint_name'])
section_mapping.setdefault(endpoint['section'], []) \
.append((endpoint['endpoint_name'],
endpoint['title']))
dump_json('endpoints/%s.json' % endpoint['endpoint_name'], endpoint)
report('docs', 'Exporting sections')
dump_json('sections.json', {
'sections': dict((section, {
'title': title,
'entries': dict(section_mapping.get(section, ())),
}) for section, title in get_sections().iteritems())
})
if __name__ == '__main__':
cli()
| bsd-3-clause |
mou4e/zirconium | cc/test/fake_proxy.cc | 1078 | // Copyright 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 "cc/test/fake_proxy.h"
namespace cc {
void FakeProxy::SetLayerTreeHost(LayerTreeHost* host) {
layer_tree_host_ = host;
}
bool FakeProxy::IsStarted() const { return true; }
bool FakeProxy::CommitToActiveTree() const {
return false;
}
const RendererCapabilities& FakeProxy::GetRendererCapabilities() const {
return capabilities_;
}
RendererCapabilities& FakeProxy::GetRendererCapabilities() {
return capabilities_;
}
bool FakeProxy::BeginMainFrameRequested() const { return false; }
bool FakeProxy::CommitRequested() const { return false; }
size_t FakeProxy::MaxPartialTextureUpdates() const {
return max_partial_texture_updates_;
}
void FakeProxy::SetMaxPartialTextureUpdates(size_t max) {
max_partial_texture_updates_ = max;
}
bool FakeProxy::SupportsImplScrolling() const { return false; }
bool FakeProxy::MainFrameWillHappenForTesting() {
return false;
}
} // namespace cc
| bsd-3-clause |
bspeterson/dbal | tests/Doctrine/Tests/DBAL/Sharding/PoolingShardConnectionTest.php | 12298 | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Tests\DBAL\Sharding;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser;
class PoolingShardConnectionTest extends \PHPUnit_Framework_TestCase
{
public function testConnect()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
array('id' => 2, 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertFalse($conn->isConnected(0));
$conn->connect(0);
$this->assertEquals(1, $conn->fetchColumn('SELECT 1'));
$this->assertTrue($conn->isConnected(0));
$this->assertFalse($conn->isConnected(1));
$conn->connect(1);
$this->assertEquals(1, $conn->fetchColumn('SELECT 1'));
$this->assertTrue($conn->isConnected(1));
$this->assertFalse($conn->isConnected(2));
$conn->connect(2);
$this->assertEquals(1, $conn->fetchColumn('SELECT 1'));
$this->assertTrue($conn->isConnected(2));
$conn->close();
$this->assertFalse($conn->isConnected(0));
$this->assertFalse($conn->isConnected(1));
$this->assertFalse($conn->isConnected(2));
}
public function testNoGlobalServerException()
{
$this->setExpectedException('InvalidArgumentException', "Connection Parameters require 'global' and 'shards' configurations.");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'shards' => array(
array('id' => 1, 'memory' => true),
array('id' => 2, 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
}
public function testNoShardsServersException()
{
$this->setExpectedException('InvalidArgumentException', "Connection Parameters require 'global' and 'shards' configurations.");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
}
public function testNoShardsChoserException()
{
$this->setExpectedException('InvalidArgumentException', "Missing Shard Choser configuration 'shardChoser'");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
array('id' => 2, 'memory' => true),
),
));
}
public function testShardChoserWrongInstance()
{
$this->setExpectedException('InvalidArgumentException', "The 'shardChoser' configuration is not a valid instance of Doctrine\DBAL\Sharding\ShardChoser\ShardChoser");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
array('id' => 2, 'memory' => true),
),
'shardChoser' => new \stdClass,
));
}
public function testShardNonNumericId()
{
$this->setExpectedException('InvalidArgumentException', "Shard Id has to be a non-negative number.");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 'foo', 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
}
public function testShardMissingId()
{
$this->setExpectedException('InvalidArgumentException', "Missing 'id' for one configured shard. Please specify a unique shard-id.");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
}
public function testDuplicateShardId()
{
$this->setExpectedException('InvalidArgumentException', "Shard 1 is duplicated in the configuration.");
DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
array('id' => 1, 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
}
public function testSwitchShardWithOpenTransactionException()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$conn->beginTransaction();
$this->setExpectedException('Doctrine\DBAL\Sharding\ShardingException', 'Cannot switch shard when transaction is active.');
$conn->connect(1);
}
public function testGetActiveShardId()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertNull($conn->getActiveShardId());
$conn->connect(0);
$this->assertEquals(0, $conn->getActiveShardId());
$conn->connect(1);
$this->assertEquals(1, $conn->getActiveShardId());
$conn->close();
$this->assertNull($conn->getActiveShardId());
}
public function testGetParamsOverride()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true, 'host' => 'localhost'),
'shards' => array(
array('id' => 1, 'memory' => true, 'host' => 'foo'),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertEquals(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true, 'host' => 'localhost'),
'shards' => array(
array('id' => 1, 'memory' => true, 'host' => 'foo'),
),
'shardChoser' => new MultiTenantShardChoser(),
'memory' => true,
'host' => 'localhost',
), $conn->getParams());
$conn->connect(1);
$this->assertEquals(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'global' => array('memory' => true, 'host' => 'localhost'),
'shards' => array(
array('id' => 1, 'memory' => true, 'host' => 'foo'),
),
'shardChoser' => new MultiTenantShardChoser(),
'id' => 1,
'memory' => true,
'host' => 'foo',
), $conn->getParams());
}
public function testGetHostOverride()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'host' => 'localhost',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true, 'host' => 'foo'),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertEquals('localhost', $conn->getHost());
$conn->connect(1);
$this->assertEquals('foo', $conn->getHost());
}
public function testGetPortOverride()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'port' => 3306,
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true, 'port' => 3307),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertEquals(3306, $conn->getPort());
$conn->connect(1);
$this->assertEquals(3307, $conn->getPort());
}
public function testGetUsernameOverride()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'user' => 'foo',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true, 'user' => 'bar'),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertEquals('foo', $conn->getUsername());
$conn->connect(1);
$this->assertEquals('bar', $conn->getUsername());
}
public function testGetPasswordOverride()
{
$conn = DriverManager::getConnection(array(
'wrapperClass' => 'Doctrine\DBAL\Sharding\PoolingShardConnection',
'driver' => 'pdo_sqlite',
'password' => 'foo',
'global' => array('memory' => true),
'shards' => array(
array('id' => 1, 'memory' => true, 'password' => 'bar'),
),
'shardChoser' => 'Doctrine\DBAL\Sharding\ShardChoser\MultiTenantShardChoser',
));
$this->assertEquals('foo', $conn->getPassword());
$conn->connect(1);
$this->assertEquals('bar', $conn->getPassword());
}
}
| mit |
unaio/una | modules/base/text/classes/BxBaseModTextInstaller.php | 411 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup BaseText Base classes for text modules
* @ingroup UnaModules
*
* @{
*/
class BxBaseModTextInstaller extends BxBaseModGeneralInstaller
{
function __construct($aConfig)
{
parent::__construct($aConfig);
}
}
/** @} */
| mit |
rkh/heroku | spec/heroku/command/keys_spec.rb | 3829 | require "spec_helper"
require "heroku/command/keys"
module Heroku::Command
describe Keys do
KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAp9AJD5QABmOcrkHm6SINuQkDefaR0MUrfgZ1Pxir3a4fM1fwa00dsUwbUaRuR7FEFD8n1E9WwDf8SwQTHtyZsJg09G9myNqUzkYXCmydN7oGr5IdVhRyv5ixcdiE0hj7dRnOJg2poSQ3Qi+Ka8SVJzF7nIw1YhuicHPSbNIFKi5s0D5a+nZb/E6MNGvhxoFCQX2IcNxaJMqhzy1ESwlixz45aT72mXYq0LIxTTpoTqma1HuKdRY8HxoREiivjmMQulYP+CxXFcMyV9kxTKIUZ/FXqlC6G5vSm3J4YScSatPOj9ID5HowpdlIx8F6y4p1/28r2tTl4CY40FFyoke4MQ== pedro@heroku"
before(:each) do
stub_core
allow(Heroku::Auth).to receive(:home_directory).and_return(Heroku::Helpers.home_directory)
end
context("add") do
it "tries to find a key if no key filename is supplied" do
expect(Heroku::Auth).to receive(:ask).and_return("y")
stderr, stdout = execute("keys:add")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
Could not find an existing public key at ~/.ssh/id_rsa.pub
Would you like to generate one? [Yn] Generating new SSH public key.
Uploading SSH public key #{Heroku::Auth.home_directory}/.ssh/id_rsa.pub... done
STDOUT
api.delete_key(`whoami`.strip + '@' + `hostname`.strip)
end
it "adds a key from a specified keyfile path" do
# This is because the JSPlugin makes a call to File.exists
# Not pretty, but will always work and should be temporary
allow(Heroku::JSPlugin).to receive(:setup?).and_return(false)
expect(File).to receive(:exists?).with('.git').and_return(false)
expect(File).to receive(:exists?).with('/my/key.pub').and_return(true)
expect(File).to receive(:read).with('/my/key.pub').and_return(KEY)
stderr, stdout = execute("keys:add /my/key.pub")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
Uploading SSH public key /my/key.pub... done
STDOUT
api.delete_key("pedro@heroku")
end
end
context("index") do
before do
api.post_key(KEY)
end
after do
api.delete_key("pedro@heroku")
end
it "list keys, trimming the hex code for better display" do
stderr, stdout = execute("keys")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
=== email@example.com Keys
ssh-rsa AAAAB3NzaC...Fyoke4MQ== pedro@heroku
STDOUT
end
it "list keys showing the whole key hex with --long" do
stderr, stdout = execute("keys --long")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
=== email@example.com Keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAp9AJD5QABmOcrkHm6SINuQkDefaR0MUrfgZ1Pxir3a4fM1fwa00dsUwbUaRuR7FEFD8n1E9WwDf8SwQTHtyZsJg09G9myNqUzkYXCmydN7oGr5IdVhRyv5ixcdiE0hj7dRnOJg2poSQ3Qi+Ka8SVJzF7nIw1YhuicHPSbNIFKi5s0D5a+nZb/E6MNGvhxoFCQX2IcNxaJMqhzy1ESwlixz45aT72mXYq0LIxTTpoTqma1HuKdRY8HxoREiivjmMQulYP+CxXFcMyV9kxTKIUZ/FXqlC6G5vSm3J4YScSatPOj9ID5HowpdlIx8F6y4p1/28r2tTl4CY40FFyoke4MQ== pedro@heroku
STDOUT
end
end
context("remove") do
context("success") do
before(:each) do
api.post_key(KEY)
end
it "succeeds" do
stderr, stdout = execute("keys:remove pedro@heroku")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
Removing pedro@heroku SSH key... done
STDOUT
end
end
it "displays an error if no key is specified" do
stderr, stdout = execute("keys:remove")
expect(stderr).to eq <<-STDERR
! Usage: heroku keys:remove KEY
! Must specify KEY to remove.
STDERR
expect(stdout).to eq("")
end
end
context("clear") do
it "succeeds" do
stderr, stdout = execute("keys:clear")
expect(stderr).to eq("")
expect(stdout).to eq <<-STDOUT
Removing all SSH keys... done
STDOUT
end
end
end
end
| mit |
isman-usoh/DefinitelyTyped | types/amplify-deferred/index.d.ts | 1231 | // Type definitions for AmplifyJs (using JQuery Deferred) 1.1
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>, Laurentiu Stamate <https://github.com/laurentiustamate94>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jquery" />
import * as amplify from "amplify";
declare module "amplify" {
interface Request {
/***
* Request a resource.
* resourceId: Identifier string for the resource.
* data: A set of key/value pairs of data to be sent to the resource.
* callback: A function to invoke if the resource is retrieved successfully.
*/
(resourceId: string, hash?: any, callback?: Function): JQueryPromise<any>;
/***
* Request a resource.
* settings: A set of key/value pairs of settings for the request.
* resourceId: Identifier string for the resource.
* data (optional): Data associated with the request.
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: RequestSettings): JQueryPromise<any>;
}
}
| mit |
vchelaru/Dodgeball | Dodgeball/Dodgeball/GumCore/ReflectionManager.cs | 1724 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ToolsUtilities
{
public static class ReflectionManager
{
public static List<T> GetMembersOfType<T>(object container)
{
Type typeOfT = typeof(T);
Type containerType = container.GetType();
List<T> toReturn = new List<T>();
IEnumerable<PropertyInfo> properties = containerType.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType == typeOfT)
{
object objectToAdd = property.GetValue(container, null);
// Fields and properties may point to
// the same object so wee want to check for
// duplicates
if (!toReturn.Contains((T)objectToAdd))
{
toReturn.Add((T)objectToAdd);
}
}
}
IEnumerable<FieldInfo> fields = containerType.GetFields();
foreach (FieldInfo field in fields)
{
if (field.FieldType == typeOfT)
{
object objectToAdd = field.GetValue(container);
// Fields and properties may point to
// the same object so wee want to check for
// duplicates
if (!toReturn.Contains((T)objectToAdd))
{
toReturn.Add((T)objectToAdd);
}
}
}
return toReturn;
}
}
}
| mit |
rtlechow/rubocop | lib/rubocop/cop/style/space_after_method_name.rb | 1062 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for space between a method name and a left parenthesis in defs.
#
# @example
#
# # bad
# def func (x) ... end
#
# # good
# def func(x) ... end
class SpaceAfterMethodName < Cop
include OnMethodDef
MSG = 'Do not put a space between a method name and the opening ' \
'parenthesis.'.freeze
def on_method_def(_node, _method_name, args, _body)
return unless args.loc.begin && args.loc.begin.is?('(')
expr = args.source_range
pos_before_left_paren = range_between(expr.begin_pos - 1,
expr.begin_pos)
return unless pos_before_left_paren.source =~ /\s/
add_offense(pos_before_left_paren, pos_before_left_paren)
end
def autocorrect(pos_before_left_paren)
->(corrector) { corrector.remove(pos_before_left_paren) }
end
end
end
end
end
| mit |
GPUOpen-LibrariesAndSDKs/TiledLighting11 | amd_sdk/src/ShaderCacheSampleHelper.cpp | 11234 | //
// Copyright (c) 2016 Advanced Micro Devices, Inc. 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.
//
//--------------------------------------------------------------------------------------
// File: ShaderCacheSampleHelper.cpp
//
// Helpers to implement the DXUT related ShaderCache interface in samples.
//--------------------------------------------------------------------------------------
#include "..\\inc\ShaderCacheSampleHelper.h"
#include "..\\..\\DXUT\\Core\\DXUT.h"
#include "..\\..\\DXUT\\Core\\DXUTmisc.h"
#include "..\\..\\DXUT\\Optional\\DXUTgui.h"
#include "..\\..\\DXUT\\Optional\\DXUTCamera.h"
#include "..\\..\\DXUT\\Optional\\DXUTSettingsDlg.h"
#include "..\\..\\DXUT\\Optional\\SDKmisc.h"
#include "..\\..\\DXUT\\Optional\\SDKmesh.h"
#include "ShaderCache.h"
#include "Sprite.h"
#include "HUD.h"
#pragma warning( disable : 4100 ) // disable unreference formal parameter warnings for /W4 builds
#if !AMD_SDK_PREBUILT_RELEASE_EXE
static void SetHUDVisibility( AMD::HUD& r_HUD, const bool i_bHUDIsVisible )
{
using namespace AMD;
assert( AMD_IDC_BUTTON_SHOW_SHADERCACHE_UI == AMD_IDC_START );
for (int i = AMD_IDC_BUTTON_SHOW_SHADERCACHE_UI + 1; i < AMD_IDC_END; ++i)
{
CDXUTControl* pControl = r_HUD.m_GUI.GetControl( GetEnum( i ) );
if (pControl)
{
pControl->SetVisible( i_bHUDIsVisible );
}
}
}
#endif
namespace AMD
{
static bool g_bAdvancedShaderCacheGUI_IsVisible = false;
HUD* g_pHUD = NULL;
ShaderCache* g_pShaderCache = NULL;
void AMD::InitApp( ShaderCache& r_ShaderCache, HUD& r_HUD, int& iY, const bool i_bAdvancedShaderCacheGUI_VisibleByDefault )
{
#if !AMD_SDK_PREBUILT_RELEASE_EXE
g_bAdvancedShaderCacheGUI_IsVisible = i_bAdvancedShaderCacheGUI_VisibleByDefault;
const int i_old_iY = iY;
g_pHUD = &r_HUD;
g_pShaderCache = &r_ShaderCache;
{
r_HUD.m_GUI.AddButton( GetEnum( AMD_IDC_BUTTON_SHOW_SHADERCACHE_UI ), L"ShaderCache HUD (F9)",
AMD::HUD::iElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, VK_F9 );
iY = 0;
static const int iSCElementOffset = AMD::HUD::iElementOffset - 256;
r_HUD.m_GUI.AddButton( GetEnum( AMD_IDC_BUTTON_RECOMPILESHADERS_CHANGED ), L"Recompile shaders (F5)",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, VK_F5 );
#if AMD_SDK_INTERNAL_BUILD
if (r_ShaderCache.GenerateISAGPRPressure())
{
r_HUD.m_GUI.AddButton( GetEnum( AMD_IDC_BUTTON_RECREATE_SHADERS ), L"Gen |ISA| shaders (F6)",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, VK_F6 );
}
#endif
r_HUD.m_GUI.AddButton( GetEnum( AMD_IDC_BUTTON_RECOMPILESHADERS_GLOBAL ), L"Build ALL shaders (F7)",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, VK_F7 );
r_HUD.m_GUI.AddCheckBox( GetEnum( AMD_IDC_CHECKBOX_AUTORECOMPILE_SHADERS ), L"Auto Recompile Shaders",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, r_ShaderCache.RecompileTouchedShaders() );
if (r_ShaderCache.ShaderErrorDisplayType() == ShaderCache::ERROR_DISPLAY_ON_SCREEN)
{
r_HUD.m_GUI.AddCheckBox( GetEnum( AMD_IDC_CHECKBOX_SHOW_SHADER_ERRORS ), L"Show Compiler Errors",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, r_ShaderCache.ShowShaderErrors() );
}
#if AMD_SDK_INTERNAL_BUILD
if (r_ShaderCache.GenerateISAGPRPressure())
{
r_HUD.m_GUI.AddCheckBox( GetEnum( AMD_IDC_CHECKBOX_SHOW_ISA_GPR_PRESSURE ), L"Show ISA GPR Pressure",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, r_ShaderCache.ShowISAGPRPressure() );
r_HUD.m_GUI.AddStatic( GetEnum( AMD_IDC_STATIC_TARGET_ISA ), L"Target ISA:",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight );
CDXUTComboBox *pCombo;
r_HUD.m_GUI.AddComboBox( GetEnum( AMD_IDC_COMBOBOX_TARGET_ISA ),
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight, 0, true, &pCombo );
if (pCombo)
{
pCombo->SetDropHeight( 300 );
for (int i = AMD::FIRST_ISA_TARGET; i < AMD::NUM_ISA_TARGETS; ++i)
{
pCombo->AddItem( AMD::AmdTargetInfo[i].m_Name, NULL );
}
pCombo->SetSelectedByIndex( AMD::DEFAULT_ISA_TARGET );
}
r_HUD.m_GUI.AddStatic( GetEnum( AMD_IDC_STATIC_TARGET_ISA_INFO ), L"Press (F6) to add New ISA",
iSCElementOffset, iY += AMD::HUD::iElementDelta, AMD::HUD::iElementWidth, AMD::HUD::iElementHeight );
}
#endif
}
SetHUDVisibility( r_HUD, i_bAdvancedShaderCacheGUI_VisibleByDefault );
iY = i_old_iY + AMD::HUD::iElementDelta;
#endif
}
void AMD::ProcessUIChanges()
{
#if !AMD_SDK_PREBUILT_RELEASE_EXE
if (g_pHUD == NULL || g_pShaderCache == NULL)
{
return;
}
ShaderCache& r_ShaderCache = *g_pShaderCache;
HUD& r_HUD = *g_pHUD;
r_ShaderCache.SetRecompileTouchedShadersFlag( r_HUD.m_GUI.GetCheckBox( GetEnum( AMD_IDC_CHECKBOX_AUTORECOMPILE_SHADERS ) )->GetChecked() );
if (r_ShaderCache.ShaderErrorDisplayType() == ShaderCache::ERROR_DISPLAY_ON_SCREEN)
{
r_ShaderCache.SetShowShaderErrorsFlag( r_HUD.m_GUI.GetCheckBox( GetEnum( AMD_IDC_CHECKBOX_SHOW_SHADER_ERRORS ) )->GetChecked() );
}
#if AMD_SDK_INTERNAL_BUILD
if (r_ShaderCache.GenerateISAGPRPressure())
{
r_ShaderCache.SetShowShaderISAFlag( r_HUD.m_GUI.GetCheckBox( GetEnum( AMD_IDC_CHECKBOX_SHOW_ISA_GPR_PRESSURE ) )->GetChecked() );
}
#endif
#endif
}
void AMD::RenderHUDUpdates( CDXUTTextHelper* i_pTxtHelper )
{
#if !AMD_SDK_PREBUILT_RELEASE_EXE
if (g_pHUD == NULL || g_pShaderCache == NULL)
{
return;
}
ShaderCache& r_ShaderCache = *g_pShaderCache;
if (r_ShaderCache.ShadersReady() || (r_ShaderCache.ShowShaderErrors() && r_ShaderCache.HasErrorsToDisplay()))
{
assert( i_pTxtHelper );
r_ShaderCache.RenderShaderErrors( i_pTxtHelper, 15, DirectX::XMVectorSet( 1.0f, 1.0f, 0.0f, 1.0f ) );
#if AMD_SDK_INTERNAL_BUILD
if (r_ShaderCache.GenerateISAGPRPressure())
{
r_ShaderCache.RenderISAInfo( i_pTxtHelper, 15, DirectX::XMVectorSet( 1.0f, 1.0f, 0.0f, 1.0f ) );
}
#endif
}
#endif
}
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
void __stdcall AMD::OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext )
{
#if !AMD_SDK_PREBUILT_RELEASE_EXE
if (g_pHUD == NULL || g_pShaderCache == NULL)
{
return;
}
ShaderCache& r_ShaderCache = *g_pShaderCache;
HUD& r_HUD = *g_pHUD;
if (nControlID == GetEnum( AMD_IDC_BUTTON_RECOMPILESHADERS_CHANGED ))
{
// Errors will post during compile, don't need them right now
const bool bOldShaderErrorsFlag = r_ShaderCache.ShowShaderErrors();
r_ShaderCache.SetShowShaderErrorsFlag( false );
r_ShaderCache.GenerateShaders( AMD::ShaderCache::CREATE_TYPE_COMPILE_CHANGES, true );
r_ShaderCache.SetShowShaderErrorsFlag( bOldShaderErrorsFlag );
}
else if (nControlID == GetEnum( AMD_IDC_BUTTON_RECOMPILESHADERS_GLOBAL ))
{
// Errors will post during compile, don't need them right now
const bool bOldShaderErrorsFlag = r_ShaderCache.ShowShaderErrors();
r_ShaderCache.SetShowShaderErrorsFlag( false );
r_ShaderCache.GenerateShaders( AMD::ShaderCache::CREATE_TYPE_FORCE_COMPILE, true );
r_ShaderCache.SetShowShaderErrorsFlag( bOldShaderErrorsFlag );
}
#if AMD_SDK_INTERNAL_BUILD
else if (nControlID == GetEnum( AMD_IDC_BUTTON_RECREATE_SHADERS ))
{
assert( r_ShaderCache.GenerateISAGPRPressure() ); // Shouldn't call this if we aren't using ISA
const bool k_bOK = r_ShaderCache.CloneShaders();
assert( k_bOK );
if (k_bOK)
{
// Errors won't post using this method... Should find a better one!
// Need to somehow toggle error rendering off and then on again next frame...
const bool bOldShaderErrorsFlag = r_ShaderCache.ShowShaderErrors();
r_ShaderCache.SetShowShaderErrorsFlag( false );
r_ShaderCache.GenerateShaders( AMD::ShaderCache::CREATE_TYPE_USE_CACHED, true );
r_ShaderCache.SetShowShaderErrorsFlag( bOldShaderErrorsFlag );
}
}
else if (nControlID == GetEnum( AMD_IDC_COMBOBOX_TARGET_ISA ))
{
assert( r_ShaderCache.GenerateISAGPRPressure() ); // Shouldn't call this if we aren't using ISA
r_ShaderCache.SetTargetISA( (AMD::ISA_TARGET)((CDXUTComboBox*)pControl)->GetSelectedIndex() );
}
#endif
else if (nControlID == GetEnum( AMD_IDC_BUTTON_SHOW_SHADERCACHE_UI ))
{
// Toggle Render of ShaderCache GUI
g_bAdvancedShaderCacheGUI_IsVisible = !g_bAdvancedShaderCacheGUI_IsVisible;
SetHUDVisibility( r_HUD, g_bAdvancedShaderCacheGUI_IsVisible );
}
#endif
}
} // namespace AMD
| mit |
RainsSoft/engine | tests/shape/test_sphere.js | 3668 | module('pc.shape.Sphere');
test('Sphere: correct default values', function() {
var sphere = new pc.shape.Sphere();
QUnit.deepEqual(sphere.center.x, 0);
QUnit.deepEqual(sphere.center.y, 0);
QUnit.deepEqual(sphere.center.z, 0);
QUnit.deepEqual(sphere.radius, 1);
});
test('Sphere: Constructor sets correct values', function() {
var sphere = new pc.shape.Sphere(new pc.Vec3(1, 2, 3), 4);
QUnit.deepEqual(sphere.center.x, 1);
QUnit.deepEqual(sphere.center.y, 2);
QUnit.deepEqual(sphere.center.z, 3);
QUnit.deepEqual(sphere.radius, 4);
});
test('containsPoint: Point is in sphere returns true', function() {
var sphere = new pc.shape.Sphere(new pc.Vec3(1, 1, 1), 2);
var point = new pc.Vec3(0.5, 0.5, 0.5);
QUnit.deepEqual(sphere.containsPoint(point), true);
});
test('containsPoint: Point not in sphere returns false', function() {
var sphere = new pc.shape.Sphere(new pc.Vec3(1, 1, 1), 2);
var point = new pc.Vec3(0, 0, 5);
QUnit.deepEqual(sphere.containsPoint(point), false);
});
test('intersectRay: Intersection is correct', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,0, 10);
var direction = new pc.Vec3(0,0,-1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection.x, 0);
QUnit.equal(intersection.y, 0);
QUnit.equal(intersection.z, 5);
});
test('intersectRay: Intersection from center of sphere is correct', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,0,0);
var direction = new pc.Vec3(1,0,0);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection.x, 5);
QUnit.equal(intersection.y, 0);
QUnit.equal(intersection.z, 0);
});
test('intersectRay: Tangential intersection works', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,5,0);
var direction = new pc.Vec3(0,0,-1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection.x, 0);
QUnit.equal(intersection.y, 5);
QUnit.equal(intersection.z, 0);
});
test('intersectRay: Ray starting from sphere returns ray origin', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,0,5);
var direction = new pc.Vec3(0,0,-1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection.x, 0);
QUnit.equal(intersection.y, 0);
QUnit.equal(intersection.z, 5);
});
test('intersectRay: Ray starting from sphere returns ray origin', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,0,5);
var direction = new pc.Vec3(0,0,-1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection.x, 0);
QUnit.equal(intersection.y, 0);
QUnit.equal(intersection.z, 5);
});
test('intersectRay: Ray pointing away from sphere does not return intersection', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,6,0);
var direction = new pc.Vec3(0,0,-1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection, null);
});
test('intersectRay: Ray pointing away from sphere does not return intersection #2', function () {
var sphere = new pc.shape.Sphere(new pc.Vec3(0,0,0), 5);
var start = new pc.Vec3(0,0,6);
var direction = new pc.Vec3(0,0,1);
var intersection = sphere.intersectRay(start, direction);
QUnit.equal(intersection, null);
});
| mit |
JeyZeta/Dangerous | Dangerous/Golismero/thirdparty_libs/shodan/api.py | 7427 | try:
from json import dumps, loads
except:
from simplejson import dumps, loads
try:
# Python 2
from urllib2 import urlopen
from urllib import urlencode
except:
# Python 3
from urllib.request import urlopen
from urllib.parse import urlencode
__all__ = ['WebAPI']
class WebAPIError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
class WebAPI:
"""Wrapper around the SHODAN webservices API"""
class Exploits:
def __init__(self, parent):
self.parent = parent
def search(self, query, sources=[], cve=None, osvdb=None, msb=None, bid=None):
"""Search the entire Shodan Exploits archive using the same query syntax
as the website.
Arguments:
query -- exploit search query; same syntax as website
Optional arguments:
sources -- metasploit, cve, osvdb, exploitdb, or packetstorm
cve -- CVE identifier (ex. 2010-0432)
osvdb -- OSVDB identifier (ex. 11666)
msb -- Microsoft Security Bulletin ID (ex. MS05-030)
bid -- Bugtraq identifier (ex. 13951)
"""
if sources:
query += ' source:' + ','.join(sources)
if cve:
query += ' cve:%s' % (str(cve).strip())
if osvdb:
query += ' osvdb:%s' % (str(osvdb).strip())
if msb:
query += ' msb:%s' % (str(msb).strip())
if bid:
query += ' bid:%s' % (str(bid).strip())
return self.parent._request('search_exploits', {'q': query})
class ExploitDb:
def __init__(self, parent):
self.parent = parent
def download(self, id):
"""Download the exploit code from the ExploitDB archive.
Arguments:
id -- ID of the ExploitDB entry
Returns:
A dictionary with the following fields:
filename -- Name of the file
content-type -- Mimetype
data -- Contents of the file
"""
return self.parent._request('exploitdb/download', {'id': id})
def search(self, query, **kwargs):
"""Search the ExploitDB archive.
Arguments:
query -- Search terms
Optional arguments:
author -- Name of the exploit submitter
platform -- Target platform (e.g. windows, linux, hardware etc.)
port -- Service port number
type -- Any, dos, local, papers, remote, shellcode and webapps
Returns:
A dictionary with 2 main items: matches (list) and total (int).
Each item in 'matches' is a dictionary with the following elements:
id
author
date
description
platform
port
type
"""
return self.parent._request('exploitdb/search', dict(q=query, **kwargs))
class Msf:
def __init__(self, parent):
self.parent = parent
def download(self, id):
"""Download a metasploit module given the fullname (id) of it.
Arguments:
id -- fullname of the module (ex. auxiliary/admin/backupexec/dump)
Returns:
A dictionary with the following fields:
filename -- Name of the file
content-type -- Mimetype
data -- File content
"""
return self.parent._request('msf/download', {'id': id})
def search(self, query, **kwargs):
"""Search for a Metasploit module.
"""
return self.parent._request('msf/search', dict(q=query, **kwargs))
def __init__(self, key):
"""Initializes the API object.
Arguments:
key -- your API key
"""
self.api_key = key
self.base_url = 'http://www.shodanhq.com/api/'
self.exploits = self.Exploits(self)
self.exploitdb = self.ExploitDb(self)
self.msf = self.Msf(self)
def _request(self, function, params):
"""General-purpose function to create web requests to SHODAN.
Arguments:
function -- name of the function you want to execute
params -- dictionary of parameters for the function
Returns
A JSON string containing the function's results.
"""
# Add the API key parameter automatically
params['key'] = self.api_key
# Send the request
data = urlopen(self.base_url + function + '?' + urlencode(params)).read().decode('utf-8')
# Parse the text into JSON
data = loads(data)
# Raise an exception if an error occurred
if data.get('error', None):
raise WebAPIError(data['error'])
# Return the data
return data
def count(self, query):
"""Returns the total number of search results for the query.
"""
return self._request('count', {'q': query})
def locations(self, query):
"""Return a break-down of all the countries and cities that the results for
the given search are located in.
"""
return self._request('locations', {'q': query})
def fingerprint(self, banner):
"""Determine the software based on the banner.
Arguments:
banner - HTTP banner
Returns:
A list of software that matched the given banner.
"""
return self._request('fingerprint', {'banner': banner})
def host(self, ip):
"""Get all available information on an IP.
Arguments:
ip -- IP of the computer
Returns:
All available information SHODAN has on the given IP,
subject to API key restrictions.
"""
return self._request('host', {'ip': ip})
def info(self):
"""Returns information about the current API key, such as a list of add-ons
and other features that are enabled for the current user's API plan.
"""
return self._request('info', {})
def search(self, query, page=1, limit=None, offset=None):
"""Search the SHODAN database.
Arguments:
query -- search query; identical syntax to the website
Optional arguments:
page -- page number of the search results
limit -- number of results to return
offset -- search offset to begin getting results from
Returns:
A dictionary with 3 main items: matches, countries and total.
Visit the website for more detailed information.
"""
args = {
'q': query,
'p': page,
}
if limit:
args['l'] = limit
if offset:
args['o'] = offset
return self._request('search', args)
| mit |
MikeHardman/orleans | src/Orleans.Core/Serialization/DeserializationContext.cs | 4189 | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Orleans.Serialization
{
public static class DeserializationContextExtensions
{
/// <summary>
/// Returns a new nested context which begins at the specified position.
/// </summary>
/// <param name="context"></param>
/// <param name="position"></param>
/// <param name="reader"></param>
/// <returns></returns>
public static IDeserializationContext CreateNestedContext(
this IDeserializationContext context,
int position,
BinaryTokenStreamReader reader)
{
return new DeserializationContext.NestedDeserializationContext(context, position, reader);
}
}
public class DeserializationContext : SerializationContextBase, IDeserializationContext
{
private readonly Dictionary<int, object> taggedObjects;
public DeserializationContext(SerializationManager serializationManager)
: base(serializationManager)
{
this.taggedObjects = new Dictionary<int, object>();
}
/// <inheritdoc />
/// <inheritdoc />
public IBinaryTokenStreamReader StreamReader { get; set; }
/// <inheritdoc />
public int CurrentObjectOffset { get; set; }
public int CurrentPosition => this.StreamReader.CurrentPosition;
/// <inheritdoc />
public void RecordObject(object obj)
{
this.RecordObject(obj, this.CurrentObjectOffset);
}
/// <inheritdoc />
public void RecordObject(object obj, int offset)
{
taggedObjects[offset] = obj;
}
/// <inheritdoc />
public object FetchReferencedObject(int offset)
{
object result;
if (!taggedObjects.TryGetValue(offset, out result))
{
throw new SerializationException("Reference with no referred object");
}
return result;
}
internal void Reset()
{
this.taggedObjects.Clear();
this.CurrentObjectOffset = 0;
}
public override object AdditionalContext => this.SerializationManager.RuntimeClient;
public object DeserializeInner(Type expected)
{
return SerializationManager.DeserializeInner(expected, this);
}
internal class NestedDeserializationContext : IDeserializationContext
{
private readonly IDeserializationContext parent;
private readonly int position;
/// <summary>
/// Initializes a new <see cref="NestedDeserializationContext"/> instance.
/// </summary>
/// <param name="parent"></param>
/// <param name="position">The position, relative to the outer-most context, at which this context begins.</param>
/// <param name="reader"></param>
public NestedDeserializationContext(IDeserializationContext parent, int position, BinaryTokenStreamReader reader)
{
this.position = position;
this.parent = parent;
this.StreamReader = reader;
this.CurrentObjectOffset = this.parent.CurrentObjectOffset;
}
public IServiceProvider ServiceProvider => this.parent.ServiceProvider;
public object AdditionalContext => this.parent.AdditionalContext;
public IBinaryTokenStreamReader StreamReader { get; }
public int CurrentObjectOffset { get; set; }
public int CurrentPosition => this.position + this.StreamReader.CurrentPosition;
public void RecordObject(object obj, int offset) => this.parent.RecordObject(obj, offset);
public void RecordObject(object obj) => this.RecordObject(obj, this.CurrentObjectOffset);
public object FetchReferencedObject(int offset) => this.parent.FetchReferencedObject(offset);
public object DeserializeInner(Type expected) => SerializationManager.DeserializeInner(expected, this);
}
}
}
| mit |
NotDemons/NotDemonsRepo | Source/Tests/Santase.Logic.Tests/Extensions/RandomProviderTests.cs | 1471 | namespace Santase.Logic.Tests.Extensions
{
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Santase.Logic.Extensions;
[TestFixture]
public class RandomProviderTests
{
[Test]
public void NextWithParametersWithParameters1And2ShouldReturn1()
{
var value = RandomProvider.Next(1, 2);
Assert.AreEqual(1, value);
}
[Test]
public void NextWithParametersWithLimitedBoundariesShouldReturnCorrectValue()
{
var value = RandomProvider.Next(1337, 1338);
Assert.AreEqual(1337, value);
}
[Test]
public void NextShouldReturnRandomValues()
{
var randomNumbers = new Dictionary<int, int>();
for (var i = 0; i < 100000; i++)
{
var value = RandomProvider.Next(1, 101);
if (!randomNumbers.ContainsKey(value))
{
randomNumbers.Add(value, 0);
}
randomNumbers[value]++;
}
Assert.IsFalse(randomNumbers.ContainsKey(0));
Assert.IsTrue(randomNumbers[1] > 0);
Assert.IsTrue(randomNumbers[100] > 0);
Assert.IsFalse(randomNumbers.ContainsKey(101));
var difference = randomNumbers.Values.Max() - randomNumbers.Values.Min();
Assert.IsTrue(difference < 2000);
}
}
}
| mit |
omgtehlion/yate | lib/runtime2.js | 16109 | var yr = {};
// --------------------------------------------------------------------------------------------------------------- //
(function() {
// --------------------------------------------------------------------------------------------------------------- //
yr.Module = function() {
};
yr.Module.prototype.doc = function(data) {
return new yr.Doc(data, this);
};
// NOTE: ex applyValue.
yr.Module.prototype.applyValue = function(M, nodeset, mode, a0) {
var r = '';
var l0 = nodeset.length;
if (!l0) {
return r;
}
// Достаем аргументы, переданные в apply, если они там есть.
var args;
var n_args = arguments.length;
if (n_args > 6) {
args = Array.prototype.slice.call(arguments, 6);
}
var imports = M.imports;
// Идем по нодесету.
for (var i0 = 0; i0 < l0; i0++) {
var c0 = nodeset[i0];
// Для каждой ноды ищем подходящий шаблон.
// Сперва ищем в текущем модуле ( imports[0] ),
// затем идем далее по списку импортов.
// Если мы найдем шаблон, в found будет его id, а в module -- модуль,
// в котором находится этот шаблон.
var found = false;
var module;
var i2 = 0;
var l2 = imports.length;
while (!found && i2 < l2) {
module = imports[i2++];
// matcher представляем собой двухуровневый объект,
// на первом уровне ключами являются моды,
// на втором -- имена нод.
// Значения на втором уровне -- список id-шников шаблонов.
var names = module.matcher[mode];
if (names) {
// FIXME: Тут неправильно. Если шаблоны для c0.name будут,
// но ни один из них не подойдет, то шаблоны для '*' не применятся вообще.
// FIXME: Плюс шаблоны на '*' всегда имеют более низкий приоритет.
var templates = names[c0.name] || names['*'];
if (templates) {
var i3 = 0;
var l3 = templates.length;
while (!found && i3 < l3) {
var tid = templates[i3++];
var template = module[tid];
var selector = template.j;
if (selector) {
// В template.j лежит id селектора (jpath'а).
// В tempalte.a флаг о том, является ли jpath абсолютным.
if ( module.matched(selector, template.a, c0, i0, l0) ) {
found = tid;
}
} else {
var selectors = template.s;
var abs = template.a;
// В template.s лежит массив с id-шниками селекторов.
for (var i4 = 0, l4 = selectors.length; i4 < l4; i4++) {
if ( module.matched(selectors[i4], abs[i4], c0, i0, l0) ) {
found = tid;
break;
}
}
}
}
}
}
}
if (found) {
// Шаблон нашли, применяем его.
// FIXME: Сравнить скорость с if-else.
switch (n_args) {
case 4:
r += template( M, c0, i0, l0, a0 );
break;
case 5:
r += template( M, c0, i0, l0, a0, arguments[4] );
break;
case 6:
r += template( M, c0, i0, l0, a0, arguments[4], arguments[5] );
break;
default:
// Шаблон позвали с параметрами, приходится изгаляться.
// FIXME: Тут переопределение this не нужно вообще.
r += template.apply( M, [M, c0, i0, l0, a0].concat(args) );
}
}
}
return r;
};
// --------------------------------------------------------------------------------------------------------------- //
yr.Doc = function(data, module) {
this.root = new yr.Node(data, '', this);
this._keys = {};
this._vars = {};
};
// --------------------------------------------------------------------------------------------------------------- //
yr.Node = function(data, name, doc, parent) {
this.data = data;
this.name = name;
this.doc = doc;
this.parent = parent || null;
};
yr.Node.prototype.child = function(data, name) {
return new yr.Node(data, name, this.doc, this);
};
yr.Node.prototype.step = function(name, result) {
result = result || ( new yr.Nodeset() );
var data = this.data;
// FIXME: Кажется, тут можно и не проверять, что это объект.
// Т.к. следующая строчка для не объекта все равно даст undefined.
if (!data || typeof data !== 'object') { return result; }
data = data[name];
if (data === undefined) { return result; }
if (data instanceof Array) {
for (var i = 0, l = data.length; i < l; i++) {
// FIXME: Может быть быстрее будет явное new yr.Node?
result.push( this.child( data[i], name ) );
}
} else {
result.push( this.child( data, name ) );
}
return result;
};
yr.Node.prototype.star = function(result) {
result = result || ( new yr.Nodeset() );
var data = this.data;
for (var name in data) {
this.step(name, result);
}
return result;
};
yr.Node.prototype.dots = function(n, result) {
var node = this;
var i = 0;
while (node && i < n) {
node = node.parent;
i++;
}
if (node) {
result.push(node);
}
return result;
};
yr.Node.prototype.scalar = function() {
var data = this.data;
return (typeof data === 'object') ? '': data;
};
yr.Node.prototype.boolean = function() {
return !!this.data;
};
yr.Node.prototype.xml = function() {
};
yr.Node.prototype.isEmpty = function() {
return false;
};
/*
steps:
step param description
---------------------------------
1 'foo' nametest
2 0 startest
3 n index
4 n dots
5 p0 filter
6 'p0' filter by id
7 p0 guard
8 'p0' guard by id
var j0 = [ 1, 'foo' ];
var j1 = [ 1, 'foo', 1, 'bar' ];
*/
yr.Node.prototype.select = function(jpath) {
var result = this;
for (var i = 0, l = jpath.length; i < l; i += 2) {
var step = jpath[i];
var param = jpath[i + 1];
switch (step) {
case 1:
result = result.step(param);
break;
case 2:
result = result.star();
break;
case 3:
result = result.index(param);
break;
case 4:
result = result.dots(param);
break;
case 5:
result = result.filter(param);
break;
case 7:
result = result.guard(param);
break;
}
if ( result.isEmpty() ) {
return result;
}
}
return result;
};
yr.Node.prototype.matches = function(jpath, abs, index, count) {
if (jpath === 1) {
// Это jpath '/'
return !this.parent;
}
var l = jpath.length;
// i (и l) всегда будет четное.
var i = l - 2;
while (i >= 0) {
if (!c0) { return false; }
var step = jpath[i];
// Тут step может быть либо 0 (nametest), либо 2 (predicate).
// Варианты 1 (dots) и 3 (index) в jpath'ах в селекторах запрещены.
switch (step) {
case 0:
// Nametest.
var name = jpath[i + 1];
if (name !== '*' && name !== c0.name) { return false; }
c0 = c0.parent;
break;
case 2:
case 4:
// Predicate or guard.
var predicate = jpath[i + 1];
if ( !predicate(this, c0, i0, l0) ) { return false; }
break;
}
i -= 2;
}
if (abs && c0.parent) {
return false;
}
return true;
};
// --------------------------------------------------------------------------------------------------------------- //
yr.scalarStep = function(name) {
};
yr.booleanStep = function(name) {
};
yr.xmlStep = function(name) {
};
// --------------------------------------------------------------------------------------------------------------- //
yr.Nodeset = function(nodes) {
this.nodes = nodes || [];
};
yr.Nodeset.prototype.isEmpty = function() {
return (this.nodes.length === 0);
};
yr.Nodeset.prototype.push = function(node) {
this.nodes.push(node);
};
yr.Nodeset.prototype.step = function(name, result) {
result = result || ( new yr.Nodeset() );
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i].step(name, result);
}
return result;
};
yr.Nodeset.prototype.star = function(result) {
result = result || ( new yr.Nodeset() );
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i].star(result);
}
return result;
};
yr.Nodeset.prototype.dots = function(n, result) {
result = result || ( new yr.Nodeset() );
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i].dots(n, result);
}
return result;
};
yr.Nodeset.prototype.index = function(index) {
var node = this.nodes[index];
var result = new yr.Nodeset();
if (node) {
result.push(node);
}
return result;
};
yr.Nodeset.prototype.filter = function(filter) {
var result = new yr.Nodeset();
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
if ( filter(node, i, l) ) {
result.push(node);
}
}
return result;
};
yr.Nodeset.prototype.guard = function(guard) {
var nodes = this.nodes;
if (nodes.length > 0) {
if ( guard( nodes[0].doc.root ) ) {
return this;
}
}
return new yr.Nodeset();
};
yr.Nodeset.prototype.scalar = function() {
return ( this.isEmpty() ) ? '' : this.nodes[0].scalar();
};
yr.Nodeset.prototype.boolean = function() {
return !this.isEmpty() && this.nodes[0].boolean();
};
yr.Nodeset.prototype.toArray = function() {
var result = [];
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
result.push( nodes[i].data );
}
return result;
};
yr.Nodeset.prototype.concat = function(nodeset) {
return new yr.Nodeset( this.nodes.concat(nodeset.nodes) );
};
yr.Nodeset.prototype.name = function() {
return ( this.isEmpty() ) ? '' : this.nodes[0].name;
};
yr.Nodeset.prototype.select = function(jpath) {
var result = new yr.Nodeset();
var nodes = this.nodes;
for (var i = 0, l = nodes.length; i < l; i++) {
result = result.concat( nodes[i].select(jpath) );
}
return result;
};
// --------------------------------------------------------------------------------------------------------------- //
function escape1(s) {
return s.replace(/&/g, '&');
}
function escape4(s) {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
function escape3(s) {
return s
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
// --------------------------------------------------------------------------------------------------------------- //
yr.Attrs = function() {
this.attrs = {};
this.name = '';
};
yr.Attrs.prototype.add = function(name, value) {
this.attrs[name] = value;
};
var shortTags = yr.shortTags = {
br: true,
col: true,
embed: true,
hr: true,
img: true,
input: true,
link: true,
meta: true,
param: true,
wbr: true
};
yr.Attrs.prototype.close = function() {
var name = this.name;
var r = '';
if (name) {
var attrs = this.attrs;
for (var attr in attrs) {
r += ' ' + attr + '="' + attrs[attr].quote() + '"';
}
r += ( shortTags[name] ) ? '/>' : '>';
this.name = '';
}
return r;
};
yr.Attrs.prototype.copy = function(to) {
to = to || new yr.Attrs();
var from_attrs = this.attrs;
var to_attrs = to.attrs;
for (var name in attrs) {
to[name] = from[name];
}
to.name = this.name;
return to;
};
// --------------------------------------------------------------------------------------------------------------- //
yr.scalarAttr = function(s) {
this.s = (s == null) ? '' : s.toString();
};
yr.scalarAttr.prototype.quote = function() {
return escape4(this.s);
};
yr.scalarAttr.prototype.add_xml = function(xml) {
return new yr.xmlAttr( escape1(this.s) + xml );
};
yr.scalarAttr.prototype.add_scalar = function(xml) {
return new yr.scalarAttr( this.s + xml );
};
// --------------------------------------------------------------------------------------------------------------- //
yr.xmlAttr = function(s) {
this.s = (s == null) ? '' : s.toString();
};
yr.xmlAttr.prototype.quote = function() {
return escape3(this.s);
};
yr.xmlAttr.prototype.addscalar = function(scalar) {
return new yr.xmlAttr( this.s + escape1(scalar) );
};
// --------------------------------------------------------------------------------------------------------------- //
/*
steps:
step param description
---------------------------------
1 'foo' nametest
2 0 startest
3 n index
4 n dots
5 p0 filter
6 'p0' filter by id
7 p0 guard
8 'p0' guard by id
*/
/*
[1,'foo',1,'bar']
function(n){return n.s('foo').s('bar')}
yr.compileSelect = function(steps) {
var r = '';
for (var i = 0, l = steps.length; i += 2) {
var step = steps[i];
var param = steps[i + 1];
switch (step) {
case 1:
r += 'r = r.step("' + param + '");';
break;
case 2:
r += 'r = r.star();';
break;
case 3:
r += 'r = r.index(' + param + ');';
break;
case 4:
case 5:
case 7:
case 6:
case 8:
}
r += 'if ( node.isEmpty() ) { return node; }';
}
};
yr.compileMatch = function(steps) {
};
*/
// --------------------------------------------------------------------------------------------------------------- //
})();
// --------------------------------------------------------------------------------------------------------------- //
| mit |
ctreatma/warbler | integration/simple_rack_test/src/test/java/org/jruby/warbler/AppTestIT.java | 847 | package org.jruby.warbler;
import java.net.*;
import java.io.*;
import org.junit.Assert;
import org.junit.Test;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
/**
* Unit test for simple App.
*/
public class AppTestIT
{
private static String appName = "simple_rack_test";
/**
* Hit the web app and test the response
*/
@Test
public void testApp() throws Exception
{
URL url = new URL("http://localhost:8080/" + appName);
URLConnection conn = url.openConnection();
BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream()));
String inputLine;
String content = "";
while ((inputLine = in.readLine()) != null)
content = inputLine;
in.close();
Assert.assertEquals("Hello, World", content);
}
}
| mit |
CascadeEnergy/hapi-mysql-routes-plugin | gulpfile.js | 48 | 'use strict';
require('require-dir')('./gulp');
| mit |
allysonbarros/gitlabhq | spec/requests/api/environments_spec.rb | 4288 | require 'spec_helper'
describe API::API, api: true do
include ApiHelpers
let(:user) { create(:user) }
let(:non_member) { create(:user) }
let(:project) { create(:project, :private, namespace: user.namespace) }
let!(:environment) { create(:environment, project: project) }
before do
project.team << [user, :master]
end
describe 'GET /projects/:id/environments' do
context 'as member of the project' do
it_behaves_like 'a paginated resources' do
let(:request) { get api("/projects/#{project.id}/environments", user) }
end
it 'returns project environments' do
get api("/projects/#{project.id}/environments", user)
expect(response).to have_http_status(200)
expect(json_response).to be_an Array
expect(json_response.size).to eq(1)
expect(json_response.first['name']).to eq(environment.name)
expect(json_response.first['external_url']).to eq(environment.external_url)
expect(json_response.first['project']['id']).to eq(project.id)
end
end
context 'as non member' do
it 'returns a 404 status code' do
get api("/projects/#{project.id}/environments", non_member)
expect(response).to have_http_status(404)
end
end
end
describe 'POST /projects/:id/environments' do
context 'as a member' do
it 'creates a environment with valid params' do
post api("/projects/#{project.id}/environments", user), name: "mepmep"
expect(response).to have_http_status(201)
expect(json_response['name']).to eq('mepmep')
expect(json_response['external']).to be nil
end
it 'requires name to be passed' do
post api("/projects/#{project.id}/environments", user), external_url: 'test.gitlab.com'
expect(response).to have_http_status(400)
end
it 'returns a 400 if environment already exists' do
post api("/projects/#{project.id}/environments", user), name: environment.name
expect(response).to have_http_status(400)
end
end
context 'a non member' do
it 'rejects the request' do
post api("/projects/#{project.id}/environments", non_member), name: 'gitlab.com'
expect(response).to have_http_status(404)
end
it 'returns a 400 when the required params are missing' do
post api("/projects/12345/environments", non_member), external_url: 'http://env.git.com'
end
end
end
describe 'PUT /projects/:id/environments/:environment_id' do
it 'returns a 200 if name and external_url are changed' do
url = 'https://mepmep.whatever.ninja'
put api("/projects/#{project.id}/environments/#{environment.id}", user),
name: 'Mepmep', external_url: url
expect(response).to have_http_status(200)
expect(json_response['name']).to eq('Mepmep')
expect(json_response['external_url']).to eq(url)
end
it "won't update the external_url if only the name is passed" do
url = environment.external_url
put api("/projects/#{project.id}/environments/#{environment.id}", user),
name: 'Mepmep'
expect(response).to have_http_status(200)
expect(json_response['name']).to eq('Mepmep')
expect(json_response['external_url']).to eq(url)
end
it 'returns a 404 if the environment does not exist' do
put api("/projects/#{project.id}/environments/12345", user)
expect(response).to have_http_status(404)
end
end
describe 'DELETE /projects/:id/environments/:environment_id' do
context 'as a master' do
it 'returns a 200 for an existing environment' do
delete api("/projects/#{project.id}/environments/#{environment.id}", user)
expect(response).to have_http_status(200)
end
it 'returns a 404 for non existing id' do
delete api("/projects/#{project.id}/environments/12345", user)
expect(response).to have_http_status(404)
expect(json_response['message']).to eq('404 Not found')
end
end
context 'a non member' do
it 'rejects the request' do
delete api("/projects/#{project.id}/environments/#{environment.id}", non_member)
expect(response).to have_http_status(404)
end
end
end
end
| mit |
stefan321/android | zxing-1.6/android/src/com/google/zxing/client/android/CaptureActivityHandler.java | 4366 | /*
* Copyright (C) 2008 ZXing authors
*
* 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 com.google.zxing.client.android;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.client.android.camera.CameraManager;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.Vector;
/**
* This class handles all the messaging which comprises the state machine for capture.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class CaptureActivityHandler extends Handler {
private static final String TAG = CaptureActivityHandler.class.getSimpleName();
private final CaptureActivity activity;
private final DecodeThread decodeThread;
private State state;
private enum State {
PREVIEW,
SUCCESS,
DONE
}
CaptureActivityHandler(CaptureActivity activity, Vector<BarcodeFormat> decodeFormats,
String characterSet) {
this.activity = activity;
decodeThread = new DecodeThread(activity, decodeFormats, characterSet,
new ViewfinderResultPointCallback(activity.getViewfinderView()));
decodeThread.start();
state = State.SUCCESS;
// Start ourselves capturing previews and decoding.
CameraManager.get().startPreview();
restartPreviewAndDecode();
}
@Override
public void handleMessage(Message message) {
if (message.what == R.id.auto_focus) {
//Log.d(TAG, "Got auto-focus message");
// When one auto focus pass finishes, start another. This is the closest thing to
// continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.
if (state == State.PREVIEW) {
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
}
} else if (message.what == R.id.restart_preview) {
Log.d(TAG, "Got restart preview message");
restartPreviewAndDecode();
} else if (message.what == R.id.decode_succeeded) {
Log.d(TAG, "Got decode succeeded message");
state = State.SUCCESS;
Bundle bundle = message.getData();
Bitmap barcode = bundle == null ? null :
(Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);
activity.handleDecode((Result) message.obj, barcode);
} else if (message.what == R.id.decode_failed) {
// We're decoding as fast as possible, so when one decode fails, start another.
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
} else if (message.what == R.id.return_scan_result) {
Log.d(TAG, "Got return scan result message");
activity.setResult(Activity.RESULT_OK, (Intent) message.obj);
activity.finish();
} else if (message.what == R.id.launch_product_query) {
Log.d(TAG, "Got product query message");
String url = (String) message.obj;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
activity.startActivity(intent);
}
}
public void quitSynchronously() {
state = State.DONE;
CameraManager.get().stopPreview();
Message quit = Message.obtain(decodeThread.getHandler(), R.id.quit);
quit.sendToTarget();
try {
decodeThread.join();
} catch (InterruptedException e) {
// continue
}
// Be absolutely sure we don't send any queued up messages
removeMessages(R.id.decode_succeeded);
removeMessages(R.id.decode_failed);
}
private void restartPreviewAndDecode() {
if (state == State.SUCCESS) {
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
activity.drawViewfinder();
}
}
}
| mit |
rajansingh10/corefx | src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs | 65753 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*
Note on transaction support:
Eventually we will want to add support for NT's transactions to our
RegistryKey API's. When we do this, here's
the list of API's we need to make transaction-aware:
RegCreateKeyEx
RegDeleteKey
RegDeleteValue
RegEnumKeyEx
RegEnumValue
RegOpenKeyEx
RegQueryInfoKey
RegQueryValueEx
RegSetValueEx
We can ignore RegConnectRegistry (remote registry access doesn't yet have
transaction support) and RegFlushKey. RegCloseKey doesn't require any
additional work.
*/
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
registry key, then the ACL only gets checked when you construct handles to
them. So if you set an ACL to deny read access to yourself, you'll still be
able to read with that handle, but not with new handles.
Another peculiarity is a Terminal Server app compatibility hack. The OS
will second guess your attempt to open a handle sometimes. If a certain
combination of Terminal Server app compat registry keys are set, then the
OS will try to reopen your handle with lesser permissions if you couldn't
open it in the specified mode. So on some machines, we will see handles that
may not be able to read or write to a registry key. It's very strange. But
the real test of these handles is attempting to read or set a value in an
affected registry key.
For reference, at least two registry keys must be set to particular values
for this behavior:
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1.
HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1
There might possibly be an interaction with yet a third registry key as well.
*/
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.AccessControl;
namespace Microsoft.Win32
{
/**
* Registry hive values. Useful only for GetRemoteBaseKey
*/
public enum RegistryHive
{
ClassesRoot = unchecked((int)0x80000000),
CurrentUser = unchecked((int)0x80000001),
LocalMachine = unchecked((int)0x80000002),
Users = unchecked((int)0x80000003),
PerformanceData = unchecked((int)0x80000004),
CurrentConfig = unchecked((int)0x80000005),
}
/**
* Registry encapsulation. To get an instance of a RegistryKey use the
* Registry class's static members then call OpenSubKey.
*
* @see Registry
* @security(checkDllCalls=off)
* @security(checkClassLinking=on)
*/
public sealed class RegistryKey : IDisposable
{
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
// Dirty indicates that we have munged data that should be potentially
// written to disk.
//
private const int STATE_DIRTY = 0x0001;
// SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened"
// or "closed".
//
private const int STATE_SYSTEMKEY = 0x0002;
// Access
//
private const int STATE_WRITEACCESS = 0x0004;
// Indicates if this key is for HKEY_PERFORMANCE_DATA
private const int STATE_PERF_DATA = 0x0008;
// Names of keys. This array must be in the same order as the HKEY values listed above.
//
private static readonly String[] hkeyNames = new String[] {
"HKEY_CLASSES_ROOT",
"HKEY_CURRENT_USER",
"HKEY_LOCAL_MACHINE",
"HKEY_USERS",
"HKEY_PERFORMANCE_DATA",
"HKEY_CURRENT_CONFIG"
};
// MSDN defines the following limits for registry key names & values:
// Key Name: 255 characters
// Value name: 16,383 Unicode characters
// Value: either 1 MB or current available memory, depending on registry format.
private const int MaxKeyLength = 255;
private const int MaxValueLength = 16383;
[System.Security.SecurityCritical]
private volatile SafeRegistryHandle hkey = null;
private volatile int state = 0;
private volatile String keyName;
private volatile bool remoteKey = false;
private volatile RegistryView regView = RegistryView.Default;
/**
* RegistryInternalCheck values. Useful only for CheckPermission
*/
private enum RegistryInternalCheck
{
CheckSubKeyWritePermission = 0,
CheckSubKeyReadPermission = 1,
CheckSubKeyCreatePermission = 2,
CheckSubTreeReadPermission = 3,
CheckSubTreeWritePermission = 4,
CheckSubTreeReadWritePermission = 5,
CheckValueWritePermission = 6,
CheckValueCreatePermission = 7,
CheckValueReadPermission = 8,
CheckKeyReadPermission = 9,
CheckSubTreePermission = 10,
CheckOpenSubKeyWithWritablePermission = 11,
CheckOpenSubKeyPermission = 12
};
/**
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed.
*/
[System.Security.SecurityCritical] // auto-generated
private RegistryKey(SafeRegistryHandle hkey, bool writable, RegistryView view)
: this(hkey, writable, false, false, false, view)
{
}
/**
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
* will be allowed. If systemkey is set then the hkey won't be released
* when the object is GC'ed.
* The remoteKey flag when set to true indicates that we are dealing with registry entries
* on a remote machine and requires the program making these calls to have full trust.
*/
[System.Security.SecurityCritical]
private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view)
{
this.hkey = hkey;
this.keyName = "";
this.remoteKey = remoteKey;
this.regView = view;
if (systemkey)
{
this.state |= STATE_SYSTEMKEY;
}
if (writable)
{
this.state |= STATE_WRITEACCESS;
}
if (isPerfData)
this.state |= STATE_PERF_DATA;
ValidateKeyView(view);
}
/**
* Closes this key, flushes it to disk if the contents have been modified.
*/
internal void Close()
{
Dispose(true);
}
[System.Security.SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (hkey != null)
{
if (!IsSystemKey())
{
try
{
hkey.Dispose();
}
catch (IOException)
{
// we don't really care if the handle is invalid at this point
}
finally
{
hkey = null;
}
}
else if (disposing && IsPerfDataKey())
{
// System keys should never be closed. However, we want to call RegCloseKey
// on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
// (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
// to be refreshed (by re-reading the registry) when accessed subsequently.
// This is the only way we can see the just installed perf counter.
// NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race in closing
// the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
// in this situation the down level OSes are not. We have a small window of race between
// the dispose below and usage elsewhere (other threads). This is By Design.
// This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
// (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
Interop.mincore.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
}
}
}
[System.Security.SecuritySafeCritical]
public void Flush()
{
if (hkey != null)
{
if (IsDirty())
{
Interop.mincore.RegFlushKey(hkey);
}
}
}
public void Dispose()
{
Dispose(true);
}
/**
* Creates a new subkey, or opens an existing one.
*
* @param subkey Name or path to subkey to create or open.
*
* @return the subkey, or <b>null</b> if the operation failed.
*/
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public RegistryKey CreateSubKey(String subkey)
{
return CreateSubKey(subkey, IsWritable());
}
public RegistryKey CreateSubKey(String subkey, bool writable)
{
return CreateSubKeyInternal(subkey, writable, RegistryOptions.None);
}
public RegistryKey CreateSubKey(String subkey, bool writable, RegistryOptions options)
{
return CreateSubKeyInternal(subkey, writable, options);
}
[System.Security.SecuritySafeCritical]
private unsafe RegistryKey CreateSubKeyInternal(String subkey, bool writable, RegistryOptions registryOptions)
{
ValidateKeyOptions(registryOptions);
ValidateKeyName(subkey);
EnsureWriteable();
subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
// only keys opened under read mode is not writable
if (!remoteKey)
{
RegistryKey key = InternalOpenSubKey(subkey, writable);
if (key != null)
{ // Key already exits
return key;
}
}
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
int disposition = 0;
// By default, the new key will be writable.
SafeRegistryHandle result = null;
int ret = Interop.mincore.RegCreateKeyEx(hkey,
subkey,
0,
null,
(int)registryOptions /* specifies if the key is volatile */,
GetRegistryKeyAccess(writable) | (int)regView,
ref secAttrs,
out result,
out disposition);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
if (subkey.Length == 0)
key.keyName = keyName;
else
key.keyName = keyName + "\\" + subkey;
return key;
}
else if (ret != 0) // syscall failed, ret is an error code.
Win32Error(ret, keyName + "\\" + subkey); // Access denied?
Debug.Fail("Unexpected code path in RegistryKey::CreateSubKey");
return null;
}
/**
* Deletes the specified subkey. Will throw an exception if the subkey has
* subkeys. To delete a tree of subkeys use, DeleteSubKeyTree.
*
* @param subkey SubKey to delete.
*
* @exception InvalidOperationException thrown if the subkey has child subkeys.
*/
public void DeleteSubKey(String subkey)
{
DeleteSubKey(subkey, true);
}
[System.Security.SecuritySafeCritical]
public void DeleteSubKey(String subkey, bool throwOnMissingSubKey)
{
ValidateKeyName(subkey);
EnsureWriteable();
subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
// Open the key we are deleting and check for children. Be sure to
// explicitly call close to avoid keeping an extra HKEY open.
//
RegistryKey key = InternalOpenSubKey(subkey, false);
if (key != null)
{
try
{
if (key.InternalSubKeyCount() > 0)
{
ThrowHelper.ThrowInvalidOperationException(SR.InvalidOperation_RegRemoveSubKey);
}
}
finally
{
key.Close();
}
int ret = Interop.mincore.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
if (ret != 0)
{
if (ret == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
if (throwOnMissingSubKey)
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent);
}
else
Win32Error(ret, null);
}
}
else
{ // there is no key which also means there is no subkey
if (throwOnMissingSubKey)
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent);
}
}
/**
* Recursively deletes a subkey and any child subkeys.
*
* @param subkey SubKey to delete.
*/
public void DeleteSubKeyTree(String subkey)
{
DeleteSubKeyTree(subkey, true /*throwOnMissingSubKey*/);
}
[System.Security.SecuritySafeCritical]
public void DeleteSubKeyTree(String subkey, Boolean throwOnMissingSubKey)
{
ValidateKeyName(subkey);
// Security concern: Deleting a hive's "" subkey would delete all
// of that hive's contents. Don't allow "".
if (subkey.Length == 0 && IsSystemKey())
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyDelHive);
}
EnsureWriteable();
subkey = FixupName(subkey); // Fixup multiple slashes to a single slash
RegistryKey key = InternalOpenSubKey(subkey, true);
if (key != null)
{
try
{
if (key.InternalSubKeyCount() > 0)
{
String[] keys = key.InternalGetSubKeyNames();
for (int i = 0; i < keys.Length; i++)
{
key.DeleteSubKeyTreeInternal(keys[i]);
}
}
}
finally
{
key.Close();
}
int ret = Interop.mincore.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
if (ret != 0) Win32Error(ret, null);
}
else if (throwOnMissingSubKey)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent);
}
}
// An internal version which does no security checks or argument checking. Skipping the
// security checks should give us a slight perf gain on large trees.
[System.Security.SecurityCritical]
private void DeleteSubKeyTreeInternal(string subkey)
{
RegistryKey key = InternalOpenSubKey(subkey, true);
if (key != null)
{
try
{
if (key.InternalSubKeyCount() > 0)
{
String[] keys = key.InternalGetSubKeyNames();
for (int i = 0; i < keys.Length; i++)
{
key.DeleteSubKeyTreeInternal(keys[i]);
}
}
}
finally
{
key.Close();
}
int ret = Interop.mincore.RegDeleteKeyEx(hkey, subkey, (int)regView, 0);
if (ret != 0) Win32Error(ret, null);
}
else
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyAbsent);
}
}
/**
* Deletes the specified value from this key.
*
* @param name Name of value to delete.
*/
public void DeleteValue(String name)
{
DeleteValue(name, true);
}
[System.Security.SecuritySafeCritical]
public void DeleteValue(String name, bool throwOnMissingValue)
{
EnsureWriteable();
int errorCode = Interop.mincore.RegDeleteValue(hkey, name);
//
// From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
if (errorCode == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.mincore.Errors.ERROR_FILENAME_EXCED_RANGE)
{
if (throwOnMissingValue)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSubKeyValueAbsent);
}
else
{
// Otherwise, reset and just return giving no indication to the user.
// (For compatibility)
errorCode = 0;
}
}
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
/**
* Retrieves a new RegistryKey that represents the requested key. Valid
* values are:
*
* HKEY_CLASSES_ROOT,
* HKEY_CURRENT_USER,
* HKEY_LOCAL_MACHINE,
* HKEY_USERS,
* HKEY_PERFORMANCE_DATA,
* HKEY_CURRENT_CONFIG.
*
* @param hKey HKEY_* to open.
*
* @return the RegistryKey requested.
*/
[System.Security.SecurityCritical]
internal static RegistryKey GetBaseKey(IntPtr hKey)
{
return GetBaseKey(hKey, RegistryView.Default);
}
[System.Security.SecurityCritical]
internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view)
{
int index = ((int)hKey) & 0x0FFFFFFF;
Debug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!");
Debug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
// only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
RegistryKey key = new RegistryKey(srh, true, true, false, isPerf, view);
key.keyName = hkeyNames[index];
return key;
}
[System.Security.SecuritySafeCritical]
public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view)
{
ValidateKeyView(view);
return GetBaseKey((IntPtr)((int)hKey), view);
}
/**
* Retrieves a new RegistryKey that represents the requested key on a foreign
* machine. Valid values for hKey are members of the RegistryHive enum, or
* Win32 integers such as:
*
* HKEY_CLASSES_ROOT,
* HKEY_CURRENT_USER,
* HKEY_LOCAL_MACHINE,
* HKEY_USERS,
* HKEY_PERFORMANCE_DATA,
* HKEY_CURRENT_CONFIG.
*
* @param hKey HKEY_* to open.
* @param machineName the machine to connect to
*
* @return the RegistryKey requested.
*/
public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName)
{
return OpenRemoteBaseKey(hKey, machineName, RegistryView.Default);
}
[System.Security.SecuritySafeCritical]
public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view)
{
if (machineName == null)
throw new ArgumentNullException("machineName");
int index = (int)hKey & 0x0FFFFFFF;
if (index < 0 || index >= hkeyNames.Length || ((int)hKey & 0xFFFFFFF0) != 0x80000000)
{
throw new ArgumentException(SR.Arg_RegKeyOutOfRange);
}
ValidateKeyView(view);
// connect to the specified remote registry
SafeRegistryHandle foreignHKey = null;
int ret = Interop.mincore.RegConnectRegistry(machineName, new SafeRegistryHandle(new IntPtr((int)hKey), false), out foreignHKey);
if (ret == Interop.mincore.Errors.ERROR_DLL_INIT_FAILED)
// return value indicates an error occurred
throw new ArgumentException(SR.Arg_DllInitFailure);
if (ret != 0)
Win32ErrorStatic(ret, null);
if (foreignHKey.IsInvalid)
// return value indicates an error occurred
throw new ArgumentException(SR.Format(SR.Arg_RegKeyNoRemoteConnect, machineName));
RegistryKey key = new RegistryKey(foreignHKey, true, false, true, ((IntPtr)hKey) == HKEY_PERFORMANCE_DATA, view);
key.keyName = hkeyNames[index];
return key;
}
/**
* Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with
* read-only access.
*
* @param name Name or path of subkey to open.
* @param readonly Set to <b>true</b> if you only need readonly access.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
[System.Security.SecuritySafeCritical]
public RegistryKey OpenSubKey(string name, bool writable)
{
return InternalOpenSubKey(name, GetRegistryKeyAccess(writable));
}
public RegistryKey OpenSubKey(String name, RegistryRights rights)
{
return InternalOpenSubKey(name, (int)rights);
}
[System.Security.SecurityCritical]
private RegistryKey InternalOpenSubKey(String name, int rights)
{
ValidateKeyName(name);
EnsureNotDisposed();
name = FixupName(name); // Fixup multiple slashes to a single slash
SafeRegistryHandle result = null;
int ret = Interop.mincore.RegOpenKeyEx(hkey, name, 0, (rights | (int)regView), out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, IsWritable(rights), false, remoteKey, false, regView);
key.keyName = keyName + "\\" + name;
return key;
}
// Return null if we didn't find the key.
if (ret == Interop.mincore.Errors.ERROR_ACCESS_DENIED || ret == Interop.mincore.Errors.ERROR_BAD_IMPERSONATION_LEVEL)
{
// We need to throw SecurityException here for compatibility reason,
// although UnauthorizedAccessException will make more sense.
ThrowHelper.ThrowSecurityException(SR.Security_RegistryPermission);
}
return null;
}
// This required no security checks. This is to get around the Deleting SubKeys which only require
// write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks
[System.Security.SecurityCritical]
internal RegistryKey InternalOpenSubKey(String name, bool writable)
{
ValidateKeyName(name);
EnsureNotDisposed();
SafeRegistryHandle result = null;
int ret = Interop.mincore.RegOpenKeyEx(hkey,
name,
0,
GetRegistryKeyAccess(writable) | (int)regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
key.keyName = keyName + "\\" + name;
return key;
}
return null;
}
/**
* Returns a subkey with read only permissions.
*
* @param name Name or path of subkey to open.
*
* @return the Subkey requested, or <b>null</b> if the operation failed.
*/
[System.Security.SecurityCritical]
public RegistryKey OpenSubKey(String name)
{
return OpenSubKey(name, false);
}
/**
* Retrieves the count of subkeys.
*
* @return a count of subkeys.
*/
public int SubKeyCount
{
[System.Security.SecuritySafeCritical]
get
{
return InternalSubKeyCount();
}
}
public RegistryView View
{
[System.Security.SecuritySafeCritical]
get
{
EnsureNotDisposed();
return regView;
}
}
public SafeRegistryHandle Handle
{
[System.Security.SecurityCritical]
get
{
EnsureNotDisposed();
int ret = Interop.mincore.Errors.ERROR_INVALID_HANDLE;
if (IsSystemKey())
{
IntPtr baseKey = (IntPtr)0;
switch (keyName)
{
case "HKEY_CLASSES_ROOT":
baseKey = HKEY_CLASSES_ROOT;
break;
case "HKEY_CURRENT_USER":
baseKey = HKEY_CURRENT_USER;
break;
case "HKEY_LOCAL_MACHINE":
baseKey = HKEY_LOCAL_MACHINE;
break;
case "HKEY_USERS":
baseKey = HKEY_USERS;
break;
case "HKEY_PERFORMANCE_DATA":
baseKey = HKEY_PERFORMANCE_DATA;
break;
case "HKEY_CURRENT_CONFIG":
baseKey = HKEY_CURRENT_CONFIG;
break;
default:
Win32Error(ret, null);
break;
}
// open the base key so that RegistryKey.Handle will return a valid handle
SafeRegistryHandle result;
ret = Interop.mincore.RegOpenKeyEx(baseKey,
null,
0,
GetRegistryKeyAccess(IsWritable()) | (int)regView,
out result);
if (ret == 0 && !result.IsInvalid)
{
return result;
}
else
{
Win32Error(ret, null);
}
}
else
{
return hkey;
}
throw new IOException(Interop.mincore.GetMessage(ret), ret);
}
}
[System.Security.SecurityCritical]
public static RegistryKey FromHandle(SafeRegistryHandle handle)
{
return FromHandle(handle, RegistryView.Default);
}
[System.Security.SecurityCritical]
public static RegistryKey FromHandle(SafeRegistryHandle handle, RegistryView view)
{
if (handle == null) throw new ArgumentNullException("handle");
ValidateKeyView(view);
return new RegistryKey(handle, true /* isWritable */, view);
}
[System.Security.SecurityCritical]
internal int InternalSubKeyCount()
{
EnsureNotDisposed();
int subkeys = 0;
int junk = 0;
int ret = Interop.mincore.RegQueryInfoKey(hkey,
null,
null,
IntPtr.Zero,
ref subkeys, // subkeys
null,
null,
ref junk, // values
null,
null,
null,
null);
if (ret != 0)
Win32Error(ret, null);
return subkeys;
}
/**
* Retrieves an array of strings containing all the subkey names.
*
* @return all subkey names.
*/
[System.Security.SecurityCritical]
public String[] GetSubKeyNames()
{
return InternalGetSubKeyNames();
}
[System.Security.SecurityCritical]
internal unsafe String[] InternalGetSubKeyNames()
{
EnsureNotDisposed();
int subkeys = InternalSubKeyCount();
if (subkeys > 0)
{
String[] names = new String[subkeys];
char[] name = new char[MaxKeyLength + 1];
int namelen;
fixed (char* namePtr = &name[0])
{
for (int i = 0; i < subkeys; i++)
{
namelen = name.Length; // Don't remove this. The API's doesn't work if this is not properly initialized.
int ret = Interop.mincore.RegEnumKeyEx(hkey,
i,
namePtr,
ref namelen,
null,
null,
null,
null);
if (ret != 0)
Win32Error(ret, null);
names[i] = new String(namePtr);
}
}
return names;
}
return Array.Empty<String>();
}
/**
* Retrieves the count of values.
*
* @return a count of values.
*/
public int ValueCount
{
[System.Security.SecuritySafeCritical]
get
{
return InternalValueCount();
}
}
[System.Security.SecurityCritical]
internal int InternalValueCount()
{
EnsureNotDisposed();
int values = 0;
int junk = 0;
int ret = Interop.mincore.RegQueryInfoKey(hkey,
null,
null,
IntPtr.Zero,
ref junk, // subkeys
null,
null,
ref values, // values
null,
null,
null,
null);
if (ret != 0)
Win32Error(ret, null);
return values;
}
/**
* Retrieves an array of strings containing all the value names.
*
* @return all value names.
*/
[System.Security.SecuritySafeCritical]
public unsafe String[] GetValueNames()
{
EnsureNotDisposed();
int values = InternalValueCount();
if (values > 0)
{
String[] names = new String[values];
char[] name = new char[MaxValueLength + 1];
int namelen;
fixed (char* namePtr = &name[0])
{
for (int i = 0; i < values; i++)
{
namelen = name.Length;
int ret = Interop.mincore.RegEnumValue(hkey,
i,
namePtr,
ref namelen,
IntPtr.Zero,
null,
null,
null);
if (ret != 0)
{
// ignore ERROR_MORE_DATA if we're querying HKEY_PERFORMANCE_DATA
if (!(IsPerfDataKey() && ret == Interop.mincore.Errors.ERROR_MORE_DATA))
Win32Error(ret, null);
}
names[i] = new String(namePtr);
}
}
return names;
}
return Array.Empty<String>();
}
/**
* Retrieves the specified value. <b>null</b> is returned if the value
* doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
*
* @param name Name of value to retrieve.
*
* @return the data associated with the value.
*/
[System.Security.SecuritySafeCritical]
public Object GetValue(String name)
{
return InternalGetValue(name, null, false, true);
}
/**
* Retrieves the specified value. <i>defaultValue</i> is returned if the value doesn't exist.
*
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
* The default values for RegistryKeys are OS-dependent. NT doesn't
* have them by default, but they can exist and be of any type. On
* Win95, the default value is always an empty key of type REG_SZ.
* Win98 supports default values of any type, but defaults to REG_SZ.
*
* @param name Name of value to retrieve.
* @param defaultValue Value to return if <i>name</i> doesn't exist.
*
* @return the data associated with the value.
*/
[System.Security.SecuritySafeCritical]
public Object GetValue(String name, Object defaultValue)
{
return InternalGetValue(name, defaultValue, false, true);
}
[System.Security.SecuritySafeCritical]
public Object GetValue(String name, Object defaultValue, RegistryValueOptions options)
{
if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), "options");
}
bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
return InternalGetValue(name, defaultValue, doNotExpand, true);
}
[System.Security.SecurityCritical]
internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity)
{
if (checkSecurity)
{
// Name can be null! It's the most common use of RegQueryValueEx
EnsureNotDisposed();
}
Object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
{
if (IsPerfDataKey())
{
int size = 65000;
int sizeInput = size;
int r;
byte[] blob = new byte[size];
while (Interop.mincore.Errors.ERROR_MORE_DATA == (r = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput)))
{
if (size == Int32.MaxValue)
{
// ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
Win32Error(r, name);
}
else if (size > (Int32.MaxValue / 2))
{
// at this point in the loop "size * 2" would cause an overflow
size = Int32.MaxValue;
}
else
{
size *= 2;
}
sizeInput = size;
blob = new byte[size];
}
if (r != 0)
Win32Error(r, name);
return blob;
}
else
{
// For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
// Some OS's returned ERROR_MORE_DATA even in success cases, so we
// want to continue on through the function.
if (ret != Interop.mincore.Errors.ERROR_MORE_DATA)
return data;
}
}
if (datasize < 0)
{
// unexpected code path
Debug.Fail("[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
switch (type)
{
case Interop.mincore.RegistryValues.REG_NONE:
case Interop.mincore.RegistryValues.REG_DWORD_BIG_ENDIAN:
case Interop.mincore.RegistryValues.REG_BINARY:
{
byte[] blob = new byte[datasize];
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_QWORD:
{ // also REG_QWORD_LITTLE_ENDIAN
if (datasize > 8)
{
// prevent an AV in the edge case that datasize is larger than sizeof(long)
goto case Interop.mincore.RegistryValues.REG_BINARY;
}
long blob = 0;
Debug.Assert(datasize == 8, "datasize==8");
// Here, datasize must be 8 when calling this
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_DWORD:
{ // also REG_DWORD_LITTLE_ENDIAN
if (datasize > 4)
{
// prevent an AV in the edge case that datasize is larger than sizeof(int)
goto case Interop.mincore.RegistryValues.REG_QWORD;
}
int blob = 0;
Debug.Assert(datasize == 4, "datasize==4");
// Here, datasize must be four when calling this
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
data = blob;
}
break;
case Interop.mincore.RegistryValues.REG_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
}
break;
case Interop.mincore.RegistryValues.REG_EXPAND_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
data = new String(blob, 0, blob.Length - 1);
}
else
{
// in the very unlikely case the data is missing null termination,
// pass in the whole char[] to prevent truncating a character
data = new String(blob);
}
if (!doNotExpand)
data = Environment.ExpandEnvironmentVariables((String)data);
}
break;
case Interop.mincore.RegistryValues.REG_MULTI_SZ:
{
if (datasize % 2 == 1)
{
// handle the case where the registry contains an odd-byte length (corrupt data?)
try
{
datasize = checked(datasize + 1);
}
catch (OverflowException e)
{
throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
}
char[] blob = new char[datasize / 2];
ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
// make sure the string is null terminated before processing the data
if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
Array.Resize(ref blob, blob.Length + 1);
}
var strings = new List<String>();
int cur = 0;
int len = blob.Length;
while (ret == 0 && cur < len)
{
int nextNull = cur;
while (nextNull < len && blob[nextNull] != (char)0)
{
nextNull++;
}
if (nextNull < len)
{
Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
if (nextNull - cur > 0)
{
strings.Add(new String(blob, cur, nextNull - cur));
}
else
{
// we found an empty string. But if we're at the end of the data,
// it's just the extra null terminator.
if (nextNull != len - 1)
strings.Add(String.Empty);
}
}
else
{
strings.Add(new String(blob, cur, len - cur));
}
cur = nextNull + 1;
}
data = strings.ToArray();
}
break;
case Interop.mincore.RegistryValues.REG_LINK:
default:
break;
}
return data;
}
[System.Security.SecuritySafeCritical]
public RegistryValueKind GetValueKind(string name)
{
EnsureNotDisposed();
int type = 0;
int datasize = 0;
int ret = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
if (ret != 0)
Win32Error(ret, null);
if (type == Interop.mincore.RegistryValues.REG_NONE)
return RegistryValueKind.None;
else if (!Enum.IsDefined(typeof(RegistryValueKind), type))
return RegistryValueKind.Unknown;
else
return (RegistryValueKind)type;
}
/**
* Retrieves the current state of the dirty property.
*
* A key is marked as dirty if any operation has occurred that modifies the
* contents of the key.
*
* @return <b>true</b> if the key has been modified.
*/
private bool IsDirty()
{
return (this.state & STATE_DIRTY) != 0;
}
private bool IsSystemKey()
{
return (this.state & STATE_SYSTEMKEY) != 0;
}
private bool IsWritable()
{
return (this.state & STATE_WRITEACCESS) != 0;
}
private bool IsPerfDataKey()
{
return (this.state & STATE_PERF_DATA) != 0;
}
public String Name
{
[System.Security.SecuritySafeCritical]
get
{
EnsureNotDisposed();
return keyName;
}
}
private void SetDirty()
{
this.state |= STATE_DIRTY;
}
/**
* Sets the specified value.
*
* @param name Name of value to store data in.
* @param value Data to store.
*/
public void SetValue(String name, Object value)
{
SetValue(name, value, RegistryValueKind.Unknown);
}
[System.Security.SecuritySafeCritical]
public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException("value");
if (name != null && name.Length > MaxValueLength)
{
throw new ArgumentException(SR.Arg_RegValStrLenBug);
}
if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
throw new ArgumentException(SR.Arg_RegBadKeyKind, "valueKind");
EnsureWriteable();
if (valueKind == RegistryValueKind.Unknown)
{
// this is to maintain compatibility with the old way of autodetecting the type.
// SetValue(string, object) will come through this codepath.
valueKind = CalculateValueKind(value);
}
int ret = 0;
try
{
switch (valueKind)
{
case RegistryValueKind.ExpandString:
case RegistryValueKind.String:
{
String data = value.ToString();
ret = Interop.mincore.RegSetValueEx(hkey,
name,
0,
valueKind,
data,
checked(data.Length * 2 + 2));
break;
}
case RegistryValueKind.MultiString:
{
// Other thread might modify the input array after we calculate the buffer length.
// Make a copy of the input array to be safe.
string[] dataStrings = (string[])(((string[])value).Clone());
// First determine the size of the array
//
// Format is null terminator between strings and final null terminator at the end.
// e.g. str1\0str2\0str3\0\0
//
int sizeInChars = 1; // no matter what, we have the final null terminator.
for (int i = 0; i < dataStrings.Length; i++)
{
if (dataStrings[i] == null)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetStrArrNull);
}
sizeInChars = checked(sizeInChars + (dataStrings[i].Length + 1));
}
int sizeInBytes = checked(sizeInChars * sizeof(char));
// Write out the strings...
//
char[] dataChars = new char[sizeInChars];
int destinationIndex = 0;
for (int i = 0; i < dataStrings.Length; i++)
{
int length = dataStrings[i].Length;
dataStrings[i].CopyTo(0, dataChars, destinationIndex, length);
destinationIndex += (length + 1); // +1 for null terminator, which is already zero-initialized in new array.
}
ret = Interop.mincore.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.MultiString,
dataChars,
sizeInBytes);
break;
}
case RegistryValueKind.None:
case RegistryValueKind.Binary:
byte[] dataBytes = (byte[])value;
ret = Interop.mincore.RegSetValueEx(hkey,
name,
0,
(valueKind == RegistryValueKind.None ? Interop.mincore.RegistryValues.REG_NONE : RegistryValueKind.Binary),
dataBytes,
dataBytes.Length);
break;
case RegistryValueKind.DWord:
{
// We need to use Convert here because we could have a boxed type cannot be
// unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.mincore.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.DWord,
ref data,
4);
break;
}
case RegistryValueKind.QWord:
{
long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
ret = Interop.mincore.RegSetValueEx(hkey,
name,
0,
RegistryValueKind.QWord,
ref data,
8);
break;
}
}
}
catch (OverflowException)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
}
catch (InvalidOperationException)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
}
catch (FormatException)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
}
catch (InvalidCastException)
{
ThrowHelper.ThrowArgumentException(SR.Arg_RegSetMismatchedKind);
}
if (ret == 0)
{
SetDirty();
}
else
Win32Error(ret, null);
}
private RegistryValueKind CalculateValueKind(Object value)
{
// This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days.
// Even though we could add detection for an int64 in here, we want to maintain compatibility with the
// old behavior.
if (value is Int32)
return RegistryValueKind.DWord;
else if (value is Array)
{
if (value is byte[])
return RegistryValueKind.Binary;
else if (value is String[])
return RegistryValueKind.MultiString;
else
throw new ArgumentException(SR.Format(SR.Arg_RegSetBadArrType, value.GetType().Name));
}
else
return RegistryValueKind.String;
}
/**
* Retrieves a string representation of this key.
*
* @return a string representing the key.
*/
[System.Security.SecuritySafeCritical]
public override String ToString()
{
EnsureNotDisposed();
return keyName;
}
/**
* After calling GetLastWin32Error(), it clears the last error field,
* so you must save the HResult and pass it to this method. This method
* will determine the appropriate exception to throw dependent on your
* error, and depending on the error, insert a string into the message
* gotten from the ResourceManager.
*/
[System.Security.SecuritySafeCritical]
internal void Win32Error(int errorCode, String str)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_ACCESS_DENIED:
if (str != null)
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str));
else
throw new UnauthorizedAccessException();
case Interop.mincore.Errors.ERROR_INVALID_HANDLE:
/**
* For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
* However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
* SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
* in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
* on reentrant calls because of this error code path in RegistryKey
*
* Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
* however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
* this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
* having serialized access).
*
*/
if (!IsPerfDataKey())
{
this.hkey.SetHandleAsInvalid();
this.hkey = null;
}
goto default;
case Interop.mincore.Errors.ERROR_FILE_NOT_FOUND:
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Interop.mincore.GetMessage(errorCode), errorCode);
}
}
[System.Security.SecuritySafeCritical]
internal static void Win32ErrorStatic(int errorCode, String str)
{
switch (errorCode)
{
case Interop.mincore.Errors.ERROR_ACCESS_DENIED:
if (str != null)
throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str));
else
throw new UnauthorizedAccessException();
default:
throw new IOException(Interop.mincore.GetMessage(errorCode), errorCode);
}
}
internal static String FixupName(String name)
{
Debug.Assert(name != null, "[FixupName]name!=null");
if (name.IndexOf('\\') == -1)
return name;
StringBuilder sb = new StringBuilder(name);
FixupPath(sb);
int temp = sb.Length - 1;
if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash
sb.Length = temp;
return sb.ToString();
}
private static void FixupPath(StringBuilder path)
{
Contract.Requires(path != null);
int length = path.Length;
bool fixup = false;
char markerChar = (char)0xFFFF;
int i = 1;
while (i < length - 1)
{
if (path[i] == '\\')
{
i++;
while (i < length)
{
if (path[i] == '\\')
{
path[i] = markerChar;
i++;
fixup = true;
}
else
break;
}
}
i++;
}
if (fixup)
{
i = 0;
int j = 0;
while (i < length)
{
if (path[i] == markerChar)
{
i++;
continue;
}
path[j] = path[i];
i++;
j++;
}
path.Length += j - i;
}
}
[System.Security.SecurityCritical]
private bool ContainsRegistryValue(string name)
{
int type = 0;
int datasize = 0;
int retval = Interop.mincore.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
return retval == 0;
}
[System.Security.SecurityCritical]
private void EnsureNotDisposed()
{
if (hkey == null)
{
ThrowHelper.ThrowObjectDisposedException(keyName, SR.ObjectDisposed_RegKeyClosed);
}
}
[System.Security.SecurityCritical]
private void EnsureWriteable()
{
EnsureNotDisposed();
if (!IsWritable())
{
ThrowHelper.ThrowUnauthorizedAccessException(SR.UnauthorizedAccess_RegistryNoWrite);
}
}
static int GetRegistryKeyAccess(bool isWritable)
{
int winAccess;
if (!isWritable)
{
winAccess = Interop.mincore.RegistryOperations.KEY_READ;
}
else
{
winAccess = Interop.mincore.RegistryOperations.KEY_READ | Interop.mincore.RegistryOperations.KEY_WRITE;
}
return winAccess;
}
static bool IsWritable(int rights)
{
return (rights & (Interop.mincore.RegistryOperations.KEY_SET_VALUE |
Interop.mincore.RegistryOperations.KEY_CREATE_SUB_KEY |
(int)RegistryRights.Delete |
(int)RegistryRights.TakeOwnership |
(int)RegistryRights.ChangePermissions)) != 0;
}
static private void ValidateKeyName(string name)
{
Contract.Ensures(name != null);
if (name == null)
{
ThrowHelper.ThrowArgumentNullException("name");
}
int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase);
int current = 0;
while (nextSlash != -1)
{
if ((nextSlash - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyStrLenBug);
current = nextSlash + 1;
nextSlash = name.IndexOf("\\", current, StringComparison.OrdinalIgnoreCase);
}
if ((name.Length - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(SR.Arg_RegKeyStrLenBug);
}
static private void ValidateKeyOptions(RegistryOptions options)
{
if (options < RegistryOptions.None || options > RegistryOptions.Volatile)
{
ThrowHelper.ThrowArgumentException(SR.Argument_InvalidRegistryOptionsCheck, "options");
}
}
static private void ValidateKeyView(RegistryView view)
{
if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64)
{
ThrowHelper.ThrowArgumentException(SR.Argument_InvalidRegistryViewCheck, "view");
}
}
}
[Flags]
public enum RegistryValueOptions
{
None = 0,
DoNotExpandEnvironmentNames = 1
}
}
| mit |
hustlzp/pagekit | app/modules/application/index.php | 1303 | <?php
use Pagekit\Application\Response;
use Pagekit\Application\UrlProvider;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler;
return [
'name' => 'application',
'main' => function ($app) {
$app['version'] = function () {
return $this->config['version'];
};
$app['debug'] = function () {
return (bool)$this->config['debug'];
};
$app['url'] = function ($app) {
return new UrlProvider($app['router'], $app['file'], $app['locator']);
};
$app['response'] = function ($app) {
return new Response($app['url']);
};
$app['exception'] = ExceptionHandler::register($app['debug']);
ErrorHandler::register(E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR);
if ($app->inConsole() || $app['debug']) {
ini_set('display_errors', 1);
} else {
ini_set('display_errors', 0);
}
},
'require' => [
'debug',
'routing',
'auth',
'config',
'cookie',
'database',
'filesystem',
'log',
'session',
'view'
],
'config' => [
'version' => '',
'debug' => false
]
];
| mit |
sufuf3/cdnjs | ajax/libs/pnp-logging/1.0.1/logging.js | 5231 | /**
@license
* @pnp/logging v1.0.1 - pnp - light-weight, subscribable logging framework
* MIT (https://github.com/pnp/pnp/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: http://officedev.github.io/PnP-JS-Core
* source: https://github.com/pnp/pnp
* bugs: https://github.com/pnp/pnp/issues
*/
/**
* Class used to subscribe ILogListener and log messages throughout an application
*
*/
class Logger {
/**
* Gets or sets the active log level to apply for log filtering
*/
static get activeLogLevel() {
return Logger.instance.activeLogLevel;
}
static set activeLogLevel(value) {
Logger.instance.activeLogLevel = value;
}
static get instance() {
if (typeof Logger._instance === "undefined" || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
}
/**
* Adds ILogListener instances to the set of subscribed listeners
*
* @param listeners One or more listeners to subscribe to this log
*/
static subscribe(...listeners) {
listeners.map(listener => Logger.instance.subscribe(listener));
}
/**
* Clears the subscribers collection, returning the collection before modifiction
*/
static clearSubscribers() {
return Logger.instance.clearSubscribers();
}
/**
* Gets the current subscriber count
*/
static get count() {
return Logger.instance.count;
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param message The message to write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static write(message, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: message });
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param json The json object to stringify and write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static writeJSON(json, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: JSON.stringify(json) });
}
/**
* Logs the supplied entry to the subscribed listeners
*
* @param entry The message to log
*/
static log(entry) {
Logger.instance.log(entry);
}
/**
* Logs an error object to the subscribed listeners
*
* @param err The error object
*/
static error(err) {
Logger.instance.log({ data: err, level: 3 /* Error */, message: err.message });
}
}
class LoggerImpl {
constructor(activeLogLevel = 2 /* Warning */, subscribers = []) {
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
subscribe(listener) {
this.subscribers.push(listener);
}
clearSubscribers() {
const s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
}
get count() {
return this.subscribers.length;
}
write(message, level = 0 /* Verbose */) {
this.log({ level: level, message: message });
}
log(entry) {
if (typeof entry !== "undefined" && this.activeLogLevel <= entry.level) {
this.subscribers.map(subscriber => subscriber.log(entry));
}
}
}
/**
* Implementation of LogListener which logs to the console
*
*/
class ConsoleListener {
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
const msg = this.format(entry);
switch (entry.level) {
case 0 /* Verbose */:
case 1 /* Info */:
console.log(msg);
break;
case 2 /* Warning */:
console.warn(msg);
break;
case 3 /* Error */:
console.error(msg);
break;
}
}
/**
* Formats the message
*
* @param entry The information to format into a string
*/
format(entry) {
const msg = [];
msg.push("Message: " + entry.message);
if (typeof entry.data !== "undefined") {
msg.push(" Data: " + JSON.stringify(entry.data));
}
return msg.join("");
}
}
/**
* Implementation of LogListener which logs to the supplied function
*
*/
class FunctionListener {
/**
* Creates a new instance of the FunctionListener class
*
* @constructor
* @param method The method to which any logging data will be passed
*/
constructor(method) {
this.method = method;
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
this.method(entry);
}
}
export { Logger, ConsoleListener, FunctionListener };
//# sourceMappingURL=logging.js.map
| mit |
anhyeuviolet/flat-manga | ms-data-base/language/it/lang.php | 4413 | <?php
$lang['L_YES']="sì";
$lang['L_TO']="fino a";
$lang['L_ACTIVATED']="attivato";
$lang['L_NOT_ACTIVATED']="non attivato";
$lang['L_ERROR']="Errore";
$lang['L_OF']=" di ";
$lang['L_ADDED']="aggiunto";
$lang['L_DB']="Database";
$lang['L_DBS']="Database";
$lang['L_TABLES']="Tabelle";
$lang['L_TABLE']="Tabella";
$lang['L_RECORDS']="Record";
$lang['L_COMPRESSED']="compresso (gz)";
$lang['L_NOTCOMPRESSED']="normale (non compresso)";
$lang['L_GENERAL']="generale";
$lang['L_COMMENT']="commento";
$lang['L_FILESIZE']="Grandezza file";
$lang['L_ALL']="tutti";
$lang['L_NONE']="nessuno";
$lang['L_WITH']=" con ";
$lang['L_DIR']="Directory";
$lang['L_RECHTE']="Diritti";
$lang['L_STATUS']="Stato ";
$lang['L_FINISHED']="terminato";
$lang['L_FILE']="File";
$lang['L_FIELDS']="campi";
$lang['L_NEW']="nuovo";
$lang['L_CHARSET']="Set di caratteri";
$lang['L_COLLATION']="Ordinamento";
$lang['L_CHANGE']="cambia";
$lang['L_IN']="in";
$lang['L_DO']="esegui";
$lang['L_VIEW']="visualizza";
$lang['L_EXISTING']="esistente";
$lang['L_BACK']="indietro";
$lang['L_DB_HOST']="Hostname del database";
$lang['L_DB_USER']="User del database";
$lang['L_DB_PASS']="Password del database";
$lang['L_INFO_SCRIPTDIR']="Indice di MySQLDumper";
$lang['L_INFO_ACTDB']="Database selezionato";
$lang['L_WRONGCONNECTIONPARS']="Parametri di connessione assenti o errati!";
$lang['L_CONN_NOT_POSSIBLE']="Collegamento non possibile !";
$lang['L_SERVERCAPTION']="Visualizzazione del server";
$lang['L_HELP_SERVERCAPTION']="Con l`uso di sistemi differenti potrebbe essere di aiuto visualizzare l'indirizzo del server in un altro colore ";
$lang['L_ACTIVATE_MULTIDUMP']="Attiva multidump";
$lang['L_SAVE']="Salva";
$lang['L_RESET']="Resetta";
$lang['L_PRAEFIX']="Prefissi tabella";
$lang['L_AUTODELETE']="cancella backups automaticamente";
$lang['L_MAX_BACKUP_FILES_EACH2']="per ogni database";
$lang['L_SAVING_DB_FORM']="Database";
$lang['L_TESTCONNECTION']="Verifica la connessione";
$lang['L_BACK_TO_MINISQL']="Elaborare database";
$lang['L_CREATE']="crea";
$lang['L_VARIABELN']="Variabili";
$lang['L_STATUSINFORMATIONEN']="Informazioni sullo stato";
$lang['L_VERSIONSINFORMATIONEN']="Informazioni sulla versione";
$lang['L_MSD_INFO']="Informazioni su MySQLDumper";
$lang['L_BACKUPFILESANZAHL']="Nella directory dei backup ci sono";
$lang['L_LASTBACKUP']="Ultimo backup";
$lang['L_NOTAVAIL']="<em>non disponibile</em>";
$lang['L_VOM']="dal";
$lang['L_MYSQLVARS']="Variabili Mysql";
$lang['L_MYSQLSYS']="Comandi Mysql";
$lang['L_STATUS']="Stato";
$lang['L_PROZESSE']="Processi";
$lang['L_INFO_NOVARS']="nessuna variabile disponibile";
$lang['L_INHALT']="Contenuto";
$lang['L_INFO_NOSTATUS']="stato non disponibile";
$lang['L_INFO_NOPROCESSES']="nessun processo in corso";
$lang['L_FM_FREESPACE']="Memoria disponibile sul server";
$lang['L_LOAD_DATABASE']="Ricarica database";
$lang['L_HOME']="Pagina iniziale";
$lang['L_CONFIG']="Configurazione";
$lang['L_DUMP']="Backup";
$lang['L_RESTORE']="Ripristina";
$lang['L_FILE_MANAGE']="Amministrazione file";
$lang['L_LOG']="Log";
$lang['L_CHOOSE_DB']="Seleziona database";
$lang['L_CREDITS']="Crediti/Aiuto";
$lang['L_MULTI_PART']="Backup in più parti";
$lang['L_LOGFILENOTWRITABLE']="Il logfile non può essere scritto!";
$lang['L_SQL_ERROR1']="Errore nella richiesta:";
$lang['L_SQL_ERROR2']="MySQL dice:";
$lang['L_UNKNOWN']="sconosciuto";
$lang['L_UNKNOWN_NUMBER_OF_RECORDS']="sconosciuto";
$lang['L_OK']="OK.";
$lang['L_CRON_COMPLETELOG']="Salvare tutte le operazioni";
$lang['L_NO']="no";
$lang['L_CREATE_DATABASE']="Crea nuovo database";
$lang['L_EXPORTFINISHED']="Esportazione completata.";
$lang['L_SQL_BROWSER']="SQL-Browser";
$lang['L_SERVER']="Server";
$lang['L_MYSQL_CONNECTION_ENCODING']="Codifica standard dei MySQL-Servers";
$lang['L_TITLE_SHOW_DATA']="Visualizza dati";
$lang['L_PRIMARYKEY_CONFIRMDELETE']="Vuoi cancellare veramente la chiave primaria?";
$lang['L_SETPRIMARYKEYSFOR']="Inserisci nuova chiave primaria per la tabella";
$lang['L_PRIMARYKEY_FIELD']="Campo chiave primaria";
$lang['L_PRIMARYKEYS_SAVE']="Salva chiave primaria";
$lang['L_CANCEL']="Cancella";
$lang['L_VISIT_HOMEPAGE']="Visit Homepage";
$lang['L_SECONDS']="Seconds";
$lang['L_BACKUPS']="Backups";
$lang['L_MINUTES']="Minutes";
$lang['L_PAGE_REFRESHS']="Page refreshs";
$lang['L_MINUTE']="Minute";
$lang['L_SETKEYSFOR']="Set new indexes for table";
$lang['L_KEY_CONFIRMDELETE']="Really delete index?";
?> | mit |
dushmis/three.js | rollup.config.js | 597 | import * as fs from 'fs';
var outro = `
Object.defineProperty( exports, 'AudioContext', {
get: function () {
return exports.getAudioContext();
}
});`;
function glsl () {
return {
transform ( code, id ) {
if ( !/\.glsl$/.test( id ) ) return;
return 'export default ' + JSON.stringify(
code
.replace( /[ \t]*\/\/.*\n/g, '' )
.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' )
.replace( /\n{2,}/g, '\n' )
) + ';';
}
};
}
export default {
entry: 'src/Three.js',
dest: 'build/three.js',
moduleName: 'THREE',
format: 'umd',
plugins: [
glsl()
],
outro: outro
};
| mit |
sufuf3/cdnjs | ajax/libs/styled-components/3.2.6/styled-components-primitives.cjs.js | 173131 | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var reactPrimitives = _interopDefault(require('react-primitives'));
var transformDeclPairs = _interopDefault(require('css-to-react-native'));
var isPlainObject = _interopDefault(require('is-plain-object'));
var supportsColor = _interopDefault(require('supports-color'));
var React = require('react');
var React__default = _interopDefault(React);
var PropTypes = _interopDefault(require('prop-types'));
var reactIs = require('react-is');
var hoistStatics = _interopDefault(require('hoist-non-react-statics'));
// Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
function murmurhash(str) {
var l = str.length | 0,
h = l | 0,
i = 0,
k;
while (l >= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
k ^= k >>> 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
}
h ^= h >>> 13;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h ^= h >>> 15;
return h >>> 0;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @typechecks
*/
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate$2(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
var hyphenate_1 = hyphenate$2;
var hyphenate = hyphenate_1;
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
var hyphenateStyleName_1 = hyphenateStyleName;
//
var objToCss = function objToCss(obj, prevKey) {
var css = Object.keys(obj).filter(function (key) {
var chunk = obj[key];
return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
}).map(function (key) {
if (isPlainObject(obj[key])) return objToCss(obj[key], key);
return hyphenateStyleName_1(key) + ': ' + obj[key] + ';';
}).join(' ');
return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
};
var flatten = function flatten(chunks, executionContext) {
return chunks.reduce(function (ruleSet, chunk) {
/* Remove falsey values */
if (chunk === undefined || chunk === null || chunk === false || chunk === '') {
return ruleSet;
}
/* Flatten ruleSet */
if (Array.isArray(chunk)) {
return [].concat(ruleSet, flatten(chunk, executionContext));
}
/* Handle other components */
if (chunk.hasOwnProperty('styledComponentId')) {
// $FlowFixMe not sure how to make this pass
return [].concat(ruleSet, ['.' + chunk.styledComponentId]);
}
/* Either execute or defer the function */
if (typeof chunk === 'function') {
return executionContext ? ruleSet.concat.apply(ruleSet, flatten([chunk(executionContext)], executionContext)) : ruleSet.concat(chunk);
}
/* Handle objects */
return ruleSet.concat(
// $FlowFixMe have to add %checks somehow to isPlainObject
isPlainObject(chunk) ? objToCss(chunk) : chunk.toString());
}, []);
};
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
var SINGLE_QUOTE = '\''.charCodeAt(0);
var DOUBLE_QUOTE = '"'.charCodeAt(0);
var BACKSLASH = '\\'.charCodeAt(0);
var SLASH = '/'.charCodeAt(0);
var NEWLINE = '\n'.charCodeAt(0);
var SPACE = ' '.charCodeAt(0);
var FEED = '\f'.charCodeAt(0);
var TAB = '\t'.charCodeAt(0);
var CR = '\r'.charCodeAt(0);
var OPEN_SQUARE = '['.charCodeAt(0);
var CLOSE_SQUARE = ']'.charCodeAt(0);
var OPEN_PARENTHESES = '('.charCodeAt(0);
var CLOSE_PARENTHESES = ')'.charCodeAt(0);
var OPEN_CURLY = '{'.charCodeAt(0);
var CLOSE_CURLY = '}'.charCodeAt(0);
var SEMICOLON = ';'.charCodeAt(0);
var ASTERISK = '*'.charCodeAt(0);
var COLON = ':'.charCodeAt(0);
var AT = '@'.charCodeAt(0);
var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
function tokenize(input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var tokens = [];
var css = input.css.valueOf();
var ignore = options.ignoreErrors;
var code = void 0,
next = void 0,
quote = void 0,
lines = void 0,
last = void 0,
content = void 0,
escape = void 0,
nextLine = void 0,
nextOffset = void 0,
escaped = void 0,
escapePos = void 0,
prev = void 0,
n = void 0;
var length = css.length;
var offset = -1;
var line = 1;
var pos = 0;
function unclosed(what) {
throw input.error('Unclosed ' + what, line, pos - offset);
}
while (pos < length) {
code = css.charCodeAt(pos);
if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
offset = pos;
line += 1;
}
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if (code === NEWLINE) {
offset = next;
line += 1;
}
} while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
tokens.push(['space', css.slice(pos, next)]);
pos = next - 1;
break;
case OPEN_SQUARE:
tokens.push(['[', '[', line, pos - offset]);
break;
case CLOSE_SQUARE:
tokens.push([']', ']', line, pos - offset]);
break;
case OPEN_CURLY:
tokens.push(['{', '{', line, pos - offset]);
break;
case CLOSE_CURLY:
tokens.push(['}', '}', line, pos - offset]);
break;
case COLON:
tokens.push([':', ':', line, pos - offset]);
break;
case SEMICOLON:
tokens.push([';', ';', line, pos - offset]);
break;
case OPEN_PARENTHESES:
prev = tokens.length ? tokens[tokens.length - 1][1] : '';
n = css.charCodeAt(pos + 1);
if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore) {
next = pos;
break;
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
tokens.push(['(', '(', line, pos - offset]);
} else {
tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
tokens.push([')', ')', line, pos - offset]);
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? '\'' : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore) {
next = pos + 1;
break;
} else {
unclosed('quote');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
next += 1;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
default:
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore) {
next = css.length;
} else {
unclosed('comment');
}
}
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
}
break;
}
pos++;
}
return tokens;
}
var HIGHLIGHT_THEME = {
'brackets': [36, 39], // cyan
'string': [31, 39], // red
'at-word': [31, 39], // red
'comment': [90, 39], // gray
'{': [32, 39], // green
'}': [32, 39], // green
':': [1, 22], // bold
';': [1, 22], // bold
'(': [1, 22], // bold
')': [1, 22] // bold
};
function code(color) {
return '\x1B[' + color + 'm';
}
function terminalHighlight(css) {
var tokens = tokenize(new Input(css), { ignoreErrors: true });
var result = [];
tokens.forEach(function (token) {
var color = HIGHLIGHT_THEME[token[0]];
if (color) {
result.push(token[1].split(/\r?\n/).map(function (i) {
return code(color[0]) + i + code(color[1]);
}).join('\n'));
} else {
result.push(token[1]);
}
});
return result.join('');
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the {@link Node#error} method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* @example
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
* }
*
* @example
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' });
*/
var CssSyntaxError = function () {
/**
* @param {string} message - error message
* @param {number} [line] - source line of the error
* @param {number} [column] - source column of the error
* @param {string} [source] - source code of the broken file
* @param {string} [file] - absolute path to the broken file
* @param {string} [plugin] - PostCSS plugin name, if error came from plugin
*/
function CssSyntaxError(message, line, column, source, file, plugin) {
classCallCheck(this, CssSyntaxError);
/**
* @member {string} - Always equal to `'CssSyntaxError'`. You should
* always check error type
* by `error.name === 'CssSyntaxError'` instead of
* `error instanceof CssSyntaxError`, because
* npm could have several PostCSS versions.
*
* @example
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
*/
this.name = 'CssSyntaxError';
/**
* @member {string} - Error message.
*
* @example
* error.message //=> 'Unclosed block'
*/
this.reason = message;
if (file) {
/**
* @member {string} - Absolute path to the broken file.
*
* @example
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
*/
this.file = file;
}
if (source) {
/**
* @member {string} - Source code of the broken file.
*
* @example
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
*/
this.source = source;
}
if (plugin) {
/**
* @member {string} - Plugin name, if error came from plugin.
*
* @example
* error.plugin //=> 'postcss-vars'
*/
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
/**
* @member {number} - Source line of the error.
*
* @example
* error.line //=> 2
* error.input.line //=> 4
*/
this.line = line;
/**
* @member {number} - Source column of the error.
*
* @example
* error.column //=> 1
* error.input.column //=> 4
*/
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
CssSyntaxError.prototype.setMessage = function setMessage() {
/**
* @member {string} - Full error text in the GNU error format
* with plugin, file, line and column.
*
* @example
* error.message //=> 'a.css:1:1: Unclosed block'
*/
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
};
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* @param {boolean} [color] whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
*
* @example
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
*
* @return {string} few lines of CSS source that caused the error
*/
CssSyntaxError.prototype.showSourceCode = function showSourceCode(color) {
var _this = this;
if (!this.source) return '';
var css = this.source;
if (typeof color === 'undefined') color = supportsColor;
if (color) css = terminalHighlight(css);
var lines = css.split(/\r?\n/);
var start = Math.max(this.line - 3, 0);
var end = Math.min(this.line + 2, lines.length);
var maxWidth = String(end).length;
return lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var padded = (' ' + number).slice(-maxWidth);
var gutter = ' ' + padded + ' | ';
if (number === _this.line) {
var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
return '>' + gutter + line + '\n ' + spacing + '^';
} else {
return ' ' + gutter + line;
}
}).join('\n');
};
/**
* Returns error position, message and source code of the broken part.
*
* @example
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
*
* @return {string} error position, message and source code
*/
CssSyntaxError.prototype.toString = function toString() {
var code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code;
};
createClass(CssSyntaxError, [{
key: 'generated',
get: function get$$1() {
warnOnce('CssSyntaxError#generated is depreacted. Use input instead.');
return this.input;
}
/**
* @memberof CssSyntaxError#
* @member {Input} input - Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* @example
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
*/
}]);
return CssSyntaxError;
}();
/* eslint-disable valid-jsdoc */
var defaultRaw = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' '
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = function () {
function Stringifier(builder) {
classCallCheck(this, Stringifier);
this.builder = builder;
}
Stringifier.prototype.stringify = function stringify(node, semicolon) {
this[node.type](node, semicolon);
};
Stringifier.prototype.root = function root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
};
Stringifier.prototype.comment = function comment(node) {
var left = this.raw(node, 'left', 'commentLeft');
var right = this.raw(node, 'right', 'commentRight');
this.builder('/*' + left + node.text + right + '*/', node);
};
Stringifier.prototype.decl = function decl(node, semicolon) {
var between = this.raw(node, 'between', 'colon');
var string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
};
Stringifier.prototype.rule = function rule(node) {
this.block(node, this.rawValue(node, 'selector'));
};
Stringifier.prototype.atrule = function atrule(node, semicolon) {
var name = '@' + node.name;
var params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
var end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
};
Stringifier.prototype.body = function body(node) {
var last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break;
last -= 1;
}
var semicolon = this.raw(node, 'semicolon');
for (var i = 0; i < node.nodes.length; i++) {
var child = node.nodes[i];
var before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
};
Stringifier.prototype.block = function block(node, start) {
var between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + '{', node, 'start');
var after = void 0;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
};
Stringifier.prototype.raw = function raw(node, own, detect) {
var value = void 0;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value;
}
var parent = node.parent;
// Hack for first rule in CSS
if (detect === 'before') {
if (!parent || parent.type === 'root' && parent.first === node) {
return '';
}
}
// Floating child without parent
if (!parent) return defaultRaw[detect];
// Detect style by other nodes
var root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect];
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect);
} else {
var method = 'raw' + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(function (i) {
value = i.raws[own];
if (typeof value !== 'undefined') return false;
});
}
}
if (typeof value === 'undefined') value = defaultRaw[detect];
root.rawCache[detect] = value;
return value;
};
Stringifier.prototype.rawSemicolon = function rawSemicolon(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawEmptyBody = function rawEmptyBody(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawIndent = function rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
var value = void 0;
root.walk(function (i) {
var p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
var parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/[^\s]/g, '');
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeComment = function rawBeforeComment(root, node) {
var value = void 0;
root.walkComments(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
}
return value;
};
Stringifier.prototype.rawBeforeDecl = function rawBeforeDecl(root, node) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
}
return value;
};
Stringifier.prototype.rawBeforeRule = function rawBeforeRule(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeClose = function rawBeforeClose(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeOpen = function rawBeforeOpen(root) {
var value = void 0;
root.walk(function (i) {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawColon = function rawColon(root) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false;
}
});
return value;
};
Stringifier.prototype.beforeAfter = function beforeAfter(node, detect) {
var value = void 0;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
var buf = node.parent;
var depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.indexOf('\n') !== -1) {
var indent = this.raw(node, null, 'indent');
if (indent.length) {
for (var step = 0; step < depth; step++) {
value += indent;
}
}
}
return value;
};
Stringifier.prototype.rawValue = function rawValue(node, prop) {
var value = node[prop];
var raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
} else {
return value;
}
};
return Stringifier;
}();
function stringify(node, builder) {
var str = new Stringifier(builder);
str.stringify(node);
}
/**
* @typedef {object} position
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* @typedef {object} source
* @property {Input} input - {@link Input} with input file
* @property {position} start - The starting position of the node’s source
* @property {position} end - The ending position of the node’s source
*/
var cloneNode = function cloneNode(obj, parent) {
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
var value = obj[i];
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned;
};
/**
* All node classes inherit the following common methods.
*
* @abstract
*/
var Node = function () {
/**
* @param {object} [defaults] - value for node properties
*/
function Node() {
var defaults$$1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, Node);
this.raws = {};
for (var name in defaults$$1) {
this[name] = defaults$$1[name];
}
}
/**
* Returns a CssSyntaxError instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* @param {string} message - error description
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this error.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the error
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the error
*
* @return {CssSyntaxError} error object to throw it
*
* @example
* if ( !variables[name] ) {
* throw decl.error('Unknown variable ' + name, { word: name });
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
*/
Node.prototype.error = function error(message) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (this.source) {
var pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts);
} else {
return new CssSyntaxError(message);
}
};
/**
* This method is provided as a convenience wrapper for {@link Result#warn}.
*
* @param {Result} result - the {@link Result} instance
* that will receive the warning
* @param {string} text - warning message
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this warning.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the warning
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the warning
*
* @return {Warning} created warning object
*
* @example
* const plugin = postcss.plugin('postcss-deprecated', () => {
* return (root, result) => {
* root.walkDecls('bad', decl => {
* decl.warn(result, 'Deprecated property bad');
* });
* };
* });
*/
Node.prototype.warn = function warn(result, text, opts) {
var data = { node: this };
for (var i in opts) {
data[i] = opts[i];
}return result.warn(text, data);
};
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* @example
* if ( decl.prop.match(/^-webkit-/) ) {
* decl.remove();
* }
*
* @return {Node} node to make calls chain
*/
Node.prototype.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
/**
* Returns a CSS string representing the node.
*
* @param {stringifier|syntax} [stringifier] - a syntax to use
* in string generation
*
* @return {string} CSS string of this node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {}"
*/
Node.prototype.toString = function toString() {
var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : stringify;
if (stringifier.stringify) stringifier = stringifier.stringify;
var result = '';
stringifier(this, function (i) {
result += i;
});
return result;
};
/**
* Returns a clone of the node.
*
* The resulting cloned node and its (cloned) children will have
* a clean parent and code style properties.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* const cloned = decl.clone({ prop: '-moz-' + decl.prop });
* cloned.raws.before //=> undefined
* cloned.parent //=> undefined
* cloned.toString() //=> -moz-transform: scale(0)
*
* @return {Node} clone of the node
*/
Node.prototype.clone = function clone() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* decl.cloneBefore({ prop: '-moz-' + decl.prop });
*
* @return {Node} - new node
*/
Node.prototype.cloneBefore = function cloneBefore() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @return {Node} - new node
*/
Node.prototype.cloneAfter = function cloneAfter() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
};
/**
* Inserts node(s) before the current node and removes the current node.
*
* @param {...Node} nodes - node(s) to replace current one
*
* @example
* if ( atrule.name == 'mixin' ) {
* atrule.replaceWith(mixinRules[atrule.params]);
* }
*
* @return {Node} current node to methods chain
*/
Node.prototype.replaceWith = function replaceWith() {
var _this = this;
if (this.parent) {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
nodes.forEach(function (node) {
_this.parent.insertBefore(_this, node);
});
this.remove();
}
return this;
};
/**
* Removes the node from its current parent and inserts it
* at the end of `newParent`.
*
* This will clean the `before` and `after` code {@link Node#raws} data
* from the node and replace them with the indentation style of `newParent`.
* It will also clean the `between` property
* if `newParent` is in another {@link Root}.
*
* @param {Container} newParent - container node where the current node
* will be moved
*
* @example
* atrule.moveTo(atrule.root());
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveTo = function moveTo(newParent) {
this.cleanRaws(this.root() === newParent.root());
this.remove();
newParent.append(this);
return this;
};
/**
* Removes the node from its current parent and inserts it into
* a new parent before `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be before current node
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveBefore = function moveBefore(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertBefore(otherNode, this);
return this;
};
/**
* Removes the node from its current parent and inserts it into
* a new parent after `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be after current node
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveAfter = function moveAfter(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertAfter(otherNode, this);
return this;
};
/**
* Returns the next child of the node’s parent.
* Returns `undefined` if the current node is the last child.
*
* @return {Node|undefined} next node
*
* @example
* if ( comment.text === 'delete next' ) {
* const next = comment.next();
* if ( next ) {
* next.remove();
* }
* }
*/
Node.prototype.next = function next() {
var index = this.parent.index(this);
return this.parent.nodes[index + 1];
};
/**
* Returns the previous child of the node’s parent.
* Returns `undefined` if the current node is the first child.
*
* @return {Node|undefined} previous node
*
* @example
* const annotation = decl.prev();
* if ( annotation.type == 'comment' ) {
* readAnnotation(annotation.text);
* }
*/
Node.prototype.prev = function prev() {
var index = this.parent.index(this);
return this.parent.nodes[index - 1];
};
Node.prototype.toJSON = function toJSON() {
var fixed = {};
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
if (name === 'parent') continue;
var value = this[name];
if (value instanceof Array) {
fixed[name] = value.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) {
return i.toJSON();
} else {
return i;
}
});
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) {
fixed[name] = value.toJSON();
} else {
fixed[name] = value;
}
}
return fixed;
};
/**
* Returns a {@link Node#raws} value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* @param {string} prop - name of code style property
* @param {string} [defaultType] - name of default value, it can be missed
* if the value is the same as prop
*
* @example
* const root = postcss.parse('a { background: white }');
* root.nodes[0].append({ prop: 'color', value: 'black' });
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
*
* @return {string} code style value
*/
Node.prototype.raw = function raw(prop, defaultType) {
var str = new Stringifier();
return str.raw(this, prop, defaultType);
};
/**
* Finds the Root instance of the node’s tree.
*
* @example
* root.nodes[0].nodes[0].root() === root
*
* @return {Root} root parent
*/
Node.prototype.root = function root() {
var result = this;
while (result.parent) {
result = result.parent;
}return result;
};
Node.prototype.cleanRaws = function cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
};
Node.prototype.positionInside = function positionInside(index) {
var string = this.toString();
var column = this.source.start.column;
var line = this.source.start.line;
for (var i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { line: line, column: column };
};
Node.prototype.positionBy = function positionBy(opts) {
var pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
var index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos;
};
Node.prototype.removeSelf = function removeSelf() {
warnOnce('Node#removeSelf is deprecated. Use Node#remove.');
return this.remove();
};
Node.prototype.replace = function replace(nodes) {
warnOnce('Node#replace is deprecated. Use Node#replaceWith');
return this.replaceWith(nodes);
};
Node.prototype.style = function style(own, detect) {
warnOnce('Node#style() is deprecated. Use Node#raw()');
return this.raw(own, detect);
};
Node.prototype.cleanStyles = function cleanStyles(keepBetween) {
warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()');
return this.cleanRaws(keepBetween);
};
createClass(Node, [{
key: 'before',
get: function get$$1() {
warnOnce('Node#before is deprecated. Use Node#raws.before');
return this.raws.before;
},
set: function set$$1(val) {
warnOnce('Node#before is deprecated. Use Node#raws.before');
this.raws.before = val;
}
}, {
key: 'between',
get: function get$$1() {
warnOnce('Node#between is deprecated. Use Node#raws.between');
return this.raws.between;
},
set: function set$$1(val) {
warnOnce('Node#between is deprecated. Use Node#raws.between');
this.raws.between = val;
}
/**
* @memberof Node#
* @member {string} type - String representing the node’s type.
* Possible values are `root`, `atrule`, `rule`,
* `decl`, or `comment`.
*
* @example
* postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
*/
/**
* @memberof Node#
* @member {Container} parent - the node’s parent node.
*
* @example
* root.nodes[0].parent == root;
*/
/**
* @memberof Node#
* @member {source} source - the input source of the node
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new node’s
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* });
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
* ```
*
* ```js
* if ( atrule.name == 'add-link' ) {
* const rule = postcss.rule({ selector: 'a', source: atrule.source });
* atrule.parent.insertBefore(atrule, rule);
* }
* ```
*
* @example
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
*/
/**
* @memberof Node#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text
* and <code>*/</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Node;
}();
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = function (_Node) {
inherits(Declaration, _Node);
function Declaration(defaults$$1) {
classCallCheck(this, Declaration);
var _this = possibleConstructorReturn(this, _Node.call(this, defaults$$1));
_this.type = 'decl';
return _this;
}
createClass(Declaration, [{
key: '_value',
get: function get$$1() {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
return this.raws.value;
},
set: function set$$1(val) {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
this.raws.value = val;
}
}, {
key: '_important',
get: function get$$1() {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
return this.raws.important;
},
set: function set$$1(val) {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
this.raws.important = val;
}
/**
* @memberof Declaration#
* @member {string} prop - the declaration’s property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declaration’s value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Declaration;
}(Node);
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
inherits(Comment, _Node);
function Comment(defaults$$1) {
classCallCheck(this, Comment);
var _this = possibleConstructorReturn(this, _Node.call(this, defaults$$1));
_this.type = 'comment';
return _this;
}
createClass(Comment, [{
key: 'left',
get: function get$$1() {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
return this.raws.left;
},
set: function set$$1(val) {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
this.raws.left = val;
}
}, {
key: 'right',
get: function get$$1() {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
return this.raws.right;
},
set: function set$$1(val) {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
this.raws.right = val;
}
/**
* @memberof Comment#
* @member {string} text - the comment’s text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text.
*/
}]);
return Comment;
}(Node);
var Parser = function () {
function Parser(input) {
classCallCheck(this, Parser);
this.input = input;
this.pos = 0;
this.root = new Root();
this.current = this.root;
this.spaces = '';
this.semicolon = false;
this.root.source = { input: input, start: { line: 1, column: 1 } };
}
Parser.prototype.tokenize = function tokenize$$1() {
this.tokens = tokenize(this.input);
};
Parser.prototype.loop = function loop() {
var token = void 0;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
switch (token[0]) {
case 'space':
case ';':
this.spaces += token[1];
break;
case '}':
this.end(token);
break;
case 'comment':
this.comment(token);
break;
case 'at-word':
this.atrule(token);
break;
case '{':
this.emptyRule(token);
break;
default:
this.other();
break;
}
this.pos += 1;
}
this.endFile();
};
Parser.prototype.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
Parser.prototype.emptyRule = function emptyRule(token) {
var node = new Rule();
this.init(node, token[2], token[3]);
node.selector = '';
node.raws.between = '';
this.current = node;
};
Parser.prototype.other = function other() {
var token = void 0;
var end = false;
var type = null;
var colon = false;
var bracket = null;
var brackets = [];
var start = this.pos;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
type = token[0];
if (type === '(' || type === '[') {
if (!bracket) bracket = token;
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(this.tokens.slice(start, this.pos + 1));
return;
} else {
break;
}
} else if (type === '{') {
this.rule(this.tokens.slice(start, this.pos + 1));
return;
} else if (type === '}') {
this.pos -= 1;
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
this.pos -= 1;
end = true;
}
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
while (this.pos > start) {
token = this.tokens[this.pos][0];
if (token !== 'space' && token !== 'comment') break;
this.pos -= 1;
}
this.decl(this.tokens.slice(start, this.pos + 1));
return;
}
this.unknownWord(start);
};
Parser.prototype.rule = function rule(tokens) {
tokens.pop();
var node = new Rule();
this.init(node, tokens[0][2], tokens[0][3]);
node.raws.between = this.spacesFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
};
Parser.prototype.decl = function decl(tokens) {
var node = new Declaration();
this.init(node);
var last = tokens[tokens.length - 1];
if (last[0] === ';') {
this.semicolon = true;
tokens.pop();
}
if (last[4]) {
node.source.end = { line: last[4], column: last[5] };
} else {
node.source.end = { line: last[2], column: last[3] };
}
while (tokens[0][0] !== 'word') {
node.raws.before += tokens.shift()[1];
}
node.source.start = { line: tokens[0][2], column: tokens[0][3] };
node.prop = '';
while (tokens.length) {
var type = tokens[0][0];
if (type === ':' || type === 'space' || type === 'comment') {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = '';
var token = void 0;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ':') {
node.raws.between += token[1];
break;
} else {
node.raws.between += token[1];
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
node.raws.between += this.spacesFromStart(tokens);
this.precheckMissedSemicolon(tokens);
for (var i = tokens.length - 1; i > 0; i--) {
token = tokens[i];
if (token[1] === '!important') {
node.important = true;
var string = this.stringFrom(tokens, i);
string = this.spacesFromEnd(tokens) + string;
if (string !== ' !important') node.raws.important = string;
break;
} else if (token[1] === 'important') {
var cache = tokens.slice(0);
var str = '';
for (var j = i; j > 0; j--) {
var _type = cache[j][0];
if (str.trim().indexOf('!') === 0 && _type !== 'space') {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf('!') === 0) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break;
}
}
this.raw(node, 'value', tokens);
if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
};
Parser.prototype.atrule = function atrule(token) {
var node = new AtRule();
node.name = token[1].slice(1);
if (node.name === '') {
this.unnamedAtrule(node, token);
}
this.init(node, token[2], token[3]);
var last = false;
var open = false;
var params = [];
this.pos += 1;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
if (token[0] === ';') {
node.source.end = { line: token[2], column: token[3] };
this.semicolon = true;
break;
} else if (token[0] === '{') {
open = true;
break;
} else if (token[0] === '}') {
this.end(token);
break;
} else {
params.push(token);
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
last = true;
}
node.raws.between = this.spacesFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesFromStart(params);
this.raw(node, 'params', params);
if (last) {
token = params[params.length - 1];
node.source.end = { line: token[4], column: token[5] };
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.raws.afterName = '';
node.params = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
};
Parser.prototype.end = function end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
this.spaces = '';
if (this.current.parent) {
this.current.source.end = { line: token[2], column: token[3] };
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
};
Parser.prototype.endFile = function endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
};
// Helpers
Parser.prototype.init = function init(node, line, column) {
this.current.push(node);
node.source = { start: { line: line, column: column }, input: this.input };
node.raws.before = this.spaces;
this.spaces = '';
if (node.type !== 'comment') this.semicolon = false;
};
Parser.prototype.raw = function raw(node, prop, tokens) {
var token = void 0,
type = void 0;
var length = tokens.length;
var value = '';
var clean = true;
for (var i = 0; i < length; i += 1) {
token = tokens[i];
type = token[0];
if (type === 'comment' || type === 'space' && i === length - 1) {
clean = false;
} else {
value += token[1];
}
}
if (!clean) {
var raw = tokens.reduce(function (all, i) {
return all + i[1];
}, '');
node.raws[prop] = { value: value, raw: raw };
}
node[prop] = value;
};
Parser.prototype.spacesFromEnd = function spacesFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.spacesFromStart = function spacesFromStart(tokens) {
var next = void 0;
var spaces = '';
while (tokens.length) {
next = tokens[0][0];
if (next !== 'space' && next !== 'comment') break;
spaces += tokens.shift()[1];
}
return spaces;
};
Parser.prototype.stringFrom = function stringFrom(tokens, from) {
var result = '';
for (var i = from; i < tokens.length; i++) {
result += tokens[i][1];
}
tokens.splice(from, tokens.length - from);
return result;
};
Parser.prototype.colon = function colon(tokens) {
var brackets = 0;
var token = void 0,
type = void 0,
prev = void 0;
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
type = token[0];
if (type === '(') {
brackets += 1;
} else if (type === ')') {
brackets -= 1;
} else if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue;
} else {
return i;
}
}
prev = token;
}
return false;
};
// Errors
Parser.prototype.unclosedBracket = function unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
};
Parser.prototype.unknownWord = function unknownWord(start) {
var token = this.tokens[start];
throw this.input.error('Unknown word', token[2], token[3]);
};
Parser.prototype.unexpectedClose = function unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2], token[3]);
};
Parser.prototype.unclosedBlock = function unclosedBlock() {
var pos = this.current.source.start;
throw this.input.error('Unclosed block', pos.line, pos.column);
};
Parser.prototype.doubleColon = function doubleColon(token) {
throw this.input.error('Double colon', token[2], token[3]);
};
Parser.prototype.unnamedAtrule = function unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2], token[3]);
};
Parser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
// Hook for Safe Parser
};
Parser.prototype.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var founded = 0;
var token = void 0;
for (var j = colon - 1; j >= 0; j--) {
token = tokens[j];
if (token[0] !== 'space') {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error('Missed semicolon', token[2], token[3]);
};
return Parser;
}();
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new Input(css, opts);
var parser = new Parser(input);
try {
parser.tokenize();
parser.loop();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
function cleanSource(nodes) {
return nodes.map(function (i) {
if (i.nodes) i.nodes = cleanSource(i.nodes);
delete i.source;
return i;
});
}
/**
* @callback childCondition
* @param {Node} node - container child
* @param {number} index - child index
* @param {Node[]} nodes - all container children
* @return {boolean}
*/
/**
* @callback childIterator
* @param {Node} node - container child
* @param {number} index - child index
* @return {false|undefined} returning `false` will break iteration
*/
/**
* The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*
* @extends Node
* @abstract
*/
var Container = function (_Node) {
inherits(Container, _Node);
function Container() {
classCallCheck(this, Container);
return possibleConstructorReturn(this, _Node.apply(this, arguments));
}
Container.prototype.push = function push(child) {
child.parent = this;
this.nodes.push(child);
return this;
};
/**
* Iterates through the container’s immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the container’s immediate children.
* If you need to recursively iterate through all the container’s descendant
* nodes, use {@link Container#walk}.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const root = postcss.parse('a { color: black; z-index: 1 }');
* const rule = root.first;
*
* for ( let decl of rule.nodes ) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Will be executed only for color and z-index
* });
*/
Container.prototype.each = function each(callback) {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.nodes) return undefined;
var index = void 0,
result = void 0;
while (this.indexes[id] < this.nodes.length) {
index = this.indexes[id];
result = callback(this.nodes[index], index);
if (result === false) break;
this.indexes[id] += 1;
}
delete this.indexes[id];
return result;
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the container’s immediate children,
* use {@link Container#each}.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walk(node => {
* // Traverses all descendant nodes.
* });
*/
Container.prototype.walk = function walk(callback) {
return this.each(function (child, i) {
var result = callback(child, i);
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [prop] - string or regular expression
* to filter declarations by property name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop);
* });
*
* root.walkDecls('border-radius', decl => {
* decl.remove();
* });
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value);
* });
*/
Container.prototype.walkDecls = function walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk(function (child, i) {
if (child.type === 'decl') {
return callback(child, i);
}
});
} else if (prop instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [selector] - string or regular expression
* to filter rules by selector
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const selectors = [];
* root.walkRules(rule => {
* selectors.push(rule.selector);
* });
* console.log(`Your CSS uses ${selectors.length} selectors`);
*/
Container.prototype.walkRules = function walkRules(selector, callback) {
if (!callback) {
callback = selector;
return this.walk(function (child, i) {
if (child.type === 'rule') {
return callback(child, i);
}
});
} else if (selector instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [name] - string or regular expression
* to filter at-rules by name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkAtRules(rule => {
* if ( isOld(rule.name) ) rule.remove();
* });
*
* let first = false;
* root.walkAtRules('charset', rule => {
* if ( !first ) {
* first = true;
* } else {
* rule.remove();
* }
* });
*/
Container.prototype.walkAtRules = function walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk(function (child, i) {
if (child.type === 'atrule') {
return callback(child, i);
}
});
} else if (name instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each comment node.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkComments(comment => {
* comment.remove();
* });
*/
Container.prototype.walkComments = function walkComments(callback) {
return this.walk(function (child, i) {
if (child.type === 'comment') {
return callback(child, i);
}
});
};
/**
* Inserts new nodes to the start of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.append(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.append = function append() {
var _this2 = this;
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
children.forEach(function (child) {
var nodes = _this2.normalize(child, _this2.last);
nodes.forEach(function (node) {
return _this2.nodes.push(node);
});
});
return this;
};
/**
* Inserts new nodes to the end of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.prepend(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.prepend = function prepend() {
var _this3 = this;
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
children = children.reverse();
children.forEach(function (child) {
var nodes = _this3.normalize(child, _this3.first, 'prepend').reverse();
nodes.forEach(function (node) {
return _this3.nodes.unshift(node);
});
for (var id in _this3.indexes) {
_this3.indexes[id] = _this3.indexes[id] + nodes.length;
}
});
return this;
};
Container.prototype.cleanRaws = function cleanRaws(keepBetween) {
_Node.prototype.cleanRaws.call(this, keepBetween);
if (this.nodes) {
this.nodes.forEach(function (node) {
return node.cleanRaws(keepBetween);
});
}
};
/**
* Insert new node before old node within the container.
*
* @param {Node|number} exist - child or child’s index.
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*
* @example
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
*/
Container.prototype.insertBefore = function insertBefore(exist, add) {
var _this4 = this;
exist = this.index(exist);
var type = exist === 0 ? 'prepend' : false;
var nodes = this.normalize(add, this.nodes[exist], type).reverse();
nodes.forEach(function (node) {
return _this4.nodes.splice(exist, 0, node);
});
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist <= index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Insert new node after old node within the container.
*
* @param {Node|number} exist - child or child’s index
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*/
Container.prototype.insertAfter = function insertAfter(exist, add) {
var _this5 = this;
exist = this.index(exist);
var nodes = this.normalize(add, this.nodes[exist]).reverse();
nodes.forEach(function (node) {
return _this5.nodes.splice(exist + 1, 0, node);
});
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist < index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
Container.prototype.remove = function remove(child) {
if (typeof child !== 'undefined') {
warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild');
this.removeChild(child);
} else {
_Node.prototype.remove.call(this);
}
return this;
};
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* @param {Node|number} child - child or child’s index
*
* @return {Node} this node for methods chain
*
* @example
* rule.nodes.length //=> 5
* rule.removeChild(decl);
* rule.nodes.length //=> 4
* decl.parent //=> undefined
*/
Container.prototype.removeChild = function removeChild(child) {
child = this.index(child);
this.nodes[child].parent = undefined;
this.nodes.splice(child, 1);
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
/**
* Removes all children from the container
* and cleans their parent properties.
*
* @return {Node} this node for methods chain
*
* @example
* rule.removeAll();
* rule.nodes.length //=> 0
*/
Container.prototype.removeAll = function removeAll() {
this.nodes.forEach(function (node) {
return node.parent = undefined;
});
this.nodes = [];
return this;
};
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* @param {string|RegExp} pattern - replace pattern
* @param {object} opts - options to speed up the search
* @param {string|string[]} opts.props - an array of property names
* @param {string} opts.fast - string that’s used
* to narrow down values and speed up
the regexp search
* @param {function|string} callback - string to replace pattern
* or callback that returns a new
* value.
* The callback will receive
* the same arguments as those
* passed to a function parameter
* of `String#replace`.
*
* @return {Node} this node for methods chain
*
* @example
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px';
* });
*/
Container.prototype.replaceValues = function replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls(function (decl) {
if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
decl.value = decl.value.replace(pattern, callback);
});
return this;
};
/**
* Returns `true` if callback returns `true`
* for all of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is every child pass condition
*
* @example
* const noPrefixes = rule.every(i => i.prop[0] !== '-');
*/
Container.prototype.every = function every(condition) {
return this.nodes.every(condition);
};
/**
* Returns `true` if callback returns `true` for (at least) one
* of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is some child pass condition
*
* @example
* const hasPrefix = rule.some(i => i.prop[0] === '-');
*/
Container.prototype.some = function some(condition) {
return this.nodes.some(condition);
};
/**
* Returns a `child`’s index within the {@link Container#nodes} array.
*
* @param {Node} child - child of the current container.
*
* @return {number} child index
*
* @example
* rule.index( rule.nodes[2] ) //=> 2
*/
Container.prototype.index = function index(child) {
if (typeof child === 'number') {
return child;
} else {
return this.nodes.indexOf(child);
}
};
/**
* The container’s first child.
*
* @type {Node}
*
* @example
* rule.first == rules.nodes[0];
*/
Container.prototype.normalize = function normalize(nodes, sample) {
var _this6 = this;
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes);
} else if (!Array.isArray(nodes)) {
if (nodes.type === 'root') {
nodes = nodes.nodes;
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation');
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new Declaration(nodes)];
} else if (nodes.selector) {
nodes = [new Rule(nodes)];
} else if (nodes.name) {
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new Comment(nodes)];
} else {
throw new Error('Unknown node type in node creation');
}
}
var processed = nodes.map(function (i) {
if (typeof i.raws === 'undefined') i = _this6.rebuild(i);
if (i.parent) i = i.clone();
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
}
}
i.parent = _this6;
return i;
});
return processed;
};
Container.prototype.rebuild = function rebuild(node, parent) {
var _this7 = this;
var fix = void 0;
if (node.type === 'root') {
fix = new Root();
} else if (node.type === 'atrule') {
fix = new AtRule();
} else if (node.type === 'rule') {
fix = new Rule();
} else if (node.type === 'decl') {
fix = new Declaration();
} else if (node.type === 'comment') {
fix = new Comment();
}
for (var i in node) {
if (i === 'nodes') {
fix.nodes = node.nodes.map(function (j) {
return _this7.rebuild(j, fix);
});
} else if (i === 'parent' && parent) {
fix.parent = parent;
} else if (node.hasOwnProperty(i)) {
fix[i] = node[i];
}
}
return fix;
};
Container.prototype.eachInside = function eachInside(callback) {
warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.');
return this.walk(callback);
};
Container.prototype.eachDecl = function eachDecl(prop, callback) {
warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.');
return this.walkDecls(prop, callback);
};
Container.prototype.eachRule = function eachRule(selector, callback) {
warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.');
return this.walkRules(selector, callback);
};
Container.prototype.eachAtRule = function eachAtRule(name, callback) {
warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.');
return this.walkAtRules(name, callback);
};
Container.prototype.eachComment = function eachComment(callback) {
warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.');
return this.walkComments(callback);
};
createClass(Container, [{
key: 'first',
get: function get$$1() {
if (!this.nodes) return undefined;
return this.nodes[0];
}
/**
* The container’s last child.
*
* @type {Node}
*
* @example
* rule.last == rule.nodes[rule.nodes.length - 1];
*/
}, {
key: 'last',
get: function get$$1() {
if (!this.nodes) return undefined;
return this.nodes[this.nodes.length - 1];
}
}, {
key: 'semicolon',
get: function get$$1() {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
return this.raws.semicolon;
},
set: function set$$1(val) {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
this.raws.semicolon = val;
}
}, {
key: 'after',
get: function get$$1() {
warnOnce('Node#after is deprecated. Use Node#raws.after');
return this.raws.after;
},
set: function set$$1(val) {
warnOnce('Node#after is deprecated. Use Node#raws.after');
this.raws.after = val;
}
/**
* @memberof Container#
* @member {Node[]} nodes - an array containing the container’s children
*
* @example
* const root = postcss.parse('a { color: black }');
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
*/
}]);
return Container;
}(Node);
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = function (_Container) {
inherits(AtRule, _Container);
function AtRule(defaults$$1) {
classCallCheck(this, AtRule);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'atrule';
return _this;
}
AtRule.prototype.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
AtRule.prototype.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
createClass(AtRule, [{
key: 'afterName',
get: function get$$1() {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
return this.raws.afterName;
},
set: function set$$1(val) {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
this.raws.afterName = val;
}
}, {
key: '_params',
get: function get$$1() {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
return this.raws.params;
},
set: function set$$1(val) {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
this.raws.params = val;
}
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
}]);
return AtRule;
}(Container);
/**
* Contains helpers for safely splitting lists of CSS values,
* preserving parentheses and quotes.
*
* @example
* const list = postcss.list;
*
* @namespace list
*/
var list = {
split: function split(string, separators, last) {
var array = [];
var current = '';
var split = false;
var func = 0;
var quote = false;
var escape = false;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (quote) {
if (escape) {
escape = false;
} else if (letter === '\\') {
escape = true;
} else if (letter === quote) {
quote = false;
}
} else if (letter === '"' || letter === '\'') {
quote = letter;
} else if (letter === '(') {
func += 1;
} else if (letter === ')') {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.indexOf(letter) !== -1) split = true;
}
if (split) {
if (current !== '') array.push(current.trim());
current = '';
split = false;
} else {
current += letter;
}
}
if (last || current !== '') array.push(current.trim());
return array;
},
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* @param {string} string - space-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
*/
space: function space(string) {
var spaces = [' ', '\n', '\t'];
return list.split(string, spaces);
},
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* @param {string} string - comma-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
*/
comma: function comma(string) {
var comma = ',';
return list.split(string, [comma], true);
}
};
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = function (_Container) {
inherits(Rule, _Container);
function Rule(defaults$$1) {
classCallCheck(this, Rule);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rule’s individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
createClass(Rule, [{
key: 'selectors',
get: function get$$1() {
return list.comma(this.selector);
},
set: function set$$1(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
}, {
key: '_selector',
get: function get$$1() {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
return this.raws.selector;
},
set: function set$$1(val) {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
this.raws.selector = val;
}
/**
* @memberof Rule#
* @member {string} selector - the rule’s full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(Container);
/**
* Represents a plugin’s warning. It can be created using {@link Node#warn}.
*
* @example
* if ( decl.important ) {
* decl.warn(result, 'Avoid !important', { word: '!important' });
* }
*/
var Warning = function () {
/**
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*/
function Warning(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Warning);
/**
* @member {string} - Type to filter warnings from
* {@link Result#messages}. Always equal
* to `"warning"`.
*
* @example
* const nonWarning = result.messages.filter(i => i.type !== 'warning')
*/
this.type = 'warning';
/**
* @member {string} - The warning message.
*
* @example
* warning.text //=> 'Try to avoid !important'
*/
this.text = text;
if (opts.node && opts.node.source) {
var pos = opts.node.positionBy(opts);
/**
* @member {number} - Line in the input file
* with this warning’s source
*
* @example
* warning.line //=> 5
*/
this.line = pos.line;
/**
* @member {number} - Column in the input file
* with this warning’s source.
*
* @example
* warning.column //=> 6
*/
this.column = pos.column;
}
for (var opt in opts) {
this[opt] = opts[opt];
}
}
/**
* Returns a warning position and message.
*
* @example
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
*
* @return {string} warning position and message
*/
Warning.prototype.toString = function toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message;
} else if (this.plugin) {
return this.plugin + ': ' + this.text;
} else {
return this.text;
}
};
/**
* @memberof Warning#
* @member {string} plugin - The name of the plugin that created
* it will fill this property automatically.
* this warning. When you call {@link Node#warn}
*
* @example
* warning.plugin //=> 'postcss-important'
*/
/**
* @memberof Warning#
* @member {Node} node - Contains the CSS node that caused the warning.
*
* @example
* warning.node.toString() //=> 'color: white !important'
*/
return Warning;
}();
/**
* @typedef {object} Message
* @property {string} type - message type
* @property {string} plugin - source PostCSS plugin name
*/
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by {@link LazyResult#then}
* or {@link Root#toResult} methods.
*
* @example
* postcss([cssnext]).process(css).then(function (result) {
* console.log(result.css);
* });
*
* @example
* var result2 = postcss.parse(css).toResult();
*/
var Result = function () {
/**
* @param {Processor} processor - processor used for this transformation.
* @param {Root} root - Root node after all transformations.
* @param {processOptions} opts - options from the {@link Processor#process}
* or {@link Root#toResult}
*/
function Result(processor, root, opts) {
classCallCheck(this, Result);
/**
* @member {Processor} - The Processor instance used
* for this transformation.
*
* @example
* for ( let plugin of result.processor.plugins) {
* if ( plugin.postcssPlugin === 'postcss-bad' ) {
* throw 'postcss-good is incompatible with postcss-bad';
* }
* });
*/
this.processor = processor;
/**
* @member {Message[]} - Contains messages from plugins
* (e.g., warnings or custom messages).
* Each message should have type
* and plugin properties.
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* var browsers = detectMinBrowsersByCanIUse(root);
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers: browsers
* });
* };
* });
*/
this.messages = [];
/**
* @member {Root} - Root node after all transformations.
*
* @example
* root.toResult().root == root;
*/
this.root = root;
/**
* @member {processOptions} - Options from the {@link Processor#process}
* or {@link Root#toResult} call
* that produced this Result instance.
*
* @example
* root.toResult(opts).opts == opts;
*/
this.opts = opts;
/**
* @member {string} - A CSS string representing of {@link Result#root}.
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
* class from the `source-map` library,
* representing changes
* to the {@link Result#root} instance.
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if ( result.map ) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString());
* }
*/
this.map = undefined;
}
/**
* Returns for @{link Result#css} content.
*
* @example
* result + '' === result.css
*
* @return {string} string representing of {@link Result#root}
*/
Result.prototype.toString = function toString() {
return this.css;
};
/**
* Creates an instance of {@link Warning} and adds it
* to {@link Result#messages}.
*
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*
* @return {Warning} created warning
*/
Result.prototype.warn = function warn(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
var warning = new Warning(text, opts);
this.messages.push(warning);
return warning;
};
/**
* Returns warnings from plugins. Filters {@link Warning} instances
* from {@link Result#messages}.
*
* @example
* result.warnings().forEach(warn => {
* console.warn(warn.toString());
* });
*
* @return {Warning[]} warnings from plugins
*/
Result.prototype.warnings = function warnings() {
return this.messages.filter(function (i) {
return i.type === 'warning';
});
};
/**
* An alias for the {@link Result#css} property.
* Use it with syntaxes that generate non-CSS output.
* @type {string}
*
* @example
* result.css === result.content;
*/
createClass(Result, [{
key: 'content',
get: function get$$1() {
return this.css;
}
}]);
return Result;
}();
function isPromise(obj) {
return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function';
}
/**
* @callback onFulfilled
* @param {Result} result
*/
/**
* @callback onRejected
* @param {Error} error
*/
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by {@link Processor#process}.
*
* @example
* const lazy = postcss([cssnext]).process(css);
*/
var LazyResult = function () {
function LazyResult(processor, css, opts) {
classCallCheck(this, LazyResult);
this.stringified = false;
this.processed = false;
var root = void 0;
if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') {
root = css;
} else if (css instanceof LazyResult || css instanceof Result) {
root = css.root;
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
var parser = parse;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error) {
this.error = error;
}
}
this.result = new Result(processor, root, opts);
}
/**
* Returns a {@link Processor} instance, which will be used
* for CSS transformations.
* @type {Processor}
*/
/**
* Processes input CSS through synchronous plugins
* and calls {@link Result#warnings()}.
*
* @return {Warning[]} warnings from plugins
*/
LazyResult.prototype.warnings = function warnings() {
return this.sync().warnings();
};
/**
* Alias for the {@link LazyResult#css} property.
*
* @example
* lazy + '' === lazy.css;
*
* @return {string} output CSS
*/
LazyResult.prototype.toString = function toString() {
return this.css;
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* @param {onFulfilled} onFulfilled - callback will be executed
* when all plugins will finish work
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* });
*/
LazyResult.prototype.then = function then(onFulfilled, onRejected) {
return this.async().then(onFulfilled, onRejected);
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* }).catch(error => {
* console.error(error);
* });
*/
LazyResult.prototype.catch = function _catch(onRejected) {
return this.async().catch(onRejected);
};
LazyResult.prototype.handleError = function handleError(error, plugin) {
try {
this.error = error;
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.setMessage();
} else if (plugin.postcssVersion) {
var pluginName = plugin.postcssPlugin;
var pluginVer = plugin.postcssVersion;
var runtimeVer = this.result.processor.version;
var a = pluginVer.split('.');
var b = runtimeVer.split('.');
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
warnOnce('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.');
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
};
LazyResult.prototype.asyncTick = function asyncTick(resolve, reject) {
var _this = this;
if (this.plugin >= this.processor.plugins.length) {
this.processed = true;
return resolve();
}
try {
var plugin = this.processor.plugins[this.plugin];
var promise = this.run(plugin);
this.plugin += 1;
if (isPromise(promise)) {
promise.then(function () {
_this.asyncTick(resolve, reject);
}).catch(function (error) {
_this.handleError(error, plugin);
_this.processed = true;
reject(error);
});
} else {
this.asyncTick(resolve, reject);
}
} catch (error) {
this.processed = true;
reject(error);
}
};
LazyResult.prototype.async = function async() {
var _this2 = this;
if (this.processed) {
return new Promise(function (resolve, reject) {
if (_this2.error) {
reject(_this2.error);
} else {
resolve(_this2.stringify());
}
});
}
if (this.processing) {
return this.processing;
}
this.processing = new Promise(function (resolve, reject) {
if (_this2.error) return reject(_this2.error);
_this2.plugin = 0;
_this2.asyncTick(resolve, reject);
}).then(function () {
_this2.processed = true;
return _this2.stringify();
});
return this.processing;
};
LazyResult.prototype.sync = function sync() {
var _this3 = this;
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
if (this.error) throw this.error;
this.result.processor.plugins.forEach(function (plugin) {
var promise = _this3.run(plugin);
if (isPromise(promise)) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
});
return this.result;
};
LazyResult.prototype.run = function run(plugin) {
this.result.lastPlugin = plugin;
try {
return plugin(this.result.root, this.result);
} catch (error) {
this.handleError(error, plugin);
throw error;
}
};
LazyResult.prototype.stringify = function stringify$$1() {
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
var opts = this.result.opts;
var str = stringify;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
var result = '';
str(this.root, function (i) {
result += i;
});
this.result.css = result;
return this.result;
};
createClass(LazyResult, [{
key: 'processor',
get: function get$$1() {
return this.result.processor;
}
/**
* Options from the {@link Processor#process} call.
* @type {processOptions}
*/
}, {
key: 'opts',
get: function get$$1() {
return this.result.opts;
}
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns {@link Result#css}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#css
*/
}, {
key: 'css',
get: function get$$1() {
return this.stringify().css;
}
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#content
*/
}, {
key: 'content',
get: function get$$1() {
return this.stringify().content;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#map}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {SourceMapGenerator}
* @see Result#map
*/
}, {
key: 'map',
get: function get$$1() {
return this.stringify().map;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#root}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Root}
* @see Result#root
*/
}, {
key: 'root',
get: function get$$1() {
return this.sync().root;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#messages}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Message[]}
* @see Result#messages
*/
}, {
key: 'messages',
get: function get$$1() {
return this.sync().messages;
}
}]);
return LazyResult;
}();
/**
* @callback builder
* @param {string} part - part of generated CSS connected to this node
* @param {Node} node - AST node
* @param {"start"|"end"} [type] - node’s part type
*/
/**
* @callback parser
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*/
/**
* @callback stringifier
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*/
/**
* @typedef {object} syntax
* @property {parser} parse - function to generate AST by string
* @property {stringifier} stringify - function to generate string by AST
*/
/**
* @typedef {object} toString
* @property {function} toString
*/
/**
* @callback pluginFunction
* @param {Root} root - parsed input CSS
* @param {Result} result - result to set warnings or check other plugins
*/
/**
* @typedef {object} Plugin
* @property {function} postcss - PostCSS plugin function
*/
/**
* @typedef {object} processOptions
* @property {string} from - the path of the CSS source file.
* You should always set `from`,
* because it is used in source map
* generation and syntax error messages.
* @property {string} to - the path where you’ll put the output
* CSS file. You should always set `to`
* to generate correct source maps.
* @property {parser} parser - function to generate AST by string
* @property {stringifier} stringifier - class to generate string by AST
* @property {syntax} syntax - object with `parse` and `stringify`
* @property {object} map - source map options
* @property {boolean} map.inline - does source map should
* be embedded in the output
* CSS as a base64-encoded
* comment
* @property {string|object|false|function} map.prev - source map content
* from a previous
* processing step
* (for example, Sass).
* PostCSS will try to find
* previous map
* automatically, so you
* could disable it by
* `false` value.
* @property {boolean} map.sourcesContent - does PostCSS should set
* the origin content to map
* @property {string|false} map.annotation - does PostCSS should set
* annotation comment to map
* @property {string} map.from - override `from` in map’s
* `sources`
*/
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.process(css1).then(result => console.log(result.css));
* processor.process(css2).then(result => console.log(result.css));
*/
var Processor = function () {
/**
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*/
function Processor() {
var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, Processor);
/**
* @member {string} - Current PostCSS version.
*
* @example
* if ( result.processor.version.split('.')[0] !== '5' ) {
* throw new Error('This plugin works only with PostCSS 5');
* }
*/
this.version = '5.2.0';
/**
* @member {pluginFunction[]} - Plugins added to this processor.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.plugins.length //=> 2
*/
this.plugins = this.normalize(plugins);
}
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin created by {@link postcss.plugin} method.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current {@link Result} instance
* as the second.
* * An object with a `postcss` method. PostCSS will use that method
* as described in #2.
* * Another {@link Processor} instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
* or {@link Processor}
* with plugins
*
* @example
* const processor = postcss()
* .use(autoprefixer)
* .use(precss);
*
* @return {Processes} current processor to make methods chain
*/
Processor.prototype.use = function use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
};
/**
* Parses source CSS and returns a {@link LazyResult} Promise proxy.
* Because some plugins can be asynchronous it doesn’t make
* any transformations. Transformations will be applied
* in the {@link LazyResult} methods.
*
* @param {string|toString|Result} css - String with input CSS or
* any object with a `toString()`
* method, like a Buffer.
* Optionally, send a {@link Result}
* instance and the processor will
* take the {@link Root} from it.
* @param {processOptions} [opts] - options
*
* @return {LazyResult} Promise proxy
*
* @example
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css);
* });
*/
Processor.prototype.process = function process(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new LazyResult(this, css, opts);
};
Processor.prototype.normalize = function normalize(plugins) {
var normalized = [];
plugins.forEach(function (i) {
if (i.postcss) i = i.postcss;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins);
} else if (typeof i === 'function') {
normalized.push(i);
} else {
throw new Error(i + ' is not a PostCSS plugin');
}
});
return normalized;
};
return Processor;
}();
/**
* Represents a CSS file and contains all its parsed nodes.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{color:black} b{z-index:2}');
* root.type //=> 'root'
* root.nodes.length //=> 2
*/
var Root = function (_Container) {
inherits(Root, _Container);
function Root(defaults$$1) {
classCallCheck(this, Root);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'root';
if (!_this.nodes) _this.nodes = [];
return _this;
}
Root.prototype.removeChild = function removeChild(child) {
child = this.index(child);
if (child === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[child].raws.before;
}
return _Container.prototype.removeChild.call(this, child);
};
Root.prototype.normalize = function normalize(child, sample, type) {
var nodes = _Container.prototype.normalize.call(this, child);
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
nodes.forEach(function (node) {
node.raws.before = sample.raws.before;
});
}
}
return nodes;
};
/**
* Returns a {@link Result} instance representing the root’s CSS.
*
* @param {processOptions} [opts] - options with only `to` and `map` keys
*
* @return {Result} result with current root’s CSS
*
* @example
* const root1 = postcss.parse(css1, { from: 'a.css' });
* const root2 = postcss.parse(css2, { from: 'b.css' });
* root1.append(root2);
* const result = root1.toResult({ to: 'all.css', map: true });
*/
Root.prototype.toResult = function toResult() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var lazy = new LazyResult(new Processor(), this, opts);
return lazy.stringify();
};
Root.prototype.remove = function remove(child) {
warnOnce('Root#remove is deprecated. Use Root#removeChild');
this.removeChild(child);
};
Root.prototype.prevMap = function prevMap() {
warnOnce('Root#prevMap is deprecated. Use Root#source.input.map');
return this.source.input.map;
};
/**
* @memberof Root#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `after`: the space symbols after the last child to the end of file.
* * `semicolon`: is the last child has an (optional) semicolon.
*
* @example
* postcss.parse('a {}\n').raws //=> { after: '\n' }
* postcss.parse('a {}').raws //=> { after: '' }
*/
return Root;
}(Container);
// import PreviousMap from './previous-map';
var sequence = 0;
/**
* @typedef {object} filePosition
* @property {string} file - path to file
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* Represents the source CSS.
*
* @example
* const root = postcss.parse(css, { from: file });
* const input = root.source.input;
*/
var Input = function () {
/**
* @param {string} css - input CSS source
* @param {object} [opts] - {@link Processor#process} options
*/
function Input(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Input);
/**
* @member {string} - input CSS source
*
* @example
* const input = postcss.parse('a{}', { from: file }).input;
* input.css //=> "a{}";
*/
this.css = css.toString();
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.css = this.css.slice(1);
}
if (opts.from) {
if (/^\w+:\/\//.test(opts.from)) {
/**
* @member {string} - The absolute path to the CSS source file
* defined with the `from` option.
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.file //=> '/home/ai/a.css'
*/
this.file = opts.from;
} else {
this.file = path.resolve(opts.from);
}
}
/*
let map = new PreviousMap(this.css, opts);
if ( map.text ) {
/!**
* @member {PreviousMap} - The input source map passed from
* a compilation step before PostCSS
* (for example, from Sass compiler).
*
* @example
* root.source.input.map.consumer().sources //=> ['a.sass']
*!/
this.map = map;
let file = map.consumer().file;
if ( !this.file && file ) this.file = this.mapResolve(file);
}
*/
if (!this.file) {
sequence += 1;
/**
* @member {string} - The unique ID of the CSS source. It will be
* created if `from` option is not provided
* (because PostCSS does not know the file path).
*
* @example
* const root = postcss.parse(css);
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 1>"
*/
this.id = '<input css ' + sequence + '>';
}
if (this.map) this.map.file = this.from;
}
Input.prototype.error = function error(message, line, column) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var result = void 0;
var origin = this.origin(line, column);
if (origin) {
result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
} else {
result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin);
}
result.input = { line: line, column: column, source: this.css };
if (this.file) result.input.file = this.file;
return result;
};
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* @param {number} line - line in input CSS
* @param {number} column - column in input CSS
*
* @return {filePosition} position in input source
*
* @example
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
*/
Input.prototype.origin = function origin(line, column) {
if (!this.map) return false;
var consumer = this.map.consumer();
var from = consumer.originalPositionFor({ line: line, column: column });
if (!from.source) return false;
var result = {
file: this.mapResolve(from.source),
line: from.line,
column: from.column
};
var source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
};
Input.prototype.mapResolve = function mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
} else {
return path.resolve(this.map.consumer().sourceRoot || '.', file);
}
};
/**
* The CSS source identifier. Contains {@link Input#file} if the user
* set the `from` option, or {@link Input#id} if they did not.
* @type {string}
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css);
* root.source.input.from //=> "<input css 1>"
*/
createClass(Input, [{
key: 'from',
get: function get$$1() {
return this.file || this.id;
}
}]);
return Input;
}();
var SafeParser = function (_Parser) {
inherits(SafeParser, _Parser);
function SafeParser() {
classCallCheck(this, SafeParser);
return possibleConstructorReturn(this, _Parser.apply(this, arguments));
}
SafeParser.prototype.tokenize = function tokenize$$1() {
this.tokens = tokenize(this.input, { ignoreErrors: true });
};
SafeParser.prototype.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2);
if (text.slice(-2) === '*/') text = text.slice(0, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
SafeParser.prototype.unclosedBracket = function unclosedBracket() {};
SafeParser.prototype.unknownWord = function unknownWord(start) {
var buffer = this.tokens.slice(start, this.pos + 1);
this.spaces += buffer.map(function (i) {
return i[1];
}).join('');
};
SafeParser.prototype.unexpectedClose = function unexpectedClose() {
this.current.raws.after += '}';
};
SafeParser.prototype.doubleColon = function doubleColon() {};
SafeParser.prototype.unnamedAtrule = function unnamedAtrule(node) {
node.name = '';
};
SafeParser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var split = void 0;
for (split = colon - 1; split >= 0; split--) {
if (tokens[split][0] === 'word') break;
}
for (split -= 1; split >= 0; split--) {
if (tokens[split][0] !== 'space') {
split += 1;
break;
}
}
var other = tokens.splice(split, tokens.length - split);
this.decl(other);
};
SafeParser.prototype.checkMissedSemicolon = function checkMissedSemicolon() {};
SafeParser.prototype.endFile = function endFile() {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
while (this.current.parent) {
this.current = this.current.parent;
this.current.raws.after = '';
}
};
return SafeParser;
}(Parser);
function safeParse(css, opts) {
var input = new Input(css, opts);
var parser = new SafeParser(input);
parser.tokenize();
parser.loop();
return parser.root;
}
//
/* eslint-disable import/no-unresolved */
var generated = {};
/*
InlineStyle takes arbitrary CSS and generates a flat object
*/
var _InlineStyle = (function (styleSheet) {
var InlineStyle = function () {
function InlineStyle(rules) {
classCallCheck(this, InlineStyle);
this.rules = rules;
}
InlineStyle.prototype.generateStyleObject = function generateStyleObject(executionContext) {
var flatCSS = flatten(this.rules, executionContext).join('');
var hash = murmurhash(flatCSS);
if (!generated[hash]) {
var root = safeParse(flatCSS);
var declPairs = [];
root.each(function (node) {
if (node.type === 'decl') {
declPairs.push([node.prop, node.value]);
} else if (node.type !== 'comment' && process.env.NODE_ENV !== 'production') {
/* eslint-disable no-console */
console.warn('Node of type ' + node.type + ' not supported as an inline style');
}
});
// RN currently does not support differing values for the corner radii of Image
// components (but does for View). It is almost impossible to tell whether we'll have
// support, so we'll just disable multiple values here.
// https://github.com/styled-components/css-to-react-native/issues/11
var styleObject = transformDeclPairs(declPairs, ['borderRadius', 'borderWidth', 'borderColor', 'borderStyle']);
var styles = styleSheet.create({
generated: styleObject
});
generated[hash] = styles.generated;
}
return generated[hash];
};
return InlineStyle;
}();
return InlineStyle;
});
//
function isTag(target) /* : %checks */{
return typeof target === 'string';
}
//
function isStyledComponent(target) /* : %checks */{
return typeof target === 'function' && typeof target.styledComponentId === 'string';
}
//
/* eslint-disable no-undef */
function getComponentName(target) {
return target.displayName || target.name || 'Component';
}
//
var determineTheme = (function (props, fallbackTheme, defaultProps) {
// Props should take precedence over ThemeProvider, which should take precedence over
// defaultProps, but React automatically puts defaultProps on props.
/* eslint-disable react/prop-types */
var isDefaultTheme = defaultProps && props.theme === defaultProps.theme;
var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme;
/* eslint-enable */
return theme;
});
//
/**
* Creates a broadcast that can be listened to, i.e. simple event emitter
*
* @see https://github.com/ReactTraining/react-broadcast
*/
var createBroadcast = function createBroadcast(initialState) {
var listeners = {};
var id = 0;
var state = initialState;
function publish(nextState) {
state = nextState;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in listeners) {
var listener = listeners[key];
if (listener === undefined) {
// eslint-disable-next-line no-continue
continue;
}
listener(state);
}
}
function subscribe(listener) {
var currentId = id;
listeners[currentId] = listener;
id += 1;
listener(state);
return currentId;
}
function unsubscribe(unsubID) {
listeners[unsubID] = undefined;
}
return { publish: publish, subscribe: subscribe, unsubscribe: unsubscribe };
};
//
// Helper to call a given function, only once
var once = (function (cb) {
var called = false;
return function () {
if (!called) {
called = true;
cb();
}
};
});
var _ThemeProvider$childC;
var _ThemeProvider$contex;
//
/* globals React$Element */
// NOTE: DO NOT CHANGE, changing this is a semver major change!
var CHANNEL = '__styled-components__';
var CHANNEL_NEXT = CHANNEL + 'next__';
var CONTEXT_CHANNEL_SHAPE = PropTypes.shape({
getTheme: PropTypes.func,
subscribe: PropTypes.func,
unsubscribe: PropTypes.func
});
var warnChannelDeprecated = void 0;
if (process.env.NODE_ENV !== 'production') {
warnChannelDeprecated = once(function () {
// eslint-disable-next-line no-console
console.error('Warning: Usage of `context.' + CHANNEL + '` as a function is deprecated. It will be replaced with the object on `.context.' + CHANNEL_NEXT + '` in a future version.');
});
}
var isFunction = function isFunction(test) {
return typeof test === 'function';
};
/**
* Provide a theme to an entire react component tree via context and event listeners (have to do
* both context and event emitter as pure components block context updates)
*/
var ThemeProvider = function (_Component) {
inherits(ThemeProvider, _Component);
function ThemeProvider() {
classCallCheck(this, ThemeProvider);
var _this = possibleConstructorReturn(this, _Component.call(this));
_this.unsubscribeToOuterId = -1;
_this.getTheme = _this.getTheme.bind(_this);
return _this;
}
ThemeProvider.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme
// with the outer theme
var outerContext = this.context[CHANNEL_NEXT];
if (outerContext !== undefined) {
this.unsubscribeToOuterId = outerContext.subscribe(function (theme) {
_this2.outerTheme = theme;
if (_this2.broadcast !== undefined) {
_this2.publish(_this2.props.theme);
}
});
}
this.broadcast = createBroadcast(this.getTheme());
};
ThemeProvider.prototype.getChildContext = function getChildContext() {
var _this3 = this,
_babelHelpers$extends;
return _extends({}, this.context, (_babelHelpers$extends = {}, _babelHelpers$extends[CHANNEL_NEXT] = {
getTheme: this.getTheme,
subscribe: this.broadcast.subscribe,
unsubscribe: this.broadcast.unsubscribe
}, _babelHelpers$extends[CHANNEL] = function (subscriber) {
if (process.env.NODE_ENV !== 'production') {
warnChannelDeprecated();
}
// Patch the old `subscribe` provide via `CHANNEL` for older clients.
var unsubscribeId = _this3.broadcast.subscribe(subscriber);
return function () {
return _this3.broadcast.unsubscribe(unsubscribeId);
};
}, _babelHelpers$extends));
};
ThemeProvider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.theme !== nextProps.theme) {
this.publish(nextProps.theme);
}
};
ThemeProvider.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribeToOuterId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeToOuterId);
}
};
// Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
ThemeProvider.prototype.getTheme = function getTheme(passedTheme) {
var theme = passedTheme || this.props.theme;
if (isFunction(theme)) {
var mergedTheme = theme(this.outerTheme);
if (process.env.NODE_ENV !== 'production' && !isPlainObject(mergedTheme)) {
throw new Error(process.env.NODE_ENV !== 'production' ? '[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!' : '');
}
return mergedTheme;
}
if (!isPlainObject(theme)) {
throw new Error(process.env.NODE_ENV !== 'production' ? '[ThemeProvider] Please make your theme prop a plain object' : '');
}
return _extends({}, this.outerTheme, theme);
};
ThemeProvider.prototype.publish = function publish(theme) {
this.broadcast.publish(this.getTheme(theme));
};
ThemeProvider.prototype.render = function render() {
if (!this.props.children) {
return null;
}
return React__default.Children.only(this.props.children);
};
return ThemeProvider;
}(React.Component);
ThemeProvider.childContextTypes = (_ThemeProvider$childC = {}, _ThemeProvider$childC[CHANNEL] = PropTypes.func, _ThemeProvider$childC[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$childC);
ThemeProvider.contextTypes = (_ThemeProvider$contex = {}, _ThemeProvider$contex[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$contex);
//
var _StyledNativeComponent = (function (constructWithOptions, InlineStyle) {
var BaseStyledNativeComponent = function (_Component) {
inherits(BaseStyledNativeComponent, _Component);
function BaseStyledNativeComponent() {
var _temp, _this, _ret;
classCallCheck(this, BaseStyledNativeComponent);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.attrs = {}, _this.state = {
theme: null,
generatedStyles: undefined
}, _this.unsubscribeId = -1, _this.onRef = function (node) {
// eslint-disable-next-line react/prop-types
var innerRef = _this.props.innerRef;
_this.root = node;
if (typeof innerRef === 'function') {
innerRef(node);
}
}, _temp), possibleConstructorReturn(_this, _ret);
}
BaseStyledNativeComponent.prototype.unsubscribeFromContext = function unsubscribeFromContext() {
if (this.unsubscribeId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
}
};
BaseStyledNativeComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props) {
var attrs = this.constructor.attrs;
var context = _extends({}, props, { theme: theme });
if (attrs === undefined) {
return context;
}
this.attrs = Object.keys(attrs).reduce(function (acc, key) {
var attr = attrs[key];
// eslint-disable-next-line no-param-reassign
acc[key] = typeof attr === 'function' ? attr(context) : attr;
return acc;
}, {});
return _extends({}, context, this.attrs);
};
BaseStyledNativeComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
var inlineStyle = this.constructor.inlineStyle;
var executionContext = this.buildExecutionContext(theme, props);
return inlineStyle.generateStyleObject(executionContext);
};
BaseStyledNativeComponent.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// If there is a theme in the context, subscribe to the event emitter. This
// is necessary due to pure components blocking context updates, this circumvents
// that by updating when an event is emitted
var styledContext = this.context[CHANNEL_NEXT];
if (styledContext !== undefined) {
var subscribe = styledContext.subscribe;
this.unsubscribeId = subscribe(function (nextTheme) {
// This will be called once immediately
var theme = determineTheme(_this2.props, nextTheme, _this2.constructor.defaultProps);
var generatedStyles = _this2.generateAndInjectStyles(theme, _this2.props);
_this2.setState({ theme: theme, generatedStyles: generatedStyles });
});
} else {
// eslint-disable-next-line react/prop-types
var theme = this.props.theme || {};
var generatedStyles = this.generateAndInjectStyles(theme, this.props);
this.setState({ theme: theme, generatedStyles: generatedStyles });
}
};
BaseStyledNativeComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this3 = this;
this.setState(function (oldState) {
var theme = determineTheme(nextProps, oldState.theme, _this3.constructor.defaultProps);
var generatedStyles = _this3.generateAndInjectStyles(theme, nextProps);
return { theme: theme, generatedStyles: generatedStyles };
});
};
BaseStyledNativeComponent.prototype.componentWillUnmount = function componentWillUnmount() {
this.unsubscribeFromContext();
};
BaseStyledNativeComponent.prototype.setNativeProps = function setNativeProps(nativeProps) {
if (this.root !== undefined) {
// $FlowFixMe
this.root.setNativeProps(nativeProps);
} else if (process.env.NODE_ENV !== 'production') {
var displayName = this.constructor.displayName;
// eslint-disable-next-line no-console
console.warn('setNativeProps was called on a Styled Component wrapping a stateless functional component. ' + 'In this case no ref will be stored, and instead an innerRef prop will be passed on.\n' + ('Check whether the stateless functional component is passing on innerRef as a ref in ' + displayName + '.'));
}
};
BaseStyledNativeComponent.prototype.render = function render() {
// eslint-disable-next-line react/prop-types
var _props = this.props,
children = _props.children,
style = _props.style;
var generatedStyles = this.state.generatedStyles;
var target = this.constructor.target;
var propsForElement = _extends({}, this.attrs, this.props, {
style: [generatedStyles, style]
});
if (!isStyledComponent(target) && (
// NOTE: We can't pass a ref to a stateless functional component
typeof target !== 'function' || target.prototype && 'isReactComponent' in target.prototype)) {
propsForElement.ref = this.onRef;
delete propsForElement.innerRef;
} else {
propsForElement.innerRef = this.onRef;
}
return React.createElement(target, propsForElement, children);
};
return BaseStyledNativeComponent;
}(React.Component);
var createStyledNativeComponent = function createStyledNativeComponent(target, options, rules) {
var _StyledNativeComponen;
var _options$displayName = options.displayName,
displayName = _options$displayName === undefined ? isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')' : _options$displayName,
_options$ParentCompon = options.ParentComponent,
ParentComponent = _options$ParentCompon === undefined ? BaseStyledNativeComponent : _options$ParentCompon,
extendingRules = options.rules,
attrs = options.attrs;
var inlineStyle = new InlineStyle(extendingRules === undefined ? rules : extendingRules.concat(rules));
var StyledNativeComponent = function (_ParentComponent) {
inherits(StyledNativeComponent, _ParentComponent);
function StyledNativeComponent() {
classCallCheck(this, StyledNativeComponent);
return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments));
}
StyledNativeComponent.withComponent = function withComponent(tag) {
var _ = options.displayName,
__ = options.componentId,
optionsToCopy = objectWithoutProperties(options, ['displayName', 'componentId']);
var newOptions = _extends({}, optionsToCopy, {
ParentComponent: StyledNativeComponent
});
return createStyledNativeComponent(tag, newOptions, rules);
};
// NOTE: This is so that isStyledComponent passes for the innerRef unwrapping
createClass(StyledNativeComponent, null, [{
key: 'extend',
get: function get$$1() {
var _ = options.displayName,
__ = options.componentId,
rulesFromOptions = options.rules,
optionsToCopy = objectWithoutProperties(options, ['displayName', 'componentId', 'rules']);
var newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules);
var newOptions = _extends({}, optionsToCopy, {
rules: newRules,
ParentComponent: StyledNativeComponent
});
return constructWithOptions(createStyledNativeComponent, target, newOptions);
}
}]);
return StyledNativeComponent;
}(ParentComponent);
StyledNativeComponent.displayName = displayName;
StyledNativeComponent.target = target;
StyledNativeComponent.attrs = attrs;
StyledNativeComponent.inlineStyle = inlineStyle;
StyledNativeComponent.contextTypes = (_StyledNativeComponen = {}, _StyledNativeComponen[CHANNEL] = PropTypes.func, _StyledNativeComponen[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _StyledNativeComponen);
StyledNativeComponent.styledComponentId = 'StyledNativeComponent';
return StyledNativeComponent;
};
return createStyledNativeComponent;
});
//
var _constructWithOptions = (function (css) {
var constructWithOptions = function constructWithOptions(componentConstructor, tag) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!reactIs.isValidElementType(tag)) {
throw new Error(process.env.NODE_ENV !== 'production' ? 'Cannot create styled-component for component: ' + String(tag) : '');
}
/* This is callable directly as a template function */
// $FlowFixMe: Not typed to avoid destructuring arguments
var templateFunction = function templateFunction() {
return componentConstructor(tag, options, css.apply(undefined, arguments));
};
/* If config methods are called, wrap up a new template function and merge options */
templateFunction.withConfig = function (config) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
};
templateFunction.attrs = function (attrs) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {
attrs: _extends({}, options.attrs || {}, attrs)
}));
};
return templateFunction;
};
return constructWithOptions;
});
//
var interleave = (function (strings, interpolations) {
return interpolations.reduce(function (array, interp, i) {
return array.concat(interp, strings[i + 1]);
}, [strings[0]]);
});
//
var css = (function (strings) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
return flatten(interleave(strings, interpolations));
});
//
/* globals ReactClass */
var wrapWithTheme = function wrapWithTheme(Component$$1) {
var _WithTheme$contextTyp;
var componentName = Component$$1.displayName || Component$$1.name || 'Component';
var isStatelessFunctionalComponent = typeof Component$$1 === 'function' && !(Component$$1.prototype && 'isReactComponent' in Component$$1.prototype);
// NOTE: We can't pass a ref to a stateless functional component
var shouldSetInnerRef = isStyledComponent(Component$$1) || isStatelessFunctionalComponent;
var WithTheme = function (_React$Component) {
inherits(WithTheme, _React$Component);
function WithTheme() {
var _temp, _this, _ret;
classCallCheck(this, WithTheme);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {}, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret);
}
// NOTE: This is so that isStyledComponent passes for the innerRef unwrapping
WithTheme.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var defaultProps = this.constructor.defaultProps;
var styledContext = this.context[CHANNEL_NEXT];
var themeProp = determineTheme(this.props, undefined, defaultProps);
if (styledContext === undefined && themeProp === undefined && process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps');
} else if (styledContext === undefined && themeProp !== undefined) {
this.setState({ theme: themeProp });
} else {
var subscribe = styledContext.subscribe;
this.unsubscribeId = subscribe(function (nextTheme) {
var theme = determineTheme(_this2.props, nextTheme, defaultProps);
_this2.setState({ theme: theme });
});
}
};
WithTheme.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var defaultProps = this.constructor.defaultProps;
this.setState(function (oldState) {
var theme = determineTheme(nextProps, oldState.theme, defaultProps);
return { theme: theme };
});
};
WithTheme.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribeId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
}
};
WithTheme.prototype.render = function render() {
var props = _extends({
theme: this.state.theme
}, this.props);
if (!shouldSetInnerRef) {
props.ref = props.innerRef;
delete props.innerRef;
}
return React__default.createElement(Component$$1, props);
};
return WithTheme;
}(React__default.Component);
WithTheme.displayName = 'WithTheme(' + componentName + ')';
WithTheme.styledComponentId = 'withTheme';
WithTheme.contextTypes = (_WithTheme$contextTyp = {}, _WithTheme$contextTyp[CHANNEL] = PropTypes.func, _WithTheme$contextTyp[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _WithTheme$contextTyp);
return hoistStatics(WithTheme, Component$$1);
};
//
/* eslint-disable import/no-unresolved */
var constructWithOptions = _constructWithOptions(css);
var InlineStyle = _InlineStyle(reactPrimitives.StyleSheet);
var StyledNativeComponent = _StyledNativeComponent(constructWithOptions, InlineStyle);
var styled = function styled(tag) {
return constructWithOptions(StyledNativeComponent, tag);
};
/* React native lazy-requires each of these modules for some reason, so let's
* assume it's for a good reason and not eagerly load them all */
var aliases = 'Image Text Touchable View ';
/* Define a getter for each alias which simply gets the reactNative component
* and passes it to styled */
aliases.split(/\s+/m).forEach(function (alias) {
return Object.defineProperty(styled, alias, {
enumerable: true,
configurable: false,
get: function get() {
return styled(reactPrimitives[alias]);
}
});
});
exports.css = css;
exports.isStyledComponent = isStyledComponent;
exports.ThemeProvider = ThemeProvider;
exports.withTheme = wrapWithTheme;
exports['default'] = styled;
//# sourceMappingURL=styled-components-primitives.cjs.js.map
| mit |
sufuf3/cdnjs | ajax/libs/angular-ui-grid/4.4.9/ui-grid.expandable.js | 22182 | /*!
* ui-grid - v4.4.9 - 2018-04-30
* Copyright (c) 2018 ; License: MIT
*/
(function () {
'use strict';
/**
* @ngdoc overview
* @name ui.grid.expandable
* @description
*
* # ui.grid.expandable
*
* <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div>
*
* This module provides the ability to create subgrids with the ability to expand a row
* to show the subgrid.
*
* <div doc-module-components="ui.grid.expandable"></div>
*/
var module = angular.module('ui.grid.expandable', ['ui.grid']);
/**
* @ngdoc service
* @name ui.grid.expandable.service:uiGridExpandableService
*
* @description Services for the expandable grid
*/
module.service('uiGridExpandableService', ['gridUtil', '$compile', function (gridUtil, $compile) {
var service = {
initializeGrid: function (grid) {
grid.expandable = {};
grid.expandable.expandedAll = false;
/**
* @ngdoc object
* @name enableExpandable
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Whether or not to use expandable feature, allows you to turn off expandable on specific grids
* within your application, or in specific modes on _this_ grid. Defaults to true.
* @example
* <pre>
* $scope.gridOptions = {
* enableExpandable: false
* }
* </pre>
*/
grid.options.enableExpandable = grid.options.enableExpandable !== false;
/**
* @ngdoc object
* @name showExpandAllButton
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Whether or not to display the expand all button, allows you to hide expand all button on specific grids
* within your application, or in specific modes on _this_ grid. Defaults to true.
* @example
* <pre>
* $scope.gridOptions = {
* showExpandAllButton: false
* }
* </pre>
*/
grid.options.showExpandAllButton = grid.options.showExpandAllButton !== false;
/**
* @ngdoc object
* @name expandableRowHeight
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Height in pixels of the expanded subgrid. Defaults to
* 150
* @example
* <pre>
* $scope.gridOptions = {
* expandableRowHeight: 150
* }
* </pre>
*/
grid.options.expandableRowHeight = grid.options.expandableRowHeight || 150;
/**
* @ngdoc object
* @name expandableRowHeaderWidth
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Width in pixels of the expandable column. Defaults to 40
* @example
* <pre>
* $scope.gridOptions = {
* expandableRowHeaderWidth: 40
* }
* </pre>
*/
grid.options.expandableRowHeaderWidth = grid.options.expandableRowHeaderWidth || 40;
/**
* @ngdoc object
* @name expandableRowTemplate
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Mandatory. The template for your expanded row
* @example
* <pre>
* $scope.gridOptions = {
* expandableRowTemplate: 'expandableRowTemplate.html'
* }
* </pre>
*/
if ( grid.options.enableExpandable && !grid.options.expandableRowTemplate ){
gridUtil.logError( 'You have not set the expandableRowTemplate, disabling expandable module' );
grid.options.enableExpandable = false;
}
/**
* @ngdoc object
* @name ui.grid.expandable.api:PublicApi
*
* @description Public Api for expandable feature
*/
/**
* @ngdoc object
* @name ui.grid.expandable.api:GridRow
*
* @description Additional properties added to GridRow when using the expandable module
*/
/**
* @ngdoc object
* @name ui.grid.expandable.api:GridOptions
*
* @description Options for configuring the expandable feature, these are available to be
* set using the ui-grid {@link ui.grid.class:GridOptions gridOptions}
*/
var publicApi = {
events: {
expandable: {
/**
* @ngdoc event
* @name rowExpandedBeforeStateChanged
* @eventOf ui.grid.expandable.api:PublicApi
* @description raised when row is expanding or collapsing
* <pre>
* gridApi.expandable.on.rowExpandedBeforeStateChanged(scope,function(row){})
* </pre>
* @param {scope} scope the application scope
* @param {GridRow} row the row that was expanded
*/
rowExpandedBeforeStateChanged: function(scope, row){
},
/**
* @ngdoc event
* @name rowExpandedStateChanged
* @eventOf ui.grid.expandable.api:PublicApi
* @description raised when row expanded or collapsed
* <pre>
* gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})
* </pre>
* @param {scope} scope the application scope
* @param {GridRow} row the row that was expanded
*/
rowExpandedStateChanged: function (scope, row) {
}
}
},
methods: {
expandable: {
/**
* @ngdoc method
* @name toggleRowExpansion
* @methodOf ui.grid.expandable.api:PublicApi
* @description Toggle a specific row
* <pre>
* gridApi.expandable.toggleRowExpansion(rowEntity);
* </pre>
* @param {object} rowEntity the data entity for the row you want to expand
*/
toggleRowExpansion: function (rowEntity) {
var row = grid.getRow(rowEntity);
if (row !== null) {
service.toggleRowExpansion(grid, row);
}
},
/**
* @ngdoc method
* @name expandAllRows
* @methodOf ui.grid.expandable.api:PublicApi
* @description Expand all subgrids.
* <pre>
* gridApi.expandable.expandAllRows();
* </pre>
*/
expandAllRows: function() {
service.expandAllRows(grid);
},
/**
* @ngdoc method
* @name collapseAllRows
* @methodOf ui.grid.expandable.api:PublicApi
* @description Collapse all subgrids.
* <pre>
* gridApi.expandable.collapseAllRows();
* </pre>
*/
collapseAllRows: function() {
service.collapseAllRows(grid);
},
/**
* @ngdoc method
* @name toggleAllRows
* @methodOf ui.grid.expandable.api:PublicApi
* @description Toggle all subgrids.
* <pre>
* gridApi.expandable.toggleAllRows();
* </pre>
*/
toggleAllRows: function() {
service.toggleAllRows(grid);
},
/**
* @ngdoc function
* @name expandRow
* @methodOf ui.grid.expandable.api:PublicApi
* @description Expand the data row
* @param {object} rowEntity gridOptions.data[] array instance
*/
expandRow: function (rowEntity) {
var row = grid.getRow(rowEntity);
if (row !== null && !row.isExpanded) {
service.toggleRowExpansion(grid, row);
}
},
/**
* @ngdoc function
* @name collapseRow
* @methodOf ui.grid.expandable.api:PublicApi
* @description Collapse the data row
* @param {object} rowEntity gridOptions.data[] array instance
*/
collapseRow: function (rowEntity) {
var row = grid.getRow(rowEntity);
if (row !== null && row.isExpanded) {
service.toggleRowExpansion(grid, row);
}
},
/**
* @ngdoc function
* @name getExpandedRows
* @methodOf ui.grid.expandable.api:PublicApi
* @description returns all expandedRow's entity references
*/
getExpandedRows: function () {
return service.getExpandedRows(grid).map(function (gridRow) {
return gridRow.entity;
});
}
}
}
};
grid.api.registerEventsFromObject(publicApi.events);
grid.api.registerMethodsFromObject(publicApi.methods);
},
toggleRowExpansion: function (grid, row) {
// trigger the "before change" event. Can change row height dynamically this way.
grid.api.expandable.raise.rowExpandedBeforeStateChanged(row);
/**
* @ngdoc object
* @name isExpanded
* @propertyOf ui.grid.expandable.api:GridRow
* @description Whether or not the row is currently expanded.
* @example
* <pre>
* $scope.api.expandable.on.rowExpandedStateChanged($scope, function (row) {
* if (row.isExpanded) {
* //...
* }
* });
* </pre>
*/
row.isExpanded = !row.isExpanded;
if (angular.isUndefined(row.expandedRowHeight)){
row.expandedRowHeight = grid.options.expandableRowHeight;
}
if (row.isExpanded) {
row.height = row.grid.options.rowHeight + row.expandedRowHeight;
grid.expandable.expandedAll = service.getExpandedRows(grid).length === grid.rows.length;
} else {
row.height = row.grid.options.rowHeight;
grid.expandable.expandedAll = false;
}
grid.api.expandable.raise.rowExpandedStateChanged(row);
},
expandAllRows: function(grid) {
grid.renderContainers.body.visibleRowCache.forEach( function(row) {
if (!row.isExpanded && !(row.entity.subGridOptions && row.entity.subGridOptions.disableRowExpandable)) {
service.toggleRowExpansion(grid, row);
}
});
grid.expandable.expandedAll = true;
grid.queueGridRefresh();
},
collapseAllRows: function(grid) {
grid.renderContainers.body.visibleRowCache.forEach( function(row) {
if (row.isExpanded) {
service.toggleRowExpansion(grid, row);
}
});
grid.expandable.expandedAll = false;
grid.queueGridRefresh();
},
toggleAllRows: function(grid) {
if (grid.expandable.expandedAll) {
service.collapseAllRows(grid);
}
else {
service.expandAllRows(grid);
}
},
getExpandedRows: function (grid) {
return grid.rows.filter(function (row) {
return row.isExpanded;
});
}
};
return service;
}]);
/**
* @ngdoc object
* @name enableExpandableRowHeader
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Show a rowHeader to provide the expandable buttons. If set to false then implies
* you're going to use a custom method for expanding and collapsing the subgrids. Defaults to true.
* @example
* <pre>
* $scope.gridOptions = {
* enableExpandableRowHeader: false
* }
* </pre>
*/
module.directive('uiGridExpandable', ['uiGridExpandableService', '$templateCache',
function (uiGridExpandableService, $templateCache) {
return {
replace: true,
priority: 0,
require: '^uiGrid',
scope: false,
compile: function () {
return {
pre: function ($scope, $elm, $attrs, uiGridCtrl) {
uiGridExpandableService.initializeGrid(uiGridCtrl.grid);
if (!uiGridCtrl.grid.options.enableExpandable) {
return;
}
if (uiGridCtrl.grid.options.enableExpandableRowHeader !== false ) {
var expandableRowHeaderColDef = {
name: 'expandableButtons',
displayName: '',
exporterSuppressExport: true,
enableColumnResizing: false,
enableColumnMenu: false,
width: uiGridCtrl.grid.options.expandableRowHeaderWidth || 40
};
expandableRowHeaderColDef.cellTemplate = $templateCache.get('ui-grid/expandableRowHeader');
expandableRowHeaderColDef.headerCellTemplate = $templateCache.get('ui-grid/expandableTopRowHeader');
uiGridCtrl.grid.addRowHeaderColumn(expandableRowHeaderColDef, -90);
}
},
post: function ($scope, $elm, $attrs, uiGridCtrl) {
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.expandable.directive:uiGrid
* @description stacks on the uiGrid directive to register child grid with parent row when child is created
*/
module.directive('uiGrid', ['uiGridExpandableService', '$templateCache',
function (uiGridExpandableService, $templateCache) {
return {
replace: true,
priority: 599,
require: '^uiGrid',
scope: false,
compile: function () {
return {
pre: function ($scope, $elm, $attrs, uiGridCtrl) {
uiGridCtrl.grid.api.core.on.renderingComplete($scope, function() {
//if a parent grid row is on the scope, then add the parentRow property to this childGrid
if ($scope.row && $scope.row.grid && $scope.row.grid.options && $scope.row.grid.options.enableExpandable) {
/**
* @ngdoc directive
* @name ui.grid.expandable.class:Grid
* @description Additional Grid properties added by expandable module
*/
/**
* @ngdoc object
* @name parentRow
* @propertyOf ui.grid.expandable.class:Grid
* @description reference to the expanded parent row that owns this grid
*/
uiGridCtrl.grid.parentRow = $scope.row;
//todo: adjust height on parent row when child grid height changes. we need some sort of gridHeightChanged event
// uiGridCtrl.grid.core.on.canvasHeightChanged($scope, function(oldHeight, newHeight) {
// uiGridCtrl.grid.parentRow = newHeight;
// });
}
});
},
post: function ($scope, $elm, $attrs, uiGridCtrl) {
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.expandable.directive:uiGridExpandableRow
* @description directive to render the expandable row template
*/
module.directive('uiGridExpandableRow',
['uiGridExpandableService', '$timeout', '$compile', 'uiGridConstants','gridUtil','$interval', '$log',
function (uiGridExpandableService, $timeout, $compile, uiGridConstants, gridUtil, $interval, $log) {
return {
replace: false,
priority: 0,
scope: false,
compile: function () {
return {
pre: function ($scope, $elm, $attrs, uiGridCtrl) {
gridUtil.getTemplate($scope.grid.options.expandableRowTemplate).then(
function (template) {
if ($scope.grid.options.expandableRowScope) {
/**
* @ngdoc object
* @name expandableRowScope
* @propertyOf ui.grid.expandable.api:GridOptions
* @description Variables of object expandableScope will be available in the scope of the expanded subgrid
* @example
* <pre>
* $scope.gridOptions = {
* expandableRowScope: expandableScope
* }
* </pre>
*/
var expandableRowScope = $scope.grid.options.expandableRowScope;
for (var property in expandableRowScope) {
if (expandableRowScope.hasOwnProperty(property)) {
$scope[property] = expandableRowScope[property];
}
}
}
var expandedRowElement = angular.element(template);
$elm.append(expandedRowElement);
expandedRowElement = $compile(expandedRowElement)($scope);
$scope.row.expandedRendered = true;
});
},
post: function ($scope, $elm, $attrs, uiGridCtrl) {
$scope.$on('$destroy', function() {
$scope.row.expandedRendered = false;
});
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.expandable.directive:uiGridRow
* @description stacks on the uiGridRow directive to add support for expandable rows
*/
module.directive('uiGridRow',
['$compile', 'gridUtil', '$templateCache',
function ($compile, gridUtil, $templateCache) {
return {
priority: -200,
scope: false,
compile: function ($elm, $attrs) {
return {
pre: function ($scope, $elm, $attrs, controllers) {
if (!$scope.grid.options.enableExpandable) {
return;
}
$scope.expandableRow = {};
$scope.expandableRow.shouldRenderExpand = function () {
var ret = $scope.colContainer.name === 'body' && $scope.grid.options.enableExpandable !== false && $scope.row.isExpanded && (!$scope.grid.isScrollingVertically || $scope.row.expandedRendered);
return ret;
};
$scope.expandableRow.shouldRenderFiller = function () {
var ret = $scope.row.isExpanded && ( $scope.colContainer.name !== 'body' || ($scope.grid.isScrollingVertically && !$scope.row.expandedRendered));
return ret;
};
/*
* Commented out @PaulL1. This has no purpose that I can see, and causes #2964. If this code needs to be reinstated for some
* reason it needs to use drawnWidth, not width, and needs to check column visibility. It should really use render container
* visible column cache also instead of checking column.renderContainer.
function updateRowContainerWidth() {
var grid = $scope.grid;
var colWidth = 0;
grid.columns.forEach( function (column) {
if (column.renderContainer === 'left') {
colWidth += column.width;
}
});
colWidth = Math.floor(colWidth);
return '.grid' + grid.id + ' .ui-grid-pinned-container-' + $scope.colContainer.name + ', .grid' + grid.id +
' .ui-grid-pinned-container-' + $scope.colContainer.name + ' .ui-grid-render-container-' + $scope.colContainer.name +
' .ui-grid-viewport .ui-grid-canvas .ui-grid-row { width: ' + colWidth + 'px; }';
}
if ($scope.colContainer.name === 'left') {
$scope.grid.registerStyleComputation({
priority: 15,
func: updateRowContainerWidth
});
}*/
},
post: function ($scope, $elm, $attrs, controllers) {
}
};
}
};
}]);
/**
* @ngdoc directive
* @name ui.grid.expandable.directive:uiGridViewport
* @description stacks on the uiGridViewport directive to append the expandable row html elements to the
* default gridRow template
*/
module.directive('uiGridViewport',
['$compile', 'gridUtil', '$templateCache',
function ($compile, gridUtil, $templateCache) {
return {
priority: -200,
scope: false,
compile: function ($elm, $attrs) {
//todo: this adds ng-if watchers to each row even if the grid is not using expandable directive
// or options.enableExpandable == false
// The alternative is to compile the template and append to each row in a uiGridRow directive
var rowRepeatDiv = angular.element($elm.children().children()[0]);
var expandedRowFillerElement = $templateCache.get('ui-grid/expandableScrollFiller');
var expandedRowElement = $templateCache.get('ui-grid/expandableRow');
rowRepeatDiv.append(expandedRowElement);
rowRepeatDiv.append(expandedRowFillerElement);
return {
pre: function ($scope, $elm, $attrs, controllers) {
},
post: function ($scope, $elm, $attrs, controllers) {
}
};
}
};
}]);
})();
| mit |
9590/webdav | node_modules/asyncjs/lib/test.js | 8995 | /*!
* async.js
* Copyright(c) 2010 Fabian Jakobs <fabian.jakobs@web.de>
* MIT Licensed
*/
var util = require("util")
var async = require("./async")
require("./plugins/utils")
var empty = function(next) { next() }
exports.TestGenerator = function(source) {
async.Generator.call(this, source)
}
util.inherits(exports.TestGenerator, async.Generator)
;(function() {
this.exec = function() {
this.run().report().summary(function(err, passed) {
process.exit(!err && passed ? 0 : 1)
})
}
this.run = function() {
return this.setupTest()
.each(function(test, next) {
test.test(function(err, passed) {
test.err = err
test.passed = passed
next()
})
})
}
this.reportJUnit = function() {
var passed = 0
var failed = 0
var context
var xml = []
var suiteXml = []
var lastTest
function writeSuite(xml, test, testsXml) {
if (context) {
xml.push('\n<testsuite "name"="', xmlEscape(test.suiteName), '" "tests"="', test.count, '" "failures"="', test.context.suiteFailed, '">')
xml.push.apply(xml, testsXml)
xml.push("\n</testsuite>")
}
}
function xmlEscape(text){
return text.replace(/[<>"'&]/g, function(value){
switch(value){
case "<": return "<";
case ">": return ">";
case "\"": return """;
case "'": return "'";
case "&": return "&";
}
});
}
this.each(function(test) {
if (test.passed)
passed += 1
else {
failed += 1
test.context.suiteFailed = test.context.suiteFailed ? test.context.suiteFailed + 1 : 0
}
// write test suite
if (context !== test.context) {
writeSuite(xml, test, suiteXml)
context = test.context;
suiteXml = []
}
lastTest = test
suiteXml.push('\n<testcase "name"="', xmlEscape(test.name), '">')
if (!test.passed)
suiteXml.push('\n <failure "message"="', xmlEscape(test.err.toString()), '"><![CDATA[' + (test.err.stack || test.err) + ']]></failure>')
suiteXml.push("\n</testcase>");
}).end(function(err) {
err && console.log(err.stack)
if (context)
writeSuite(xml, lastTest, suiteXml)
xml.unshift('<testsuites>')
xml.push("\n</testsuites>")
console.log(xml.join(""))
})
}
this.report = function() {
return this.each(function(test, next) {
var color = test.skip ? "\x1b[33m" : (test.passed ? "\x1b[32m" : "\x1b[31m")
var result = test.skip ? "SKIPPED" : (test.passed ? "OK" : "FAIL")
var name = test.name
if (test.suiteName)
name = test.suiteName + ": " + test.name
console.log(color + "[" + test.count + "/" + test.index + "] " + name + " " + result + "\x1b[0m")
if (!test.passed)
if (test.err.stack)
console.log(test.err.stack)
else
console.log(test.err)
next()
})
}
this.summary = function(callback) {
var passed = 0
var failed = 0
var skipped = 0
this.each(function(test) {
if (test.skip)
skipped += 1
else if (test.passed)
passed += 1
else
failed += 1
}).end(function(err) {
if (err) {
console.log("")
console.log("\x1b[31mTest run aborted. Not all tests could be run!")
if (err.stack) {
console.log(err.stack)
}
else
console.log(err)
console.log("\x1b[0m")
}
console.log("")
console.log("Summary:")
console.log("")
console.log("Total number of tests: " + (passed + failed + skipped))
passed && console.log("\x1b[32mPassed tests: " + passed + "\x1b[0m")
skipped && console.log("\x1b[33mSkipped tests: " + skipped + "\x1b[0m")
failed && console.log("\x1b[31mFailed tests: " + failed + "\x1b[0m")
console.log("")
callback(err, failed == 0)
})
}
this.setupTest = function() {
return this.each(function(test, next) {
var context = test.context || this
if (test.setUp)
var setUp = async.makeAsync(0, test.setUp, context)
else
setUp = empty
var tearDownCalled = false
if (test.tearDown)
var tearDownInner = async.makeAsync(0, test.tearDown, context)
else
tearDownInner = empty
function tearDown(next) {
tearDownCalled = true
tearDownInner.call(test.context, next)
}
var testFn = async.makeAsync(0, test.fn, context)
test.test = function(callback) {
var called
function errorListener(e) {
if (called)
return
called = true
process.removeListener('uncaughtException', errorListener)
if (!tearDownCalled) {
async.list([tearDown])
.call()
.timeout(test.timeout)
.end(function() {
callback(e, false)
}) }
else
callback(e, false)
}
process.addListener('uncaughtException', errorListener)
var chain = test.skip ?
[test.setUpSuite, test.tearDownSuite] :
[test.setUpSuite, setUp, testFn, tearDown, test.tearDownSuite]
async.list(chain)
.delay(0)
.call(context)
.timeout(test.timeout)
.toArray(false, function(errors, values) {
if (called)
return
called = true
var err = errors[2]
process.removeListener('uncaughtException', errorListener)
callback(err, !err)
})
}
next()
})
}
}).call(exports.TestGenerator.prototype)
exports.testcase = function(testcase, suiteName, timeout) {
var methods = []
for (var method in testcase)
methods.push(method)
var setUp = testcase.setUp || null
var tearDown = testcase.tearDown || null
var single
methods.forEach(function(name) {
if (name.charAt(0) == '>')
single = name
})
if (single)
methods = [single]
var testNames = methods.filter(function(method) {
return method.match(/^[>\!]?test/) && typeof(testcase[method]) == "function"
})
var count = testNames.length
var i=1
var tests = testNames.map(function(name) {
var skip = name.charAt(0) === "!"
return {
suiteName: suiteName || testcase.name || "",
name: name,
setUp: setUp,
tearDown: tearDown,
context: testcase,
timeout: timeout || testcase.timeout || 3000,
fn: testcase[name],
count: count,
setUpSuite: i-1 == 0 && testcase.setUpSuite
? async.makeAsync(0, testcase.setUpSuite, testcase)
: empty,
tearDownSuite: i == testNames.length && testcase.tearDownSuite
? async.makeAsync(0, testcase.tearDownSuite, testcase)
: empty,
skip: skip,
index: i++
}
})
return async.list(tests, exports.TestGenerator)
}
exports.walkTestCases = function(paths, matchRe) {
require("./plugins/fs-node")
if (typeof paths == "string")
paths = [paths]
var walkers = paths.map(function(path) {
return async.walkfiles(path)
})
return async.concat.apply(async, walkers)
.stat()
.filter(function(file) {
return file.stat.isFile() && file.name.match(matchRe || /(_test|Test)\.js$/)
})
.get("path")
.expand(function(path) {
return exports.testcase(require(path))
}, exports.TestGenerator)
}
| mit |
pail23/openhab2-addons | addons/binding/org.openhab.binding.denonmarantz/src/main/java/org/openhab/binding/denonmarantz/internal/connector/DenonMarantzConnectorFactory.java | 1444 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.denonmarantz.internal.connector;
import java.util.concurrent.ScheduledExecutorService;
import org.eclipse.jetty.client.HttpClient;
import org.openhab.binding.denonmarantz.internal.DenonMarantzState;
import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration;
import org.openhab.binding.denonmarantz.internal.connector.http.DenonMarantzHttpConnector;
import org.openhab.binding.denonmarantz.internal.connector.telnet.DenonMarantzTelnetConnector;
/**
* Returns the connector based on the configuration.
* Currently there are 2 types: HTTP and Telnet
*
* @author Jan-Willem Veldhuis - Initial contribution
*/
public class DenonMarantzConnectorFactory {
public DenonMarantzConnector getConnector(DenonMarantzConfiguration config, DenonMarantzState state,
ScheduledExecutorService scheduler, HttpClient httpClient) {
if (config.isTelnet()) {
return new DenonMarantzTelnetConnector(config, state, scheduler);
} else {
return new DenonMarantzHttpConnector(config, state, scheduler, httpClient);
}
}
}
| epl-1.0 |
sja/smarthome | bundles/core/org.eclipse.smarthome.core.thing/src/main/java/org/eclipse/smarthome/core/thing/binding/BaseThingHandlerFactory.java | 12103 | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.core.thing.binding;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.smarthome.config.core.ConfigDescriptionRegistry;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.config.core.status.ConfigStatusProvider;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.ThingUID;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeRegistry;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
/**
* {@link BaseThingHandlerFactory} provides a base implementation for the {@link ThingHandlerFactory} interface. It
* provides the OSGi service registration logic.
*
* @author Dennis Nobel - Initial contribution
* @author Benedikt Niehues - fix for Bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=445137 considering
* default values
* @author Thomas Höfer - added config status provider service registration
*/
public abstract class BaseThingHandlerFactory implements ThingHandlerFactory {
protected BundleContext bundleContext;
private Map<String, ServiceRegistration<ThingHandler>> thingHandlers = new HashMap<>();
private Map<String, ServiceRegistration<ConfigStatusProvider>> configStatusProviders = new HashMap<>();
private ServiceTracker<ThingTypeRegistry, ThingTypeRegistry> thingTypeRegistryServiceTracker;
private ServiceTracker<ConfigDescriptionRegistry, ConfigDescriptionRegistry> configDescriptionRegistryServiceTracker;
/**
* Initializes the {@link BaseThingHandlerFactory}. If this method is
* overridden by a sub class, the implementing method must call <code>super.activate(componentContext)</code> first.
*
* @param componentContext
* component context (must not be null)
*/
protected void activate(ComponentContext componentContext) {
this.bundleContext = componentContext.getBundleContext();
thingTypeRegistryServiceTracker = new ServiceTracker<>(bundleContext, ThingTypeRegistry.class.getName(), null);
thingTypeRegistryServiceTracker.open();
configDescriptionRegistryServiceTracker = new ServiceTracker<>(bundleContext,
ConfigDescriptionRegistry.class.getName(), null);
configDescriptionRegistryServiceTracker.open();
}
/**
* Disposes the {@link BaseThingHandlerFactory}. If this method is
* overridden by a sub class, the implementing method must call <code>super.deactivate(componentContext)</code>
* first.
*
* @param componentContext
* component context (must not be null)
*/
protected void deactivate(ComponentContext componentContext) {
for (ServiceRegistration<ThingHandler> serviceRegistration : this.thingHandlers.values()) {
unregisterHandler(serviceRegistration);
}
for (ServiceRegistration<ConfigStatusProvider> serviceRegistration : configStatusProviders.values()) {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
}
thingTypeRegistryServiceTracker.close();
configDescriptionRegistryServiceTracker.close();
this.thingHandlers.clear();
this.configStatusProviders.clear();
this.bundleContext = null;
}
@Override
public void unregisterHandler(Thing thing) {
ServiceRegistration<ThingHandler> thingHandlerServiceRegistration = thingHandlers
.remove(thing.getUID().toString());
if (thingHandlerServiceRegistration != null) {
unregisterHandler(thingHandlerServiceRegistration);
}
ServiceRegistration<ConfigStatusProvider> configStatusProviderServiceRegistration = configStatusProviders
.remove(thing.getUID().getAsString());
if (configStatusProviderServiceRegistration != null) {
configStatusProviderServiceRegistration.unregister();
}
}
private void unregisterHandler(ServiceRegistration<ThingHandler> serviceRegistration) {
ThingHandler thingHandler = bundleContext.getService(serviceRegistration.getReference());
removeHandler(thingHandler);
serviceRegistration.unregister();
if (thingHandler instanceof BaseThingHandler) {
((BaseThingHandler) thingHandler).unsetBundleContext(bundleContext);
}
}
@Override
public void registerHandler(Thing thing, ThingHandlerCallback thingHandlerListener) {
ThingHandler thingHandler = createHandler(thing);
if (thingHandler == null) {
throw new IllegalStateException(this.getClass().getSimpleName()
+ " could not create a handler for the thing '" + thing.getUID() + "'.");
}
if (thingHandler instanceof BaseThingHandler) {
if (bundleContext == null) {
throw new IllegalStateException(
"Base thing handler factory has not been properly initialized. Did you forget to call super.activate()?");
}
((BaseThingHandler) thingHandler).setBundleContext(bundleContext);
}
ServiceRegistration<ThingHandler> thingHandlderServiceRegistration = registerThingHandlerAsService(thing,
thingHandler);
thingHandlers.put(thing.getUID().toString(), thingHandlderServiceRegistration);
if (thingHandler instanceof ConfigStatusProvider) {
ServiceRegistration<ConfigStatusProvider> configStatusProviderServiceRegistration = registerConfigValidatorAsService(
thingHandler);
configStatusProviders.put(thing.getUID().getAsString(), configStatusProviderServiceRegistration);
}
}
private ServiceRegistration<ThingHandler> registerThingHandlerAsService(Thing thing, ThingHandler thingHandler) {
Dictionary<String, Object> serviceProperties = getServiceProperties(thing, thingHandler);
@SuppressWarnings("unchecked")
ServiceRegistration<ThingHandler> serviceRegistration = (ServiceRegistration<ThingHandler>) bundleContext
.registerService(ThingHandler.class.getName(), thingHandler, serviceProperties);
return serviceRegistration;
}
private ServiceRegistration<ConfigStatusProvider> registerConfigValidatorAsService(ThingHandler thingHandler) {
@SuppressWarnings("unchecked")
ServiceRegistration<ConfigStatusProvider> serviceRegistration = (ServiceRegistration<ConfigStatusProvider>) bundleContext
.registerService(ConfigStatusProvider.class.getName(), thingHandler, null);
return serviceRegistration;
}
private Dictionary<String, Object> getServiceProperties(Thing thing, ThingHandler thingHandler) {
Dictionary<String, Object> serviceProperties = new Hashtable<>();
serviceProperties.put(ThingHandler.SERVICE_PROPERTY_THING_ID, thing.getUID());
serviceProperties.put(ThingHandler.SERVICE_PROPERTY_THING_TYPE, thing.getThingTypeUID().toString());
Map<String, Object> additionalServiceProperties = getServiceProperties(thingHandler);
if (additionalServiceProperties != null) {
for (Entry<String, Object> additionalServiceProperty : additionalServiceProperties.entrySet()) {
serviceProperties.put(additionalServiceProperty.getKey(), additionalServiceProperty.getValue());
}
}
return serviceProperties;
}
/**
* This method can be overridden to append additional service properties to
* the registered OSGi {@link ThingHandler} service.
*
* @param thingHandler
* thing handler, which will be registered as OSGi service
* @return map of additional service properties
*/
protected Map<String, Object> getServiceProperties(ThingHandler thingHandler) {
return null;
}
/**
* The method implementation must create and return the {@link ThingHandler} for the given thing.
*
* @param thing
* thing
* @return thing handler
*/
protected abstract ThingHandler createHandler(Thing thing);
/**
* This method is called when a thing handler should be removed. The
* implementing caller can override this method to release specific
* resources.
*
* @param thingHandler
* thing handler to be removed
*/
protected void removeHandler(ThingHandler thingHandler) {
// can be overridden
}
@Override
public void removeThing(ThingUID thingUID) {
// can be overridden
}
/**
* Returns the {@link ThingType} which is represented by the given {@link ThingTypeUID}.
*
* @param thingTypeUID the unique id of the thing type
* @return the thing type represented by the given unique id
*/
protected ThingType getThingTypeByUID(ThingTypeUID thingTypeUID) {
if (thingTypeRegistryServiceTracker == null) {
throw new IllegalStateException(
"Base thing handler factory has not been properly initialized. Did you forget to call super.activate()?");
}
ThingTypeRegistry thingTypeRegistry = thingTypeRegistryServiceTracker.getService();
if (thingTypeRegistry != null) {
return thingTypeRegistry.getThingType(thingTypeUID);
}
return null;
}
/**
* Creates a thing based on given thing type uid.
*
* @param thingTypeUID
* thing type uid (can not be null)
* @param thingUID
* thingUID (can not be null)
* @param configuration
* (can not be null)
* @return thing (can be null, if thing type is unknown)
*/
protected Thing createThing(ThingTypeUID thingTypeUID, Configuration configuration, ThingUID thingUID) {
return createThing(thingTypeUID, configuration, thingUID, null);
}
/**
* Creates a thing based on given thing type uid.
*
* @param thingTypeUID
* thing type uid (must not be null)
* @param thingUID
* thingUID (can be null)
* @param configuration
* (must not be null)
* @param bridgeUID
* (can be null)
* @return thing (can be null, if thing type is unknown)
*/
@Override
public Thing createThing(ThingTypeUID thingTypeUID, Configuration configuration, ThingUID thingUID,
ThingUID bridgeUID) {
if (thingTypeUID == null) {
throw new IllegalArgumentException("Thing Type UID must not be null");
}
if (thingUID == null) {
thingUID = ThingFactory.generateRandomThingUID(thingTypeUID);
}
ThingType thingType = getThingTypeByUID(thingTypeUID);
if (thingType != null) {
Thing thing = ThingFactory.createThing(thingType, thingUID, configuration, bridgeUID,
getConfigDescriptionRegistry());
return thing;
} else {
return null;
}
}
protected ConfigDescriptionRegistry getConfigDescriptionRegistry() {
if (configDescriptionRegistryServiceTracker == null) {
throw new IllegalStateException(
"Config Description Registry has not been properly initialized. Did you forget to call super.activate()?");
}
return configDescriptionRegistryServiceTracker.getService();
}
} | epl-1.0 |
jjalnos/vogella | de.vogella.rcp.intro.commands.popup/src/de/vogella/rcp/intro/commands/popup/View.java | 1822 | package de.vogella.rcp.intro.commands.popup;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
public class View extends ViewPart {
private TableViewer viewer;
class ViewLabelProvider extends LabelProvider {
@Override
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
@Override
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getData());
// Create a menu manager and create context menu
MenuManager menuManager = new MenuManager();
Menu menu = menuManager.createContextMenu(viewer.getTable());
// set the menu on the SWT widget
viewer.getTable().setMenu(menu);
// register the menu with the framework
getSite().registerContextMenu(menuManager, viewer);
// make the viewer selection available
getSite().setSelectionProvider(viewer);
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
viewer.getControl().setFocus();
}
private List<String> getData() {
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
list.add("Three");
return list;
}
} | epl-1.0 |
crazywhatever/vogella | de.vogella.task.application/src/de/vogella/task/application/views/provider/TaskLabelProvider.java | 2154 | package de.vogella.task.application.views.provider;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import de.vogella.task.application.Application;
import de.vogella.task.model.ITask;
import de.vogella.task.model.Status;
public class TaskLabelProvider extends LabelProvider implements
ITableLabelProvider {
// We use icons
private static final Image ERROR = AbstractUIPlugin
.imageDescriptorFromPlugin(Application.PLUGIN_ID, "icons/error.gif")
.createImage();
private static final Image WARNING = AbstractUIPlugin
.imageDescriptorFromPlugin(Application.PLUGIN_ID,
"icons/errorwarning.gif").createImage();
private static final Image PROCESS = AbstractUIPlugin
.imageDescriptorFromPlugin(Application.PLUGIN_ID,
"icons/progress_spinner.gif").createImage();
@Override
public Image getColumnImage(Object element, int columnIndex) {
ITask task = (ITask) element;
if (columnIndex == 0) {
return getIcons(task);
}
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
ITask task = (ITask) element;
switch (columnIndex) {
case 0:
return "";// String.valueOf(task.getId());
case 1:
SimpleDateFormat date_format = new SimpleDateFormat("MM/dd/yyyy");
return date_format.format(task.getDueDate().getTime());
case 2:
return task.getSummary();
case 3:
return task.getPriority().toString();
case 4:
return String.valueOf(task.getStatus());
}
throw new RuntimeException("LabelProvider: Should not happen");
}
private Image getIcons(ITask task) {
if (!task.getStatus().equals(Status.DONE)) {
Calendar today = GregorianCalendar.getInstance();
if (task.getDueDate().after(today)) {
return ERROR;
}
if (task.getStatus().equals(Status.STARTED)) {
return PROCESS;
}
today.add(Calendar.DATE, 10);
if (task.getDueDate().before(today)) {
return WARNING;
}
}
return null;
}
}
| epl-1.0 |
boiled-sugar/mkvtoolnix | tests/test-410extract_vp9.rb | 157 | #!/usr/bin/ruby -w
# T_410extract_vp9
describe "mkvextract / extract VP9"
test "extraction" do
extract "data/webm/out-vp9.webm", 0 => tmp
hash_tmp
end
| gpl-2.0 |
krichter722/gcc | libstdc++-v3/testsuite/util/native_type/native_multimap.hpp | 3952 | // -*- C++ -*-
// Copyright (C) 2005-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file native_multimap.hpp
* Contains an adapter to std::multimap
*/
#ifndef PB_DS_NATIVE_MULTIMAP_HPP
#define PB_DS_NATIVE_MULTIMAP_HPP
#include <map>
#include <string>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <native_type/native_tree_tag.hpp>
namespace __gnu_pbds
{
namespace test
{
#define PB_DS_BASE_C_DEC \
std::multimap<Key, Data, Less_Fn, \
typename _Alloc::template rebind<std::pair<const Key, Data> >::other>
template<typename Key, typename Data, class Less_Fn = std::less<Key>,
typename _Alloc = std::allocator<char> >
class native_multimap : public PB_DS_BASE_C_DEC
{
private:
typedef PB_DS_BASE_C_DEC base_type;
public:
typedef native_tree_tag container_category;
typedef _Alloc allocator;
typedef
typename _Alloc::template rebind<
std::pair<Key, Data> >::other::const_reference
const_reference;
typedef typename base_type::iterator iterator;
typedef typename base_type::const_iterator const_iterator;
native_multimap() { }
template<typename It>
native_multimap(It f, It l) : base_type(f, l)
{ }
inline void
insert(const_reference r_val)
{
typedef std::pair<iterator, iterator> eq_range_t;
eq_range_t f = base_type::equal_range(r_val.first);
iterator it = f.first;
while (it != f.second)
{
if (it->second == r_val.second)
return;
++it;
}
base_type::insert(r_val);
}
inline iterator
find(const_reference r_val)
{
typedef std::pair<iterator, iterator> eq_range_t;
eq_range_t f = base_type::equal_range(r_val.first);
iterator it = f.first;
while (it != f.second)
{
if (it->second == r_val.second)
return it;
++it;
}
return base_type::end();
}
inline const_iterator
find(const_reference r_val) const
{
typedef std::pair<const_iterator, const_iterator> eq_range_t;
eq_range_t f = base_type::equal_range(r_val.first);
const_iterator it = f.first;
while (it != f.second)
{
if (it->second == r_val.second)
return it;
++it;
}
return base_type::end();
}
static std::string
name()
{ return std::string("n_mmap"); }
static std::string
desc()
{ return make_xml_tag("type", "value", "std_multimap"); }
};
#undef PB_DS_BASE_C_DEC
} // namespace test
} // namespace __gnu_pbds
#endif // #ifndef PB_DS_NATIVE_MULTIMAP_HPP
| gpl-2.0 |
PrincetonUniversity/NVJVM | build/linux-amd64/jaxws/drop/jaxws_src/src/com/sun/xml/internal/bind/v2/runtime/reflect/PrimitiveArrayListerDouble.java | 3441 | /*
* Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.bind.v2.runtime.reflect;
import com.sun.xml.internal.bind.api.AccessorException;
import com.sun.xml.internal.bind.v2.runtime.XMLSerializer;
/**
* {@link Lister} for primitive type arrays.
*
* <p>
* B y t e ArrayLister is used as the master to generate the rest of the
* lister classes. Do not modify the generated copies.
*/
final class PrimitiveArrayListerDouble<BeanT> extends Lister<BeanT,double[],Double,PrimitiveArrayListerDouble.DoubleArrayPack> {
private PrimitiveArrayListerDouble() {
}
/*package*/ static void register() {
Lister.primitiveArrayListers.put(Double.TYPE,new PrimitiveArrayListerDouble());
}
public ListIterator<Double> iterator(final double[] objects, XMLSerializer context) {
return new ListIterator<Double>() {
int idx=0;
public boolean hasNext() {
return idx<objects.length;
}
public Double next() {
return objects[idx++];
}
};
}
public DoubleArrayPack startPacking(BeanT current, Accessor<BeanT, double[]> acc) {
return new DoubleArrayPack();
}
public void addToPack(DoubleArrayPack objects, Double o) {
objects.add(o);
}
public void endPacking( DoubleArrayPack pack, BeanT bean, Accessor<BeanT,double[]> acc ) throws AccessorException {
acc.set(bean,pack.build());
}
public void reset(BeanT o,Accessor<BeanT,double[]> acc) throws AccessorException {
acc.set(o,new double[0]);
}
static final class DoubleArrayPack {
double[] buf = new double[16];
int size;
void add(Double b) {
if(buf.length==size) {
// realloc
double[] nb = new double[buf.length*2];
System.arraycopy(buf,0,nb,0,buf.length);
buf = nb;
}
if(b!=null)
buf[size++] = b;
}
double[] build() {
if(buf.length==size)
// if we are lucky enough
return buf;
double[] r = new double[size];
System.arraycopy(buf,0,r,0,size);
return r;
}
}
}
| gpl-2.0 |
Gurgel100/gcc | gcc/testsuite/g++.dg/cpp1z/constexpr-if12.C | 252 | // PR c++/80562
// { dg-do compile { target c++17 } }
struct T {
int i;
constexpr auto foo() { return false; }
};
template <class MustBeTemplate>
constexpr auto bf(T t) {
if constexpr(t.foo()) {
return false;
}
return true;
}
| gpl-2.0 |
rgacogne/pdns | pdns/dnsdistdist/dnsdist-prometheus.hh | 2280 | /*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* 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.
*/
#pragma once
// Metric types for Prometheus
enum class PrometheusMetricType: int {
counter = 1,
gauge = 2
};
// Keeps additional information about metrics
struct MetricDefinition {
MetricDefinition(PrometheusMetricType _prometheusType, const std::string& _description): description(_description), prometheusType(_prometheusType) {
}
MetricDefinition() = default;
// Metric description
std::string description;
// Metric type for Prometheus
PrometheusMetricType prometheusType;
};
struct MetricDefinitionStorage {
// Return metric definition by name
bool getMetricDetails(const std::string& metricName, MetricDefinition& metric) const {
const auto& metricDetailsIter = metrics.find(metricName);
if (metricDetailsIter == metrics.end()) {
return false;
}
metric = metricDetailsIter->second;
return true;
};
// Return string representation of Prometheus metric type
std::string getPrometheusStringMetricType(PrometheusMetricType metricType) const {
switch (metricType) {
case PrometheusMetricType::counter:
return "counter";
break;
case PrometheusMetricType::gauge:
return "gauge";
break;
default:
return "";
break;
}
};
static const std::map<std::string, MetricDefinition> metrics;
};
| gpl-2.0 |
tsuibin/qtextended | src/tools/qdawggen/global.cpp | 1374 | /****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
// simplified version of Global::tempDir(). This avoids having to include more
// source files
#include "global.h"
/*!
\internal
Returns the default system path for storing temporary files.
Note: This does not ensure that the provided directory exists.
*/
namespace Qtopia
{
QString tempDir()
{
QString result;
#ifdef Q_OS_UNIX
result="/tmp/";
#else
if (getenv("TEMP"))
result = getenv("TEMP");
else
result = getenv("TMP");
if (result[(int)result.length() - 1] != QDir::separator())
result.append(QDir::separator());
#endif
return result;
}
}
| gpl-2.0 |
zidad/jaydata | Types/StorageProviders/mongoDB/mongoDBProjectionCompiler.js | 5635 | $C('$data.storageProviders.mongoDB.mongoDBProjectionCompiler', $data.Expressions.EntityExpressionVisitor, null, {
constructor: function (provider, lambdaPrefix, compiler) {
this.provider = provider;
this.lambdaPrefix = lambdaPrefix;
if (compiler){
this.compiler = compiler;
this.includes = compiler.includes;
this.mainEntitySet = compiler.mainEntitySet;
}
},
compile: function (expression, context) {
this.Visit(expression, context);
delete context.current;
delete context.complexType;
},
VisitProjectionExpression: function (expression, context) {
this.Visit(expression.selector, context);
},
VisitParametricQueryExpression: function (expression, context) {
this.Visit(expression.expression, context);
},
VisitObjectLiteralExpression: function (expression, context) {
var tempObjectLiteralPath = this.ObjectLiteralPath;
this.hasObjectLiteral = true;
expression.members.forEach(function (member, index) {
this.Visit(member, context);
}, this);
},
VisitObjectFieldExpression: function (expression, context) {
this.Visit(expression.expression, context);
},
VisitComplexTypeExpression: function (expression, context) {
this.Visit(expression.source, context);
this.Visit(expression.selector, context);
},
VisitEntityFieldExpression: function (expression, context) {
this.Visit(expression.source, context);
this.Visit(expression.selector, context);
},
VisitEntityExpression: function (expression, context) {
if (context.includeOptions && !context.includeOptions.fields){
context.include.full = true;
}
delete context.include;
delete context.includeOptions;
this.Visit(expression.source, context);
},
VisitEntitySetExpression: function (expression, context) {
if (expression.source instanceof $data.Expressions.EntityExpression) {
this.Visit(expression.source, context);
}
if (expression.selector instanceof $data.Expressions.AssociationInfoExpression) {
this.Visit(expression.selector, context);
}
},
VisitAssociationInfoExpression: function (expression, context) {
this.includes = this.includes || [];
var from = context.include ? context.include.name + '.' + expression.associationInfo.FromPropertyName : expression.associationInfo.FromPropertyName;
var includeFragment = from.split('.');
var tempData = null;
var storageModel = this.mainEntitySet.entityContext._storageModel.getStorageModel(this.mainEntitySet.createNew);
for (var i = 0; i < includeFragment.length; i++) {
if (tempData) { tempData += '.' + includeFragment[i]; } else { tempData = includeFragment[i]; }
var association = storageModel.Associations[includeFragment[i]];
if (association) {
var inc = this.includes.filter(function (include) { return include.name == tempData }, this);
if (context.include && i < includeFragment.length - 1){
if (!context.include.options.fields) context.include.options.fields = { _id: 1 };
context.include.options.fields[includeFragment[i + 1]] = 1;
}
if (inc.length) {
context.includeOptions = inc[0].options;
context.include = inc[0];
inc[0].mapped = true;
}else{
var inc = { name: tempData, type: association.ToType, from: association.FromType, query: {}, options: {}, mapped: true };
context.includeOptions = inc.options;
context.include = inc;
context.include.options.fields = { _id: 1 };
context.include.options.fields[association.ToPropertyName] = 1;
this.includes.push(inc);
}
if (!context.options.fields) context.options.fields = { _id: 1 };
context.options.fields[includeFragment[0]] = 1;
association.ReferentialConstraint.forEach(function(ref){
for (var p in ref){
context.options.fields[ref[p]] = 1;
}
});
}
else {
Guard.raise(new Exception("The given include path is invalid: " + expression.associationInfo.FromPropertyName + ", invalid point: " + tempData));
}
storageModel = this.mainEntitySet.entityContext._storageModel.getStorageModel(association.ToType);
}
},
VisitMemberInfoExpression: function (expression, context) {
if (!(context.includeOptions || context.options).fields) (context.includeOptions || context.options).fields = { _id: 1 };
context.current = expression.memberName;
if (context.complexType){
delete (context.includeOptions || context.options).fields[context.complexType];
(context.includeOptions || context.options).fields[context.complexType + '.' + context.current] = 1;
delete context.complexType;
}else{
if (!(context.includeOptions || context.options).fields[expression.memberName]) (context.includeOptions || context.options).fields[expression.memberName] = 1;
}
delete context.includeOptions;
delete context.include;
},
VisitConstantExpression: function (expression, context) {
}
});
| gpl-2.0 |
nmcgill/UOReturns | Scripts/Items/Suits/SeerRobe.cs | 514 | using System;
using Server;
namespace Server.Items
{
public class SeerRobe : BaseSuit
{
[Constructable]
public SeerRobe() : base( AccessLevel.Seer, 0x1D3, 0x204F )
{
}
public SeerRobe( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | gpl-2.0 |
jjzhang/ocfs2-tools | ocfs2console/ocfs2interface/pushconfig.py | 3521 | # OCFS2Console - GUI frontend for OCFS2 management and debugging
# Copyright (C) 2005 Oracle. All rights reserved.
#
# 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 021110-1307, USA.
import socket
import gtk
import o2cb_ctl
from guiutil import error_box
from terminal import TerminalDialog, terminal_ok as pushconfig_ok
CONFIG_FILE = '/etc/ocfs2/cluster.conf'
command_template = '''set -e
mkdir -p /etc/ocfs2
cat > /etc/ocfs2/cluster.conf <<\_______EOF
%(cluster_config)s
_______EOF
#/etc/init.d/o2cb online %(cluster_name)s
'''
def get_hosts(parent=None):
hostname = socket.gethostname()
cluster_name = o2cb_ctl.get_active_cluster_name(parent)
nodes = o2cb_ctl.get_cluster_nodes(cluster_name, parent)
remote_nodes = [node['name'] for node in nodes if node['name'] != hostname]
return cluster_name, remote_nodes
def generate_command(cluster_name):
conf_file = open(CONFIG_FILE)
config_data = conf_file.read()
conf_file.close()
if config_data.endswith('\n'):
config_data = config_data[:-1]
info = {'cluster_config' : config_data,
'cluster_name' : cluster_name}
return command_template % info
def propagate(terminal, dialog, remote_command, host_iter):
try:
host = host_iter.next()
except StopIteration:
terminal.feed('Finished!\r\n', -1)
dialog.finished = True
return
command = ('ssh', 'root@%s' % host, remote_command)
terminal.feed('Propagating cluster configuration to %s...\r\n' % host, -1)
terminal.fork_command(command=command[0], argv=command)
def push_config(parent=None):
try:
cluster_name, hosts = get_hosts(parent)
except o2cb_ctl.CtlError, e:
error_box(parent, str(e))
return
try:
command = generate_command(cluster_name)
except IOError, e:
error_box(parent, str(e))
return
title = 'Propagate Cluster Configuration'
dialog = TerminalDialog(parent=parent, title=title)
terminal = dialog.terminal
dialog.finished = False
dialog.show_all()
host_iter = iter(hosts)
terminal.connect('child-exited', propagate, dialog, command, host_iter)
propagate(terminal, dialog, command, host_iter)
while 1:
dialog.run()
if dialog.finished:
break
msg = ('Cluster configuration propagation is still running. You '
'should not close this window until it is finished')
info = gtk.MessageDialog(parent=dialog,
flags=gtk.DIALOG_DESTROY_WITH_PARENT,
type=gtk.MESSAGE_WARNING,
buttons=gtk.BUTTONS_CLOSE,
message_format=msg)
info.run()
info.destroy()
dialog.destroy()
def main():
push_config()
if __name__ == '__main__':
main()
| gpl-2.0 |
jn7163/aria2 | src/DHTBucketRefreshTask.cc | 2994 | /* <!-- copyright */
/*
* aria2 - The high speed download utility
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of portions of this program with the
* OpenSSL library under certain conditions as described in each
* individual source file, and distribute linked combinations
* including the two.
* You must obey the GNU General Public License in all respects
* for all of the code used other than OpenSSL. If you modify
* file(s) with this exception, you may extend this exception to your
* version of the file(s), but you are not obligated to do so. If you
* do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source
* files in the program, then also delete it here.
*/
/* copyright --> */
#include "DHTBucketRefreshTask.h"
#include "DHTBucket.h"
#include "DHTRoutingTable.h"
#include "DHTNodeLookupTask.h"
#include "DHTTaskQueue.h"
#include "DHTNode.h"
#include "DHTNodeLookupEntry.h"
#include "util.h"
#include "Logger.h"
#include "LogFactory.h"
#include "DHTMessageCallback.h"
#include "fmt.h"
namespace aria2 {
DHTBucketRefreshTask::DHTBucketRefreshTask():
forceRefresh_(false) {}
DHTBucketRefreshTask::~DHTBucketRefreshTask() {}
void DHTBucketRefreshTask::startup()
{
std::vector<std::shared_ptr<DHTBucket> > buckets;
getRoutingTable()->getBuckets(buckets);
for (auto& b : buckets) {
if(!forceRefresh_ && ! b->needsRefresh()) {
continue;
}
b->notifyUpdate();
unsigned char targetID[DHT_ID_LENGTH];
b->getRandomNodeID(targetID);
auto task = std::make_shared<DHTNodeLookupTask>(targetID);
task->setRoutingTable(getRoutingTable());
task->setMessageDispatcher(getMessageDispatcher());
task->setMessageFactory(getMessageFactory());
task->setTaskQueue(getTaskQueue());
task->setLocalNode(getLocalNode());
A2_LOG_INFO(fmt("Dispating bucket refresh. targetID=%s",
util::toHex(targetID, DHT_ID_LENGTH).c_str()));
getTaskQueue()->addPeriodicTask1(task);
}
setFinished(true);
}
void DHTBucketRefreshTask::setForceRefresh(bool forceRefresh)
{
forceRefresh_ = forceRefresh;
}
} // namespace aria2
| gpl-2.0 |
yodaaut/icingaweb2 | modules/monitoring/application/forms/Command/Object/ProcessCheckResultCommandForm.php | 4613 | <?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\Forms\Command\Object;
use Icinga\Web\Notification;
use Icinga\Module\Monitoring\Command\Object\ProcessCheckResultCommand;
/**
* Form for submitting a passive host or service check result
*/
class ProcessCheckResultCommandForm extends ObjectsCommandForm
{
/**
* Initialize this form
*/
public function init()
{
$this->addDescription($this->translate(
'This command is used to submit passive host or service check results.'
));
}
/**
* (non-PHPDoc)
* @see \Icinga\Web\Form::getSubmitLabel() For the method documentation.
*/
public function getSubmitLabel()
{
return $this->translatePlural(
'Submit Passive Check Result', 'Submit Passive Check Results', count($this->objects)
);
}
/**
* (non-PHPDoc)
* @see \Icinga\Web\Form::createElements() For the method documentation.
*/
public function createElements(array $formData)
{
foreach ($this->getObjects() as $object) {
/** @var \Icinga\Module\Monitoring\Object\MonitoredObject $object */
// Nasty, but as getObjects() returns everything but an object with a real
// iterator interface this is the only way to fetch just the first element
break;
}
$this->addElement(
'select',
'status',
array(
'required' => true,
'label' => $this->translate('Status'),
'description' => $this->translate('The state this check result should report'),
'multiOptions' => $object->getType() === $object::TYPE_HOST ? $this->getHostMultiOptions() : array(
ProcessCheckResultCommand::SERVICE_OK => $this->translate('OK', 'icinga.state'),
ProcessCheckResultCommand::SERVICE_WARNING => $this->translate('WARNING', 'icinga.state'),
ProcessCheckResultCommand::SERVICE_CRITICAL => $this->translate('CRITICAL', 'icinga.state'),
ProcessCheckResultCommand::SERVICE_UNKNOWN => $this->translate('UNKNOWN', 'icinga.state')
)
)
);
$this->addElement(
'text',
'output',
array(
'required' => true,
'label' => $this->translate('Output'),
'description' => $this->translate('The plugin output of this check result')
)
);
$this->addElement(
'text',
'perfdata',
array(
'allowEmpty' => true,
'label' => $this->translate('Performance Data'),
'description' => $this->translate(
'The performance data of this check result. Leave empty'
. ' if this check result has no performance data'
)
)
);
}
/**
* (non-PHPDoc)
* @see \Icinga\Web\Form::onSuccess() For the method documentation.
*/
public function onSuccess()
{
foreach ($this->objects as $object) {
/** @var \Icinga\Module\Monitoring\Object\MonitoredObject $object */
$command = new ProcessCheckResultCommand();
$command->setObject($object);
$command->setStatus($this->getValue('status'));
$command->setOutput($this->getValue('output'));
if ($perfdata = $this->getValue('perfdata')) {
$command->setPerformanceData($perfdata);
}
$this->getTransport($this->request)->send($command);
}
Notification::success($this->translatePlural(
'Processing check result..',
'Processing check results..',
count($this->objects)
));
return true;
}
/**
* Returns the available host options based on the program version
*
* @return array
*/
protected function getHostMultiOptions()
{
$options = array(
ProcessCheckResultCommand::HOST_UP => $this->translate('UP', 'icinga.state'),
ProcessCheckResultCommand::HOST_DOWN => $this->translate('DOWN', 'icinga.state')
);
if (substr($this->getBackend()->getProgramVersion(), 0, 2) !== 'v2') {
$options[ProcessCheckResultCommand::HOST_UNREACHABLE] = $this->translate('UNREACHABLE', 'icinga.state');
}
return $options;
}
}
| gpl-2.0 |
matrix-msu/kora | vendor/seld/jsonlint/tests/JsonParserTest.php | 7190 | <?php
/*
* This file is part of the JSON Lint package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use PHPUnit\Framework\TestCase;
use Seld\JsonLint\JsonParser;
use Seld\JsonLint\ParsingException;
use Seld\JsonLint\DuplicateKeyException;
class JsonParserTest extends TestCase
{
protected $json = array(
'42', '42.3', '0.3', '-42', '-42.3', '-0.3',
'2e1', '2E1', '-2e1', '-2E1', '2E+2', '2E-2', '-2E+2', '-2E-2',
'true', 'false', 'null', '""', '[]', '{}', '"string"',
'["a", "sdfsd"]',
'{"foo":"bar", "bar":"baz", "":"buz"}',
'{"":"foo", "_empty_":"bar"}',
'"\u00c9v\u00e9nement"',
'"http:\/\/foo.com"',
'"zo\\\\mg"',
'{"test":"\u00c9v\u00e9nement"}',
'["\u00c9v\u00e9nement"]',
'"foo/bar"',
'{"test":"http:\/\/foo\\\\zomg"}',
'["http:\/\/foo\\\\zomg"]',
'{"":"foo"}',
'{"a":"b", "b":"c"}',
'0',
'""',
);
/**
* @dataProvider provideValidStrings
*/
public function testParsesValidStrings($input)
{
$parser = new JsonParser();
$this->assertEquals(json_decode($input), $parser->parse($input));
}
public function provideValidStrings()
{
$strings = array();
foreach ($this->json as $input) {
$strings[] = array($input);
}
return $strings;
}
public function testErrorOnTrailingComma()
{
$parser = new JsonParser();
try {
$parser->parse('{
"foo":"bar",
}');
$this->fail('Invalid trailing comma should be detected');
} catch (ParsingException $e) {
$this->assertContains('It appears you have an extra trailing comma', $e->getMessage());
}
}
public function testErrorOnInvalidQuotes()
{
$parser = new JsonParser();
try {
$parser->parse('{
"foo": \'bar\',
}');
$this->fail('Invalid quotes for string should be detected');
} catch (ParsingException $e) {
$this->assertContains('Invalid string, it appears you used single quotes instead of double quotes', $e->getMessage());
}
}
public function testErrorOnUnescapedBackslash()
{
$parser = new JsonParser();
try {
$parser->parse('{
"foo": "bar\z",
}');
$this->fail('Invalid unescaped string should be detected');
} catch (ParsingException $e) {
$this->assertContains('Invalid string, it appears you have an unescaped backslash at: \z', $e->getMessage());
}
}
public function testErrorOnUnterminatedString()
{
$parser = new JsonParser();
try {
$parser->parse('{"bar": "foo}');
$this->fail('Invalid unterminated string should be detected');
} catch (ParsingException $e) {
$this->assertContains('Invalid string, it appears you forgot to terminate a string, or attempted to write a multiline string which is invalid', $e->getMessage());
}
}
public function testErrorOnMultilineString()
{
$parser = new JsonParser();
try {
$parser->parse('{"bar": "foo
bar"}');
$this->fail('Invalid multi-line string should be detected');
} catch (ParsingException $e) {
$this->assertContains('Invalid string, it appears you forgot to terminate a string, or attempted to write a multiline string which is invalid', $e->getMessage());
}
}
public function testErrorAtBeginning()
{
$parser = new JsonParser();
try {
$parser->parse('
');
$this->fail('Empty string should be invalid');
} catch (ParsingException $e) {
$this->assertContains("Parse error on line 1:\n\n^", $e->getMessage());
}
}
public function testParsesMultiInARow()
{
$parser = new JsonParser();
foreach ($this->json as $input) {
$this->assertEquals(json_decode($input), $parser->parse($input));
}
}
public function testDetectsKeyOverrides()
{
$parser = new JsonParser();
try {
$parser->parse('{"a":"b", "a":"c"}', JsonParser::DETECT_KEY_CONFLICTS);
$this->fail('Duplicate keys should not be allowed');
} catch (DuplicateKeyException $e) {
$this->assertContains('Duplicate key: a', $e->getMessage());
$this->assertSame('a', $e->getKey());
$this->assertSame(array('line' => 1, 'key' => 'a'), $e->getDetails());
}
}
public function testDetectsKeyOverridesWithEmpty()
{
$parser = new JsonParser();
if (PHP_VERSION_ID >= 70100) {
$this->markTestSkipped('Only for PHP < 7.1');
}
try {
$parser->parse('{"":"b", "_empty_":"a"}', JsonParser::DETECT_KEY_CONFLICTS);
$this->fail('Duplicate keys should not be allowed');
} catch (DuplicateKeyException $e) {
$this->assertContains('Duplicate key: _empty_', $e->getMessage());
$this->assertSame('_empty_', $e->getKey());
$this->assertSame(array('line' => 1, 'key' => '_empty_'), $e->getDetails());
}
}
public function testDuplicateKeys()
{
$parser = new JsonParser();
$result = $parser->parse('{"a":"b", "a":"c", "a":"d"}', JsonParser::ALLOW_DUPLICATE_KEYS);
$this->assertThat($result,
$this->logicalAnd(
$this->objectHasAttribute('a'),
$this->objectHasAttribute('a.1'),
$this->objectHasAttribute('a.2')
)
);
}
public function testDuplicateKeysWithEmpty()
{
$parser = new JsonParser();
if (PHP_VERSION_ID >= 70100) {
$this->markTestSkipped('Only for PHP < 7.1');
}
$result = $parser->parse('{"":"a", "_empty_":"b"}', JsonParser::ALLOW_DUPLICATE_KEYS);
$this->assertThat($result,
$this->logicalAnd(
$this->objectHasAttribute('_empty_'),
$this->objectHasAttribute('_empty_.1')
)
);
}
public function testParseToArray()
{
$parser = new JsonParser();
$json = '{"one":"a", "two":{"three": "four"}, "": "empty"}';
$result = $parser->parse($json, JsonParser::PARSE_TO_ASSOC);
$this->assertSame(json_decode($json, true), $result);
}
public function testFileWithBOM()
{
try {
$parser = new JsonParser();
$parser->parse(file_get_contents(dirname(__FILE__) .'/bom.json'));
$this->fail('BOM should be detected');
} catch (ParsingException $e) {
$this->assertContains('BOM detected', $e->getMessage());
}
}
public function testLongString()
{
$parser = new JsonParser();
$json = '{"k":"' . str_repeat("a\\n",10000) . '"}';
$this->assertEquals(json_decode($json), $parser->parse($json));
}
}
| gpl-2.0 |
monikajoinfilms/jfbackup | sites/all/modules/jquery_update/replace/ui/ui/minified/jquery.ui.draggable.min.js | 18755 | /*
* jQuery UI Draggable 1.8.11
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Draggables
*
* Depends:
* jquery.ui.core.js
* jquery.ui.mouse.js
* jquery.ui.widget.js
*/
(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper==
"original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:function(a){var b=
this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-
this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions();
d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||
this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&
this.options.revert.call(this.element,b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==
a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||
0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-
(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),
height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[(a.containment=="document"?0:d(window).scrollLeft())-this.offset.relative.left-this.offset.parent.left,(a.containment=="document"?0:d(window).scrollTop())-this.offset.relative.top-this.offset.parent.top,(a.containment=="document"?0:d(window).scrollLeft())+d(a.containment=="document"?
document:window).width()-this.helperProportions.width-this.margins.left,(a.containment=="document"?0:d(window).scrollTop())+(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),
10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0),a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0),a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),
10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&
d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=
this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e=this.originalPageX+Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?
e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():
f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs=this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,
offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.8.11"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data(this,"sortable");if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g.refreshPositions();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},
b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper;c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=
d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};
a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&
this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",
{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","iframeFix",{start:function(){var a=d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+
"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",
a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+
c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX-b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<
c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()-c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+
c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this,width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),
f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+e&&j-e<o&&o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=
c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k}).left-c.margins.left}var t=p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=
c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width}).left-c.margins.left}if(!c.snapElements[h].snapping&&(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),
{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"),10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=
parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery);
| gpl-2.0 |
liuyanghejerry/qtextended | examples/simpleplayer/basicmedia.cpp | 4522 | /****************************************************************************
**
** This file is part of the Qt Extended Opensource Package.
**
** Copyright (C) 2009 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** version 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include "basicmedia.h"
#include <QContent>
#include <QMediaControlNotifier>
#include <QMediaVideoControl>
#include <QVBoxLayout>
#include <QApplication>
#include <QMediaControl>
#include <QResizeEvent>
#include <QSize>
#include <QDebug>
/*
m_state 0 constructed
m_state 1 set filename
m_state 2 mediaControlValid
m_state 3 mediaVideoControlValid
m_state 4 stopped
*/
BasicMedia::BasicMedia(QWidget* parent)
: QWidget(parent), m_mediaContent(0), m_control(0), m_video(0), m_state(0), videoWidget(0)
{
layout = new QVBoxLayout;
layout->setMargin(0);
setLayout(layout);
// First create a container for all player objects
context = new QMediaContentContext(this);
// watches a media content object for availability of a given media control
QMediaControlNotifier* notifier = new QMediaControlNotifier(QMediaControl::name(), this);
connect(notifier, SIGNAL(valid()), this, SLOT(mediaControlValid()));
context->addObject(notifier);
// watches a media content object for availability of a given media control
QMediaControlNotifier* video = new QMediaControlNotifier(QMediaVideoControl::name(), this);
connect(video, SIGNAL(valid()), this, SLOT(mediaVideoControlValid()));
context->addObject(video);
volume=100;
}
void BasicMedia::keyReleaseEvent( QKeyEvent *ke )
{
ke->ignore();
}
void BasicMedia::setFilename(QString f)
{
// Step 1: must set a file to play
m_state = 1;
vfile = f;
}
void BasicMedia::mediaVideoControlValid()
{
if(m_state == 2) {
m_state = 3;
delete m_video;
delete videoWidget;
// create video widget
m_video = new QMediaVideoControl(m_mediaContent);
videoWidget = m_video->createVideoWidget(this);
if (!videoWidget) {
qWarning("Failed to create video widget");
return;
}
videoWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// display the video widget on the screen
layout->addWidget(videoWidget);
} else {
qWarning("(%d) ERROR BasicMedia::mediaVideoControlValid, should appear after mediaControlValid???",m_state);
}
}
void BasicMedia::mediaControlValid()
{
if(m_state == 1) {
m_state = 2;
delete m_control;
m_control = new QMediaControl(m_mediaContent);
m_control->start();
} else {
qWarning("(%d) ERROR BasicMedia::mediaControlValid, must call setFilename() before start()!!!",m_state);
}
}
BasicMedia::~BasicMedia()
{
delete m_mediaContent;
delete m_control;
}
void BasicMedia::stop()
{
if(m_state == 3) {
//Normal stop request
m_control->stop();
m_state=1;
} else if(m_control) {
//Video start play failed???
m_control->stop();
m_state=1;
}
if(m_state > 1) {
if(m_video!=NULL) {
delete m_video;
delete videoWidget;
delete m_mediaContent;
m_video = NULL;
videoWidget = NULL;
m_mediaContent = NULL;
}
}
}
void BasicMedia::start()
{
if(m_state == 1) {
QContent content(vfile);
if (!content.isValid()) {
qWarning() << "Failed to load" << vfile;
return;
}
m_mediaContent = new QMediaContent(content);
context->setMediaContent(m_mediaContent);
} else {
qWarning("(%d) BasicMedia::start() must stop() and setFilename() before calling start!!!",m_state);
}
}
void BasicMedia::volumeup()
{
if(volume<90) {
volume=volume+10;
m_control->setVolume(volume);
}
}
void BasicMedia::volumedown()
{
if(volume>10) {
volume=volume-10;
m_control->setVolume(volume);
}
}
| gpl-2.0 |
Neopumper666/prueba | administrator/components/com_hikashop/views/plugins/tmpl/selectimages.php | 2626 | <?php
/**
* @package HikaShop for Joomla!
* @version 2.1.3
* @author hikashop.com
* @copyright (C) 2010-2013 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><script language="javascript" type="text/javascript">
<!--
var selectedContents = new Array();
var allElements = <?php echo count($this->rows);?>;
<?php
foreach($this->rows as $oneRow){
if(!empty($oneRow->selected)){
echo "selectedContents['".$oneRow->id."'] = 'content';";
}
}
?>
function applyContent(contentid,rowClass){
if(selectedContents[contentid]){
window.document.getElementById('content'+contentid).className = rowClass;
delete selectedContents[contentid];
}else{
window.document.getElementById('content'+contentid).className = 'selectedrow';
selectedContents[contentid] = 'content';
}
}
function insertTag(){
var tag = '';
for(var i in selectedContents){
if(selectedContents[i] == 'content'){
allElements--;
if(tag != '') tag += ',';
tag = tag + i;
}
}
if(allElements == 0) tag = 'All';
if(allElements == <?php echo count($this->rows);?>) tag = 'None';
window.top.document.getElementById('plugin_images').value = tag;
window.parent.hikashop.closeBox();
}
//-->
</script>
<style type="text/css">
table.adminlist tr.selectedrow td{
background-color:#FDE2BA;
}
</style>
<form action="index.php?option=<?php echo HIKASHOP_COMPONENT ?>" method="post" name="adminForm" id="adminForm">
<div style="float:right;margin-bottom : 10px">
<button class="btn" id='insertButton' onclick="insertTag(); return false;"><?php echo JText::_('HIKA_APPLY'); ?></button>
</div>
<div style="clear:both"/>
<table class="adminlist table table-striped table-hover" cellpadding="1">
<thead>
<tr>
<th class="title">
<?php echo JText::_('HIKA_IMAGE'); ?>
</th>
<th class="title">
<?php echo JText::_('HIKA_NAME'); ?>
</th>
</tr>
</thead>
<tbody>
<?php
$k = 0;
for($i = 0,$a = count($this->rows);$i<$a;$i++){
$row =& $this->rows[$i];
?>
<tr class="<?php echo empty($row->selected) ? "row$k" : 'selectedrow'; ?>" id="content<?php echo $row->id?>" onclick="applyContent('<?php echo $this->escape($row->id)."','row$k'"?>);" style="cursor:pointer;">
<td>
<img src="<?php echo $row->full;?>" />
</td>
<td>
<?php echo $row->name;?>
</td>
</tr>
<?php
$k = 1-$k;
}
?>
</tbody>
</table>
</div>
</form>
| gpl-2.0 |
md-5/jdk10 | test/jdk/jdk/jfr/event/gc/heapsummary/TestHeapSummaryEventG1.java | 1806 | /*
* Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.event.gc.heapsummary;
import jdk.test.lib.jfr.GCHelper;
/**
* @test
* @key jfr
* @requires vm.hasJFR
* @requires (vm.gc == "G1" | vm.gc == null)
* & vm.opt.ExplicitGCInvokesConcurrent != true
* @library /test/lib /test/jdk
* @run main/othervm -XX:+UnlockExperimentalVMOptions -XX:-UseFastUnorderedTimeStamps -XX:+UseG1GC jdk.jfr.event.gc.heapsummary.TestHeapSummaryEventG1
*/
public class TestHeapSummaryEventG1 {
public static void main(String[] args) throws Exception {
HeapSummaryEventAllGcs.test(GCHelper.gcG1New, GCHelper.gcG1Old);
}
}
| gpl-2.0 |
summerpulse/openjdk7 | jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/wsdl/writer/document/package-info.java | 1397 | /*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @author WS Development Team
*/
@com.sun.xml.internal.txw2.annotation.XmlNamespace("http://schemas.xmlsoap.org/wsdl/")
package com.sun.xml.internal.ws.wsdl.writer.document;
| gpl-2.0 |
KennyLv/LearnFromCocos2dwebgame | cocos2d/core/platform/CCMacro.js | 8416 | /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* @constant
* @type Number
*/
cc.INVALID_INDEX = -1;
/**
* PI is the ratio of a circle's circumference to its diameter.
* @constant
* @type Number
*/
cc.PI = Math.PI;
/**
* @constant
* @type Number
*/
cc.FLT_MAX = parseFloat('3.402823466e+38F');
/**
* @constant
* @type Number
*/
cc.RAD = cc.PI / 180;
/**
* @constant
* @type Number
*/
cc.DEG = 180 / cc.PI;
/**
* maximum unsigned int value
* @constant
* @type Number
*/
cc.UINT_MAX = 0xffffffff;
/**
* <p>
* simple macro that swaps 2 variables<br/>
* modified from c++ macro, you need to pass in the x and y variables names in string, <br/>
* and then a reference to the whole object as third variable
* </p>
* @param x
* @param y
* @param ref
* @function
* @deprecated
*/
cc.SWAP = function (x, y, ref) {
if ((typeof ref) == 'object' && (typeof ref.x) != 'undefined' && (typeof ref.y) != 'undefined') {
var tmp = ref[x];
ref[x] = ref[y];
ref[y] = tmp;
} else
cc.log("cc.SWAP is being modified from original macro, please check usage");
};
/**
* <p>
* Linear interpolation between 2 numbers, the ratio sets how much it is biased to each end
* </p>
* @param {Number} a number A
* @param {Number} b number B
* @param {Number} r ratio between 0 and 1
* @function
* @example
* cc.lerp(2,10,0.5)//returns 6<br/>
* cc.lerp(2,10,0.2)//returns 3.6
*/
cc.lerp = function (a, b, r) {
return a + (b - a) * r;
};
/**
* returns a random float between -1 and 1
* @return {Number}
* @function
*/
cc.RANDOM_MINUS1_1 = function () {
return (Math.random() - 0.5) * 2;
};
/**
* returns a random float between 0 and 1
* @return {Number}
* @function
*/
cc.RANDOM_0_1 = function () {
return Math.random();
};
/**
* converts degrees to radians
* @param {Number} angle
* @return {Number}
* @function
*/
cc.DEGREES_TO_RADIANS = function (angle) {
return angle * cc.RAD;
};
/**
* converts radians to degrees
* @param {Number} angle
* @return {Number}
* @function
*/
cc.RADIANS_TO_DEGREES = function (angle) {
return angle * cc.DEG;
};
/**
* @constant
* @type Number
*/
cc.REPEAT_FOREVER = Number.MAX_VALUE - 1;
/**
* default gl blend src function. Compatible with premultiplied alpha images.
* @constant
* @type Number
*/
cc.BLEND_SRC = cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA ? 1 : 0x0302;
/**
* default gl blend dst function. Compatible with premultiplied alpha images.
* @constant
* @type Number
*/
cc.BLEND_DST = 0x0303;
/**
* Helpful macro that setups the GL server state, the correct GL program and sets the Model View Projection matrix
* @param {cc.Node} node setup node
* @function
*/
cc.NODE_DRAW_SETUP = function (node) {
//cc.glEnable(node._glServerState);
if (node._shaderProgram) {
//cc.renderContext.useProgram(node._shaderProgram._programObj);
node._shaderProgram.use();
node._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
}
};
/**
* <p>
* GL states that are enabled:<br/>
* - GL_TEXTURE_2D<br/>
* - GL_VERTEX_ARRAY<br/>
* - GL_TEXTURE_COORD_ARRAY<br/>
* - GL_COLOR_ARRAY<br/>
* </p>
* @function
*/
cc.ENABLE_DEFAULT_GL_STATES = function () {
//TODO OPENGL STUFF
/*
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);*/
};
/**
* <p>
* Disable default GL states:<br/>
* - GL_TEXTURE_2D<br/>
* - GL_TEXTURE_COORD_ARRAY<br/>
* - GL_COLOR_ARRAY<br/>
* </p>
* @function
*/
cc.DISABLE_DEFAULT_GL_STATES = function () {
//TODO OPENGL
/*
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
*/
};
/**
* <p>
* Increments the GL Draws counts by one.<br/>
* The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled.<br/>
* </p>
* @param {Number} addNumber
* @function
*/
cc.INCREMENT_GL_DRAWS = function (addNumber) {
cc.g_NumberOfDraws += addNumber;
};
/**
* @constant
* @type Number
*/
cc.FLT_EPSILON = 0.0000001192092896;
/**
* <p>
* On Mac it returns 1;<br/>
* On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1
* </p>
* @function
*/
cc.CONTENT_SCALE_FACTOR = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () {
return cc.Director.getInstance().getContentScaleFactor();
} : function () {
return 1;
};
/**
* Converts a Point in points to pixels
* @param {cc.Point} points
* @return {cc.Point}
* @function
*/
cc.POINT_POINTS_TO_PIXELS = function (points) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.p(points.x * scale, points.y * scale);
};
/**
* Converts a Size in points to pixels
* @param {cc.Size} sizeInPoints
* @return {cc.Size}
* @function
*/
cc.SIZE_POINTS_TO_PIXELS = function (sizeInPoints) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.size(sizeInPoints.width * scale, sizeInPoints.height * scale);
};
/**
* Converts a size in pixels to points
* @param {cc.Size} sizeInPixels
* @return {cc.Size}
* @function
*/
cc.SIZE_PIXELS_TO_POINTS = function (sizeInPixels) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.size(sizeInPixels.width / scale, sizeInPixels.height / scale);
};
/**
* Converts a Point in pixels to points
* @param {Point} pixels
* @function
*/
cc.POINT_PIXELS_TO_POINTS = function (pixels) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.p(pixels.x / scale, pixels.y / scale);
};
/**
* Converts a rect in pixels to points
* @param {cc.Rect} pixel
* @function
*/
cc.RECT_PIXELS_TO_POINTS = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.rect(pixel.x / scale, pixel.y / scale,
pixel.width / scale, pixel.height / scale);
} : function (p) {
return p;
};
/**
* Converts a rect in points to pixels
* @param {cc.Rect} point
* @function
*/
cc.RECT_POINTS_TO_PIXELS = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) {
var scale = cc.CONTENT_SCALE_FACTOR();
return cc.rect(point.x * scale, point.y * scale,
point.width * scale, point.height * scale);
} : function (p) {
return p;
};
if (!cc.Browser.supportWebGL) {
/**
* WebGL constants
* @type {object}
*/
var gl = gl || {};
/**
* @constant
* @type Number
*/
gl.ONE = 1;
/**
* @constant
* @type Number
*/
gl.ZERO = 0;
/**
* @constant
* @type Number
*/
gl.SRC_ALPHA = 0x0302;
/**
* @constant
* @type Number
*/
gl.ONE_MINUS_SRC_ALPHA = 0x0303;
/**
* @constant
* @type Number
*/
gl.ONE_MINUS_DST_COLOR = 0x0307;
}
cc.CHECK_GL_ERROR_DEBUG = function () {
if (cc.renderMode == cc.WEBGL) {
var _error = cc.renderContext.getError();
if (_error) {
cc.log("WebGL error " + _error);
}
}
};
| gpl-2.0 |
Siguana/linyipassport | plugins/system/jat3/jat3/core/head.php | 31131 | <?php
/**
* ------------------------------------------------------------------------
* JA T3v2 System Plugin for J25 & J32
* ------------------------------------------------------------------------
* Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
// No direct access
defined('_JEXEC') or die;
/**
* Optimizing css/js class for rendering T3 template
*
* @package JAT3.Core
*/
class T3Head extends JObject
{
/**
* Array folder & file js ignore when minify
*
* @var array
*/
private static $js_ignore_list = array(
'media/system/js/',
'media/media/js/',
'/jquery.min.js'
);
/**
* Execute css/js optimizing base on joomla document object
*
* @return void
*/
public static function proccess()
{
$document = JFactory::getDocument();
$urlPath = new T3Path;
//proccess stylesheets
$themes = T3Common::get_active_themes();
//$themes[] = array('core', 'default'); //default now move to template root folder
//$themes[] = array('engine', 'default');
$themes = array_reverse($themes);
$scripts = array();
$css_urls = array();
$css_urls['site'] = array();
foreach ($themes as $theme) {
$css_urls[$theme[0].'.'.$theme[1]] = array();
}
foreach ($themes as $theme) {
$css_urls[$theme[0].'.'.$theme[1].'-browser'] = array();
}
if (T3Common::isRTL()) {
foreach ($themes as $theme) {
$css_urls[$theme[0].'.'.$theme[1].'-rtl'] = array();
}
}
//$bname = T3Common::getBrowserSortName();
//$bver = T3Common::getBrowserMajorVersion();
$optimize_css = T3Parameter::_getParam('optimize_css', 2);
$optimize_js = T3Parameter::_getParam('optimize_js', 2);
foreach ($document->_styleSheets as $strSrc => $strAttr) {
$path = T3Head::cleanUrl($strSrc);
if (!$path || !preg_match('#\.css$#', $path)) {
//External url
$css_urls['site'][] = array ('', $strSrc);
continue;
}
$intemplate = false;
if (preg_match('/^templates\/' . T3_ACTIVE_TEMPLATE . '\//', $path)) {
$path = preg_replace('/^templates\/' . T3_ACTIVE_TEMPLATE . '\//', '', $path);
$intemplate = true;
}
$paths = array();
//$paths[] = array ('', $path, $strSrc); //The third element is the original url
$paths[] = array('', $path); // Fix when source code in subfolder
//if ($intemplate) {
//only load other css files if in T3v2 template
$ext = '';
if (preg_match('#\.[^.]+$#', $path, $matches)) {
$ext = $matches[0];
}
//if ($ext) {
//$paths[] = array('-browser', str_replace($ext, "-$bname$ext", $path));
//$paths[] = array('-browser', str_replace($ext, "-$bname$bver$ext", $path));
//if (T3Common::isRTL()) {
//$paths[] = array('-rtl', str_replace($ext, "-rtl$ext", $path));
//$paths[] = array('-rtl', str_replace($ext, "-$bname-rtl$ext", $path));
//$paths[] = array('-rtl', str_replace($ext, "-$bname$bver-rtl$ext", $path));
//}
//}
if ($ext && T3Common::isRTL()) {
$paths[] = array('-rtl', str_replace($ext, "-rtl$ext", $path));
}
//}
foreach ($paths as $path) {
//
if ($intemplate) {
$urls = $urlPath->get($path[1], true);
if ($urls) {
foreach ($urls as $theme=>$url) {
$url[] = $strAttr;
$css_urls [$theme.$path[0]][$url[0]] = $url;
}
}
} else {
if (is_file(T3Path::path($path[1]))) {
$css_urls['site'][T3Path::path($path[1])] = array (
T3Path::path($path[1]),
count($path) > 2 ? $path[2] : T3Path::url($path[1]),
$strAttr
); //use original url ($path[2]) if exists
}
}
}
}
// Remove current stylesheets
$document->_styleSheets = array();
foreach ($document->_scripts as $strSrc => $strType) {
$srcurl = T3Head::cleanUrl($strSrc);
if (!$srcurl || !preg_match('#\.js$#', $srcurl)) {
$scrips[] = array ('', $strSrc);
continue;
}
if (preg_match('/^templates\/'.T3_ACTIVE_TEMPLATE.'\//', $srcurl)) {
//in template
$srcurl = preg_replace('/^templates\/'.T3_ACTIVE_TEMPLATE.'\//', '', $srcurl);
$path = str_replace('/', DS, $srcurl);
$url = $urlPath->get($path);
if ($url) {
$scrips[] = $url;
}
} else {
// Don't read file content => keep original link
if ($optimize_js < 1) {
$scrips[] = array ('', $strSrc);
continue;
}
$path = str_replace('/', DS, $srcurl);
$scrips[] = array (JPATH_SITE.DS.$path, JURI::base(true).'/'.$srcurl);
}
}
//remove current scripts
$document->_scripts = array();
$tmp_css_urls = false;
do {
$tmp_css_urls = T3Head::optimizecss($css_urls);
} while ($tmp_css_urls === false);
$css_urls = $tmp_css_urls;
//if ($url) $css_urls = array(array(array('', $url)));
//re-add stylesheet to head
foreach ($css_urls as $urls) {
foreach ($urls as $url) {
if (count($url) > 2) {
$attrs = $url[2];
$document->addStylesheet($url[1], $attrs['mime'], $attrs['media'], $attrs['attribs']);
} else {
$document->addStylesheet($url[1]);
}
}
}
$tmp_scrips = false;
do {
$tmp_scrips = T3Head::optimizejs($scrips);
} while ($tmp_scrips === false);
$scrips = $tmp_scrips;
//re-add stylesheet to head
foreach ($scrips as $url) {
$document->addScript($url[1]);
}
}
/**
* Check and make URL more clean
*
* @param string $strSrc URL
*
* @return string clean URL
*/
public static function cleanUrl($strSrc)
{
$strSrc = preg_replace('#[?\#]+.*$#', '', $strSrc);
// Fix bug when K2 add jQuery library without http:
if (strpos($strSrc, '//ajax.googleapis.com') !== false || strpos($strSrc, 'k2.js') !== false) {
return false;
} elseif (preg_match('/^https?\:/', $strSrc)) {
if (! preg_match('#^' . preg_quote(JURI::base()) . '#', $strSrc)) {
// External css
return false;
}
$strSrc = str_replace(JURI::base(), '', $strSrc);
} elseif (preg_match('/^\//', $strSrc) && JURI::base(true)) {
if (!preg_match('#^' . preg_quote(JURI::base(true)) . '#', $strSrc)) {
// Same server, but outsite website
return false;
}
$strSrc = preg_replace('#^' . preg_quote(JURI::base(true)) . '#', '', $strSrc);
}
$strSrc = str_replace('//', '/', $strSrc); //replace double slash by one
$strSrc = preg_replace('/^\//', '', $strSrc); //remove first slash
return $strSrc;
}
/**
* Check if someone is optimizing css or js
* loop in 1/100 second
* if waiting more 5 seconds, we will hot release lock
*
* @param string $cache_path Cache path
* @param string $lock_file Lock file name
*
* @return bool TRUE if still lock, otherwise FALSE
*/
public static function optimizeCheckLock($cache_path, $lock_file)
{
$waiting = false;
$counter = 0;
while (file_exists($cache_path . DS . $lock_file)) {
usleep(10000);
$waiting = true;
$counter++;
if ($counter > 500) {
T3Head::optimizeReleaseLock($cache_path, $lock_file);
break;
}
}
return $waiting;
}
/**
* Create lock before optimizing js or cs
* This process is only finish if and only if can write something to this file
*
* @param string $cache_path Cache path
* @param string $lock_file Lock file name
*
* @return bool TRUE if create success, otherwise FALSE
*/
public static function optimizeCreateLock($cache_path, $lock_file)
{
if (!is_dir($cache_path)) {
// Cannot create cache folder for js/css optimize
if (!@JFolder::create($cache_path)) {
return false;
}
}
/*
$file = @fopen($cache_path . DS . $lock_file, "x");
if($file)
{
fclose($file);
return true;
}
return false;
*/
// # Fix when ftp & web server use 2 diferent accounts.
$data = 'lock';
return JFile::write($cache_path . DS . $lock_file, $data);
}
/**
* Release lock file
*
* @param string $cache_path Cache path
* @param string $lock_file Lock file name
*
* @return bool TRUE if success, otherwise FALSE
*/
public static function optimizeReleaseLock($cache_path, $lock_file)
{
if (file_exists($cache_path . DS . $lock_file)) {
try {
//unlink($cache_path . DS . $lock_file);
//return true;
// # Fix when ftp & web server use 2 diferent accounts.
return @JFile::delete($cache_path . DS . $lock_file);
} catch (Exception $e) {
}
}
return false;
}
/**
* Optimize js base on list js
*
* @param array $js_urls List of js file
*
* @return array List of optimized js file
*/
public static function optimizejs($js_urls)
{
$content = '';
$optimize_js = T3Parameter::_getParam('optimize_js', 1);
if (!$optimize_js) {
return $js_urls;
}
//# Fix when optimized_folder is un-writeable
$cachepath = T3Path::path(T3Parameter::_getParam('optimize_folder', 't3-assets'));
$cachepath .= DS . 'js';
if (!T3Common::checkWriteable($cachepath)) {
return $js_urls;
}
$output = array();
$optimize_exclude = trim(T3Parameter::_getParam('optimize_exclude', ''));
$optimize_exclude_regex = null;
if ($optimize_exclude) {
$optimize_exclude_regex = '#' . preg_replace('#[\r\n]+#', '|', preg_quote($optimize_exclude)) . '#';
}
$files = array();
//# Check lock file before start checking update
$lock_file = "optimize.js.lock";
$waiting = T3Head::optimizeCheckLock($cachepath, $lock_file);
$lock_file_file = null;
$needupdate = false;
$need_optimize = false;
$required_optimize_list = array();
$files_array = array();
jimport('joomla.filesystem.file');
foreach ($js_urls as $url) {
if (!$url[0] || !preg_match('#\.js$#', $url[0])
|| ($optimize_exclude_regex && preg_match($optimize_exclude_regex, $url[1]))
) {
//ignore if not a local file or not a static js file
//output to file
if (count($files)) {
$files_array[] = array('files' => $files, 'needupdate' => $needupdate);
}
//put this ignore file into ouput
//$output[] = $url;
// Ignore file however must follow by order
$files_array[] = array('files' => $url, 'ignore' => true);
//reset the flag for file update
$needupdate = false;
$files = array();
} else {
//for static local file
if ($optimize_js > 1) {
// Check js file was minified
$ignore_compress = false;
foreach (self::$js_ignore_list as $js_ignore) {
if (strpos($url[1], $js_ignore)) {
$ignore_compress = true;
break;
}
}
if ($ignore_compress) {
$files[] = array($url[0], '');
} else {
// Need optimized
// Check if this file is changed from the last optimized
// This file is changed/modified after cached
$cfile = $cachepath . DS . 'js_' . md5($url[0]) . '.' . basename($url[0]);
if (!file_exists($cfile) || @filemtime($url[0]) > @filemtime($cfile)) {
$required_optimize_list[] = array('cfile' => $cfile, 'url0' => $url[0], 'url1' => $url[1]);
$needupdate = true;
$need_optimize = true;
}
$files[] = array($cfile, '');
}
} else {
//just keep original
$files[] = $url;
}
}
}
if ($need_optimize) {
//# Only create lock if and only if require optimize
if (!T3Head::optimizeCreateLock($cachepath, $lock_file)) {
return false;
}
foreach ($required_optimize_list as $required_optimize) {
$data = T3Head::compressjs(@JFile::read($required_optimize['url0']), $required_optimize['url1']) . ';';
@JFile::write($required_optimize['cfile'], $data);
}
}
if (!file_exists($cachepath)) {
@JFolder::create($cachepath);
}
//$file = fopen($cachepath . DS . session_id() . "txt", "a");
if (count($files)) {
$files_array[] = array('files' => $files, 'needupdate' => $needupdate);
}
foreach ($files_array as $group_files) {
// Check ignore file
if (!isset($group_files['ignore'])) {
$ourl = T3Head::store_file2($group_files['files'], 'js', $group_files['needupdate']);
// Check result
if (!$ourl) {
return $js_urls;
}
// Put result into output
$output[] = array('', $ourl);
} else {
//$ourl = $group_files['files'];
$output[] = $group_files['files'];
}
}
//# Release lock
T3Head::optimizeReleaseLock($cachepath, $lock_file);
return $output;
}
/**
* Optimize css base on list css
*
* @param array $css_urls List of css file
*
* @return array List of optimized css file
*/
public static function optimizecss($css_urls)
{
$content = '';
$optimize_css = T3Parameter::_getParam('optimize_css', 2);
if (!$optimize_css) {
return $css_urls; //no optimize css
}
// # Fix when optimized_folder is un-writeable
$cachepath = T3Path::path(T3Parameter::_getParam('optimize_folder', 't3-assets'));
$cachepath .= DS . 'css';
//$parentpath = dirname($cachepath);
if (!T3Common::checkWriteable($cachepath)) {
return $css_urls;
}
$output = array();
$optimize_exclude = trim(T3Parameter::_getParam('optimize_exclude', ''));
$optimize_exclude_regex = null;
if ($optimize_exclude) {
$optimize_exclude_regex = '#' . preg_replace('#[\r\n]+#', '|', preg_quote($optimize_exclude)) . '#';
}
$files = array();
// # Check lock file before start checking update
$lock_file = "optimize.js.lock";
$waiting = T3Head::optimizeCheckLock($cachepath, $lock_file);
$lock_file_file = null;
$needupdate = false;
$need_optimize = false;
$required_optimize_list = array();
$files_array = array();
// Limit files import into a css file (in IE7, only first 30 css files are loaded). other case, load unlimited
$filelimit = ($optimize_css == 1)?20:999;
$filecount = 0;
jimport('joomla.filesystem.file');
foreach ($css_urls as $theme=>$urls) {
foreach ($urls as $url) {
$ignore = false;
$import = false;
$importupdate = false;
// check ignore to optimize
// - not a local file
// - not a css file
// - in ignore list
if (!$url[0]) {
$ignore = true;
} elseif (!preg_match('#\.css$#', $url[0])) {
$ignore = true; //ignore dynamic css file
} elseif (($optimize_exclude_regex && preg_match($optimize_exclude_regex, $url[1]))) {
$ignore = true;
}
if (!$ignore && $optimize_css > 1) {
//check if need update. for css, the cache should be [filename] or [filename]-import
//[filename]-import - for the case there's @import inside
//in the ignore of @import, file still optimize but will be put into a sigle file
$cfile = $cachepath . DS . 'css_' . md5($url[0]).'.'.basename($url[0]);
if (!(file_exists($cfile) && @filemtime($url[0]) < @filemtime($cfile))
&& !(file_exists($cfile.'-import') && @filemtime($url[0]) < @filemtime($cfile.'-import'))
) {
$required_optimize_list[] = array('cfile' => $cfile, 'url0' => $url[0], 'url1' => $url[1]);
//Need update
$data = @JFile::read($url[0]);
if (preg_match('#@import\s+.+#', $data)) {
$import = true;
$importupdate = true;
$cfile = $cfile.'-import';
}
$needupdate = true;
$need_optimize = true;
} elseif (is_file($cfile.'-import')) {
$import = true;
$importupdate = false;
$cfile = $cfile.'-import';
}
}
//match ignore file, or import file, or reach the limit: flush previous files out
if ($ignore || $import || count($files)==$filelimit) {
if (count($files)) {
$files_array[] = array('files' => $files, 'needupdate' => $needupdate);
}
//reset the flag for file update
$needupdate = false;
$files = array();
}
//write out the @import file
if ($ignore) {
//$output[] = $url;
// Ignore file however must follow by order
$files_array[] = array('files' => $url, 'ignore' => true);
} else {
if ($optimize_css > 1) {
$files[] = array($cfile,'', $url[2]);
} else {
$files[] = $url;
}
}
}
}
if ($need_optimize) {
//# Only create lock if and only if require optimize
if (!T3Head::optimizeCreateLock($cachepath, $lock_file)) {
return false;
}
foreach ($required_optimize_list as $required_optimize) {
$data = T3Head::compresscss(@JFile::read($required_optimize['url0']), $required_optimize['url1']);
if (preg_match('#@import\s+.+#', $data)) {
$import = true;
$importupdate = true;
$required_optimize['cfile'] = $required_optimize['cfile'] . '-import';
}
if (JFile::exists($required_optimize['cfile'])) {
@JFile::delete($required_optimize['cfile']);
}
if (JFile::exists($required_optimize['cfile'] . '-import')) {
@JFile::delete($required_optimize['cfile'] . '-import');
}
@JFile::write($required_optimize['cfile'], $data);
$needupdate = true;
}
}
if (count($files)) {
$files_array[] = array('files' => $files, 'needupdate' => $needupdate);
}
foreach ($files_array as $group_files) {
// Check ignore file
if (!isset($group_files['ignore'])) {
$ourl = T3Head::store_file2($group_files['files'], 'css', $group_files['needupdate']);
if (!$ourl) {
return $css_urls;
}
$output[] = array('', $ourl);
} else {
$output[] = $group_files['files'];
}
}
// # Release lock
T3Head::optimizeReleaseLock($cachepath, $lock_file);
return array($output);
}
/**
* Compress css file
*
* @param string $data CSS data
* @param string $url CSS URL
*
* @return string Compressed css data
*/
public static function compresscss($data, $url)
{
global $current_css_url;
//if ($url[0] == '/') $url = JURI::root(false, '').substr($url, 1);
$current_css_url = $url;
/* remove comments */
$data = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $data);
/* remove tabs, spaces, new lines, etc. */
$data = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), ' ', $data);
/* remove unnecessary spaces */
$data = preg_replace('/[ ]+([{};,:])/', '\1', $data);
$data = preg_replace('/([{};,:])[ ]+/', '\1', $data);
/* remove empty class */
$data = preg_replace('/(\}([^\}]*\{\})+)/', '}', $data);
/* replace url*/
$data = preg_replace_callback('/url\(([^\)]*)\)/', array('T3Head', 'replaceurl'), $data);
return $data;
}
/**
* Compress js file
*
* @param string $data JS data
* @param string $url JS URL
*
* @return string Compressed js data
*/
public static function compressjs($data, $url)
{
$optimize_js = T3Parameter::_getParam('optimize_js', 1);
if ($optimize_js < 2) {
return $data; //no compress
}
//compress using jsmin
t3import('core.libs.jsmin');
return JSMin::minify($data);
}
/**
* Replace URL for suitable mode
*
* @param array $matches Matches of URL
*
* @return string Replaced URL
*/
public static function replaceurl($matches)
{
$url = str_replace(array('"', '\''), '', $matches[1]);
global $current_css_url;
$url = T3Head::converturl($url, $current_css_url);
return "url('$url')";
}
/**
* Convert URL for suitable mode
*
* @param string $_url URL
* @param string $cssurl CSS URL
*
* @return string Converted URL
*/
public static function converturl($_url, $cssurl)
{
$url = $_url;
$base = dirname($cssurl);
$base = str_replace(JURI::base(), JURI::base(true) . '/', $base);
$optimize_css = T3Parameter::_getParam('optimize_css', 2);
if ($optimize_css < 3) {
//compress - using absolute path
//not compress - convert to relative path
$base = T3Head::cleanUrl($base);
$cache_path = T3Parameter::_getParam('optimize_folder', 't3-assets');
while ($cache_path && $cache_path != '.') {
$cache_path = dirname($cache_path);
$base = '../' . $base;
}
}
if (preg_match('/^(\/|http)/', $url)) {
return $url; /*absolute or root*/
}
while (preg_match('/^\.\.\//', $url)) {
$base = dirname($base);
$url = substr($url, 3);
}
//if ($base === '\\' || $base === '/') $base = '';
$url = $base . '/' . $url;
if ($url[0] == '\\' || $url[0] == '/') {
$url = ltrim($url, '\\/');
$url = '/' . $url;
}
return $url;
}
//
/**
* Use a shorter and readable filename. use version to tell the browser that the file content is change.
* Read content from array of files $files and write to one cached file if need update $needupdate or cached file not exists
*
* @param array $files List of file
* @param string $ext Extension
* @param bool $needupdate Indicate need to update file or not
*
* @return The new file url
*/
public static function store_file2($files, $ext, $needupdate)
{
$cache_path = T3Parameter::_getParam('optimize_folder', 't3-assets');
$optimize_level = T3Parameter::_getParam('optimize_' . $ext, 1);
$path = T3Path::path($cache_path);
if (!is_dir($path)) {
if (!@JFolder::create($path)) {
return false; //cannot create cache folder for js/css optimize
}
}
if (!is_file($path . DS . 'index.html')) {
$indexcontent = '<html><body></body></html>';
if (!@JFile::write($path . DS . 'index.html', $indexcontent)) {
return false; //cannot create blank index.html to prevent list files
}
}
static $filemap = array();
//data.php contain filename maps
$datafile = $path.'/data.php';
if (is_file($datafile)) {
include_once $datafile;
}
//get a salt
if (!isset($filemap['salt']) || !$filemap['salt']) {
$filemap['salt'] = rand();
}
//build destination file
$file = md5($filemap['salt'] . serialize($files));
$filename = $ext . '_' . substr($file, 0, 5) . ".$ext";
$destfile = $path . DS . $filename;
//re-populate $needupdate in case $destfile exists & keep original (not minify)
if ($optimize_level == 1 && is_file($destfile)) {
foreach ($files as $f) {
if (@filemtime($f[0]) > @filemtime($destfile)) {
$needupdate = true;
break;
}
}
}
//check if need update
if (!$needupdate && is_file($destfile)) {
$fileversion = isset($filemap[$ext]) && isset($filemap[$ext][$file]) ? $filemap[$ext][$file] : 1;
$fileversion = $fileversion == 1 ? "" : "?v=" . $filemap[$ext][$file];
if ($optimize_level < 3) {
return T3Path::url($cache_path) . '/' . $filename . $fileversion;
} else {
$url = "jat3action=gzip&jat3type=$ext&jat3file=" . urlencode($cache_path . '/' . $filename);
// Fix when enable languagefilter plugin
$url = self::buildURL($url);
return $url;
}
}
//get files content
$content = '';
foreach ($files as $f) {
$media = count($f) > 2 ? trim($f[2]['media']) : "";
if ($ext == 'css') {
if ($optimize_level == 1) {
$content .= "@import url(\"{$f[1]}\") {$media};\n";
} elseif (!empty($media)) {
$content .= "/* " . substr(basename($f[0]), 33) . " */\n" . "@media " . $f[2]['media'] . " {\n" . @JFile::read($f[0]) . "\n}\n\n";
} else {
$content .= "/* " . substr(basename($f[0]), 33) . " */\n" . @JFile::read($f[0]) . "\n\n";
}
} else {
$content .= "/* " . basename($f[0]) . " */\n" . @JFile::read($f[0]) . ";\n\n";
}
}
if (!isset($filemap[$ext])) {
$filemap[$ext] = array();
}
if (!isset($filemap[$ext][$file])) {
$filemap[$ext][$file] = 0; //store file version
}
//update file version
$filemap[$ext][$file] = $filemap[$ext][$file] + 1;
$fileversion = $filemap[$ext][$file]==1?"":"?v=".$filemap[$ext][$file];
//update datafile
$filemapdata = '<?php $filemap = ' . var_export($filemap, true) . '; ?>';
@JFile::write($datafile, $filemapdata);
//create new file
if (! @JFile::write($destfile, $content)) {
return false; // Cannot create file
}
//return result
//check if need compress
if ($optimize_level == 3) { //compress
$url = "jat3action=gzip&jat3type=$ext&jat3file=" . urlencode($cache_path . '/' . $filename);
// Fix when enable languagefilter plugin
$url = self::buildURL($url);
return $url;
}
return T3Path::url($cache_path) . '/' . $filename . $fileversion;
}
/**
* Build URL for suitable language filter & sef mode in Joomla 1.7
*
* @param string $url URL
*
* @return string Built URL
*/
public static function buildURL($url)
{
if (JPluginHelper::isEnabled('system', 'languagefilter')) {
$lang_codes = JLanguageHelper::getLanguages('lang_code');
$default_lang = JComponentHelper::getParams('com_languages')->get('site', 'en-GB');
$default_sef = $lang_codes[$default_lang]->sef;
$app = JFactory::getApplication();
$router = $app->getRouter();
if ($router->getMode() == JROUTER_MODE_SEF) {
if ($app->getCfg('sef_rewrite')) {
$url = JURI::base(true) . "/en/?$url";
} else {
$url = JURI::base(true) . "/index.php/en/?$url";
}
} else {
$url = JURI::base(true) . "/index.php?lang=$default_sef&$url";
}
} else {
$url = JURI::base(true) . "/index.php?$url";
}
return $url;
}
} | gpl-2.0 |
wiki2014/Learning-Summary | alps/developers/build/prebuilts/gradle/LNotifications/Application/tests/src/com/example/android/lnotifications/HeadsUpNotificationFragmentTest.java | 1898 | package com.example.android.lnotifications;
import android.app.Notification;
import android.test.ActivityInstrumentationTestCase2;
/**
* Unit tests for {@link HeadsUpNotificationFragment}.
*/
public class HeadsUpNotificationFragmentTest extends
ActivityInstrumentationTestCase2<LNotificationActivity> {
private LNotificationActivity mActivity;
private HeadsUpNotificationFragment mFragment;
public HeadsUpNotificationFragmentTest() {
super(LNotificationActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mActivity = getActivity();
// The first tab should be {@link HeadsUpNotificationFragment}, that is tested in the
// {@link LNotificationActivityTest}.
mActivity.getActionBar().setSelectedNavigationItem(0);
getInstrumentation().waitForIdleSync();
mFragment = (HeadsUpNotificationFragment) mActivity.getFragmentManager()
.findFragmentById(R.id.container);
}
public void testPreconditions() {
assertNotNull(mActivity);
assertNotNull(mFragment);
assertNotNull(mActivity.findViewById(R.id.heads_up_notification_description));
assertNotNull(mActivity.findViewById(R.id.show_notification_button));
assertNotNull(mActivity.findViewById(R.id.use_heads_up_checkbox));
}
public void testCreateNotification_verifyFullScreenIntentIsNotNull() {
Notification notification = mFragment.createNotification(true);
assertNotNull(notification.fullScreenIntent);
}
public void testCreateNotification_verifyFullScreenIntentIsNull() {
Notification notification = mFragment.createNotification(false);
assertNull(notification.fullScreenIntent);
}
// If Mockito can be used, mock the NotificationManager and tests Notifications are actually
// created.
}
| gpl-3.0 |
Sweetgrassbuffalo/ReactionSweeGrass-v2 | node_modules/d3-scale-chromatic/src/sequential-single/Greens.js | 440 | import colors from "../colors";
import ramp from "../ramp";
export var scheme = new Array(3).concat(
"e5f5e0a1d99b31a354",
"edf8e9bae4b374c476238b45",
"edf8e9bae4b374c47631a354006d2c",
"edf8e9c7e9c0a1d99b74c47631a354006d2c",
"edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32",
"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32",
"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b"
).map(colors);
export default ramp(scheme);
| gpl-3.0 |
AnHardt/Marlin | Marlin/src/lcd/menu/game/brickout.cpp | 7045 | /**
* Marlin 3D Printer Firmware
* Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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, see <https://www.gnu.org/licenses/>.
*
*/
#include "../../../inc/MarlinConfigPre.h"
#if ENABLED(MARLIN_BRICKOUT)
#include "game.h"
#define BRICK_H 5
#define BRICK_TOP MENU_FONT_ASCENT
#define PADDLE_H 2
#define PADDLE_VEL 3
#define PADDLE_W ((LCD_PIXEL_WIDTH) / 8)
#define PADDLE_Y (LCD_PIXEL_HEIGHT - 1 - PADDLE_H)
#define BRICK_W ((LCD_PIXEL_WIDTH) / (BRICK_COLS))
#define BRICK_BOT (BRICK_TOP + BRICK_H * BRICK_ROWS - 1)
#define BRICK_COL(X) ((X) / (BRICK_W))
#define BRICK_ROW(Y) ((Y - (BRICK_TOP)) / (BRICK_H))
brickout_data_t &bdat = marlin_game_data.brickout;
inline void reset_bricks(const uint16_t v) {
bdat.brick_count = (BRICK_COLS) * (BRICK_ROWS);
LOOP_L_N(i, BRICK_ROWS) bdat.bricks[i] = v;
}
void reset_ball() {
constexpr uint8_t ball_dist = 24;
bdat.bally = BTOF(PADDLE_Y - ball_dist);
bdat.ballv = FTOP(1.3f);
bdat.ballh = -FTOP(1.25f);
uint8_t bx = bdat.paddle_x + (PADDLE_W) / 2 + ball_dist;
if (bx >= LCD_PIXEL_WIDTH - 10) { bx -= ball_dist * 2; bdat.ballh = -bdat.ballh; }
bdat.ballx = BTOF(bx);
bdat.hit_dir = -1;
}
void BrickoutGame::game_screen() {
if (game_frame()) { // Run logic twice for finer resolution
// Update Paddle Position
bdat.paddle_x = constrain(int8_t(ui.encoderPosition), 0, (LCD_PIXEL_WIDTH - (PADDLE_W)) / (PADDLE_VEL));
ui.encoderPosition = bdat.paddle_x;
bdat.paddle_x *= (PADDLE_VEL);
// Run the ball logic
if (game_state) do {
// Provisionally update the ball position
const fixed_t newx = bdat.ballx + bdat.ballh, newy = bdat.bally + bdat.ballv; // current next position
if (!WITHIN(newx, 0, BTOF(LCD_PIXEL_WIDTH - 1))) { // out in x?
bdat.ballh = -bdat.ballh; _BUZZ(5, 220); // bounce x
}
if (newy < 0) { // out in y?
bdat.ballv = -bdat.ballv; _BUZZ(5, 280); // bounce v
bdat.hit_dir = 1;
}
// Did the ball go below the bottom?
else if (newy > BTOF(LCD_PIXEL_HEIGHT)) {
_BUZZ(500, 75);
if (--bdat.balls_left) reset_ball(); else game_state = 0;
break; // done
}
// Is the ball colliding with a brick?
if (WITHIN(newy, BTOF(BRICK_TOP), BTOF(BRICK_BOT))) {
const int8_t bit = BRICK_COL(FTOB(newx)), row = BRICK_ROW(FTOB(newy));
const uint16_t mask = _BV(bit);
if (bdat.bricks[row] & mask) {
// Yes. Remove it!
bdat.bricks[row] &= ~mask;
// Score!
score += BRICK_ROWS - row;
// If bricks are gone, go to reset state
if (!--bdat.brick_count) game_state = 2;
// Bounce the ball cleverly
if ((bdat.ballv < 0) == (bdat.hit_dir < 0)) { bdat.ballv = -bdat.ballv; bdat.ballh += fixed_t(random(-16, 16)); _BUZZ(5, 880); }
else { bdat.ballh = -bdat.ballh; bdat.ballv += fixed_t(random(-16, 16)); _BUZZ(5, 640); }
}
}
// Is the ball moving down and in paddle range?
else if (bdat.ballv > 0 && WITHIN(newy, BTOF(PADDLE_Y), BTOF(PADDLE_Y + PADDLE_H))) {
// Ball actually hitting paddle
const int8_t diff = FTOB(newx) - bdat.paddle_x;
if (WITHIN(diff, 0, PADDLE_W - 1)) {
// Reverse Y direction
bdat.ballv = -bdat.ballv; _BUZZ(3, 880);
bdat.hit_dir = -1;
// Near edges affects X velocity
const bool is_left_edge = (diff <= 1);
if (is_left_edge || diff >= PADDLE_W-1 - 1) {
if ((bdat.ballh > 0) == is_left_edge) bdat.ballh = -bdat.ballh;
}
else if (diff <= 3) {
bdat.ballh += fixed_t(random(-64, 0));
NOLESS(bdat.ballh, BTOF(-2));
NOMORE(bdat.ballh, BTOF(2));
}
else if (diff >= PADDLE_W-1 - 3) {
bdat.ballh += fixed_t(random( 0, 64));
NOLESS(bdat.ballh, BTOF(-2));
NOMORE(bdat.ballh, BTOF(2));
}
// Paddle hit after clearing the board? Reset the board.
if (game_state == 2) { reset_bricks(0xFFFF); game_state = 1; }
}
}
bdat.ballx += bdat.ballh; bdat.bally += bdat.ballv; // update with new velocity
} while (false);
}
u8g.setColorIndex(1);
// Draw bricks
if (PAGE_CONTAINS(BRICK_TOP, BRICK_BOT)) {
LOOP_L_N(y, BRICK_ROWS) {
const uint8_t yy = y * BRICK_H + BRICK_TOP;
if (PAGE_CONTAINS(yy, yy + BRICK_H - 1)) {
LOOP_L_N(x, BRICK_COLS) {
if (TEST(bdat.bricks[y], x)) {
const uint8_t xx = x * BRICK_W;
LOOP_L_N(v, BRICK_H - 1)
if (PAGE_CONTAINS(yy + v, yy + v))
u8g.drawHLine(xx, yy + v, BRICK_W - 1);
}
}
}
}
}
// Draw paddle
if (PAGE_CONTAINS(PADDLE_Y-1, PADDLE_Y)) {
u8g.drawHLine(bdat.paddle_x, PADDLE_Y, PADDLE_W);
#if PADDLE_H > 1
u8g.drawHLine(bdat.paddle_x, PADDLE_Y-1, PADDLE_W);
#if PADDLE_H > 2
u8g.drawHLine(bdat.paddle_x, PADDLE_Y-2, PADDLE_W);
#endif
#endif
}
// Draw ball while game is running
if (game_state) {
const uint8_t by = FTOB(bdat.bally);
if (PAGE_CONTAINS(by, by+1))
u8g.drawFrame(FTOB(bdat.ballx), by, 2, 2);
}
// Or draw GAME OVER
else
draw_game_over();
if (PAGE_UNDER(MENU_FONT_ASCENT)) {
// Score Digits
//const uint8_t sx = (LCD_PIXEL_WIDTH - (score >= 10 ? score >= 100 ? score >= 1000 ? 4 : 3 : 2 : 1) * MENU_FONT_WIDTH) / 2;
constexpr uint8_t sx = 0;
lcd_put_int(sx, MENU_FONT_ASCENT - 1, score);
// Balls Left
lcd_moveto(LCD_PIXEL_WIDTH - MENU_FONT_WIDTH * 3, MENU_FONT_ASCENT - 1);
PGM_P const ohs = PSTR("ooo\0\0");
lcd_put_u8str_P(ohs + 3 - bdat.balls_left);
}
// A click always exits this game
if (ui.use_click()) exit_game();
}
#define SCREEN_M ((LCD_PIXEL_WIDTH) / 2)
void BrickoutGame::enter_game() {
init_game(2, game_screen); // 2 = reset bricks on paddle hit
constexpr uint8_t paddle_start = SCREEN_M - (PADDLE_W) / 2;
bdat.paddle_x = paddle_start;
bdat.balls_left = 3;
reset_bricks(0x0000);
reset_ball();
ui.encoderPosition = paddle_start / (PADDLE_VEL);
}
#endif // MARLIN_BRICKOUT
| gpl-3.0 |
HossainKhademian/Studio3 | plugins/com.aptana.core/src/com/aptana/core/internal/resources/MarkerDelta.java | 1759 | /**
* Aptana Studio
* Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.core.internal.resources;
import org.eclipse.core.internal.resources.IMarkerSetElement;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.ResourcesPlugin;
import com.aptana.core.resources.IUniformResource;
/**
*
*/
@SuppressWarnings("restriction")
public class MarkerDelta extends org.eclipse.core.internal.resources.MarkerDelta {
/**
* uniform resource
*/
protected IUniformResource resource;
public MarkerDelta(int kind, IUniformResource resource, MarkerInfo info)
{
super(kind, ResourcesPlugin.getWorkspace().getRoot(), info);
this.resource = resource;
}
/* (non-Javadoc)
* @see org.eclipse.core.internal.resources.MarkerDelta#isSubtypeOf(java.lang.String)
*/
public boolean isSubtypeOf(String superType)
{
return MarkerManager.getInstance().isSubtype(getType(), superType);
}
/* (non-Javadoc)
* @see org.eclipse.core.internal.resources.MarkerDelta#getMarker()
*/
public IMarker getMarker()
{
return new UniformResourceMarker(resource, getId());
}
/**
* getUniformResource
*
* @return IUniformResource
*/
public IUniformResource getUniformResource() {
return resource;
}
protected static MarkerSet merge(MarkerSet oldChanges, IMarkerSetElement[] newChanges) {
MarkerSet merged = new MarkerSet();
merged.addAll(org.eclipse.core.internal.resources.MarkerDelta.merge(oldChanges, newChanges).elements());
return merged;
}
}
| gpl-3.0 |
carpe-diem/conectar-igualdad-server-apps | apps/src/intranet/mediawiki/includes/Categoryfinder.php | 5203 | <?php
/**
* The "Categoryfinder" class takes a list of articles, creates an internal
* representation of all their parent categories (as well as parents of
* parents etc.). From this representation, it determines which of these
* articles are in one or all of a given subset of categories.
*
* Example use :
* <code>
* # Determines whether the article with the page_id 12345 is in both
* # "Category 1" and "Category 2" or their subcategories, respectively
*
* $cf = new Categoryfinder;
* $cf->seed(
* array( 12345 ),
* array( 'Category 1', 'Category 2' ),
* 'AND'
* );
* $a = $cf->run();
* print implode( ',' , $a );
* </code>
*
*/
class Categoryfinder {
var $articles = array(); # The original article IDs passed to the seed function
var $deadend = array(); # Array of DBKEY category names for categories that don't have a page
var $parents = array(); # Array of [ID => array()]
var $next = array(); # Array of article/category IDs
var $targets = array(); # Array of DBKEY category names
var $name2id = array();
var $mode; # "AND" or "OR"
var $dbr; # Read-DB slave
/**
* Constructor (currently empty).
*/
function __construct() {
}
/**
* Initializes the instance. Do this prior to calling run().
* @param $article_ids Array of article IDs
* @param $categories FIXME
* @param $mode String: FIXME, default 'AND'.
*/
function seed( $article_ids, $categories, $mode = 'AND' ) {
$this->articles = $article_ids;
$this->next = $article_ids;
$this->mode = $mode;
# Set the list of target categories; convert them to DBKEY form first
$this->targets = array();
foreach ( $categories as $c ) {
$ct = Title::makeTitleSafe( NS_CATEGORY, $c );
if ( $ct ) {
$c = $ct->getDBkey();
$this->targets[$c] = $c;
}
}
}
/**
* Iterates through the parent tree starting with the seed values,
* then checks the articles if they match the conditions
* @return array of page_ids (those given to seed() that match the conditions)
*/
function run() {
$this->dbr = wfGetDB( DB_SLAVE );
while ( count( $this->next ) > 0 ) {
$this->scan_next_layer();
}
# Now check if this applies to the individual articles
$ret = array();
foreach ( $this->articles as $article ) {
$conds = $this->targets;
if ( $this->check( $article, $conds ) ) {
# Matches the conditions
$ret[] = $article;
}
}
return $ret;
}
/**
* This functions recurses through the parent representation, trying to match the conditions
* @param $id The article/category to check
* @param $conds The array of categories to match
* @param $path used to check for recursion loops
* @return bool Does this match the conditions?
*/
function check( $id, &$conds, $path = array() ) {
// Check for loops and stop!
if ( in_array( $id, $path ) ) {
return false;
}
$path[] = $id;
# Shortcut (runtime paranoia): No contitions=all matched
if ( count( $conds ) == 0 ) {
return true;
}
if ( !isset( $this->parents[$id] ) ) {
return false;
}
# iterate through the parents
foreach ( $this->parents[$id] as $p ) {
$pname = $p->cl_to ;
# Is this a condition?
if ( isset( $conds[$pname] ) ) {
# This key is in the category list!
if ( $this->mode == 'OR' ) {
# One found, that's enough!
$conds = array();
return true;
} else {
# Assuming "AND" as default
unset( $conds[$pname] );
if ( count( $conds ) == 0 ) {
# All conditions met, done
return true;
}
}
}
# Not done yet, try sub-parents
if ( !isset( $this->name2id[$pname] ) ) {
# No sub-parent
continue;
}
$done = $this->check( $this->name2id[$pname], $conds, $path );
if ( $done || count( $conds ) == 0 ) {
# Subparents have done it!
return true;
}
}
return false;
}
/**
* Scans a "parent layer" of the articles/categories in $this->next
*/
function scan_next_layer() {
# Find all parents of the article currently in $this->next
$layer = array();
$res = $this->dbr->select(
/* FROM */ 'categorylinks',
/* SELECT */ '*',
/* WHERE */ array( 'cl_from' => $this->next ),
__METHOD__ . '-1'
);
foreach ( $res as $o ) {
$k = $o->cl_to;
# Update parent tree
if ( !isset( $this->parents[$o->cl_from] ) ) {
$this->parents[$o->cl_from] = array();
}
$this->parents[$o->cl_from][$k] = $o;
# Ignore those we already have
if ( in_array( $k, $this->deadend ) ) {
continue;
}
if ( isset( $this->name2id[$k] ) ) {
continue;
}
# Hey, new category!
$layer[$k] = $k;
}
$this->next = array();
# Find the IDs of all category pages in $layer, if they exist
if ( count( $layer ) > 0 ) {
$res = $this->dbr->select(
/* FROM */ 'page',
/* SELECT */ array( 'page_id', 'page_title' ),
/* WHERE */ array( 'page_namespace' => NS_CATEGORY , 'page_title' => $layer ),
__METHOD__ . '-2'
);
foreach ( $res as $o ) {
$id = $o->page_id;
$name = $o->page_title;
$this->name2id[$name] = $id;
$this->next[] = $id;
unset( $layer[$name] );
}
}
# Mark dead ends
foreach ( $layer as $v ) {
$this->deadend[$v] = $v;
}
}
}
| gpl-3.0 |
collectiveaccess/pawtucket2 | vendor/symfony/var-dumper/Caster/LinkStub.php | 3392 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\VarDumper\Caster;
/**
* Represents a file or a URL.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class LinkStub extends ConstStub
{
public $inVendor = false;
private static $vendorRoots;
private static $composerRoots;
public function __construct(string $label, int $line = 0, string $href = null)
{
$this->value = $label;
if (null === $href) {
$href = $label;
}
if (!\is_string($href)) {
return;
}
if (str_starts_with($href, 'file://')) {
if ($href === $label) {
$label = substr($label, 7);
}
$href = substr($href, 7);
} elseif (str_contains($href, '://')) {
$this->attr['href'] = $href;
return;
}
if (!is_file($href)) {
return;
}
if ($line) {
$this->attr['line'] = $line;
}
if ($label !== $this->attr['file'] = realpath($href) ?: $href) {
return;
}
if ($composerRoot = $this->getComposerRoot($href, $this->inVendor)) {
$this->attr['ellipsis'] = \strlen($href) - \strlen($composerRoot) + 1;
$this->attr['ellipsis-type'] = 'path';
$this->attr['ellipsis-tail'] = 1 + ($this->inVendor ? 2 + \strlen(implode('', \array_slice(explode(\DIRECTORY_SEPARATOR, substr($href, 1 - $this->attr['ellipsis'])), 0, 2))) : 0);
} elseif (3 < \count($ellipsis = explode(\DIRECTORY_SEPARATOR, $href))) {
$this->attr['ellipsis'] = 2 + \strlen(implode('', \array_slice($ellipsis, -2)));
$this->attr['ellipsis-type'] = 'path';
$this->attr['ellipsis-tail'] = 1;
}
}
private function getComposerRoot(string $file, bool &$inVendor)
{
if (null === self::$vendorRoots) {
self::$vendorRoots = [];
foreach (get_declared_classes() as $class) {
if ('C' === $class[0] && str_starts_with($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$v = \dirname($r->getFileName(), 2);
if (is_file($v.'/composer/installed.json')) {
self::$vendorRoots[] = $v.\DIRECTORY_SEPARATOR;
}
}
}
}
$inVendor = false;
if (isset(self::$composerRoots[$dir = \dirname($file)])) {
return self::$composerRoots[$dir];
}
foreach (self::$vendorRoots as $root) {
if ($inVendor = str_starts_with($file, $root)) {
return $root;
}
}
$parent = $dir;
while (!@is_file($parent.'/composer.json')) {
if (!@file_exists($parent)) {
// open_basedir restriction in effect
break;
}
if ($parent === \dirname($parent)) {
return self::$composerRoots[$dir] = false;
}
$parent = \dirname($parent);
}
return self::$composerRoots[$dir] = $parent.\DIRECTORY_SEPARATOR;
}
}
| gpl-3.0 |
aitch0083/extjs-and-more | extjs6/ext/modern/modern/src/grid/plugin/ViewOptions.js | 17673 | /**
* The Modern Grid's ViewOptions plugin produces a menu that slides in from the right (by default)
* when you drag your finger or cursor right-to-left over the grid's column headers. The
* menu displays the column header names which represents the order of the grid's columns.
* This allows users to easily reorder the grid's columns by reordering the rows. Items may
* be dragged by grabbing the furthest left side of the row and moving the item vertically.
*
* Once the columns are ordered to your liking, you may then close the menu by tapping the
* "Done" button.
*
* @example
* var store = Ext.create('Ext.data.Store', {
* fields: ['name', 'email', 'phone'],
* data: [
* { 'name': 'Lisa', "email":"lisa@simpsons.com", "phone":"555-111-1224" },
* { 'name': 'Bart', "email":"bart@simpsons.com", "phone":"555-222-1234" },
* { 'name': 'Homer', "email":"home@simpsons.com", "phone":"555-222-1244" },
* { 'name': 'Marge', "email":"marge@simpsons.com", "phone":"555-222-1254" }
* ]
* );
*
* Ext.create('Ext.grid.Grid', {
* store: store,
* plugins: [{
* type: 'gridviewoptions'
* }],
* columns: [
* { text: 'Name', dataIndex: 'name', width: 200},
* { text: 'Email', dataIndex: 'email', width: 250},
* { text: 'Phone', dataIndex: 'phone', width: 120}
* ],
* height: 200,
* layout: 'fit',
* fullscreen: true
* );
*
* Developers may modify the menu and its contents by overriding {@link #sheet} and
* {@link #columnList} respectively.
*
*/
Ext.define('Ext.grid.plugin.ViewOptions', {
extend: 'Ext.Component',
alias: 'plugin.gridviewoptions' ,
requires: [
'Ext.field.Toggle',
'Ext.dataview.NestedList',
'Ext.plugin.SortableList'
],
config: {
/**
* @private
*/
grid: null,
/**
* The width of the menu
*/
sheetWidth: 320,
/**
* The configuration of the menu
*/
sheet: {
baseCls: Ext.baseCSSPrefix + 'grid-viewoptions',
xtype: 'sheet',
items: [{
docked: 'top',
xtype: 'titlebar',
title: 'Customize',
items: {
xtype: 'button',
text: 'Done',
ui: 'action',
align: 'right',
role: 'donebutton'
}
}],
hideOnMaskTap: false,
enter: 'right',
exit: 'right',
modal: false,
translatable: {
translationMethod: 'csstransform'
},
right: 0,
layout: 'fit',
stretchY: true
},
/**
* The column's configuration
*/
columnList: {
xtype: 'nestedlist',
title: 'Column',
listConfig: {
plugins: [{
type: 'sortablelist',
handleSelector: '.' + Ext.baseCSSPrefix + 'column-options-sortablehandle'
}],
mode: 'MULTI',
infinite: true,
itemTpl: [
'<div class="' + Ext.baseCSSPrefix + 'column-options-itemwrap<tpl if="hidden"> {hiddenCls}</tpl>',
'<tpl if="grouped"> {groupedCls}</tpl>">',
'<div class="' + Ext.baseCSSPrefix + 'column-options-sortablehandle"></div>',
'<tpl if="header">',
'<div class="' + Ext.baseCSSPrefix + 'column-options-folder"></div>',
'<tpl else>',
'<div class="' + Ext.baseCSSPrefix + 'column-options-leaf"></div>',
'</tpl>',
'<div class="' + Ext.baseCSSPrefix + 'column-options-text">{text}</div>',
'<tpl if="groupable && dataIndex">',
'<div class="' + Ext.baseCSSPrefix + 'column-options-groupindicator"></div>',
'</tpl>',
'<div class="' + Ext.baseCSSPrefix + 'column-options-visibleindicator"></div>',
'</div>'
],
triggerEvent: null,
bufferSize: 1,
minimumBufferSize: 1
},
store: {
type: 'tree',
fields: [
'id',
'text',
'dataIndex',
'header',
'hidden',
'hiddenCls',
'grouped',
'groupedCls',
'groupable'
],
root: {
text: 'Columns'
}
},
clearSelectionOnListChange: false
},
/**
* The CSS class responsible for displaying the visibility indicator.
*/
visibleIndicatorSelector: '.' + Ext.baseCSSPrefix + 'column-options-visibleindicator',
/**
* The CSS class responsible for displaying the grouping indicator.
*/
groupIndicatorSelector: '.' + Ext.baseCSSPrefix + 'column-options-groupindicator'
},
/**
* @private
*/
_hiddenColumnCls: Ext.baseCSSPrefix + 'column-options-hidden',
/**
* @private
*/
_groupedColumnCls: Ext.baseCSSPrefix + 'column-options-grouped',
/**
* Determines the menu's visibility when the grid is loaded.
*/
sheetVisible: false,
init: function(grid) {
this.setGrid(grid);
},
updateGrid: function(grid, oldGrid) {
if (oldGrid) {
oldGrid.getHeaderContainer().renderElement.un({
dragstart: 'onDragStart',
drag: 'onDrag',
dragend: 'onDragEnd',
longpress: 'onHeaderLongPress',
scope: this
});
oldGrid.getHeaderContainer().un({
columnadd: 'onColumnAdd',
columnmove: 'onColumnMove',
columnremove: 'onColumnRemove',
scope: this
});
}
if (grid) {
grid.getHeaderContainer().renderElement.on({
dragstart: 'onDragStart',
drag: 'onDrag',
dragend: 'onDragEnd',
longpress: 'onHeaderLongPress',
scope: this
});
grid.getHeaderContainer().on({
columnadd: 'onColumnAdd',
columnmove: 'onColumnMove',
columnremove: 'onColumnRemove',
columnhide: 'onColumnHide',
columnshow: 'onColumnShow',
scope: this
});
}
},
applySheet: function(sheet) {
if (sheet && !sheet.isComponent) {
sheet = Ext.factory(sheet, Ext.Sheet);
}
return sheet;
},
applyColumnList: function(list) {
if (list && !list.isComponent) {
list = Ext.factory(list, Ext.Container);
}
return list;
},
updateColumnList: function(list) {
if (list) {
list.on({
listchange: 'onListChange',
scope: this
});
list.on({
dragsort: 'onColumnReorder',
delegate: '> list',
scope: this
});
this.attachTapListeners();
}
},
updateSheet: function(sheet) {
var sheetWidth = this.getSheetWidth();
sheet.setWidth(sheetWidth);
sheet.translate(sheetWidth);
sheet.add(this.getColumnList());
},
onDoneButtonTap: function() {
this.hideViewOptions();
},
onColumnReorder: function(list, row, newIndex) {
var column = Ext.getCmp(row.getRecord().get('id')),
parent = column.getParent(),
siblings = parent.getInnerItems(),
i, ln, sibling;
for (i = 0, ln = newIndex; i < ln; i++) {
sibling = siblings[i];
if (!sibling.isHeaderGroup && sibling.getIgnore()) {
newIndex += 1;
}
}
this.isMoving = true;
parent.insert(newIndex, column);
this.isMoving = false;
},
attachTapListeners: function() {
var activeList = this.getColumnList().getActiveItem();
if (!activeList.hasAttachedTapListeners) {
activeList.onBefore({
itemtap: 'onListItemTap',
scope: this
});
activeList.hasAttachedTapListeners = true;
}
},
onListChange: function(nestedList, list) {
var store = list.getStore(),
activeNode = store.getNode(),
records = activeNode.childNodes,
ln = records.length,
i, column, record;
for (i = 0; i < ln; i++) {
record = records[i];
column = Ext.getCmp(record.getId());
record.set('hidden', column.isHidden());
}
this.attachTapListeners();
},
onListItemTap: function(list, index, row, record, e) {
var me = this,
handled = false;
if (Ext.fly(e.target).is(me.getVisibleIndicatorSelector())) {
me.onVisibleIndicatorTap(row, record, index);
handled = true;
} else if (Ext.fly(e.target).is(me.getGroupIndicatorSelector())) {
me.onGroupIndicatorTap(row, record, index);
handled = true;
}
return !handled;
},
onVisibleIndicatorTap: function(row, record) {
var hidden = !record.get('hidden'),
column = Ext.getCmp(record.get('id'));
if (hidden) {
column.hide();
record.set('hidden', true);
} else {
column.show();
record.set('hidden', false);
}
},
onGroupIndicatorTap: function(row, record) {
var me = this,
grouped = !record.get('grouped'),
store = me.getGrid().getStore(),
groupedRecord = me._groupedRecord;
if (groupedRecord) {
groupedRecord.set('grouped', false);
}
if (grouped) {
store.setGrouper({
property: record.get('dataIndex')
});
me._groupedRecord = record;
record.set('grouped', true);
} else {
store.setGrouper(null);
me._groupedRecord = null;
record.set('grouped', false);
}
},
onColumnHide: function(headerContainer, column) {
var nestedList = this.getColumnList(),
activeList = nestedList.getActiveItem(),
store = activeList.getStore(),
record = store.getById(column.getId());
if (record) {
record.set('hidden', true);
}
},
onColumnShow: function(headerContainer, column) {
var nestedList = this.getColumnList(),
activeList = nestedList.getActiveItem(),
store = activeList.getStore(),
record = store.getById(column.getId());
if (record) {
record.set('hidden', false);
}
},
onColumnAdd: function(headerContainer, column, header) {
if (column.getIgnore() || this.isMoving) {
return;
}
var me = this,
nestedList = me.getColumnList(),
store = nestedList.getStore(),
parentNode = store.getRoot(),
hiddenCls = me._hiddenColumnCls,
grid = me.getGrid(),
isGridGrouped = grid.getGrouped(),
grouper = grid.getStore().getGrouper(),
dataIndex = column.getDataIndex(),
data = {
id: column.getId(),
text: column.getText(),
groupable: isGridGrouped && column.getGroupable(),
hidden: column.isHidden(),
hiddenCls: hiddenCls,
grouped: !!(isGridGrouped && grouper && grouper.getProperty() === dataIndex),
groupedCls: me._groupedColumnCls,
dataIndex: column.getDataIndex(),
leaf: true
}, idx, headerNode;
if (header) {
headerNode = parentNode.findChild('id', header.getId());
if (!headerNode) {
idx = header.getParent().indexOf(header);
headerNode = parentNode.insertChild(idx, {
groupable: false,
header: true,
hidden: header.isHidden(),
hiddenCls: hiddenCls,
id: header.getId(),
text: header.getText()
});
}
idx = header.indexOf(column);
parentNode = headerNode;
} else {
idx = headerContainer.indexOf(column);
}
parentNode.insertChild(idx, data);
},
onColumnMove: function(headerContainer, column, header) {
this.onColumnRemove(headerContainer, column);
this.onColumnAdd(headerContainer, column, header);
},
onColumnRemove: function(headerContainer, column) {
if (column.getIgnore() || this.isMoving) {
return;
}
var root = this.getColumnList().getStore().getRoot(),
record = root.findChild('id', column.getId(), true);
if (record) {
record.parentNode.removeChild(record, true);
}
},
onDragStart: function() {
var sheetWidth = this.getSheetWidth(),
sheet = this.getSheet();
if (!this.sheetVisible) {
sheet.translate(sheetWidth);
this.startTranslate = sheetWidth;
} else {
sheet.translate(0);
this.startTranslate = 0;
}
},
onDrag: function(e) {
this.getSheet().translate(Math.max(this.startTranslate + e.deltaX, 0));
},
onDragEnd: function(e) {
var me = this;
if (e.flick.velocity.x > 0.1) {
me.hideViewOptions();
} else {
me.showViewOptions();
}
},
onHeaderLongPress: function(e) {
if (!this.sheetVisible) {
this.showViewOptions();
}
},
hideViewOptions: function() {
var sheet = this.getSheet();
this.getGrid().getHeaderContainer().setSortable(true);
sheet.translate(this.getSheetWidth(), 0, {duration: 100});
sheet.getTranslatable().on('animationend', function() {
if (sheet.getModal()) {
sheet.getModal().destroy();
sheet.setModal(null);
}
sheet.hide(null);
}, this, {single: true});
this.sheetVisible = false;
},
showViewOptions: function() {
var me = this,
sheet = me.getSheet(),
modal = null;
me.setup();
if (!me.sheetVisible) {
// Since we may have shown the header in response to a longpress we don't
// want the succeeeding "tap" to trigger column sorting, so we temporarily
// disable sort-on-tap while the ViewOptions are shown
me.getGrid().getHeaderContainer().setSortable(false);
me.updateListInfo();
sheet.show();
sheet.translate(0, 0, {duration: 100});
sheet.getTranslatable().on('animationend', function() {
sheet.setModal(true);
modal = sheet.getModal();
modal.element.onBefore({
tap: 'hideViewOptions',
dragstart: 'onDragStart',
drag: 'onDrag',
dragend: 'onDragEnd',
scope: me
});
}, me, {single: true});
me.sheetVisible = true;
}
},
privates: {
setup: function() {
var me = this,
sheet;
if (me.doneSetup) {
return;
}
me.doneSetup = true;
sheet = me.getSheet();
me.getGrid().add(sheet);
sheet.translate(me.getSheetWidth());
sheet.down('button[role=donebutton]').on({
tap: 'onDoneButtonTap',
scope: me
});
},
updateListInfo: function() {
var grid = this.getGrid(),
store = grid.getStore(),
grouper = store.getGrouper(),
grouperProp = grouper && grouper.getProperty(),
headerContainer = grid.getHeaderContainer();
this.getColumnList().getStore().getRoot().cascadeBy(function(node) {
var dataIndex = node.get('dataIndex');
node.set('grouped', dataIndex && dataIndex === grouperProp);
});
}
}
}); | gpl-3.0 |
arrmo/librenms | app/Http/Controllers/Select/MuninPluginController.php | 1774 | <?php
/**
* MuninPluginController.php
*
* -Description-
*
* 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, see <https://www.gnu.org/licenses/>.
*
* @link https://www.librenms.org
*
* @copyright 2018 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace App\Http\Controllers\Select;
use App\Models\MuninPlugin;
class MuninPluginController extends SelectController
{
/**
* Defines the base query for this resource
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
protected function baseQuery($request)
{
return MuninPlugin::hasAccess($request->user())
->with(['device' => function ($query) {
$query->select('device_id', 'hostname', 'sysName');
}])
->select('mplug_id', 'mplug_type', 'device_id');
}
/**
* @param MuninPlugin $munin_plugin
*/
public function formatItem($munin_plugin)
{
return [
'id' => $munin_plugin->mplug_id,
'text' => $munin_plugin->device->shortDisplayName() . ' - ' . $munin_plugin->mplug_type,
];
}
}
| gpl-3.0 |
writeameer/moodle | blog/lib.php | 43600 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Core global functions for Blog.
*
* @package moodlecore
* @subpackage blog
* @copyright 2009 Nicolas Connault
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Library of functions and constants for blog
*/
require_once($CFG->dirroot .'/blog/rsslib.php');
require_once($CFG->dirroot.'/tag/lib.php');
/**
* User can edit a blog entry if this is their own blog entry and they have
* the capability moodle/blog:create, or if they have the capability
* moodle/blog:manageentries.
*
* This also applies to deleting of entries.
*/
function blog_user_can_edit_entry($blogentry) {
global $USER;
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (has_capability('moodle/blog:manageentries', $sitecontext)) {
return true; // can edit any blog entry
}
if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
return true; // can edit own when having blog:create capability
}
return false;
}
/**
* Checks to see if a user can view the blogs of another user.
* Only blog level is checked here, the capabilities are enforced
* in blog/index.php
*/
function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
global $CFG, $USER, $DB;
if (empty($CFG->bloglevel)) {
return false; // blog system disabled
}
if (isloggedin() && $USER->id == $targetuserid) {
return true; // can view own entries in any case
}
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (has_capability('moodle/blog:manageentries', $sitecontext)) {
return true; // can manage all entries
}
// coming for 1 entry, make sure it's not a draft
if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
return false; // can not view draft of others
}
// coming for 0 entry, make sure user is logged in, if not a public blog
if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
return false;
}
switch ($CFG->bloglevel) {
case BLOG_GLOBAL_LEVEL:
return true;
break;
case BLOG_SITE_LEVEL:
if (isloggedin()) { // not logged in viewers forbidden
return true;
}
return false;
break;
case BLOG_USER_LEVEL:
default:
$personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
return has_capability('moodle/user:readuserblogs', $personalcontext);
break;
}
}
/**
* remove all associations for the blog entries of a particular user
* @param int userid - id of user whose blog associations will be deleted
*/
function blog_remove_associations_for_user($userid) {
global $DB;
throw new coding_exception('function blog_remove_associations_for_user() is not finished');
/*
$blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
foreach ($blogentries as $entry) {
if (blog_user_can_edit_entry($entry)) {
blog_remove_associations_for_entry($entry->id);
}
}
*/
}
/**
* remove all associations for the blog entries of a particular course
* @param int courseid - id of user whose blog associations will be deleted
*/
function blog_remove_associations_for_course($courseid) {
global $DB;
$context = get_context_instance(CONTEXT_COURSE, $courseid);
$DB->delete_records('blog_association', array('contextid' => $context->id));
}
/**
* Given a record in the {blog_external} table, checks the blog's URL
* for new entries not yet copied into Moodle.
* Also attempts to identify and remove deleted blog entries
*
* @param object $externalblog
* @return boolean False if the Feed is invalid
*/
function blog_sync_external_entries($externalblog) {
global $CFG, $DB;
require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
$rssfile = new moodle_simplepie_file($externalblog->url);
$filetest = new SimplePie_Locator($rssfile);
if (!$filetest->is_feed($rssfile)) {
$externalblog->failedlastsync = 1;
$DB->update_record('blog_external', $externalblog);
return false;
} else if (!empty($externalblog->failedlastsync)) {
$externalblog->failedlastsync = 0;
$DB->update_record('blog_external', $externalblog);
}
$rss = new moodle_simplepie($externalblog->url);
if (empty($rss->data)) {
return null;
}
//used to identify blog posts that have been deleted from the source feed
$oldesttimestamp = null;
$uniquehashes = array();
foreach ($rss->get_items() as $entry) {
// If filtertags are defined, use them to filter the entries by RSS category
if (!empty($externalblog->filtertags)) {
$containsfiltertag = false;
$categories = $entry->get_categories();
$filtertags = explode(',', $externalblog->filtertags);
$filtertags = array_map('trim', $filtertags);
$filtertags = array_map('strtolower', $filtertags);
foreach ($categories as $category) {
if (in_array(trim(strtolower($category->term)), $filtertags)) {
$containsfiltertag = true;
}
}
if (!$containsfiltertag) {
continue;
}
}
$uniquehashes[] = $entry->get_permalink();
$newentry = new stdClass();
$newentry->userid = $externalblog->userid;
$newentry->module = 'blog_external';
$newentry->content = $externalblog->id;
$newentry->uniquehash = $entry->get_permalink();
$newentry->publishstate = 'site';
$newentry->format = FORMAT_HTML;
// Clean subject of html, just in case
$newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
// Observe 128 max chars in DB
// TODO: +1 to raise this to 255
if (textlib::strlen($newentry->subject) > 128) {
$newentry->subject = textlib::substr($newentry->subject, 0, 125) . '...';
}
$newentry->summary = $entry->get_description();
//used to decide whether to insert or update
//uses enty permalink plus creation date if available
$existingpostconditions = array('uniquehash' => $entry->get_permalink());
//our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
$entrydate = $entry->get_date('U');
if (!empty($entrydate)) {
$existingpostconditions['created'] = $entrydate;
}
//the post ID or false if post not found in DB
$postid = $DB->get_field('post', 'id', $existingpostconditions);
$timestamp = null;
if (empty($entrydate)) {
$timestamp = time();
} else {
$timestamp = $entrydate;
}
//only set created if its a new post so we retain the original creation timestamp if the post is edited
if ($postid === false) {
$newentry->created = $timestamp;
}
$newentry->lastmodified = $timestamp;
if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
//found an older post
$oldesttimestamp = $timestamp;
}
if (textlib::strlen($newentry->uniquehash) > 255) {
// The URL for this item is too long for the field. Rather than add
// the entry without the link we will skip straight over it.
// RSS spec says recommended length 500, we use 255.
debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
continue;
}
if ($postid === false) {
$id = $DB->insert_record('post', $newentry);
// Set tags
if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
tag_set('post', $id, $tags);
}
} else {
$newentry->id = $postid;
$DB->update_record('post', $newentry);
}
}
// Look at the posts we have in the database to check if any of them have been deleted from the feed.
// Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
// may just not be returned anymore. We can't tell the difference so we leave older posts alone.
$sql = "SELECT id, uniquehash
FROM {post}
WHERE module = 'blog_external'
AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
AND created > :ts";
$dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
$todelete = array();
foreach($dbposts as $dbpost) {
if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
$todelete[] = $dbpost->id;
}
}
$DB->delete_records_list('post', 'id', $todelete);
$DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
}
/**
* Given an external blog object, deletes all related blog entries from the post table.
* NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
* @param object $externablog
*/
function blog_delete_external_entries($externalblog) {
global $DB;
require_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM));
$DB->delete_records_select('post',
"module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
array($externalblog->id));
}
/**
* Returns a URL based on the context of the current page.
* This URL points to blog/index.php and includes filter parameters appropriate for the current page.
*
* @param stdclass $context
* @return string
*/
function blog_get_context_url($context=null) {
global $CFG;
$viewblogentriesurl = new moodle_url('/blog/index.php');
if (empty($context)) {
global $PAGE;
$context = $PAGE->context;
}
// Change contextlevel to SYSTEM if viewing the site course
if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
$context = context_system::instance();
}
$filterparam = '';
$strlevel = '';
switch ($context->contextlevel) {
case CONTEXT_SYSTEM:
case CONTEXT_BLOCK:
case CONTEXT_COURSECAT:
break;
case CONTEXT_COURSE:
$filterparam = 'courseid';
$strlevel = get_string('course');
break;
case CONTEXT_MODULE:
$filterparam = 'modid';
$strlevel = print_context_name($context);
break;
case CONTEXT_USER:
$filterparam = 'userid';
$strlevel = get_string('user');
break;
}
if (!empty($filterparam)) {
$viewblogentriesurl->param($filterparam, $context->instanceid);
}
return $viewblogentriesurl;
}
/**
* This function checks that blogs are enabled, and that the user can see blogs at all
* @return bool
*/
function blog_is_enabled_for_user() {
global $CFG;
//return (!empty($CFG->bloglevel) && $CFG->bloglevel <= BLOG_GLOBAL_LEVEL && isloggedin() && !isguestuser());
return (!empty($CFG->bloglevel) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
}
/**
* This function gets all of the options available for the current user in respect
* to blogs.
*
* It loads the following if applicable:
* - Module options {@see blog_get_options_for_module}
* - Course options {@see blog_get_options_for_course}
* - User specific options {@see blog_get_options_for_user}
* - General options (BLOG_LEVEL_GLOBAL)
*
* @param moodle_page $page The page to load for (normally $PAGE)
* @param stdClass $userid Load for a specific user
* @return array An array of options organised by type.
*/
function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
global $CFG, $DB, $USER;
$options = array();
// If blogs are enabled and the user is logged in and not a guest
if (blog_is_enabled_for_user()) {
// If the context is the user then assume we want to load for the users context
if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
$userid = $page->context->instanceid;
}
// Check the userid var
if (!is_null($userid) && $userid!==$USER->id) {
// Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
$user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
} else {
$user = null;
}
if ($CFG->useblogassociations && $page->cm !== null) {
// Load for the module associated with the page
$options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
} else if ($CFG->useblogassociations && $page->course->id != SITEID) {
// Load the options for the course associated with the page
$options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
}
// Get the options for the user
if ($user !== null and !isguestuser($user)) {
// Load for the requested user
$options[CONTEXT_USER+1] = blog_get_options_for_user($user);
}
// Load for the current user
if (isloggedin() and !isguestuser()) {
$options[CONTEXT_USER] = blog_get_options_for_user();
}
}
// If blog level is global then display a link to view all site entries
if (!empty($CFG->bloglevel) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
$options[CONTEXT_SYSTEM] = array('viewsite' => array(
'string' => get_string('viewsiteentries', 'blog'),
'link' => new moodle_url('/blog/index.php')
));
}
// Return the options
return $options;
}
/**
* Get all of the blog options that relate to the passed user.
*
* If no user is passed the current user is assumed.
*
* @staticvar array $useroptions Cache so we don't have to regenerate multiple times
* @param stdClass $user
* @return array The array of options for the requested user
*/
function blog_get_options_for_user(stdClass $user=null) {
global $CFG, $USER;
// Cache
static $useroptions = array();
$options = array();
// Blogs must be enabled and the user must be logged in
if (!blog_is_enabled_for_user()) {
return $options;
}
// Sort out the user var
if ($user === null || $user->id == $USER->id) {
$user = $USER;
$iscurrentuser = true;
} else {
$iscurrentuser = false;
}
// If we've already generated serve from the cache
if (array_key_exists($user->id, $useroptions)) {
return $useroptions[$user->id];
}
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
$canview = has_capability('moodle/blog:view', $sitecontext);
if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
// Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
$options['userentries'] = array(
'string' => get_string('viewuserentries', 'blog', fullname($user)),
'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
);
} else {
// It's the current user
if ($canview) {
// We can view our own blogs .... BIG surprise
$options['view'] = array(
'string' => get_string('viewallmyentries', 'blog'),
'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
);
}
if (has_capability('moodle/blog:create', $sitecontext)) {
// We can add to our own blog
$options['add'] = array(
'string' => get_string('addnewentry', 'blog'),
'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
);
}
}
if ($canview && $CFG->enablerssfeeds) {
$options['rss'] = array(
'string' => get_string('rssfeed', 'blog'),
'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
);
}
// Cache the options
$useroptions[$user->id] = $options;
// Return the options
return $options;
}
/**
* Get the blog options that relate to the given course for the given user.
*
* @staticvar array $courseoptions A cache so we can save regenerating multiple times
* @param stdClass $course The course to load options for
* @param stdClass $user The user to load options for null == current user
* @return array The array of options
*/
function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
global $CFG, $USER;
// Cache
static $courseoptions = array();
$options = array();
// User must be logged in and blogs must be enabled
if (!blog_is_enabled_for_user()) {
return $options;
}
// Check that the user can associate with the course
$sitecontext = context_system::instance();
$coursecontext = context_course::instance($course->id);
if (!has_capability('moodle/blog:associatecourse', $coursecontext)) {
return $options;
}
// Generate the cache key
$key = $course->id.':';
if (!empty($user)) {
$key .= $user->id;
} else {
$key .= $USER->id;
}
// Serve from the cache if we've already generated for this course
if (array_key_exists($key, $courseoptions)) {
return $courseoptions[$key];
}
$canparticipate = (is_enrolled($coursecontext) or is_viewing($coursecontext));
if (has_capability('moodle/blog:view', $coursecontext)) {
// We can view!
if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
// View entries about this course
$options['courseview'] = array(
'string' => get_string('viewcourseblogs', 'blog'),
'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
);
}
// View MY entries about this course
$options['courseviewmine'] = array(
'string' => get_string('viewmyentriesaboutcourse', 'blog'),
'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
);
if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
// View the provided users entries about this course
$options['courseviewuser'] = array(
'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
);
}
}
if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
// We can blog about this course
$options['courseadd'] = array(
'string' => get_string('blogaboutthiscourse', 'blog'),
'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
);
}
// Cache the options for this course
$courseoptions[$key] = $options;
// Return the options
return $options;
}
/**
* Get the blog options relating to the given module for the given user
*
* @staticvar array $moduleoptions Cache
* @param stdClass|cm_info $module The module to get options for
* @param stdClass $user The user to get options for null == currentuser
* @return array
*/
function blog_get_options_for_module($module, $user=null) {
global $CFG, $USER;
// Cache
static $moduleoptions = array();
$options = array();
// User must be logged in, blogs must be enabled
if (!blog_is_enabled_for_user()) {
return $options;
}
// Check the user can associate with the module
$modcontext = context_module::instance($module->id);
$sitecontext = context_system::instance();
if (!has_capability('moodle/blog:associatemodule', $modcontext)) {
return $options;
}
// Generate the cache key
$key = $module->id.':';
if (!empty($user)) {
$key .= $user->id;
} else {
$key .= $USER->id;
}
if (array_key_exists($key, $moduleoptions)) {
// Serve from the cache so we don't have to regenerate
return $moduleoptions[$module->id];
}
$canparticipate = (is_enrolled($modcontext) or is_viewing($modcontext));
if (has_capability('moodle/blog:view', $modcontext)) {
// Save correct module name for later usage.
$modulename = get_string('modulename', $module->modname);
// We can view!
if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
// View all entries about this module
$a = new stdClass;
$a->type = $modulename;
$options['moduleview'] = array(
'string' => get_string('viewallmodentries', 'blog', $a),
'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
);
}
// View MY entries about this module
$options['moduleviewmine'] = array(
'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
);
if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
// View the given users entries about this module
$a = new stdClass;
$a->mod = $modulename;
$a->user = fullname($user);
$options['moduleviewuser'] = array(
'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
);
}
}
if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
// The user can blog about this module
$options['moduleadd'] = array(
'string' => get_string('blogaboutthismodule', 'blog', $modulename),
'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
);
}
// Cache the options
$moduleoptions[$key] = $options;
// Return the options
return $options;
}
/**
* This function encapsulates all the logic behind the complex
* navigation, titles and headings of the blog listing page, depending
* on URL params. It looks at URL params and at the current context level.
* It builds and returns an array containing:
*
* 1. heading: The heading displayed above the blog entries
* 2. stradd: The text to be used as the "Add entry" link
* 3. strview: The text to be used as the "View entries" link
* 4. url: The moodle_url object used as the base for add and view links
* 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
*
* All other variables are set directly in $PAGE
*
* It uses the current URL to build these variables.
* A number of mutually exclusive use cases are used to structure this function.
*
* @return array
*/
function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
global $CFG, $PAGE, $DB, $USER;
$id = optional_param('id', null, PARAM_INT);
$tag = optional_param('tag', null, PARAM_NOTAGS);
$tagid = optional_param('tagid', $tagid, PARAM_INT);
$userid = optional_param('userid', $userid, PARAM_INT);
$modid = optional_param('modid', null, PARAM_INT);
$entryid = optional_param('entryid', null, PARAM_INT);
$groupid = optional_param('groupid', $groupid, PARAM_INT);
$courseid = optional_param('courseid', $courseid, PARAM_INT);
$search = optional_param('search', null, PARAM_RAW);
$action = optional_param('action', null, PARAM_ALPHA);
$confirm = optional_param('confirm', false, PARAM_BOOL);
// Ignore userid when action == add
if ($action == 'add' && $userid) {
unset($userid);
$PAGE->url->remove_params(array('userid'));
} else if ($action == 'add' && $entryid) {
unset($entryid);
$PAGE->url->remove_params(array('entryid'));
}
$headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
$blogurl = new moodle_url('/blog/index.php');
// If the title is not yet set, it's likely that the context isn't set either, so skip this part
$pagetitle = $PAGE->title;
if (!empty($pagetitle)) {
$contexturl = blog_get_context_url();
// Look at the context URL, it may have additional params that are not in the current URL
if (!$blogurl->compare($contexturl)) {
$blogurl = $contexturl;
if (empty($courseid)) {
$courseid = $blogurl->param('courseid');
}
if (empty($modid)) {
$modid = $blogurl->param('modid');
}
}
}
$headers['stradd'] = get_string('addnewentry', 'blog');
$headers['strview'] = null;
$site = $DB->get_record('course', array('id' => SITEID));
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
// Common Lang strings
$strparticipants = get_string("participants");
$strblogentries = get_string("blogentries", 'blog');
// Prepare record objects as needed
if (!empty($courseid)) {
$headers['filters']['course'] = $courseid;
$course = $DB->get_record('course', array('id' => $courseid));
}
if (!empty($userid)) {
$headers['filters']['user'] = $userid;
$user = $DB->get_record('user', array('id' => $userid));
}
if (!empty($groupid)) { // groupid always overrides courseid
$headers['filters']['group'] = $groupid;
$group = $DB->get_record('groups', array('id' => $groupid));
$course = $DB->get_record('course', array('id' => $group->courseid));
}
$PAGE->set_pagelayout('standard');
// modid always overrides courseid, so the $course object may be reset here
if (!empty($modid) && $CFG->useblogassociations) {
$headers['filters']['module'] = $modid;
// A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
$courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
$course = $DB->get_record('course', array('id' => $courseid));
$cm = $DB->get_record('course_modules', array('id' => $modid));
$cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
$cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
$a = new stdClass();
$a->type = get_string('modulename', $cm->modname);
$PAGE->set_cm($cm, $course);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewallmodentries', 'blog', $a);
}
// Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
// Note: if action is set to 'add' or 'edit', we do this at the end
if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
$shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$PAGE->navbar->add($strblogentries, $blogurl);
$PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
$PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
$headers['heading'] = get_string('siteblog', 'blog', $shortname);
// $headers['strview'] = get_string('viewsiteentries', 'blog');
}
// Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
if (!empty($entryid)) {
$headers['filters']['entry'] = $entryid;
$sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
$user = $DB->get_record_sql($sql, array($entryid));
$entry = $DB->get_record('post', array('id' => $entryid));
$blogurl->param('userid', $user->id);
if (!empty($course)) {
$mycourseid = $course->id;
$blogurl->param('courseid', $mycourseid);
} else {
$mycourseid = $site->id;
}
$shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$PAGE->navbar->add($strblogentries, $blogurl);
$blogurl->remove_params('userid');
$PAGE->navbar->add($entry->subject, $blogurl);
$PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
$PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
$headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
// We ignore tag and search params
if (empty($action) || !$CFG->useblogassociations) {
$headers['url'] = $blogurl;
return $headers;
}
}
// Case 3: A user's blog entries
if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
$shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$blogurl->param('userid', $userid);
$PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
$PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
$headers['heading'] = get_string('userblog', 'blog', fullname($user));
$headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
} else
// Case 4: No blog associations, no userid
if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
$shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
$PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
$headers['heading'] = get_string('siteblog', 'blog', $shortname);
} else
// Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
if (!empty($userid) && !empty($modid) && empty($entryid)) {
$shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$blogurl->param('userid', $userid);
$blogurl->param('modid', $modid);
// Course module navigation is handled by build_navigation as the second param
$headers['cm'] = $cm;
$PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
$PAGE->navbar->add($strblogentries, $blogurl);
$PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
$PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
$a = new stdClass();
$a->user = fullname($user);
$a->mod = $cm->name;
$a->type = get_string('modulename', $cm->modname);
$headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewallmodentries', 'blog', $a);
} else
// Case 6: Blog entries associated with a course by a specific user
if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
$siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$blogurl->param('userid', $userid);
$blogurl->param('courseid', $courseid);
$PAGE->navbar->add($strblogentries, $blogurl);
$PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
$PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
$a = new stdClass();
$a->user = fullname($user);
$a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$a->type = get_string('course');
$headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewblogentries', 'blog', $a);
// Remove the userid from the URL to inform the blog_menu block correctly
$blogurl->remove_params(array('userid'));
} else
// Case 7: Blog entries by members of a group, associated with that group's course
if (!empty($groupid) && empty($modid) && empty($entryid)) {
$siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$blogurl->param('courseid', $course->id);
$PAGE->navbar->add($strblogentries, $blogurl);
$blogurl->remove_params(array('courseid'));
$blogurl->param('groupid', $groupid);
$PAGE->navbar->add($group->name, $blogurl);
$PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
$PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
$a = new stdClass();
$a->group = $group->name;
$a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$a->type = get_string('course');
$headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewblogentries', 'blog', $a);
} else
// Case 8: Blog entries by members of a group, associated with an activity in that course
if (!empty($groupid) && !empty($modid) && empty($entryid)) {
$siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$headers['cm'] = $cm;
$blogurl->param('modid', $modid);
$PAGE->navbar->add($strblogentries, $blogurl);
$blogurl->param('groupid', $groupid);
$PAGE->navbar->add($group->name, $blogurl);
$PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
$PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
$a = new stdClass();
$a->group = $group->name;
$a->mod = $cm->name;
$a->type = get_string('modulename', $cm->modname);
$headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewallmodentries', 'blog', $a);
} else
// Case 9: All blog entries associated with an activity
if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
$siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$PAGE->set_cm($cm, $course);
$blogurl->param('modid', $modid);
$PAGE->navbar->add($strblogentries, $blogurl);
$PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
$PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
$headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
$a = new stdClass();
$a->type = get_string('modulename', $cm->modname);
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewallmodentries', 'blog', $a);
} else
// Case 10: All blog entries associated with a course
if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
$siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
$courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
$blogurl->param('courseid', $courseid);
$PAGE->navbar->add($strblogentries, $blogurl);
$PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
$PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
$a = new stdClass();
$a->type = get_string('course');
$headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
$headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
$headers['strview'] = get_string('viewblogentries', 'blog', $a);
$blogurl->remove_params(array('userid'));
}
if (!in_array($action, array('edit', 'add'))) {
// Append Tag info
if (!empty($tagid)) {
$headers['filters']['tag'] = $tagid;
$blogurl->param('tagid', $tagid);
$tagrec = $DB->get_record('tag', array('id'=>$tagid));
$PAGE->navbar->add($tagrec->name, $blogurl);
} elseif (!empty($tag)) {
$blogurl->param('tag', $tag);
$PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
}
// Append Search info
if (!empty($search)) {
$headers['filters']['search'] = $search;
$blogurl->param('search', $search);
$PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
}
}
// Append edit mode info
if (!empty($action) && $action == 'add') {
} else if (!empty($action) && $action == 'edit') {
$PAGE->navbar->add(get_string('editentry', 'blog'));
}
if (empty($headers['url'])) {
$headers['url'] = $blogurl;
}
return $headers;
}
/**
* Shortcut function for getting a count of blog entries associated with a course or a module
* @param int $courseid The ID of the course
* @param int $cmid The ID of the course_modules
* @return string The number of associated entries
*/
function blog_get_associated_count($courseid, $cmid=null) {
global $DB;
$context = get_context_instance(CONTEXT_COURSE, $courseid);
if ($cmid) {
$context = get_context_instance(CONTEXT_MODULE, $cmid);
}
return $DB->count_records('blog_association', array('contextid' => $context->id));
}
/**
* Running addtional permission check on plugin, for example, plugins
* may have switch to turn on/off comments option, this callback will
* affect UI display, not like pluginname_comment_validate only throw
* exceptions.
* Capability check has been done in comment->check_permissions(), we
* don't need to do it again here.
*
* @package core_blog
* @category comment
*
* @param stdClass $comment_param {
* context => context the context object
* courseid => int course id
* cm => stdClass course module object
* commentarea => string comment area
* itemid => int itemid
* }
* @return array
*/
function blog_comment_permissions($comment_param) {
return array('post'=>true, 'view'=>true);
}
/**
* Validate comment parameter before perform other comments actions
*
* @package core_blog
* @category comment
*
* @param stdClass $comment {
* context => context the context object
* courseid => int course id
* cm => stdClass course module object
* commentarea => string comment area
* itemid => int itemid
* }
* @return boolean
*/
function blog_comment_validate($comment_param) {
global $DB;
// validate comment itemid
if (!$entry = $DB->get_record('post', array('id'=>$comment_param->itemid))) {
throw new comment_exception('invalidcommentitemid');
}
// validate comment area
if ($comment_param->commentarea != 'format_blog') {
throw new comment_exception('invalidcommentarea');
}
// validation for comment deletion
if (!empty($comment_param->commentid)) {
if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
if ($record->commentarea != 'format_blog') {
throw new comment_exception('invalidcommentarea');
}
if ($record->contextid != $comment_param->context->id) {
throw new comment_exception('invalidcontext');
}
if ($record->itemid != $comment_param->itemid) {
throw new comment_exception('invalidcommentitemid');
}
} else {
throw new comment_exception('invalidcommentid');
}
}
return true;
}
/**
* Return a list of page types
* @param string $pagetype current page type
* @param stdClass $parentcontext Block's parent context
* @param stdClass $currentcontext Current context of block
*/
function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
return array(
'*'=>get_string('page-x', 'pagetype'),
'blog-*'=>get_string('page-blog-x', 'blog'),
'blog-index'=>get_string('page-blog-index', 'blog'),
'blog-edit'=>get_string('page-blog-edit', 'blog')
);
}
| gpl-3.0 |