code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// // Copyright (c) 2018, Joyent, Inc. All rights reserved. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // package network import ( "context" "encoding/json" "net/http" "path" "strconv" "github.com/joyent/triton-go/client" "github.com/pkg/errors" ) type FabricsClient struct { client *client.Client } type FabricVLAN struct { Name string `json:"name"` ID int `json:"vlan_id"` Description string `json:"description"` } type ListVLANsInput struct{} func (c *FabricsClient) ListVLANs(ctx context.Context, _ *ListVLANsInput) ([]*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans") reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to list VLANs") } var result []*FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode list VLANs response") } return result, nil } type CreateVLANInput struct { Name string `json:"name"` ID int `json:"vlan_id"` Description string `json:"description,omitempty"` } func (c *FabricsClient) CreateVLAN(ctx context.Context, input *CreateVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans") reqInputs := client.RequestInput{ Method: http.MethodPost, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to create VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode create VLAN response") } return result, nil } type UpdateVLANInput struct { ID int `json:"-"` Name string `json:"name"` Description string `json:"description"` } func (c *FabricsClient) UpdateVLAN(ctx context.Context, input *UpdateVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodPut, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to update VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode update VLAN response") } return result, nil } type GetVLANInput struct { ID int `json:"-"` } func (c *FabricsClient) GetVLAN(ctx context.Context, input *GetVLANInput) (*FabricVLAN, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to get VLAN") } var result *FabricVLAN decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode get VLAN response") } return result, nil } type DeleteVLANInput struct { ID int `json:"-"` } func (c *FabricsClient) DeleteVLAN(ctx context.Context, input *DeleteVLANInput) error { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.ID)) reqInputs := client.RequestInput{ Method: http.MethodDelete, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return errors.Wrap(err, "unable to delete VLAN") } return nil } type ListFabricsInput struct { FabricVLANID int `json:"-"` } func (c *FabricsClient) List(ctx context.Context, input *ListFabricsInput) ([]*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks") reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to list fabrics") } var result []*Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode list fabrics response") } return result, nil } type CreateFabricInput struct { FabricVLANID int `json:"-"` Name string `json:"name"` Description string `json:"description,omitempty"` Subnet string `json:"subnet"` ProvisionStartIP string `json:"provision_start_ip"` ProvisionEndIP string `json:"provision_end_ip"` Gateway string `json:"gateway,omitempty"` Resolvers []string `json:"resolvers,omitempty"` Routes map[string]string `json:"routes,omitempty"` InternetNAT bool `json:"internet_nat"` } func (c *FabricsClient) Create(ctx context.Context, input *CreateFabricInput) (*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks") reqInputs := client.RequestInput{ Method: http.MethodPost, Path: fullPath, Body: input, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to create fabric") } var result *Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode create fabric response") } return result, nil } type GetFabricInput struct { FabricVLANID int `json:"-"` NetworkID string `json:"-"` } func (c *FabricsClient) Get(ctx context.Context, input *GetFabricInput) (*Network, error) { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID) reqInputs := client.RequestInput{ Method: http.MethodGet, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return nil, errors.Wrap(err, "unable to get fabric") } var result *Network decoder := json.NewDecoder(respReader) if err = decoder.Decode(&result); err != nil { return nil, errors.Wrap(err, "unable to decode get fabric response") } return result, nil } type DeleteFabricInput struct { FabricVLANID int `json:"-"` NetworkID string `json:"-"` } func (c *FabricsClient) Delete(ctx context.Context, input *DeleteFabricInput) error { fullPath := path.Join("/", c.client.AccountName, "fabrics", "default", "vlans", strconv.Itoa(input.FabricVLANID), "networks", input.NetworkID) reqInputs := client.RequestInput{ Method: http.MethodDelete, Path: fullPath, } respReader, err := c.client.ExecuteRequest(ctx, reqInputs) if respReader != nil { defer respReader.Close() } if err != nil { return errors.Wrap(err, "unable to delete fabric") } return nil }
dave2/packer
vendor/github.com/joyent/triton-go/network/fabrics.go
GO
mpl-2.0
7,828
class Report attr_reader :group, :since attr_reader :questions, :answers, :users, :badges, :votes def initialize(group, since = Time.now.yesterday) @group = group @since = since @questions = group.questions.where(:created_at => {:$gt => since}).count @answers = group.answers.where(:created_at => {:$gt => since}).count @users = group.memberships.count @badges = group.badges.where(:created_at => {:$gt => since}).count end end
10xEngineer/shapado
app/models/report.rb
Ruby
agpl-3.0
463
from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp.addons.point_of_sale.point_of_sale import pos_session class pos_session_opening(osv.osv_memory): _name = 'pos.session.opening' _columns = { 'pos_config_id' : fields.many2one('pos.config', string='Point of Sale', required=True), 'pos_session_id' : fields.many2one('pos.session', string='PoS Session'), 'pos_state' : fields.related('pos_session_id', 'state', type='selection', selection=pos_session.POS_SESSION_STATE, string='Session Status', readonly=True), 'pos_state_str' : fields.char('Status', readonly=True), 'show_config' : fields.boolean('Show Config', readonly=True), 'pos_session_name' : fields.related('pos_session_id', 'name', string="Session Name", type='char', size=64, readonly=True), 'pos_session_username' : fields.related('pos_session_id', 'user_id', 'name', type='char', size=64, readonly=True) } def open_ui(self, cr, uid, ids, context=None): data = self.browse(cr, uid, ids[0], context=context) context = dict(context or {}) context['active_id'] = data.pos_session_id.id return { 'type' : 'ir.actions.act_url', 'url': '/pos/web/', 'target': 'self', } def open_existing_session_cb_close(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context=context) wizard.pos_session_id.signal_workflow('cashbox_control') return self.open_session_cb(cr, uid, ids, context) def open_session_cb(self, cr, uid, ids, context=None): assert len(ids) == 1, "you can open only one session at a time" proxy = self.pool.get('pos.session') wizard = self.browse(cr, uid, ids[0], context=context) if not wizard.pos_session_id: values = { 'user_id' : uid, 'config_id' : wizard.pos_config_id.id, } session_id = proxy.create(cr, uid, values, context=context) s = proxy.browse(cr, uid, session_id, context=context) if s.state=='opened': return self.open_ui(cr, uid, ids, context=context) return self._open_session(session_id) return self._open_session(wizard.pos_session_id.id) def open_existing_session_cb(self, cr, uid, ids, context=None): assert len(ids) == 1 wizard = self.browse(cr, uid, ids[0], context=context) return self._open_session(wizard.pos_session_id.id) def _open_session(self, session_id): return { 'name': _('Session'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'pos.session', 'res_id': session_id, 'view_id': False, 'type': 'ir.actions.act_window', } def on_change_config(self, cr, uid, ids, config_id, context=None): result = { 'pos_session_id': False, 'pos_state': False, 'pos_state_str' : '', 'pos_session_username' : False, 'pos_session_name' : False, } if not config_id: return {'value' : result} proxy = self.pool.get('pos.session') session_ids = proxy.search(cr, uid, [ ('state', '!=', 'closed'), ('config_id', '=', config_id), ('user_id', '=', uid), ], context=context) if session_ids: session = proxy.browse(cr, uid, session_ids[0], context=context) result['pos_state'] = str(session.state) result['pos_state_str'] = dict(pos_session.POS_SESSION_STATE).get(session.state, '') result['pos_session_id'] = session.id result['pos_session_name'] = session.name result['pos_session_username'] = session.user_id.name return {'value' : result} def default_get(self, cr, uid, fieldnames, context=None): so = self.pool.get('pos.session') session_ids = so.search(cr, uid, [('state','<>','closed'), ('user_id','=',uid)], context=context) if session_ids: result = so.browse(cr, uid, session_ids[0], context=context).config_id.id else: current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context) result = current_user.pos_config and current_user.pos_config.id or False if not result: r = self.pool.get('pos.config').search(cr, uid, [], context=context) result = r and r[0] or False count = self.pool.get('pos.config').search_count(cr, uid, [('state', '=', 'active')], context=context) show_config = bool(count > 1) return { 'pos_config_id' : result, 'show_config' : show_config, }
addition-it-solutions/project-all
addons/point_of_sale/wizard/pos_session_opening.py
Python
agpl-3.0
5,032
// Copyright 2011 Software Freedom Conservancy // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "command.h" #include "command_types.h" #include "logging.h" namespace webdriver { Command::Command() : command_type_(webdriver::CommandType::NoCommand) { } Command::~Command() { } void Command::Populate(const std::string& json_command) { LOG(TRACE) << "Entering Command::Populate"; // Clear the existing maps. this->command_parameters_.clear(); this->locator_parameters_.clear(); LOG(DEBUG) << "Raw JSON command: " << json_command; Json::Value root; Json::Reader reader; bool successful_parse = reader.parse(json_command, root); if (!successful_parse) { // report to the user the failure and their locations in the document. LOG(WARN) << "Failed to parse configuration due " << reader.getFormatedErrorMessages() << std::endl << "JSON command: '" << json_command << "'"; } this->command_type_ = root.get("command", webdriver::CommandType::NoCommand).asString(); if (this->command_type_ != webdriver::CommandType::NoCommand) { Json::Value locator_parameter_object = root["locator"]; Json::Value::iterator it = locator_parameter_object.begin(); Json::Value::iterator end = locator_parameter_object.end(); for (; it != end; ++it) { std::string key = it.key().asString(); std::string value = locator_parameter_object[key].asString(); this->locator_parameters_[key] = value; } Json::Value command_parameter_object = root["parameters"]; it = command_parameter_object.begin(); end = command_parameter_object.end(); for (; it != end; ++it) { std::string key = it.key().asString(); Json::Value value = command_parameter_object[key]; this->command_parameters_[key] = value; } } else { LOG(DEBUG) << "Command type is zero, no 'command' attribute in JSON object"; } } } // namespace webdriver
jknguyen/josephknguyen-selenium
cpp/webdriver-server/command.cc
C++
apache-2.0
2,447
/* Copyright 2015 The Kubernetes 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 e2e import ( "fmt" "strings" "time" "k8s.io/kubernetes/pkg/api" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/util" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/test/e2e/framework" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) const ( // Interval to framework.Poll /runningpods on a node pollInterval = 1 * time.Second // Interval to framework.Poll /stats/container on a node containerStatsPollingInterval = 5 * time.Second // Maximum number of nodes that we constraint to maxNodesToCheck = 10 ) // getPodMatches returns a set of pod names on the given node that matches the // podNamePrefix and namespace. func getPodMatches(c *client.Client, nodeName string, podNamePrefix string, namespace string) sets.String { matches := sets.NewString() framework.Logf("Checking pods on node %v via /runningpods endpoint", nodeName) runningPods, err := framework.GetKubeletPods(c, nodeName) if err != nil { framework.Logf("Error checking running pods on %v: %v", nodeName, err) return matches } for _, pod := range runningPods.Items { if pod.Namespace == namespace && strings.HasPrefix(pod.Name, podNamePrefix) { matches.Insert(pod.Name) } } return matches } // waitTillNPodsRunningOnNodes polls the /runningpods endpoint on kubelet until // it finds targetNumPods pods that match the given criteria (namespace and // podNamePrefix). Note that we usually use label selector to filter pods that // belong to the same RC. However, we use podNamePrefix with namespace here // because pods returned from /runningpods do not contain the original label // information; they are reconstructed by examining the container runtime. In // the scope of this test, we do not expect pod naming conflicts so // podNamePrefix should be sufficient to identify the pods. func waitTillNPodsRunningOnNodes(c *client.Client, nodeNames sets.String, podNamePrefix string, namespace string, targetNumPods int, timeout time.Duration) error { return wait.Poll(pollInterval, timeout, func() (bool, error) { matchCh := make(chan sets.String, len(nodeNames)) for _, item := range nodeNames.List() { // Launch a goroutine per node to check the pods running on the nodes. nodeName := item go func() { matchCh <- getPodMatches(c, nodeName, podNamePrefix, namespace) }() } seen := sets.NewString() for i := 0; i < len(nodeNames.List()); i++ { seen = seen.Union(<-matchCh) } if seen.Len() == targetNumPods { return true, nil } framework.Logf("Waiting for %d pods to be running on the node; %d are currently running;", targetNumPods, seen.Len()) return false, nil }) } // updates labels of nodes given by nodeNames. // In case a given label already exists, it overwrites it. If label to remove doesn't exist // it silently ignores it. func updateNodeLabels(c *client.Client, nodeNames sets.String, toAdd, toRemove map[string]string) { const maxRetries = 5 for nodeName := range nodeNames { var node *api.Node var err error for i := 0; i < maxRetries; i++ { node, err = c.Nodes().Get(nodeName) if err != nil { framework.Logf("Error getting node %s: %v", nodeName, err) continue } if toAdd != nil { for k, v := range toAdd { node.ObjectMeta.Labels[k] = v } } if toRemove != nil { for k := range toRemove { delete(node.ObjectMeta.Labels, k) } } _, err = c.Nodes().Update(node) if err != nil { framework.Logf("Error updating node %s: %v", nodeName, err) } else { break } } Expect(err).NotTo(HaveOccurred()) } } var _ = framework.KubeDescribe("kubelet", func() { var c *client.Client var numNodes int var nodeNames sets.String var nodeLabels map[string]string f := framework.NewDefaultFramework("kubelet") var resourceMonitor *framework.ResourceMonitor BeforeEach(func() { c = f.Client nodes := framework.GetReadySchedulableNodesOrDie(f.Client) numNodes = len(nodes.Items) nodeNames = sets.NewString() // If there are a lot of nodes, we don't want to use all of them // (if there are 1000 nodes in the cluster, starting 10 pods/node // will take ~10 minutes today). And there is also deletion phase. // // Instead, we choose at most 10 nodes and will constraint pods // that we are creating to be scheduled only on that nodes. if numNodes > maxNodesToCheck { numNodes = maxNodesToCheck nodeLabels = make(map[string]string) nodeLabels["kubelet_cleanup"] = "true" } for i := 0; i < numNodes; i++ { nodeNames.Insert(nodes.Items[i].Name) } updateNodeLabels(c, nodeNames, nodeLabels, nil) // Start resourceMonitor only in small clusters. if len(nodes.Items) <= maxNodesToCheck { resourceMonitor = framework.NewResourceMonitor(f.Client, framework.TargetContainers(), containerStatsPollingInterval) resourceMonitor.Start() } }) AfterEach(func() { if resourceMonitor != nil { resourceMonitor.Stop() } // If we added labels to nodes in this test, remove them now. updateNodeLabels(c, nodeNames, nil, nodeLabels) }) framework.KubeDescribe("Clean up pods on node", func() { type DeleteTest struct { podsPerNode int timeout time.Duration } deleteTests := []DeleteTest{ {podsPerNode: 10, timeout: 1 * time.Minute}, } for _, itArg := range deleteTests { name := fmt.Sprintf( "kubelet should be able to delete %d pods per node in %v.", itArg.podsPerNode, itArg.timeout) It(name, func() { totalPods := itArg.podsPerNode * numNodes By(fmt.Sprintf("Creating a RC of %d pods and wait until all pods of this RC are running", totalPods)) rcName := fmt.Sprintf("cleanup%d-%s", totalPods, string(util.NewUUID())) Expect(framework.RunRC(framework.RCConfig{ Client: f.Client, Name: rcName, Namespace: f.Namespace.Name, Image: framework.GetPauseImageName(f.Client), Replicas: totalPods, NodeSelector: nodeLabels, })).NotTo(HaveOccurred()) // Perform a sanity check so that we know all desired pods are // running on the nodes according to kubelet. The timeout is set to // only 30 seconds here because framework.RunRC already waited for all pods to // transition to the running status. Expect(waitTillNPodsRunningOnNodes(f.Client, nodeNames, rcName, f.Namespace.Name, totalPods, time.Second*30)).NotTo(HaveOccurred()) if resourceMonitor != nil { resourceMonitor.LogLatest() } By("Deleting the RC") framework.DeleteRC(f.Client, f.Namespace.Name, rcName) // Check that the pods really are gone by querying /runningpods on the // node. The /runningpods handler checks the container runtime (or its // cache) and returns a list of running pods. Some possible causes of // failures are: // - kubelet deadlock // - a bug in graceful termination (if it is enabled) // - docker slow to delete pods (or resource problems causing slowness) start := time.Now() Expect(waitTillNPodsRunningOnNodes(f.Client, nodeNames, rcName, f.Namespace.Name, 0, itArg.timeout)).NotTo(HaveOccurred()) framework.Logf("Deleting %d pods on %d nodes completed in %v after the RC was deleted", totalPods, len(nodeNames), time.Since(start)) if resourceMonitor != nil { resourceMonitor.LogCPUSummary() } }) } }) })
anguslees/kubernetes
test/e2e/kubelet.go
GO
apache-2.0
7,953
package org.apereo.cas.audit; import org.apereo.inspektr.audit.AuditActionContext; import org.apereo.inspektr.audit.AuditTrailManager; import java.time.LocalDate; import java.util.List; import java.util.Set; /** * This is {@link AuditTrailExecutionPlan}. * * @author Misagh Moayyed * @since 5.3.0 */ public interface AuditTrailExecutionPlan { /** * Register audit trail manager. * * @param manager the manager */ void registerAuditTrailManager(AuditTrailManager manager); /** * Gets audit trail managers. * * @return the audit trail managers */ List<AuditTrailManager> getAuditTrailManagers(); /** * Record. * * @param audit the audit */ void record(AuditActionContext audit); /** * Gets audit records since the specified date. * * @param sinceDate the since date * @return the audit records since */ Set<AuditActionContext> getAuditRecordsSince(LocalDate sinceDate); }
robertoschwald/cas
api/cas-server-core-api-audit/src/main/java/org/apereo/cas/audit/AuditTrailExecutionPlan.java
Java
apache-2.0
999
/* * 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.druid.extendedset.intset; import java.util.NoSuchElementException; public final class EmptyIntIterator implements IntSet.IntIterator { private static final EmptyIntIterator INSTANCE = new EmptyIntIterator(); public static EmptyIntIterator instance() { return INSTANCE; } private EmptyIntIterator() { } @Override public boolean hasNext() { return false; } @Override public int next() { throw new NoSuchElementException(); } @Override public void skipAllBefore(int element) { // nothing to skip } @Override public IntSet.IntIterator clone() { return new EmptyIntIterator(); } }
deltaprojects/druid
extendedset/src/main/java/org/apache/druid/extendedset/intset/EmptyIntIterator.java
Java
apache-2.0
1,478
using Provisioning.Common.Authentication; using Provisioning.Common.Configuration; using Provisioning.Common.Configuration.Application; using Provisioning.Common.Utilities; using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.Online.SharePoint.TenantManagement; using Microsoft.SharePoint.Client; using OfficeDevPnP.Core.Entities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Provisioning.Common.Data.Templates; namespace Provisioning.Common { /// <summary> /// Implementation class for Provisioning an Office 365 Site. /// </summary> public class Office365SiteProvisioningService : AbstractSiteProvisioningService { #region Constructor /// <summary> /// Constructor /// </summary> public Office365SiteProvisioningService() : base() { } #endregion public override void CreateSiteCollection(SiteRequestInformation siteRequest, Template template) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Starting, siteRequest.Url); UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); var _newsite = new SiteCreationProperties(); _newsite.Title = siteRequest.Title; _newsite.Url = siteRequest.Url; _newsite.Owner = siteRequest.SiteOwner.Name; _newsite.Template = template.RootTemplate; _newsite.Lcid = siteRequest.Lcid; _newsite.TimeZoneId = siteRequest.TimeZoneId; _newsite.StorageMaximumLevel = template.StorageMaximumLevel; _newsite.StorageWarningLevel = template.StorageWarningLevel; _newsite.UserCodeMaximumLevel = template.UserCodeMaximumLevel; _newsite.UserCodeMaximumLevel = template.UserCodeWarningLevel; SpoOperation op = _tenant.CreateSite(_newsite); ctx.Load(_tenant); ctx.Load(op, i => i.IsComplete); ctx.ExecuteQuery(); while (!op.IsComplete) { //wait 30seconds and try again System.Threading.Thread.Sleep(30000); op.RefreshLoad(); ctx.ExecuteQuery(); } var _site = _tenant.GetSiteByUrl(siteRequest.Url); var _web = _site.RootWeb; _web.Description = siteRequest.Description; _web.Update(); ctx.Load(_web); ctx.ExecuteQuery(); } catch (Exception ex) { Log.Error("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Failure, siteRequest.Url, ex.Message, ex); throw; } Log.Info("Provisioning.Common.Office365SiteProvisioningService.CreateSiteCollection", PCResources.SiteCreation_Creation_Successfull, siteRequest.Url); }); } /// <summary> /// /// </summary> /// <param name="siteInfo"></param> public override void SetExternalSharing(SiteRequestInformation siteInfo) { UsingContext(ctx => { try { Tenant _tenant = new Tenant(ctx); SiteProperties _siteProps = _tenant.GetSitePropertiesByUrl(siteInfo.Url, false); ctx.Load(_tenant); ctx.Load(_siteProps); ctx.ExecuteQuery(); bool _shouldBeUpdated = false; var _tenantSharingCapability = _tenant.SharingCapability; var _siteSharingCapability = _siteProps.SharingCapability; var _targetSharingCapability = SharingCapabilities.Disabled; if(siteInfo.EnableExternalSharing && _tenantSharingCapability != SharingCapabilities.Disabled) { _targetSharingCapability = SharingCapabilities.ExternalUserSharingOnly; _shouldBeUpdated = true; } if (_siteSharingCapability != _targetSharingCapability && _shouldBeUpdated) { _siteProps.SharingCapability = _targetSharingCapability; _siteProps.Update(); ctx.ExecuteQuery(); Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Successfull, siteInfo.Url); } } catch(Exception _ex) { Log.Info("Provisioning.Common.Office365SiteProvisioningService.SetExternalSharing", PCResources.ExternalSharing_Exception, siteInfo.Url, _ex); } }); } } }
Rick-Kirkham/PnP
Solutions/Provisioning.UX.App/Provisioning.Common/Office365SiteProvisioningService.cs
C#
apache-2.0
5,418
require 'spec_helper' describe 'docker::exec', :type => :define do let(:title) { 'sample' } context 'when running detached' do let(:params) { {'command' => 'command', 'container' => 'container', 'detach' => true} } it { should contain_exec('docker exec --detach=true container command') } end context 'when running with tty' do let(:params) { {'command' => 'command', 'container' => 'container', 'tty' => true} } it { should contain_exec('docker exec --tty=true container command') } end context 'when running with interactive' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true} } it { should contain_exec('docker exec --interactive=true container command') } end context 'when running with unless' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true, 'unless' => 'some_command arg1'} } it { should contain_exec('docker exec --interactive=true container command').with_unless ('docker exec --interactive=true container some_command arg1') } end context 'when running without unless' do let(:params) { {'command' => 'command', 'container' => 'container', 'interactive' => true,} } it { should contain_exec('docker exec --interactive=true container command').with_unless (nil) } end end
cornelf/garethr-docker
spec/defines/exec_spec.rb
Ruby
apache-2.0
1,361
/* * 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.beam.runners.dataflow.worker; import com.google.api.services.dataflow.model.CounterUpdate; import org.apache.beam.runners.dataflow.worker.util.common.worker.WorkExecutor; /** An general executor for work in the Dataflow legacy and Beam harness. */ public interface DataflowWorkExecutor extends WorkExecutor { /** * Extract metric updates that are still pending to be reported to the Dataflow service, removing * them from this {@link DataflowWorkExecutor}. */ Iterable<CounterUpdate> extractMetricUpdates(); }
mxm/incubator-beam
runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/DataflowWorkExecutor.java
Java
apache-2.0
1,351
package org.gwtbootstrap3.client.ui.base.button; /* * #%L * GwtBootstrap3 * %% * Copyright (C) 2013 - 2014 GwtBootstrap3 * %% * 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. * #L% */
gwtbootstrap3/gwtbootstrap3
gwtbootstrap3/src/main/java/org/gwtbootstrap3/client/ui/base/button/package-info.java
Java
apache-2.0
701
/* * 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.facebook.presto.sql.tree; import java.util.Objects; import java.util.Optional; import static com.google.common.base.MoreObjects.toStringHelper; import static java.util.Objects.requireNonNull; public class Prepare extends Statement { private final String name; private final Statement statement; public Prepare(NodeLocation location, String name, Statement statement) { this(Optional.of(location), name, statement); } public Prepare(String name, Statement statement) { this(Optional.empty(), name, statement); } private Prepare(Optional<NodeLocation> location, String name, Statement statement) { super(location); this.name = requireNonNull(name, "name is null"); this.statement = requireNonNull(statement, "statement is null"); } public String getName() { return name; } public Statement getStatement() { return statement; } @Override public <R, C> R accept(AstVisitor<R, C> visitor, C context) { return visitor.visitPrepare(this, context); } @Override public int hashCode() { return Objects.hash(name, statement); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if ((obj == null) || (getClass() != obj.getClass())) { return false; } Prepare o = (Prepare) obj; return Objects.equals(name, o.name) && Objects.equals(statement, o.statement); } @Override public String toString() { return toStringHelper(this) .add("name", name) .add("statement", statement) .toString(); } }
propene/presto
presto-parser/src/main/java/com/facebook/presto/sql/tree/Prepare.java
Java
apache-2.0
2,348
/* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/J is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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; version 2 of the License. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ package com.mysql.jdbc; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.sql.Date; import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.TimeZone; /** * A RowHolder implementation that is for cached results (a-la * mysql_store_result()). * * @version $Id: $ */ public class ByteArrayRow extends ResultSetRow { byte[][] internalRowData; public ByteArrayRow(byte[][] internalRowData, ExceptionInterceptor exceptionInterceptor) { super(exceptionInterceptor); this.internalRowData = internalRowData; } public byte[] getColumnValue(int index) throws SQLException { return this.internalRowData[index]; } public void setColumnValue(int index, byte[] value) throws SQLException { this.internalRowData[index] = value; } public String getString(int index, String encoding, MySQLConnection conn) throws SQLException { byte[] columnData = this.internalRowData[index]; if (columnData == null) { return null; } return getString(encoding, conn, columnData, 0, columnData.length); } public boolean isNull(int index) throws SQLException { return this.internalRowData[index] == null; } public boolean isFloatingPointNumber(int index) throws SQLException { byte[] numAsBytes = this.internalRowData[index]; if (this.internalRowData[index] == null || this.internalRowData[index].length == 0) { return false; } for (int i = 0; i < numAsBytes.length; i++) { if (((char) numAsBytes[i] == 'e') || ((char) numAsBytes[i] == 'E')) { return true; } } return false; } public long length(int index) throws SQLException { if (this.internalRowData[index] == null) { return 0; } return this.internalRowData[index].length; } public int getInt(int columnIndex) { if (this.internalRowData[columnIndex] == null) { return 0; } return StringUtils.getInt(this.internalRowData[columnIndex]); } public long getLong(int columnIndex) { if (this.internalRowData[columnIndex] == null) { return 0; } return StringUtils.getLong(this.internalRowData[columnIndex]); } public Timestamp getTimestampFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getTimestampFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public double getNativeDouble(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeDouble(this.internalRowData[columnIndex], 0); } public float getNativeFloat(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeFloat(this.internalRowData[columnIndex], 0); } public int getNativeInt(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeInt(this.internalRowData[columnIndex], 0); } public long getNativeLong(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeLong(this.internalRowData[columnIndex], 0); } public short getNativeShort(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return 0; } return getNativeShort(this.internalRowData[columnIndex], 0); } public Timestamp getNativeTimestamp(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] bits = this.internalRowData[columnIndex]; if (bits == null) { return null; } return getNativeTimestamp(bits, 0, bits.length, targetCalendar, tz, rollForward, conn, rs); } public void closeOpenStreams() { // no-op for this type } public InputStream getBinaryInputStream(int columnIndex) throws SQLException { if (this.internalRowData[columnIndex] == null) { return null; } return new ByteArrayInputStream(this.internalRowData[columnIndex]); } public Reader getReader(int columnIndex) throws SQLException { InputStream stream = getBinaryInputStream(columnIndex); if (stream == null) { return null; } try { return new InputStreamReader(stream, this.metadata[columnIndex] .getCharacterSet()); } catch (UnsupportedEncodingException e) { SQLException sqlEx = SQLError.createSQLException("", this.exceptionInterceptor); sqlEx.initCause(e); throw sqlEx; } } public Time getTimeFast(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getTimeFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public Date getDateFast(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar targetCalendar) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getDateFast(columnIndex, this.internalRowData[columnIndex], 0, columnValue.length, conn, rs, targetCalendar); } public Object getNativeDateTimeValue(int columnIndex, Calendar targetCalendar, int jdbcType, int mysqlType, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeDateTimeValue(columnIndex, columnValue, 0, columnValue.length, targetCalendar, jdbcType, mysqlType, tz, rollForward, conn, rs); } public Date getNativeDate(int columnIndex, MySQLConnection conn, ResultSetImpl rs, Calendar cal) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeDate(columnIndex, columnValue, 0, columnValue.length, conn, rs, cal); } public Time getNativeTime(int columnIndex, Calendar targetCalendar, TimeZone tz, boolean rollForward, MySQLConnection conn, ResultSetImpl rs) throws SQLException { byte[] columnValue = this.internalRowData[columnIndex]; if (columnValue == null) { return null; } return getNativeTime(columnIndex, columnValue, 0, columnValue.length, targetCalendar, tz, rollForward, conn, rs); } public int getBytesSize() { if (internalRowData == null) { return 0; } int bytesSize = 0; for (int i = 0; i < internalRowData.length; i++) { if (internalRowData[i] != null) { bytesSize += internalRowData[i].length; } } return bytesSize; } }
suthat/signal
vendor/mysql-connector-java-5.1.26/src/com/mysql/jdbc/ByteArrayRow.java
Java
apache-2.0
8,491
var names = Alloy.Collections.name; function green(str) { return '\x1B[32m' + str + '\x1B[39m'; } function red(str) { return '\x1B[31m' + str + '\x1B[39m'; } // show the info from the selected model function showInfo(e) { // get the model id from the list item var modelId = e.section.getItemAt(e.itemIndex).properties.modelId; // fetch a specific model based on the given id var model = Alloy.createModel('info'); model.fetch({ id: modelId }); // assert we got the right data back var pass = JSON.stringify(model.attributes) === JSON.stringify({ id: modelId, info: 'info ' + modelId }); Ti.API.info('Assert single info model returned with "{id:' + modelId + '}": ' + (pass ? green('OK') : red('FAIL'))); } // fetch the data to update the UI names.fetch(); // open the window $.index.open();
brentonhouse/brentonhouse.alloy
test/apps/testing/ALOY-829/controllers/index.js
JavaScript
apache-2.0
810
# Copyright 2014, Rackspace, US, 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. """This package holds the REST API that supports the Horizon dashboard Javascript code. It is not intended to be used outside of Horizon, and makes no promises of stability or fitness for purpose outside of that scope. It does not promise to adhere to the general OpenStack API Guidelines set out in https://wiki.openstack.org/wiki/APIChangeGuidelines. """ # import REST API modules here from . import cinder #flake8: noqa from . import config #flake8: noqa from . import glance #flake8: noqa from . import heat #flake8: noqa from . import keystone #flake8: noqa from . import network #flake8: noqa from . import neutron #flake8: noqa from . import nova #flake8: noqa from . import policy #flake8: noqa
takeshineshiro/horizon
openstack_dashboard/api/rest/__init__.py
Python
apache-2.0
1,343
# Copyright 2015 The TensorFlow 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. # ============================================================================== """Functions to provide simpler and prettier logging.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import logging_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import tensor_array_ops __all__ = ["print_op"] def _get_tensor_repr(t, print_tensor_name=True, print_tensor_type=True, print_shape=True, summarize_indicator_vector=True): """Return a list of Tensors that summarize the given tensor t.""" tensor_list = [] if print_tensor_name and isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Name: " + t.name)) if print_tensor_type: if isinstance(t, ops.Tensor): t_type_str = "Type: Tensor ({})".format(t.dtype.name) elif isinstance(t, ops.SparseTensor): t_type_str = "Type: SparseTensor ({})".format(t.dtype.name) elif isinstance(t, tensor_array_ops.TensorArray): t_type_str = "Type: TensorArray ({})".format(t.dtype.name) tensor_list.append(constant_op.constant(t_type_str)) if print_shape: if isinstance(t, ops.SparseTensor): tensor_list.append(constant_op.constant("Shape:")) tensor_list.append(t.shape) elif isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Shape: " + str(t.get_shape( ).dims))) elif isinstance(t, tensor_array_ops.TensorArray): tensor_list.append(constant_op.constant("Size:")) tensor_list.append(t.size()) if summarize_indicator_vector and t.dtype == dtypes.bool: int_tensor = math_ops.cast(t, dtypes.uint8) tensor_list.append(constant_op.constant("First True in Boolean tensor at:")) tensor_list.append(math_ops.argmax(int_tensor, 0)) if isinstance(t, ops.SparseTensor): tensor_list.append(constant_op.constant("Sparse indices:")) tensor_list.append(t.indices) tensor_list.append(constant_op.constant("Sparse values:")) tensor_list.append(t.values) elif isinstance(t, ops.Tensor): tensor_list.append(constant_op.constant("Value:")) tensor_list.append(t) elif isinstance(t, tensor_array_ops.TensorArray): tensor_list.append(constant_op.constant("Value:")) tensor_list.append(t.pack()) return tensor_list def print_op(input_, data=None, message=None, first_n=None, summarize=20, print_tensor_name=True, print_tensor_type=True, print_shape=True, summarize_indicator_vector=True, name=None): """Creates a print op that will print when a tensor is accessed. Wraps the tensor passed in so that whenever that tensor is accessed, the message `message` is printed, along with the current value of the tensor `t` and an optional list of other tensors. Args: input_: A Tensor/SparseTensor/TensorArray to print when it is evaluated. data: A list of other tensors to print. message: A string message to print as a prefix. first_n: Only log `first_n` number of times. Negative numbers log always; this is the default. summarize: Print this number of elements in the tensor. print_tensor_name: Print the tensor name. print_tensor_type: Print the tensor type. print_shape: Print the tensor's shape. summarize_indicator_vector: Whether to print the index of the first true value in an indicator vector (a Boolean tensor). name: The name to give this op. Returns: A Print op. The Print op returns `input_`. Raises: ValueError: If the tensor `input_` is not a Tensor, SparseTensor or TensorArray. """ message = message or "" if input_ is None: raise ValueError("input_ must be of type " "Tensor, SparseTensor or TensorArray") tensor_list = _get_tensor_repr(input_, print_tensor_name, print_tensor_type, print_shape, summarize_indicator_vector) if data is not None: for t in data: tensor_list.extend(_get_tensor_repr(t, print_tensor_name, print_tensor_type, print_shape, summarize_indicator_vector)) if isinstance(input_, ops.Tensor): input_ = logging_ops.Print(input_, tensor_list, message, first_n, summarize, name) elif isinstance(input_, ops.SparseTensor): p = logging_ops.Print( constant_op.constant([]), tensor_list, message, first_n, summarize, name) with ops.control_dependencies([p]): input_ = ops.SparseTensor(array_ops.identity(input_.indices), array_ops.identity(input_.values), array_ops.identity(input_.shape)) elif isinstance(input_, tensor_array_ops.TensorArray): p = logging_ops.Print( constant_op.constant([]), tensor_list, message, first_n, summarize, name) with ops.control_dependencies([p]): input_ = tensor_array_ops.TensorArray(dtype=input_.dtype, handle=input_.handle) else: raise ValueError("input_ must be of type " "Tensor, SparseTensor or TensorArray") return input_
cg31/tensorflow
tensorflow/contrib/framework/python/ops/prettyprint_ops.py
Python
apache-2.0
6,195
//// [tests/cases/compiler/extendingClassFromAliasAndUsageInIndexer.ts] //// //// [extendingClassFromAliasAndUsageInIndexer_backbone.ts] export class Model { public someData: string; } //// [extendingClassFromAliasAndUsageInIndexer_moduleA.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { // interesting stuff here } //// [extendingClassFromAliasAndUsageInIndexer_moduleB.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); export class VisualizationModel extends Backbone.Model { // different interesting stuff here } //// [extendingClassFromAliasAndUsageInIndexer_main.ts] import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); import moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA"); import moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB"); interface IHasVisualizationModel { VisualizationModel: typeof Backbone.Model; } var moduleATyped: IHasVisualizationModel = moduleA; var moduleMap: { [key: string]: IHasVisualizationModel } = { "moduleA": moduleA, "moduleB": moduleB }; var moduleName: string; var visModel = new moduleMap[moduleName].VisualizationModel(); //// [extendingClassFromAliasAndUsageInIndexer_backbone.js] "use strict"; var Model = (function () { function Model() { } return Model; }()); exports.Model = Model; //// [extendingClassFromAliasAndUsageInIndexer_moduleA.js] "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { __extends(VisualizationModel, _super); function VisualizationModel() { _super.apply(this, arguments); } return VisualizationModel; }(Backbone.Model)); exports.VisualizationModel = VisualizationModel; //// [extendingClassFromAliasAndUsageInIndexer_moduleB.js] "use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone"); var VisualizationModel = (function (_super) { __extends(VisualizationModel, _super); function VisualizationModel() { _super.apply(this, arguments); } return VisualizationModel; }(Backbone.Model)); exports.VisualizationModel = VisualizationModel; //// [extendingClassFromAliasAndUsageInIndexer_main.js] "use strict"; var moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA"); var moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB"); var moduleATyped = moduleA; var moduleMap = { "moduleA": moduleA, "moduleB": moduleB }; var moduleName; var visModel = new moduleMap[moduleName].VisualizationModel();
kimamula/TypeScript
tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js
JavaScript
apache-2.0
3,294
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.openapi.wm.impl.status; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.Gray; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.ComponentUI; import java.awt.*; /** * User: spLeaner */ public class StatusBarUI extends ComponentUI { private static final Dimension MAX_SIZE = new Dimension(Integer.MAX_VALUE, 23); private static final Dimension MIN_SIZE = new Dimension(100, 23); private static final Border BACKGROUND_PAINTER = new BackgroundPainter(); @Override public void paint(final Graphics g, final JComponent c) { final Rectangle bounds = c.getBounds(); BACKGROUND_PAINTER.paintBorder(c, g, 0, 0, bounds.width, bounds.height); } @Override public Dimension getMinimumSize(JComponent c) { return MIN_SIZE; // TODO } @Override public Dimension getMaximumSize(JComponent c) { return MAX_SIZE; } private static final class BackgroundPainter implements Border { private static final Color BORDER_TOP_COLOR = Gray._145; private static final Color BORDER2_TOP_COLOR = Gray._255; private static final Color BORDER_BOTTOM_COLOR = Gray._255; private static final Insets INSETS = new Insets(0, 0, 0, 0); public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { final Graphics2D g2d = (Graphics2D) g.create(); final Color background = UIUtil.getPanelBackground(); g2d.setColor(background); g2d.fillRect(0, 0, width, height); Color topColor = UIUtil.isUnderDarcula() ? BORDER_TOP_COLOR.darker().darker() : BORDER_TOP_COLOR; if (SystemInfo.isMac && UIUtil.isUnderIntelliJLaF()) { topColor = Gray.xC9; } g2d.setColor(topColor); g2d.drawLine(0, 0, width, 0); if (!UIUtil.isUnderDarcula()) { g2d.setColor(BORDER_BOTTOM_COLOR); g2d.drawLine(0, height, width, height); } g2d.dispose(); } public Insets getBorderInsets(Component c) { return (Insets)INSETS.clone(); } public boolean isBorderOpaque() { return true; } } }
hurricup/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusBarUI.java
Java
apache-2.0
2,790
# # Description: This method checks to see if the configured_system has been provisioned # # Get current provisioning status task = $evm.root['miq_provision_task'] task_status = task['status'] result = task.statemachine_task_status $evm.log('info', "ProvisionCheck returned <#{result}> for state <#{task.state}> and status <#{task_status}>") case result when 'error' $evm.root['ae_result'] = 'error' reason = $evm.root['miq_provision_task'].message reason = reason[7..-1] if reason[0..6] == 'Error: ' $evm.root['ae_reason'] = reason when 'retry' $evm.root['ae_result'] = 'retry' $evm.root['ae_retry_interval'] = '1.minute' when 'ok' # Bump State $evm.root['ae_result'] = 'ok' end
maas-ufcg/manageiq
db/fixtures/ae_datastore/ManageIQ/Infrastructure/Configured_System/Provisioning/StateMachines/Methods.class/__methods__/check_provisioned.rb
Ruby
apache-2.0
707
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.structuralsearch.impl.matcher.predicates; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiType; import com.intellij.structuralsearch.impl.matcher.MatchContext; import com.siyeh.ig.psiutils.ExpectedTypeUtils; public class FormalArgTypePredicate extends ExprTypePredicate { public FormalArgTypePredicate(String type, String baseName, boolean withinHierarchy, boolean caseSensitiveMatch, boolean target) { super(type, baseName, withinHierarchy, caseSensitiveMatch, target); } @Override protected PsiType evalType(PsiExpression match, MatchContext context) { return ExpectedTypeUtils.findExpectedType(match, true, true); } }
jk1/intellij-community
java/structuralsearch-java/src/com/intellij/structuralsearch/impl/matcher/predicates/FormalArgTypePredicate.java
Java
apache-2.0
1,283
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "SerialExecutor.h" namespace facebook { namespace hermes { namespace inspector { namespace detail { SerialExecutor::SerialExecutor(const std::string &name) : finish_(false), thread_(name, [this]() { runLoop(); }) {} SerialExecutor::~SerialExecutor() { { std::lock_guard<std::mutex> lock(mutex_); finish_ = true; wakeup_.notify_one(); } thread_.join(); } void SerialExecutor::add(folly::Func func) { std::lock_guard<std::mutex> lock(mutex_); funcs_.push(std::move(func)); wakeup_.notify_one(); } void SerialExecutor::runLoop() { bool shouldExit = false; while (!shouldExit) { folly::Func func; { std::unique_lock<std::mutex> lock(mutex_); wakeup_.wait(lock, [this] { return finish_ || !funcs_.empty(); }); if (!funcs_.empty()) { func = std::move(funcs_.front()); funcs_.pop(); } shouldExit = funcs_.empty() && finish_; } if (func) { func(); } } } } // namespace detail } // namespace inspector } // namespace hermes } // namespace facebook
exponent/exponent
android/versioned-react-native/ReactCommon/hermes/inspector/detail/SerialExecutor.cpp
C++
bsd-3-clause
1,254
import { ChangeDetectorRef, Component, ElementRef, Input, Optional, Renderer, ViewChild, ViewEncapsulation } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { clamp, isTrueProperty } from '../../util/util'; import { Config } from '../../config/config'; import { DomController } from '../../platform/dom-controller'; import { Form } from '../../util/form'; import { Haptic } from '../../tap-click/haptic'; import { BaseInput } from '../../util/base-input'; import { Item } from '../item/item'; import { Platform } from '../../platform/platform'; import { pointerCoord } from '../../util/dom'; import { UIEventManager } from '../../gestures/ui-event-manager'; /** * \@name Range * \@description * The Range slider lets users select from a range of values by moving * the slider knob. It can accept dual knobs, but by default one knob * controls the value of the range. * * ### Range Labels * Labels can be placed on either side of the range by adding the * `range-left` or `range-right` property to the element. The element * doesn't have to be an `ion-label`, it can be added to any element * to place it to the left or right of the range. See [usage](#usage) * below for examples. * * * ### Minimum and Maximum Values * Minimum and maximum values can be passed to the range through the `min` * and `max` properties, respectively. By default, the range sets the `min` * to `0` and the `max` to `100`. * * * ### Steps and Snaps * The `step` property specifies the value granularity of the range's value. * It can be useful to set the `step` when the value isn't in increments of `1`. * Setting the `step` property will show tick marks on the range for each step. * The `snaps` property can be set to automatically move the knob to the nearest * tick mark based on the step property value. * * * ### Dual Knobs * Setting the `dualKnobs` property to `true` on the range component will * enable two knobs on the range. If the range has two knobs, the value will * be an object containing two properties: `lower` and `upper`. * * * \@usage * ```html * <ion-list> * <ion-item> * <ion-range [(ngModel)]="singleValue" color="danger" pin="true"></ion-range> * </ion-item> * * <ion-item> * <ion-range min="-200" max="200" [(ngModel)]="saturation" color="secondary"> * <ion-label range-left>-200</ion-label> * <ion-label range-right>200</ion-label> * </ion-range> * </ion-item> * * <ion-item> * <ion-range min="20" max="80" step="2" [(ngModel)]="brightness"> * <ion-icon small range-left name="sunny"></ion-icon> * <ion-icon range-right name="sunny"></ion-icon> * </ion-range> * </ion-item> * * <ion-item> * <ion-label>step=100, snaps, {{singleValue4}}</ion-label> * <ion-range min="1000" max="2000" step="100" snaps="true" color="secondary" [(ngModel)]="singleValue4"></ion-range> * </ion-item> * * <ion-item> * <ion-label>dual, step=3, snaps, {{dualValue2 | json}}</ion-label> * <ion-range dualKnobs="true" [(ngModel)]="dualValue2" min="21" max="72" step="3" snaps="true"></ion-range> * </ion-item> * </ion-list> * ``` * * * \@demo /docs/demos/src/range/ */ export class Range extends BaseInput { /** * @param {?} form * @param {?} _haptic * @param {?} item * @param {?} config * @param {?} _plt * @param {?} elementRef * @param {?} renderer * @param {?} _dom * @param {?} _cd */ constructor(form, _haptic, item, config, _plt, elementRef, renderer, _dom, _cd) { super(config, elementRef, renderer, 'range', 0, form, item, null); this._haptic = _haptic; this._plt = _plt; this._dom = _dom; this._cd = _cd; this._min = 0; this._max = 100; this._step = 1; this._valA = 0; this._valB = 0; this._ratioA = 0; this._ratioB = 0; this._events = new UIEventManager(_plt); } /** * \@input {number} Minimum integer value of the range. Defaults to `0`. * @return {?} */ get min() { return this._min; } /** * @param {?} val * @return {?} */ set min(val) { val = Math.round(val); if (!isNaN(val)) { this._min = val; this._inputUpdated(); } } /** * \@input {number} Maximum integer value of the range. Defaults to `100`. * @return {?} */ get max() { return this._max; } /** * @param {?} val * @return {?} */ set max(val) { val = Math.round(val); if (!isNaN(val)) { this._max = val; this._inputUpdated(); } } /** * \@input {number} Specifies the value granularity. Defaults to `1`. * @return {?} */ get step() { return this._step; } /** * @param {?} val * @return {?} */ set step(val) { val = Math.round(val); if (!isNaN(val) && val > 0) { this._step = val; } } /** * \@input {boolean} If true, the knob snaps to tick marks evenly spaced based * on the step property value. Defaults to `false`. * @return {?} */ get snaps() { return this._snaps; } /** * @param {?} val * @return {?} */ set snaps(val) { this._snaps = isTrueProperty(val); } /** * \@input {boolean} If true, a pin with integer value is shown when the knob * is pressed. Defaults to `false`. * @return {?} */ get pin() { return this._pin; } /** * @param {?} val * @return {?} */ set pin(val) { this._pin = isTrueProperty(val); } /** * \@input {number} How long, in milliseconds, to wait to trigger the * `ionChange` event after each change in the range value. Default `0`. * @return {?} */ get debounce() { return this._debouncer.wait; } /** * @param {?} val * @return {?} */ set debounce(val) { this._debouncer.wait = val; } /** * \@input {boolean} Show two knobs. Defaults to `false`. * @return {?} */ get dualKnobs() { return this._dual; } /** * @param {?} val * @return {?} */ set dualKnobs(val) { this._dual = isTrueProperty(val); } /** * Returns the ratio of the knob's is current location, which is a number * between `0` and `1`. If two knobs are used, this property represents * the lower value. * @return {?} */ get ratio() { if (this._dual) { return Math.min(this._ratioA, this._ratioB); } return this._ratioA; } /** * Returns the ratio of the upper value's is current location, which is * a number between `0` and `1`. If there is only one knob, then this * will return `null`. * @return {?} */ get ratioUpper() { if (this._dual) { return Math.max(this._ratioA, this._ratioB); } return null; } /** * @hidden * @return {?} */ ngAfterContentInit() { this._initialize(); // add touchstart/mousedown listeners this._events.pointerEvents({ element: this._slider.nativeElement, pointerDown: this._pointerDown.bind(this), pointerMove: this._pointerMove.bind(this), pointerUp: this._pointerUp.bind(this), zone: true }); // build all the ticks if there are any to show this._createTicks(); } /** * \@internal * @param {?} ev * @return {?} */ _pointerDown(ev) { // TODO: we could stop listening for events instead of checking this._disabled. // since there are a lot of events involved, this solution is // enough for the moment if (this._disabled) { return false; } // trigger ionFocus event this._fireFocus(); // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // get the start coordinates const /** @type {?} */ current = pointerCoord(ev); // get the full dimensions of the slider element const /** @type {?} */ rect = this._rect = this._plt.getElementBoundingClientRect(this._slider.nativeElement); // figure out which knob they started closer to const /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1); this._activeB = this._dual && (Math.abs(ratio - this._ratioA) > Math.abs(ratio - this._ratioB)); // update the active knob's position this._update(current, rect, true); // trigger a haptic start this._haptic.gestureSelectionStart(); // return true so the pointer events // know everything's still valid return true; } /** * \@internal * @param {?} ev * @return {?} */ _pointerMove(ev) { if (this._disabled) { return; } // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // update the active knob's position const /** @type {?} */ hasChanged = this._update(pointerCoord(ev), this._rect, true); if (hasChanged && this._snaps) { // trigger a haptic selection changed event // if this is a snap range this._haptic.gestureSelectionChanged(); } } /** * \@internal * @param {?} ev * @return {?} */ _pointerUp(ev) { if (this._disabled) { return; } // prevent default so scrolling does not happen ev.preventDefault(); ev.stopPropagation(); // update the active knob's position this._update(pointerCoord(ev), this._rect, false); // trigger a haptic end this._haptic.gestureSelectionEnd(); // trigger ionBlur event this._fireBlur(); } /** * \@internal * @param {?} current * @param {?} rect * @param {?} isPressed * @return {?} */ _update(current, rect, isPressed) { // figure out where the pointer is currently at // update the knob being interacted with let /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1); let /** @type {?} */ val = this._ratioToValue(ratio); if (this._snaps) { // snaps the ratio to the current value ratio = this._valueToRatio(val); } // update which knob is pressed this._pressed = isPressed; let /** @type {?} */ valChanged = false; if (this._activeB) { // when the pointer down started it was determined // that knob B was the one they were interacting with this._pressedB = isPressed; this._pressedA = false; this._ratioB = ratio; valChanged = val === this._valB; this._valB = val; } else { // interacting with knob A this._pressedA = isPressed; this._pressedB = false; this._ratioA = ratio; valChanged = val === this._valA; this._valA = val; } this._updateBar(); if (valChanged) { return false; } // value has been updated let /** @type {?} */ value; if (this._dual) { // dual knobs have an lower and upper value value = { lower: Math.min(this._valA, this._valB), upper: Math.max(this._valA, this._valB) }; (void 0) /* console.debug */; } else { // single knob only has one value value = this._valA; (void 0) /* console.debug */; } // Update input value this.value = value; return true; } /** * \@internal * @return {?} */ _updateBar() { const /** @type {?} */ ratioA = this._ratioA; const /** @type {?} */ ratioB = this._ratioB; if (this._dual) { this._barL = `${(Math.min(ratioA, ratioB) * 100)}%`; this._barR = `${100 - (Math.max(ratioA, ratioB) * 100)}%`; } else { this._barL = ''; this._barR = `${100 - (ratioA * 100)}%`; } this._updateTicks(); } /** * \@internal * @return {?} */ _createTicks() { if (this._snaps) { this._dom.write(() => { // TODO: Fix to not use RAF this._ticks = []; for (var /** @type {?} */ value = this._min; value <= this._max; value += this._step) { var /** @type {?} */ ratio = this._valueToRatio(value); this._ticks.push({ ratio: ratio, left: `${ratio * 100}%`, }); } this._updateTicks(); }); } } /** * \@internal * @return {?} */ _updateTicks() { const /** @type {?} */ ticks = this._ticks; const /** @type {?} */ ratio = this.ratio; if (this._snaps && ticks) { if (this._dual) { var /** @type {?} */ upperRatio = this.ratioUpper; ticks.forEach(t => { t.active = (t.ratio >= ratio && t.ratio <= upperRatio); }); } else { ticks.forEach(t => { t.active = (t.ratio <= ratio); }); } } } /** * @hidden * @param {?} isIncrease * @param {?} isKnobB * @return {?} */ _keyChg(isIncrease, isKnobB) { const /** @type {?} */ step = this._step; if (isKnobB) { if (isIncrease) { this._valB += step; } else { this._valB -= step; } this._valB = clamp(this._min, this._valB, this._max); this._ratioB = this._valueToRatio(this._valB); } else { if (isIncrease) { this._valA += step; } else { this._valA -= step; } this._valA = clamp(this._min, this._valA, this._max); this._ratioA = this._valueToRatio(this._valA); } this._updateBar(); } /** * \@internal * @param {?} ratio * @return {?} */ _ratioToValue(ratio) { ratio = Math.round(((this._max - this._min) * ratio)); ratio = Math.round(ratio / this._step) * this._step + this._min; return clamp(this._min, ratio, this._max); } /** * \@internal * @param {?} value * @return {?} */ _valueToRatio(value) { value = Math.round((value - this._min) / this._step) * this._step; value = value / (this._max - this._min); return clamp(0, value, 1); } /** * @param {?} val * @return {?} */ _inputNormalize(val) { if (this._dual) { return val; } else { val = parseFloat(val); return isNaN(val) ? undefined : val; } } /** * @hidden * @return {?} */ _inputUpdated() { const /** @type {?} */ val = this.value; if (this._dual) { this._valA = val.lower; this._valB = val.upper; this._ratioA = this._valueToRatio(val.lower); this._ratioB = this._valueToRatio(val.upper); } else { this._valA = val; this._ratioA = this._valueToRatio(val); } this._updateBar(); this._cd.detectChanges(); } /** * @hidden * @return {?} */ ngOnDestroy() { super.ngOnDestroy(); this._events.destroy(); } } Range.decorators = [ { type: Component, args: [{ selector: 'ion-range', template: '<ng-content select="[range-left]"></ng-content>' + '<div class="range-slider" #slider>' + '<div class="range-tick" *ngFor="let t of _ticks" [style.left]="t.left" [class.range-tick-active]="t.active" role="presentation"></div>' + '<div class="range-bar" role="presentation"></div>' + '<div class="range-bar range-bar-active" [style.left]="_barL" [style.right]="_barR" #bar role="presentation"></div>' + '<div class="range-knob-handle" (ionIncrease)="_keyChg(true, false)" (ionDecrease)="_keyChg(false, false)" [ratio]="_ratioA" [val]="_valA" [pin]="_pin" [pressed]="_pressedA" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId"></div>' + '<div class="range-knob-handle" (ionIncrease)="_keyChg(true, true)" (ionDecrease)="_keyChg(false, true)" [ratio]="_ratioB" [val]="_valB" [pin]="_pin" [pressed]="_pressedB" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId" *ngIf="_dual"></div>' + '</div>' + '<ng-content select="[range-right]"></ng-content>', host: { '[class.range-disabled]': '_disabled', '[class.range-pressed]': '_pressed', '[class.range-has-pin]': '_pin' }, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: Range, multi: true }], encapsulation: ViewEncapsulation.None, },] }, ]; /** * @nocollapse */ Range.ctorParameters = () => [ { type: Form, }, { type: Haptic, }, { type: Item, decorators: [{ type: Optional },] }, { type: Config, }, { type: Platform, }, { type: ElementRef, }, { type: Renderer, }, { type: DomController, }, { type: ChangeDetectorRef, }, ]; Range.propDecorators = { '_slider': [{ type: ViewChild, args: ['slider',] },], 'min': [{ type: Input },], 'max': [{ type: Input },], 'step': [{ type: Input },], 'snaps': [{ type: Input },], 'pin': [{ type: Input },], 'debounce': [{ type: Input },], 'dualKnobs': [{ type: Input },], }; function Range_tsickle_Closure_declarations() { /** @type {?} */ Range.decorators; /** * @nocollapse * @type {?} */ Range.ctorParameters; /** @type {?} */ Range.propDecorators; /** @type {?} */ Range.prototype._dual; /** @type {?} */ Range.prototype._pin; /** @type {?} */ Range.prototype._pressed; /** @type {?} */ Range.prototype._activeB; /** @type {?} */ Range.prototype._rect; /** @type {?} */ Range.prototype._ticks; /** @type {?} */ Range.prototype._min; /** @type {?} */ Range.prototype._max; /** @type {?} */ Range.prototype._step; /** @type {?} */ Range.prototype._snaps; /** @type {?} */ Range.prototype._valA; /** @type {?} */ Range.prototype._valB; /** @type {?} */ Range.prototype._ratioA; /** @type {?} */ Range.prototype._ratioB; /** @type {?} */ Range.prototype._pressedA; /** @type {?} */ Range.prototype._pressedB; /** @type {?} */ Range.prototype._barL; /** @type {?} */ Range.prototype._barR; /** @type {?} */ Range.prototype._events; /** @type {?} */ Range.prototype._slider; /** @type {?} */ Range.prototype._haptic; /** @type {?} */ Range.prototype._plt; /** @type {?} */ Range.prototype._dom; /** @type {?} */ Range.prototype._cd; } //# sourceMappingURL=range.js.map
vivadaniele/spid-ionic-sdk
node_modules/ionic-angular/es2015/components/range/range.js
JavaScript
bsd-3-clause
19,852
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.tabmodel; import org.chromium.chrome.browser.Tab; import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType; import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType; import java.util.List; /** * An interface to be notified about changes to a TabModel. */ public interface TabModelObserver { /** * Called when a tab is selected. * * @param tab The newly selected tab. * @param type The type of selection. * @param lastId The ID of the last selected tab, or {@link Tab#INVALID_TAB_ID} if no tab was * selected. */ void didSelectTab(Tab tab, TabSelectionType type, int lastId); /** * Called when a tab starts closing. * * @param tab The tab to close. * @param animate Whether or not to animate the closing. */ void willCloseTab(Tab tab, boolean animate); /** * Called right after {@code tab} has been destroyed. * * @param tab The tab that has been destroyed. */ void didCloseTab(Tab tab); /** * Called before a tab will be added to the {@link TabModel}. * * @param tab The tab about to be added. * @param type The type of tab launch. */ void willAddTab(Tab tab, TabLaunchType type); /** * Called after a tab has been added to the {@link TabModel}. * * @param tab The newly added tab. * @param type The type of tab launch. */ void didAddTab(Tab tab, TabLaunchType type); /** * Called after a tab has been moved from one position in the {@link TabModel} to another. * * @param tab The tab which has been moved. * @param newIndex The new index of the tab in the model. * @param curIndex The old index of the tab in the model. */ void didMoveTab(Tab tab, int newIndex, int curIndex); /** * Called when a tab is pending closure, i.e. the user has just closed it, but it can still be * undone. At this point, the Tab has been removed from the TabModel and can only be accessed * via {@link TabModel#getComprehensiveModel()}. * * @param tab The tab that is pending closure. */ void tabPendingClosure(Tab tab); /** * Called when a tab closure is undone. * * @param tab The tab that has been reopened. */ void tabClosureUndone(Tab tab); /** * Called when a tab closure is committed and can't be undone anymore. * * @param tab The tab that has been closed. */ void tabClosureCommitted(Tab tab); /** * Called when "all tabs" are pending closure. * * @param tabIds The list of tabs IDs that are pending closure. */ void allTabsPendingClosure(List<Integer> tabIds); /** * Called when an "all tabs" closure has been committed and can't be undone anymore. */ void allTabsClosureCommitted(); }
guorendong/iridium-browser-ubuntu
chrome/android/java/src/org/chromium/chrome/browser/tabmodel/TabModelObserver.java
Java
bsd-3-clause
3,080
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gsub.h" #include <limits> #include <vector> #include "gdef.h" #include "gpos.h" #include "layout.h" #include "maxp.h" // GSUB - The Glyph Substitution Table // http://www.microsoft.com/typography/otspec/gsub.htm namespace { // The GSUB header size const size_t kGsubHeaderSize = 4 + 3 * 2; enum GSUB_TYPE { GSUB_TYPE_SINGLE = 1, GSUB_TYPE_MULTIPLE = 2, GSUB_TYPE_ALTERNATE = 3, GSUB_TYPE_LIGATURE = 4, GSUB_TYPE_CONTEXT = 5, GSUB_TYPE_CHANGING_CONTEXT = 6, GSUB_TYPE_EXTENSION_SUBSTITUTION = 7, GSUB_TYPE_REVERSE_CHAINING_CONTEXT_SINGLE = 8, GSUB_TYPE_RESERVED = 9 }; // Lookup type parsers. bool ParseSingleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseMutipleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseAlternateSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseLigatureSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseChainingContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseExtensionSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); bool ParseReverseChainingContextSingleSubstitution( const ots::OpenTypeFile *file, const uint8_t *data, const size_t length); const ots::LookupSubtableParser::TypeParser kGsubTypeParsers[] = { {GSUB_TYPE_SINGLE, ParseSingleSubstitution}, {GSUB_TYPE_MULTIPLE, ParseMutipleSubstitution}, {GSUB_TYPE_ALTERNATE, ParseAlternateSubstitution}, {GSUB_TYPE_LIGATURE, ParseLigatureSubstitution}, {GSUB_TYPE_CONTEXT, ParseContextSubstitution}, {GSUB_TYPE_CHANGING_CONTEXT, ParseChainingContextSubstitution}, {GSUB_TYPE_EXTENSION_SUBSTITUTION, ParseExtensionSubstitution}, {GSUB_TYPE_REVERSE_CHAINING_CONTEXT_SINGLE, ParseReverseChainingContextSingleSubstitution} }; const ots::LookupSubtableParser kGsubLookupSubtableParser = { arraysize(kGsubTypeParsers), GSUB_TYPE_EXTENSION_SUBSTITUTION, kGsubTypeParsers }; // Lookup Type 1: // Single Substitution Subtable bool ParseSingleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage)) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; if (format == 1) { // Parse SingleSubstFormat1 int16_t delta_glyph_id = 0; if (!subtable.ReadS16(&delta_glyph_id)) { return OTS_FAILURE(); } if (std::abs(delta_glyph_id) >= num_glyphs) { return OTS_FAILURE(); } } else if (format == 2) { // Parse SingleSubstFormat2 uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { OTS_WARNING("too large substitute: %u", substitute); return OTS_FAILURE(); } } } else { return OTS_FAILURE(); } if (offset_coverage < subtable.offset() || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseSequenceTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { return OTS_FAILURE(); } } return true; } // Lookup Type 2: // Multiple Substitution Subtable bool ParseMutipleSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t sequence_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&sequence_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned sequence_end = static_cast<unsigned>(6) + sequence_count * 2; if (sequence_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < sequence_count; ++i) { uint16_t offset_sequence = 0; if (!subtable.ReadU16(&offset_sequence)) { return OTS_FAILURE(); } if (offset_sequence < sequence_end || offset_sequence >= length) { return OTS_FAILURE(); } if (!ParseSequenceTable(data + offset_sequence, length - offset_sequence, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < sequence_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseAlternateSetTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t alternate = 0; if (!subtable.ReadU16(&alternate)) { return OTS_FAILURE(); } if (alternate >= num_glyphs) { OTS_WARNING("too arge alternate: %u", alternate); return OTS_FAILURE(); } } return true; } // Lookup Type 3: // Alternate Substitution Subtable bool ParseAlternateSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t alternate_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&alternate_set_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned alternate_set_end = static_cast<unsigned>(6) + alternate_set_count * 2; if (alternate_set_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < alternate_set_count; ++i) { uint16_t offset_alternate_set = 0; if (!subtable.ReadU16(&offset_alternate_set)) { return OTS_FAILURE(); } if (offset_alternate_set < alternate_set_end || offset_alternate_set >= length) { return OTS_FAILURE(); } if (!ParseAlternateSetTable(data + offset_alternate_set, length - offset_alternate_set, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < alternate_set_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } bool ParseLigatureTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t lig_glyph = 0; uint16_t comp_count = 0; if (!subtable.ReadU16(&lig_glyph) || !subtable.ReadU16(&comp_count)) { return OTS_FAILURE(); } if (lig_glyph >= num_glyphs) { OTS_WARNING("too large lig_glyph: %u", lig_glyph); return OTS_FAILURE(); } if (comp_count == 0 || comp_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < comp_count - static_cast<unsigned>(1); ++i) { uint16_t component = 0; if (!subtable.ReadU16(&component)) { return OTS_FAILURE(); } if (component >= num_glyphs) { return OTS_FAILURE(); } } return true; } bool ParseLigatureSetTable(const uint8_t *data, const size_t length, const uint16_t num_glyphs) { ots::Buffer subtable(data, length); uint16_t ligature_count = 0; if (!subtable.ReadU16(&ligature_count)) { return OTS_FAILURE(); } const unsigned ligature_end = static_cast<unsigned>(2) + ligature_count * 2; if (ligature_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < ligature_count; ++i) { uint16_t offset_ligature = 0; if (!subtable.ReadU16(&offset_ligature)) { return OTS_FAILURE(); } if (offset_ligature < ligature_end || offset_ligature >= length) { return OTS_FAILURE(); } if (!ParseLigatureTable(data + offset_ligature, length - offset_ligature, num_glyphs)) { return OTS_FAILURE(); } } return true; } // Lookup Type 4: // Ligature Substitution Subtable bool ParseLigatureSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; uint16_t lig_set_count = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage) || !subtable.ReadU16(&lig_set_count)) { return OTS_FAILURE(); } if (format != 1) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; const unsigned ligature_set_end = static_cast<unsigned>(6) + lig_set_count * 2; if (ligature_set_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } for (unsigned i = 0; i < lig_set_count; ++i) { uint16_t offset_ligature_set = 0; if (!subtable.ReadU16(&offset_ligature_set)) { return OTS_FAILURE(); } if (offset_ligature_set < ligature_set_end || offset_ligature_set >= length) { return OTS_FAILURE(); } if (!ParseLigatureSetTable(data + offset_ligature_set, length - offset_ligature_set, num_glyphs)) { return OTS_FAILURE(); } } if (offset_coverage < ligature_set_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } return true; } // Lookup Type 5: // Contextual Substitution Subtable bool ParseContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseContextSubtable(data, length, file->maxp->num_glyphs, file->gsub->num_lookups); } // Lookup Type 6: // Chaining Contextual Substitution Subtable bool ParseChainingContextSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseChainingContextSubtable(data, length, file->maxp->num_glyphs, file->gsub->num_lookups); } // Lookup Type 7: // Extension Substition bool ParseExtensionSubstitution(const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { return ots::ParseExtensionSubtable(file, data, length, &kGsubLookupSubtableParser); } // Lookup Type 8: // Reverse Chaining Contexual Single Substitution Subtable bool ParseReverseChainingContextSingleSubstitution( const ots::OpenTypeFile *file, const uint8_t *data, const size_t length) { ots::Buffer subtable(data, length); uint16_t format = 0; uint16_t offset_coverage = 0; if (!subtable.ReadU16(&format) || !subtable.ReadU16(&offset_coverage)) { return OTS_FAILURE(); } const uint16_t num_glyphs = file->maxp->num_glyphs; uint16_t backtrack_glyph_count = 0; if (!subtable.ReadU16(&backtrack_glyph_count)) { return OTS_FAILURE(); } if (backtrack_glyph_count > num_glyphs) { return OTS_FAILURE(); } std::vector<uint16_t> offsets_backtrack; offsets_backtrack.reserve(backtrack_glyph_count); for (unsigned i = 0; i < backtrack_glyph_count; ++i) { uint16_t offset = 0; if (!subtable.ReadU16(&offset)) { return OTS_FAILURE(); } offsets_backtrack.push_back(offset); } uint16_t lookahead_glyph_count = 0; if (!subtable.ReadU16(&lookahead_glyph_count)) { return OTS_FAILURE(); } if (lookahead_glyph_count > num_glyphs) { return OTS_FAILURE(); } std::vector<uint16_t> offsets_lookahead; offsets_lookahead.reserve(lookahead_glyph_count); for (unsigned i = 0; i < lookahead_glyph_count; ++i) { uint16_t offset = 0; if (!subtable.ReadU16(&offset)) { return OTS_FAILURE(); } offsets_lookahead.push_back(offset); } uint16_t glyph_count = 0; if (!subtable.ReadU16(&glyph_count)) { return OTS_FAILURE(); } if (glyph_count > num_glyphs) { return OTS_FAILURE(); } for (unsigned i = 0; i < glyph_count; ++i) { uint16_t substitute = 0; if (!subtable.ReadU16(&substitute)) { return OTS_FAILURE(); } if (substitute >= num_glyphs) { return OTS_FAILURE(); } } const unsigned substitute_end = static_cast<unsigned>(10) + (backtrack_glyph_count + lookahead_glyph_count + glyph_count) * 2; if (substitute_end > std::numeric_limits<uint16_t>::max()) { return OTS_FAILURE(); } if (offset_coverage < substitute_end || offset_coverage >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offset_coverage, length - offset_coverage, num_glyphs)) { return OTS_FAILURE(); } for (unsigned i = 0; i < backtrack_glyph_count; ++i) { if (offsets_backtrack[i] < substitute_end || offsets_backtrack[i] >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offsets_backtrack[i], length - offsets_backtrack[i], num_glyphs)) { return OTS_FAILURE(); } } for (unsigned i = 0; i < lookahead_glyph_count; ++i) { if (offsets_lookahead[i] < substitute_end || offsets_lookahead[i] >= length) { return OTS_FAILURE(); } if (!ots::ParseCoverageTable(data + offsets_lookahead[i], length - offsets_lookahead[i], num_glyphs)) { return OTS_FAILURE(); } } return true; } } // namespace #define DROP_THIS_TABLE \ do { file->gsub->data = 0; file->gsub->length = 0; } while (0) namespace ots { // As far as I checked, following fonts contain invalid values in GSUB table. // OTS will drop their GSUB table. // // # too large substitute (value is 0xFFFF) // kaiu.ttf // mingliub2.ttf // mingliub1.ttf // mingliub0.ttf // GraublauWeb.otf // GraublauWebBold.otf // // # too large alternate (value is 0xFFFF) // ManchuFont.ttf // // # bad offset to lang sys table (NULL offset) // DejaVuMonoSansBold.ttf // DejaVuMonoSansBoldOblique.ttf // DejaVuMonoSansOblique.ttf // DejaVuSansMono-BoldOblique.ttf // DejaVuSansMono-Oblique.ttf // DejaVuSansMono-Bold.ttf // // # bad start coverage index // GenBasBI.ttf // GenBasI.ttf // AndBasR.ttf // GenBkBasI.ttf // CharisSILR.ttf // CharisSILBI.ttf // CharisSILI.ttf // CharisSILB.ttf // DoulosSILR.ttf // CharisSILBI.ttf // GenBkBasB.ttf // GenBkBasR.ttf // GenBkBasBI.ttf // GenBasB.ttf // GenBasR.ttf // // # glyph range is overlapping // KacstTitleL.ttf // KacstDecorative.ttf // KacstTitle.ttf // KacstArt.ttf // KacstPoster.ttf // KacstQurn.ttf // KacstDigital.ttf // KacstBook.ttf // KacstFarsi.ttf bool ots_gsub_parse(OpenTypeFile *file, const uint8_t *data, size_t length) { // Parsing gsub table requires |file->maxp->num_glyphs| if (!file->maxp) { return OTS_FAILURE(); } Buffer table(data, length); OpenTypeGSUB *gsub = new OpenTypeGSUB; file->gsub = gsub; uint32_t version = 0; uint16_t offset_script_list = 0; uint16_t offset_feature_list = 0; uint16_t offset_lookup_list = 0; if (!table.ReadU32(&version) || !table.ReadU16(&offset_script_list) || !table.ReadU16(&offset_feature_list) || !table.ReadU16(&offset_lookup_list)) { return OTS_FAILURE(); } if (version != 0x00010000) { OTS_WARNING("bad GSUB version"); DROP_THIS_TABLE; return true; } if ((offset_script_list < kGsubHeaderSize || offset_script_list >= length) || (offset_feature_list < kGsubHeaderSize || offset_feature_list >= length) || (offset_lookup_list < kGsubHeaderSize || offset_lookup_list >= length)) { OTS_WARNING("bad offset in GSUB header"); DROP_THIS_TABLE; return true; } if (!ParseLookupListTable(file, data + offset_lookup_list, length - offset_lookup_list, &kGsubLookupSubtableParser, &gsub->num_lookups)) { OTS_WARNING("faild to parse lookup list table"); DROP_THIS_TABLE; return true; } uint16_t num_features = 0; if (!ParseFeatureListTable(data + offset_feature_list, length - offset_feature_list, gsub->num_lookups, &num_features)) { OTS_WARNING("faild to parse feature list table"); DROP_THIS_TABLE; return true; } if (!ParseScriptListTable(data + offset_script_list, length - offset_script_list, num_features)) { OTS_WARNING("faild to parse script list table"); DROP_THIS_TABLE; return true; } gsub->data = data; gsub->length = length; return true; } bool ots_gsub_should_serialise(OpenTypeFile *file) { const bool needed_tables_dropped = (file->gdef && file->gdef->data == NULL) || (file->gpos && file->gpos->data == NULL); return file->gsub != NULL && file->gsub->data != NULL && !needed_tables_dropped; } bool ots_gsub_serialise(OTSStream *out, OpenTypeFile *file) { if (!out->Write(file->gsub->data, file->gsub->length)) { return OTS_FAILURE(); } return true; } void ots_gsub_free(OpenTypeFile *file) { delete file->gsub; } } // namespace ots
mxOBS/deb-pkg_trusty_chromium-browser
third_party/ots/src/gsub.cc
C++
bsd-3-clause
19,426
<?php // autoload.php generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit518a89b59c2eb3bdea93f03672c19e1a::getLoader();
cruceo/cruceo
vendor/autoload.php
PHP
mit
182
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join the network together again - verify that getchaintips now returns two chain tips. """ from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal class GetChainTipsTest (BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 def run_test(self): tips = self.nodes[0].getchaintips() assert_equal(len(tips), 1) assert_equal(tips[0]['branchlen'], 0) assert_equal(tips[0]['height'], 200) assert_equal(tips[0]['status'], 'active') # Split the network and build two chains of different lengths. self.split_network() self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address) self.nodes[2].generatetoaddress(20, self.nodes[2].get_deterministic_priv_key().address) self.sync_all([self.nodes[:2], self.nodes[2:]]) tips = self.nodes[1].getchaintips () assert_equal (len (tips), 1) shortTip = tips[0] assert_equal (shortTip['branchlen'], 0) assert_equal (shortTip['height'], 210) assert_equal (tips[0]['status'], 'active') tips = self.nodes[3].getchaintips () assert_equal (len (tips), 1) longTip = tips[0] assert_equal (longTip['branchlen'], 0) assert_equal (longTip['height'], 220) assert_equal (tips[0]['status'], 'active') # Join the network halves and check that we now have two tips # (at least at the nodes that previously had the short chain). self.join_network () tips = self.nodes[0].getchaintips () assert_equal (len (tips), 2) assert_equal (tips[0], longTip) assert_equal (tips[1]['branchlen'], 10) assert_equal (tips[1]['status'], 'valid-fork') tips[1]['branchlen'] = 0 tips[1]['status'] = 'active' assert_equal (tips[1], shortTip) if __name__ == '__main__': GetChainTipsTest ().main ()
litecoin-project/litecoin
test/functional/rpc_getchaintips.py
Python
mit
2,291
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http.WinHttpHandlerUnitTests { public class WinHttpRequestStreamTest { public WinHttpRequestStreamTest() { TestControl.ResetAll(); } [Fact] public void CanWrite_WhenCreated_ReturnsTrue() { Stream stream = MakeRequestStream(); bool result = stream.CanWrite; Assert.True(result); } [Fact] public void CanWrite_WhenDisposed_ReturnsFalse() { Stream stream = MakeRequestStream(); stream.Dispose(); bool result = stream.CanWrite; Assert.False(result); } [Fact] public void CanSeek_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanSeek; Assert.False(result); } [Fact] public void CanRead_Always_ReturnsFalse() { Stream stream = MakeRequestStream(); bool result = stream.CanRead; Assert.False(result); } [Fact] public void Length_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Length); } [Fact] public void Length_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Length); } [Fact] public void Position_WhenCreatedDoGet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Position); } [Fact] public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position); } [Fact] public void Position_WhenCreatedDoSet_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Position = 0); } [Fact] public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Position = 0); } [Fact] public void Seek_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Seek(0, SeekOrigin.Begin)); } [Fact] public void Seek_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin)); } [Fact] public void SetLength_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.SetLength(0)); } [Fact] public void SetLength_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.SetLength(0)); } [Fact] public void Read_WhenCreated_ThrowsNotSupportedException() { Stream stream = MakeRequestStream(); Assert.Throws<NotSupportedException>(() => stream.Read(new byte[1], 0, 1)); } [Fact] public void Read_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Read(new byte[1], 0, 1)); } [Fact] public void Write_BufferIsNull_ThrowsArgumentNullException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1)); } [Fact] public void Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[1], -1, 1)); } [Fact] public void Write_CountIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[1], 0, -1)); } [Fact] public void Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => stream.Write(new byte[1], 0, 3)); } [Fact] public void Write_OffsetPlusCountMaxValueExceedsBufferLength_ThrowsArgumentException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentException>(() => stream.Write(new byte[1], int.MaxValue, int.MaxValue)); } [Fact] public void Write_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => stream.Write(new byte[1], 0, 1)); } [Fact] public void Write_NetworkFails_ThrowsIOException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.ErrorOnCompletion = true; Assert.Throws<IOException>(() => stream.Write(new byte[1], 0, 1)); } [Fact] public void Write_NoOffset_AllDataIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); stream.Write(buffer, 0, buffer.Length); byte[] serverBytes = TestServer.RequestBody; Assert.Equal(buffer, serverBytes); } [Fact] public void Write_UsingOffset_DataFromOffsetIsWritten() { Stream stream = MakeRequestStream(); string data = "Test Data"; byte[] buffer = Encoding.ASCII.GetBytes(data); int offset = 5; stream.Write(buffer, offset, buffer.Length - offset); byte[] serverBytes = TestServer.RequestBody; Assert.Equal( new ArraySegment<byte>(buffer, offset, buffer.Length - offset), new ArraySegment<byte>(serverBytes, 0, serverBytes.Length)); } [Fact] public void WriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException() { Stream stream = MakeRequestStream(); Assert.Throws<ArgumentOutOfRangeException>(() => { Task t = stream.WriteAsync(new byte[1], -1, 1); }); } [Fact] public async Task WriteAsync_NetworkFails_TaskIsFaultedWithIOException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.ErrorOnCompletion = true; await Assert.ThrowsAsync<IOException>(() => stream.WriteAsync(new byte[1], 0, 1)); } [Fact] public void WriteAsync_TokenIsAlreadyCanceled_TaskIsCanceled() { Stream stream = MakeRequestStream(); var cts = new CancellationTokenSource(); cts.Cancel(); Task t = stream.WriteAsync(new byte[1], 0, 1, cts.Token); Assert.True(t.IsCanceled); } [Fact] public void WtiteAsync_WhenDisposed_ThrowsObjectDisposedException() { Stream stream = MakeRequestStream(); stream.Dispose(); Assert.Throws<ObjectDisposedException>(() => { Task t = stream.WriteAsync(new byte[1], 0, 1); }); } [Fact] public void WriteAsync_PriorWriteInProgress_ThrowsInvalidOperationException() { Stream stream = MakeRequestStream(); TestControl.WinHttpWriteData.Pause(); Task t1 = stream.WriteAsync(new byte[1], 0, 1); Assert.Throws<InvalidOperationException>(() => { Task t2 = stream.WriteAsync(new byte[1], 0, 1); }); TestControl.WinHttpWriteData.Resume(); t1.Wait(); } internal Stream MakeRequestStream() { var state = new WinHttpRequestState(); var handle = new FakeSafeWinHttpHandle(true); handle.Callback = WinHttpRequestCallback.StaticCallbackDelegate; handle.Context = state.ToIntPtr(); state.RequestHandle = handle; return new WinHttpRequestStream(state, false); } } }
shahid-pk/corefx
src/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpRequestStreamTest.cs
C#
mit
9,576
package com.appMobi.appMobiLib; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.SimpleTimeZone; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import com.appMobi.appMobiLib.util.Debug; import android.telephony.TelephonyManager; import android.util.Log; import com.appMobi.appMobiLib.AppMobiActivity.AppInfo; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class AppMobiAnalytics extends AppMobiCommand { private static String deviceKey = null; private static final String OFFLINE = "OFFLINE"; Collection<PageEvent> events; final Object lock; static { initStoredDeviceKey(); } public AppMobiAnalytics(AppMobiActivity activity, AppMobiWebView webview){ super(activity, webview); lock = this; //load events from disk loadEvents(); new Thread("AppMobiAnalytics:constructor") { public void run() { //if there were any saved events, submit them now if( events != null && events.size() > 0 ) { if(lock==null) return; synchronized(lock) { submitEvents(); } } } }.start(); } private void saveEvents() { File eventsFile = new File(activity.baseDir(), "analytics.dat"); String json = null; json = PageEvent.toJSON(events); try { FileWriter writer = new FileWriter(eventsFile); writer.write(json); writer.flush(); writer.close(); } catch (IOException e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } } private void loadEvents() { File eventsFile = new File(activity.baseDir(), "analytics.dat"); if(eventsFile.exists()) { try { FileInputStream fis = new FileInputStream(eventsFile); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileUtils.copyInputStream(fis, baos); events = PageEvent.fromJSON(baos.toString()); if (events == null) events = new LinkedList<PageEvent>(); //remove events that are older than 30 days Date now = new Date(); ArrayList<PageEvent> toBeRemoved = new ArrayList<PageEvent>(0); for(PageEvent event:events) { long diff = now.getTime() - event.date.getTime(); if(diff/(1000*60*60*24*30) > 30) { toBeRemoved.add(event); } if(OFFLINE.equals(event.ip)) { event.ip = getIpFromServer(); } } events.removeAll(toBeRemoved); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } } else { events = new LinkedList<PageEvent>(); } } public void logPageEvent(String page, String query, String status, String method, String bytes, String userReferer) { if( !webview.config.hasAnalytics ) return; final PageEvent event = new PageEvent(page, query, status, method, bytes, userReferer); new Thread("AppMobiAnalytics:logPageEvent") { public void run() { synchronized(lock) { events.add(event); saveEvents(); submitEvents(); } } }.start(); } private void submitEvents() { if(webview!=null && webview.config != null && webview.config.analyticsUrl!=null && webview.config.analyticsUrl.length()>0) { ArrayList<PageEvent> toBeRemoved = new ArrayList<PageEvent>(0); for(PageEvent event:events) { String url = webview.config.analyticsUrl + "?Action=SendMessage&MessageBody=" + event.getPageString() + "&Version=2009-02-01"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; try { response = httpclient.execute(new HttpGet(url)); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } if(response!=null && response.getEntity()!=null) { int responseLength = (int)response.getEntity().getContentLength(); ByteArrayOutputStream baos = new ByteArrayOutputStream(responseLength>0?responseLength:1024); try { FileUtils.copyInputStream(response.getEntity().getContent(), baos); } catch (Exception e) { } if(baos.toString().indexOf("<SendMessageResponse")!=-1) { toBeRemoved.add(event); } } } events.removeAll(toBeRemoved); saveEvents(); } } private static String getIpFromServer() { String ip = null; String url = "http://services.appmobi.com/external/echoip.aspx"; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; try { response = httpclient.execute(new HttpGet(url)); } catch (Exception e) { if(Debug.isDebuggerConnected()) { Log.d("[appMobi]", e.getMessage(), e); } } // make sure we get a response and that it is only an IP -- hotel wifi accepting screen bypass if(response!=null && response.getEntity()!=null && response.getEntity().getContentLength()<16) { int responseLength = (int)response.getEntity().getContentLength(); ByteArrayOutputStream baos = new ByteArrayOutputStream(responseLength>0?responseLength:1024); try { FileUtils.copyInputStream(response.getEntity().getContent(), baos); } catch (Exception e) { } String temp = baos.toString(); if(response.getStatusLine().getStatusCode()==200 && temp.length()>0) ip = temp; } return ip==null?OFFLINE:ip; } static String getDeviceKey() { if(deviceKey==null) { initStoredDeviceKey(); } return deviceKey; } private static void initStoredDeviceKey() { final String USER_DATA = "analytics_user_data"; SharedPreferences prefs = AppMobiActivity.sharedActivity.getSharedPreferences(AppInfo.APP_PREFS, Context.MODE_PRIVATE); deviceKey = prefs.getString(USER_DATA, null); if(deviceKey==null) { String deviceid = AppMobiActivity.sharedActivity.getDeviceID(); long timestamp = System.currentTimeMillis(); deviceKey = (deviceid.hashCode() + "." + timestamp).replace(' ', '+'); SharedPreferences.Editor editor = prefs.edit(); editor.putString(USER_DATA, deviceKey); editor.commit(); } } final static class PageEvent { private String page; private String query; private String status; private String method; private String bytes; private Date date; private String dateTime; private String ip; private String userAgent; private String referer; public PageEvent() { super(); } public PageEvent(String page, String query, String status, String method, String bytes, String userReferer) { super(); this.page = page.replace(' ', '+'); this.query = query.replace(' ', '+'); this.status = status.replace(' ', '+'); this.method = method.replace(' ', '+'); this.bytes = bytes.replace(' ', '+'); //format the date for the log SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT")); format.setCalendar(cal); this.date = new Date(); this.dateTime = format.format(this.date); this.ip = getIpFromServer(); this.userAgent = ("Mozilla/5.0+(Linux;+U;+Android+" + Build.VERSION.RELEASE + //osVersion ";+en-us;+" + Build.MODEL + //device name "+Build/FRF91)+AppleWebKit/533.1+(KHTML,+like+Gecko)+Version/4.0+Mobile+Safari/533.1+(" + AppMobiAnalytics.deviceKey + ")").replace(' ', '+'); this.referer = ("http://" + AppMobiActivity.sharedActivity.configData.appName + "-" + AppMobiActivity.sharedActivity.configData.releaseName + "-" + userReferer).replace(' ', '+'); } //check if the ip is valid, if not try to get it again //return the private String getPageString() { if(this.ip == OFFLINE) { this.ip = getIpFromServer(); } String pageStr = URLEncoder.encode( (dateTime + " " + //date/time ip + " " + deviceKey + " " + //ip, userData method + " " + //method page + " " + query + " " + status + " " + //page, query, status bytes + " " + //bytes userAgent + " " + referer) ); if(Debug.isDebuggerConnected()) { Log.d("[appMobi]","logPageEvent ~~ " + pageStr); } return pageStr; } //write to json public static String toJSON(Collection<PageEvent> pageEvents) { String json = new Gson().toJson(pageEvents, new TypeToken<Collection<PageEvent>>(){}.getType()); return json; } //read from JSON public static Collection<PageEvent> fromJSON(String json) { Collection<PageEvent> pageEvents = null; pageEvents = new Gson().fromJson(json, new TypeToken<Collection<PageEvent>>(){}.getType()); return pageEvents; } } }
jasonweng/android
appMobiLib/src/com/appMobi/appMobiLib/AppMobiAnalytics.java
Java
mit
8,899
<?php /* * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com> * * 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. */ namespace JMS\Serializer; use JMS\Serializer\Metadata\ClassMetadata; use JMS\Serializer\Exception\InvalidArgumentException; use JMS\Serializer\Metadata\PropertyMetadata; abstract class GenericSerializationVisitor extends AbstractVisitor { private $navigator; private $root; private $dataStack; private $data; public function setNavigator(GraphNavigator $navigator) { $this->navigator = $navigator; $this->root = null; $this->dataStack = new \SplStack; } /** * @return GraphNavigator */ public function getNavigator() { return $this->navigator; } public function visitNull($data, array $type, Context $context) { return null; } public function visitString($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (string) $data; } public function visitBoolean($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (boolean) $data; } public function visitInteger($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (int) $data; } public function visitDouble($data, array $type, Context $context) { if (null === $this->root) { $this->root = $data; } return (float) $data; } /** * @param array $data * @param array $type */ public function visitArray($data, array $type, Context $context) { if (null === $this->root) { $this->root = array(); $rs = &$this->root; } else { $rs = array(); } foreach ($data as $k => $v) { $v = $this->navigator->accept($v, isset($type['params'][1]) ? $type['params'][1] : null, $context); if (null === $v && (!is_string($k) || !$context->shouldSerializeNull())) { continue; } $rs[$k] = $v; } return $rs; } public function startVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { if (null === $this->root) { $this->root = new \stdClass; } $this->dataStack->push($this->data); $this->data = array(); } public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context) { $rs = $this->data; $this->data = $this->dataStack->pop(); if ($this->root instanceof \stdClass && 0 === $this->dataStack->count()) { $this->root = $rs; } return $rs; } public function visitProperty(PropertyMetadata $metadata, $data, Context $context) { $v = $metadata->getValue($data); $v = $this->navigator->accept($v, $metadata->type, $context); if (null === $v && !$context->shouldSerializeNull()) { return; } $k = $this->namingStrategy->translateName($metadata); if ($metadata->inline && is_array($v)) { $this->data = array_merge($this->data, $v); } else { $this->data[$k] = $v; } } /** * Allows you to add additional data to the current object/root element. * * @param string $key * @param scalar|array $value This value must either be a regular scalar, or an array. * It must not contain any objects anymore. */ public function addData($key, $value) { if (isset($this->data[$key])) { throw new InvalidArgumentException(sprintf('There is already data for "%s".', $key)); } $this->data[$key] = $value; } public function getRoot() { return $this->root; } /** * @param array|\ArrayObject $data the passed data must be understood by whatever encoding function is applied later. */ public function setRoot($data) { $this->root = $data; } }
Akashan/DreamCommunity
vendor/jms/serializer/src/JMS/Serializer/GenericSerializationVisitor.php
PHP
mit
4,763
package im.actor.images.ops; import android.graphics.*; import im.actor.images.common.WorkCache; import static im.actor.images.ops.ImageDrawing.*; /** * Scaling images effectively with keeping good quality. * * @author Stepan ex3ndr Korshakov me@ex3ndr.com */ public class ImageScaling { /** * Scaling bitmap to fill rect with centering. Method keep aspect ratio. * * @param src source bitmap * @param w width of result * @param h height of result * @return scaled bitmap */ public static Bitmap scaleFill(Bitmap src, int w, int h) { Bitmap res = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); scaleFill(src, res); return res; } /** * Scaling src bitmap to fill dest bitmap with centering. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scaleFill(Bitmap src, Bitmap dest) { scaleFill(src, dest, CLEAR_COLOR); } /** * Scaling src bitmap to fill dest bitmap with centering. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scaleFill(Bitmap src, Bitmap dest, int clearColor) { float ratio = Math.max(dest.getWidth() / (float) src.getWidth(), dest.getHeight() / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); int paddingTop = (dest.getHeight() - (int) (src.getHeight() * ratio)) / 2; int paddingLeft = (dest.getWidth() - (int) (src.getWidth() * ratio)) / 2; scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), paddingLeft, paddingTop, newW + paddingLeft, newH + paddingTop); } /** * Scaling bitmap to fit required sizes. Method keep aspect ratio. * * @param src source bitmap * @param maxW maximum width of result bitmap * @param maxH maximum height of result bitmap * @return scaled bitmap */ public static Bitmap scaleFit(Bitmap src, int maxW, int maxH) { float ratio = Math.min(maxW / (float) src.getWidth(), maxH / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); return scale(src, newW, newH); } /** * Scaling src Bitmap to fit and cenetered in dest bitmap. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scaleFit(Bitmap src, Bitmap dest) { scaleFit(src, dest, CLEAR_COLOR); } /** * Scaling src Bitmap to fit and cenetered in dest bitmap. Method keep aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scaleFit(Bitmap src, Bitmap dest, int clearColor) { float ratio = Math.min(dest.getWidth() / (float) src.getWidth(), dest.getHeight() / (float) src.getHeight()); int newW = (int) (src.getWidth() * ratio); int newH = (int) (src.getHeight() * ratio); int paddingTop = (dest.getHeight() - (int) (src.getHeight() * ratio)) / 2; int paddingLeft = (dest.getWidth() - (int) (src.getWidth() * ratio)) / 2; scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), paddingLeft, paddingTop, newW + paddingLeft, newH + paddingTop); } /** * Scaling bitmap to specific width and height without keeping aspect ratio. * * @param src source bitmap * @param dw new width * @param dh new height * @return scaled bitmap */ public static Bitmap scale(Bitmap src, int dw, int dh) { Bitmap res = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888); scale(src, res); return res; } /** * Scaling bitmap to fill dest bitmap without keeping aspect ratio. * * @param src source bitmap * @param dest destination bitmap */ public static void scale(Bitmap src, Bitmap dest) { scale(src, dest, CLEAR_COLOR); } /** * Scaling bitmap to fill dest bitmap without keeping aspect ratio. * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing */ public static void scale(Bitmap src, Bitmap dest, int clearColor) { scale(src, dest, clearColor, 0, 0, src.getWidth(), src.getHeight(), 0, 0, dest.getWidth(), dest.getHeight()); } /** * Scaling region of bitmap to destination bitmap region * * @param src source bitmap * @param dest destination bitmap * @param x source x * @param y source y * @param sw source width * @param sh source height * @param dx destination x * @param dy destination y * @param dw destination width * @param dh destination height */ public static void scale(Bitmap src, Bitmap dest, int x, int y, int sw, int sh, int dx, int dy, int dw, int dh) { scale(src, dest, CLEAR_COLOR, x, y, sw, sh, dx, dy, dw, dh); } /** * Scaling region of bitmap to destination bitmap region * * @param src source bitmap * @param dest destination bitmap * @param clearColor color for clearing dest before drawing * @param x source x * @param y source y * @param sw source width * @param sh source height * @param dx destination x * @param dy destination y * @param dw destination width * @param dh destination height */ public static void scale(Bitmap src, Bitmap dest, int clearColor, int x, int y, int sw, int sh, int dx, int dy, int dw, int dh) { clearBitmap(dest, clearColor); Canvas canvas = new Canvas(dest); Paint paint = WorkCache.PAINT.get(); paint.setFilterBitmap(true); canvas.drawBitmap(src, new Rect(x + 1, y + 1, sw - 1, sh - 1), new Rect(dx, dy, dw, dh), paint); canvas.setBitmap(null); } protected ImageScaling() { } }
TimurTarasenko/actor-platform
actor-apps/app-android/src/main/java/im/actor/images/ops/ImageScaling.java
Java
mit
6,594
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\ResourceBundle\Controller; use FOS\RestBundle\View\View; use FOS\RestBundle\View\ViewHandler as RestViewHandler; use JMS\Serializer\SerializationContext; use PhpSpec\ObjectBehavior; use Sylius\Bundle\ResourceBundle\Controller\RequestConfiguration; use Sylius\Bundle\ResourceBundle\Controller\ViewHandler; use Sylius\Bundle\ResourceBundle\Controller\ViewHandlerInterface; use Symfony\Component\HttpFoundation\Response; /** * @mixin ViewHandler * * @author Paweł Jędrzejewski <pawel@sylius.org> */ class ViewHandlerSpec extends ObjectBehavior { function let(RestViewHandler $restViewHandler) { $this->beConstructedWith($restViewHandler); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\ResourceBundle\Controller\ViewHandler'); } function it_implements_view_handler_interface() { $this->shouldImplement(ViewHandlerInterface::class); } function it_handles_view_normally_for_html_requests( RequestConfiguration $requestConfiguration, RestViewHandler $restViewHandler, Response $response ) { $requestConfiguration->isHtmlRequest()->willReturn(true); $view = View::create(); $restViewHandler->handle($view)->willReturn($response); $this->handle($requestConfiguration, $view)->shouldReturn($response); } function it_sets_proper_values_for_non_html_requests( RequestConfiguration $requestConfiguration, RestViewHandler $restViewHandler, Response $response ) { $requestConfiguration->isHtmlRequest()->willReturn(false); $view = View::create(); $view->setSerializationContext(new SerializationContext()); $requestConfiguration->getSerializationGroups()->willReturn(['Detailed']); $requestConfiguration->getSerializationVersion()->willReturn('2.0.0'); $restViewHandler->setExclusionStrategyGroups(['Detailed'])->shouldBeCalled(); $restViewHandler->setExclusionStrategyVersion('2.0.0')->shouldBeCalled(); $restViewHandler->handle($view)->willReturn($response); $this->handle($requestConfiguration, $view)->shouldReturn($response); } }
psyray/Sylius
src/Sylius/Bundle/ResourceBundle/spec/Controller/ViewHandlerSpec.php
PHP
mit
2,449
/* * Copyright (c) 1999, 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. * * 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. * */ #ifndef SHARE_VM_CI_CISIGNATURE_HPP #define SHARE_VM_CI_CISIGNATURE_HPP #include "ci/ciClassList.hpp" #include "ci/ciSymbol.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/growableArray.hpp" // ciSignature // // This class represents the signature of a method. class ciSignature : public ResourceObj { private: ciSymbol* _symbol; ciKlass* _accessing_klass; GrowableArray<ciType*>* _types; int _size; // number of stack slots required for arguments int _count; // number of parameter types in the signature friend class ciMethod; friend class ciBytecodeStream; friend class ciObjectFactory; ciSignature(ciKlass* accessing_klass, constantPoolHandle cpool, ciSymbol* signature); ciSignature(ciKlass* accessing_klass, ciSymbol* signature, ciMethodType* method_type); void get_all_klasses(); Symbol* get_symbol() const { return _symbol->get_symbol(); } public: ciSymbol* as_symbol() const { return _symbol; } ciKlass* accessing_klass() const { return _accessing_klass; } ciType* return_type() const; ciType* type_at(int index) const; int size() const { return _size; } int count() const { return _count; } int arg_size_for_bc(Bytecodes::Code bc) { return size() + (Bytecodes::has_receiver(bc) ? 1 : 0); } bool equals(ciSignature* that); void print_signature(); void print(); }; #endif // SHARE_VM_CI_CISIGNATURE_HPP
BobZhao/HotSpotResearch
src/share/vm/ci/ciSignature.hpp
C++
gpl-2.0
2,603
/* * Copyright (c) 2013, 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. * * 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.vm.ci.code; /** * Exception thrown by the runtime in case an invalidated machine code is called. */ public final class InvalidInstalledCodeException extends Exception { private static final long serialVersionUID = -3540232440794244844L; }
mohlerm/hotspot_cached_profiles
src/jdk.vm.ci/share/classes/jdk.vm.ci.code/src/jdk/vm/ci/code/InvalidInstalledCodeException.java
Java
gpl-2.0
1,310
<?php /** * @package Joomla.UnitTest * @subpackage Twitter * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ /** * Test class for JTwitterLists. * * @package Joomla.UnitTest * @subpackage Twitter * * @since 3.1.4 */ class JTwitterListsTest extends TestCase { /** * @var JRegistry Options for the Twitter object. * @since 3.1.4 */ protected $options; /** * @var JHttp Mock client object. * @since 3.1.4 */ protected $client; /** * @var JInput The input object to use in retrieving GET/POST data. * @since 3.1.4 */ protected $input; /** * @var JTwitterLists Object under test. * @since 3.1.4 */ protected $object; /** * @var JTwitterOauth Authentication object for the Twitter object. * @since 3.1.4 */ protected $oauth; /** * @var string Sample JSON string. * @since 3.1.4 */ protected $sampleString = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; /** * @var string Sample JSON error message. * @since 3.1.4 */ protected $errorString = '{"error":"Generic error"}'; /** * @var string Sample JSON string. * @since 3.1.4 */ protected $rateLimit = '{"resources": {"lists": { "/lists/list": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/statuses": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/create": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscribers/destroy": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members/create_all": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/members": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/show": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/subscriptions": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/update": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/create": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"}, "/lists/destroy": {"remaining":15, "reset":"Mon Jun 25 17:20:53 +0000 2012"} }}}'; /** * Backup of the SERVER superglobal * * @var array * @since 3.6 */ protected $backupServer; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. * * @access protected * * @return void */ protected function setUp() { $this->backupServer = $_SERVER; $_SERVER['HTTP_HOST'] = 'example.com'; $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0'; $_SERVER['REQUEST_URI'] = '/index.php'; $_SERVER['SCRIPT_NAME'] = '/index.php'; $key = "app_key"; $secret = "app_secret"; $my_url = "http://127.0.0.1/gsoc/joomla-platform/twitter_test.php"; $access_token = array('key' => 'token_key', 'secret' => 'token_secret'); $this->options = new JRegistry; $this->input = new JInput; $this->client = $this->getMockBuilder('JHttp')->setMethods(array('get', 'post', 'delete', 'put'))->getMock(); $this->oauth = new JTwitterOAuth($this->options, $this->client, $this->input); $this->oauth->setToken($access_token); $this->object = new JTwitterLists($this->options, $this->client, $this->oauth); $this->options->set('consumer_key', $key); $this->options->set('consumer_secret', $secret); $this->options->set('callback', $my_url); $this->options->set('sendheaders', true); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. * * @return void * * @see \PHPUnit\Framework\TestCase::tearDown() * @since 3.6 */ protected function tearDown() { $_SERVER = $this->backupServer; unset($this->backupServer, $this->options, $this->input, $this->client, $this->oauth, $this->object); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedUser() { // User ID or screen name return array( array(234654235457), array('testUser'), array(null) ); } /** * Tests the getAllLists method * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser */ public function testGetLists($user) { $reverse = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getLists($user); } $data['reverse'] = true; $path = $this->object->fetchUrl('/lists/list.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getLists($user, $reverse), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getAllLists method - failure * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser * @expectedException DomainException */ public function testGetListsFailure($user) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getLists($user); } $path = $this->object->fetchUrl('/lists/list.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getLists($user); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedListStatuses() { // List ID or slug and owner return array( array(234654235457, null), array('test-list', 'testUser'), array('test-list', 12345), array('test-list', null), array(null, null) ); } /** * Tests the getListStatuses method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetStatuses($list, $owner) { $since_id = 12345; $max_id = 54321; $count = 10; $entities = true; $include_rts = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } $data['since_id'] = $since_id; $data['max_id'] = $max_id; $data['count'] = $count; $data['include_entities'] = $entities; $data['include_rts'] = $include_rts; $path = $this->object->fetchUrl('/lists/statuses.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getStatuses($list, $owner, $since_id, $max_id, $count, $entities, $include_rts), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListStatuses method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetStatusesFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getStatuses($list, $owner); } $path = $this->object->fetchUrl('/lists/statuses.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getStatuses($list, $owner); } /** * Tests the getListSubscribers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetSubscribers($list, $owner) { $cursor = 1234; $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } $data['cursor'] = $cursor; $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getSubscribers($list, $owner, $cursor, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListSubscribers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetSubscribersFailure($list, $owner) { $cursor = 1234; $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscribers($list, $owner); } $data['cursor'] = $cursor; $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getSubscribers($list, $owner, $cursor, $entities, $skip_status); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedMembers() { // List, User ID, screen name and owner. return array( array(234654235457, null, '234654235457', null), array('test-list', null, 'userTest', 'testUser'), array('test-list', '234654235457', null, '56165105642'), array('test-list', 'testUser', null, null), array('test-list', null, null, 'testUser'), array('test-list', 'testUser', '234654235457', 'userTest'), array(null, null, null, null) ); } /** * Tests the deleteListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedMembers */ public function testDeleteMembers($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/destroy_all.json'); $this->client->expects($this->once()) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->deleteMembers($list, $user_id, $screen_name, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the deleteListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedMembers * @expectedException DomainException */ public function testDeleteMembersFailure($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/destroy_all.json'); $this->client->expects($this->once()) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->deleteMembers($list, $user_id, $screen_name, $owner); } /** * Tests the subscribe method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testSubscribe($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->subscribe($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the subscribe method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testSubscribeFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->subscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->subscribe($list, $owner); } /** * Provides test data for request format detection. * * @return array * * @since 3.1.4 */ public function seedListUserOwner() { // List, User and Owner. return array( array(234654235457, '234654235457', null), array('test-list', 'userTest', 'testUser'), array('test-list', '234654235457', '56165105642'), array('test-list', 'testUser', null), array('test-list', null, 'testUser'), array(null, null, null) ); } /** * Tests the isListMember method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner */ public function testIsMember($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->isMember($list, $user, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the isListMember method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner * @expectedException DomainException */ public function testIsMemberFailure($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isMember($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->isMember($list, $user, $owner, $entities, $skip_status); } /** * Tests the isListSubscriber method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner */ public function testIsSubscriber($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->isSubscriber($list, $user, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the isListSubscriber method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $user Either an integer containing the user ID or a string containing the screen name of the user to remove. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name of the owner. * * @return void * * @since 3.1.4 * @dataProvider seedListUserOwner * @expectedException DomainException */ public function testIsSubscriberFailure($list, $user, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->isSubscriber($list, $user, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/subscribers/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->isSubscriber($list, $user, $owner, $entities, $skip_status); } /** * Tests the unsubscribe method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testUnsubscribe($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->unsubscribe($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the unsubscribe method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testUnsubscribeFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->unsubscribe($list, $owner); } $path = $this->object->fetchUrl('/lists/subscribers/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->unsubscribe($list, $owner); } /** * Tests the addListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedMembers */ public function testAddMembers($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/create_all.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->addMembers($list, $user_id, $screen_name, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the addListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param string $user_id A comma separated list of user IDs, up to 100 are allowed in a single request. * @param string $screen_name A comma separated list of screen names, up to 100 are allowed in a single request. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedMembers * @expectedException DomainException */ public function testAddMembersFailure($list, $user_id, $screen_name, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } if ($user_id) { $data['user_id'] = $user_id; } if ($screen_name) { $data['screen_name'] = $screen_name; } if ($user_id == null && $screen_name == null) { $this->setExpectedException('RuntimeException'); $this->object->addMembers($list, $user_id, $screen_name, $owner); } $path = $this->object->fetchUrl('/lists/members/create_all.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->addMembers($list, $user_id, $screen_name, $owner); } /** * Tests the getListMembers method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetMembers($list, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getMembers($list, $owner, $entities, $skip_status), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListMembers method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetMembersFailure($list, $owner) { $entities = true; $skip_status = true; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getMembers($list, $owner); } $data['include_entities'] = $entities; $data['skip_status'] = $skip_status; $path = $this->object->fetchUrl('/lists/members.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getMembers($list, $owner, $entities, $skip_status); } /** * Tests the getListById method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testGetListById($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } $path = $this->object->fetchUrl('/lists/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getListById($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getListById method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testGetListByIdFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->getListById($list, $owner); } $path = $this->object->fetchUrl('/lists/show.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getListById($list, $owner); } /** * Tests the getSubscriptions method * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser */ public function testGetSubscriptions($user) { $count = 10; $cursor = 1234; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscriptions($user); } $data['count'] = $count; $data['cursor'] = $cursor; $path = $this->object->fetchUrl('/lists/subscriptions.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->getSubscriptions($user, $count, $cursor), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the getSubscriptions method - failure * * @param mixed $user Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedUser * @expectedException DomainException */ public function testGetSubscriptionsFailure($user) { $count = 10; $cursor = 1234; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($user)) { $data['user_id'] = $user; } elseif (is_string($user)) { $data['screen_name'] = $user; } else { $this->setExpectedException('RuntimeException'); $this->object->getSubscriptions($user); } $data['count'] = $count; $data['cursor'] = $cursor; $path = $this->object->fetchUrl('/lists/subscriptions.json', $data); $this->client->expects($this->at(1)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $this->object->getSubscriptions($user, $count, $cursor); } /** * Tests the updateList method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testUpdate($list, $owner) { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/update.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->update($list, $owner, $name, $mode, $description), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the updateList method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testUpdateFailure($list, $owner) { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->update($list, $owner); } $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/update.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->update($list, $owner, $name, $mode, $description); } /** * Tests the createList method * * @return void * * @since 3.1.4 */ public function testCreate() { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->create($name, $mode, $description), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the createList method - failure * * @return void * * @since 3.1.4 * @expectedException DomainException */ public function testCreateFailure() { $name = 'test list'; $mode = 'private'; $description = 'this is a description'; $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; $data['name'] = $name; $data['mode'] = $mode; $data['description'] = $description; $path = $this->object->fetchUrl('/lists/create.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->create($name, $mode, $description); } /** * Tests the deleteList method * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses */ public function testDelete($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->sampleString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } $path = $this->object->fetchUrl('/lists/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->assertThat( $this->object->delete($list, $owner), $this->equalTo(json_decode($this->sampleString)) ); } /** * Tests the deleteList method - failure * * @param mixed $list Either an integer containing the list ID or a string containing the list slug. * @param mixed $owner Either an integer containing the user ID or a string containing the screen name. * * @return void * * @since 3.1.4 * @dataProvider seedListStatuses * @expectedException DomainException */ public function testDeleteFailure($list, $owner) { $returnData = new stdClass; $returnData->code = 200; $returnData->body = $this->rateLimit; $path = $this->object->fetchUrl('/application/rate_limit_status.json', array("resources" => "lists")); $this->client->expects($this->at(0)) ->method('get') ->with($path) ->will($this->returnValue($returnData)); $returnData = new stdClass; $returnData->code = 500; $returnData->body = $this->errorString; // Set request parameters. if (is_numeric($list)) { $data['list_id'] = $list; } elseif (is_string($list)) { $data['slug'] = $list; if (is_numeric($owner)) { $data['owner_id'] = $owner; } elseif (is_string($owner)) { $data['owner_screen_name'] = $owner; } else { // We don't have a valid entry $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } } else { $this->setExpectedException('RuntimeException'); $this->object->delete($list, $owner); } $path = $this->object->fetchUrl('/lists/destroy.json'); $this->client->expects($this->at(1)) ->method('post') ->with($path, $data) ->will($this->returnValue($returnData)); $this->object->delete($list, $owner); } }
IOC/joomla3
tests/unit/suites/libraries/joomla/twitter/JTwitterListsTest.php
PHP
gpl-2.0
59,472
<?php namespace OpenCloud\Base\Exceptions; class NetworkUrlError extends \Exception {}
paulwalker/schulteinsurance
wp-content/plugins/backwpup/sdk/OpenCloud/OpenCloud/Base/Exceptions/NetworkUrlError.php
PHP
gpl-2.0
89
/* * Copyright (c) 2000, 2013, 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 java.security.cert; import java.io.IOException; import sun.security.util.HexDumpEncoder; import sun.security.util.DerValue; /** * An immutable policy qualifier represented by the ASN.1 PolicyQualifierInfo * structure. * * <p>The ASN.1 definition is as follows: * <pre> * PolicyQualifierInfo ::= SEQUENCE { * policyQualifierId PolicyQualifierId, * qualifier ANY DEFINED BY policyQualifierId } * </pre> * <p> * A certificate policies extension, if present in an X.509 version 3 * certificate, contains a sequence of one or more policy information terms, * each of which consists of an object identifier (OID) and optional * qualifiers. In an end-entity certificate, these policy information terms * indicate the policy under which the certificate has been issued and the * purposes for which the certificate may be used. In a CA certificate, these * policy information terms limit the set of policies for certification paths * which include this certificate. * <p> * A {@code Set} of {@code PolicyQualifierInfo} objects are returned * by the {@link PolicyNode#getPolicyQualifiers PolicyNode.getPolicyQualifiers} * method. This allows applications with specific policy requirements to * process and validate each policy qualifier. Applications that need to * process policy qualifiers should explicitly set the * {@code policyQualifiersRejected} flag to false (by calling the * {@link PKIXParameters#setPolicyQualifiersRejected * PKIXParameters.setPolicyQualifiersRejected} method) before validating * a certification path. * * <p>Note that the PKIX certification path validation algorithm specifies * that any policy qualifier in a certificate policies extension that is * marked critical must be processed and validated. Otherwise the * certification path must be rejected. If the * {@code policyQualifiersRejected} flag is set to false, it is up to * the application to validate all policy qualifiers in this manner in order * to be PKIX compliant. * * <p><b>Concurrent Access</b> * * <p>All {@code PolicyQualifierInfo} objects must be immutable and * thread-safe. That is, multiple threads may concurrently invoke the * methods defined in this class on a single {@code PolicyQualifierInfo} * object (or more than one) with no ill effects. Requiring * {@code PolicyQualifierInfo} objects to be immutable and thread-safe * allows them to be passed around to various pieces of code without * worrying about coordinating access. * * @author seth proctor * @author Sean Mullan * @since 1.4 */ public class PolicyQualifierInfo { private byte [] mEncoded; private String mId; private byte [] mData; private String pqiString; /** * Creates an instance of {@code PolicyQualifierInfo} from the * encoded bytes. The encoded byte array is copied on construction. * * @param encoded a byte array containing the qualifier in DER encoding * @exception IOException thrown if the byte array does not represent a * valid and parsable policy qualifier */ public PolicyQualifierInfo(byte[] encoded) throws IOException { mEncoded = encoded.clone(); DerValue val = new DerValue(mEncoded); if (val.tag != DerValue.tag_Sequence) throw new IOException("Invalid encoding for PolicyQualifierInfo"); mId = (val.data.getDerValue()).getOID().toString(); byte [] tmp = val.data.toByteArray(); if (tmp == null) { mData = null; } else { mData = new byte[tmp.length]; System.arraycopy(tmp, 0, mData, 0, tmp.length); } } /** * Returns the {@code policyQualifierId} field of this * {@code PolicyQualifierInfo}. The {@code policyQualifierId} * is an Object Identifier (OID) represented by a set of nonnegative * integers separated by periods. * * @return the OID (never {@code null}) */ public final String getPolicyQualifierId() { return mId; } /** * Returns the ASN.1 DER encoded form of this * {@code PolicyQualifierInfo}. * * @return the ASN.1 DER encoded bytes (never {@code null}). * Note that a copy is returned, so the data is cloned each time * this method is called. */ public final byte[] getEncoded() { return mEncoded.clone(); } /** * Returns the ASN.1 DER encoded form of the {@code qualifier} * field of this {@code PolicyQualifierInfo}. * * @return the ASN.1 DER encoded bytes of the {@code qualifier} * field. Note that a copy is returned, so the data is cloned each * time this method is called. */ public final byte[] getPolicyQualifier() { return (mData == null ? null : mData.clone()); } /** * Return a printable representation of this * {@code PolicyQualifierInfo}. * * @return a {@code String} describing the contents of this * {@code PolicyQualifierInfo} */ public String toString() { if (pqiString != null) return pqiString; HexDumpEncoder enc = new HexDumpEncoder(); StringBuilder sb = new StringBuilder(); sb.append("PolicyQualifierInfo: [\n"); sb.append(" qualifierID: " + mId + "\n"); sb.append(" qualifier: " + (mData == null ? "null" : enc.encodeBuffer(mData)) + "\n"); sb.append("]"); pqiString = sb.toString(); return pqiString; } }
FauxFaux/jdk9-jdk
src/java.base/share/classes/java/security/cert/PolicyQualifierInfo.java
Java
gpl-2.0
6,754
package org.thoughtcrime.securesms.service; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.thoughtcrime.redphone.signaling.RedPhoneAccountAttributes; import org.thoughtcrime.redphone.signaling.RedPhoneAccountManager; import org.thoughtcrime.redphone.signaling.RedPhoneTrustStore; import org.thoughtcrime.securesms.BuildConfig; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.crypto.IdentityKeyUtil; import org.thoughtcrime.securesms.crypto.PreKeyUtil; import org.thoughtcrime.securesms.database.DatabaseFactory; import org.thoughtcrime.securesms.jobs.GcmRefreshJob; import org.thoughtcrime.securesms.push.TextSecureCommunicationFactory; import org.thoughtcrime.securesms.recipients.Recipient; import org.thoughtcrime.securesms.recipients.RecipientFactory; import org.thoughtcrime.securesms.util.DirectoryHelper; import org.thoughtcrime.securesms.util.TextSecurePreferences; import org.thoughtcrime.securesms.util.Util; import org.whispersystems.libaxolotl.IdentityKeyPair; import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.libaxolotl.util.KeyHelper; import org.whispersystems.libaxolotl.util.guava.Optional; import org.whispersystems.textsecure.api.TextSecureAccountManager; import org.whispersystems.textsecure.api.push.exceptions.ExpectationFailedException; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * The RegisterationService handles the process of PushService registration and verification. * If it receives an intent with a REGISTER_NUMBER_ACTION, it does the following through * an executor: * * 1) Generate secrets. * 2) Register the specified number and those secrets with the server. * 3) Wait for a challenge SMS. * 4) Verify the challenge with the server. * 5) Start the GCM registration process. * 6) Retrieve the current directory. * * The RegistrationService broadcasts its state throughout this process, and also makes its * state available through service binding. This enables a View to display progress. * * @author Moxie Marlinspike * */ public class RegistrationService extends Service { public static final String REGISTER_NUMBER_ACTION = "org.thoughtcrime.securesms.RegistrationService.REGISTER_NUMBER"; public static final String VOICE_REQUESTED_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REQUESTED"; public static final String VOICE_REGISTER_ACTION = "org.thoughtcrime.securesms.RegistrationService.VOICE_REGISTER"; public static final String NOTIFICATION_TITLE = "org.thoughtcrime.securesms.NOTIFICATION_TITLE"; public static final String NOTIFICATION_TEXT = "org.thoughtcrime.securesms.NOTIFICATION_TEXT"; public static final String CHALLENGE_EVENT = "org.thoughtcrime.securesms.CHALLENGE_EVENT"; public static final String REGISTRATION_EVENT = "org.thoughtcrime.securesms.REGISTRATION_EVENT"; public static final String CHALLENGE_EXTRA = "CAAChallenge"; private static final long REGISTRATION_TIMEOUT_MILLIS = 120000; private final ExecutorService executor = Executors.newSingleThreadExecutor(); private final Binder binder = new RegistrationServiceBinder(); private volatile RegistrationState registrationState = new RegistrationState(RegistrationState.STATE_IDLE); private volatile WeakReference<Handler> registrationStateHandler; private volatile ChallengeReceiver challengeReceiver; private String challenge; private long verificationStartTime; private boolean generatingPreKeys; @Override public int onStartCommand(final Intent intent, int flags, int startId) { if (intent != null) { executor.execute(new Runnable() { @Override public void run() { if (REGISTER_NUMBER_ACTION.equals(intent.getAction())) handleSmsRegistrationIntent(intent); else if (VOICE_REQUESTED_ACTION.equals(intent.getAction())) handleVoiceRequestedIntent(intent); else if (VOICE_REGISTER_ACTION.equals(intent.getAction())) handleVoiceRegistrationIntent(intent); } }); } return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); executor.shutdown(); shutdown(); } @Override public IBinder onBind(Intent intent) { return binder; } public void shutdown() { shutdownChallengeListener(); markAsVerifying(false); registrationState = new RegistrationState(RegistrationState.STATE_IDLE); } public synchronized int getSecondsRemaining() { long millisPassed; if (verificationStartTime == 0) millisPassed = 0; else millisPassed = System.currentTimeMillis() - verificationStartTime; return Math.max((int)(REGISTRATION_TIMEOUT_MILLIS - millisPassed) / 1000, 0); } public RegistrationState getRegistrationState() { return registrationState; } private void initializeChallengeListener() { this.challenge = null; challengeReceiver = new ChallengeReceiver(); IntentFilter filter = new IntentFilter(CHALLENGE_EVENT); registerReceiver(challengeReceiver, filter); } private synchronized void shutdownChallengeListener() { if (challengeReceiver != null) { unregisterReceiver(challengeReceiver); challengeReceiver = null; } } private void handleVoiceRequestedIntent(Intent intent) { setState(new RegistrationState(RegistrationState.STATE_VOICE_REQUESTED, intent.getStringExtra("e164number"), intent.getStringExtra("password"))); } private void handleVoiceRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); String password = intent.getStringExtra("password"); String signalingKey = intent.getStringExtra("signaling_key"); try { TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } } private void handleSmsRegistrationIntent(Intent intent) { markAsVerifying(true); String number = intent.getStringExtra("e164number"); int registrationId = TextSecurePreferences.getLocalRegistrationId(this); if (registrationId == 0) { registrationId = KeyHelper.generateRegistrationId(false); TextSecurePreferences.setLocalRegistrationId(this, registrationId); } try { String password = Util.getSecret(18); String signalingKey = Util.getSecret(52); initializeChallengeListener(); setState(new RegistrationState(RegistrationState.STATE_CONNECTING, number)); TextSecureAccountManager accountManager = TextSecureCommunicationFactory.createManager(this, number, password); accountManager.requestSmsVerificationCode(); setState(new RegistrationState(RegistrationState.STATE_VERIFYING, number)); String challenge = waitForChallenge(); accountManager.verifyAccountWithCode(challenge, signalingKey, registrationId, true); handleCommonRegistration(accountManager, number, password, signalingKey); markAsVerified(number, password, signalingKey); setState(new RegistrationState(RegistrationState.STATE_COMPLETE, number)); broadcastComplete(true); } catch (ExpectationFailedException efe) { Log.w("RegistrationService", efe); setState(new RegistrationState(RegistrationState.STATE_MULTI_REGISTERED, number)); broadcastComplete(false); } catch (UnsupportedOperationException uoe) { Log.w("RegistrationService", uoe); setState(new RegistrationState(RegistrationState.STATE_GCM_UNSUPPORTED, number)); broadcastComplete(false); } catch (AccountVerificationTimeoutException avte) { Log.w("RegistrationService", avte); setState(new RegistrationState(RegistrationState.STATE_TIMEOUT, number)); broadcastComplete(false); } catch (IOException e) { Log.w("RegistrationService", e); setState(new RegistrationState(RegistrationState.STATE_NETWORK_ERROR, number)); broadcastComplete(false); } finally { shutdownChallengeListener(); } } private void handleCommonRegistration(TextSecureAccountManager accountManager, String number, String password, String signalingKey) throws IOException { setState(new RegistrationState(RegistrationState.STATE_GENERATING_KEYS, number)); Recipient self = RecipientFactory.getRecipientsFromString(this, number, false).getPrimaryRecipient(); IdentityKeyPair identityKey = IdentityKeyUtil.getIdentityKeyPair(this); List<PreKeyRecord> records = PreKeyUtil.generatePreKeys(this); PreKeyRecord lastResort = PreKeyUtil.generateLastResortKey(this); SignedPreKeyRecord signedPreKey = PreKeyUtil.generateSignedPreKey(this, identityKey); accountManager.setPreKeys(identityKey.getPublicKey(),lastResort, signedPreKey, records); setState(new RegistrationState(RegistrationState.STATE_GCM_REGISTERING, number)); String gcmRegistrationId = GoogleCloudMessaging.getInstance(this).register(GcmRefreshJob.REGISTRATION_ID); accountManager.setGcmId(Optional.of(gcmRegistrationId)); TextSecurePreferences.setGcmRegistrationId(this, gcmRegistrationId); TextSecurePreferences.setWebsocketRegistered(this, true); DatabaseFactory.getIdentityDatabase(this).saveIdentity(self.getRecipientId(), identityKey.getPublicKey()); DirectoryHelper.refreshDirectory(this, accountManager, number); RedPhoneAccountManager redPhoneAccountManager = new RedPhoneAccountManager(BuildConfig.REDPHONE_MASTER_URL, new RedPhoneTrustStore(this), number, password); String verificationToken = accountManager.getAccountVerificationToken(); redPhoneAccountManager.createAccount(verificationToken, new RedPhoneAccountAttributes(signalingKey, gcmRegistrationId)); DirectoryRefreshListener.schedule(this); } private synchronized String waitForChallenge() throws AccountVerificationTimeoutException { this.verificationStartTime = System.currentTimeMillis(); if (this.challenge == null) { try { wait(REGISTRATION_TIMEOUT_MILLIS); } catch (InterruptedException e) { throw new IllegalArgumentException(e); } } if (this.challenge == null) throw new AccountVerificationTimeoutException(); return this.challenge; } private synchronized void challengeReceived(String challenge) { this.challenge = challenge; notifyAll(); } private void markAsVerifying(boolean verifying) { TextSecurePreferences.setVerifying(this, verifying); if (verifying) { TextSecurePreferences.setPushRegistered(this, false); } } private void markAsVerified(String number, String password, String signalingKey) { TextSecurePreferences.setVerifying(this, false); TextSecurePreferences.setPushRegistered(this, true); TextSecurePreferences.setLocalNumber(this, number); TextSecurePreferences.setPushServerPassword(this, password); TextSecurePreferences.setSignalingKey(this, signalingKey); TextSecurePreferences.setSignedPreKeyRegistered(this, true); TextSecurePreferences.setPromptedPushRegistration(this, true); } private void setState(RegistrationState state) { this.registrationState = state; Handler registrationStateHandler = this.registrationStateHandler.get(); if (registrationStateHandler != null) { registrationStateHandler.obtainMessage(state.state, state).sendToTarget(); } } private void broadcastComplete(boolean success) { Intent intent = new Intent(); intent.setAction(REGISTRATION_EVENT); if (success) { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_complete)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_successfully_completed)); } else { intent.putExtra(NOTIFICATION_TITLE, getString(R.string.RegistrationService_registration_error)); intent.putExtra(NOTIFICATION_TEXT, getString(R.string.RegistrationService_signal_registration_has_encountered_a_problem)); } this.sendOrderedBroadcast(intent, null); } public void setRegistrationStateHandler(Handler registrationStateHandler) { this.registrationStateHandler = new WeakReference<>(registrationStateHandler); } public class RegistrationServiceBinder extends Binder { public RegistrationService getService() { return RegistrationService.this; } } private class ChallengeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.w("RegistrationService", "Got a challenge broadcast..."); challengeReceived(intent.getStringExtra(CHALLENGE_EXTRA)); } } public static class RegistrationState { public static final int STATE_IDLE = 0; public static final int STATE_CONNECTING = 1; public static final int STATE_VERIFYING = 2; public static final int STATE_TIMER = 3; public static final int STATE_COMPLETE = 4; public static final int STATE_TIMEOUT = 5; public static final int STATE_NETWORK_ERROR = 6; public static final int STATE_GCM_UNSUPPORTED = 8; public static final int STATE_GCM_REGISTERING = 9; public static final int STATE_GCM_TIMEOUT = 10; public static final int STATE_VOICE_REQUESTED = 12; public static final int STATE_GENERATING_KEYS = 13; public static final int STATE_MULTI_REGISTERED = 14; public final int state; public final String number; public final String password; public RegistrationState(int state) { this(state, null); } public RegistrationState(int state, String number) { this(state, number, null); } public RegistrationState(int state, String number, String password) { this.state = state; this.number = number; this.password = password; } } }
jocelynthode/TextSecure
src/org/thoughtcrime/securesms/service/RegistrationService.java
Java
gpl-3.0
15,468
import getCompletions from "./get-completions" // Add an autosuggest completer export const addAutosuggestionCompleters = (ori, system) => (context) => { return ori(context).concat([{ getCompletions(...args) { // Add `context`, then `system` as the last args return getCompletions(...args, context, system) } }]) }
thomaxxl/safrs
swagger-editor/src/plugins/editor-autosuggest-snippets/wrap-actions.js
JavaScript
gpl-3.0
340
<?php /** * @package Mautic * @copyright 2014 Mautic Contributors. All rights reserved. * @author Mautic * @link http://mautic.org * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ echo $view->render( 'MauticFormBundle:Field:text.html.php', array( 'field' => $field, 'inForm' => (isset($inForm)) ? $inForm : false, 'type' => 'email', 'id' => $id, 'deleted' => (!empty($deleted)) ? true : false, 'formId' => (isset($formId)) ? $formId : 0, 'formName' => (isset($formName)) ? $formName : '' ) );
juliopontes/mautic
app/bundles/FormBundle/Views/Field/email.html.php
PHP
gpl-3.0
619
package loader import ( "errors" "fmt" "go/ast" "go/parser" "go/scanner" "go/token" "go/types" "log" "os" "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/go/packages" ) // Graph resolves patterns and returns packages with all the // information required to later load type information, and optionally // syntax trees. // // The provided config can set any setting with the exception of Mode. func Graph(cfg packages.Config, patterns ...string) ([]*packages.Package, error) { cfg.Mode = packages.NeedName | packages.NeedImports | packages.NeedDeps | packages.NeedExportsFile | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedTypesSizes pkgs, err := packages.Load(&cfg, patterns...) if err != nil { return nil, err } fset := token.NewFileSet() packages.Visit(pkgs, nil, func(pkg *packages.Package) { pkg.Fset = fset }) n := 0 for _, pkg := range pkgs { if len(pkg.CompiledGoFiles) == 0 && len(pkg.Errors) == 0 && pkg.PkgPath != "unsafe" { // If a package consists only of test files, then // go/packages incorrectly(?) returns an empty package for // the non-test variant. Get rid of those packages. See // #646. // // Do not, however, skip packages that have errors. Those, // too, may have no files, but we want to print the // errors. continue } pkgs[n] = pkg n++ } return pkgs[:n], nil } // LoadFromExport loads a package from export data. All of its // dependencies must have been loaded already. func LoadFromExport(pkg *packages.Package) error { pkg.IllTyped = true for path, pkg := range pkg.Imports { if pkg.Types == nil { return fmt.Errorf("dependency %q hasn't been loaded yet", path) } } if pkg.ExportFile == "" { return fmt.Errorf("no export data for %q", pkg.ID) } f, err := os.Open(pkg.ExportFile) if err != nil { return err } defer f.Close() r, err := gcexportdata.NewReader(f) if err != nil { return err } view := make(map[string]*types.Package) // view seen by gcexportdata seen := make(map[*packages.Package]bool) // all visited packages var visit func(pkgs map[string]*packages.Package) visit = func(pkgs map[string]*packages.Package) { for _, pkg := range pkgs { if !seen[pkg] { seen[pkg] = true view[pkg.PkgPath] = pkg.Types visit(pkg.Imports) } } } visit(pkg.Imports) tpkg, err := gcexportdata.Read(r, pkg.Fset, view, pkg.PkgPath) if err != nil { return err } pkg.Types = tpkg pkg.IllTyped = false return nil } // LoadFromSource loads a package from source. All of its dependencies // must have been loaded already. func LoadFromSource(pkg *packages.Package) error { pkg.IllTyped = true pkg.Types = types.NewPackage(pkg.PkgPath, pkg.Name) // OPT(dh): many packages have few files, much fewer than there // are CPU cores. Additionally, parsing each individual file is // very fast. A naive parallel implementation of this loop won't // be faster, and tends to be slower due to extra scheduling, // bookkeeping and potentially false sharing of cache lines. pkg.Syntax = make([]*ast.File, len(pkg.CompiledGoFiles)) for i, file := range pkg.CompiledGoFiles { f, err := parser.ParseFile(pkg.Fset, file, nil, parser.ParseComments) if err != nil { pkg.Errors = append(pkg.Errors, convertError(err)...) return err } pkg.Syntax[i] = f } pkg.TypesInfo = &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } importer := func(path string) (*types.Package, error) { if path == "unsafe" { return types.Unsafe, nil } if path == "C" { // go/packages doesn't tell us that cgo preprocessing // failed. When we subsequently try to parse the package, // we'll encounter the raw C import. return nil, errors.New("cgo preprocessing failed") } imp := pkg.Imports[path] if imp == nil { return nil, nil } if len(imp.Errors) > 0 { return nil, imp.Errors[0] } return imp.Types, nil } tc := &types.Config{ Importer: importerFunc(importer), Error: func(err error) { pkg.Errors = append(pkg.Errors, convertError(err)...) }, } err := types.NewChecker(tc, pkg.Fset, pkg.Types, pkg.TypesInfo).Files(pkg.Syntax) if err != nil { return err } pkg.IllTyped = false return nil } func convertError(err error) []packages.Error { var errs []packages.Error // taken from go/packages switch err := err.(type) { case packages.Error: // from driver errs = append(errs, err) case *os.PathError: // from parser errs = append(errs, packages.Error{ Pos: err.Path + ":1", Msg: err.Err.Error(), Kind: packages.ParseError, }) case scanner.ErrorList: // from parser for _, err := range err { errs = append(errs, packages.Error{ Pos: err.Pos.String(), Msg: err.Msg, Kind: packages.ParseError, }) } case types.Error: // from type checker errs = append(errs, packages.Error{ Pos: err.Fset.Position(err.Pos).String(), Msg: err.Msg, Kind: packages.TypeError, }) default: // unexpected impoverished error from parser? errs = append(errs, packages.Error{ Pos: "-", Msg: err.Error(), Kind: packages.UnknownError, }) // If you see this error message, please file a bug. log.Printf("internal error: error %q (%T) without position", err, err) } return errs } type importerFunc func(path string) (*types.Package, error) func (f importerFunc) Import(path string) (*types.Package, error) { return f(path) }
mozilla/tls-observatory
vendor/honnef.co/go/tools/loader/loader.go
GO
mpl-2.0
5,677
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * Copyright (C) 2008 WEmu Team * * 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 * 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 <http://www.gnu.org/licenses/>. */ #include "Setup.h" class ProtectingtheShipment : public QuestScript { public: void OnQuestStart(Player* mTarget, QuestLogEntry* qLogEntry) { float SSX = mTarget->GetPositionX(); float SSY = mTarget->GetPositionY(); float SSZ = mTarget->GetPositionZ(); Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 1379); if(creat == NULL) return; creat->m_escorter = mTarget; creat->GetAIInterface()->setMoveType(11); creat->GetAIInterface()->StopMovement(3000); creat->GetAIInterface()->SetAllowedToEnterCombat(false); creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Okay let's do!"); creat->SetUInt32Value(UNIT_NPC_FLAGS, 0); sEAS.CreateCustomWaypointMap(creat); sEAS.WaypointCreate(creat, -5753.780762f, -3433.290039f, 301.628387f, 4.834769f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5744.062500f, -3476.653564f, 302.269287f, 5.580896f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5674.703125f, -3543.583984f, 303.273682f, 4.775867f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5670.187500f, -3595.618164f, 311.888153f, 4.791576f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5664.515625f, -3687.601563f, 317.954590f, 4.131842f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5705.745117f, -3755.254150f, 321.452118f, 4.457779f, 0, 256, 1417); sEAS.WaypointCreate(creat, -5711.766113f, -3778.145752f, 322.827942f, 4.473486f, 0, 256, 1417); sEAS.EnableWaypoints(creat); } }; class Miran : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(Miran); Miran(Creature* pCreature) : CreatureAIScript(pCreature) {} void OnReachWP(uint32 iWaypointId, bool bForwards) { if(iWaypointId == 7) { _unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Thanks, I'm outta here!"); _unit->Despawn(5000, 1000); sEAS.DeleteWaypoints(_unit); if(_unit->m_escorter == NULL) return; Player* plr = _unit->m_escorter; _unit->m_escorter = NULL; plr->GetQuestLogForEntry(309)->SendQuestComplete(); } } }; void SetupLochModan(ScriptMgr* mgr) { mgr->register_creature_script(1379, &Miran::Create); /*mgr->register_quest_script(309, new ProtectingtheShipment());*/ }
arcemu-ng/arcemu
src/scripts/src/QuestScripts/Quest_LochModan.cpp
C++
agpl-3.0
3,075
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * * 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 * 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 <http://www.gnu.org/licenses/>. */ #include "Setup.h" enum ENCOUNTER_CREATURES { CN_SARTHARION = 28860, CN_FLAME_TSUNAMI = 30616, CN_LAVA_BLAZE = 30643, CN_CYCLON = 30648, CN_DRAKE_TENEBRON = 30452, CN_DRAKE_VESPERON = 30449, CN_DRAKE_SHADRON = 30451, }; enum SARTHARION_DATA { DRAKE_TENEBRON, DRAKE_VESPERON, DRAKE_SHADRON, BOSS_SARTHARION, OS_DATA_END = 4 }; #define SARTHARION_FLAME_BREATH HeroicInt( 56908, 58956 ) #define SARTHARION_TAIL_LASH HeroicInt( 56910, 58957 ) enum ENCOUNTER_SPELLS { // Sartharion SARTHARION_CLEAVE = 56909, SARTHARION_ENRAGE = 61632, SARTHARION_AURA = 61254, // Tsunami spells TSUNAMI = 57492, TSUNAMI_VISUAL = 57494, // Cyclon spells CYCLON_AURA = 57562, CYCLON_SPELL = 57560, // TODO: add drake spells SHADRON_AURA = 58105, TENEBRON_AURA = 61248, VESPERON_AURA = 61251, }; static Location TSUNAMI_SPAWN[] = { // Right { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f }, // Left { 3211.564697f, 505.982727f, 59.556610f, 0.000000f }, { 3214.280029f, 531.491089f, 59.168331f, 0.000000f }, { 3211.609131f, 560.359375f, 59.420803f, 0.000000f }, }; static Location TSUNAMI_MOVE[] = { // Left if right { 3211.564697f, 505.982727f, 59.556610f, 3.148659f }, { 3214.280029f, 531.491089f, 59.168331f, 3.156505f }, { 3211.609131f, 560.359375f, 59.420803f, 3.105450f }, // Right 1 if left 1 { 3283.215820f, 511.234100f, 59.288776f, 3.148659f }, { 3286.661133f, 533.317261f, 59.366989f, 3.156505f }, { 3283.311035f, 556.839611f, 59.397129f, 3.105450f } }; #define MAP_OS 615 class ObsidianSanctumScript : public MoonInstanceScript { public: uint32 m_creatureGuid[OS_DATA_END]; MOONSCRIPT_INSTANCE_FACTORY_FUNCTION(ObsidianSanctumScript, MoonInstanceScript); ObsidianSanctumScript(MapMgr* pMapMgr) : MoonInstanceScript(pMapMgr) { memset(m_creatureGuid, 0, sizeof(m_creatureGuid)); }; void OnCreaturePushToWorld(Creature* pCreature) { switch(pCreature->GetEntry()) { case CN_DRAKE_TENEBRON: m_creatureGuid[DRAKE_TENEBRON] = pCreature->GetLowGUID(); break; case CN_DRAKE_VESPERON: m_creatureGuid[DRAKE_VESPERON] = pCreature->GetLowGUID(); break; case CN_DRAKE_SHADRON: m_creatureGuid[DRAKE_SHADRON] = pCreature->GetLowGUID(); break; case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = pCreature->GetLowGUID(); break; default: break; }; }; void OnCreatureDeath(Creature* pVictim, Unit* pKiller) { switch(pVictim->GetEntry()) { case CN_SARTHARION: m_creatureGuid[BOSS_SARTHARION] = 0; break; default: break; }; }; void DoDrakeAura(uint8 pData) { uint32 pSpellEntry = 0; switch(pData) { case DRAKE_TENEBRON: pSpellEntry = TENEBRON_AURA; break; case DRAKE_SHADRON: pSpellEntry = SHADRON_AURA; break; case DRAKE_VESPERON: pSpellEntry = VESPERON_AURA; break; default: break; }; Creature* pSartharion = GetCreature(BOSS_SARTHARION); if(pSartharion == NULL) return; pSartharion->CastSpell(pSartharion, pSpellEntry, true); pSartharion->RemoveAura(pSpellEntry); // unproper hackfix }; Creature* GetCreature(uint8 pData) { if(pData >= OS_DATA_END) // impossible tho return NULL; return GetCreatureByGuid(m_creatureGuid[pData]); }; }; void SpellFunc_FlameTsunami(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI != NULL) { pCreatureAI->GetUnit()->SendChatMessage(CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, "The lava surrounding Sartharion churns!"); uint32 RandomSpeach = rand() % 4; switch(RandomSpeach) { case 0: pCreatureAI->Emote("Such flammable little insects....", Text_Yell, 14100); break; case 1: pCreatureAI->Emote("Your charred bones will litter the floor!", Text_Yell, 14101); break; case 2: pCreatureAI->Emote("How much heat can you take?", Text_Yell, 14102); break; case 3: pCreatureAI->Emote("All will be reduced to ash!", Text_Yell, 14103); break; }; uint32 RndSide = rand() % 2; Creature* Tsunami = NULL; for(int i = 0; i < 3; ++i) { switch(RndSide) { case 0: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i].x, TSUNAMI_SPAWN[i].y, TSUNAMI_SPAWN[i].z, TSUNAMI_SPAWN[i].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i].x, TSUNAMI_MOVE[i].y, TSUNAMI_MOVE[i].z, TSUNAMI_MOVE[i].o); break; case 1: Tsunami = pCreatureAI->GetUnit()->GetMapMgr()->GetInterface()->SpawnCreature(CN_FLAME_TSUNAMI, TSUNAMI_SPAWN[i + 3].x, TSUNAMI_SPAWN[i + 3].y, TSUNAMI_SPAWN[i + 3].z, TSUNAMI_SPAWN[i + 3].o, true, true, 0, 0); if(Tsunami != NULL) Tsunami->GetAIInterface()->MoveTo(TSUNAMI_MOVE[i + 3].x, TSUNAMI_MOVE[i + 3].y, TSUNAMI_MOVE[i + 3].z, TSUNAMI_MOVE[i + 3].o); }; Tsunami = NULL; }; }; }; void SpellFunc_LavaSpawn(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { if(pCreatureAI == NULL) return; for(int i = 0; i < 2; ++i) { uint32 j = rand() % 6; pCreatureAI->SpawnCreature(CN_LAVA_BLAZE, pTarget->GetPositionX() + j, pTarget->GetPositionY() + j, pTarget->GetPositionZ(), pTarget->GetOrientation(), true); }; }; class SartharionAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(SartharionAI, MoonScriptBossAI); SartharionAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { mInstance = dynamic_cast<ObsidianSanctumScript*>(GetInstanceScript()); AddSpell(SARTHARION_CLEAVE, Target_Current, 24, 0, 8); SpellDesc* mFlame = AddSpell(SARTHARION_FLAME_BREATH, Target_Self, 18, 2, 16); mFlame->AddEmote("Burn, you miserable wretches!", Text_Yell, 14098); AddSpell(SARTHARION_TAIL_LASH, Target_Self, 40, 0, 12); mFlameTsunami = AddSpellFunc(&SpellFunc_FlameTsunami, Target_Self, 99, 0, 25); mSummonLava = AddSpellFunc(&SpellFunc_LavaSpawn, Target_RandomUnitNotCurrent, 25, 0, 8); AddEmote(Event_OnTargetDied, "You will make a fine meal for the hatchlings.", Text_Yell, 14094); AddEmote(Event_OnTargetDied, "You are at a grave disadvantage!", Text_Yell, 14096); AddEmote(Event_OnTargetDied, "This is why we call you lesser beings.", Text_Yell, 14097); AddEmote(Event_OnCombatStart, "It is my charge to watch over these eggs. I will see you burn before any harm comes to them!", Text_Yell, 14093); for(int i = 0; i < OS_DATA_END - 1; i++) { m_bDrakes[i] = false; m_cDrakes[i] = NULL; } mDrakeTimer = 0; m_bEnraged = false; m_iDrakeCount = 0; }; void OnCombatStart(Unit* pTarget) { m_bEnraged = false; mFlameTsunami->TriggerCooldown(); CheckDrakes(); if(m_iDrakeCount >= 1) //HardMode! { mDrakeTimer = AddTimer(30000); ApplyAura(SARTHARION_AURA); RemoveAuraOnPlayers(SARTHARION_AURA); // unproper hackfix Regenerate();// Lets heal him as aura increase his hp for 25% }; ParentClass::OnCombatStart(pTarget); }; void AIUpdate() { if(m_iDrakeCount >= 1) { if(IsTimerFinished(mDrakeTimer)) { if(m_bDrakes[DRAKE_TENEBRON] == true) CallTenebron(); else if(m_bDrakes[DRAKE_SHADRON] == true) CallShadron(); else if(m_bDrakes[DRAKE_VESPERON] == true) CallVesperon(); ResetTimer(mDrakeTimer, 45000); }; }; if(GetHealthPercent() <= 10 && m_bEnraged == false) // enrage phase { for(uint32 i = 0; i < 3; ++i) CastSpellNowNoScheduling(mSummonLava); m_bEnraged = true; }; ParentClass::AIUpdate(); }; void CheckDrakes() { if(mInstance == NULL) return; m_iDrakeCount = 0; for(uint8 i = 0; i < (OS_DATA_END - 1); ++i) { m_cDrakes[i] = mInstance->GetCreature(i); if(m_cDrakes[i] != NULL && m_cDrakes[i]->isAlive()) { m_bDrakes[i] = true; m_iDrakeCount++; mInstance->DoDrakeAura(i); }; }; }; void CallTenebron() { if(m_cDrakes[DRAKE_TENEBRON] != NULL && m_cDrakes[DRAKE_TENEBRON]->isAlive()) { Emote("Tenebron! The eggs are yours to protect as well!", Text_Yell, 14106); m_cDrakes[DRAKE_TENEBRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_TENEBRON] = false; }; void CallShadron() { if(m_cDrakes[DRAKE_SHADRON] != NULL && m_cDrakes[DRAKE_SHADRON]->isAlive()) { Emote("Shadron! The clutch is in danger! Assist me!", Text_Yell, 14104); m_cDrakes[DRAKE_SHADRON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_SHADRON] = false; }; void CallVesperon() { if(m_cDrakes[DRAKE_VESPERON] != NULL && m_cDrakes[DRAKE_VESPERON]->isAlive()) { Emote("Vesperon! Come to me, all is at risk!", Text_Yell, 14105); m_cDrakes[DRAKE_VESPERON]->GetAIInterface()->MoveTo(3254.606689f, 531.867859f, 66.898163f, 4.215994f); }; m_bDrakes[DRAKE_VESPERON] = false; }; void OnDied(Unit* pKiller) { Emote("Such is the price... of failure...", Text_Yell, 14107); RemoveAIUpdateEvent(); ParentClass::OnDied(pKiller); }; private: bool m_bDrakes[OS_DATA_END - 1]; int32 mDrakeTimer; bool m_bEnraged; int m_iDrakeCount; ObsidianSanctumScript* mInstance; Creature* m_cDrakes[OS_DATA_END - 1]; // exclude boss SpellDesc* mFlameTsunami, *mSummonLava; }; class TsunamiAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(TsunamiAI, MoonScriptBossAI); TsunamiAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { RegisterAIUpdateEvent(1000); SetFlyMode(true); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Despawn(11500, 0); ParentClass::OnLoad(); }; void AIUpdate() { ApplyAura(TSUNAMI); ApplyAura(TSUNAMI_VISUAL); RegisterAIUpdateEvent(11000); ParentClass::OnLoad(); }; }; class CyclonAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(CyclonAI, MoonScriptBossAI); CyclonAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { SetCanMove(false); SetCanEnterCombat(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); ApplyAura(CYCLON_SPELL); ApplyAura(CYCLON_AURA); ParentClass::OnLoad(); }; }; class LavaBlazeAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(LavaBlazeAI, MoonScriptBossAI); LavaBlazeAI(Creature* pCreature) : MoonScriptBossAI(pCreature) {}; void OnLoad() { AggroNearestPlayer(1); ParentClass::OnLoad(); }; void OnCombatStop(Unit* pTarget) { Despawn(1000, 0); }; void OnDied(Unit* pKiller) { Despawn(1000, 0); }; }; void SetupTheObsidianSanctum(ScriptMgr* mgr) { ////////////////////////////////////////////////////////////////////////////////////////// ///////// Mobs ////////////////////////////////////////////////////////////////////////////////////////// ///////// Bosses mgr->register_creature_script(CN_SARTHARION, &SartharionAI::Create); mgr->register_creature_script(CN_FLAME_TSUNAMI, &TsunamiAI::Create); mgr->register_creature_script(CN_CYCLON, &CyclonAI::Create); mgr->register_creature_script(CN_LAVA_BLAZE, &LavaBlazeAI::Create); ////////////////////////////////////////////////////////////////////////////////////////// ///////// Instance mgr->register_instance_script(MAP_OS, &ObsidianSanctumScript::Create); };
sysuzhang/arcemu
src/scripts/src/InstanceScripts/Raid_TheObsidianSanctum.cpp
C++
agpl-3.0
12,532
from ..libmp.backend import xrange from .functions import defun, defun_wrapped, defun_static @defun def stieltjes(ctx, n, a=1): n = ctx.convert(n) a = ctx.convert(a) if n < 0: return ctx.bad_domain("Stieltjes constants defined for n >= 0") if hasattr(ctx, "stieltjes_cache"): stieltjes_cache = ctx.stieltjes_cache else: stieltjes_cache = ctx.stieltjes_cache = {} if a == 1: if n == 0: return +ctx.euler if n in stieltjes_cache: prec, s = stieltjes_cache[n] if prec >= ctx.prec: return +s mag = 1 def f(x): xa = x/a v = (xa-ctx.j)*ctx.ln(a-ctx.j*x)**n/(1+xa**2)/(ctx.exp(2*ctx.pi*x)-1) return ctx._re(v) / mag orig = ctx.prec try: # Normalize integrand by approx. magnitude to # speed up quadrature (which uses absolute error) if n > 50: ctx.prec = 20 mag = ctx.quad(f, [0,ctx.inf], maxdegree=3) ctx.prec = orig + 10 + int(n**0.5) s = ctx.quad(f, [0,ctx.inf], maxdegree=20) v = ctx.ln(a)**n/(2*a) - ctx.ln(a)**(n+1)/(n+1) + 2*s/a*mag finally: ctx.prec = orig if a == 1 and ctx.isint(n): stieltjes_cache[n] = (ctx.prec, v) return +v @defun_wrapped def siegeltheta(ctx, t, derivative=0): d = int(derivative) if (t == ctx.inf or t == ctx.ninf): if d < 2: if t == ctx.ninf and d == 0: return ctx.ninf return ctx.inf else: return ctx.zero if d == 0: if ctx._im(t): # XXX: cancellation occurs a = ctx.loggamma(0.25+0.5j*t) b = ctx.loggamma(0.25-0.5j*t) return -ctx.ln(ctx.pi)/2*t - 0.5j*(a-b) else: if ctx.isinf(t): return t return ctx._im(ctx.loggamma(0.25+0.5j*t)) - ctx.ln(ctx.pi)/2*t if d > 0: a = (-0.5j)**(d-1)*ctx.polygamma(d-1, 0.25-0.5j*t) b = (0.5j)**(d-1)*ctx.polygamma(d-1, 0.25+0.5j*t) if ctx._im(t): if d == 1: return -0.5*ctx.log(ctx.pi)+0.25*(a+b) else: return 0.25*(a+b) else: if d == 1: return ctx._re(-0.5*ctx.log(ctx.pi)+0.25*(a+b)) else: return ctx._re(0.25*(a+b)) @defun_wrapped def grampoint(ctx, n): # asymptotic expansion, from # http://mathworld.wolfram.com/GramPoint.html g = 2*ctx.pi*ctx.exp(1+ctx.lambertw((8*n+1)/(8*ctx.e))) return ctx.findroot(lambda t: ctx.siegeltheta(t)-ctx.pi*n, g) @defun_wrapped def siegelz(ctx, t, **kwargs): d = int(kwargs.get("derivative", 0)) t = ctx.convert(t) t1 = ctx._re(t) t2 = ctx._im(t) prec = ctx.prec try: if abs(t1) > 500*prec and t2**2 < t1: v = ctx.rs_z(t, d) if ctx._is_real_type(t): return ctx._re(v) return v except NotImplementedError: pass ctx.prec += 21 e1 = ctx.expj(ctx.siegeltheta(t)) z = ctx.zeta(0.5+ctx.j*t) if d == 0: v = e1*z ctx.prec=prec if ctx._is_real_type(t): return ctx._re(v) return +v z1 = ctx.zeta(0.5+ctx.j*t, derivative=1) theta1 = ctx.siegeltheta(t, derivative=1) if d == 1: v = ctx.j*e1*(z1+z*theta1) ctx.prec=prec if ctx._is_real_type(t): return ctx._re(v) return +v z2 = ctx.zeta(0.5+ctx.j*t, derivative=2) theta2 = ctx.siegeltheta(t, derivative=2) comb1 = theta1**2-ctx.j*theta2 if d == 2: def terms(): return [2*z1*theta1, z2, z*comb1] v = ctx.sum_accurately(terms, 1) v = -e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v ctx.prec += 10 z3 = ctx.zeta(0.5+ctx.j*t, derivative=3) theta3 = ctx.siegeltheta(t, derivative=3) comb2 = theta1**3-3*ctx.j*theta1*theta2-theta3 if d == 3: def terms(): return [3*theta1*z2, 3*z1*comb1, z3+z*comb2] v = ctx.sum_accurately(terms, 1) v = -ctx.j*e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v z4 = ctx.zeta(0.5+ctx.j*t, derivative=4) theta4 = ctx.siegeltheta(t, derivative=4) def terms(): return [theta1**4, -6*ctx.j*theta1**2*theta2, -3*theta2**2, -4*theta1*theta3, ctx.j*theta4] comb3 = ctx.sum_accurately(terms, 1) if d == 4: def terms(): return [6*theta1**2*z2, -6*ctx.j*z2*theta2, 4*theta1*z3, 4*z1*comb2, z4, z*comb3] v = ctx.sum_accurately(terms, 1) v = e1*v ctx.prec = prec if ctx._is_real_type(t): return ctx._re(v) return +v if d > 4: h = lambda x: ctx.siegelz(x, derivative=4) return ctx.diff(h, t, n=d-4) _zeta_zeros = [ 14.134725142,21.022039639,25.010857580,30.424876126,32.935061588, 37.586178159,40.918719012,43.327073281,48.005150881,49.773832478, 52.970321478,56.446247697,59.347044003,60.831778525,65.112544048, 67.079810529,69.546401711,72.067157674,75.704690699,77.144840069, 79.337375020,82.910380854,84.735492981,87.425274613,88.809111208, 92.491899271,94.651344041,95.870634228,98.831194218,101.317851006, 103.725538040,105.446623052,107.168611184,111.029535543,111.874659177, 114.320220915,116.226680321,118.790782866,121.370125002,122.946829294, 124.256818554,127.516683880,129.578704200,131.087688531,133.497737203, 134.756509753,138.116042055,139.736208952,141.123707404,143.111845808, 146.000982487,147.422765343,150.053520421,150.925257612,153.024693811, 156.112909294,157.597591818,158.849988171,161.188964138,163.030709687, 165.537069188,167.184439978,169.094515416,169.911976479,173.411536520, 174.754191523,176.441434298,178.377407776,179.916484020,182.207078484, 184.874467848,185.598783678,187.228922584,189.416158656,192.026656361, 193.079726604,195.265396680,196.876481841,198.015309676,201.264751944, 202.493594514,204.189671803,205.394697202,207.906258888,209.576509717, 211.690862595,213.347919360,214.547044783,216.169538508,219.067596349, 220.714918839,221.430705555,224.007000255,224.983324670,227.421444280, 229.337413306,231.250188700,231.987235253,233.693404179,236.524229666, ] def _load_zeta_zeros(url): import urllib d = urllib.urlopen(url) L = [float(x) for x in d.readlines()] # Sanity check assert round(L[0]) == 14 _zeta_zeros[:] = L @defun def oldzetazero(ctx, n, url='http://www.dtc.umn.edu/~odlyzko/zeta_tables/zeros1'): n = int(n) if n < 0: return ctx.zetazero(-n).conjugate() if n == 0: raise ValueError("n must be nonzero") if n > len(_zeta_zeros) and n <= 100000: _load_zeta_zeros(url) if n > len(_zeta_zeros): raise NotImplementedError("n too large for zetazeros") return ctx.mpc(0.5, ctx.findroot(ctx.siegelz, _zeta_zeros[n-1])) @defun_wrapped def riemannr(ctx, x): if x == 0: return ctx.zero # Check if a simple asymptotic estimate is accurate enough if abs(x) > 1000: a = ctx.li(x) b = 0.5*ctx.li(ctx.sqrt(x)) if abs(b) < abs(a)*ctx.eps: return a if abs(x) < 0.01: # XXX ctx.prec += int(-ctx.log(abs(x),2)) # Sum Gram's series s = t = ctx.one u = ctx.ln(x) k = 1 while abs(t) > abs(s)*ctx.eps: t = t * u / k s += t / (k * ctx._zeta_int(k+1)) k += 1 return s @defun_static def primepi(ctx, x): x = int(x) if x < 2: return 0 return len(ctx.list_primes(x)) # TODO: fix the interface wrt contexts @defun_wrapped def primepi2(ctx, x): x = int(x) if x < 2: return ctx._iv.zero if x < 2657: return ctx._iv.mpf(ctx.primepi(x)) mid = ctx.li(x) # Schoenfeld's estimate for x >= 2657, assuming RH err = ctx.sqrt(x,rounding='u')*ctx.ln(x,rounding='u')/8/ctx.pi(rounding='d') a = ctx.floor((ctx._iv.mpf(mid)-err).a, rounding='d') b = ctx.ceil((ctx._iv.mpf(mid)+err).b, rounding='u') return ctx._iv.mpf([a,b]) @defun_wrapped def primezeta(ctx, s): if ctx.isnan(s): return s if ctx.re(s) <= 0: raise ValueError("prime zeta function defined only for re(s) > 0") if s == 1: return ctx.inf if s == 0.5: return ctx.mpc(ctx.ninf, ctx.pi) r = ctx.re(s) if r > ctx.prec: return 0.5**s else: wp = ctx.prec + int(r) def terms(): orig = ctx.prec # zeta ~ 1+eps; need to set precision # to get logarithm accurately k = 0 while 1: k += 1 u = ctx.moebius(k) if not u: continue ctx.prec = wp t = u*ctx.ln(ctx.zeta(k*s))/k if not t: return #print ctx.prec, ctx.nstr(t) ctx.prec = orig yield t return ctx.sum_accurately(terms) # TODO: for bernpoly and eulerpoly, ensure that all exact zeros are covered @defun_wrapped def bernpoly(ctx, n, z): # Slow implementation: #return sum(ctx.binomial(n,k)*ctx.bernoulli(k)*z**(n-k) for k in xrange(0,n+1)) n = int(n) if n < 0: raise ValueError("Bernoulli polynomials only defined for n >= 0") if z == 0 or (z == 1 and n > 1): return ctx.bernoulli(n) if z == 0.5: return (ctx.ldexp(1,1-n)-1)*ctx.bernoulli(n) if n <= 3: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return (6*z*(z-1)+1)/6 if n == 3: return z*(z*(z-1.5)+0.5) if ctx.isinf(z): return z ** n if ctx.isnan(z): return z if abs(z) > 2: def terms(): t = ctx.one yield t r = ctx.one/z k = 1 while k <= n: t = t*(n+1-k)/k*r if not (k > 2 and k & 1): yield t*ctx.bernoulli(k) k += 1 return ctx.sum_accurately(terms) * z**n else: def terms(): yield ctx.bernoulli(n) t = ctx.one k = 1 while k <= n: t = t*(n+1-k)/k * z m = n-k if not (m > 2 and m & 1): yield t*ctx.bernoulli(m) k += 1 return ctx.sum_accurately(terms) @defun_wrapped def eulerpoly(ctx, n, z): n = int(n) if n < 0: raise ValueError("Euler polynomials only defined for n >= 0") if n <= 2: if n == 0: return z ** 0 if n == 1: return z - 0.5 if n == 2: return z*(z-1) if ctx.isinf(z): return z**n if ctx.isnan(z): return z m = n+1 if z == 0: return -2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 1: return 2*(ctx.ldexp(1,m)-1)*ctx.bernoulli(m)/m * z**0 if z == 0.5: if n % 2: return ctx.zero # Use exact code for Euler numbers if n < 100 or n*ctx.mag(0.46839865*n) < ctx.prec*0.25: return ctx.ldexp(ctx._eulernum(n), -n) # http://functions.wolfram.com/Polynomials/EulerE2/06/01/02/01/0002/ def terms(): t = ctx.one k = 0 w = ctx.ldexp(1,n+2) while 1: v = n-k+1 if not (v > 2 and v & 1): yield (2-w)*ctx.bernoulli(v)*t k += 1 if k > n: break t = t*z*(n-k+2)/k w *= 0.5 return ctx.sum_accurately(terms) / m @defun def eulernum(ctx, n, exact=False): n = int(n) if exact: return int(ctx._eulernum(n)) if n < 100: return ctx.mpf(ctx._eulernum(n)) if n % 2: return ctx.zero return ctx.ldexp(ctx.eulerpoly(n,0.5), n) # TODO: this should be implemented low-level def polylog_series(ctx, s, z): tol = +ctx.eps l = ctx.zero k = 1 zk = z while 1: term = zk / k**s l += term if abs(term) < tol: break zk *= z k += 1 return l def polylog_continuation(ctx, n, z): if n < 0: return z*0 twopij = 2j * ctx.pi a = -twopij**n/ctx.fac(n) * ctx.bernpoly(n, ctx.ln(z)/twopij) if ctx._is_real_type(z) and z < 0: a = ctx._re(a) if ctx._im(z) < 0 or (ctx._im(z) == 0 and ctx._re(z) >= 1): a -= twopij*ctx.ln(z)**(n-1)/ctx.fac(n-1) return a def polylog_unitcircle(ctx, n, z): tol = +ctx.eps if n > 1: l = ctx.zero logz = ctx.ln(z) logmz = ctx.one m = 0 while 1: if (n-m) != 1: term = ctx.zeta(n-m) * logmz / ctx.fac(m) if term and abs(term) < tol: break l += term logmz *= logz m += 1 l += ctx.ln(z)**(n-1)/ctx.fac(n-1)*(ctx.harmonic(n-1)-ctx.ln(-ctx.ln(z))) elif n < 1: # else l = ctx.fac(-n)*(-ctx.ln(z))**(n-1) logz = ctx.ln(z) logkz = ctx.one k = 0 while 1: b = ctx.bernoulli(k-n+1) if b: term = b*logkz/(ctx.fac(k)*(k-n+1)) if abs(term) < tol: break l -= term logkz *= logz k += 1 else: raise ValueError if ctx._is_real_type(z) and z < 0: l = ctx._re(l) return l def polylog_general(ctx, s, z): v = ctx.zero u = ctx.ln(z) if not abs(u) < 5: # theoretically |u| < 2*pi raise NotImplementedError("polylog for arbitrary s and z") t = 1 k = 0 while 1: term = ctx.zeta(s-k) * t if abs(term) < ctx.eps: break v += term k += 1 t *= u t /= k return ctx.gamma(1-s)*(-u)**(s-1) + v @defun_wrapped def polylog(ctx, s, z): s = ctx.convert(s) z = ctx.convert(z) if z == 1: return ctx.zeta(s) if z == -1: return -ctx.altzeta(s) if s == 0: return z/(1-z) if s == 1: return -ctx.ln(1-z) if s == -1: return z/(1-z)**2 if abs(z) <= 0.75 or (not ctx.isint(s) and abs(z) < 0.9): return polylog_series(ctx, s, z) if abs(z) >= 1.4 and ctx.isint(s): return (-1)**(s+1)*polylog_series(ctx, s, 1/z) + polylog_continuation(ctx, s, z) if ctx.isint(s): return polylog_unitcircle(ctx, int(s), z) return polylog_general(ctx, s, z) #raise NotImplementedError("polylog for arbitrary s and z") # This could perhaps be used in some cases #from quadrature import quad #return quad(lambda t: t**(s-1)/(exp(t)/z-1),[0,inf])/gamma(s) @defun_wrapped def clsin(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 1: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.im(ctx.polylog(s,a)) b = 1/a return (-0.5j)*(ctx.polylog(s,a) - ctx.polylog(s,b)) @defun_wrapped def clcos(ctx, s, z, pi=False): if ctx.isint(s) and s < 0 and int(s) % 2 == 0: return z*0 if pi: a = ctx.expjpi(z) else: a = ctx.expj(z) if ctx._is_real_type(z) and ctx._is_real_type(s): return ctx.re(ctx.polylog(s,a)) b = 1/a return 0.5*(ctx.polylog(s,a) + ctx.polylog(s,b)) @defun def altzeta(ctx, s, **kwargs): try: return ctx._altzeta(s, **kwargs) except NotImplementedError: return ctx._altzeta_generic(s) @defun_wrapped def _altzeta_generic(ctx, s): if s == 1: return ctx.ln2 + 0*s return -ctx.powm1(2, 1-s) * ctx.zeta(s) @defun def zeta(ctx, s, a=1, derivative=0, method=None, **kwargs): d = int(derivative) if a == 1 and not (d or method): try: return ctx._zeta(s, **kwargs) except NotImplementedError: pass s = ctx.convert(s) prec = ctx.prec method = kwargs.get('method') verbose = kwargs.get('verbose') if a == 1 and method != 'euler-maclaurin': im = abs(ctx._im(s)) re = abs(ctx._re(s)) #if (im < prec or method == 'borwein') and not derivative: # try: # if verbose: # print "zeta: Attempting to use the Borwein algorithm" # return ctx._zeta(s, **kwargs) # except NotImplementedError: # if verbose: # print "zeta: Could not use the Borwein algorithm" # pass if abs(im) > 500*prec and 10*re < prec and derivative <= 4 or \ method == 'riemann-siegel': try: # py2.4 compatible try block try: if verbose: print("zeta: Attempting to use the Riemann-Siegel algorithm") return ctx.rs_zeta(s, derivative, **kwargs) except NotImplementedError: if verbose: print("zeta: Could not use the Riemann-Siegel algorithm") pass finally: ctx.prec = prec if s == 1: return ctx.inf abss = abs(s) if abss == ctx.inf: if ctx.re(s) == ctx.inf: if d == 0: return ctx.one return ctx.zero return s*0 elif ctx.isnan(abss): return 1/s if ctx.re(s) > 2*ctx.prec and a == 1 and not derivative: return ctx.one + ctx.power(2, -s) return +ctx._hurwitz(s, a, d, **kwargs) @defun def _hurwitz(ctx, s, a=1, d=0, **kwargs): prec = ctx.prec verbose = kwargs.get('verbose') try: extraprec = 10 ctx.prec += extraprec # We strongly want to special-case rational a a, atype = ctx._convert_param(a) if ctx.re(s) < 0: if verbose: print("zeta: Attempting reflection formula") try: return _hurwitz_reflection(ctx, s, a, d, atype) except NotImplementedError: pass if verbose: print("zeta: Reflection formula failed") if verbose: print("zeta: Using the Euler-Maclaurin algorithm") while 1: ctx.prec = prec + extraprec T1, T2 = _hurwitz_em(ctx, s, a, d, prec+10, verbose) cancellation = ctx.mag(T1) - ctx.mag(T1+T2) if verbose: print("Term 1:", T1) print("Term 2:", T2) print("Cancellation:", cancellation, "bits") if cancellation < extraprec: return T1 + T2 else: extraprec = max(2*extraprec, min(cancellation + 5, 100*prec)) if extraprec > kwargs.get('maxprec', 100*prec): raise ctx.NoConvergence("zeta: too much cancellation") finally: ctx.prec = prec def _hurwitz_reflection(ctx, s, a, d, atype): # TODO: implement for derivatives if d != 0: raise NotImplementedError res = ctx.re(s) negs = -s # Integer reflection formula if ctx.isnpint(s): n = int(res) if n <= 0: return ctx.bernpoly(1-n, a) / (n-1) t = 1-s # We now require a to be standardized v = 0 shift = 0 b = a while ctx.re(b) > 1: b -= 1 v -= b**negs shift -= 1 while ctx.re(b) <= 0: v += b**negs b += 1 shift += 1 # Rational reflection formula if atype == 'Q' or atype == 'Z': try: p, q = a._mpq_ except: assert a == int(a) p = int(a) q = 1 p += shift*q assert 1 <= p <= q g = ctx.fsum(ctx.cospi(t/2-2*k*b)*ctx._hurwitz(t,(k,q)) \ for k in range(1,q+1)) g *= 2*ctx.gamma(t)/(2*ctx.pi*q)**t v += g return v # General reflection formula # Note: clcos/clsin can raise NotImplementedError else: C1, C2 = ctx.cospi_sinpi(0.5*t) # Clausen functions; could maybe use polylog directly if C1: C1 *= ctx.clcos(t, 2*a, pi=True) if C2: C2 *= ctx.clsin(t, 2*a, pi=True) v += 2*ctx.gamma(t)/(2*ctx.pi)**t*(C1+C2) return v def _hurwitz_em(ctx, s, a, d, prec, verbose): # May not be converted at this point a = ctx.convert(a) tol = -prec # Estimate number of terms for Euler-Maclaurin summation; could be improved M1 = 0 M2 = prec // 3 N = M2 lsum = 0 # This speeds up the recurrence for derivatives if ctx.isint(s): s = int(ctx._re(s)) s1 = s-1 while 1: # Truncated L-series l = ctx._zetasum(s, M1+a, M2-M1-1, [d])[0][0] #if d: # l = ctx.fsum((-ctx.ln(n+a))**d * (n+a)**negs for n in range(M1,M2)) #else: # l = ctx.fsum((n+a)**negs for n in range(M1,M2)) lsum += l M2a = M2+a logM2a = ctx.ln(M2a) logM2ad = logM2a**d logs = [logM2ad] logr = 1/logM2a rM2a = 1/M2a M2as = rM2a**s if d: tailsum = ctx.gammainc(d+1, s1*logM2a) / s1**(d+1) else: tailsum = 1/((s1)*(M2a)**s1) tailsum += 0.5 * logM2ad * M2as U = [1] r = M2as fact = 2 for j in range(1, N+1): # TODO: the following could perhaps be tidied a bit j2 = 2*j if j == 1: upds = [1] else: upds = [j2-2, j2-1] for m in upds: D = min(m,d+1) if m <= d: logs.append(logs[-1] * logr) Un = [0]*(D+1) for i in xrange(D): Un[i] = (1-m-s)*U[i] for i in xrange(1,D+1): Un[i] += (d-(i-1))*U[i-1] U = Un r *= rM2a t = ctx.fdot(U, logs) * r * ctx.bernoulli(j2)/(-fact) tailsum += t if ctx.mag(t) < tol: return lsum, (-1)**d * tailsum fact *= (j2+1)*(j2+2) if verbose: print("Sum range:", M1, M2, "term magnitude", ctx.mag(t), "tolerance", tol) M1, M2 = M2, M2*2 if ctx.re(s) < 0: N += N//2 @defun def _zetasum(ctx, s, a, n, derivatives=[0], reflect=False): """ Returns [xd0,xd1,...,xdr], [yd0,yd1,...ydr] where xdk = D^k ( 1/a^s + 1/(a+1)^s + ... + 1/(a+n)^s ) ydk = D^k conj( 1/a^(1-s) + 1/(a+1)^(1-s) + ... + 1/(a+n)^(1-s) ) D^k = kth derivative with respect to s, k ranges over the given list of derivatives (which should consist of either a single element or a range 0,1,...r). If reflect=False, the ydks are not computed. """ #print "zetasum", s, a, n try: return ctx._zetasum_fast(s, a, n, derivatives, reflect) except NotImplementedError: pass negs = ctx.fneg(s, exact=True) have_derivatives = derivatives != [0] have_one_derivative = len(derivatives) == 1 if not reflect: if not have_derivatives: return [ctx.fsum((a+k)**negs for k in xrange(n+1))], [] if have_one_derivative: d = derivatives[0] x = ctx.fsum(ctx.ln(a+k)**d * (a+k)**negs for k in xrange(n+1)) return [(-1)**d * x], [] maxd = max(derivatives) if not have_one_derivative: derivatives = range(maxd+1) xs = [ctx.zero for d in derivatives] if reflect: ys = [ctx.zero for d in derivatives] else: ys = [] for k in xrange(n+1): w = a + k xterm = w ** negs if reflect: yterm = ctx.conj(ctx.one / (w * xterm)) if have_derivatives: logw = -ctx.ln(w) if have_one_derivative: logw = logw ** maxd xs[0] += xterm * logw if reflect: ys[0] += yterm * logw else: t = ctx.one for d in derivatives: xs[d] += xterm * t if reflect: ys[d] += yterm * t t *= logw else: xs[0] += xterm if reflect: ys[0] += yterm return xs, ys @defun def dirichlet(ctx, s, chi=[1], derivative=0): s = ctx.convert(s) q = len(chi) d = int(derivative) if d > 2: raise NotImplementedError("arbitrary order derivatives") prec = ctx.prec try: ctx.prec += 10 if s == 1: have_pole = True for x in chi: if x and x != 1: have_pole = False h = +ctx.eps ctx.prec *= 2*(d+1) s += h if have_pole: return +ctx.inf z = ctx.zero for p in range(1,q+1): if chi[p%q]: if d == 1: z += chi[p%q] * (ctx.zeta(s, (p,q), 1) - \ ctx.zeta(s, (p,q))*ctx.log(q)) else: z += chi[p%q] * ctx.zeta(s, (p,q)) z /= q**s finally: ctx.prec = prec return +z def secondzeta_main_term(ctx, s, a, **kwargs): tol = ctx.eps f = lambda n: ctx.gammainc(0.5*s, a*gamm**2, regularized=True)*gamm**(-s) totsum = term = ctx.zero mg = ctx.inf n = 0 while mg > tol: totsum += term n += 1 gamm = ctx.im(ctx.zetazero_memoized(n)) term = f(n) mg = abs(term) err = 0 if kwargs.get("error"): sg = ctx.re(s) err = 0.5*ctx.pi**(-1)*max(1,sg)*a**(sg-0.5)*ctx.log(gamm/(2*ctx.pi))*\ ctx.gammainc(-0.5, a*gamm**2)/abs(ctx.gamma(s/2)) err = abs(err) return +totsum, err, n def secondzeta_prime_term(ctx, s, a, **kwargs): tol = ctx.eps f = lambda n: ctx.gammainc(0.5*(1-s),0.25*ctx.log(n)**2 * a**(-1))*\ ((0.5*ctx.log(n))**(s-1))*ctx.mangoldt(n)/ctx.sqrt(n)/\ (2*ctx.gamma(0.5*s)*ctx.sqrt(ctx.pi)) totsum = term = ctx.zero mg = ctx.inf n = 1 while mg > tol or n < 9: totsum += term n += 1 term = f(n) if term == 0: mg = ctx.inf else: mg = abs(term) if kwargs.get("error"): err = mg return +totsum, err, n def secondzeta_exp_term(ctx, s, a): if ctx.isint(s) and ctx.re(s) <= 0: m = int(round(ctx.re(s))) if not m & 1: return ctx.mpf('-0.25')**(-m//2) tol = ctx.eps f = lambda n: (0.25*a)**n/((n+0.5*s)*ctx.fac(n)) totsum = ctx.zero term = f(0) mg = ctx.inf n = 0 while mg > tol: totsum += term n += 1 term = f(n) mg = abs(term) v = a**(0.5*s)*totsum/ctx.gamma(0.5*s) return v def secondzeta_singular_term(ctx, s, a, **kwargs): factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) extraprec = ctx.mag(factor) ctx.prec += extraprec factor = a**(0.5*(s-1))/(4*ctx.sqrt(ctx.pi)*ctx.gamma(0.5*s)) tol = ctx.eps f = lambda n: ctx.bernpoly(n,0.75)*(4*ctx.sqrt(a))**n*\ ctx.gamma(0.5*n)/((s+n-1)*ctx.fac(n)) totsum = ctx.zero mg1 = ctx.inf n = 1 term = f(n) mg2 = abs(term) while mg2 > tol and mg2 <= mg1: totsum += term n += 1 term = f(n) totsum += term n +=1 term = f(n) mg1 = mg2 mg2 = abs(term) totsum += term pole = -2*(s-1)**(-2)+(ctx.euler+ctx.log(16*ctx.pi**2*a))*(s-1)**(-1) st = factor*(pole+totsum) err = 0 if kwargs.get("error"): if not ((mg2 > tol) and (mg2 <= mg1)): if mg2 <= tol: err = ctx.mpf(10)**int(ctx.log(abs(factor*tol),10)) if mg2 > mg1: err = ctx.mpf(10)**int(ctx.log(abs(factor*mg1),10)) err = max(err, ctx.eps*1.) ctx.prec -= extraprec return +st, err @defun def secondzeta(ctx, s, a = 0.015, **kwargs): r""" Evaluates the secondary zeta function `Z(s)`, defined for `\mathrm{Re}(s)>1` by .. math :: Z(s) = \sum_{n=1}^{\infty} \frac{1}{\tau_n^s} where `\frac12+i\tau_n` runs through the zeros of `\zeta(s)` with imaginary part positive. `Z(s)` extends to a meromorphic function on `\mathbb{C}` with a double pole at `s=1` and simple poles at the points `-2n` for `n=0`, 1, 2, ... **Examples** >>> from mpmath import * >>> mp.pretty = True; mp.dps = 15 >>> secondzeta(2) 0.023104993115419 >>> xi = lambda s: 0.5*s*(s-1)*pi**(-0.5*s)*gamma(0.5*s)*zeta(s) >>> Xi = lambda t: xi(0.5+t*j) >>> -0.5*diff(Xi,0,n=2)/Xi(0) (0.023104993115419 + 0.0j) We may ask for an approximate error value:: >>> secondzeta(0.5+100j, error=True) ((-0.216272011276718 - 0.844952708937228j), 2.22044604925031e-16) The function has poles at the negative odd integers, and dyadic rational values at the negative even integers:: >>> mp.dps = 30 >>> secondzeta(-8) -0.67236328125 >>> secondzeta(-7) +inf **Implementation notes** The function is computed as sum of four terms `Z(s)=A(s)-P(s)+E(s)-S(s)` respectively main, prime, exponential and singular terms. The main term `A(s)` is computed from the zeros of zeta. The prime term depends on the von Mangoldt function. The singular term is responsible for the poles of the function. The four terms depends on a small parameter `a`. We may change the value of `a`. Theoretically this has no effect on the sum of the four terms, but in practice may be important. A smaller value of the parameter `a` makes `A(s)` depend on a smaller number of zeros of zeta, but `P(s)` uses more values of von Mangoldt function. We may also add a verbose option to obtain data about the values of the four terms. >>> mp.dps = 10 >>> secondzeta(0.5 + 40j, error=True, verbose=True) main term = (-30190318549.138656312556 - 13964804384.624622876523j) computed using 19 zeros of zeta prime term = (132717176.89212754625045 + 188980555.17563978290601j) computed using 9 values of the von Mangoldt function exponential term = (542447428666.07179812536 + 362434922978.80192435203j) singular term = (512124392939.98154322355 + 348281138038.65531023921j) ((0.059471043 + 0.3463514534j), 1.455191523e-11) >>> secondzeta(0.5 + 40j, a=0.04, error=True, verbose=True) main term = (-151962888.19606243907725 - 217930683.90210294051982j) computed using 9 zeros of zeta prime term = (2476659342.3038722372461 + 28711581821.921627163136j) computed using 37 values of the von Mangoldt function exponential term = (178506047114.7838188264 + 819674143244.45677330576j) singular term = (175877424884.22441310708 + 790744630738.28669174871j) ((0.059471043 + 0.3463514534j), 1.455191523e-11) Notice the great cancellation between the four terms. Changing `a`, the four terms are very different numbers but the cancellation gives the good value of Z(s). **References** A. Voros, Zeta functions for the Riemann zeros, Ann. Institute Fourier, 53, (2003) 665--699. A. Voros, Zeta functions over Zeros of Zeta Functions, Lecture Notes of the Unione Matematica Italiana, Springer, 2009. """ s = ctx.convert(s) a = ctx.convert(a) tol = ctx.eps if ctx.isint(s) and ctx.re(s) <= 1: if abs(s-1) < tol*1000: return ctx.inf m = int(round(ctx.re(s))) if m & 1: return ctx.inf else: return ((-1)**(-m//2)*\ ctx.fraction(8-ctx.eulernum(-m,exact=True),2**(-m+3))) prec = ctx.prec try: t3 = secondzeta_exp_term(ctx, s, a) extraprec = max(ctx.mag(t3),0) ctx.prec += extraprec + 3 t1, r1, gt = secondzeta_main_term(ctx,s,a,error='True', verbose='True') t2, r2, pt = secondzeta_prime_term(ctx,s,a,error='True', verbose='True') t4, r4 = secondzeta_singular_term(ctx,s,a,error='True') t3 = secondzeta_exp_term(ctx, s, a) err = r1+r2+r4 t = t1-t2+t3-t4 if kwargs.get("verbose"): print('main term =', t1) print(' computed using', gt, 'zeros of zeta') print('prime term =', t2) print(' computed using', pt, 'values of the von Mangoldt function') print('exponential term =', t3) print('singular term =', t4) finally: ctx.prec = prec if kwargs.get("error"): w = max(ctx.mag(abs(t)),0) err = max(err*2**w, ctx.eps*1.*2**w) return +t, err return +t @defun_wrapped def lerchphi(ctx, z, s, a): r""" Gives the Lerch transcendent, defined for `|z| < 1` and `\Re{a} > 0` by .. math :: \Phi(z,s,a) = \sum_{k=0}^{\infty} \frac{z^k}{(a+k)^s} and generally by the recurrence `\Phi(z,s,a) = z \Phi(z,s,a+1) + a^{-s}` along with the integral representation valid for `\Re{a} > 0` .. math :: \Phi(z,s,a) = \frac{1}{2 a^s} + \int_0^{\infty} \frac{z^t}{(a+t)^s} dt - 2 \int_0^{\infty} \frac{\sin(t \log z - s \operatorname{arctan}(t/a)}{(a^2 + t^2)^{s/2} (e^{2 \pi t}-1)} dt. The Lerch transcendent generalizes the Hurwitz zeta function :func:`zeta` (`z = 1`) and the polylogarithm :func:`polylog` (`a = 1`). **Examples** Several evaluations in terms of simpler functions:: >>> from mpmath import * >>> mp.dps = 25; mp.pretty = True >>> lerchphi(-1,2,0.5); 4*catalan 3.663862376708876060218414 3.663862376708876060218414 >>> diff(lerchphi, (-1,-2,1), (0,1,0)); 7*zeta(3)/(4*pi**2) 0.2131391994087528954617607 0.2131391994087528954617607 >>> lerchphi(-4,1,1); log(5)/4 0.4023594781085250936501898 0.4023594781085250936501898 >>> lerchphi(-3+2j,1,0.5); 2*atanh(sqrt(-3+2j))/sqrt(-3+2j) (1.142423447120257137774002 + 0.2118232380980201350495795j) (1.142423447120257137774002 + 0.2118232380980201350495795j) Evaluation works for complex arguments and `|z| \ge 1`:: >>> lerchphi(1+2j, 3-j, 4+2j) (0.002025009957009908600539469 + 0.003327897536813558807438089j) >>> lerchphi(-2,2,-2.5) -12.28676272353094275265944 >>> lerchphi(10,10,10) (-4.462130727102185701817349e-11 + 1.575172198981096218823481e-12j) >>> lerchphi(10,10,-10.5) (112658784011940.5605789002 + 498113185.5756221777743631j) Some degenerate cases:: >>> lerchphi(0,1,2) 0.5 >>> lerchphi(0,1,-2) -0.5 **References** 1. [DLMF]_ section 25.14 """ if z == 0: return a ** (-s) """ # Faster, but these cases are useful for testing right now if z == 1: return ctx.zeta(s, a) if a == 1: return z * ctx.polylog(s, z) """ if ctx.re(a) < 1: if ctx.isnpint(a): raise ValueError("Lerch transcendent complex infinity") m = int(ctx.ceil(1-ctx.re(a))) v = ctx.zero zpow = ctx.one for n in xrange(m): v += zpow / (a+n)**s zpow *= z return zpow * ctx.lerchphi(z,s, a+m) + v g = ctx.ln(z) v = 1/(2*a**s) + ctx.gammainc(1-s, -a*g) * (-g)**(s-1) / z**a h = s / 2 r = 2*ctx.pi f = lambda t: ctx.sin(s*ctx.atan(t/a)-t*g) / \ ((a**2+t**2)**h * ctx.expm1(r*t)) v += 2*ctx.quad(f, [0, ctx.inf]) if not ctx.im(z) and not ctx.im(s) and not ctx.im(a) and ctx.re(z) < 1: v = ctx.chop(v) return v
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/sympy/mpmath/functions/zeta.py
Python
agpl-3.0
35,983
// Accord Math Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // // The source code presented in this file has been adapted from LibSVM - // A Library for Support Vector Machines, created by Chih-Chung Chang and // Chih-Jen Lin. Original license is given below. // // Copyright (c) 2000-2014 Chih-Chung Chang and Chih-Jen Lin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither name of copyright holders nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. // namespace Accord.Math.Optimization { using System; using System.Diagnostics; /// <summary> /// General Sequential Minimal Optimization algorithm for Quadratic Programming problems. /// </summary> /// /// <remarks> /// <para> /// This class implements the same optimization method found in LibSVM. It can be used /// to solve quadratic programming problems where the quadratic matrix Q may be too large /// to fit in memory.</para> /// /// <para> /// The method is described in Fan et al., JMLR 6(2005), p. 1889--1918. It solves the /// minimization problem:</para> /// /// <code> /// min 0.5(\alpha^T Q \alpha) + p^T \alpha /// /// y^T \alpha = \delta /// y_i = +1 or -1 /// 0 &lt;= alpha_i &lt;= C_i /// </code> /// /// <para> /// Given Q, p, y, C, and an initial feasible point \alpha, where l is /// the size of vectors and matrices and eps is the stopping tolerance. /// </para> /// </remarks> /// public class FanChenLinQuadraticOptimization : IOptimizationMethod { const double TAU = 1e-12; int active_size; int[] y; double[] G; // gradient of objective function enum Status { LOWER_BOUND, UPPER_BOUND, FREE }; Status[] alpha_status; double[] alpha; Func<int, int, double> Q; double[] QD; // diagonal double eps = 0.001; double[] C; double[] p; int[] active_set; int[] indices; double[] G_bar; // gradient, if we treat free variables as 0 int l; bool unshrink; bool shrinking; double rho; double obj; /// <summary> /// Gets the number of variables (free parameters) in the optimization /// problem. In a SVM learning problem, this is the number of samples in /// the learning dataset. /// </summary> /// /// <value> /// The number of parameters for the optimization problem. /// </value> /// public int NumberOfVariables { get { return l; } } /// <summary> /// Gets the current solution found, the values of /// the parameters which optimizes the function. /// </summary> /// public double[] Solution { get { return alpha; } set { alpha = value; } } /// <summary> /// Gets the output of the function at the current <see cref="Solution" />. /// </summary> /// public double Value { get { return obj; } } /// <summary> /// Gets the threshold (bias) value for a SVM trained using this method. /// </summary> /// public double Rho { get { return rho; } } /// <summary> /// Gets or sets the precision tolerance before /// the method stops. Default is 0.001. /// </summary> /// public double Tolerance { get { return eps; } set { eps = value; } } /// <summary> /// Gets or sets a value indicating whether shrinking /// heuristics should be used. /// </summary> /// /// <value> /// <c>true</c> to use shrinking heuristics; otherwise, <c>false</c>. /// </value> /// public bool Shrinking { get { return shrinking; } set { shrinking = value; } } /// <summary> /// Gets the upper bounds for the optimization problem. In /// a SVM learning problem, this would be the capacity limit /// for each Lagrange multiplier (alpha) in the machine. The /// default is to use a vector filled with 1's. /// </summary> /// public double[] UpperBounds { get { return C; } } /// <summary> /// Initializes a new instance of the <see cref="FanChenLinQuadraticOptimization"/> class. /// </summary> /// /// <param name="numberOfVariables">The number of free parameters in the optimization problem.</param> /// <param name="Q"> /// The quadratic matrix Q. It should be specified as a lambda /// function so Q doesn't need to be always kept in memory.</param> /// public FanChenLinQuadraticOptimization(int numberOfVariables, Func<int, int, double> Q) { var zeros = new double[numberOfVariables]; var ones = new int[numberOfVariables]; for (int i = 0; i < ones.Length; i++) ones[i] = 1; initialize(numberOfVariables, Q, zeros, ones); } /// <summary> /// Initializes a new instance of the <see cref="FanChenLinQuadraticOptimization"/> class. /// </summary> /// /// <param name="numberOfVariables">The number of free parameters in the optimization problem.</param> /// <param name="Q"> /// The quadratic matrix Q. It should be specified as a lambda /// function so Q doesn't need to be always kept in memory.</param> /// <param name="p">The vector of linear terms p. Default is a zero vector.</param> /// <param name="y">The class labels y. Default is a unit vector.</param> /// public FanChenLinQuadraticOptimization(int numberOfVariables, Func<int, int, double> Q, double[] p, int[] y) { initialize(numberOfVariables, Q, p, y); } private void initialize(int numberOfVariables, Func<int, int, double> Q, double[] p, int[] y) { this.l = numberOfVariables; this.Q = Q; this.C = new double[l]; this.indices = new int[l]; this.alpha_status = new Status[l]; this.active_set = new int[l]; this.G = new double[l]; this.G_bar = new double[l]; this.p = p; this.y = y; this.alpha = new double[l]; for (int i = 0; i < C.Length; i++) C[i] = 1.0; } /// <summary> /// Finds the minimum value of a function. The solution vector /// will be made available at the <see cref="Solution" /> property. /// </summary> /// /// <returns> /// Returns <c>true</c> if the method converged to a <see cref="Solution" />. /// In this case, the found value will also be available at the <see cref="Value" /> /// property. /// </returns> /// public bool Minimize() { QD = new double[l]; for (int k = 0; k < QD.Length; k++) QD[k] = Q(k, k); unshrink = false; double[] Q_i = new double[l]; double[] Q_j = new double[l]; // initialize alpha_status { for (int i = 0; i < l; i++) update_alpha_status(i); } // initialize active set (for shrinking) { for (int i = 0; i < l; i++) active_set[i] = i; active_size = l; } // initialize index lookup vector { for (int i = 0; i < indices.Length; i++) indices[i] = i; } // initialize gradient { for (int i = 0; i < l; i++) { G[i] = p[i]; G_bar[i] = 0; } for (int i = 0; i < l; i++) { if (!is_lower_bound(i)) { row(i, l, Q_i); double alpha_i = alpha[i]; for (int j = 0; j < l; j++) G[j] += alpha_i * Q_i[j]; if (is_upper_bound(i)) { for (int j = 0; j < l; j++) G_bar[j] += C[i] * Q_i[j]; } } } } // optimization step int iter = 0; int max_iter = Math.Max(10000000, l > int.MaxValue / 100 ? int.MaxValue : 100 * l); int counter = Math.Min(l, 1000) + 1; while (iter < max_iter) { // show progress and do shrinking if (--counter == 0) { counter = Math.Min(l, 1000); if (shrinking) do_shrinking(); Trace.WriteLine("."); } int i = 0, j = 0; if (select_working_set(ref i, ref j) != 0) { // reconstruct the whole gradient reconstruct_gradient(); // reset active set size and check active_size = l; Trace.WriteLine("*"); if (select_working_set(ref i, ref j) != 0) { break; } else { counter = 1; // do shrinking next iteration } } ++iter; // update alpha[i] and alpha[j], handle bounds carefully row(i, active_size, Q_i); row(j, active_size, Q_j); double C_i = C[i]; double C_j = C[j]; double old_alpha_i = alpha[i]; double old_alpha_j = alpha[j]; if (y[i] != y[j]) { double quad_coef = QD[i] + QD[j] + 2 * Q_i[j]; if (quad_coef <= 0) quad_coef = TAU; double delta = (-G[i] - G[j]) / quad_coef; double diff = alpha[i] - alpha[j]; alpha[i] += delta; alpha[j] += delta; if (diff > 0) { if (alpha[j] < 0) { alpha[j] = 0; alpha[i] = diff; } } else { if (alpha[i] < 0) { alpha[i] = 0; alpha[j] = -diff; } } if (diff > C_i - C_j) { if (alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = C_i - diff; } } else { if (alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = C_j + diff; } } } else { double quad_coef = QD[i] + QD[j] - 2 * Q_i[j]; if (quad_coef <= 0) quad_coef = TAU; double delta = (G[i] - G[j]) / quad_coef; double sum = alpha[i] + alpha[j]; alpha[i] -= delta; alpha[j] += delta; if (sum > C_i) { if (alpha[i] > C_i) { alpha[i] = C_i; alpha[j] = sum - C_i; } } else { if (alpha[j] < 0) { alpha[j] = 0; alpha[i] = sum; } } if (sum > C_j) { if (alpha[j] > C_j) { alpha[j] = C_j; alpha[i] = sum - C_j; } } else { if (alpha[i] < 0) { alpha[i] = 0; alpha[j] = sum; } } } // update G double delta_alpha_i = alpha[i] - old_alpha_i; double delta_alpha_j = alpha[j] - old_alpha_j; for (int k = 0; k < active_size; k++) { G[k] += Q_i[k] * delta_alpha_i + Q_j[k] * delta_alpha_j; } // update alpha_status and G_bar { bool ui = is_upper_bound(i); bool uj = is_upper_bound(j); update_alpha_status(i); update_alpha_status(j); if (ui != is_upper_bound(i)) { row(i, l, Q_i); if (ui) { for (int k = 0; k < l; k++) G_bar[k] -= C_i * Q_i[k]; } else { for (int k = 0; k < l; k++) G_bar[k] += C_i * Q_i[k]; } } if (uj != is_upper_bound(j)) { row(j, l, Q_j); if (uj) { for (int k = 0; k < l; k++) G_bar[k] -= C_j * Q_j[k]; } else { for (int k = 0; k < l; k++) G_bar[k] += C_j * Q_j[k]; } } } } if (iter >= max_iter) { if (active_size < l) { // reconstruct the whole gradient to calculate objective value reconstruct_gradient(); active_size = l; Trace.WriteLine("*"); } Trace.WriteLine("WARNING: reaching max number of iterations"); } // calculate rho rho = calculate_rho(); // calculate objective value { double v = 0; for (int i = 0; i < l; i++) v += alpha[i] * (G[i] + p[i]); obj = v / 2; } // put back the solution { var solution = (double[])alpha.Clone(); Array.Clear(alpha, 0, alpha.Length); for (int i = 0; i < l; i++) alpha[active_set[i]] = solution[i]; } // juggle everything back /*{ for(int i=0;i<l;i++) while(active_set[i] != i) swap_index(i,active_set[i]); // or Q.swap_index(i,active_set[i]); }*/ Trace.WriteLine("optimization finished, #iter = " + iter); return (iter < max_iter); } /// <summary> /// Not supported. /// </summary> /// public bool Maximize() { throw new NotSupportedException(); } void update_alpha_status(int i) { if (alpha[i] >= C[i]) alpha_status[i] = Status.UPPER_BOUND; else if (alpha[i] <= 0) alpha_status[i] = Status.LOWER_BOUND; else alpha_status[i] = Status.FREE; } bool is_upper_bound(int i) { return alpha_status[i] == Status.UPPER_BOUND; } bool is_lower_bound(int i) { return alpha_status[i] == Status.LOWER_BOUND; } bool is_free(int i) { return alpha_status[i] == Status.FREE; } void reconstruct_gradient() { // reconstruct inactive elements of G from G_bar and free variables if (active_size == l) return; int nr_free = 0; for (int j = active_size; j < l; j++) G[j] = G_bar[j] + p[j]; for (int j = 0; j < active_size; j++) if (is_free(j)) nr_free++; if (2 * nr_free < active_size) Trace.WriteLine("WARNING: using -h 0 may be faster"); if (nr_free * l > 2 * active_size * (l - active_size)) { for (int i = active_size; i < l; i++) { int ii = indices[i]; for (int j = 0; j < active_size; j++) { if (is_free(j)) G[i] += alpha[j] * Q(ii, indices[j]); } } } else { for (int i = 0; i < active_size; i++) { if (is_free(i)) { int ii = indices[i]; double alpha_i = alpha[i]; for (int j = active_size; j < l; j++) G[j] += alpha_i * Q(ii, indices[j]); } } } } // return 1 if already optimal, return 0 otherwise int select_working_set(ref int out_i, ref int out_j) { // return i,j such that // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha) // j: minimizes the decrease of obj value // (if quadratic coefficient <= 0, replace it with tau) // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha) double Gmax = Double.NegativeInfinity; double Gmax2 = Double.NegativeInfinity; int Gmax_idx = -1; int Gmin_idx = -1; double obj_diff_min = Double.PositiveInfinity; for (int t = 0; t < active_size; t++) { if (y[t] == +1) { if (!is_upper_bound(t)) { if (-G[t] >= Gmax) { Gmax = -G[t]; Gmax_idx = t; } } } else { if (!is_lower_bound(t)) { if (G[t] >= Gmax) { Gmax = G[t]; Gmax_idx = t; } } } } int i = Gmax_idx; double[] Q_i = null; if (i != -1) { Q_i = new double[active_size]; row(i, active_size, Q_i); // NULL Q_i not accessed: Gmax=-INF if i=-1 } for (int j = 0; j < active_size; j++) { if (y[j] == +1) { if (!is_lower_bound(j)) { double grad_diff = Gmax + G[j]; if (G[j] >= Gmax2) Gmax2 = G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i] + QD[j] - 2.0 * y[i] * Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = -(grad_diff * grad_diff) / TAU; if (obj_diff <= obj_diff_min) { Gmin_idx = j; obj_diff_min = obj_diff; } } } } else { if (!is_upper_bound(j)) { double grad_diff = Gmax - G[j]; if (-G[j] >= Gmax2) Gmax2 = -G[j]; if (grad_diff > 0) { double obj_diff; double quad_coef = QD[i] + QD[j] + 2.0 * y[i] * Q_i[j]; if (quad_coef > 0) obj_diff = -(grad_diff * grad_diff) / quad_coef; else obj_diff = -(grad_diff * grad_diff) / TAU; if (obj_diff <= obj_diff_min) { Gmin_idx = j; obj_diff_min = obj_diff; } } } } } if (Gmax + Gmax2 < eps) return 1; out_i = Gmax_idx; out_j = Gmin_idx; return 0; } double calculate_rho() { double r; int nr_free = 0; double ub = Double.PositiveInfinity; double lb = Double.NegativeInfinity; double sum_free = 0; for (int i = 0; i < active_size; i++) { double yG = y[i] * G[i]; if (is_upper_bound(i)) { if (y[i] == -1) ub = Math.Min(ub, yG); else lb = Math.Max(lb, yG); } else if (is_lower_bound(i)) { if (y[i] == +1) ub = Math.Min(ub, yG); else lb = Math.Max(lb, yG); } else { ++nr_free; sum_free += yG; } } if (nr_free > 0) r = sum_free / nr_free; else r = (ub + lb) / 2; return r; } void do_shrinking() { double Gmax1 = Double.NegativeInfinity; // max { -y_i * grad(f)_i | i in I_up(\alpha) } double Gmax2 = Double.NegativeInfinity; // max { y_i * grad(f)_i | i in I_low(\alpha) } // find maximal violating pair first for (int i = 0; i < active_size; i++) { if (y[i] == +1) { if (!is_upper_bound(i)) { if (-G[i] >= Gmax1) Gmax1 = -G[i]; } if (!is_lower_bound(i)) { if (G[i] >= Gmax2) Gmax2 = G[i]; } } else { if (!is_upper_bound(i)) { if (-G[i] >= Gmax2) Gmax2 = -G[i]; } if (!is_lower_bound(i)) { if (G[i] >= Gmax1) Gmax1 = G[i]; } } } if (unshrink == false && Gmax1 + Gmax2 <= eps * 10) { unshrink = true; reconstruct_gradient(); active_size = l; Trace.WriteLine("*"); } for (int i = 0; i < active_size; i++) { if (be_shrunk(i, Gmax1, Gmax2)) { active_size--; while (active_size > i) { if (!be_shrunk(active_size, Gmax1, Gmax2)) { swap_index(i, active_size); break; } active_size--; } } } } bool be_shrunk(int i, double Gmax1, double Gmax2) { if (is_upper_bound(i)) { if (y[i] == +1) return (-G[i] > Gmax1); return (-G[i] > Gmax2); } else if (is_lower_bound(i)) { if (y[i] == +1) return (G[i] > Gmax2); return (G[i] > Gmax1); } return false; } void row(int i, int length, double[] row) { int ii = indices[i]; for (int j = 0; j < length; j++) row[j] = Q(ii, indices[j]); } void swap_index(int i, int j) { swap(ref indices[i], ref indices[j]); swap(ref y[i], ref y[j]); swap(ref G[i], ref G[j]); swap(ref alpha_status[i], ref alpha_status[j]); swap(ref alpha[i], ref alpha[j]); swap(ref p[i], ref p[j]); swap(ref active_set[i], ref active_set[j]); swap(ref G_bar[i], ref G_bar[j]); } static void swap<T>(ref T a, ref T b) { T t = a; a = b; b = t; } } }
AnnaPeng/framework
Sources/Accord.Math/Optimization/Unconstrained/FanChenLinQuadraticOptimization.cs
C#
lgpl-2.1
29,682
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Core * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Custom variable model * * @method Mage_Core_Model_Resource_Variable _getResource() * @method Mage_Core_Model_Resource_Variable getResource() * @method string getCode() * @method Mage_Core_Model_Variable setCode(string $value) * @method string getName() * @method Mage_Core_Model_Variable setName(string $value) * * @category Mage * @package Mage_Core * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Core_Model_Variable extends Mage_Core_Model_Abstract { const TYPE_TEXT = 'text'; const TYPE_HTML = 'html'; protected $_storeId = 0; /** * Internal Constructor */ protected function _construct() { parent::_construct(); $this->_init('core/variable'); } /** * Setter * * @param integer $storeId * @return Mage_Core_Model_Variable */ public function setStoreId($storeId) { $this->_storeId = $storeId; return $this; } /** * Getter * * @return integer */ public function getStoreId() { return $this->_storeId; } /** * Load variable by code * * @param string $code * @return Mage_Core_Model_Variable */ public function loadByCode($code) { $this->getResource()->loadByCode($this, $code); return $this; } /** * Return variable value depend on given type * * @param string $type * @return string */ public function getValue($type = null) { if ($type === null) { $type = self::TYPE_HTML; } if ($type == self::TYPE_TEXT || !(strlen((string)$this->getData('html_value')))) { $value = $this->getData('plain_value'); //escape html if type is html, but html value is not defined if ($type == self::TYPE_HTML) { $value = nl2br(Mage::helper('core')->escapeHtml($value)); } return $value; } return $this->getData('html_value'); } /** * Validation of object data. Checking for unique variable code * * @return boolean | string */ public function validate() { if ($this->getCode() && $this->getName()) { $variable = $this->getResource()->getVariableByCode($this->getCode()); if (!empty($variable) && $variable['variable_id'] != $this->getId()) { return Mage::helper('core')->__('Variable Code must be unique.'); } return true; } return Mage::helper('core')->__('Validation has failed.'); } /** * Retrieve variables option array * * @param boolean $withValues * @return array */ public function getVariablesOptionArray($withGroup = false) { /* @var $collection Mage_Core_Model_Mysql4_Variable_Collection */ $collection = $this->getCollection(); $variables = array(); foreach ($collection->toOptionArray() as $variable) { $variables[] = array( 'value' => '{{customVar code=' . $variable['value'] . '}}', 'label' => Mage::helper('core')->__('%s', $variable['label']) ); } if ($withGroup && $variables) { $variables = array( 'label' => Mage::helper('core')->__('Custom Variables'), 'value' => $variables ); } return $variables; } }
dbashyal/MagentoStarterBase
trunk/app/code/core/Mage/Core/Model/Variable.php
PHP
lgpl-3.0
4,450
/** * 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 discovery; import org.codehaus.jackson.map.annotate.JsonRootName; /** * In a real application, the Service payload will most likely * be more detailed than this. But, this gives a good example. */ @JsonRootName("details") public class InstanceDetails { private String description; public InstanceDetails() { this(""); } public InstanceDetails(String description) { this.description = description; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } }
digital-abyss/curator
curator-examples/src/main/java/discovery/InstanceDetails.java
Java
apache-2.0
1,456
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.JavaExtensions { using System.Collections.Generic; using System.Linq; using IDictionary = System.Collections.IDictionary; using ObsoleteAttribute = System.ObsoleteAttribute; public static class DictionaryExtensions { [Obsolete] public static bool containsKey( this IDictionary map, object key ) { return map.Contains( key ); } [Obsolete] public static object get( this IDictionary map, object key ) { return map[key]; } public static TValue get<TKey, TValue>( this IDictionary<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } // disambiguates public static TValue get<TKey, TValue>( this Dictionary<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } public static TValue get<TKey, TValue>( this SortedList<TKey, TValue> map, TKey key ) { TValue value; if ( map.TryGetValue( key, out value ) ) return value; if ( typeof( TValue ).IsValueType ) throw new KeyNotFoundException(); return default( TValue ); } [Obsolete] public static void put( this IDictionary map, object key, object value ) { map[key] = value; } [Obsolete] public static void put<TKey, TValue>( this IDictionary<TKey, TValue> map, TKey key, TValue value ) { map[key] = value; } [Obsolete] public static void put<TKey, TValue>( this Dictionary<TKey, TValue> map, TKey key, TValue value ) { map[key] = value; } [Obsolete] public static HashSet<object> keySet( this IDictionary map ) { return new HashSet<object>( map.Keys.Cast<object>() ); } [Obsolete] public static HashSet<TKey> keySet<TKey, TValue>( this IDictionary<TKey, TValue> map ) { return new HashSet<TKey>( map.Keys ); } // disambiguates for Dictionary, which implements both IDictionary<T,K> and IDictionary [Obsolete] public static HashSet<TKey> keySet<TKey, TValue>( this Dictionary<TKey, TValue> map ) { return new HashSet<TKey>( map.Keys ); } [Obsolete] public static HashSet<object> keySet<TKey, TValue>( this SortedList<TKey, TValue> map ) { return new HashSet<object>( map.Keys.Cast<object>() ); } } }
ekcs/congress
thirdparty/antlr3-antlr-3.5/runtime/CSharp3/Sources/Antlr3.Runtime.JavaExtensions/DictionaryExtensions.cs
C#
apache-2.0
4,627
// Copyright 2015 go-swagger maintainers // // 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 loads import ( "bytes" "encoding/json" "fmt" "net/url" "path/filepath" "github.com/go-openapi/analysis" "github.com/go-openapi/loads/fmts" "github.com/go-openapi/spec" "github.com/go-openapi/swag" ) // JSONDoc loads a json document from either a file or a remote url func JSONDoc(path string) (json.RawMessage, error) { data, err := swag.LoadFromFileOrHTTP(path) if err != nil { return nil, err } return json.RawMessage(data), nil } // DocLoader represents a doc loader type type DocLoader func(string) (json.RawMessage, error) // DocMatcher represents a predicate to check if a loader matches type DocMatcher func(string) bool var ( loaders *loader defaultLoader *loader ) func init() { defaultLoader = &loader{Match: func(_ string) bool { return true }, Fn: JSONDoc} loaders = defaultLoader spec.PathLoader = loaders.Fn AddLoader(fmts.YAMLMatcher, fmts.YAMLDoc) } // AddLoader for a document func AddLoader(predicate DocMatcher, load DocLoader) { prev := loaders loaders = &loader{ Match: predicate, Fn: load, Next: prev, } spec.PathLoader = loaders.Fn } type loader struct { Fn DocLoader Match DocMatcher Next *loader } // JSONSpec loads a spec from a json document func JSONSpec(path string) (*Document, error) { data, err := JSONDoc(path) if err != nil { return nil, err } // convert to json return Analyzed(json.RawMessage(data), "") } // Document represents a swagger spec document type Document struct { // specAnalyzer Analyzer *analysis.Spec spec *spec.Swagger specFilePath string origSpec *spec.Swagger schema *spec.Schema raw json.RawMessage } // Spec loads a new spec document func Spec(path string) (*Document, error) { specURL, err := url.Parse(path) if err != nil { return nil, err } var lastErr error for l := loaders.Next; l != nil; l = l.Next { if loaders.Match(specURL.Path) { b, err2 := loaders.Fn(path) if err2 != nil { lastErr = err2 continue } doc, err := Analyzed(b, "") if err != nil { return nil, err } if doc != nil { doc.specFilePath = path } return doc, nil } } if lastErr != nil { return nil, lastErr } b, err := defaultLoader.Fn(path) if err != nil { return nil, err } document, err := Analyzed(b, "") if document != nil { document.specFilePath = path } return document, err } // Analyzed creates a new analyzed spec document func Analyzed(data json.RawMessage, version string) (*Document, error) { if version == "" { version = "2.0" } if version != "2.0" { return nil, fmt.Errorf("spec version %q is not supported", version) } raw := data trimmed := bytes.TrimSpace(data) if len(trimmed) > 0 { if trimmed[0] != '{' && trimmed[0] != '[' { yml, err := fmts.BytesToYAMLDoc(trimmed) if err != nil { return nil, fmt.Errorf("analyzed: %v", err) } d, err := fmts.YAMLToJSON(yml) if err != nil { return nil, fmt.Errorf("analyzed: %v", err) } raw = d } } swspec := new(spec.Swagger) if err := json.Unmarshal(raw, swspec); err != nil { return nil, err } origsqspec := new(spec.Swagger) if err := json.Unmarshal(raw, origsqspec); err != nil { return nil, err } d := &Document{ Analyzer: analysis.New(swspec), schema: spec.MustLoadSwagger20Schema(), spec: swspec, raw: raw, origSpec: origsqspec, } return d, nil } // Expanded expands the ref fields in the spec document and returns a new spec document func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) { swspec := new(spec.Swagger) if err := json.Unmarshal(d.raw, swspec); err != nil { return nil, err } var expandOptions *spec.ExpandOptions if len(options) > 0 { expandOptions = options[1] } else { expandOptions = &spec.ExpandOptions{ RelativeBase: filepath.Dir(d.specFilePath), } } if err := spec.ExpandSpec(swspec, expandOptions); err != nil { return nil, err } dd := &Document{ Analyzer: analysis.New(swspec), spec: swspec, schema: spec.MustLoadSwagger20Schema(), raw: d.raw, origSpec: d.origSpec, } return dd, nil } // BasePath the base path for this spec func (d *Document) BasePath() string { return d.spec.BasePath } // Version returns the version of this spec func (d *Document) Version() string { return d.spec.Swagger } // Schema returns the swagger 2.0 schema func (d *Document) Schema() *spec.Schema { return d.schema } // Spec returns the swagger spec object model func (d *Document) Spec() *spec.Swagger { return d.spec } // Host returns the host for the API func (d *Document) Host() string { return d.spec.Host } // Raw returns the raw swagger spec as json bytes func (d *Document) Raw() json.RawMessage { return d.raw } func (d *Document) OrigSpec() *spec.Swagger { return d.origSpec } // ResetDefinitions gives a shallow copy with the models reset func (d *Document) ResetDefinitions() *Document { defs := make(map[string]spec.Schema, len(d.origSpec.Definitions)) for k, v := range d.origSpec.Definitions { defs[k] = v } d.spec.Definitions = defs return d } // Pristine creates a new pristine document instance based on the input data func (d *Document) Pristine() *Document { dd, _ := Analyzed(d.Raw(), d.Version()) return dd } // SpecFilePath returns the file path of the spec if one is defined func (d *Document) SpecFilePath() string { return d.specFilePath }
scanf/cilium
vendor/github.com/go-openapi/loads/spec.go
GO
apache-2.0
6,031
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.components.runtime; import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.common.PropertyTypeConstants; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.components.runtime.util.ErrorMessages; import com.google.appinventor.components.runtime.util.FileUtil; import android.media.MediaRecorder; import android.media.MediaRecorder.OnErrorListener; import android.media.MediaRecorder.OnInfoListener; import android.os.Environment; import android.util.Log; import java.io.IOException; /** * Multimedia component that records audio using * {@link android.media.MediaRecorder}. * */ @DesignerComponent(version = YaVersion.SOUND_RECORDER_COMPONENT_VERSION, description = "<p>Multimedia component that records audio.</p>", category = ComponentCategory.MEDIA, nonVisible = true, iconName = "images/soundRecorder.png") @SimpleObject @UsesPermissions(permissionNames = "android.permission.RECORD_AUDIO") public final class SoundRecorder extends AndroidNonvisibleComponent implements Component, OnErrorListener, OnInfoListener { private static final String TAG = "SoundRecorder"; // the path to the savedRecording // if it is the null string, the recorder will generate a path // note that this is also initialized to "" in the designer private String savedRecording = ""; /** * This class encapsulates the required state during recording. */ private class RecordingController { final MediaRecorder recorder; // file is the same as savedRecording, but we'll keep it local to the // RecordingController for future flexibility final String file; RecordingController(String savedRecording) throws IOException { // pick a pathname if none was specified file = (savedRecording.equals("")) ? FileUtil.getRecordingFile("3gp").getAbsolutePath() : savedRecording; recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); Log.i(TAG, "Setting output file to " + file); recorder.setOutputFile(file); Log.i(TAG, "preparing"); recorder.prepare(); recorder.setOnErrorListener(SoundRecorder.this); recorder.setOnInfoListener(SoundRecorder.this); } void start() throws IllegalStateException { Log.i(TAG, "starting"); try { recorder.start(); } catch (IllegalStateException e) { // This is the error produced when there are two recorders running. // There might be other causes, but we don't know them. // Using Log.e will log a stack trace, so we can investigate Log.e(TAG, "got IllegalStateException. Are there two recorders running?", e); // Pass back a message detail for dispatchErrorOccurred to // show at user level throw (new IllegalStateException("Is there another recording running?")); } } void stop() { recorder.setOnErrorListener(null); recorder.setOnInfoListener(null); recorder.stop(); recorder.reset(); recorder.release(); } } /* * This is null when not recording, and contains the active RecordingState * when recording. */ private RecordingController controller; public SoundRecorder(final ComponentContainer container) { super(container.$form()); } /** * Returns the path to the saved recording * * @return savedRecording path to recording */ @SimpleProperty( description = "Specifies the path to the file where the recording is stored. " + "If this proprety is the empty string, then starting a recording will create a file in " + "an appropriate location.", category = PropertyCategory.BEHAVIOR) public String SavedRecording() { return savedRecording; } /** * Specifies the path to the saved recording displayed by the label. * * @param pathName path to saved recording */ @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "") @SimpleProperty public void SavedRecording(String pathName) { savedRecording = pathName; } /** * Starts recording. */ @SimpleFunction public void Start() { if (controller != null) { Log.i(TAG, "Start() called, but already recording to " + controller.file); return; } Log.i(TAG, "Start() called"); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE); return; } try { controller = new RecordingController(savedRecording); } catch (Throwable t) { form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } try { controller.start(); } catch (Throwable t) { // I'm commenting the next line out because stop can throw an error, and // it's not clear to me how to handle that. // controller.stop(); controller = null; form.dispatchErrorOccurredEvent( this, "Start", ErrorMessages.ERROR_SOUND_RECORDER_CANNOT_CREATE, t.getMessage()); return; } StartedRecording(); } @Override public void onError(MediaRecorder affectedRecorder, int what, int extra) { if (controller == null || affectedRecorder != controller.recorder) { Log.w(TAG, "onError called with wrong recorder. Ignoring."); return; } form.dispatchErrorOccurredEvent(this, "onError", ErrorMessages.ERROR_SOUND_RECORDER); try { controller.stop(); } catch (Throwable e) { Log.w(TAG, e.getMessage()); } finally { controller = null; StoppedRecording(); } } @Override public void onInfo(MediaRecorder affectedRecorder, int what, int extra) { if (controller == null || affectedRecorder != controller.recorder) { Log.w(TAG, "onInfo called with wrong recorder. Ignoring."); return; } Log.i(TAG, "Recoverable condition while recording. Will attempt to stop normally."); controller.recorder.stop(); } /** * Stops recording. */ @SimpleFunction public void Stop() { if (controller == null) { Log.i(TAG, "Stop() called, but already stopped."); return; } try { Log.i(TAG, "Stop() called"); Log.i(TAG, "stopping"); controller.stop(); Log.i(TAG, "Firing AfterSoundRecorded with " + controller.file); AfterSoundRecorded(controller.file); } catch (Throwable t) { form.dispatchErrorOccurredEvent(this, "Stop", ErrorMessages.ERROR_SOUND_RECORDER); } finally { controller = null; StoppedRecording(); } } @SimpleEvent(description = "Provides the location of the newly created sound.") public void AfterSoundRecorded(final String sound) { EventDispatcher.dispatchEvent(this, "AfterSoundRecorded", sound); } @SimpleEvent(description = "Indicates that the recorder has started, and can be stopped.") public void StartedRecording() { EventDispatcher.dispatchEvent(this, "StartedRecording"); } @SimpleEvent(description = "Indicates that the recorder has stopped, and can be started again.") public void StoppedRecording() { EventDispatcher.dispatchEvent(this, "StoppedRecording"); } }
tvomf/appinventor-mapps
appinventor/components/src/com/google/appinventor/components/runtime/SoundRecorder.java
Java
apache-2.0
8,379
using NUnit.Framework; using Nest.Tests.MockData.Domain; namespace Nest.Tests.Unit.Search.Query.Singles { [TestFixture] public class HasChildQueryJson { [Test] public void HasChildThisQuery() { var s = new SearchDescriptor<ElasticsearchProject>() .From(0) .Size(10) .Query(q => q .HasChild<Person>(fz => fz .Name("named_query") .Query(qq=>qq.Term(f=>f.FirstName, "john")) .Score(ChildScoreType.Average) ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { has_child: { _name: ""named_query"", type: ""person"", score_type: ""avg"", query: { term: { firstName: { value: ""john"" } } } }}}"; Assert.True(json.JsonEquals(expected), json); } [Test] public void HasChildOverrideTypeQuery() { var s = new SearchDescriptor<ElasticsearchProject>() .From(0) .Size(10) .Query(q => q .HasChild<Person>(fz => fz .Query(qq => qq.Term(f => f.FirstName, "john")) .Type("sillypeople") ) ); var json = TestElasticClient.Serialize(s); var expected = @"{ from: 0, size: 10, query : { has_child: { type: ""sillypeople"", query: { term: { firstName: { value: ""john"" } } } }}}"; Assert.True(json.JsonEquals(expected), json); } } }
joehmchan/elasticsearch-net
src/Tests/Nest.Tests.Unit/Search/Query/Singles/HasChildQueryJson.cs
C#
apache-2.0
1,392
// +build !providerless /* Copyright 2020 The Kubernetes 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 storageaccountclient import ( "context" "fmt" "net/http" "time" "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/to" "k8s.io/client-go/util/flowcontrol" "k8s.io/klog/v2" azclients "k8s.io/legacy-cloud-providers/azure/clients" "k8s.io/legacy-cloud-providers/azure/clients/armclient" "k8s.io/legacy-cloud-providers/azure/metrics" "k8s.io/legacy-cloud-providers/azure/retry" ) var _ Interface = &Client{} // Client implements StorageAccount client Interface. type Client struct { armClient armclient.Interface subscriptionID string // Rate limiting configures. rateLimiterReader flowcontrol.RateLimiter rateLimiterWriter flowcontrol.RateLimiter // ARM throttling configures. RetryAfterReader time.Time RetryAfterWriter time.Time } // New creates a new StorageAccount client with ratelimiting. func New(config *azclients.ClientConfig) *Client { baseURI := config.ResourceManagerEndpoint authorizer := config.Authorizer armClient := armclient.New(authorizer, baseURI, config.UserAgent, APIVersion, config.Location, config.Backoff) rateLimiterReader, rateLimiterWriter := azclients.NewRateLimiter(config.RateLimitConfig) klog.V(2).Infof("Azure StorageAccountClient (read ops) using rate limit config: QPS=%g, bucket=%d", config.RateLimitConfig.CloudProviderRateLimitQPS, config.RateLimitConfig.CloudProviderRateLimitBucket) klog.V(2).Infof("Azure StorageAccountClient (write ops) using rate limit config: QPS=%g, bucket=%d", config.RateLimitConfig.CloudProviderRateLimitQPSWrite, config.RateLimitConfig.CloudProviderRateLimitBucketWrite) client := &Client{ armClient: armClient, rateLimiterReader: rateLimiterReader, rateLimiterWriter: rateLimiterWriter, subscriptionID: config.SubscriptionID, } return client } // GetProperties gets properties of the StorageAccount. func (c *Client) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "get", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return storage.Account{}, retry.GetRateLimitError(false, "StorageAccountGet") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountGet", "client throttled", c.RetryAfterReader) return storage.Account{}, rerr } result, rerr := c.getStorageAccount(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // getStorageAccount gets properties of the StorageAccount. func (c *Client) getStorageAccount(ctx context.Context, resourceGroupName string, accountName string) (storage.Account, *retry.Error) { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) result := storage.Account{} response, rerr := c.armClient.GetResource(ctx, resourceID, "") defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.get.request", resourceID, rerr.Error()) return result, rerr } err := autorest.Respond( response, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.get.respond", resourceID, err) return result, retry.GetError(response, err) } result.Response = autorest.Response{Response: response} return result, nil } // ListKeys get a list of storage account keys. func (c *Client) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "list_keys", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return storage.AccountListKeysResult{}, retry.GetRateLimitError(false, "StorageAccountListKeys") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountListKeys", "client throttled", c.RetryAfterReader) return storage.AccountListKeysResult{}, rerr } result, rerr := c.listStorageAccountKeys(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // listStorageAccountKeys get a list of storage account keys. func (c *Client) listStorageAccountKeys(ctx context.Context, resourceGroupName string, accountName string) (storage.AccountListKeysResult, *retry.Error) { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) result := storage.AccountListKeysResult{} response, rerr := c.armClient.PostResource(ctx, resourceID, "listKeys", struct{}{}) defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.listkeys.request", resourceID, rerr.Error()) return result, rerr } err := autorest.Respond( response, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageaccount.listkeys.respond", resourceID, err) return result, retry.GetError(response, err) } result.Response = autorest.Response{Response: response} return result, nil } // Create creates a StorageAccount. func (c *Client) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error { mc := metrics.NewMetricContext("storage_account", "create", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterWriter.TryAccept() { mc.RateLimitedCount() return retry.GetRateLimitError(true, "StorageAccountCreate") } // Report errors if the client is throttled. if c.RetryAfterWriter.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountCreate", "client throttled", c.RetryAfterWriter) return rerr } rerr := c.createStorageAccount(ctx, resourceGroupName, accountName, parameters) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterWriter = rerr.RetryAfter } return rerr } return nil } // createStorageAccount creates or updates a StorageAccount. func (c *Client) createStorageAccount(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) *retry.Error { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) response, rerr := c.armClient.PutResource(ctx, resourceID, parameters) defer c.armClient.CloseResponse(ctx, response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.put.request", resourceID, rerr.Error()) return rerr } if response != nil && response.StatusCode != http.StatusNoContent { _, rerr = c.createResponder(response) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.put.respond", resourceID, rerr.Error()) return rerr } } return nil } func (c *Client) createResponder(resp *http.Response) (*storage.Account, *retry.Error) { result := &storage.Account{} err := autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), autorest.ByUnmarshallingJSON(&result)) result.Response = autorest.Response{Response: resp} return result, retry.GetError(resp, err) } // Delete deletes a StorageAccount by name. func (c *Client) Delete(ctx context.Context, resourceGroupName string, accountName string) *retry.Error { mc := metrics.NewMetricContext("storage_account", "delete", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterWriter.TryAccept() { mc.RateLimitedCount() return retry.GetRateLimitError(true, "StorageAccountDelete") } // Report errors if the client is throttled. if c.RetryAfterWriter.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountDelete", "client throttled", c.RetryAfterWriter) return rerr } rerr := c.deleteStorageAccount(ctx, resourceGroupName, accountName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterWriter = rerr.RetryAfter } return rerr } return nil } // deleteStorageAccount deletes a PublicIPAddress by name. func (c *Client) deleteStorageAccount(ctx context.Context, resourceGroupName string, accountName string) *retry.Error { resourceID := armclient.GetResourceID( c.subscriptionID, resourceGroupName, "Microsoft.Storage/storageAccounts", accountName, ) return c.armClient.DeleteResource(ctx, resourceID, "") } // ListByResourceGroup get a list storage accounts by resourceGroup. func (c *Client) ListByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) { mc := metrics.NewMetricContext("storage_account", "list_by_resource_group", resourceGroupName, c.subscriptionID, "") // Report errors if the client is rate limited. if !c.rateLimiterReader.TryAccept() { mc.RateLimitedCount() return nil, retry.GetRateLimitError(false, "StorageAccountListByResourceGroup") } // Report errors if the client is throttled. if c.RetryAfterReader.After(time.Now()) { mc.ThrottledCount() rerr := retry.GetThrottlingError("StorageAccountListByResourceGroup", "client throttled", c.RetryAfterReader) return nil, rerr } result, rerr := c.ListStorageAccountByResourceGroup(ctx, resourceGroupName) mc.Observe(rerr.Error()) if rerr != nil { if rerr.IsThrottled() { // Update RetryAfterReader so that no more requests would be sent until RetryAfter expires. c.RetryAfterReader = rerr.RetryAfter } return result, rerr } return result, nil } // ListStorageAccountByResourceGroup get a list storage accounts by resourceGroup. func (c *Client) ListStorageAccountByResourceGroup(ctx context.Context, resourceGroupName string) ([]storage.Account, *retry.Error) { resourceID := fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts", autorest.Encode("path", c.subscriptionID), autorest.Encode("path", resourceGroupName)) result := make([]storage.Account, 0) page := &AccountListResultPage{} page.fn = c.listNextResults resp, rerr := c.armClient.GetResource(ctx, resourceID, "") defer c.armClient.CloseResponse(ctx, resp) if rerr != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.request", resourceID, rerr.Error()) return result, rerr } var err error page.alr, err = c.listResponder(resp) if err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.respond", resourceID, err) return result, retry.GetError(resp, err) } for page.NotDone() { result = append(result, *page.Response().Value...) if err = page.NextWithContext(ctx); err != nil { klog.V(5).Infof("Received error in %s: resourceID: %s, error: %s", "storageAccount.list.next", resourceID, err) return result, retry.GetError(page.Response().Response.Response, err) } } return result, nil } func (c *Client) listResponder(resp *http.Response) (result storage.AccountListResult, err error) { err = autorest.Respond( resp, autorest.ByIgnoring(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result)) result.Response = autorest.Response{Response: resp} return } // StorageAccountResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (c *Client) StorageAccountResultPreparer(ctx context.Context, lr storage.AccountListResult) (*http.Request, error) { if lr.NextLink == nil || len(to.String(lr.NextLink)) < 1 { return nil, nil } decorators := []autorest.PrepareDecorator{ autorest.WithBaseURL(to.String(lr.NextLink)), } return c.armClient.PrepareGetRequest(ctx, decorators...) } // listNextResults retrieves the next set of results, if any. func (c *Client) listNextResults(ctx context.Context, lastResults storage.AccountListResult) (result storage.AccountListResult, err error) { req, err := c.StorageAccountResultPreparer(ctx, lastResults) if err != nil { return result, autorest.NewErrorWithError(err, "storageaccount", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, rerr := c.armClient.Send(ctx, req) defer c.armClient.CloseResponse(ctx, resp) if rerr != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(rerr.Error(), "storageaccount", "listNextResults", resp, "Failure sending next results request") } result, err = c.listResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "storageaccount", "listNextResults", resp, "Failure responding to next results request") } return } // AccountListResultPage contains a page of Account values. type AccountListResultPage struct { fn func(context.Context, storage.AccountListResult) (storage.AccountListResult, error) alr storage.AccountListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *AccountListResultPage) NextWithContext(ctx context.Context) (err error) { next, err := page.fn(ctx, page.alr) if err != nil { return err } page.alr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *AccountListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page AccountListResultPage) NotDone() bool { return !page.alr.IsEmpty() } // Response returns the raw server response from the last page request. func (page AccountListResultPage) Response() storage.AccountListResult { return page.alr } // Values returns the slice of values for the current page or nil if there are no values. func (page AccountListResultPage) Values() []storage.Account { if page.alr.IsEmpty() { return nil } return *page.alr.Value }
nak3/origin
vendor/k8s.io/legacy-cloud-providers/azure/clients/storageaccountclient/azure_storageaccountclient.go
GO
apache-2.0
16,148
/* * Copyright 2005-2007 WSO2, Inc. (http://wso2.com) * * 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.wso2.appserver.sample.chad.data; /** * POJO representing a poll result */ public class ChadPollResult { private int totalNumberOfVotes; private String pollId; private String pollTitle; private String pollDescription; private boolean isPollStopped; private boolean isSingleVote; private ChadChoice[] orderedChoices; public ChadPollResult() { } public ChadChoice[] getOrderedChoices() { return orderedChoices; } public void setOrderedChoices(ChadChoice[] orderedChoices) { this.orderedChoices = orderedChoices; } public String getPollDescription() { return pollDescription; } public void setPollDescription(String pollDescription) { this.pollDescription = pollDescription; } public String getPollId() { return pollId; } public void setPollId(String pollId) { this.pollId = pollId; } public String getPollTitle() { return pollTitle; } public void setPollTitle(String pollTitle) { this.pollTitle = pollTitle; } public int getTotalNumberOfVotes() { return totalNumberOfVotes; } public void setTotalNumberOfVotes(int totalNumberOfVotes) { this.totalNumberOfVotes = totalNumberOfVotes; } public boolean isPollStopped() { return isPollStopped; } public void setPollStopped(boolean pollStopped) { isPollStopped = pollStopped; } public boolean isSingleVote() { return isSingleVote; } public void setSingleVote(boolean singleVote) { isSingleVote = singleVote; } }
sanethd/product-as
modules/samples/product/Chad/src/org/wso2/appserver/sample/chad/data/ChadPollResult.java
Java
apache-2.0
2,258
/* * Copyright 2009 Google 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. */ package com.google.template.soy; import com.google.inject.AbstractModule; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.template.soy.SoyFileSet.SoyFileSetFactory; import com.google.template.soy.basicdirectives.BasicDirectivesModule; import com.google.template.soy.basicfunctions.BasicFunctionsModule; import com.google.template.soy.bididirectives.BidiDirectivesModule; import com.google.template.soy.bidifunctions.BidiFunctionsModule; import com.google.template.soy.i18ndirectives.I18nDirectivesModule; import com.google.template.soy.javasrc.internal.JavaSrcModule; import com.google.template.soy.jssrc.internal.JsSrcModule; import com.google.template.soy.parsepasses.CheckFunctionCallsVisitor; import com.google.template.soy.parsepasses.PerformAutoescapeVisitor; import com.google.template.soy.parsepasses.contextautoesc.ContextualAutoescaper; import com.google.template.soy.shared.internal.SharedModule; import com.google.template.soy.tofu.internal.TofuModule; /** * Guice module for Soy's programmatic interface. * * @author Kai Huang */ public class SoyModule extends AbstractModule { @Override protected void configure() { // Install requisite modules. install(new SharedModule()); install(new TofuModule()); install(new JsSrcModule()); install(new JavaSrcModule()); // Bindings for when explicit dependencies are required. bind(CheckFunctionCallsVisitor.class); bind(ContextualAutoescaper.class); bind(PerformAutoescapeVisitor.class); // Install default directive and function modules. install(new BasicDirectivesModule()); install(new BidiDirectivesModule()); install(new BasicFunctionsModule()); install(new BidiFunctionsModule()); install(new I18nDirectivesModule()); // Bind providers of factories (created via assisted inject). install(new FactoryModuleBuilder().build(SoyFileSetFactory.class)); // The static injection of SoyFileSetFactory into SoyFileSet.Builder is what allows the Soy // compiler to use Guice even if the user of the Soy API does not use Guice. requestStaticInjection(SoyFileSet.Builder.class); // Mark the fact that Guice has been initialized. requestStaticInjection(GuiceInitializer.class); } }
core9/closure-templates
src/impl/java/com/google/template/soy/SoyModule.java
Java
apache-2.0
2,866
# Copyright 2017 gRPC 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. """Common utilities for tests of the Cython layer of gRPC Python.""" import collections import threading from grpc._cython import cygrpc RPC_COUNT = 4000 EMPTY_FLAGS = 0 INVOCATION_METADATA = ( ('client-md-key', 'client-md-key'), ('client-md-key-bin', b'\x00\x01' * 3000), ) INITIAL_METADATA = ( ('server-initial-md-key', 'server-initial-md-value'), ('server-initial-md-key-bin', b'\x00\x02' * 3000), ) TRAILING_METADATA = ( ('server-trailing-md-key', 'server-trailing-md-value'), ('server-trailing-md-key-bin', b'\x00\x03' * 3000), ) class QueueDriver(object): def __init__(self, condition, completion_queue): self._condition = condition self._completion_queue = completion_queue self._due = collections.defaultdict(int) self._events = collections.defaultdict(list) def add_due(self, tags): if not self._due: def in_thread(): while True: event = self._completion_queue.poll() with self._condition: self._events[event.tag].append(event) self._due[event.tag] -= 1 self._condition.notify_all() if self._due[event.tag] <= 0: self._due.pop(event.tag) if not self._due: return thread = threading.Thread(target=in_thread) thread.start() for tag in tags: self._due[tag] += 1 def event_with_tag(self, tag): with self._condition: while True: if self._events[tag]: return self._events[tag].pop(0) else: self._condition.wait() def execute_many_times(behavior): return tuple(behavior() for _ in range(RPC_COUNT)) class OperationResult( collections.namedtuple('OperationResult', ( 'start_batch_result', 'completion_type', 'success', ))): pass SUCCESSFUL_OPERATION_RESULT = OperationResult( cygrpc.CallError.ok, cygrpc.CompletionType.operation_complete, True) class RpcTest(object): def setUp(self): self.server_completion_queue = cygrpc.CompletionQueue() self.server = cygrpc.Server([(b'grpc.so_reuseport', 0)]) self.server.register_completion_queue(self.server_completion_queue) port = self.server.add_http2_port(b'[::]:0') self.server.start() self.channel = cygrpc.Channel('localhost:{}'.format(port).encode(), [], None) self._server_shutdown_tag = 'server_shutdown_tag' self.server_condition = threading.Condition() self.server_driver = QueueDriver(self.server_condition, self.server_completion_queue) with self.server_condition: self.server_driver.add_due({ self._server_shutdown_tag, }) self.client_condition = threading.Condition() self.client_completion_queue = cygrpc.CompletionQueue() self.client_driver = QueueDriver(self.client_condition, self.client_completion_queue) def tearDown(self): self.server.shutdown(self.server_completion_queue, self._server_shutdown_tag) self.server.cancel_all_calls()
endlessm/chromium-browser
third_party/grpc/src/src/python/grpcio_tests/tests/unit/_cython/_common.py
Python
bsd-3-clause
4,044
/*============================================================================= Copyright (c) 2011 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_SEGMENTED_END_IMPL_HPP_INCLUDED) #define BOOST_FUSION_SEGMENTED_END_IMPL_HPP_INCLUDED #include <boost/fusion/support/config.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/fusion/sequence/intrinsic_fwd.hpp> #include <boost/fusion/container/list/cons_fwd.hpp> #include <boost/fusion/support/is_segmented.hpp> namespace boost { namespace fusion { template <typename First, typename Last> struct iterator_range; }} namespace boost { namespace fusion { namespace detail { //auto segmented_end_impl( seq, stack ) //{ // assert(is_segmented(seq)); // auto it = end(segments(seq)); // return cons(iterator_range(it, it), stack); //} template <typename Sequence, typename Stack> struct segmented_end_impl { BOOST_MPL_ASSERT((traits::is_segmented<Sequence>)); typedef typename result_of::end< typename remove_reference< typename add_const< typename result_of::segments<Sequence>::type >::type >::type >::type end_type; typedef iterator_range<end_type, end_type> pair_type; typedef cons<pair_type, Stack> type; BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static pair_type make_pair(end_type end) { return pair_type(end, end); } BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(Sequence & seq, Stack stack) { return type( make_pair(fusion::end(fusion::segments(seq))), stack); } }; }}} #endif
nginnever/zogminer
tests/deps/boost/fusion/sequence/intrinsic/detail/segmented_end_impl.hpp
C++
mit
2,194
module Rack # Middleware that authenticates webhooks from Twilio using the request # validator. # # The middleware takes an auth token with which to set up the request # validator and any number of paths. When a path matches the incoming request # path, the request will be checked for authentication. # # Example: # # require 'rack' # use Rack::TwilioWebhookAuthentication, ENV['AUTH_TOKEN'], /\/messages/ # # The above appends this middleware to the stack, using an auth token saved in # the ENV and only against paths that match /\/messages/. If the request # validates then it gets passed on to the action as normal. If the request # doesn't validate then the middleware responds immediately with a 403 status. class TwilioWebhookAuthentication def initialize(app, auth_token, *paths, &auth_token_lookup) @app = app @auth_token = auth_token define_singleton_method(:get_auth_token, auth_token_lookup) if block_given? @path_regex = Regexp.union(paths) end def call(env) return @app.call(env) unless env["PATH_INFO"].match(@path_regex) request = Rack::Request.new(env) original_url = request.url params = request.post? ? request.POST : {} auth_token = @auth_token || get_auth_token(params['AccountSid']) validator = Twilio::Util::RequestValidator.new(auth_token) signature = env['HTTP_X_TWILIO_SIGNATURE'] || "" if validator.validate(original_url, params, signature) @app.call(env) else [ 403, {'Content-Type' => 'text/plain'}, ["Twilio Request Validation Failed."] ] end end end end
JupiterLikeThePlanet/Quoter
vendor/bundle/ruby/2.3.0/gems/twilio-ruby-4.2.1/lib/rack/twilio_webhook_authentication.rb
Ruby
mit
1,679
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.ServiceModel.Discovery { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime; using SR2 = System.ServiceModel.Discovery.SR; [Fx.Tag.XamlVisible(false)] public class FindResponse { Dictionary<EndpointDiscoveryMetadata, DiscoveryMessageSequence> messageSequenceTable; Collection<EndpointDiscoveryMetadata> endpoints; internal FindResponse() { this.endpoints = new Collection<EndpointDiscoveryMetadata>(); this.messageSequenceTable = new Dictionary<EndpointDiscoveryMetadata, DiscoveryMessageSequence>(); } public Collection<EndpointDiscoveryMetadata> Endpoints { get { return this.endpoints; } } public DiscoveryMessageSequence GetMessageSequence(EndpointDiscoveryMetadata endpointDiscoveryMetadata) { if (endpointDiscoveryMetadata == null) { throw FxTrace.Exception.ArgumentNull("endpointDiscoveryMetadata"); } DiscoveryMessageSequence messageSequence = null; if (!this.messageSequenceTable.TryGetValue(endpointDiscoveryMetadata, out messageSequence)) { throw FxTrace.Exception.Argument("endpointDiscoveryMetadata", SR2.DiscoveryFindResponseMessageSequenceNotFound); } return messageSequence; } internal void AddDiscoveredEndpoint(EndpointDiscoveryMetadata endpointDiscoveryMetadata, DiscoveryMessageSequence messageSequence) { this.messageSequenceTable.Add(endpointDiscoveryMetadata, messageSequence); this.endpoints.Add(endpointDiscoveryMetadata); } } }
sekcheong/referencesource
System.ServiceModel.Discovery/System/ServiceModel/Discovery/FindResponse.cs
C#
mit
2,000
var foo = arr.map(v => ({ x: v.bar, y: v.bar * 2 })); var fn = () => ({}).key;
rmacklin/babel
packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/expected.js
JavaScript
mit
83
//------------------------------------------------------------------------------ // <copyright file="LinqDataSource.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System.Web.UI.WebControls.Expressions; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Web.DynamicData; using System.Web.Resources; using System.Web.UI; // Represents a data source that applies LINQ expressions against a business object in order to perform the Select // operation. When the Delete, Insert and Update operations are enabled the business object, specified in // ContextTypeName, must be a LINQ TO SQL DataContext. The LINQ expressions are applied in the order of Where, // OrderBy, GroupBy, OrderGroupsBy, Select. [ DefaultEvent("Selecting"), DefaultProperty("ContextTypeName"), Designer("System.Web.UI.Design.WebControls.LinqDataSourceDesigner, " + AssemblyRef.SystemWebExtensionsDesign), ParseChildren(true), PersistChildren(false), ResourceDescription("LinqDataSource_Description"), ResourceDisplayName("LinqDataSource_DisplayName"), ToolboxBitmap(typeof(LinqDataSource), "LinqDataSource.bmp") ] public class LinqDataSource : ContextDataSource, IDynamicDataSource { private const string DefaultViewName = "DefaultView"; private LinqDataSourceView _view; public LinqDataSource() { } internal LinqDataSource(LinqDataSourceView view) : base(view) { } // internal constructor that takes page mock for unit tests. internal LinqDataSource(IPage page) : base(page) { } private LinqDataSourceView View { get { if (_view == null) { _view = (LinqDataSourceView)GetView(DefaultViewName); } return _view; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateOrderByClause"), ] public bool AutoGenerateOrderByClause { get { return View.AutoGenerateOrderByClause; } set { View.AutoGenerateOrderByClause = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_AutoGenerateWhereClause"), ] public bool AutoGenerateWhereClause { get { return View.AutoGenerateWhereClause; } set { View.AutoGenerateWhereClause = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoPage"), ] public bool AutoPage { get { return View.AutoPage; } set { View.AutoPage = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_AutoSort"), ] public bool AutoSort { get { return View.AutoSort; } set { View.AutoSort = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_DeleteParameters"), Browsable(false) ] public ParameterCollection DeleteParameters { get { return View.DeleteParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_ContextTypeName") ] public override string ContextTypeName { get { return View.ContextTypeName; } set { View.ContextTypeName = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableDelete"), ] public bool EnableDelete { get { return View.EnableDelete; } set { View.EnableDelete = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableInsert"), ] public bool EnableInsert { get { return View.EnableInsert; } set { View.EnableInsert = value; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_EnableObjectTracking"), ] public bool EnableObjectTracking { get { return View.EnableObjectTracking; } set { View.EnableObjectTracking = value; } } [ DefaultValue(false), Category("Behavior"), ResourceDescription("LinqDataSource_EnableUpdate"), ] public bool EnableUpdate { get { return View.EnableUpdate; } set { View.EnableUpdate = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_GroupBy"), ] public string GroupBy { get { return View.GroupBy; } set { View.GroupBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_GroupByParameters"), Browsable(false) ] public ParameterCollection GroupByParameters { get { return View.GroupByParameters; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_InsertParameters"), Browsable(false) ] public ParameterCollection InsertParameters { get { return View.InsertParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderBy"), ] public string OrderBy { get { return View.OrderBy; } set { View.OrderBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderByParameters"), Browsable(false) ] public ParameterCollection OrderByParameters { get { return View.OrderByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsBy"), ] public string OrderGroupsBy { get { return View.OrderGroupsBy; } set { View.OrderGroupsBy = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_OrderGroupsByParameters"), Browsable(false) ] public ParameterCollection OrderGroupsByParameters { get { return View.OrderGroupsByParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Select"), ] public string Select { get { return View.SelectNew; } set { View.SelectNew = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_SelectParameters"), Browsable(false) ] public ParameterCollection SelectParameters { get { return View.SelectNewParameters; } } [ DefaultValue(true), Category("Behavior"), ResourceDescription("LinqDataSource_StoreOriginalValuesInViewState"), ] public bool StoreOriginalValuesInViewState { get { return View.StoreOriginalValuesInViewState; } set { View.StoreOriginalValuesInViewState = value; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_TableName"), ] public string TableName { get { return View.TableName; } set { View.TableName = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_UpdateParameters"), Browsable(false) ] public ParameterCollection UpdateParameters { get { return View.UpdateParameters; } } [ DefaultValue(""), Category("Data"), ResourceDescription("LinqDataSource_Where"), ] public string Where { get { return View.Where; } set { View.Where = value; } } [ DefaultValue(null), MergableProperty(false), PersistenceMode(PersistenceMode.InnerProperty), Category("Data"), ResourceDescription("LinqDataSource_WhereParameters"), Browsable(false) ] public ParameterCollection WhereParameters { get { return View.WhereParameters; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> ContextCreated { add { View.ContextCreated += value; } remove { View.ContextCreated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextCreating"), ] public event EventHandler<LinqDataSourceContextEventArgs> ContextCreating { add { View.ContextCreating += value; } remove { View.ContextCreating -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_ContextDisposing"), ] public event EventHandler<LinqDataSourceDisposeEventArgs> ContextDisposing { add { View.ContextDisposing += value; } remove { View.ContextDisposing -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Deleted { add { View.Deleted += value; } remove { View.Deleted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Deleting"), ] public event EventHandler<LinqDataSourceDeleteEventArgs> Deleting { add { View.Deleting += value; } remove { View.Deleting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserted"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Inserted { add { View.Inserted += value; } remove { View.Inserted -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Inserting"), ] public event EventHandler<LinqDataSourceInsertEventArgs> Inserting { add { View.Inserting += value; } remove { View.Inserting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selected"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Selected { add { View.Selected += value; } remove { View.Selected -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Selecting"), ] public event EventHandler<LinqDataSourceSelectEventArgs> Selecting { add { View.Selecting += value; } remove { View.Selecting -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updated"), ] public event EventHandler<LinqDataSourceStatusEventArgs> Updated { add { View.Updated += value; } remove { View.Updated -= value; } } [ Category("Data"), ResourceDescription("LinqDataSource_Updating"), ] public event EventHandler<LinqDataSourceUpdateEventArgs> Updating { add { View.Updating += value; } remove { View.Updating -= value; } } protected virtual LinqDataSourceView CreateView() { return new LinqDataSourceView(this, DefaultViewName, Context); } protected override QueryableDataSourceView CreateQueryableView() { return CreateView(); } public int Delete(IDictionary keys, IDictionary oldValues) { return View.Delete(keys, oldValues); } public int Insert(IDictionary values) { return View.Insert(values); } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (StoreOriginalValuesInViewState && (EnableUpdate || EnableDelete)) { IPage.RegisterRequiresViewStateEncryption(); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected internal override void OnUnload(EventArgs e) { base.OnUnload(e); // keeping the select contexts alive until Unload so that users can use deferred query evaluation. if (View != null) { View.ReleaseSelectContexts(); } } public int Update(IDictionary keys, IDictionary values, IDictionary oldValues) { return View.Update(keys, values, oldValues); } #region IDynamicDataSource members [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the ContextTypeName.")] Type IDynamicDataSource.ContextType { get { if (String.IsNullOrEmpty(ContextTypeName)) { return null; } return View.ContextType; } set { View.ContextTypeName = value.AssemblyQualifiedName; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Property used for IDynamicDataSource abstraction that wraps the TableName.")] string IDynamicDataSource.EntitySetName { get { return TableName; } set { TableName = value; } } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "IDynamicDataSource abstraction for handling exceptions available to user through other events.")] event EventHandler<DynamicValidatorEventArgs> IDynamicDataSource.Exception { add { View.Exception += value; } remove { View.Exception -= value; } } #endregion } }
sekcheong/referencesource
System.Web.Extensions/ui/WebControls/LinqDataSource.cs
C#
mit
17,606
//------------------------------------------------------------------------------ // <copyright file="SqlDataSourceFilterEventHandler.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; public delegate void SqlDataSourceFilteringEventHandler(object sender, SqlDataSourceFilteringEventArgs e); }
sekcheong/referencesource
System.Web/UI/WebControls/SqlDataSourceFilteringEventHandler.cs
C#
mit
558
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class ConnectionTypeOperationsExtensions { /// <summary> /// Create a connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connectiontype operation. /// </param> /// <returns> /// The response model for the create or update connection type /// operation. /// </returns> public static ConnectionTypeCreateOrUpdateResponse CreateOrUpdate(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create or update /// connectiontype operation. /// </param> /// <returns> /// The response model for the create or update connection type /// operation. /// </returns> public static Task<ConnectionTypeCreateOrUpdateResponse> CreateOrUpdateAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).DeleteAsync(resourceGroupName, automationAccount, connectionTypeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the connectiontype. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return operations.DeleteAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None); } /// <summary> /// Retrieve the connectiontype identified by connectiontype name. /// (see http://aka.ms/azureautomationsdk/connectiontypeoperations /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// The response model for the get connection type operation. /// </returns> public static ConnectionTypeGetResponse Get(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).GetAsync(resourceGroupName, automationAccount, connectionTypeName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the connectiontype identified by connectiontype name. /// (see http://aka.ms/azureautomationsdk/connectiontypeoperations /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='connectionTypeName'> /// Required. The name of connectiontype. /// </param> /// <returns> /// The response model for the get connection type operation. /// </returns> public static Task<ConnectionTypeGetResponse> GetAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName) { return operations.GetAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None); } /// <summary> /// Retrieve a list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static ConnectionTypeListResponse List(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).ListAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static Task<ConnectionTypeListResponse> ListAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount) { return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static ConnectionTypeListResponse ListNext(this IConnectionTypeOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IConnectionTypeOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of connectiontypes. (see /// http://aka.ms/azureautomationsdk/connectiontypeoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IConnectionTypeOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list connection type operation. /// </returns> public static Task<ConnectionTypeListResponse> ListNextAsync(this IConnectionTypeOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
ScottHolden/azure-sdk-for-net
src/SDKs/Automation/Management.Automation/Generated/ConnectionTypeOperationsExtensions.cs
C#
mit
12,740
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v12.0.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnController_1 = require("../columnController/columnController"); var gridPanel_1 = require("../gridPanel/gridPanel"); var column_1 = require("../entities/column"); var context_1 = require("../context/context"); var headerContainer_1 = require("./headerContainer"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var scrollVisibleService_1 = require("../gridPanel/scrollVisibleService"); var HeaderRenderer = (function () { function HeaderRenderer() { } HeaderRenderer.prototype.init = function () { var _this = this; this.eHeaderViewport = this.gridPanel.getHeaderViewport(); this.eRoot = this.gridPanel.getRoot(); this.eHeaderOverlay = this.gridPanel.getHeaderOverlay(); this.centerContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getHeaderContainer(), this.gridPanel.getHeaderViewport(), this.eRoot, null); this.childContainers = [this.centerContainer]; if (!this.gridOptionsWrapper.isForPrint()) { this.pinnedLeftContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedLeftHeader(), null, this.eRoot, column_1.Column.PINNED_LEFT); this.pinnedRightContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedRightHeader(), null, this.eRoot, column_1.Column.PINNED_RIGHT); this.childContainers.push(this.pinnedLeftContainer); this.childContainers.push(this.pinnedRightContainer); } this.childContainers.forEach(function (container) { return _this.context.wireBean(container); }); // when grid columns change, it means the number of rows in the header has changed and it's all new columns this.eventService.addEventListener(events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this)); // shotgun way to get labels to change, eg from sum(amount) to avg(amount) this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.refreshHeader.bind(this)); // for resized, the individual cells take care of this, so don't need to refresh everything this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.setPinnedColContainerWidth.bind(this)); this.eventService.addEventListener(events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this)); if (this.columnController.isReady()) { this.refreshHeader(); } }; HeaderRenderer.prototype.onScrollVisibilityChanged = function () { this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.forEachHeaderElement = function (callback) { this.childContainers.forEach(function (childContainer) { return childContainer.forEachHeaderElement(callback); }); }; HeaderRenderer.prototype.destroy = function () { this.childContainers.forEach(function (container) { return container.destroy(); }); }; HeaderRenderer.prototype.onGridColumnsChanged = function () { this.setHeight(); }; HeaderRenderer.prototype.refreshHeader = function () { this.setHeight(); this.childContainers.forEach(function (container) { return container.refresh(); }); this.setPinnedColContainerWidth(); }; HeaderRenderer.prototype.setHeight = function () { // if forPrint, overlay is missing if (this.eHeaderOverlay) { var rowHeight = this.gridOptionsWrapper.getHeaderHeight(); // we can probably get rid of this when we no longer need the overlay var dept = this.columnController.getHeaderRowCount(); this.eHeaderOverlay.style.height = rowHeight + 'px'; this.eHeaderOverlay.style.top = ((dept - 1) * rowHeight) + 'px'; } }; HeaderRenderer.prototype.setPinnedColContainerWidth = function () { // pinned col doesn't exist when doing forPrint if (this.gridOptionsWrapper.isForPrint()) { return; } var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth(); var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth(); this.eHeaderViewport.style.marginLeft = pinnedLeftWidthWithScroll + 'px'; this.eHeaderViewport.style.marginRight = pinnedRightWidthWithScroll + 'px'; }; __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], HeaderRenderer.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnController'), __metadata("design:type", columnController_1.ColumnController) ], HeaderRenderer.prototype, "columnController", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata("design:type", gridPanel_1.GridPanel) ], HeaderRenderer.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('context'), __metadata("design:type", context_1.Context) ], HeaderRenderer.prototype, "context", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], HeaderRenderer.prototype, "eventService", void 0); __decorate([ context_1.Autowired('scrollVisibleService'), __metadata("design:type", scrollVisibleService_1.ScrollVisibleService) ], HeaderRenderer.prototype, "scrollVisibleService", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "init", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], HeaderRenderer.prototype, "destroy", null); HeaderRenderer = __decorate([ context_1.Bean('headerRenderer') ], HeaderRenderer); return HeaderRenderer; }()); exports.HeaderRenderer = HeaderRenderer;
sufuf3/cdnjs
ajax/libs/ag-grid/12.0.1/lib/headerRendering/headerRenderer.js
JavaScript
mit
7,396
require File.join(File.dirname(File.expand_path(__FILE__)), "spec_helper") describe "pg_hstore extension" do before do Sequel.extension :pg_array, :pg_hstore @db = Sequel.connect('mock://postgres', :quote_identifiers=>false) @m = Sequel::Postgres @c = @m::HStore @db.extension :pg_hstore end it "should parse hstore strings correctly" do @c.parse('').to_hash.must_equal({}) @c.parse('"a"=>"b"').to_hash.must_equal('a'=>'b') @c.parse('"a"=>"b", "c"=>NULL').to_hash.must_equal('a'=>'b', 'c'=>nil) @c.parse('"a"=>"b", "c"=>"NULL"').to_hash.must_equal('a'=>'b', 'c'=>'NULL') @c.parse('"a"=>"b", "c"=>"\\\\ \\"\'=>"').to_hash.must_equal('a'=>'b', 'c'=>'\ "\'=>') end it "should cache parse results" do r = @c::Parser.new('') o = r.parse o.must_equal({}) r.parse.must_be_same_as(o) end it "should literalize HStores to strings correctly" do @db.literal(Sequel.hstore({})).must_equal '\'\'::hstore' @db.literal(Sequel.hstore("a"=>"b")).must_equal '\'"a"=>"b"\'::hstore' @db.literal(Sequel.hstore("c"=>nil)).must_equal '\'"c"=>NULL\'::hstore' @db.literal(Sequel.hstore("c"=>'NULL')).must_equal '\'"c"=>"NULL"\'::hstore' @db.literal(Sequel.hstore('c'=>'\ "\'=>')).must_equal '\'"c"=>"\\\\ \\"\'\'=>"\'::hstore' ['\'"a"=>"b","c"=>"d"\'::hstore', '\'"c"=>"d","a"=>"b"\'::hstore'].must_include(@db.literal(Sequel.hstore("a"=>"b","c"=>"d"))) end it "should have Sequel.hstore method for creating HStore instances" do Sequel.hstore({}).class.must_equal(@c) end it "should have Sequel.hstore return HStores as-is" do a = Sequel.hstore({}) Sequel.hstore(a).object_id.must_equal(a.object_id) end it "should HStore#to_hash method for getting underlying hash" do Sequel.hstore({}).to_hash.must_be_kind_of(Hash) end it "should convert keys and values to strings on creation" do Sequel.hstore(1=>2).to_hash.must_equal("1"=>"2") end it "should convert keys and values to strings on assignment" do v = Sequel.hstore({}) v[1] = 2 v.to_hash.must_equal("1"=>"2") v.store(:'1', 3) v.to_hash.must_equal("1"=>"3") end it "should not convert nil values to strings on creation" do Sequel.hstore(:foo=>nil).to_hash.must_equal("foo"=>nil) end it "should not convert nil values to strings on assignment" do v = Sequel.hstore({}) v[:foo] = nil v.to_hash.must_equal("foo"=>nil) end it "should convert lookups by key to string" do Sequel.hstore('foo'=>'bar')[:foo].must_equal 'bar' Sequel.hstore('1'=>'bar')[1].must_equal 'bar' Sequel.hstore('foo'=>'bar').fetch(:foo).must_equal 'bar' Sequel.hstore('foo'=>'bar').fetch(:foo2, 2).must_equal 2 k = nil Sequel.hstore('foo2'=>'bar').fetch(:foo){|key| k = key }.must_equal 'foo' k.must_equal 'foo' Sequel.hstore('foo'=>'bar').has_key?(:foo).must_equal true Sequel.hstore('foo'=>'bar').has_key?(:bar).must_equal false Sequel.hstore('foo'=>'bar').key?(:foo).must_equal true Sequel.hstore('foo'=>'bar').key?(:bar).must_equal false Sequel.hstore('foo'=>'bar').member?(:foo).must_equal true Sequel.hstore('foo'=>'bar').member?(:bar).must_equal false Sequel.hstore('foo'=>'bar').include?(:foo).must_equal true Sequel.hstore('foo'=>'bar').include?(:bar).must_equal false Sequel.hstore('foo'=>'bar', '1'=>'2').values_at(:foo3, :foo, :foo2, 1).must_equal [nil, 'bar', nil, '2'] if RUBY_VERSION >= '1.9.0' Sequel.hstore('foo'=>'bar').assoc(:foo).must_equal ['foo', 'bar'] Sequel.hstore('foo'=>'bar').assoc(:foo2).must_equal nil end end it "should convert has_value?/value? lookups to string" do Sequel.hstore('foo'=>'bar').has_value?(:bar).must_equal true Sequel.hstore('foo'=>'bar').has_value?(:foo).must_equal false Sequel.hstore('foo'=>'bar').value?(:bar).must_equal true Sequel.hstore('foo'=>'bar').value?(:foo).must_equal false end it "should handle nil values in has_value?/value? lookups" do Sequel.hstore('foo'=>'').has_value?('').must_equal true Sequel.hstore('foo'=>'').has_value?(nil).must_equal false Sequel.hstore('foo'=>nil).has_value?(nil).must_equal true end it "should have underlying hash convert lookups by key to string" do Sequel.hstore('foo'=>'bar').to_hash[:foo].must_equal 'bar' Sequel.hstore('1'=>'bar').to_hash[1].must_equal 'bar' end if RUBY_VERSION >= '1.9.0' it "should convert key lookups to string" do Sequel.hstore('foo'=>'bar').key(:bar).must_equal 'foo' Sequel.hstore('foo'=>'bar').key(:bar2).must_equal nil end it "should handle nil values in key lookups" do Sequel.hstore('foo'=>'').key('').must_equal 'foo' Sequel.hstore('foo'=>'').key(nil).must_equal nil Sequel.hstore('foo'=>nil).key(nil).must_equal 'foo' end it "should convert rassoc lookups to string" do Sequel.hstore('foo'=>'bar').rassoc(:bar).must_equal ['foo', 'bar'] Sequel.hstore('foo'=>'bar').rassoc(:bar2).must_equal nil end it "should handle nil values in rassoc lookups" do Sequel.hstore('foo'=>'').rassoc('').must_equal ['foo', ''] Sequel.hstore('foo'=>'').rassoc(nil).must_equal nil Sequel.hstore('foo'=>nil).rassoc(nil).must_equal ['foo', nil] end end it "should have delete convert key to string" do v = Sequel.hstore('foo'=>'bar') v.delete(:foo).must_equal 'bar' v.to_hash.must_equal({}) end it "should handle #replace with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar') v.replace(:bar=>1) v.class.must_equal(@c) v.must_equal('bar'=>'1') v.to_hash[:bar].must_equal '1' end it "should handle #merge with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar').merge(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') end it "should handle #merge/#update with hashes that do not use strings" do v = Sequel.hstore('foo'=>'bar') v.merge!(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') v = Sequel.hstore('foo'=>'bar') v.update(:bar=>1) v.class.must_equal(@c) v.must_equal('foo'=>'bar', 'bar'=>'1') end it "should support using hstores as bound variables" do @db.bound_variable_arg(1, nil).must_equal 1 @db.bound_variable_arg({'1'=>'2'}, nil).must_equal '"1"=>"2"' @db.bound_variable_arg(Sequel.hstore('1'=>'2'), nil).must_equal '"1"=>"2"' @db.bound_variable_arg(Sequel.hstore('1'=>nil), nil).must_equal '"1"=>NULL' @db.bound_variable_arg(Sequel.hstore('1'=>"NULL"), nil).must_equal '"1"=>"NULL"' @db.bound_variable_arg(Sequel.hstore('1'=>"'\\ \"=>"), nil).must_equal '"1"=>"\'\\\\ \\"=>"' ['"a"=>"b","c"=>"d"', '"c"=>"d","a"=>"b"'].must_include(@db.bound_variable_arg(Sequel.hstore("a"=>"b","c"=>"d"), nil)) end it "should parse hstore type from the schema correctly" do @db.fetch = [{:name=>'id', :db_type=>'integer'}, {:name=>'i', :db_type=>'hstore'}] @db.schema(:items).map{|e| e[1][:type]}.must_equal [:integer, :hstore] end it "should support typecasting for the hstore type" do h = Sequel.hstore(1=>2) @db.typecast_value(:hstore, h).object_id.must_equal(h.object_id) @db.typecast_value(:hstore, {}).class.must_equal(@c) @db.typecast_value(:hstore, {}).must_equal Sequel.hstore({}) @db.typecast_value(:hstore, {'a'=>'b'}).must_equal Sequel.hstore("a"=>"b") proc{@db.typecast_value(:hstore, [])}.must_raise(Sequel::InvalidValue) end it "should be serializable" do v = Sequel.hstore('foo'=>'bar') dump = Marshal.dump(v) Marshal.load(dump).must_equal v end it "should return correct results for Database#schema_type_class" do @db.schema_type_class(:hstore).must_equal Sequel::Postgres::HStore @db.schema_type_class(:integer).must_equal Integer end end
knut2/sequel
spec/extensions/pg_hstore_spec.rb
Ruby
mit
7,877
/** * Copyright (c) 2009--2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.domain.kickstart; import java.util.Date; import java.io.Serializable; import org.apache.commons.lang.builder.HashCodeBuilder; import com.redhat.rhn.domain.rhnpackage.PackageName; /** * KickstartPackage * @version $Rev$ */ public class KickstartPackage implements Serializable, Comparable<KickstartPackage> { private static final long serialVersionUID = 1L; private Long position; private Date created; private Date modified; private KickstartData ksData; private PackageName packageName; /** * */ public KickstartPackage() { super(); } /** * @param ksDataIn identifies kickstart * @param packageNameIn PackageName to be associated */ public KickstartPackage(KickstartData ksDataIn, PackageName packageNameIn) { super(); this.ksData = ksDataIn; this.packageName = packageNameIn; this.position = 0L; } /** * @param ksDataIn identifies kickstart * @param packageNameIn PackageName to be associated * @param posIn position the package Name is in the kickstart package list */ public KickstartPackage(KickstartData ksDataIn, PackageName packageNameIn, Long posIn) { this(ksDataIn, packageNameIn); this.position = posIn; } /** * @return Returns the position. */ public Long getPosition() { return position; } /** * @param positionIn The position to set. */ public void setPosition(Long positionIn) { this.position = positionIn; } /** * @return Returns the created. */ public Date getCreated() { return created; } /** * @param createdIn The created to set. */ public void setCreated(Date createdIn) { this.created = createdIn; } /** * @return Returns the modified. */ public Date getModified() { return modified; } /** * @param modifiedIn The modified to set. */ public void setModified(Date modifiedIn) { this.modified = modifiedIn; } /** * @return Returns the ksdata. */ public KickstartData getKsData() { return ksData; } /** * @param ksdata The ksdata to set. */ public void setKsData(KickstartData ksdata) { this.ksData = ksdata; } /** * @return Returns the packageName. */ public PackageName getPackageName() { return packageName; } /** * @param pn The packageName to set. */ public void setPackageName(PackageName pn) { this.packageName = pn; } /** * @param that KickstartPackage to be compared * @return -1,0,1 for sort algo */ public int compareTo(KickstartPackage that) { final int equal = 0; if (this.equals(that)) { return equal; } int comparism = this.getKsData().getLabel().compareTo(that.getKsData().getLabel()); if (equal != comparism) { return comparism; } comparism = this.getPosition().compareTo(that.getPosition()); if (equal != comparism) { return comparism; } return this.getPackageName().compareTo(that.getPackageName()); } /** * {@inheritDoc} */ public boolean equals(final Object other) { if (!(other instanceof KickstartPackage)) { return false; } KickstartPackage that = (KickstartPackage) other; return this.hashCode() == other.hashCode(); } /** * {@inheritDoc} */ public int hashCode() { return new HashCodeBuilder() .append(getKsData().getId()) .append(getPosition()) .append(getPackageName()) .toHashCode(); } /** * {@inheritDoc} */ public String toString() { return "{ " + this.getKsData().getId().toString() + ", " + this.getPosition().toString() + ", " + this.getPackageName().getName() + " }"; } /** * Produce a clone of a kickstartPackage object * @param data The new kickstart data * @return the clone */ public KickstartPackage deepCopy(KickstartData data) { KickstartPackage kp = new KickstartPackage(); kp.setKsData(data); kp.setPackageName(this.getPackageName()); kp.setPosition(this.getPosition()); return kp; } }
xkollar/spacewalk
java/code/src/com/redhat/rhn/domain/kickstart/KickstartPackage.java
Java
gpl-2.0
5,119
<?php namespace Drupal\commerce; /** * Represents a country. */ final class Country { /** * Two-letter country code. * * @var string */ protected $countryCode; /** * Constructs a new Country object. * * @param string $country_code * The country code. */ public function __construct($country_code) { $this->countryCode = strtoupper($country_code); } /** * Gets the country code. * * @return string * The country code. */ public function getCountryCode() { return $this->countryCode; } /** * Gets the string representation of the country. * * @return string * The string representation of the country */ public function __toString() { return $this->countryCode; } }
jigish-addweb/d8commerce
web/modules/contrib/commerce/src/Country.php
PHP
gpl-2.0
770
<table class="form-table"> <tr> <th>Main color</th> <td> <?php $controls->color('theme_color'); ?> (eg. #87aa14) </td> </tr> </table>
fdixon7/oktoberfestma
wp-content/plugins/newsletter/emails/themes/cta-2015/theme-options.php
PHP
gpl-2.0
184
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: HtmlElement.php 24593 2012-01-05 20:35:02Z matthew $ */ /** * @see Zend_View_Helper_Abstract */ #require_once 'Zend/View/Helper/Abstract.php'; /** * @category Zend * @package Zend_View * @subpackage Helper * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_View_Helper_HtmlElement extends Zend_View_Helper_Abstract { /** * EOL character */ const EOL = "\n"; /** * The tag closing bracket * * @var string */ protected $_closingBracket = null; /** * Get the tag closing bracket * * @return string */ public function getClosingBracket() { if (!$this->_closingBracket) { if ($this->_isXhtml()) { $this->_closingBracket = ' />'; } else { $this->_closingBracket = '>'; } } return $this->_closingBracket; } /** * Is doctype XHTML? * * @return boolean */ protected function _isXhtml() { $doctype = $this->view->doctype(); return $doctype->isXhtml(); } /** * Is doctype strict? * * @return boolean */ protected function _isStrictDoctype() { $doctype = $this->view->doctype(); return $doctype->isStrict(); } /** * Converts an associative array to a string of tag attributes. * * @access public * * @param array $attribs From this array, each key-value pair is * converted to an attribute name and value. * * @return string The XHTML for the attributes. */ protected function _htmlAttribs($attribs) { $xhtml = ''; foreach ((array) $attribs as $key => $val) { $key = $this->view->escape($key); if (('on' == substr($key, 0, 2)) || ('constraints' == $key)) { // Don't escape event attributes; _do_ substitute double quotes with singles if (!is_scalar($val)) { // non-scalar data should be cast to JSON first #require_once 'Zend/Json.php'; $val = Zend_Json::encode($val); } // Escape single quotes inside event attribute values. // This will create html, where the attribute value has // single quotes around it, and escaped single quotes or // non-escaped double quotes inside of it $val = str_replace('\'', '&#39;', $val); } else { if (is_array($val)) { $val = implode(' ', $val); } $val = $this->view->escape($val); } if ('id' == $key) { $val = $this->_normalizeId($val); } if (strpos($val, '"') !== false) { $xhtml .= " $key='$val'"; } else { $xhtml .= " $key=\"$val\""; } } return $xhtml; } /** * Normalize an ID * * @param string $value * @return string */ protected function _normalizeId($value) { if (strstr($value, '[')) { if ('[]' == substr($value, -2)) { $value = substr($value, 0, strlen($value) - 2); } $value = trim($value, ']'); $value = str_replace('][', '-', $value); $value = str_replace('[', '-', $value); } return $value; } }
Eristoff47/P2
src/public/lib/Zend/View/Helper/HtmlElement.php
PHP
gpl-2.0
4,337
<?php if (!defined('sugarEntry') || !sugarEntry) { die('Not A Valid Entry Point'); } /** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ $module_name = 'SurveyQuestionResponses'; $listViewDefs[$module_name] = array( 'NAME' => array( 'width' => '32', 'label' => 'LBL_NAME', 'default' => true, 'link' => true ), 'ASSIGNED_USER_NAME' => array( 'width' => '9', 'label' => 'LBL_ASSIGNED_TO_NAME', 'module' => 'Employees', 'id' => 'ASSIGNED_USER_ID', 'default' => true ), );
Dillon-Brown/SuiteCRM
modules/SurveyQuestionResponses/metadata/listviewdefs.php
PHP
agpl-3.0
2,602
/* * 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.ignite.internal.processors.rest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.logger.java.JavaLogger; import org.apache.ignite.marshaller.Marshaller; import org.apache.ignite.marshaller.jdk.JdkMarshaller; import org.jetbrains.annotations.Nullable; /** * Test client. */ final class TestMemcacheClient { /** Header length. */ private static final short HDR_LEN = 24; /** Serialized flag. */ private static final short SERIALIZED_FLAG = 1; /** Boolean flag. */ private static final short BOOLEAN_FLAG = (1 << 8); /** Integer flag. */ private static final short INT_FLAG = (2 << 8); /** Long flag. */ private static final short LONG_FLAG = (3 << 8); /** Date flag. */ private static final short DATE_FLAG = (4 << 8); /** Byte flag. */ private static final short BYTE_FLAG = (5 << 8); /** Float flag. */ private static final short FLOAT_FLAG = (6 << 8); /** Double flag. */ private static final short DOUBLE_FLAG = (7 << 8); /** Byte array flag. */ private static final short BYTE_ARR_FLAG = (8 << 8); /** Logger. */ private final IgniteLogger log = new JavaLogger(); /** JDK marshaller. */ private final Marshaller jdkMarshaller = new JdkMarshaller(); /** Socket. */ private final Socket sock; /** Opaque counter. */ private final AtomicInteger opaqueCntr = new AtomicInteger(0); /** Response queue. */ private final BlockingQueue<Response> queue = new LinkedBlockingQueue<>(); /** Socket reader. */ private final Thread rdr; /** Quit response. */ private static final Response QUIT_RESP = new Response(0, false, null, null); /** * Creates client. * * @param host Hostname. * @param port Port number. * @throws IgniteCheckedException In case of error. */ TestMemcacheClient(String host, int port) throws IgniteCheckedException { assert host != null; assert port > 0; try { sock = new Socket(host, port); } catch (IOException e) { throw new IgniteCheckedException("Failed to establish connection.", e); } // Start socket reader thread. rdr = new Thread(new Runnable() { @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { try { InputStream in = sock.getInputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); boolean running = true; while (running) { byte opCode = 0; byte extrasLength = 0; int keyLength = 0; boolean success = false; int totalLength = 0; int opaque = 0; short keyFlags = 0; short valFlags = 0; Object obj = null; Object key = null; int i = 0; while (true) { int symbol = in.read(); if (symbol == -1) { running = false; break; } byte b = (byte)symbol; if (i == 1) opCode = b; if (i == 2 || i == 3) { buf.write(b); if (i == 3) { keyLength = U.bytesToShort(buf.toByteArray(), 0); buf.reset(); } } else if (i == 4) extrasLength = b; else if (i == 6 || i == 7) { buf.write(b); if (i == 7) { success = U.bytesToShort(buf.toByteArray(), 0) == 0; buf.reset(); } } else if (i >= 8 && i <= 11) { buf.write(b); if (i == 11) { totalLength = U.bytesToInt(buf.toByteArray(), 0); buf.reset(); } } else if (i >= 12 && i <= 15) { buf.write(b); if (i == 15) { opaque = U.bytesToInt(buf.toByteArray(), 0); buf.reset(); } } else if (i >= HDR_LEN && i < HDR_LEN + extrasLength) { buf.write(b); if (i == HDR_LEN + extrasLength - 1) { byte[] rawFlags = buf.toByteArray(); keyFlags = U.bytesToShort(rawFlags, 0); valFlags = U.bytesToShort(rawFlags, 2); buf.reset(); } } else if (i >= HDR_LEN + extrasLength && i < HDR_LEN + extrasLength + keyLength) { buf.write(b); if (i == HDR_LEN + extrasLength + keyLength - 1) { key = decode(buf.toByteArray(), keyFlags); buf.reset(); } } else if (i >= HDR_LEN + extrasLength + keyLength && i < HDR_LEN + totalLength) { buf.write(b); if (opCode == 0x05 || opCode == 0x06) valFlags = LONG_FLAG; if (i == HDR_LEN + totalLength - 1) { obj = decode(buf.toByteArray(), valFlags); buf.reset(); } } if (i == HDR_LEN + totalLength - 1) { queue.add(new Response(opaque, success, key, obj)); break; } i++; } } } catch (IOException e) { if (!Thread.currentThread().isInterrupted()) U.error(log, e); } catch (Exception e) { U.error(log, e); } finally { U.closeQuiet(sock); queue.add(QUIT_RESP); } } }); rdr.start(); } /** {@inheritDoc} */ public void shutdown() throws IgniteCheckedException { try { if (rdr != null) { rdr.interrupt(); U.closeQuiet(sock); rdr.join(); } } catch (InterruptedException e) { throw new IgniteCheckedException(e); } } /** * Makes request to server and waits for response. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param extras Extras. * @return Response. * @throws IgniteCheckedException In case of error. */ private Response makeRequest( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, @Nullable Long... extras ) throws IgniteCheckedException { assert cmd != null; int opaque = opaqueCntr.getAndIncrement(); // Send request. try { sock.getOutputStream().write(createPacket(cmd, cacheName, key, val, opaque, extras)); } catch (IOException e) { throw new IgniteCheckedException("Failed to send packet.", e); } // Wait for response. while (true) { try { // Take response from queue. Response res = queue.take(); if (res == QUIT_RESP) return res; // Check opaque value. if (res.getOpaque() == opaque) { if (!res.isSuccess() && res.getObject() != null) throw new IgniteCheckedException((String)res.getObject()); else return res; } else // Return response to queue if opaque is incorrect. queue.add(res); } catch (InterruptedException e) { throw new IgniteCheckedException("Interrupted while waiting for response.", e); } } } /** * Makes request to server and waits for response. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param extras Extras. * @return Response. * @throws IgniteCheckedException In case of error. */ private List<Response> makeMultiRequest( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, @Nullable Long... extras ) throws IgniteCheckedException { assert cmd != null; int opaque = opaqueCntr.getAndIncrement(); List<Response> resList = new LinkedList<>(); // Send request. try { sock.getOutputStream().write(createPacket(cmd, cacheName, key, val, opaque, extras)); } catch (IOException e) { throw new IgniteCheckedException("Failed to send packet.", e); } // Wait for response. while (true) { try { // Take response from queue. Response res = queue.take(); if (res == QUIT_RESP) return resList; // Check opaque value. if (res.getOpaque() == opaque) { if (!res.isSuccess() && res.getObject() != null) throw new IgniteCheckedException((String)res.getObject()); else { if (res.getObject() == null) return resList; resList.add(res); } } else // Return response to queue if opaque is incorrect. queue.add(res); } catch (InterruptedException e) { throw new IgniteCheckedException("Interrupted while waiting for response.", e); } } } /** * Creates packet. * * @param cmd Command. * @param cacheName Cache name. * @param key Key. * @param val Value. * @param opaque Opaque. * @param extras Extras. * @throws IgniteCheckedException In case of error. * @return Packet. */ private byte[] createPacket( Command cmd, @Nullable String cacheName, @Nullable Object key, @Nullable Object val, int opaque, @Nullable Long[] extras ) throws IgniteCheckedException { assert cmd != null; assert opaque >= 0; byte[] cacheNameBytes = cacheName != null ? cacheName.getBytes() : null; Data keyData = encode(key); Data valData = encode(val); int cacheNameLength = cacheNameBytes != null ? cacheNameBytes.length : 0; int extrasLength = cmd.extrasLength() + cacheNameLength; byte[] packet = new byte[HDR_LEN + extrasLength + keyData.length() + valData.length()]; packet[0] = (byte)0x80; packet[1] = cmd.operationCode(); U.shortToBytes((short) keyData.length(), packet, 2); packet[4] = (byte)(extrasLength); U.intToBytes(extrasLength + keyData.length() + valData.length(), packet, 8); U.intToBytes(opaque, packet, 12); if (extrasLength > 0) { if (extras != null) { int offset = HDR_LEN; for (Long extra : extras) { if (extra != null) U.longToBytes(extra, packet, offset); offset += 8; } } else { U.shortToBytes(keyData.getFlags(), packet, HDR_LEN); U.shortToBytes(valData.getFlags(), packet, HDR_LEN + 2); } } if (cacheNameBytes != null) U.arrayCopy(cacheNameBytes, 0, packet, HDR_LEN + cmd.extrasLength(), cacheNameLength); if (keyData.getBytes() != null) U.arrayCopy(keyData.getBytes(), 0, packet, HDR_LEN + extrasLength, keyData.length()); if (valData.getBytes() != null) U.arrayCopy(valData.getBytes(), 0, packet, HDR_LEN + extrasLength + keyData.length(), valData.length()); return packet; } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return If value was actually put. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cachePut(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.PUT, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @return Value. * @throws IgniteCheckedException In case of error. */ public <K, V> V cacheGet(@Nullable String cacheName, K key) throws IgniteCheckedException { assert key != null; return makeRequest(Command.GET, cacheName, key, null).getObject(); } /** * @param cacheName Cache name. * @param key Key. * @return Whether entry was actually removed. * @throws IgniteCheckedException In case of error. */ public <K> boolean cacheRemove(@Nullable String cacheName, K key) throws IgniteCheckedException { assert key != null; return makeRequest(Command.REMOVE, cacheName, key, null).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return Whether entry was added. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cacheAdd(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.ADD, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value. * @return Whether value was actually replaced. * @throws IgniteCheckedException In case of error. */ public <K, V> boolean cacheReplace(@Nullable String cacheName, K key, V val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.REPLACE, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @throws IgniteCheckedException In case of error. * @return Metrics map. */ public <K> Map<String, Long> cacheMetrics(@Nullable String cacheName) throws IgniteCheckedException { List<Response> raw = makeMultiRequest(Command.CACHE_METRICS, cacheName, null, null); Map<String, Long> res = new HashMap<>(raw.size()); for (Response resp : raw) res.put((String)resp.key(), Long.parseLong(String.valueOf(resp.<String>getObject()))); return res; } /** * @param key Key. * @param init Initial value (optional). * @param incr Amount to add. * @return New value. * @throws IgniteCheckedException In case of error. */ public <K> long increment(K key, @Nullable Long init, long incr) throws IgniteCheckedException { assert key != null; return makeRequest(Command.INCREMENT, null, key, null, incr, init).<Long>getObject(); } /** * @param key Key. * @param init Initial value (optional). * @param decr Amount to subtract. * @return New value. * @throws IgniteCheckedException In case of error. */ public <K> long decrement(K key, @Nullable Long init, long decr) throws IgniteCheckedException { assert key != null; return makeRequest(Command.DECREMENT, null, key, null, decr, init).<Long>getObject(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value to append. * @return Whether operation succeeded. * @throws IgniteCheckedException In case of error. */ public <K> boolean cacheAppend(@Nullable String cacheName, K key, String val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.APPEND, cacheName, key, val).isSuccess(); } /** * @param cacheName Cache name. * @param key Key. * @param val Value to prepend. * @return Whether operation succeeded. * @throws IgniteCheckedException In case of error. */ public <K> boolean cachePrepend(@Nullable String cacheName, K key, String val) throws IgniteCheckedException { assert key != null; assert val != null; return makeRequest(Command.PREPEND, cacheName, key, val).isSuccess(); } /** * @return Version. * @throws IgniteCheckedException In case of error. */ public String version() throws IgniteCheckedException { return makeRequest(Command.VERSION, null, null, null).getObject(); } /** * @throws IgniteCheckedException In case of error. */ public void noop() throws IgniteCheckedException { Response res = makeRequest(Command.NOOP, null, null, null); assert res != null; assert res.isSuccess(); assert res.getObject() == null; } /** * @throws IgniteCheckedException In case of error. */ public void quit() throws IgniteCheckedException { makeRequest(Command.QUIT, null, null, null); assert sock.isClosed(); } /** * Encodes object. * * @param obj Object. * @return Encoded data. * @throws IgniteCheckedException In case of error. */ public Data encode(@Nullable Object obj) throws IgniteCheckedException { if (obj == null) return new Data(null, (short)0); byte[] bytes; short flags = 0; if (obj instanceof String) bytes = ((String)obj).getBytes(); else if (obj instanceof Boolean) { bytes = new byte[] {(byte)((Boolean)obj ? '1' : '0')}; flags |= BOOLEAN_FLAG; } else if (obj instanceof Integer) { bytes = U.intToBytes((Integer) obj); flags |= INT_FLAG; } else if (obj instanceof Long) { bytes = U.longToBytes((Long) obj); flags |= LONG_FLAG; } else if (obj instanceof Date) { bytes = U.longToBytes(((Date) obj).getTime()); flags |= DATE_FLAG; } else if (obj instanceof Byte) { bytes = new byte[] {(Byte)obj}; flags |= BYTE_FLAG; } else if (obj instanceof Float) { bytes = U.intToBytes(Float.floatToIntBits((Float) obj)); flags |= FLOAT_FLAG; } else if (obj instanceof Double) { bytes = U.longToBytes(Double.doubleToLongBits((Double) obj)); flags |= DOUBLE_FLAG; } else if (obj instanceof byte[]) { bytes = (byte[])obj; flags |= BYTE_ARR_FLAG; } else { bytes = jdkMarshaller.marshal(obj); flags |= SERIALIZED_FLAG; } return new Data(bytes, flags); } /** * @param bytes Byte array to decode. * @param flags Flags. * @return Decoded value. * @throws IgniteCheckedException In case of error. */ public Object decode(byte[] bytes, short flags) throws IgniteCheckedException { assert bytes != null; assert flags >= 0; if ((flags & SERIALIZED_FLAG) != 0) return jdkMarshaller.unmarshal(bytes, getClass().getClassLoader()); int masked = flags & 0xff00; switch (masked) { case BOOLEAN_FLAG: return bytes[0] == '1'; case INT_FLAG: return U.bytesToInt(bytes, 0); case LONG_FLAG: return U.bytesToLong(bytes, 0); case DATE_FLAG: return new Date(U.bytesToLong(bytes, 0)); case BYTE_FLAG: return bytes[0]; case FLOAT_FLAG: return Float.intBitsToFloat(U.bytesToInt(bytes, 0)); case DOUBLE_FLAG: return Double.longBitsToDouble(U.bytesToLong(bytes, 0)); case BYTE_ARR_FLAG: return bytes; default: return new String(bytes); } } /** * Response data. */ private static class Response { /** Opaque. */ private final int opaque; /** Success flag. */ private final boolean success; /** Key. */ private final Object key; /** Response object. */ private final Object obj; /** * @param opaque Opaque. * @param success Success flag. * @param key Key object. * @param obj Response object. */ Response(int opaque, boolean success, @Nullable Object key, @Nullable Object obj) { assert opaque >= 0; this.opaque = opaque; this.success = success; this.key = key; this.obj = obj; } /** * @return Opaque. */ int getOpaque() { return opaque; } /** * @return Success flag. */ boolean isSuccess() { return success; } Object key() { return key; } /** * @return Response object. */ @SuppressWarnings("unchecked") <T> T getObject() { return (T)obj; } } private static class Data { /** Bytes. */ private final byte[] bytes; /** Flags. */ private final short flags; /** * @param bytes Bytes. * @param flags Flags. */ Data(@Nullable byte[] bytes, short flags) { assert flags >= 0; this.bytes = bytes; this.flags = flags; } /** * @return Bytes. */ @Nullable public byte[] getBytes() { return bytes; } /** * @return Flags. */ public short getFlags() { return flags; } /** * @return Length. */ public int length() { return bytes != null ? bytes.length : 0; } } /** * Command. */ private enum Command { /** Get. */ GET((byte)0x00, 4), /** Put. */ PUT((byte)0x01, 8), /** Add. */ ADD((byte)0x02, 8), /** Replace. */ REPLACE((byte)0x03, 8), /** Remove. */ REMOVE((byte)0x04, 4), /** Increment. */ INCREMENT((byte)0x05, 20), /** Decrement. */ DECREMENT((byte)0x06, 20), /** Quit. */ QUIT((byte)0x07, 0), /** Cache metrics. */ CACHE_METRICS((byte)0x10, 4), /** No-op. */ NOOP((byte)0x0A, 0), /** Version. */ VERSION((byte)0x0B, 0), /** Append. */ APPEND((byte)0x0E, 4), /** Append. */ PREPEND((byte)0x0F, 4); /** Operation code. */ private final byte opCode; /** Extras length. */ private final int extrasLength; /** * @param opCode Operation code. * @param extrasLength Extras length. */ Command(byte opCode, int extrasLength) { this.opCode = opCode; this.extrasLength = extrasLength; } /** * @return Operation code. */ public byte operationCode() { return opCode; } /** * @return Extras length. */ public int extrasLength() { return extrasLength; } } }
irudyak/ignite
modules/clients/src/test/java/org/apache/ignite/internal/processors/rest/TestMemcacheClient.java
Java
apache-2.0
26,565
module Fog module Parsers module AWS module RDS class SecurityGroupParser < Fog::Parsers::Base def reset @security_group = fresh_security_group end def fresh_security_group {'EC2SecurityGroups' => [], 'IPRanges' => []} end def start_element(name, attrs = []) super case name when 'EC2SecurityGroup', 'IPRange'; then @ingress = {} end end def end_element(name) case name when 'DBSecurityGroupDescription' then @security_group['DBSecurityGroupDescription'] = value when 'DBSecurityGroupName' then @security_group['DBSecurityGroupName'] = value when 'OwnerId' then @security_group['OwnerId'] = value when 'EC2SecurityGroup', 'IPRange' @security_group["#{name}s"] << @ingress unless @ingress.empty? when 'EC2SecurityGroupName', 'EC2SecurityGroupOwnerId', 'CIDRIP', 'Status' @ingress[name] = value end end end end end end end
jreichhold/chef-repo
vendor/ruby/2.0.0/gems/fog-1.20.0/lib/fog/aws/parsers/rds/security_group_parser.rb
Ruby
apache-2.0
1,131
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:generate go run gen.go gen_trieval.go gen_common.go // Package idna implements IDNA2008 using the compatibility processing // defined by UTS (Unicode Technical Standard) #46, which defines a standard to // deal with the transition from IDNA2003. // // IDNA2008 (Internationalized Domain Names for Applications), is defined in RFC // 5890, RFC 5891, RFC 5892, RFC 5893 and RFC 5894. // UTS #46 is defined in http://www.unicode.org/reports/tr46. // See http://unicode.org/cldr/utility/idna.jsp for a visualization of the // differences between these two standards. package idna // import "golang.org/x/text/internal/export/idna" import ( "fmt" "strings" "unicode/utf8" "golang.org/x/text/secure/bidirule" "golang.org/x/text/unicode/bidi" "golang.org/x/text/unicode/norm" ) // NOTE: Unlike common practice in Go APIs, the functions will return a // sanitized domain name in case of errors. Browsers sometimes use a partially // evaluated string as lookup. // TODO: the current error handling is, in my opinion, the least opinionated. // Other strategies are also viable, though: // Option 1) Return an empty string in case of error, but allow the user to // specify explicitly which errors to ignore. // Option 2) Return the partially evaluated string if it is itself a valid // string, otherwise return the empty string in case of error. // Option 3) Option 1 and 2. // Option 4) Always return an empty string for now and implement Option 1 as // needed, and document that the return string may not be empty in case of // error in the future. // I think Option 1 is best, but it is quite opinionated. // ToASCII is a wrapper for Punycode.ToASCII. func ToASCII(s string) (string, error) { return Punycode.process(s, true) } // ToUnicode is a wrapper for Punycode.ToUnicode. func ToUnicode(s string) (string, error) { return Punycode.process(s, false) } // An Option configures a Profile at creation time. type Option func(*options) // Transitional sets a Profile to use the Transitional mapping as defined in UTS // #46. This will cause, for example, "ß" to be mapped to "ss". Using the // transitional mapping provides a compromise between IDNA2003 and IDNA2008 // compatibility. It is used by most browsers when resolving domain names. This // option is only meaningful if combined with MapForLookup. func Transitional(transitional bool) Option { return func(o *options) { o.transitional = true } } // VerifyDNSLength sets whether a Profile should fail if any of the IDN parts // are longer than allowed by the RFC. func VerifyDNSLength(verify bool) Option { return func(o *options) { o.verifyDNSLength = verify } } // RemoveLeadingDots removes leading label separators. Leading runes that map to // dots, such as U+3002 IDEOGRAPHIC FULL STOP, are removed as well. // // This is the behavior suggested by the UTS #46 and is adopted by some // browsers. func RemoveLeadingDots(remove bool) Option { return func(o *options) { o.removeLeadingDots = remove } } // ValidateLabels sets whether to check the mandatory label validation criteria // as defined in Section 5.4 of RFC 5891. This includes testing for correct use // of hyphens ('-'), normalization, validity of runes, and the context rules. func ValidateLabels(enable bool) Option { return func(o *options) { // Don't override existing mappings, but set one that at least checks // normalization if it is not set. if o.mapping == nil && enable { o.mapping = normalize } o.trie = trie o.validateLabels = enable o.fromPuny = validateFromPunycode } } // StrictDomainName limits the set of permissible ASCII characters to those // allowed in domain names as defined in RFC 1034 (A-Z, a-z, 0-9 and the // hyphen). This is set by default for MapForLookup and ValidateForRegistration. // // This option is useful, for instance, for browsers that allow characters // outside this range, for example a '_' (U+005F LOW LINE). See // http://www.rfc-editor.org/std/std3.txt for more details This option // corresponds to the UseSTD3ASCIIRules option in UTS #46. func StrictDomainName(use bool) Option { return func(o *options) { o.trie = trie o.useSTD3Rules = use o.fromPuny = validateFromPunycode } } // NOTE: the following options pull in tables. The tables should not be linked // in as long as the options are not used. // BidiRule enables the Bidi rule as defined in RFC 5893. Any application // that relies on proper validation of labels should include this rule. func BidiRule() Option { return func(o *options) { o.bidirule = bidirule.ValidString } } // ValidateForRegistration sets validation options to verify that a given IDN is // properly formatted for registration as defined by Section 4 of RFC 5891. func ValidateForRegistration() Option { return func(o *options) { o.mapping = validateRegistration StrictDomainName(true)(o) ValidateLabels(true)(o) VerifyDNSLength(true)(o) BidiRule()(o) } } // MapForLookup sets validation and mapping options such that a given IDN is // transformed for domain name lookup according to the requirements set out in // Section 5 of RFC 5891. The mappings follow the recommendations of RFC 5894, // RFC 5895 and UTS 46. It does not add the Bidi Rule. Use the BidiRule option // to add this check. // // The mappings include normalization and mapping case, width and other // compatibility mappings. func MapForLookup() Option { return func(o *options) { o.mapping = validateAndMap StrictDomainName(true)(o) ValidateLabels(true)(o) } } type options struct { transitional bool useSTD3Rules bool validateLabels bool verifyDNSLength bool removeLeadingDots bool trie *idnaTrie // fromPuny calls validation rules when converting A-labels to U-labels. fromPuny func(p *Profile, s string) error // mapping implements a validation and mapping step as defined in RFC 5895 // or UTS 46, tailored to, for example, domain registration or lookup. mapping func(p *Profile, s string) (mapped string, isBidi bool, err error) // bidirule, if specified, checks whether s conforms to the Bidi Rule // defined in RFC 5893. bidirule func(s string) bool } // A Profile defines the configuration of an IDNA mapper. type Profile struct { options } func apply(o *options, opts []Option) { for _, f := range opts { f(o) } } // New creates a new Profile. // // With no options, the returned Profile is the most permissive and equals the // Punycode Profile. Options can be passed to further restrict the Profile. The // MapForLookup and ValidateForRegistration options set a collection of options, // for lookup and registration purposes respectively, which can be tailored by // adding more fine-grained options, where later options override earlier // options. func New(o ...Option) *Profile { p := &Profile{} apply(&p.options, o) return p } // ToASCII converts a domain or domain label to its ASCII form. For example, // ToASCII("bücher.example.com") is "xn--bcher-kva.example.com", and // ToASCII("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToASCII(s string) (string, error) { return p.process(s, true) } // ToUnicode converts a domain or domain label to its Unicode form. For example, // ToUnicode("xn--bcher-kva.example.com") is "bücher.example.com", and // ToUnicode("golang") is "golang". If an error is encountered it will return // an error and a (partially) processed result. func (p *Profile) ToUnicode(s string) (string, error) { pp := *p pp.transitional = false return pp.process(s, false) } // String reports a string with a description of the profile for debugging // purposes. The string format may change with different versions. func (p *Profile) String() string { s := "" if p.transitional { s = "Transitional" } else { s = "NonTransitional" } if p.useSTD3Rules { s += ":UseSTD3Rules" } if p.validateLabels { s += ":ValidateLabels" } if p.verifyDNSLength { s += ":VerifyDNSLength" } return s } var ( // Punycode is a Profile that does raw punycode processing with a minimum // of validation. Punycode *Profile = punycode // Lookup is the recommended profile for looking up domain names, according // to Section 5 of RFC 5891. The exact configuration of this profile may // change over time. Lookup *Profile = lookup // Display is the recommended profile for displaying domain names. // The configuration of this profile may change over time. Display *Profile = display // Registration is the recommended profile for checking whether a given // IDN is valid for registration, according to Section 4 of RFC 5891. Registration *Profile = registration punycode = &Profile{} lookup = &Profile{options{ transitional: true, useSTD3Rules: true, validateLabels: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} display = &Profile{options{ useSTD3Rules: true, validateLabels: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateAndMap, bidirule: bidirule.ValidString, }} registration = &Profile{options{ useSTD3Rules: true, validateLabels: true, verifyDNSLength: true, trie: trie, fromPuny: validateFromPunycode, mapping: validateRegistration, bidirule: bidirule.ValidString, }} // TODO: profiles // Register: recommended for approving domain names: don't do any mappings // but rather reject on invalid input. Bundle or block deviation characters. ) type labelError struct{ label, code_ string } func (e labelError) code() string { return e.code_ } func (e labelError) Error() string { return fmt.Sprintf("idna: invalid label %q", e.label) } type runeError rune func (e runeError) code() string { return "P1" } func (e runeError) Error() string { return fmt.Sprintf("idna: disallowed rune %U", e) } // process implements the algorithm described in section 4 of UTS #46, // see http://www.unicode.org/reports/tr46. func (p *Profile) process(s string, toASCII bool) (string, error) { var err error var isBidi bool if p.mapping != nil { s, isBidi, err = p.mapping(p, s) } // Remove leading empty labels. if p.removeLeadingDots { for ; len(s) > 0 && s[0] == '.'; s = s[1:] { } } // TODO: allow for a quick check of the tables data. // It seems like we should only create this error on ToASCII, but the // UTS 46 conformance tests suggests we should always check this. if err == nil && p.verifyDNSLength && s == "" { err = &labelError{s, "A4"} } labels := labelIter{orig: s} for ; !labels.done(); labels.next() { label := labels.label() if label == "" { // Empty labels are not okay. The label iterator skips the last // label if it is empty. if err == nil && p.verifyDNSLength { err = &labelError{s, "A4"} } continue } if strings.HasPrefix(label, acePrefix) { u, err2 := decode(label[len(acePrefix):]) if err2 != nil { if err == nil { err = err2 } // Spec says keep the old label. continue } isBidi = isBidi || bidirule.DirectionString(u) != bidi.LeftToRight labels.set(u) if err == nil && p.validateLabels { err = p.fromPuny(p, u) } if err == nil { // This should be called on NonTransitional, according to the // spec, but that currently does not have any effect. Use the // original profile to preserve options. err = p.validateLabel(u) } } else if err == nil { err = p.validateLabel(label) } } if isBidi && p.bidirule != nil && err == nil { for labels.reset(); !labels.done(); labels.next() { if !p.bidirule(labels.label()) { err = &labelError{s, "B"} break } } } if toASCII { for labels.reset(); !labels.done(); labels.next() { label := labels.label() if !ascii(label) { a, err2 := encode(acePrefix, label) if err == nil { err = err2 } label = a labels.set(a) } n := len(label) if p.verifyDNSLength && err == nil && (n == 0 || n > 63) { err = &labelError{label, "A4"} } } } s = labels.result() if toASCII && p.verifyDNSLength && err == nil { // Compute the length of the domain name minus the root label and its dot. n := len(s) if n > 0 && s[n-1] == '.' { n-- } if len(s) < 1 || n > 253 { err = &labelError{s, "A4"} } } return s, err } func normalize(p *Profile, s string) (mapped string, isBidi bool, err error) { // TODO: consider first doing a quick check to see if any of these checks // need to be done. This will make it slower in the general case, but // faster in the common case. mapped = norm.NFC.String(s) isBidi = bidirule.DirectionString(mapped) == bidi.RightToLeft return mapped, isBidi, nil } func validateRegistration(p *Profile, s string) (idem string, bidi bool, err error) { // TODO: filter need for normalization in loop below. if !norm.NFC.IsNormalString(s) { return s, false, &labelError{s, "V1"} } for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { return s, bidi, runeError(utf8.RuneError) } bidi = bidi || info(v).isBidi(s[i:]) // Copy bytes not copied so far. switch p.simplify(info(v).category()) { // TODO: handle the NV8 defined in the Unicode idna data set to allow // for strict conformance to IDNA2008. case valid, deviation: case disallowed, mapped, unknown, ignored: r, _ := utf8.DecodeRuneInString(s[i:]) return s, bidi, runeError(r) } i += sz } return s, bidi, nil } func (c info) isBidi(s string) bool { if !c.isMapped() { return c&attributesMask == rtl } // TODO: also store bidi info for mapped data. This is possible, but a bit // cumbersome and not for the common case. p, _ := bidi.LookupString(s) switch p.Class() { case bidi.R, bidi.AL, bidi.AN: return true } return false } func validateAndMap(p *Profile, s string) (vm string, bidi bool, err error) { var ( b []byte k int ) // combinedInfoBits contains the or-ed bits of all runes. We use this // to derive the mayNeedNorm bit later. This may trigger normalization // overeagerly, but it will not do so in the common case. The end result // is another 10% saving on BenchmarkProfile for the common case. var combinedInfoBits info for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { b = append(b, s[k:i]...) b = append(b, "\ufffd"...) k = len(s) if err == nil { err = runeError(utf8.RuneError) } break } combinedInfoBits |= info(v) bidi = bidi || info(v).isBidi(s[i:]) start := i i += sz // Copy bytes not copied so far. switch p.simplify(info(v).category()) { case valid: continue case disallowed: if err == nil { r, _ := utf8.DecodeRuneInString(s[start:]) err = runeError(r) } continue case mapped, deviation: b = append(b, s[k:start]...) b = info(v).appendMapping(b, s[start:i]) case ignored: b = append(b, s[k:start]...) // drop the rune case unknown: b = append(b, s[k:start]...) b = append(b, "\ufffd"...) } k = i } if k == 0 { // No changes so far. if combinedInfoBits&mayNeedNorm != 0 { s = norm.NFC.String(s) } } else { b = append(b, s[k:]...) if norm.NFC.QuickSpan(b) != len(b) { b = norm.NFC.Bytes(b) } // TODO: the punycode converters require strings as input. s = string(b) } return s, bidi, err } // A labelIter allows iterating over domain name labels. type labelIter struct { orig string slice []string curStart int curEnd int i int } func (l *labelIter) reset() { l.curStart = 0 l.curEnd = 0 l.i = 0 } func (l *labelIter) done() bool { return l.curStart >= len(l.orig) } func (l *labelIter) result() string { if l.slice != nil { return strings.Join(l.slice, ".") } return l.orig } func (l *labelIter) label() string { if l.slice != nil { return l.slice[l.i] } p := strings.IndexByte(l.orig[l.curStart:], '.') l.curEnd = l.curStart + p if p == -1 { l.curEnd = len(l.orig) } return l.orig[l.curStart:l.curEnd] } // next sets the value to the next label. It skips the last label if it is empty. func (l *labelIter) next() { l.i++ if l.slice != nil { if l.i >= len(l.slice) || l.i == len(l.slice)-1 && l.slice[l.i] == "" { l.curStart = len(l.orig) } } else { l.curStart = l.curEnd + 1 if l.curStart == len(l.orig)-1 && l.orig[l.curStart] == '.' { l.curStart = len(l.orig) } } } func (l *labelIter) set(s string) { if l.slice == nil { l.slice = strings.Split(l.orig, ".") } l.slice[l.i] = s } // acePrefix is the ASCII Compatible Encoding prefix. const acePrefix = "xn--" func (p *Profile) simplify(cat category) category { switch cat { case disallowedSTD3Mapped: if p.useSTD3Rules { cat = disallowed } else { cat = mapped } case disallowedSTD3Valid: if p.useSTD3Rules { cat = disallowed } else { cat = valid } case deviation: if !p.transitional { cat = valid } case validNV8, validXV8: // TODO: handle V2008 cat = valid } return cat } func validateFromPunycode(p *Profile, s string) error { if !norm.NFC.IsNormalString(s) { return &labelError{s, "V1"} } // TODO: detect whether string may have to be normalized in the following // loop. for i := 0; i < len(s); { v, sz := trie.lookupString(s[i:]) if sz == 0 { return runeError(utf8.RuneError) } if c := p.simplify(info(v).category()); c != valid && c != deviation { return &labelError{s, "V6"} } i += sz } return nil } const ( zwnj = "\u200c" zwj = "\u200d" ) type joinState int8 const ( stateStart joinState = iota stateVirama stateBefore stateBeforeVirama stateAfter stateFAIL ) var joinStates = [][numJoinTypes]joinState{ stateStart: { joiningL: stateBefore, joiningD: stateBefore, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateVirama, }, stateVirama: { joiningL: stateBefore, joiningD: stateBefore, }, stateBefore: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, joinZWNJ: stateAfter, joinZWJ: stateFAIL, joinVirama: stateBeforeVirama, }, stateBeforeVirama: { joiningL: stateBefore, joiningD: stateBefore, joiningT: stateBefore, }, stateAfter: { joiningL: stateFAIL, joiningD: stateBefore, joiningT: stateAfter, joiningR: stateStart, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateAfter, // no-op as we can't accept joiners here }, stateFAIL: { 0: stateFAIL, joiningL: stateFAIL, joiningD: stateFAIL, joiningT: stateFAIL, joiningR: stateFAIL, joinZWNJ: stateFAIL, joinZWJ: stateFAIL, joinVirama: stateFAIL, }, } // validateLabel validates the criteria from Section 4.1. Item 1, 4, and 6 are // already implicitly satisfied by the overall implementation. func (p *Profile) validateLabel(s string) (err error) { if s == "" { if p.verifyDNSLength { return &labelError{s, "A4"} } return nil } if !p.validateLabels { return nil } trie := p.trie // p.validateLabels is only set if trie is set. if len(s) > 4 && s[2] == '-' && s[3] == '-' { return &labelError{s, "V2"} } if s[0] == '-' || s[len(s)-1] == '-' { return &labelError{s, "V3"} } // TODO: merge the use of this in the trie. v, sz := trie.lookupString(s) x := info(v) if x.isModifier() { return &labelError{s, "V5"} } // Quickly return in the absence of zero-width (non) joiners. if strings.Index(s, zwj) == -1 && strings.Index(s, zwnj) == -1 { return nil } st := stateStart for i := 0; ; { jt := x.joinType() if s[i:i+sz] == zwj { jt = joinZWJ } else if s[i:i+sz] == zwnj { jt = joinZWNJ } st = joinStates[st][jt] if x.isViramaModifier() { st = joinStates[st][joinVirama] } if i += sz; i == len(s) { break } v, sz = trie.lookupString(s[i:]) x = info(v) } if st == stateFAIL || st == stateAfter { return &labelError{s, "C"} } return nil } func ascii(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true }
go-tin/tin
vendor/golang.org/x/text/internal/export/idna/idna.go
GO
apache-2.0
20,293
/* * 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.deltaspike.core.api.literal; import javax.enterprise.util.AnnotationLiteral; import org.apache.deltaspike.core.api.lifecycle.Initialized; /** * Annotation literal for {@link Initialized}. */ public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized { public static final Initialized INSTANCE = new InitializedLiteral(); private static final long serialVersionUID = 2392444150652655120L; }
os890/deltaspike-vote
deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/literal/InitializedLiteral.java
Java
apache-2.0
1,262
/* chi_squared_test.hpp header file * * Copyright Steven Watanabe 2010 * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * $Id: chi_squared_test.hpp 71018 2011-04-05 21:27:52Z steven_watanabe $ * */ #ifndef BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED #define BOOST_RANDOM_TEST_CHI_SQUARED_TEST_HPP_INCLUDED #include <vector> #include <boost/math/special_functions/pow.hpp> #include <boost/math/distributions/chi_squared.hpp> // This only works for discrete distributions with fixed // upper and lower bounds. template<class IntType> struct chi_squared_collector { static const IntType cutoff = 5; chi_squared_collector() : chi_squared(0), variables(0), prev_actual(0), prev_expected(0), current_actual(0), current_expected(0) {} void operator()(IntType actual, double expected) { current_actual += actual; current_expected += expected; if(current_expected >= cutoff) { if(prev_expected != 0) { update(prev_actual, prev_expected); } prev_actual = current_actual; prev_expected = current_expected; current_actual = 0; current_expected = 0; } } void update(IntType actual, double expected) { chi_squared += boost::math::pow<2>(actual - expected) / expected; ++variables; } double cdf() { if(prev_expected != 0) { update(prev_actual + current_actual, prev_expected + current_expected); prev_actual = 0; prev_expected = 0; current_actual = 0; current_expected = 0; } if(variables <= 1) { return 0; } else { return boost::math::cdf(boost::math::chi_squared(variables - 1), chi_squared); } } double chi_squared; std::size_t variables; IntType prev_actual; double prev_expected; IntType current_actual; double current_expected; }; template<class IntType> double chi_squared_test(const std::vector<IntType>& results, const std::vector<double>& probabilities, IntType iterations) { chi_squared_collector<IntType> calc; for(std::size_t i = 0; i < results.size(); ++i) { calc(results[i], iterations * probabilities[i]); } return calc.cdf(); } #endif
NixaSoftware/CVis
venv/bin/libs/random/test/chi_squared_test.hpp
C++
apache-2.0
2,471
package com.mossle.ext; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.MultipartResolver; public class MultipartHandler { private static Logger logger = LoggerFactory .getLogger(MultipartHandler.class); private MultipartResolver multipartResolver; private MultipartHttpServletRequest multipartHttpServletRequest = null; private MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<String, String>(); private MultiValueMap<String, MultipartFile> multiFileMap; public MultipartHandler(MultipartResolver multipartResolver) { this.multipartResolver = multipartResolver; } public void handle(HttpServletRequest request) { if (request instanceof MultipartHttpServletRequest) { logger.debug("force cast to MultipartHttpServletRequest"); MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; this.multiFileMap = req.getMultiFileMap(); logger.debug("multiFileMap : {}", multiFileMap); this.handleMultiValueMap(req); logger.debug("multiValueMap : {}", multiValueMap); return; } if (multipartResolver.isMultipart(request)) { logger.debug("is multipart : {}", multipartResolver.isMultipart(request)); this.multipartHttpServletRequest = multipartResolver .resolveMultipart(request); logger.debug("multipartHttpServletRequest : {}", multipartHttpServletRequest); this.multiFileMap = multipartHttpServletRequest.getMultiFileMap(); logger.debug("multiFileMap : {}", multiFileMap); this.handleMultiValueMap(multipartHttpServletRequest); logger.debug("multiValueMap : {}", multiValueMap); } else { this.handleMultiValueMap(request); logger.debug("multiValueMap : {}", multiValueMap); } } public void clear() { if (multipartHttpServletRequest == null) { return; } multipartResolver.cleanupMultipart(multipartHttpServletRequest); } public void handleMultiValueMap(HttpServletRequest request) { Map<String, String[]> parameterMap = request.getParameterMap(); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); for (String value : entry.getValue()) { multiValueMap.add(key, value); } } } public MultiValueMap<String, String> getMultiValueMap() { return multiValueMap; } public MultiValueMap<String, MultipartFile> getMultiFileMap() { return multiFileMap; } }
callmeyan/lemon
src/main/java/com/mossle/ext/MultipartHandler.java
Java
apache-2.0
3,091
<?php /** * Отображение для environment: * * @category YupeView * @package yupe * @author Yupe Team <team@yupe.ru> * @license https://github.com/yupe/yupe/blob/master/LICENSE BSD * @link http://yupe.ru **/ ?> <?php if (!$data['result']) : { ?> <div class="alert alert-danger"> <b><?php echo Yii::t('InstallModule.install', 'Install can\'t be continued. Please check errors!'); ?></b> </div> <?php } endif; ?> <?php $this->widget('install.widgets.GetHelpWidget'); ?> <div class="alert alert-info"> <p><?php echo Yii::t( 'InstallModule.install', 'On this step Yupe checks access right for needed directories.' ); ?></p> <p><?php echo Yii::t( 'InstallModule.install', 'To continue installation you need to repair error was occured.' ); ?></p> </div> <table class="table table-striped"> <tr> <th><?php echo Yii::t('InstallModule.install', 'Value'); ?></th> <th><?php echo Yii::t('InstallModule.install', 'Result'); ?></th> <th><?php echo Yii::t('InstallModule.install', 'Comments'); ?></th> </tr> <?php foreach ($data['requirements'] as $requirement): { ?> <tr> <td style="width:200px;"><?php echo $requirement[0]; ?></td> <td> <?php $this->widget( 'bootstrap.widgets.TbLabel', [ 'context' => $requirement[1] ? 'success' : 'danger', 'label' => $requirement[1] ? 'ОК' : Yii::t('InstallModule.install', 'Error'), ] ); ?> </td> <td><?php echo $requirement[2]; ?></td> </tr> <?php } endforeach; ?> </table> <br/> <?php echo CHtml::link( Yii::t('InstallModule.install', '< Back'), ['/install/default/index'], ['class' => 'btn btn-primary'] ); ?> <?php if ($data['result'] !== false) { echo CHtml::link( Yii::t('InstallModule.install', 'Continue >'), ['/install/default/requirements'], ['class' => 'btn btn-primary'] ); } else { echo CHtml::link( Yii::t('InstallModule.install', 'Refresh'), ['/install/default/environment'], ['class' => 'btn btn-primary'] ); } ?>
Anton-Am/yupe
protected/modules/install/views/default/environment.php
PHP
bsd-3-clause
2,319
// RUN: mkdir -p %T/move-type-alias // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: cd %T/move-type-alias // // ----------------------------------------------------------------------------- // Test moving typedef declarations. // ----------------------------------------------------------------------------- // RUN: clang-move -names="Int1" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-NEW-TEST-H-CASE1 %s // RUN: FileCheck -input-file=%T/move-type-alias/type_alias.h -check-prefix=CHECK-OLD-TEST-H-CASE1 %s // CHECK-NEW-TEST-H-CASE1: typedef int Int1; // CHECK-OLD-TEST-H-CASE1-NOT: typedef int Int1; // ----------------------------------------------------------------------------- // Test moving type alias declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="Int2" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-NEW-TEST-H-CASE2 %s // RUN: FileCheck -input-file=%T/move-type-alias/type_alias.h -check-prefix=CHECK-OLD-TEST-H-CASE2 %s // CHECK-NEW-TEST-H-CASE2: using Int2 = int; // CHECK-OLD-TEST-H-CASE2-NOT: using Int2 = int; // ----------------------------------------------------------------------------- // Test moving template type alias declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="B" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -check-prefix=CHECK-OLD-TEST-H-CASE3 %s // CHECK-NEW-TEST-H-CASE3: template<class T> using B = A<T>; // CHECK-OLD-TEST-H-CASE3-NOT: template<class T> using B = A<T>; // ----------------------------------------------------------------------------- // Test not moving class-insided typedef declarations. // ----------------------------------------------------------------------------- // RUN: cp %S/Inputs/type_alias.h %T/move-type-alias/type_alias.h // RUN: echo '#include "type_alias.h"' > %T/move-type-alias/type_alias.cpp // RUN: clang-move -names="C::Int3" -new_cc=%T/move-type-alias/new_test.cpp -new_header=%T/move-type-alias/new_test.h -old_cc=%T/move-type-alias/type_alias.cpp -old_header=%T/move-type-alias/type_alias.h %T/move-type-alias/type_alias.cpp -- -std=c++11 // RUN: FileCheck -input-file=%T/move-type-alias/new_test.h -allow-empty -check-prefix=CHECK-EMPTY %s // CHECK-EMPTY: {{^}}{{$}}
endlessm/chromium-browser
third_party/llvm/clang-tools-extra/test/clang-move/move-type-alias.cpp
C++
bsd-3-clause
3,421
// Copyright 2008 The Closure Library 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. /** * @fileoverview Generator for unique element IDs. * */ goog.provide('goog.ui.IdGenerator'); /** * Creates a new id generator. * @constructor */ goog.ui.IdGenerator = function() { }; goog.addSingletonGetter(goog.ui.IdGenerator); /** * Next unique ID to use * @type {number} * @private */ goog.ui.IdGenerator.prototype.nextId_ = 0; /** * Gets the next unique ID. * @return {string} The next unique identifier. */ goog.ui.IdGenerator.prototype.getNextUniqueId = function() { return ':' + (this.nextId_++).toString(36); }; /** * Default instance for id generation. Done as an instance instead of statics * so it's possible to inject a mock for unit testing purposes. * @type {goog.ui.IdGenerator} * @deprecated Use goog.ui.IdGenerator.getInstance() instead and do not refer * to goog.ui.IdGenerator.instance anymore. */ goog.ui.IdGenerator.instance = goog.ui.IdGenerator.getInstance();
marcelohg/NasajonWebTeamplateProject
web/js/google-closure/closure/goog/ui/idgenerator.js
JavaScript
mit
1,545
// // Main.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2011 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace RecipesAndPrinting { public class Application { // This is the main entry point of the application. static void Main (string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } }
davidrynn/monotouch-samples
RecipesAndPrinting/Main.cs
C#
mit
1,607
#!/usr/bin/python2.4 # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Test for environment_tools. These are SMALL and MEDIUM tests.""" import os import unittest import TestFramework class EnvToolsTests(unittest.TestCase): """Tests for environment_tools module.""" def setUp(self): """Per-test setup.""" self.env = self.root_env.Clone() def testFilterOut(self): """Test FilterOut().""" env = self.env env.Replace( TEST1=['ant', 'bear', 'cat'], TEST2=[1, 2, 3, 4], ) # Simple filter env.FilterOut(TEST1=['bear']) self.assertEqual(env['TEST1'], ['ant', 'cat']) # Filter multiple env.FilterOut(TEST1=['ant'], TEST2=[1, 3]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) # Filter doesn't care if the variable or value doesn't exist env.FilterOut(TEST1=['dog'], TEST3=[2]) self.assertEqual(env['TEST1'], ['cat']) self.assertEqual(env['TEST2'], [2, 4]) def testFilterOutRepeated(self): """Test FilterOut() filters all matches.""" env = self.env env['TEST3'] = ['A', 'B', 'B', 'C'] env.FilterOut(TEST3=['B']) self.assertEqual(env['TEST3'], ['A', 'C']) def testFilterOutNested(self): """Test FilterOut on nested lists.""" env = self.env # FilterOut does not currently flatten lists, nor remove values from # sub-lists. This is related to not evaluating environment variables (see # below). env['TEST4'] = ['A', ['B', 'C'], 'D'] env.FilterOut(TEST4=['B']) self.assertEqual(env['TEST4'], ['A', ['B', 'C'], 'D']) # If you specify the entire sub-list, it will be filtered env.FilterOut(TEST4=[['B', 'C']]) self.assertEqual(env['TEST4'], ['A', 'D']) def testFilterOutNoEval(self): """Test FilterOut does not evaluate variables in the list.""" env = self.env # FilterOut does not evaluate variables in the list. (Doing so would # defeat much of the purpose of variables.) Note that this means it does # not filter variables which evaluate partially or wholly to the filtered # string. On the plus side, this means you CAN filter out variables. env.Replace( TEST5=['$V1', '$V2', '$V3', '$V4'], V1='A', # (V2 intentionally undefined at this point) V3=['A', 'B'], V4='C', ) env.FilterOut(TEST5=['A', '$V4']) self.assertEqual(env['TEST5'], ['$V1', '$V2', '$V3']) def testOverlap(self): """Test Overlap().""" env = self.env env.Replace( OLVAR='baz', OLLIST=['2', '3', '4'], ) # Simple string compares self.assertEqual(env.Overlap('foo', 'foo'), ['foo']) self.assertEqual(env.Overlap('foo', 'food'), []) # String compare with variable substitution self.assertEqual(env.Overlap('foobaz', 'foo$OLVAR'), ['foobaz']) # Simple list overlap # Need to use set() for comparison, since the order of entries in the # output list is indeterminate self.assertEqual(set(env.Overlap(['1', '2', '3'], ['2', '3', '4'])), set(['2', '3'])) # Overlap removes duplicates self.assertEqual(env.Overlap(['1', '2', '2'], ['2', '3', '2']), ['2']) # List and string self.assertEqual(env.Overlap('3', ['1', '2', '3']), ['3']) self.assertEqual(env.Overlap('4', ['1', '2', '3']), []) self.assertEqual(env.Overlap(['1', '$OLVAR', '3'], '$OLVAR'), ['baz']) # Variable substitition will replace and flatten lists self.assertEqual(set(env.Overlap(['1', '2', '3'], '$OLLIST')), set(['2', '3'])) # Substitution flattens lists self.assertEqual(set(env.Overlap([['1', '2'], '3'], ['2', ['3', '4']])), set(['2', '3'])) def testSubstList2(self): """Test SubstList2().""" env = self.env # Empty args should return empty list self.assertEqual(env.SubstList2(), []) # Undefined variable also returns empty list self.assertEqual(env.SubstList2('$NO_SUCH_VAR'), []) # Simple substitution (recursively evaluates variables) env['STR1'] = 'FOO$STR2' env['STR2'] = 'BAR' self.assertEqual(env.SubstList2('$STR1'), ['FOOBAR']) # Simple list substitution env['LIST1'] = ['A', 'B'] self.assertEqual(env.SubstList2('$LIST1'), ['A', 'B']) # Nested lists env['LIST2'] = ['C', '$LIST1'] self.assertEqual(env.SubstList2('$LIST2'), ['C', 'A', 'B']) # Multiple variables in a single entry stay a single entry self.assertEqual(env.SubstList2('$STR1 $STR2'), ['FOOBAR BAR']) # Multiple args to command self.assertEqual(env.SubstList2('$LIST2', '$STR2'), ['C', 'A', 'B', 'BAR']) # Items in list are actually strings, not some subclass self.assert_(type(env.SubstList2('$STR1')[0]) is str) def testRelativePath(self): """Test RelativePath().""" env = self.env # Trivial cases - directory or file relative to itself self.assertEqual(env.RelativePath('a', 'a'), '.') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c'), '.') self.assertEqual(env.RelativePath('a', 'a', source_is_file=True), 'a') self.assertEqual(env.RelativePath('a/b/c', 'a/b/c', source_is_file=True), 'c') # Can pass in directory or file nodes self.assertEqual(env.RelativePath(env.Dir('a'), env.File('b/c'), sep='/'), '../b/c') # Separator argument is respected self.assertEqual(env.RelativePath('.', 'a/b/c', sep='BOOGA'), 'aBOOGAbBOOGAc') # Default separator is os.sep self.assertEqual(env.RelativePath('.', 'a/b'), 'a' + os.sep + 'b') # No common dirs self.assertEqual(env.RelativePath('a/b/c', 'd/e/f', sep='/'), '../../../d/e/f') self.assertEqual( env.RelativePath('a/b/c', 'd/e/f', sep='/', source_is_file=True), '../../d/e/f') # Common dirs self.assertEqual(env.RelativePath('a/b/c/d', 'a/b/e/f', sep='/'), '../../e/f') # Source or destination path is different length self.assertEqual(env.RelativePath('a/b/c/d', 'a/b', sep='/'), '../..') self.assertEqual(env.RelativePath('a/b', 'a/b/c/d', sep='/'), 'c/d') # Current directory on either side self.assertEqual(env.RelativePath('a/b/c', '.', sep='/'), '../../..') self.assertEqual(env.RelativePath('.', 'a/b/c', sep='/'), 'a/b/c') # Variables are evaluated env.Replace( DIR1='foo', DIR2='bar', ) self.assertEqual(env.RelativePath('foo/$DIR2/a', '$DIR1/bar/b', sep='/'), '../b') def testApplyBuildSConscript(self): """Test ApplySConscript() and BuildSConscript() (MEDIUM test).""" env = self.env env['SUB1'] = 'nougat' # ApplySConscript() affects the calling environment env.ApplySConscript('SConscript1') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript() does not affect the calling environment env.BuildSConscript('SConscript2') self.assertEqual(env.get('SUB2'), 'orange') # BuildSConscript finds build.scons in preference to SConscript env.BuildSConscript('abs1') # But does look for SConscript if there isn't build.scons env.BuildSConscript('abs2') def TestSConstruct(scons_globals): """Test SConstruct file. Args: scons_globals: Global variables dict from the SConscript file. """ # Get globals from SCons Environment = scons_globals['Environment'] env = Environment(tools=['environment_tools']) # Run unit tests TestFramework.RunUnitTests(EnvToolsTests, root_env=env) sconscript1_contents = """ Import('env') if env.get('SUB1') != 'nougat': raise ValueError('ApplySConscript() failure in sconscript1') env['SUB2'] = 'orange' """ sconscript2_contents = """ Import('env') if env.get('SUB1') != 'nougat': raise ValueError('BuildSConscript() failure in sconscript2') env['SUB2'] = 'pizza' """ sconscript3_contents = """ Import('env') filename = '%s' env.Execute(Touch(filename)) """ def main(): test = TestFramework.TestFramework() test.subdir('environment_tools') base = 'environment_tools/' test.WriteSConscript(base + 'SConstruct', TestSConstruct) test.write(base + 'SConscript1', sconscript1_contents) test.write(base + 'SConscript2', sconscript2_contents) test.subdir(base + 'abs1') test.write(base + 'abs1/build.scons', sconscript3_contents % 'yes1') test.write(base + 'abs1/SConscript', sconscript3_contents % 'no') test.subdir(base + 'abs2') test.write(base + 'abs2/SConscript', sconscript3_contents % 'yes2') # Ignore stderr since unittest prints its output there test.run(chdir=base, stderr=None) test.must_exist(base + 'abs1/yes1') test.must_not_exist(base + 'abs1/no') test.must_exist(base + 'abs2/yes2') test.pass_test() if __name__ == '__main__': main()
nguyentran/openviber
tools/swtoolkit/test/environment_tools_test.py
Python
mit
10,313
// Type definitions for geojson 7946.0 // Project: https://geojson.org/ // Definitions by: Jacob Bruun <https://github.com/cobster> // Arne Schubert <https://github.com/atd-schubert> // Jeff Jacobson <https://github.com/JeffJacobson> // Ilia Choly <https://github.com/icholy> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 // Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems // are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} export as namespace GeoJSON; /** * The valid values for the "type" property of GeoJSON geometry objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ export type GeoJsonGeometryTypes = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | "MultiPolygon" | "GeometryCollection"; /** * The value values for the "type" property of GeoJSON Objects. * https://tools.ietf.org/html/rfc7946#section-1.4 */ export type GeoJsonTypes = "FeatureCollection" | "Feature" | GeoJsonGeometryTypes; /** * Bounding box * https://tools.ietf.org/html/rfc7946#section-5 */ export type BBox = [number, number, number, number] | [number, number, number, number, number, number]; /** * A Position is an array of coordinates. * https://tools.ietf.org/html/rfc7946#section-3.1.1 * Array should contain between two and three elements. * The previous GeoJSON specification allowed more elements (e.g., which could be used to represent M values), * but the current specification only allows X, Y, and (optionally) Z to be defined. */ export type Position = number[]; // [number, number] | [number, number, number]; /** * The base GeoJSON object. * https://tools.ietf.org/html/rfc7946#section-3 * The GeoJSON specification also allows foreign members * (https://tools.ietf.org/html/rfc7946#section-6.1) * Developers should use "&" type in TypeScript or extend the interface * to add these foreign members. */ export interface GeoJsonObject { // Don't include foreign members directly into this type def. // in order to preserve type safety. // [key: string]: any; /** * Specifies the type of GeoJSON object. */ type: GeoJsonTypes; /** * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. * https://tools.ietf.org/html/rfc7946#section-5 */ bbox?: BBox; } /** * Union of GeoJSON objects. */ export type GeoJSON = Geometry | Feature | FeatureCollection; /** * A geometry object. * https://tools.ietf.org/html/rfc7946#section-3 */ export interface GeometryObject extends GeoJsonObject { type: GeoJsonGeometryTypes; } /** * Union of geometry objects. * https://tools.ietf.org/html/rfc7946#section-3 */ export type Geometry = Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon | GeometryCollection; /** * Point geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ export interface Point extends GeometryObject { type: "Point"; coordinates: Position; } /** * MultiPoint geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ export interface MultiPoint extends GeometryObject { type: "MultiPoint"; coordinates: Position[]; } /** * LineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ export interface LineString extends GeometryObject { type: "LineString"; coordinates: Position[]; } /** * MultiLineString geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ export interface MultiLineString extends GeometryObject { type: "MultiLineString"; coordinates: Position[][]; } /** * Polygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ export interface Polygon extends GeometryObject { type: "Polygon"; coordinates: Position[][]; } /** * MultiPolygon geometry object. * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ export interface MultiPolygon extends GeometryObject { type: "MultiPolygon"; coordinates: Position[][][]; } /** * Geometry Collection * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ export interface GeometryCollection extends GeometryObject { type: "GeometryCollection"; geometries: Geometry[]; } export type GeoJsonProperties = { [name: string]: any; } | null; /** * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ export interface Feature<G extends GeometryObject | null = Geometry, P = GeoJsonProperties> extends GeoJsonObject { type: "Feature"; /** * The feature's geometry */ geometry: G; /** * A value that uniquely identifies this feature in a * https://tools.ietf.org/html/rfc7946#section-3.2. */ id?: string | number; /** * Properties associated with this feature. */ properties: P; } /** * A collection of feature objects. * https://tools.ietf.org/html/rfc7946#section-3.3 */ export interface FeatureCollection<G extends GeometryObject | null = Geometry, P = GeoJsonProperties> extends GeoJsonObject { type: "FeatureCollection"; features: Array<Feature<G, P>>; }
AgentME/DefinitelyTyped
types/geojson/index.d.ts
TypeScript
mit
5,288
version https://git-lfs.github.com/spec/v1 oid sha256:df5a7287a63d8b28fe1df2552b7f2deaa719327f8aa49fef192f5fb72bbbbaad size 4023
yogeshsaroya/new-cdnjs
ajax/libs/ink/3.1.7/js/html5shiv-printshiv.js
JavaScript
mit
129
'use strict'; var path = require('path'); var mergeTrees = require('broccoli-merge-trees'); var SassCompiler = require('../broccoli-sass'); function SASSPlugin() { this.name = 'ember-cli-sass'; this.ext = ['scss', 'sass']; } SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) { var options = inputOptions; var inputTrees = [tree]; if (options.includePaths) { inputTrees = inputTrees.concat(options.includePaths); } var ext = options.extension || 'scss'; var paths = options.outputPaths; var trees = Object.keys(paths).map(function(file) { var input = path.join(inputPath, file + '.' + ext); var output = paths[file]; return new SassCompiler(inputTrees, input, output, options); }); return mergeTrees(trees); }; module.exports = { name: 'ember-cli-sass', setupPreprocessorRegistry: function(type, registry) { registry.add('css', new SASSPlugin()); }, };
xtian/ember-cli
tests/fixtures/preprocessor-tests/app-with-addon-with-preprocessors/node_modules/ember-cli-sass/index.js
JavaScript
mit
940
<?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 MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\DBAL\Platforms; use Doctrine\DBAL\Schema\TableDiff, Doctrine\DBAL\Schema\Table; /** * PostgreSqlPlatform. * * @since 2.0 * @author Roman Borschel <roman@code-factory.org> * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library) * @author Benjamin Eberlei <kontakt@beberlei.de> * @todo Rename: PostgreSQLPlatform */ class PostgreSqlPlatform extends AbstractPlatform { /** * @var bool */ private $useBooleanTrueFalseStrings = true; /** * PostgreSQL has different behavior with some drivers * with regard to how booleans have to be handled. * * Enables use of 'true'/'false' or otherwise 1 and 0 instead. * * @param bool $flag */ public function setUseBooleanTrueFalseStrings($flag) { $this->useBooleanTrueFalseStrings = (bool)$flag; } /** * {@inheritDoc} */ public function getSubstringExpression($value, $from, $length = null) { if ($length === null) { return 'SUBSTRING(' . $value . ' FROM ' . $from . ')'; } return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $length . ')'; } /** * {@inheritDoc} */ public function getNowExpression() { return 'LOCALTIMESTAMP(0)'; } /** * {@inheritDoc} */ public function getRegexpExpression() { return 'SIMILAR TO'; } /** * {@inheritDoc} */ public function getLocateExpression($str, $substr, $startPos = false) { if ($startPos !== false) { $str = $this->getSubstringExpression($str, $startPos); return 'CASE WHEN (POSITION('.$substr.' IN '.$str.') = 0) THEN 0 ELSE (POSITION('.$substr.' IN '.$str.') + '.($startPos-1).') END'; } return 'POSITION('.$substr.' IN '.$str.')'; } /** * {@inheritDoc} */ public function getDateDiffExpression($date1, $date2) { return '(DATE(' . $date1 . ')-DATE(' . $date2 . '))'; } /** * {@inheritDoc} */ public function getDateAddDaysExpression($date, $days) { return "(" . $date ." + (" . $days . " || ' day')::interval)"; } /** * {@inheritDoc} */ public function getDateSubDaysExpression($date, $days) { return "(" . $date ." - (" . $days . " || ' day')::interval)"; } /** * {@inheritDoc} */ public function getDateAddMonthExpression($date, $months) { return "(" . $date ." + (" . $months . " || ' month')::interval)"; } /** * {@inheritDoc} */ public function getDateSubMonthExpression($date, $months) { return "(" . $date ." - (" . $months . " || ' month')::interval)"; } /** * {@inheritDoc} */ public function supportsSequences() { return true; } /** * {@inheritDoc} */ public function supportsSchemas() { return true; } /** * {@inheritDoc} */ public function supportsIdentityColumns() { return true; } /** * {@inheritDoc} */ public function supportsCommentOnStatement() { return true; } /** * {@inheritDoc} */ public function prefersSequences() { return true; } /** * {@inheritDoc} */ public function hasNativeGuidType() { return true; } public function getListDatabasesSQL() { return 'SELECT datname FROM pg_database'; } public function getListSequencesSQL($database) { return "SELECT c.relname, n.nspname AS schemaname FROM pg_class c, pg_namespace n WHERE relkind = 'S' AND n.oid = c.relnamespace AND (n.nspname NOT LIKE 'pg_%' AND n.nspname != 'information_schema')"; } public function getListTablesSQL() { return "SELECT tablename AS table_name, schemaname AS schema_name FROM pg_tables WHERE schemaname NOT LIKE 'pg_%' AND schemaname != 'information_schema' AND tablename != 'geometry_columns' AND tablename != 'spatial_ref_sys'"; } /** * {@inheritDoc} */ public function getListViewsSQL($database) { return 'SELECT viewname, definition FROM pg_views'; } public function getListTableForeignKeysSQL($table, $database = null) { return "SELECT r.conname, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = ( SELECT c.oid FROM pg_catalog.pg_class c, pg_catalog.pg_namespace n WHERE " .$this->getTableWhereClause($table) ." AND n.oid = c.relnamespace ) AND r.contype = 'f'"; } public function getCreateViewSQL($name, $sql) { return 'CREATE VIEW ' . $name . ' AS ' . $sql; } public function getDropViewSQL($name) { return 'DROP VIEW '. $name; } public function getListTableConstraintsSQL($table) { return "SELECT relname FROM pg_class WHERE oid IN ( SELECT indexrelid FROM pg_index, pg_class WHERE pg_class.relname = '$table' AND pg_class.oid = pg_index.indrelid AND (indisunique = 't' OR indisprimary = 't') )"; } /** * {@inheritDoc} * * @license New BSD License * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html */ public function getListTableIndexesSQL($table, $currentDatabase = null) { return "SELECT relname, pg_index.indisunique, pg_index.indisprimary, pg_index.indkey, pg_index.indrelid FROM pg_class, pg_index WHERE oid IN ( SELECT indexrelid FROM pg_index si, pg_class sc, pg_namespace sn WHERE " . $this->getTableWhereClause($table, 'sc', 'sn')." AND sc.oid=si.indrelid AND sc.relnamespace = sn.oid ) AND pg_index.indexrelid = oid"; } /** * @param string $table * @param string $classAlias * @param string $namespaceAlias * * @return string */ private function getTableWhereClause($table, $classAlias = 'c', $namespaceAlias = 'n') { $whereClause = $namespaceAlias.".nspname NOT IN ('pg_catalog', 'information_schema', 'pg_toast') AND "; if (strpos($table, ".") !== false) { list($schema, $table) = explode(".", $table); $schema = "'" . $schema . "'"; } else { $schema = "ANY(string_to_array((select replace(setting,'\"\$user\"',user) from pg_catalog.pg_settings where name = 'search_path'),','))"; } $whereClause .= "$classAlias.relname = '" . $table . "' AND $namespaceAlias.nspname = $schema"; return $whereClause; } public function getListTableColumnsSQL($table, $database = null) { return "SELECT a.attnum, a.attname AS field, t.typname AS type, format_type(a.atttypid, a.atttypmod) AS complete_type, (SELECT t1.typname FROM pg_catalog.pg_type t1 WHERE t1.oid = t.typbasetype) AS domain_type, (SELECT format_type(t2.typbasetype, t2.typtypmod) FROM pg_catalog.pg_type t2 WHERE t2.typtype = 'd' AND t2.oid = a.atttypid) AS domain_complete_type, a.attnotnull AS isnotnull, (SELECT 't' FROM pg_index WHERE c.oid = pg_index.indrelid AND pg_index.indkey[0] = a.attnum AND pg_index.indisprimary = 't' ) AS pri, (SELECT pg_attrdef.adsrc FROM pg_attrdef WHERE c.oid = pg_attrdef.adrelid AND pg_attrdef.adnum=a.attnum ) AS default, (SELECT pg_description.description FROM pg_description WHERE pg_description.objoid = c.oid AND a.attnum = pg_description.objsubid ) AS comment FROM pg_attribute a, pg_class c, pg_type t, pg_namespace n WHERE ".$this->getTableWhereClause($table, 'c', 'n') ." AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid AND n.oid = c.relnamespace ORDER BY a.attnum"; } /** * {@inheritDoc} */ public function getCreateDatabaseSQL($name) { return 'CREATE DATABASE ' . $name; } /** * {@inheritDoc} */ public function getAdvancedForeignKeyOptionsSQL(\Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey) { $query = ''; if ($foreignKey->hasOption('match')) { $query .= ' MATCH ' . $foreignKey->getOption('match'); } $query .= parent::getAdvancedForeignKeyOptionsSQL($foreignKey); if ($foreignKey->hasOption('deferrable') && $foreignKey->getOption('deferrable') !== false) { $query .= ' DEFERRABLE'; } else { $query .= ' NOT DEFERRABLE'; } if (($foreignKey->hasOption('feferred') && $foreignKey->getOption('feferred') !== false) || ($foreignKey->hasOption('deferred') && $foreignKey->getOption('deferred') !== false) ) { $query .= ' INITIALLY DEFERRED'; } else { $query .= ' INITIALLY IMMEDIATE'; } return $query; } /** * {@inheritDoc} */ public function getAlterTableSQL(TableDiff $diff) { $sql = array(); $commentsSQL = array(); $columnSql = array(); foreach ($diff->addedColumns as $column) { if ($this->onSchemaAlterTableAddColumn($column, $diff, $columnSql)) { continue; } $query = 'ADD ' . $this->getColumnDeclarationSQL($column->getQuotedName($this), $column->toArray()); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; if ($comment = $this->getColumnComment($column)) { $commentsSQL[] = $this->getCommentOnColumnSQL($diff->name, $column->getName(), $comment); } } foreach ($diff->removedColumns as $column) { if ($this->onSchemaAlterTableRemoveColumn($column, $diff, $columnSql)) { continue; } $query = 'DROP ' . $column->getQuotedName($this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } foreach ($diff->changedColumns as $columnDiff) { /** @var $columnDiff \Doctrine\DBAL\Schema\ColumnDiff */ if ($this->onSchemaAlterTableChangeColumn($columnDiff, $diff, $columnSql)) { continue; } $oldColumnName = $columnDiff->oldColumnName; $column = $columnDiff->column; if ($columnDiff->hasChanged('type')) { $type = $column->getType(); // here was a server version check before, but DBAL API does not support this anymore. $query = 'ALTER ' . $oldColumnName . ' TYPE ' . $type->getSqlDeclaration($column->toArray(), $this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('default')) { $query = 'ALTER ' . $oldColumnName . ' SET ' . $this->getDefaultValueDeclarationSQL($column->toArray()); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('notnull')) { $query = 'ALTER ' . $oldColumnName . ' ' . ($column->getNotNull() ? 'SET' : 'DROP') . ' NOT NULL'; $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } if ($columnDiff->hasChanged('autoincrement')) { if ($column->getAutoincrement()) { // add autoincrement $seqName = $diff->name . '_' . $oldColumnName . '_seq'; $sql[] = "CREATE SEQUENCE " . $seqName; $sql[] = "SELECT setval('" . $seqName . "', (SELECT MAX(" . $oldColumnName . ") FROM " . $diff->name . "))"; $query = "ALTER " . $oldColumnName . " SET DEFAULT nextval('" . $seqName . "')"; $sql[] = "ALTER TABLE " . $diff->name . " " . $query; } else { // Drop autoincrement, but do NOT drop the sequence. It might be re-used by other tables or have $query = "ALTER " . $oldColumnName . " " . "DROP DEFAULT"; $sql[] = "ALTER TABLE " . $diff->name . " " . $query; } } if ($columnDiff->hasChanged('comment')) { $commentsSQL[] = $this->getCommentOnColumnSQL( $diff->name, $column->getName(), $this->getColumnComment($column) ); } if ($columnDiff->hasChanged('length')) { $query = 'ALTER ' . $column->getName() . ' TYPE ' . $column->getType()->getSqlDeclaration($column->toArray(), $this); $sql[] = 'ALTER TABLE ' . $diff->name . ' ' . $query; } } foreach ($diff->renamedColumns as $oldColumnName => $column) { if ($this->onSchemaAlterTableRenameColumn($oldColumnName, $column, $diff, $columnSql)) { continue; } $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME COLUMN ' . $oldColumnName . ' TO ' . $column->getQuotedName($this); } $tableSql = array(); if ( ! $this->onSchemaAlterTable($diff, $tableSql)) { if ($diff->newName !== false) { $sql[] = 'ALTER TABLE ' . $diff->name . ' RENAME TO ' . $diff->newName; } $sql = array_merge($sql, $this->_getAlterTableIndexForeignKeySQL($diff), $commentsSQL); } return array_merge($sql, $tableSql, $columnSql); } /** * {@inheritdoc} */ public function getCommentOnColumnSQL($tableName, $columnName, $comment) { $comment = $comment === null ? 'NULL' : "'$comment'"; return "COMMENT ON COLUMN $tableName.$columnName IS $comment"; } /** * {@inheritDoc} */ public function getCreateSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence) { return 'CREATE SEQUENCE ' . $sequence->getQuotedName($this) . ' INCREMENT BY ' . $sequence->getAllocationSize() . ' MINVALUE ' . $sequence->getInitialValue() . ' START ' . $sequence->getInitialValue(); } /** * {@inheritDoc} */ public function getAlterSequenceSQL(\Doctrine\DBAL\Schema\Sequence $sequence) { return 'ALTER SEQUENCE ' . $sequence->getQuotedName($this) . ' INCREMENT BY ' . $sequence->getAllocationSize(); } /** * {@inheritDoc} */ public function getDropSequenceSQL($sequence) { if ($sequence instanceof \Doctrine\DBAL\Schema\Sequence) { $sequence = $sequence->getQuotedName($this); } return 'DROP SEQUENCE ' . $sequence . ' CASCADE'; } /** * {@inheritDoc} */ public function getDropForeignKeySQL($foreignKey, $table) { return $this->getDropConstraintSQL($foreignKey, $table); } /** * {@inheritDoc} */ protected function _getCreateTableSQL($tableName, array $columns, array $options = array()) { $queryFields = $this->getColumnDeclarationListSQL($columns); if (isset($options['primary']) && ! empty($options['primary'])) { $keyColumns = array_unique(array_values($options['primary'])); $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; } $query = 'CREATE TABLE ' . $tableName . ' (' . $queryFields . ')'; $sql[] = $query; if (isset($options['indexes']) && ! empty($options['indexes'])) { foreach ($options['indexes'] as $index) { $sql[] = $this->getCreateIndexSQL($index, $tableName); } } if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $definition) { $sql[] = $this->getCreateForeignKeySQL($definition, $tableName); } } return $sql; } /** * {@inheritDoc} * * Postgres wants boolean values converted to the strings 'true'/'false'. */ public function convertBooleans($item) { if ( ! $this->useBooleanTrueFalseStrings) { return parent::convertBooleans($item); } if (is_array($item)) { foreach ($item as $key => $value) { if (is_bool($value) || is_numeric($item)) { $item[$key] = ($value) ? 'true' : 'false'; } } } else { if (is_bool($item) || is_numeric($item)) { $item = ($item) ? 'true' : 'false'; } } return $item; } public function getSequenceNextValSQL($sequenceName) { return "SELECT NEXTVAL('" . $sequenceName . "')"; } /** * {@inheritDoc} */ public function getSetTransactionIsolationSQL($level) { return 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ' . $this->_getTransactionIsolationLevelSQL($level); } /** * {@inheritDoc} */ public function getBooleanTypeDeclarationSQL(array $field) { return 'BOOLEAN'; } /** * {@inheritDoc} */ public function getIntegerTypeDeclarationSQL(array $field) { if ( ! empty($field['autoincrement'])) { return 'SERIAL'; } return 'INT'; } /** * {@inheritDoc} */ public function getBigIntTypeDeclarationSQL(array $field) { if ( ! empty($field['autoincrement'])) { return 'BIGSERIAL'; } return 'BIGINT'; } /** * {@inheritDoc} */ public function getSmallIntTypeDeclarationSQL(array $field) { return 'SMALLINT'; } /** * {@inheritDoc} */ public function getGuidTypeDeclarationSQL(array $field) { return 'UUID'; } /** * {@inheritDoc} */ public function getDateTimeTypeDeclarationSQL(array $fieldDeclaration) { return 'TIMESTAMP(0) WITHOUT TIME ZONE'; } /** * {@inheritDoc} */ public function getDateTimeTzTypeDeclarationSQL(array $fieldDeclaration) { return 'TIMESTAMP(0) WITH TIME ZONE'; } /** * {@inheritDoc} */ public function getDateTypeDeclarationSQL(array $fieldDeclaration) { return 'DATE'; } /** * {@inheritDoc} */ public function getTimeTypeDeclarationSQL(array $fieldDeclaration) { return 'TIME(0) WITHOUT TIME ZONE'; } /** * {@inheritDoc} */ public function getGuidExpression() { return 'UUID_GENERATE_V4()'; } /** * {@inheritDoc} */ protected function _getCommonIntegerTypeDeclarationSQL(array $columnDef) { return ''; } /** * {@inheritDoc} */ protected function getVarcharTypeDeclarationSQLSnippet($length, $fixed) { return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)') : ($length ? 'VARCHAR(' . $length . ')' : 'VARCHAR(255)'); } /** * {@inheritDoc} */ public function getClobTypeDeclarationSQL(array $field) { return 'TEXT'; } /** * {@inheritDoc} */ public function getName() { return 'postgresql'; } /** * {@inheritDoc} * * PostgreSQL returns all column names in SQL result sets in lowercase. */ public function getSQLResultCasing($column) { return strtolower($column); } /** * {@inheritDoc} */ public function getDateTimeTzFormatString() { return 'Y-m-d H:i:sO'; } /** * {@inheritDoc} */ public function getEmptyIdentityInsertSQL($quotedTableName, $quotedIdentifierColumnName) { return 'INSERT INTO ' . $quotedTableName . ' (' . $quotedIdentifierColumnName . ') VALUES (DEFAULT)'; } /** * {@inheritDoc} */ public function getTruncateTableSQL($tableName, $cascade = false) { return 'TRUNCATE '.$tableName.' '.(($cascade)?'CASCADE':''); } /** * {@inheritDoc} */ public function getReadLockSQL() { return 'FOR SHARE'; } /** * {@inheritDoc} */ protected function initializeDoctrineTypeMappings() { $this->doctrineTypeMapping = array( 'smallint' => 'smallint', 'int2' => 'smallint', 'serial' => 'integer', 'serial4' => 'integer', 'int' => 'integer', 'int4' => 'integer', 'integer' => 'integer', 'bigserial' => 'bigint', 'serial8' => 'bigint', 'bigint' => 'bigint', 'int8' => 'bigint', 'bool' => 'boolean', 'boolean' => 'boolean', 'text' => 'text', 'varchar' => 'string', 'interval' => 'string', '_varchar' => 'string', 'char' => 'string', 'bpchar' => 'string', 'inet' => 'string', 'date' => 'date', 'datetime' => 'datetime', 'timestamp' => 'datetime', 'timestamptz' => 'datetimetz', 'time' => 'time', 'timetz' => 'time', 'float' => 'float', 'float4' => 'float', 'float8' => 'float', 'double' => 'float', 'double precision' => 'float', 'real' => 'float', 'decimal' => 'decimal', 'money' => 'decimal', 'numeric' => 'decimal', 'year' => 'date', 'uuid' => 'guid', 'bytea' => 'blob', ); } /** * {@inheritDoc} */ public function getVarcharMaxLength() { return 65535; } /** * {@inheritDoc} */ protected function getReservedKeywordsClass() { return 'Doctrine\DBAL\Platforms\Keywords\PostgreSQLKeywords'; } /** * {@inheritDoc} */ public function getBlobTypeDeclarationSQL(array $field) { return 'BYTEA'; } }
htanya/Symfo
vendor/doctrine/dbal/lib/Doctrine/DBAL/Platforms/PostgreSqlPlatform.php
PHP
mit
24,378
declare class X { a: number; static b: number; c: number; }
cbishopvelti/babylon
test/fixtures/flow/declare-statements/17/actual.js
JavaScript
mit
63
// eSpeak and other code here are under the GNU GPL. function generateSpeech(text, args) { var self = { text: text, args: args, ret: null }; (function() {
francoislaberge/texttospeech
src/shell_pre.js
JavaScript
gpl-3.0
160
/******/ (function() { // webpackBootstrap /******/ "use strict"; /******/ /******/ /******/ })() ;
mindsharelabs/mindshare-api
includes/acf/assets/build/css/pro/acf-pro-input.css.js
JavaScript
gpl-3.0
104
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ScottClayton.Neural { /// <summary> /// A list of NNVectors with an added size check and the ability to save the list. /// </summary> class DoubleVectorList : List<DoubleVector> { /// <summary> /// Add a vector to the list /// </summary> /// <param name="item">The vector to add</param> /// <exception cref="VectorSizeMismatchException"></exception> public new void Add(DoubleVector item) { // If entering another item into the list, make sure that it has the same size as the rest of the vectors if (this.Count > 0 && this[0].Size != item.Size) { throw new VectorSizeMismatchException(); } base.Add(item); } public void Save(BinaryWriter w) { w.Write(this.Count); foreach (DoubleVector v in this) { v.Save(w); } } public static DoubleVectorList Load(BinaryReader r) { DoubleVectorList nnvl = new DoubleVectorList(); int count = r.ReadInt32(); for (int i = 0; i < count; i++) { nnvl.Add(DoubleVector.Load(r)); } return nnvl; } } }
rss9051/captcha-breaking-library
ScottClayton.CAPTCHA/Neural/DoubleVectorList.cs
C#
gpl-3.0
1,465
/* * ServerScheduler.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SERVER_SCHEDULER_HPP #define SERVER_SCHEDULER_HPP #include <string> #include <core/ScheduledCommand.hpp> namespace rstudio { namespace server { namespace scheduler { // add a scheduled command to the server // // note that this function does not synchronize access to the list of // scheduled commands so it should ONLY be called during server init void addCommand(boost::shared_ptr<core::ScheduledCommand> pCmd); } // namespace scheduler } // namespace server } // namespace rstudio #endif // SERVER_SCHEDULER_HPP
jzhu8803/rstudio
src/cpp/server/include/server/ServerScheduler.hpp
C++
agpl-3.0
1,116
# pylint: disable=missing-docstring # pylint: disable=redefined-outer-name # pylint: disable=unused-argument from lettuce import step, world from common import * ############### ACTIONS #################### @step('There are no courses$') def no_courses(step): world.clear_courses() create_studio_user() @step('I click the New Course button$') def i_click_new_course(step): world.css_click('.new-course-button') @step('I fill in the new course information$') def i_fill_in_a_new_course_information(step): fill_in_course_info() @step('I create a course with "([^"]*)", "([^"]*)", "([^"]*)", and "([^"]*)"') def i_create_course(step, name, org, number, run): fill_in_course_info(name=name, org=org, num=number, run=run) @step('I create a new course$') def i_create_a_course(step): create_a_course() @step('I click the course link in Studio Home$') def i_click_the_course_link_in_studio_home(step): # pylint: disable=invalid-name course_css = 'a.course-link' world.css_click(course_css) @step('I see an error about the length of the org/course/run tuple') def i_see_error_about_length(step): assert world.css_has_text( '#course_creation_error', 'The combined length of the organization, course number, ' 'and course run fields cannot be more than 65 characters.' ) ############ ASSERTIONS ################### @step('the Courseware page has loaded in Studio$') def courseware_page_has_loaded_in_studio(step): course_title_css = 'span.course-title' assert world.is_css_present(course_title_css) @step('I see the course listed in Studio Home$') def i_see_the_course_in_studio_home(step): course_css = 'h3.class-title' assert world.css_has_text(course_css, world.scenario_dict['COURSE'].display_name) @step('I am on the "([^"]*)" tab$') def i_am_on_tab(step, tab_name): header_css = 'div.inner-wrapper h1' assert world.css_has_text(header_css, tab_name) @step('I see a link for adding a new section$') def i_see_new_section_link(step): link_css = '.outline .button-new' assert world.css_has_text(link_css, 'New Section')
Stanford-Online/edx-platform
cms/djangoapps/contentstore/features/courses.py
Python
agpl-3.0
2,137
/** * * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc. * * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd. * Copyright (C) 2011 - 2018 SalesAgility Ltd. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not * reasonably feasible for technical reasons, the Appropriate Legal Notices must * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM". */ var aclviewer = function () { var lastDisplay = ''; return { view: function (role_id, role_module) { YAHOO.util.Connect.asyncRequest('POST', 'index.php', { 'success': aclviewer.display, 'failure': aclviewer.failed }, 'module=ACLRoles&action=EditRole&record=' + role_id + '&category_name=' + role_module); ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED')); }, save: function (form_name) { var formObject = document.getElementById(form_name); YAHOO.util.Connect.setForm(formObject); YAHOO.util.Connect.asyncRequest('POST', 'index.php', { 'success': aclviewer.postSave, 'failure': aclviewer.failed }); ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING')); }, postSave: function (o) { SUGAR.util.globalEval(o.responseText); aclviewer.view(result['role_id'], result['module']); }, display: function (o) { aclviewer.lastDisplay = ''; ajaxStatus.flashStatus('Done'); document.getElementById('category_data').innerHTML = o.responseText; }, failed: function () { ajax.flashStatus('Could Not Connect'); }, toggleDisplay: function (id) { if (aclviewer.lastDisplay != '' && typeof(aclviewer.lastDisplay) != 'undefined') { aclviewer.hideDisplay(aclviewer.lastDisplay); } if (aclviewer.lastDisplay != id) { aclviewer.showDisplay(id); aclviewer.lastDisplay = id; } else { aclviewer.lastDisplay = ''; } }, hideDisplay: function (id) { document.getElementById(id).style.display = 'none'; document.getElementById(id + 'link').style.display = ''; }, showDisplay: function (id) { document.getElementById(id).style.display = ''; document.getElementById(id + 'link').style.display = 'none'; } }; }();
lionixevolve/SuiteCRM
jssource/src_files/modules/ACLRoles/ACLRoles.js
JavaScript
agpl-3.0
3,972
// Accord.NET Sample Applications // http://accord.googlecode.com // // Copyright © César Souza, 2009-2012 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace DeepLearning.ViewModel { using System.ComponentModel; using System.Windows.Media.Imaging; using Accord.Math; using Accord.Neuro.Networks; using DeepLearning.Databases; /// <summary> /// View-Model for the Use tab. /// </summary> /// public class UseViewModel : INotifyPropertyChanged { public MainViewModel Main { get; private set; } public double[] UserInput { get; set; } public BitmapImage NetworkOutput { get; set; } public bool IsActive { get; set; } public int Classification { get; set; } public UseViewModel(MainViewModel main) { Main = main; PropertyChanged += new PropertyChangedEventHandler(UseViewModel_PropertyChanged); } private void UseViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "UserInput" && IsActive) Compute(); } public bool CanCompute { get { return UserInput != null && Main.CanGenerate; } } public void Compute() { if (!CanCompute) return; double[] input = UserInput; DeepBeliefNetwork network = Main.Network; IDatabase database = Main.Database; database.Normalize(input); { double[] output = network.GenerateOutput(input); double[] reconstruction = network.Reconstruct(output); NetworkOutput = (database.ToBitmap(reconstruction).ToBitmapImage()); } if (Main.CanClassify) { double[] output = network.Compute(input); int imax; output.Max(out imax); Classification = imax; } } // The PropertyChanged event doesn't needs to be explicitly raised // from this application. The event raising is handled automatically // by the NotifyPropertyWeaver VS extension using IL injection. // #pragma warning disable 0067 /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #pragma warning restore 0067 } }
DiegoCatalano/framework
Samples/Neuro/Deep Learning/ViewModel/UseViewModel.cs
C#
lgpl-2.1
3,192
/* * Copyright 2013 LinkedIn, 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. */ package voldemort.client.rebalance.task; import java.util.concurrent.Semaphore; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.client.protocol.admin.AdminClient; import voldemort.client.rebalance.RebalanceBatchPlanProgressBar; import voldemort.client.rebalance.RebalanceScheduler; import voldemort.client.rebalance.RebalanceTaskInfo; import voldemort.server.rebalance.AlreadyRebalancingException; import voldemort.store.UnreachableStoreException; import com.google.common.collect.Lists; /** * Immutable class that executes a {@link RebalanceTaskInfo} instance on * the rebalance client side. * * This is run from the stealer nodes perspective */ public class StealerBasedRebalanceTask extends RebalanceTask { private static final Logger logger = Logger.getLogger(StealerBasedRebalanceTask.class); private final int stealerNodeId; private final int donorNodeId; private final RebalanceScheduler scheduler; public StealerBasedRebalanceTask(final int batchId, final int taskId, final RebalanceTaskInfo stealInfo, final Semaphore donorPermit, final AdminClient adminClient, final RebalanceBatchPlanProgressBar progressBar, final RebalanceScheduler scheduler) { super(batchId, taskId, Lists.newArrayList(stealInfo), donorPermit, adminClient, progressBar, logger); this.stealerNodeId = stealInfo.getStealerId(); this.donorNodeId = stealInfo.getDonorId(); this.scheduler = scheduler; taskLog(toString()); } private int startNodeRebalancing() { try { taskLog("Trying to start async rebalance task on stealer node " + stealerNodeId); int asyncOperationId = adminClient.rebalanceOps.rebalanceNode(stealInfos.get(0)); taskLog("Started async rebalance task on stealer node " + stealerNodeId); return asyncOperationId; } catch(AlreadyRebalancingException e) { String errorMessage = "Node " + stealerNodeId + " is currently rebalancing. Should not have tried to start new task on stealer node!"; taskLog(errorMessage); throw new VoldemortException(errorMessage + " Failed to start rebalancing with plan: " + getStealInfos(), e); } } @Override public void run() { int rebalanceAsyncId = INVALID_REBALANCE_ID; String threadName = Thread.currentThread().getName(); try { Thread.currentThread().setName(threadName + "-Task-" + taskId + "-asyncid-" + rebalanceAsyncId); acquirePermit(stealInfos.get(0).getDonorId()); // Start rebalance task and then wait. rebalanceAsyncId = startNodeRebalancing(); taskStart(taskId, rebalanceAsyncId); adminClient.rpcOps.waitForCompletion(stealerNodeId, rebalanceAsyncId); taskDone(taskId, rebalanceAsyncId); } catch(UnreachableStoreException e) { exception = e; logger.error("Stealer node " + stealerNodeId + " is unreachable, please make sure it is up and running : " + e.getMessage(), e); } catch(Exception e) { exception = e; logger.error("Rebalance failed : " + e.getMessage(), e); } finally { Thread.currentThread().setName(threadName); donorPermit.release(); isComplete.set(true); scheduler.doneTask(stealerNodeId, donorNodeId); } } @Override public String toString() { return "Stealer based rebalance task on stealer node " + stealerNodeId + " from donor node " + donorNodeId + " : " + getStealInfos(); } }
bitti/voldemort
src/java/voldemort/client/rebalance/task/StealerBasedRebalanceTask.java
Java
apache-2.0
4,789
# Copyright 2018 The TensorFlow 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. # ============================================================================== """Tests and Benchmarks for Densenet model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import time import tensorflow as tf import tensorflow.contrib.eager as tfe from tensorflow.contrib.eager.python.examples.densenet import densenet from tensorflow.python.client import device_lib class DensenetTest(tf.test.TestCase): def test_bottleneck_true(self): depth = 7 growth_rate = 2 num_blocks = 3 output_classes = 10 num_layers_in_each_block = -1 batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=False, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_bottleneck_false(self): depth = 7 growth_rate = 2 num_blocks = 3 output_classes = 10 num_layers_in_each_block = -1 batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=False, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=False, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_pool_initial_true(self): depth = 7 growth_rate = 2 num_blocks = 4 output_classes = 10 num_layers_in_each_block = [1, 2, 2, 1] batch_size = 1 data_format = ('channels_first') if tf.test.is_gpu_available() else ( 'channels_last') model = densenet.DenseNet(depth, growth_rate, num_blocks, output_classes, num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) if data_format == 'channels_last': rand_input = tf.random_uniform((batch_size, 32, 32, 3)) else: rand_input = tf.random_uniform((batch_size, 3, 32, 32)) output_shape = model(rand_input).shape self.assertEqual(output_shape, (batch_size, output_classes)) def test_regularization(self): if tf.test.is_gpu_available(): rand_input = tf.random_uniform((10, 3, 32, 32)) data_format = 'channels_first' else: rand_input = tf.random_uniform((10, 32, 32, 3)) data_format = 'channels_last' weight_decay = 1e-4 conv = tf.keras.layers.Conv2D( 3, (3, 3), padding='same', use_bias=False, data_format=data_format, kernel_regularizer=tf.keras.regularizers.l2(weight_decay)) optimizer = tf.train.GradientDescentOptimizer(0.1) conv(rand_input) # Initialize the variables in the layer def compute_true_l2(vs, wd): return tf.reduce_sum(tf.square(vs)) * wd true_l2 = compute_true_l2(conv.variables, weight_decay) keras_l2 = tf.add_n(conv.losses) self.assertAllClose(true_l2, keras_l2) with tf.GradientTape() as tape_true, tf.GradientTape() as tape_keras: loss = tf.reduce_sum(conv(rand_input)) loss_with_true_l2 = loss + compute_true_l2(conv.variables, weight_decay) loss_with_keras_l2 = loss + tf.add_n(conv.losses) true_grads = tape_true.gradient(loss_with_true_l2, conv.variables) keras_grads = tape_keras.gradient(loss_with_keras_l2, conv.variables) self.assertAllClose(true_grads, keras_grads) optimizer.apply_gradients(zip(keras_grads, conv.variables)) keras_l2_after_update = tf.add_n(conv.losses) self.assertNotAllClose(keras_l2, keras_l2_after_update) def compute_gradients(model, images, labels): with tf.GradientTape() as tape: logits = model(images, training=True) cross_ent = tf.losses.softmax_cross_entropy( logits=logits, onehot_labels=labels) regularization = tf.add_n(model.losses) loss = cross_ent + regularization tf.contrib.summary.scalar(name='loss', tensor=loss) return tape.gradient(loss, model.variables) def apply_gradients(model, optimizer, gradients): optimizer.apply_gradients(zip(gradients, model.variables)) def device_and_data_format(): return ('/gpu:0', 'channels_first') if tf.test.is_gpu_available() else ('/cpu:0', 'channels_last') def random_batch(batch_size, data_format): shape = (3, 224, 224) if data_format == 'channels_first' else (224, 224, 3) shape = (batch_size,) + shape num_classes = 1000 images = tf.random_uniform(shape) labels = tf.random_uniform( [batch_size], minval=0, maxval=num_classes, dtype=tf.int32) one_hot = tf.one_hot(labels, num_classes) return images, one_hot class MockIterator(object): def __init__(self, tensors): self._tensors = [tf.identity(x) for x in tensors] def next(self): return self._tensors class DensenetBenchmark(tf.test.Benchmark): def __init__(self): self.depth = 121 self.growth_rate = 32 self.num_blocks = 4 self.output_classes = 1000 self.num_layers_in_each_block = [6, 12, 24, 16] def _train_batch_sizes(self): """Choose batch sizes based on GPU capability.""" for device in device_lib.list_local_devices(): if tf.DeviceSpec.from_string(device.name).device_type == 'GPU': if 'K20' in device.physical_device_desc: return (16,) if 'P100' in device.physical_device_desc: return (16, 32, 64) if tf.DeviceSpec.from_string(device.name).device_type == 'TPU': return (32,) return (16, 32) def _report(self, label, start, num_iters, device, batch_size, data_format): avg_time = (time.time() - start) / num_iters dev = tf.DeviceSpec.from_string(device).device_type.lower() name = '%s_%s_batch_%d_%s' % (label, dev, batch_size, data_format) extras = {'examples_per_sec': batch_size / avg_time} self.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras) def _force_device_sync(self): # If this function is called in the context of a non-CPU device # (e.g., inside a 'with tf.device("/gpu:0")' block) # then this will force a copy from CPU->NON_CPU_DEVICE->CPU, # which forces a sync. This is a roundabout way, yes. tf.constant(1.).cpu() def _benchmark_eager_apply(self, label, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) if defun: # TODO(apassos) enable tfe.function here model.call = tfe.defun(model.call) batch_size = 64 num_burn = 5 num_iters = 30 with tf.device(device): images, _ = random_batch(batch_size, data_format) for _ in xrange(num_burn): model(images, training=False).cpu() if execution_mode: tfe.async_wait() gc.collect() start = time.time() for _ in xrange(num_iters): model(images, training=False).cpu() if execution_mode: tfe.async_wait() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_apply_sync(self): self._benchmark_eager_apply('eager_apply', device_and_data_format(), defun=False) def benchmark_eager_apply_async(self): self._benchmark_eager_apply( 'eager_apply_async', device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_apply_with_defun(self): self._benchmark_eager_apply('eager_apply_with_defun', device_and_data_format(), defun=True) def _benchmark_eager_train(self, label, make_iterator, device_and_format, defun=False, execution_mode=None): with tfe.execution_mode(execution_mode): device, data_format = device_and_format for batch_size in self._train_batch_sizes(): (images, labels) = random_batch(batch_size, data_format) model = densenet.DenseNet(self.depth, self.growth_rate, self.num_blocks, self.output_classes, self.num_layers_in_each_block, data_format, bottleneck=True, compression=0.5, weight_decay=1e-4, dropout_rate=0, pool_initial=True, include_top=True) optimizer = tf.train.GradientDescentOptimizer(0.1) apply_grads = apply_gradients if defun: model.call = tfe.defun(model.call) apply_grads = tfe.defun(apply_gradients) num_burn = 3 num_iters = 10 with tf.device(device): iterator = make_iterator((images, labels)) for _ in xrange(num_burn): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() gc.collect() start = time.time() for _ in xrange(num_iters): (images, labels) = iterator.next() apply_grads(model, optimizer, compute_gradients(model, images, labels)) if execution_mode: tfe.async_wait() self._force_device_sync() self._report(label, start, num_iters, device, batch_size, data_format) def benchmark_eager_train_sync(self): self._benchmark_eager_train('eager_train', MockIterator, device_and_data_format(), defun=False) def benchmark_eager_train_async(self): self._benchmark_eager_train( 'eager_train_async', MockIterator, device_and_data_format(), defun=False, execution_mode=tfe.ASYNC) def benchmark_eager_train_with_defun(self): self._benchmark_eager_train( 'eager_train_with_defun', MockIterator, device_and_data_format(), defun=True) def benchmark_eager_train_datasets(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset', make_iterator, device_and_data_format(), defun=False) def benchmark_eager_train_datasets_with_defun(self): def make_iterator(tensors): with tf.device('/device:CPU:0'): ds = tf.data.Dataset.from_tensors(tensors).repeat() return tfe.Iterator(ds) self._benchmark_eager_train( 'eager_train_dataset_with_defun', make_iterator, device_and_data_format(), defun=True) if __name__ == '__main__': tf.enable_eager_execution() tf.test.main()
ghchinoy/tensorflow
tensorflow/contrib/eager/python/examples/densenet/densenet_test.py
Python
apache-2.0
12,967
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.packages; import com.google.common.base.Predicate; import com.google.common.base.Verify; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.collect.nestedset.Order; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.syntax.Label; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Model for the "environment_group' rule: the piece of Bazel's rule constraint system that binds * thematically related environments together and determines which environments a rule supports * by default. See {@link com.google.devtools.build.lib.analysis.constraints.ConstraintSemantics} * for precise semantic details of how this information is used. * * <p>Note that "environment_group" is implemented as a loading-time function, not a rule. This is * to support proper discovery of defaults: Say rule A has no explicit constraints and depends * on rule B, which is explicitly constrained to environment ":bar". Since A declares nothing * explicitly, it's implicitly constrained to DEFAULTS (whatever that is). Therefore, the * dependency is only allowed if DEFAULTS doesn't include environments beyond ":bar". To figure * that out, we need to be able to look up the environment group for ":bar", which is what this * class provides. * * <p>If we implemented this as a rule, we'd have to provide that lookup via rule dependencies, * e.g. something like: * * <code> * environment( * name = 'bar', * group = [':sample_environments'], * is_default = 1 * ) * </code> * * <p>But this won't work. This would let us find the environment group for ":bar", but the only way * to determine what other environments belong to the group is to have the group somehow reference * them. That would produce circular dependencies in the build graph, which is no good. */ @Immutable public class EnvironmentGroup implements Target { private final Label label; private final Location location; private final Package containingPackage; private final Set<Label> environments; private final Set<Label> defaults; /** * Maps a member environment to the set of environments that directly fulfill it. Note that * we can't populate this map until all Target instances for member environments have been * initialized, which may occur after group instantiation (this makes the class mutable). */ private final Map<Label, NestedSet<Label>> fulfillersMap = new HashMap<>(); /** * Predicate that matches labels from a different package than the initialized package. */ private static final class DifferentPackage implements Predicate<Label> { private final Package containingPackage; private DifferentPackage(Package containingPackage) { this.containingPackage = containingPackage; } @Override public boolean apply(Label environment) { return !environment.getPackageName().equals(containingPackage.getName()); } } /** * Instantiates a new group without verifying the soundness of its contents. See the validation * methods below for appropriate checks. * * @param label the build label identifying this group * @param pkg the package this group belongs to * @param environments the set of environments that belong to this group * @param defaults the environments a rule implicitly supports unless otherwise specified * @param location location in the BUILD file of this group */ EnvironmentGroup(Label label, Package pkg, final List<Label> environments, List<Label> defaults, Location location) { this.label = label; this.location = location; this.containingPackage = pkg; this.environments = ImmutableSet.copyOf(environments); this.defaults = ImmutableSet.copyOf(defaults); } /** * Checks that all environments declared by this group are in the same package as the group (so * we can perform an environment --> environment_group lookup and know the package is available) * and checks that all defaults are legitimate members of the group. * * <p>Does <b>not</b> check that the referenced environments exist (see * {@link #processMemberEnvironments}). * * @return a list of validation errors that occurred */ List<Event> validateMembership() { List<Event> events = new ArrayList<>(); // All environments should belong to the same package as this group. for (Label environment : Iterables.filter(environments, new DifferentPackage(containingPackage))) { events.add(Event.error(location, environment + " is not in the same package as group " + label)); } // The defaults must be a subset of the member environments. for (Label unknownDefault : Sets.difference(defaults, environments)) { events.add(Event.error(location, "default " + unknownDefault + " is not a " + "declared environment for group " + getLabel())); } return events; } /** * Checks that the group's declared environments are legitimate same-package environment * rules and prepares the "fulfills" relationships between these environments to support * {@link #getFulfillers}. * * @param pkgTargets mapping from label name to target instance for this group's package * @return a list of validation errors that occurred */ List<Event> processMemberEnvironments(Map<String, Target> pkgTargets) { List<Event> events = new ArrayList<>(); // Maps an environment to the environments that directly fulfill it. Multimap<Label, Label> directFulfillers = HashMultimap.create(); for (Label envName : environments) { Target env = pkgTargets.get(envName.getName()); if (isValidEnvironment(env, envName, "", events)) { AttributeMap attr = NonconfigurableAttributeMapper.of((Rule) env); for (Label fulfilledEnv : attr.get("fulfills", Type.LABEL_LIST)) { if (isValidEnvironment(pkgTargets.get(fulfilledEnv.getName()), fulfilledEnv, "in \"fulfills\" attribute of " + envName + ": ", events)) { directFulfillers.put(fulfilledEnv, envName); } } } } // Now that we know which environments directly fulfill each other, compute which environments // transitively fulfill each other. We could alternatively compute this on-demand, but since // we don't expect these chains to be very large we opt toward computing them once at package // load time. Verify.verify(fulfillersMap.isEmpty()); for (Label envName : environments) { setTransitiveFulfillers(envName, directFulfillers, fulfillersMap); } return events; } /** * Given an environment and set of environments that directly fulfill it, computes a nested * set of environments that <i>transitively</i> fulfill it, places it into transitiveFulfillers, * and returns that set. */ private static NestedSet<Label> setTransitiveFulfillers(Label env, Multimap<Label, Label> directFulfillers, Map<Label, NestedSet<Label>> transitiveFulfillers) { if (transitiveFulfillers.containsKey(env)) { return transitiveFulfillers.get(env); } else if (!directFulfillers.containsKey(env)) { // Nobody fulfills this environment. NestedSet<Label> emptySet = NestedSetBuilder.emptySet(Order.STABLE_ORDER); transitiveFulfillers.put(env, emptySet); return emptySet; } else { NestedSetBuilder<Label> set = NestedSetBuilder.stableOrder(); for (Label fulfillingEnv : directFulfillers.get(env)) { set.add(fulfillingEnv); set.addTransitive( setTransitiveFulfillers(fulfillingEnv, directFulfillers, transitiveFulfillers)); } NestedSet<Label> builtSet = set.build(); transitiveFulfillers.put(env, builtSet); return builtSet; } } private boolean isValidEnvironment(Target env, Label envName, String prefix, List<Event> events) { if (env == null) { events.add(Event.error(location, prefix + "environment " + envName + " does not exist")); return false; } else if (!env.getTargetKind().equals("environment rule")) { events.add(Event.error(location, prefix + env.getLabel() + " is not a valid environment")); return false; } else if (!environments.contains(env.getLabel())) { events.add(Event.error(location, prefix + env.getLabel() + " is not a member of this group")); return false; } return true; } /** * Returns the environments that belong to this group. */ public Set<Label> getEnvironments() { return environments; } /** * Returns the environments a rule supports by default, i.e. if it has no explicit references to * environments in this group. */ public Set<Label> getDefaults() { return defaults; } /** * Determines whether or not an environment is a default. Returns false if the environment * doesn't belong to this group. */ public boolean isDefault(Label environment) { return defaults.contains(environment); } /** * Returns the set of environments that transitively fulfill the specified environment. * The environment must be a valid member of this group. * * <p>>For example, if the input is <code>":foo"</code> and <code>":bar"</code> fulfills * <code>":foo"</code> and <code>":baz"</code> fulfills <code>":bar"</code>, this returns * <code>[":foo", ":bar", ":baz"]</code>. * * <p>If no environments fulfill the input, returns an empty set. */ public Iterable<Label> getFulfillers(Label environment) { return Verify.verifyNotNull(fulfillersMap.get(environment)); } @Override public Label getLabel() { return label; } @Override public String getName() { return label.getName(); } @Override public Package getPackage() { return containingPackage; } @Override public String getTargetKind() { return targetKind(); } @Override public Rule getAssociatedRule() { return null; } @Override public License getLicense() { return License.NO_LICENSE; } @Override public Location getLocation() { return location; } @Override public String toString() { return targetKind() + " " + getLabel(); } @Override public Set<License.DistributionType> getDistributions() { return Collections.emptySet(); } @Override public RuleVisibility getVisibility() { return ConstantRuleVisibility.PRIVATE; // No rule should be referencing an environment_group. } public static String targetKind() { return "environment group"; } @Override public boolean equals(Object o) { // In a distributed implementation these may not be the same object. if (o == this) { return true; } else if (!(o instanceof EnvironmentGroup)) { return false; } else { return ((EnvironmentGroup) o).getLabel().equals(getLabel()); } } }
wakashige/bazel
src/main/java/com/google/devtools/build/lib/packages/EnvironmentGroup.java
Java
apache-2.0
12,087
/* * 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.jmeter.control; import java.io.Serializable; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.testelement.property.BooleanProperty; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jmeter.threads.JMeterContext; import org.apache.jmeter.threads.JMeterVariables; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * ForeachController that iterates over a list of variables named XXXX_NN stored in {@link JMeterVariables} * where NN is a number starting from 1 to number of occurences. * This list of variable is usually set by PostProcessor (Regexp PostProcessor or {@link org.apache.jmeter.extractor.HtmlExtractor}) * Iteration can take the full list or only a subset (configured through indexes) * */ public class ForeachController extends GenericController implements Serializable { private static final Logger log = LoggingManager.getLoggerForClass(); private static final long serialVersionUID = 240L; private static final String INPUTVAL = "ForeachController.inputVal";// $NON-NLS-1$ private static final String START_INDEX = "ForeachController.startIndex";// $NON-NLS-1$ private static final String END_INDEX = "ForeachController.endIndex";// $NON-NLS-1$ private static final String RETURNVAL = "ForeachController.returnVal";// $NON-NLS-1$ private static final String USE_SEPARATOR = "ForeachController.useSeparator";// $NON-NLS-1$ private static final String INDEX_DEFAULT_VALUE = ""; // start/end index default value for string getters and setters private int loopCount = 0; private static final String DEFAULT_SEPARATOR = "_";// $NON-NLS-1$ public ForeachController() { } /** * @param startIndex Start index of loop */ public void setStartIndex(String startIndex) { setProperty(START_INDEX, startIndex, INDEX_DEFAULT_VALUE); } /** * @return start index of loop */ private int getStartIndex() { // Although the default is not the same as for the string value, it is only used internally return getPropertyAsInt(START_INDEX, 0); } /** * @return start index of loop as String */ public String getStartIndexAsString() { return getPropertyAsString(START_INDEX, INDEX_DEFAULT_VALUE); } /** * @param endIndex End index of loop */ public void setEndIndex(String endIndex) { setProperty(END_INDEX, endIndex, INDEX_DEFAULT_VALUE); } /** * @return end index of loop */ private int getEndIndex() { // Although the default is not the same as for the string value, it is only used internally return getPropertyAsInt(END_INDEX, Integer.MAX_VALUE); } /** * @return end index of loop */ public String getEndIndexAsString() { return getPropertyAsString(END_INDEX, INDEX_DEFAULT_VALUE); } public void setInputVal(String inputValue) { setProperty(new StringProperty(INPUTVAL, inputValue)); } private String getInputVal() { getProperty(INPUTVAL).recoverRunningVersion(null); return getInputValString(); } public String getInputValString() { return getPropertyAsString(INPUTVAL); } public void setReturnVal(String inputValue) { setProperty(new StringProperty(RETURNVAL, inputValue)); } private String getReturnVal() { getProperty(RETURNVAL).recoverRunningVersion(null); return getReturnValString(); } public String getReturnValString() { return getPropertyAsString(RETURNVAL); } private String getSeparator() { return getUseSeparator() ? DEFAULT_SEPARATOR : "";// $NON-NLS-1$ } public void setUseSeparator(boolean b) { setProperty(new BooleanProperty(USE_SEPARATOR, b)); } public boolean getUseSeparator() { return getPropertyAsBoolean(USE_SEPARATOR, true); } /** * {@inheritDoc} */ @Override public boolean isDone() { if (loopCount >= getEndIndex()) { return true; } JMeterContext context = getThreadContext(); StringBuilder builder = new StringBuilder( getInputVal().length()+getSeparator().length()+3); String inputVariable = builder.append(getInputVal()) .append(getSeparator()) .append(Integer.toString(loopCount+1)).toString(); final JMeterVariables variables = context.getVariables(); final Object currentVariable = variables.getObject(inputVariable); if (currentVariable != null) { variables.putObject(getReturnVal(), currentVariable); if (log.isDebugEnabled()) { log.debug("ForEach resultstring isDone=" + variables.get(getReturnVal())); } return false; } return super.isDone(); } /** * Tests that JMeterVariables contain inputVal_<count>, if not we can stop iterating */ private boolean endOfArguments() { JMeterContext context = getThreadContext(); String inputVariable = getInputVal() + getSeparator() + (loopCount + 1); if (context.getVariables().getObject(inputVariable) != null) { log.debug("ForEach resultstring eofArgs= false"); return false; } log.debug("ForEach resultstring eofArgs= true"); return true; } // Prevent entry if nothing to do @Override public Sampler next() { if (emptyList()) { reInitialize(); resetLoopCount(); return null; } return super.next(); } /** * Check if there are any matching entries * * @return whether any entries in the list */ private boolean emptyList() { JMeterContext context = getThreadContext(); StringBuilder builder = new StringBuilder( getInputVal().length()+getSeparator().length()+3); String inputVariable = builder.append(getInputVal()) .append(getSeparator()) .append(Integer.toString(loopCount+1)).toString(); if (context.getVariables().getObject(inputVariable) != null) { return false; } if (log.isDebugEnabled()) { log.debug("No entries found - null first entry: " + inputVariable); } return true; } /** * {@inheritDoc} */ @Override protected Sampler nextIsNull() throws NextIsNullException { reInitialize(); // Conditions to reset the loop count if (endOfArguments() // no more variables to iterate ||loopCount >= getEndIndex() // we reached end index ) { // setDone(true); resetLoopCount(); return null; } return next(); } protected void incrementLoopCount() { loopCount++; } protected void resetLoopCount() { loopCount = getStartIndex(); } /** * {@inheritDoc} */ @Override protected int getIterCount() { return loopCount + 1; } /** * {@inheritDoc} */ @Override protected void reInitialize() { setFirst(true); resetCurrent(); incrementLoopCount(); recoverRunningVersion(); } /** * {@inheritDoc} */ @Override public void triggerEndOfLoop() { super.triggerEndOfLoop(); resetLoopCount(); } /** * Reset loopCount to Start index * @see org.apache.jmeter.control.GenericController#initialize() */ @Override public void initialize() { super.initialize(); loopCount = getStartIndex(); } }
hizhangqi/jmeter-1
src/components/org/apache/jmeter/control/ForeachController.java
Java
apache-2.0
8,665
/* Copyright (c) 2007 Google 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. */ package sample.gbase.cmdline; import com.google.gdata.client.Service; import java.net.URL; /** * Displays the media entry (meta-data) of one attachment. * This command is called from {@link CustomerTool}. */ public class GetMediaCommand extends Command { private String attachmentId; @Override public void execute() throws Exception { Service service = createService(); Service.GDataRequest request = service.createEntryRequest(new URL(attachmentId)); // Send the request (HTTP GET) request.execute(); // Save the response outputRawResponse(request); } /** Sets the id/URL of the media attachment to display. */ public void setAttachmentId(String attachmentId) { this.attachmentId = attachmentId; } }
vanta/gdata-java-client
java/sample/gbase/cmdline/GetMediaCommand.java
Java
apache-2.0
1,357
//===--- PlistReporter.cpp - ARC Migrate Tool Plist Reporter ----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "Internals.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/PlistSupport.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" using namespace clang; using namespace arcmt; using namespace markup; static StringRef getLevelName(DiagnosticsEngine::Level Level) { switch (Level) { case DiagnosticsEngine::Ignored: llvm_unreachable("ignored"); case DiagnosticsEngine::Note: return "note"; case DiagnosticsEngine::Remark: case DiagnosticsEngine::Warning: return "warning"; case DiagnosticsEngine::Fatal: case DiagnosticsEngine::Error: return "error"; } llvm_unreachable("Invalid DiagnosticsEngine level!"); } void arcmt::writeARCDiagsToPlist(const std::string &outPath, ArrayRef<StoredDiagnostic> diags, SourceManager &SM, const LangOptions &LangOpts) { DiagnosticIDs DiagIDs; // Build up a set of FIDs that we use by scanning the locations and // ranges of the diagnostics. FIDMap FM; SmallVector<FileID, 10> Fids; for (ArrayRef<StoredDiagnostic>::iterator I = diags.begin(), E = diags.end(); I != E; ++I) { const StoredDiagnostic &D = *I; AddFID(FM, Fids, SM, D.getLocation()); for (StoredDiagnostic::range_iterator RI = D.range_begin(), RE = D.range_end(); RI != RE; ++RI) { AddFID(FM, Fids, SM, RI->getBegin()); AddFID(FM, Fids, SM, RI->getEnd()); } } std::error_code EC; llvm::raw_fd_ostream o(outPath, EC, llvm::sys::fs::F_Text); if (EC) { llvm::errs() << "error: could not create file: " << outPath << '\n'; return; } EmitPlistHeader(o); // Write the root object: a <dict> containing... // - "files", an <array> mapping from FIDs to file names // - "diagnostics", an <array> containing the diagnostics o << "<dict>\n" " <key>files</key>\n" " <array>\n"; for (FileID FID : Fids) EmitString(o << " ", SM.getFileEntryForID(FID)->getName()) << '\n'; o << " </array>\n" " <key>diagnostics</key>\n" " <array>\n"; for (ArrayRef<StoredDiagnostic>::iterator DI = diags.begin(), DE = diags.end(); DI != DE; ++DI) { const StoredDiagnostic &D = *DI; if (D.getLevel() == DiagnosticsEngine::Ignored) continue; o << " <dict>\n"; // Output the diagnostic. o << " <key>description</key>"; EmitString(o, D.getMessage()) << '\n'; o << " <key>category</key>"; EmitString(o, DiagIDs.getCategoryNameFromID( DiagIDs.getCategoryNumberForDiag(D.getID()))) << '\n'; o << " <key>type</key>"; EmitString(o, getLevelName(D.getLevel())) << '\n'; // Output the location of the bug. o << " <key>location</key>\n"; EmitLocation(o, SM, D.getLocation(), FM, 2); // Output the ranges (if any). if (!D.getRanges().empty()) { o << " <key>ranges</key>\n"; o << " <array>\n"; for (auto &R : D.getRanges()) { CharSourceRange ExpansionRange = SM.getExpansionRange(R); EmitRange(o, SM, Lexer::getAsCharRange(ExpansionRange, SM, LangOpts), FM, 4); } o << " </array>\n"; } // Close up the entry. o << " </dict>\n"; } o << " </array>\n"; // Finish. o << "</dict>\n</plist>\n"; }
apple/swift-clang
lib/ARCMigrate/PlistReporter.cpp
C++
apache-2.0
3,727
<?php /** * File containing the ezcDocumentOdtElementWhitespaceFilter class. * * @package Document * @version 1.3.1 * @copyright Copyright (C) 2005-2010 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/new_bsd New BSD License * @access private */ /** * Filter for ODT <text:s/>, <text:tab/> and <text:line-break/> elements. * * @package Document * @version 1.3.1 * @access private */ class ezcDocumentOdtElementWhitespaceFilter extends ezcDocumentOdtElementBaseFilter { /** * Filter a single element. * * @param DOMElement $element * @return void */ public function filterElement( DOMElement $element ) { $spaces = ''; switch ( $element->localName ) { case 's': $count = $element->getAttributeNS( ezcDocumentOdt::NS_ODT_TEXT, 'c' ); $spaces = str_repeat( ' ', ( $count !== '' ? (int) $count : 1 ) ); break; case 'tab': $spaces = "\t"; break; case 'line-break': $spaces = "\n"; break; } $element->setProperty( 'spaces', $spaces ); } /** * Check if filter handles the current element. * * Returns a boolean value, indicating weather this filter can handle * the current element. * * @param DOMElement $element * @return void */ public function handles( DOMElement $element ) { return ( $element->namespaceURI === ezcDocumentOdt::NS_ODT_TEXT && ( $element->localName === 's' || $element->localName === 'tab' || $element->localName === 'line-break' ) ); } } ?>
mgrauer/qibench
modules/scheduler/library/ezcomponents/Document/src/document/xml/odt/filter/element/whitespace.php
PHP
bsd-3-clause
1,814
/* YUI 3.17.2 (build 9c3c78e) Copyright 2014 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('axis-time-base', function (Y, NAME) { /** * Provides functionality for the handling of time axis data for a chart. * * @module charts * @submodule axis-time-base */ var Y_Lang = Y.Lang; /** * TimeImpl contains logic for time data. TimeImpl is used by the following classes: * <ul> * <li>{{#crossLink "TimeAxisBase"}}{{/crossLink}}</li> * <li>{{#crossLink "TimeAxis"}}{{/crossLink}}</li> * </ul> * * @class TimeImpl * @constructor * @submodule axis-time-base */ function TimeImpl() { } TimeImpl.NAME = "timeImpl"; TimeImpl.ATTRS = { /** * Method used for formatting a label. This attribute allows for the default label formatting method to overridden. * The method use would need to implement the arguments below and return a `String` or an `HTMLElement`. The default * implementation of the method returns a `String`. The output of this method will be rendered to the DOM using * `appendChild`. If you override the `labelFunction` method and return an html string, you will also need to override * the Axis' `appendLabelFunction` to accept html as a `String`. * <dl> * <dt>val</dt><dd>Label to be formatted. (`String`)</dd> * <dt>format</dt><dd>STRFTime string used to format the label. (optional)</dd> * </dl> * * @attribute labelFunction * @type Function */ /** * Pattern used by the `labelFunction` to format a label. * * @attribute labelFormat * @type String */ labelFormat: { value: "%b %d, %y" } }; TimeImpl.prototype = { /** * Type of data used in `Data`. * * @property _type * @readOnly * @private */ _type: "time", /** * Getter method for maximum attribute. * * @method _maximumGetter * @return Number * @private */ _maximumGetter: function () { var max = this._getNumber(this._setMaximum); if(!Y_Lang.isNumber(max)) { max = this._getNumber(this.get("dataMaximum")); } return parseFloat(max); }, /** * Setter method for maximum attribute. * * @method _maximumSetter * @param {Object} value * @private */ _maximumSetter: function (value) { this._setMaximum = this._getNumber(value); return value; }, /** * Getter method for minimum attribute. * * @method _minimumGetter * @return Number * @private */ _minimumGetter: function () { var min = this._getNumber(this._setMinimum); if(!Y_Lang.isNumber(min)) { min = this._getNumber(this.get("dataMinimum")); } return parseFloat(min); }, /** * Setter method for minimum attribute. * * @method _minimumSetter * @param {Object} value * @private */ _minimumSetter: function (value) { this._setMinimum = this._getNumber(value); return value; }, /** * Indicates whether or not the maximum attribute has been explicitly set. * * @method _getSetMax * @return Boolean * @private */ _getSetMax: function() { var max = this._getNumber(this._setMaximum); return (Y_Lang.isNumber(max)); }, /** * Indicates whether or not the minimum attribute has been explicitly set. * * @method _getSetMin * @return Boolean * @private */ _getSetMin: function() { var min = this._getNumber(this._setMinimum); return (Y_Lang.isNumber(min)); }, /** * Formats a label based on the axis type and optionally specified format. * * @method formatLabel * @param {Object} value * @param {Object} format Pattern used to format the value. * @return String */ formatLabel: function(val, format) { val = Y.DataType.Date.parse(val); if(format) { return Y.DataType.Date.format(val, {format:format}); } return val; }, /** * Constant used to generate unique id. * * @property GUID * @type String * @private */ GUID: "yuitimeaxis", /** * Type of data used in `Axis`. * * @property _dataType * @readOnly * @private */ _dataType: "time", /** * Gets an array of values based on a key. * * @method _getKeyArray * @param {String} key Value key associated with the data array. * @param {Array} data Array in which the data resides. * @return Array * @private */ _getKeyArray: function(key, data) { var obj, keyArray = [], i = 0, val, len = data.length; for(; i < len; ++i) { obj = data[i][key]; if(Y_Lang.isDate(obj)) { val = obj.valueOf(); } else { val = new Date(obj); if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(obj)) { if(Y_Lang.isNumber(parseFloat(obj))) { val = parseFloat(obj); } else { if(typeof obj !== "string") { obj = obj; } val = new Date(obj).valueOf(); } } else { val = obj; } } keyArray[i] = val; } return keyArray; }, /** * Calculates the maximum and minimum values for the `Axis`. * * @method _updateMinAndMax * @private */ _updateMinAndMax: function() { var data = this.get("data"), max = 0, min = 0, len, num, i; if(data && data.length && data.length > 0) { len = data.length; max = min = data[0]; if(len > 1) { for(i = 1; i < len; i++) { num = data[i]; if(isNaN(num)) { continue; } max = Math.max(num, max); min = Math.min(num, min); } } } this._dataMaximum = max; this._dataMinimum = min; }, /** * Returns a coordinate corresponding to a data values. * * @method _getCoordFromValue * @param {Number} min The minimum for the axis. * @param {Number} max The maximum for the axis. * @param {Number} length The distance that the axis spans. * @param {Number} dataValue A value used to ascertain the coordinate. * @param {Number} offset Value in which to offset the coordinates. * @param {Boolean} reverse Indicates whether the coordinates should start from * the end of an axis. Only used in the numeric implementation. * @return Number * @private */ _getCoordFromValue: function(min, max, length, dataValue, offset) { var range, multiplier, valuecoord, isNumber = Y_Lang.isNumber; dataValue = this._getNumber(dataValue); if(isNumber(dataValue)) { range = max - min; multiplier = length/range; valuecoord = (dataValue - min) * multiplier; valuecoord = offset + valuecoord; } else { valuecoord = NaN; } return valuecoord; }, /** * Parses value into a number. * * @method _getNumber * @param val {Object} Value to parse into a number * @return Number * @private */ _getNumber: function(val) { if(Y_Lang.isDate(val)) { val = val.valueOf(); } else if(!Y_Lang.isNumber(val) && val) { val = new Date(val).valueOf(); } return val; } }; Y.TimeImpl = TimeImpl; /** * TimeAxisBase manages time data for an axis. * * @class TimeAxisBase * @extends AxisBase * @uses TimeImpl * @constructor * @param {Object} config (optional) Configuration parameters. * @submodule axis-time-base */ Y.TimeAxisBase = Y.Base.create("timeAxisBase", Y.AxisBase, [Y.TimeImpl]); }, '3.17.2', {"requires": ["axis-base"]});
gdomingos/Wegas
wegas-resources/src/main/webapp/lib/yui3/build/axis-time-base/axis-time-base.js
JavaScript
mit
8,841
// mgo - MongoDB driver for Go // // Copyright (c) 2014 - Gustavo Niemeyer <gustavo@niemeyer.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 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. // Pacakage scram implements a SCRAM-{SHA-1,etc} client per RFC5802. // // http://tools.ietf.org/html/rfc5802 // package scram import ( "bytes" "crypto/hmac" "crypto/rand" "encoding/base64" "fmt" "hash" "strconv" "strings" ) // Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc). // // A Client may be used within a SASL conversation with logic resembling: // // var in []byte // var client = scram.NewClient(sha1.New, user, pass) // for client.Step(in) { // out := client.Out() // // send out to server // in := serverOut // } // if client.Err() != nil { // // auth failed // } // type Client struct { newHash func() hash.Hash user string pass string step int out bytes.Buffer err error clientNonce []byte serverNonce []byte saltedPass []byte authMsg bytes.Buffer } // NewClient returns a new SCRAM-* client with the provided hash algorithm. // // For SCRAM-SHA-1, for example, use: // // client := scram.NewClient(sha1.New, user, pass) // func NewClient(newHash func() hash.Hash, user, pass string) *Client { c := &Client{ newHash: newHash, user: user, pass: pass, } c.out.Grow(256) c.authMsg.Grow(256) return c } // Out returns the data to be sent to the server in the current step. func (c *Client) Out() []byte { if c.out.Len() == 0 { return nil } return c.out.Bytes() } // Err returns the error that ocurred, or nil if there were no errors. func (c *Client) Err() error { return c.err } // SetNonce sets the client nonce to the provided value. // If not set, the nonce is generated automatically out of crypto/rand on the first step. func (c *Client) SetNonce(nonce []byte) { c.clientNonce = nonce } var escaper = strings.NewReplacer("=", "=3D", ",", "=2C") // Step processes the incoming data from the server and makes the // next round of data for the server available via Client.Out. // Step returns false if there are no errors and more data is // still expected. func (c *Client) Step(in []byte) bool { c.out.Reset() if c.step > 2 || c.err != nil { return false } c.step++ switch c.step { case 1: c.err = c.step1(in) case 2: c.err = c.step2(in) case 3: c.err = c.step3(in) } return c.step > 2 || c.err != nil } func (c *Client) step1(in []byte) error { if len(c.clientNonce) == 0 { const nonceLen = 6 buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen)) if _, err := rand.Read(buf[:nonceLen]); err != nil { return fmt.Errorf("cannot read random SCRAM-SHA-1 nonce from operating system: %v", err) } c.clientNonce = buf[nonceLen:] b64.Encode(c.clientNonce, buf[:nonceLen]) } c.authMsg.WriteString("n=") escaper.WriteString(&c.authMsg, c.user) c.authMsg.WriteString(",r=") c.authMsg.Write(c.clientNonce) c.out.WriteString("n,,") c.out.Write(c.authMsg.Bytes()) return nil } var b64 = base64.StdEncoding func (c *Client) step2(in []byte) error { c.authMsg.WriteByte(',') c.authMsg.Write(in) fields := bytes.Split(in, []byte(",")) if len(fields) != 3 { return fmt.Errorf("expected 3 fields in first SCRAM-SHA-1 server message, got %d: %q", len(fields), in) } if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 nonce: %q", fields[0]) } if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 salt: %q", fields[1]) } if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2]) } c.serverNonce = fields[0][2:] if !bytes.HasPrefix(c.serverNonce, c.clientNonce) { return fmt.Errorf("server SCRAM-SHA-1 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce) } salt := make([]byte, b64.DecodedLen(len(fields[1][2:]))) n, err := b64.Decode(salt, fields[1][2:]) if err != nil { return fmt.Errorf("cannot decode SCRAM-SHA-1 salt sent by server: %q", fields[1]) } salt = salt[:n] iterCount, err := strconv.Atoi(string(fields[2][2:])) if err != nil { return fmt.Errorf("server sent an invalid SCRAM-SHA-1 iteration count: %q", fields[2]) } c.saltPassword(salt, iterCount) c.authMsg.WriteString(",c=biws,r=") c.authMsg.Write(c.serverNonce) c.out.WriteString("c=biws,r=") c.out.Write(c.serverNonce) c.out.WriteString(",p=") c.out.Write(c.clientProof()) return nil } func (c *Client) step3(in []byte) error { var isv, ise bool var fields = bytes.Split(in, []byte(",")) if len(fields) == 1 { isv = bytes.HasPrefix(fields[0], []byte("v=")) ise = bytes.HasPrefix(fields[0], []byte("e=")) } if ise { return fmt.Errorf("SCRAM-SHA-1 authentication error: %s", fields[0][2:]) } else if !isv { return fmt.Errorf("unsupported SCRAM-SHA-1 final message from server: %q", in) } if !bytes.Equal(c.serverSignature(), fields[0][2:]) { return fmt.Errorf("cannot authenticate SCRAM-SHA-1 server signature: %q", fields[0][2:]) } return nil } func (c *Client) saltPassword(salt []byte, iterCount int) { mac := hmac.New(c.newHash, []byte(c.pass)) mac.Write(salt) mac.Write([]byte{0, 0, 0, 1}) ui := mac.Sum(nil) hi := make([]byte, len(ui)) copy(hi, ui) for i := 1; i < iterCount; i++ { mac.Reset() mac.Write(ui) mac.Sum(ui[:0]) for j, b := range ui { hi[j] ^= b } } c.saltedPass = hi } func (c *Client) clientProof() []byte { mac := hmac.New(c.newHash, c.saltedPass) mac.Write([]byte("Client Key")) clientKey := mac.Sum(nil) hash := c.newHash() hash.Write(clientKey) storedKey := hash.Sum(nil) mac = hmac.New(c.newHash, storedKey) mac.Write(c.authMsg.Bytes()) clientProof := mac.Sum(nil) for i, b := range clientKey { clientProof[i] ^= b } clientProof64 := make([]byte, b64.EncodedLen(len(clientProof))) b64.Encode(clientProof64, clientProof) return clientProof64 } func (c *Client) serverSignature() []byte { mac := hmac.New(c.newHash, c.saltedPass) mac.Write([]byte("Server Key")) serverKey := mac.Sum(nil) mac = hmac.New(c.newHash, serverKey) mac.Write(c.authMsg.Bytes()) serverSignature := mac.Sum(nil) encoded := make([]byte, b64.EncodedLen(len(serverSignature))) b64.Encode(encoded, serverSignature) return encoded }
nildev/prj-tpl-basic-api
vendor/gopkg.in/mgo.v2/internal/scram/scram.go
GO
mit
7,708